Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

fix(helpers): decode XML entities in ssml_to_deepgram - #812

Open
RaphaelFakhri wants to merge 3 commits into
deepgram:mainfrom
RaphaelFakhri:fix/ssml-xml-entities
Open

RaphaelFakhri wants to merge 3 commits into
deepgram:mainfrom
RaphaelFakhri:fix/ssml-xml-entities

Conversation

@RaphaelFakhri

@RaphaelFakhri RaphaelFakhri commented Oct 22, 2026 •

Copy link
Copy Markdown

ssml_to_deepgram() and TextBuilder.from_ssml() strip SSML tags but never decoded XML entities. SSML is XML, so & must be written &, and apostrophes and quotes are commonly written ', " or '. Those entities reached the TTS request unchanged. Fixes #811.

This is not cosmetic: the voice speaks the markup

Verified against production, synthesizing with aura-2-thalia-en and transcribing the result back with nova-3:

Sent to /v1/speak What the voice said
Call AT&T, it's open. Call ATMT. It opposes open.
Call AT&T, it's open. Call AT and T. It's open.
café and café Cafan pound two hundred thirty three and cafe

' is heard as "opposes". é is read aloud as "pound two hundred thirty three". The escaped audio was 159404 bytes against 113324 for the decoded text, because the voice is speaking the entity. Byte counts and exact transcripts are one run and vary between syntheses; the direction does not. The response headers below reproduced exactly across runs.

The pronunciation path is worse, because the request succeeds with a warning most callers never read:

before after
helper emits \{"word": "AT&T", "pronounce": "tə"\} \{"word": "AT&T", "pronounce": "tə"\}
dg-pronunciations-applied 1 1
dg-warnings PRON-001 (absent)
voice says Call Tian Pound six zero one today. Call to today.

The control is not dropped, it is applied with a corrupt IPA value.

Fix

Decode the five predefined XML entities and numeric character references, in the <phoneme> word and ph value before building the pronunciation control, and in the remaining text after tag stripping. Inline controls are skipped so nothing is decoded twice, and escaped markup such as &lt;break/&gt; stays literal text rather than being parsed. HTML-only names such as &copy; and a bare & are left alone.

A numeric reference is decoded only when it falls inside the XML 1.0 Char production. This matters beyond correctness: chr(0xD800) is a lone UTF-16 surrogate, and the resulting str raises UnicodeEncodeError as soon as anything encodes it as UTF-8, so &#xD800; would fail deep inside the HTTP client with an error naming neither the SSML nor the reference. Surrogates, NUL, the C0 controls and the two non-characters at the end of the BMP (U+FFFE, U+FFFF) are left as written. U+FDD0 to U+FDEF are also non-characters but XML's Char production allows them, so they still decode. A conforming parser would reject the whole document on such a reference; this converter is deliberately more lenient and passes it through as text, which is what it did before. Every code point XML allows still decodes, boundaries included.

A < decoded into a phoneme was eaten by the tag stripper

Decoding runs on the <phoneme> word and ph value while the control is built, so &lt; could put a literal < into text the "remove any remaining XML tags" pass still had to run over. That pass deleted from the < to the next > anywhere later in the document, and a later > comes from every subsequent SSML tag:

input main before the fix after
<phoneme alphabet="ipa" ph="lɛs">&lt;</phoneme> is <emphasis>less</emphasis> \{"word": "&lt;", ...\} is less \{"word": "less → HTTP 400 MALFORMED_CONTROL_CLOSURE \{"word": "<", "pronounce": "lɛs"\} is less → 200
<phoneme alphabet="ipa" ph="x">a&lt;b&gt;c</phoneme> \{"word": "a&lt;b&gt;c", ...\} \{"word": "ac", ...\} → 200, no warning \{"word": "a<b>c", "pronounce": "x"\} → 200

The second row is the worse one: headers are indistinguishable from a correct request, so the caller pays for audio speaking the wrong word with nothing to show it. Controls are now held aside behind NUL-delimited placeholders while tags are stripped and entities decoded, then restored. Caller text cannot forge a placeholder: NUL is removed on entry and &#0; is not decoded into one.

Behavior change

No realistic SSML changes from accepted to rejected. Plain entities, numeric references, phonemes, escaped markup and breaks all still convert. Two contrived inputs do now raise, correctly, because after decoding the text really does contain what the error describes: nine pause markers written as &#92;{pause:500ms&#92;} raise the eight-pause limit, and an entity-escaped pronunciation marker beside a <break> raises the mixed-controls error.

Known limitation, recorded in a test

A pause marker arriving as literal text never passes through replace_break, so its duration is not range checked: <break time="9999ms"/> raises, the same marker written as text does not. Count limits still apply, since _control_counts runs after decoding. This behaves identically on main for a marker typed directly, so entity decoding only makes an existing gap easier to reach. test_entity_injected_pause_is_not_range_checked pins it.

Verification

  • pytest tests/custom: 1139 passed, 1 skipped, 1 xfailed. 119 passed in python:3.10-slim and python:3.13-slim containers, covering CI's matrix ends. mypy src/: 955 files clean. mypy tests/typecheck clean. ruff check clean on both changed files.
  • The new Char-range tests fail without the range check; five of the seven invalid references were decoded before it.
  • The two new regexes are flat on adversarial input: 0.0003s at n=20000.
  • Rebased onto current main, so feat(helpers): preserve SSML breaks with additional attributes, fix matcher backtracking #809's tag-matcher backtracking fix is intact and still returns in 0.0001s.

Both files are permanently frozen in .fernignore, so no Fern regeneration interaction applies.


The entity decoding, its four tests and the issue report are @RaphaelFakhri's work. The Char-range restriction, the tag-stripper fix, their tests and the recorded pause limitation were added on top by a maintainer.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

RaphaelFakhri and others added 3 commits December 2, 2026 16:47
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("<speak>a&#xD800;b</speak>")  ->  '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 `a&#xD800;b`, 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 (`&#xD800;`, `&#xDFFF;`), NUL and the C0 controls
(`&#0;`, `&#x1;`) and the BMP non-characters (`&#xFFFE;`). 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. `<break time="9999ms"/>`
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.
Entity decoding runs on the `<phoneme>` word and `ph` value while the control
is built, so `&lt;` 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:

    <speak><phoneme alphabet="ipa" ph="lɛs">&lt;</phoneme> is
    <emphasis>less</emphasis></speak>

        -> '\{"word": "less'
        -> HTTP 400 MALFORMED_CONTROL_CLOSURE

    <phoneme alphabet="ipa" ph="x">a&lt;b&gt;c</phoneme>

        -> '\{"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. `&lt;` and `&gt;` 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 `&#0;`
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.
@GregHolmes
GregHolmes force-pushed the fix/ssml-xml-entities branch from e52f399 to ad38b81 Compare December 2, 2026 16:48

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ssml_to_deepgram leaves XML entities such as &amp; and &apos; in the TTS text

3 participants