diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py index 2e1d5251..2bb5125e 100644 --- a/src/deepgram/helpers/text_builder.py +++ b/src/deepgram/helpers/text_builder.py @@ -7,7 +7,7 @@ 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 = ( @@ -15,6 +15,8 @@ + 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: @@ -258,6 +260,7 @@ def ssml_to_deepgram(ssml_text: str) -> str: - or , in any attribute order and alongside other attributes such as `strength`, which are ignored - Strips wrapper tags + - Decodes XML entities such as & and ' Args: ssml_text: SSML-formatted text @@ -275,8 +278,10 @@ def ssml_to_deepgram(ssml_text: str) -> str: ''' 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 `�`), so removing + # it here makes the control placeholders below unforgeable by caller text. + ssml_text = ssml_text.replace("\x00", "").strip() # If wrapped in tags, extract content speak_pattern = r"]*>(.*?)" @@ -299,15 +304,23 @@ def ssml_to_deepgram(ssml_text: str) -> str: # its surrounding whitespace. phoneme_pattern = r"]*?)>([^<]*)" + 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) @@ -346,6 +359,12 @@ def replace_break(match): # Remove any remaining XML tags ssml_text = re.sub(r"<[^>]+>", "", ssml_text) + # Decode XML entities (&, ', ', ...) 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: @@ -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. diff --git a/tests/custom/test_text_builder.py b/tests/custom/test_text_builder.py index 8a437aea..72dc88fe 100644 --- a/tests/custom/test_text_builder.py +++ b/tests/custom/test_text_builder.py @@ -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 = "AT&T says it's 3 < 5 & "ok"" + 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 = 'AT&T' + 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 = "Use <break time="500ms"/> here" + result = ssml_to_deepgram(ssml) + + assert result == 'Use here' + + def test_decodes_entities_once_in_unsupported_phoneme(self): + """A phoneme without an IPA alphabet keeps its word as text, decoded once""" + ssml = '&lt;b&gt;' + result = ssml_to_deepgram(ssml) + + assert result == "<b>" + + @pytest.mark.parametrize( + "reference", + [ + "�", # lone surrogate, unencodable as UTF-8 + "�", # the other end of the surrogate block + "�", # NUL + "", # C0 control + "￾", # BMP non-character + "�", # past the last code point + "�", # 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"a{reference}b") + + assert result == f"a{reference}b" + result.encode("utf-8") + + @pytest.mark.parametrize( + "reference, character", + [ + (" ", "\t"), + (" ", "\n"), + (" ", "\r"), + (" ", " "), + ("퟿", "\ud7ff"), + ("", "\ue000"), + ("�", "\ufffd"), + ("𐀀", "\U00010000"), + ("􏿿", "\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"a{reference}b") + + 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 `` tag, so `` + 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('ab') + + assert ssml_to_deepgram("a\{pause:9999ms\}b") == r"a\{pause:9999ms\}b" + + with pytest.raises(ValueError, match="Maximum 8 pauses"): + ssml_to_deepgram("" + "\{pause:500ms\}" * 9 + "") + + 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 `<` + 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 = ( + '<' + " is less" + ) + expected = '\\{"word": "<", "pronounce": "l\u025bs"\\} is less' + assert ssml_to_deepgram(truncating) == expected + + silent = 'a<b>c' + assert ssml_to_deepgram(silent) == r'\{"word": "ac", "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 `�` into one. Neither route lets + caller text name a control slot. + """ + assert ssml_to_deepgram("a\x000\x00b") == "a0b" + assert ssml_to_deepgram("a�0�b") == "a�0�b" + + adjacent = 'w123' + 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 = '''