Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 66 additions & 5 deletions src/deepgram/helpers/text_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@

import json
import re
from typing import Tuple
from typing import List, Tuple

PAUSE_PATTERN = re.escape(r"\{pause:") + r"(\d+)ms" + re.escape(r"\}")
PRONUNCIATION_PATTERN = (
re.escape(r"\{")
+ r'"word":\s*"(?:[^"\\]|\\.)*",\s*"pronounce":\s*"(?:[^"\\]|\\.)*"'
+ re.escape(r"\}")
)
_XML_ENTITY_PATTERN = r"&(?:#x([0-9a-fA-F]+)|#([0-9]+)|(amp|lt|gt|quot|apos));"
_XML_ENTITIES = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}


class TextBuilder:
Expand Down Expand Up @@ -258,6 +260,7 @@ def ssml_to_deepgram(ssml_text: str) -> str:
- <break time="500ms"/> or <break time="0.5s"/>, in any attribute order and
alongside other attributes such as `strength`, which are ignored
- Strips <speak> wrapper tags
- Decodes XML entities such as &amp; and &#39;

Args:
ssml_text: SSML-formatted text
Expand All @@ -275,8 +278,10 @@ def ssml_to_deepgram(ssml_text: str) -> str:
</speak>'''
text = ssml_to_deepgram(ssml)
"""
# Strip leading/trailing whitespace
ssml_text = ssml_text.strip()
# Strip leading/trailing whitespace. NUL is not a legal XML character and
# cannot come from entity decoding (`_is_xml_char` rejects `&#0;`), so removing
# it here makes the control placeholders below unforgeable by caller text.
ssml_text = ssml_text.replace("\x00", "").strip()

# If wrapped in <speak> tags, extract content
speak_pattern = r"<speak[^>]*>(.*?)</speak>"
Expand All @@ -299,15 +304,23 @@ def ssml_to_deepgram(ssml_text: str) -> str:
# its surrounding whitespace.
phoneme_pattern = r"<phoneme\s([^<>]*?)>([^<]*)</phoneme>"

controls: List[str] = []

def replace_phoneme(match):
attributes = match.group(1)
word = match.group(2)
alphabet_match = re.search(r'(?:^|\s)alphabet\s*=\s*(["\'])ipa\1(?=\s|$)', attributes)
ph_match = re.search(r'(?:^|\s)ph\s*=\s*(["\'])(.*?)\1(?=\s|$)', attributes)
if alphabet_match is None or ph_match is None:
# Left as text; entities are decoded with the rest of the text below.
return word
ipa = ph_match.group(2)
return _pronunciation_control(word, ipa)
ipa = _unescape_xml(ph_match.group(2))
# Hold the built control aside behind a placeholder. Decoding can put a
# `<` or `>` into the word or the IPA, and the tag strip below would then
# eat from that `<` to the next `>` anywhere later in the document,
# destroying the control and the text around it.
controls.append(_pronunciation_control(_unescape_xml(word), ipa))
return f"\x00{len(controls) - 1}\x00"

ssml_text = re.sub(phoneme_pattern, replace_phoneme, ssml_text)

Expand Down Expand Up @@ -346,6 +359,12 @@ def replace_break(match):
# Remove any remaining XML tags
ssml_text = re.sub(r"<[^>]+>", "", ssml_text)

# Decode XML entities (&amp;, &apos;, &#39;, ...) in the remaining text, then
# restore the pronunciation controls. Their word and IPA were decoded above,
# so holding them aside is also what keeps them from being decoded twice.
ssml_text = _unescape_xml(ssml_text)
ssml_text = re.sub(r"\x00(\d+)\x00", lambda m: controls[int(m.group(1))], ssml_text)

ssml_text = ssml_text.strip()
pronunciation_count, pause_count = _control_counts(ssml_text)
if pronunciation_count > 500:
Expand All @@ -357,6 +376,48 @@ def replace_break(match):
return ssml_text


def _is_xml_char(code_point: int) -> bool:
"""Whether a code point is allowed by the XML 1.0 `Char` production.

The excluded ranges are NUL and the C0 controls, the UTF-16 surrogates, and
the two non-characters at the end of the BMP. Surrogates matter most here:
`chr(0xD800)` builds a `str` that raises `UnicodeEncodeError` the moment
anything encodes it as UTF-8, so decoding one would move a harmless piece of
malformed markup into a crash inside the HTTP client, far from its cause.
"""
return (
code_point in (0x9, 0xA, 0xD)
or 0x20 <= code_point <= 0xD7FF
or 0xE000 <= code_point <= 0xFFFD
or 0x10000 <= code_point <= 0x10FFFF
)


def _unescape_xml(text: str) -> str:
"""Decode the predefined XML entities and numeric character references.

A reference outside the XML `Char` production is left as written. A
conforming parser treats such a reference as a fatal error and rejects the
whole document (XML 1.0 section 4.1, WFC: Legal Character); this converter is
deliberately more lenient and passes it through as text, which is what it did
before entity decoding existed.
"""

def replace_entity(match):
hex_code, decimal_code, name = match.groups()
if name:
return _XML_ENTITIES[name]
try:
code_point = int(hex_code, 16) if hex_code else int(decimal_code)
except (ValueError, OverflowError):
return match.group(0)
if not _is_xml_char(code_point):
return match.group(0)
return chr(code_point)

return re.sub(_XML_ENTITY_PATTERN, replace_entity, text)


def validate_ipa(ipa: str) -> Tuple[bool, str]:
"""
Validate IPA string format.
Expand Down
127 changes: 127 additions & 0 deletions tests/custom/test_text_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,133 @@ def test_speak_wrapper(self):

assert result == "Hello world"

def test_decodes_xml_entities_in_text(self):
"""Escaped characters in SSML text must reach the output as plain characters"""
ssml = "<speak>AT&amp;T says it&apos;s 3 &lt; 5 &#38; &#x22;ok&quot;</speak>"
result = ssml_to_deepgram(ssml)

assert result == 'AT&T says it\'s 3 < 5 & "ok"'

def test_decodes_xml_entities_in_phoneme(self):
"""Escaped characters in the phoneme word and ph attribute must be decoded"""
ssml = '<phoneme alphabet="ipa" ph="&#x2C8;e&#618; ti&#720; &#601;nd ti&#720;">AT&amp;T</phoneme>'
result = ssml_to_deepgram(ssml)

assert result == r'\{"word": "AT&T", "pronounce": "ˈeɪ tiː ənd tiː"\}'

def test_escaped_markup_stays_text(self):
"""Escaped markup is text, not an SSML element"""
ssml = "<speak>Use &lt;break time=&quot;500ms&quot;/&gt; here</speak>"
result = ssml_to_deepgram(ssml)

assert result == 'Use <break time="500ms"/> here'

def test_decodes_entities_once_in_unsupported_phoneme(self):
"""A phoneme without an IPA alphabet keeps its word as text, decoded once"""
ssml = '<speak><phoneme ph="x">&amp;lt;b&amp;gt;</phoneme></speak>'
result = ssml_to_deepgram(ssml)

assert result == "&lt;b&gt;"

@pytest.mark.parametrize(
"reference",
[
"&#xD800;", # lone surrogate, unencodable as UTF-8
"&#xDFFF;", # the other end of the surrogate block
"&#0;", # NUL
"&#x1;", # C0 control
"&#xFFFE;", # BMP non-character
"&#x110000;", # past the last code point
"&#999999999999999999;", # larger than chr() accepts
],
)
def test_leaves_xml_invalid_numeric_references_literal(self, reference):
"""A reference outside the XML `Char` production must not be decoded.

Decoding a surrogate builds a `str` that raises `UnicodeEncodeError` as
soon as anything encodes it, which would turn malformed markup into a
crash inside the HTTP client rather than text the API can reject.
"""
result = ssml_to_deepgram(f"<speak>a{reference}b</speak>")

assert result == f"a{reference}b"
result.encode("utf-8")

@pytest.mark.parametrize(
"reference, character",
[
("&#x9;", "\t"),
("&#xA;", "\n"),
("&#xD;", "\r"),
("&#x20;", " "),
("&#xD7FF;", "\ud7ff"),
("&#xE000;", "\ue000"),
("&#xFFFD;", "\ufffd"),
("&#x10000;", "\U00010000"),
("&#x10FFFF;", "\U0010ffff"),
],
)
def test_decodes_the_xml_char_range_boundaries(self, reference, character):
"""Every code point the XML `Char` production allows still decodes."""
result = ssml_to_deepgram(f"<speak>a{reference}b</speak>")

assert result == f"a{character}b"
result.encode("utf-8")

def test_entity_injected_pause_is_not_range_checked(self):
"""Known limitation, pre-existing: a control written as text skips validation.

`replace_break` validates a `<break>` tag, so `<break time="9999ms"/>`
raises. A pause marker that arrives as literal text never passes through
it, and entity decoding is one more way to write such text. The count
limits still apply, because `_control_counts` runs afterwards. The same
gap exists on a marker typed directly, so this records behavior rather
than a regression this change introduces. If that gap is ever closed,
the second assertion below becomes a `pytest.raises` rather than being
deleted.
"""
with pytest.raises(ValueError, match="must not exceed 3000ms"):
ssml_to_deepgram('<speak>a<break time="9999ms"/>b</speak>')

assert ssml_to_deepgram("<speak>a&#92;{pause:9999ms&#92;}b</speak>") == r"a\{pause:9999ms\}b"

with pytest.raises(ValueError, match="Maximum 8 pauses"):
ssml_to_deepgram("<speak>" + "&#92;{pause:500ms&#92;}" * 9 + "</speak>")

def test_decoded_angle_bracket_in_phoneme_survives_tag_stripping(self):
"""A `<` decoded into a phoneme must not be eaten by the tag stripper.

The word and the IPA are decoded while building the control, so `&lt;`
can put a literal `<` into text that the "remove any remaining XML tags"
pass still has to run over. Without holding the control aside, that pass
deletes from the `<` to the next `>` anywhere later in the document,
which either truncates the control into malformed output the API rejects
with MALFORMED_CONTROL_CLOSURE, or silently drops characters and returns
audio that speaks the wrong word.
"""
truncating = (
'<speak><phoneme alphabet="ipa" ph="l\u025bs">&lt;</phoneme>'
" is <emphasis>less</emphasis></speak>"
)
expected = '\\{"word": "<", "pronounce": "l\u025bs"\\} is less'
assert ssml_to_deepgram(truncating) == expected

silent = '<phoneme alphabet="ipa" ph="x">a&lt;b&gt;c</phoneme>'
assert ssml_to_deepgram(silent) == r'\{"word": "a<b>c", "pronounce": "x"\}'

def test_caller_text_cannot_forge_a_control_placeholder(self):
"""Controls are held aside behind NUL placeholders while tags are stripped.

NUL is not a legal XML character, so it is removed on entry and
`_is_xml_char` refuses to decode `&#0;` into one. Neither route lets
caller text name a control slot.
"""
assert ssml_to_deepgram("<speak>a\x000\x00b</speak>") == "a0b"
assert ssml_to_deepgram("<speak>a&#0;0&#0;b</speak>") == "a&#0;0&#0;b"

adjacent = '<speak><phoneme alphabet="ipa" ph="x">w</phoneme>123</speak>'
assert ssml_to_deepgram(adjacent) == r'\{"word": "w", "pronounce": "x"\}123'

def test_complex_ssml_rejects_mixed_controls(self):
"""Flux batch cannot combine SSML phoneme and break controls."""
ssml = '''<speak>
Expand Down