From b9935c5d1646c737a49f3d1bf29a0a0f27d1ef74 Mon Sep 17 00:00:00 2001
From: Raphael Fakhri <153192858+RaphaelFakhri@users.noreply.github.com>
Date: Thu, 22 Oct 2026 12:40:56 +0000
Subject: [PATCH 1/3] fix(helpers): decode XML entities in ssml_to_deepgram
---
src/deepgram/helpers/text_builder.py | 40 ++++++++++++++++++++++++++--
tests/custom/test_text_builder.py | 28 +++++++++++++++++++
2 files changed, 66 insertions(+), 2 deletions(-)
diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py
index 2e1d5251..04e1bf28 100644
--- a/src/deepgram/helpers/text_builder.py
+++ b/src/deepgram/helpers/text_builder.py
@@ -15,6 +15,9 @@
+ r'"word":\s*"(?:[^"\\]|\\.)*",\s*"pronounce":\s*"(?:[^"\\]|\\.)*"'
+ re.escape(r"\}")
)
+_CONTROL_PATTERN = PRONUNCIATION_PATTERN + "|" + PAUSE_PATTERN
+_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 +261,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
@@ -305,9 +309,10 @@ def replace_phoneme(match):
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))
+ return _pronunciation_control(_unescape_xml(word), ipa)
ssml_text = re.sub(phoneme_pattern, replace_phoneme, ssml_text)
@@ -346,6 +351,10 @@ def replace_break(match):
# Remove any remaining XML tags
ssml_text = re.sub(r"<[^>]+>", "", ssml_text)
+ # Decode XML entities (&, ', ', ...) in the remaining text. Inline
+ # controls are skipped because their word and IPA were decoded above.
+ ssml_text = _unescape_xml_outside_controls(ssml_text)
+
ssml_text = ssml_text.strip()
pronunciation_count, pause_count = _control_counts(ssml_text)
if pronunciation_count > 500:
@@ -357,6 +366,33 @@ def replace_break(match):
return ssml_text
+def _unescape_xml(text: str) -> str:
+ """Decode the predefined XML entities and numeric character references."""
+
+ def replace_entity(match):
+ hex_code, decimal_code, name = match.groups()
+ if name:
+ return _XML_ENTITIES[name]
+ try:
+ return chr(int(hex_code, 16) if hex_code else int(decimal_code))
+ except (ValueError, OverflowError):
+ return match.group(0)
+
+ return re.sub(_XML_ENTITY_PATTERN, replace_entity, text)
+
+
+def _unescape_xml_outside_controls(text: str) -> str:
+ """Decode XML entities in plain text while leaving inline controls unchanged."""
+ parts = []
+ position = 0
+ for match in re.finditer(_CONTROL_PATTERN, text):
+ parts.append(_unescape_xml(text[position : match.start()]))
+ parts.append(match.group(0))
+ position = match.end()
+ parts.append(_unescape_xml(text[position:]))
+ return "".join(parts)
+
+
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..3f51ba1a 100644
--- a/tests/custom/test_text_builder.py
+++ b/tests/custom/test_text_builder.py
@@ -321,6 +321,34 @@ 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 = '<b>'
+ result = ssml_to_deepgram(ssml)
+
+ assert result == "<b>"
+
def test_complex_ssml_rejects_mixed_controls(self):
"""Flux batch cannot combine SSML phoneme and break controls."""
ssml = '''
From c2d14d62fe76f590202ea4de9141ecd207d8bc12 Mon Sep 17 00:00:00 2001
From: Greg Holmes
Date: Mon, 30 Nov 2026 13:41:09 +0000
Subject: [PATCH 2/3] fix(helpers): decode only XML-valid character references
The entity decoder added in the previous commit called `chr()` on any numeric
character reference `chr()` would accept. Three ranges that a conforming XML
parser rejects got decoded anyway, and one of them is not merely wrong output:
ssml_to_deepgram("ab") -> 'a\ud800b'
`chr(0xD800)` is a lone UTF-16 surrogate. The resulting `str` raises
`UnicodeEncodeError` the moment anything encodes it as UTF-8, so a request
carrying it fails deep inside the HTTP client with an error that names neither
the SSML nor the reference that produced it. Before this change the same input
passed through as the literal text `ab`, which encodes cleanly and
which the API can simply read or reject.
Decode a numeric reference only when it falls in the XML 1.0 `Char`
production, and leave it as written otherwise. That restores the prior
behavior for surrogates (``, ``), NUL and the C0 controls
(``, ``) and the BMP non-characters (``). References past the
last code point were already left literal by the existing `try`/`except`; this
does not change them. Every code point XML does allow still decodes, including
the boundaries at 0x9, 0xD7FF, 0xE000, 0xFFFD and 0x10FFFF.
Also record a pre-existing limitation the entity decoding makes easier to
reach: a pause marker arriving as literal text never passes through
`replace_break`, so its duration is not range checked. ``
raises, while the same marker written as text does not. The count limits still
apply, because `_control_counts` runs after decoding. A marker typed directly
behaves identically on main, so this is behavior worth pinning rather than a
regression this change introduces.
---
src/deepgram/helpers/text_builder.py | 29 ++++++++++++-
tests/custom/test_text_builder.py | 63 ++++++++++++++++++++++++++++
2 files changed, 90 insertions(+), 2 deletions(-)
diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py
index 04e1bf28..f5f94ec3 100644
--- a/src/deepgram/helpers/text_builder.py
+++ b/src/deepgram/helpers/text_builder.py
@@ -366,17 +366,42 @@ 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."""
+ """Decode the predefined XML entities and numeric character references.
+
+ A reference outside the XML `Char` production is left as written, which is
+ what a conforming parser does with it and what this converter did before
+ entity decoding existed.
+ """
def replace_entity(match):
hex_code, decimal_code, name = match.groups()
if name:
return _XML_ENTITIES[name]
try:
- return chr(int(hex_code, 16) if hex_code else int(decimal_code))
+ 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)
diff --git a/tests/custom/test_text_builder.py b/tests/custom/test_text_builder.py
index 3f51ba1a..ec94c098 100644
--- a/tests/custom/test_text_builder.py
+++ b/tests/custom/test_text_builder.py
@@ -349,6 +349,69 @@ def test_decodes_entities_once_in_unsupported_phoneme(self):
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.
+ """
+ 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_complex_ssml_rejects_mixed_controls(self):
"""Flux batch cannot combine SSML phoneme and break controls."""
ssml = '''
From ad38b8136786fe318ea920181481d0abc03dd168 Mon Sep 17 00:00:00 2001
From: Greg Holmes
Date: Mon, 30 Nov 2026 14:08:07 +0000
Subject: [PATCH 3/3] fix(helpers): keep decoded angle brackets from reaching
the tag stripper
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Entity decoding runs on the `` word and `ph` value while the control
is built, so `<` can put a literal `<` into text that the "remove any
remaining XML tags" pass still has to run over. That pass then deletes from
the `<` to the next `>` anywhere later in the document, and a later `>` comes
from every subsequent SSML tag, so it is the normal case rather than an edge
one. Two failure modes, both verified against production:
< is
less
-> '\{"word": "less'
-> HTTP 400 MALFORMED_CONTROL_CLOSURE
a<b>c
-> '\{"word": "ac", "pronounce": "x"\}'
-> HTTP 200, dg-pronunciations-applied: 1, no dg-warnings
The second is the worse one: the response is indistinguishable from a correct
request, so the caller pays for audio that speaks the wrong word with nothing
in the headers to show it. `<` and `>` are two of the five entities this
feature exists to decode, so a caller has every reason to write them here.
Hold each built control aside behind a NUL-delimited placeholder, run the tag
strip and the entity decode over the remaining text, then put the controls
back last. Caller text cannot name a slot: NUL is not a legal XML character,
so it is removed on entry, and `_is_xml_char` already refuses to decode ``
into one. Holding the controls aside is also what keeps their contents from
being decoded twice, which is what `_unescape_xml_outside_controls` did before;
that helper and `_CONTROL_PATTERN` are now unused and removed. Entities a
caller hand-wrote inside an inline control in SSML text are now decoded like
any other text, where they were skipped before.
Both rows now return the structurally correct control and HTTP 200 with
dg-pronunciations-applied: 1 and no warnings.
Also correct a false statement in the previous commit's docstring. A
conforming XML parser does not pass an out-of-`Char` reference through; XML 1.0
section 4.1 (WFC: Legal Character) makes it a fatal error and the parser
rejects the document. This converter is deliberately more lenient.
---
src/deepgram/helpers/text_builder.py | 46 ++++++++++++++--------------
tests/custom/test_text_builder.py | 38 ++++++++++++++++++++++-
2 files changed, 60 insertions(+), 24 deletions(-)
diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py
index f5f94ec3..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,7 +15,6 @@
+ r'"word":\s*"(?:[^"\\]|\\.)*",\s*"pronounce":\s*"(?:[^"\\]|\\.)*"'
+ re.escape(r"\}")
)
-_CONTROL_PATTERN = PRONUNCIATION_PATTERN + "|" + PAUSE_PATTERN
_XML_ENTITY_PATTERN = r"&(?:#x([0-9a-fA-F]+)|#([0-9]+)|(amp|lt|gt|quot|apos));"
_XML_ENTITIES = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}
@@ -279,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"]*>(.*?)"
@@ -303,6 +304,8 @@ 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)
@@ -312,7 +315,12 @@ def replace_phoneme(match):
# Left as text; entities are decoded with the rest of the text below.
return word
ipa = _unescape_xml(ph_match.group(2))
- return _pronunciation_control(_unescape_xml(word), ipa)
+ # 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)
@@ -351,9 +359,11 @@ def replace_break(match):
# Remove any remaining XML tags
ssml_text = re.sub(r"<[^>]+>", "", ssml_text)
- # Decode XML entities (&, ', ', ...) in the remaining text. Inline
- # controls are skipped because their word and IPA were decoded above.
- ssml_text = _unescape_xml_outside_controls(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)
@@ -386,9 +396,11 @@ def _is_xml_char(code_point: int) -> bool:
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, which is
- what a conforming parser does with it and what this converter did before
- entity decoding existed.
+ 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):
@@ -406,18 +418,6 @@ def replace_entity(match):
return re.sub(_XML_ENTITY_PATTERN, replace_entity, text)
-def _unescape_xml_outside_controls(text: str) -> str:
- """Decode XML entities in plain text while leaving inline controls unchanged."""
- parts = []
- position = 0
- for match in re.finditer(_CONTROL_PATTERN, text):
- parts.append(_unescape_xml(text[position : match.start()]))
- parts.append(match.group(0))
- position = match.end()
- parts.append(_unescape_xml(text[position:]))
- return "".join(parts)
-
-
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 ec94c098..72dc88fe 100644
--- a/tests/custom/test_text_builder.py
+++ b/tests/custom/test_text_builder.py
@@ -402,7 +402,9 @@ def test_entity_injected_pause_is_not_range_checked(self):
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.
+ 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')
@@ -412,6 +414,40 @@ def test_entity_injected_pause_is_not_range_checked(self):
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("a0b") == "a0b"
+
+ 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 = '''