From b23e2d8f4c1b48e81da715aac3334f81e3eaa04c Mon Sep 17 00:00:00 2001 From: Apeksha_2022 <70309060+Apeksha9389@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:28:55 +0530 Subject: [PATCH 1/2] fix(helpers): preserve SSML breaks with additional attributes --- src/deepgram/helpers/text_builder.py | 12 +++++++++--- tests/custom/test_text_builder.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py index f8109403..65b0ef74 100644 --- a/src/deepgram/helpers/text_builder.py +++ b/src/deepgram/helpers/text_builder.py @@ -305,11 +305,17 @@ def replace_phoneme(match): ssml_text = re.sub(phoneme_pattern, replace_phoneme, ssml_text) # Handle tags - break_pattern = r'' + break_pattern = r"]*?)\s*/>" def replace_break(match): - value = float(match.group(1)) - unit = match.group(2) + time_match = re.search( + r"(?:^|\s)time\s*=\s*([\"'])(\d+(?:\.\d+)?)(ms|s)\1(?=\s|$)", + match.group(1), + ) + if time_match is None: + return match.group(0) + value = float(time_match.group(2)) + unit = time_match.group(3) duration_ms = value * 1000 if unit == "s" else value if not duration_ms.is_integer(): diff --git a/tests/custom/test_text_builder.py b/tests/custom/test_text_builder.py index 5f1f3083..9d69c600 100644 --- a/tests/custom/test_text_builder.py +++ b/tests/custom/test_text_builder.py @@ -554,3 +554,19 @@ def test_standalone_function_workflow(self): assert '"pronounce": "ˌæzəˈθaɪəpriːn"' in text assert '"word": "dupilumab"' in text assert '"pronounce": "duːˈpɪljuːmæb"' in text + + +@pytest.mark.parametrize( + "markup", + [ + '', + "", + '', + '', + ], +) +def test_ssml_break_time_accepts_attribute_spacing_and_order(markup): + ssml = f"Hello{markup}world" + + assert ssml_to_deepgram(ssml) == r"Hello\{pause:500ms\}world" + assert TextBuilder().from_ssml(ssml).build() == r"Hello\{pause:500ms\}world" From 700fb30e7ca97a7c3556cca7ba74f4665d61b0a1 Mon Sep 17 00:00:00 2001 From: Greg Holmes Date: Mon, 30 Nov 2026 11:54:12 +0000 Subject: [PATCH 2/2] fix(helpers): stop cubic backtracking on unterminated SSML tags The wider `` matcher added in the previous commit put three whitespace-capable quantifiers in a row (`\s+`, `[^<>]*?`, `\s*`). On an unterminated tag the match backtracks cubically, about 8x per doubling of the whitespace run: a `` pattern has carried the same shape since the attribute-order fix and is affected in released versions: on 7.20.0 it takes about 22s on a 4 KB input, so any caller passing user-supplied SSML can be stalled by a few kilobytes of text. The attribute lookups are anchored on `(?:^|\s)` and `(?=\s|$)`, so the captured group keeps its surrounding whitespace without changing which attributes match. Scope: this covers the long-whitespace-run shape. Two milder pre-existing shapes are untouched and remain quadratic, needing 40x to 140x more input to stall: the `ph` lookup's `(.*?)\1(?=\s|$)` and the trailing `re.sub(r"<[^>]+>", "", ...)` tag stripper. Behavior is unchanged: 16 `` spellings and 4 `` spellings produce identical output before and after, and the fixed shape is flat at 0.0003s out to n=20000. Also add the coverage the wider matcher needs. The four original cases asserted only success, while an attributed break can now reach the duration floor, ceiling and 100ms grid, the eight-pause limit and the pronunciation/pause exclusion that a bare break already hit. Move them onto `TestSsmlToDeepgram` with their peers, and record the known limitation that the `time` lookup is not quote-aware, so a `time=` inside another attribute's quoted value is read as the real one. --- src/deepgram/helpers/text_builder.py | 24 ++++-- tests/custom/test_text_builder.py | 112 +++++++++++++++++++++++---- 2 files changed, 115 insertions(+), 21 deletions(-) diff --git a/src/deepgram/helpers/text_builder.py b/src/deepgram/helpers/text_builder.py index 65b0ef74..2e1d5251 100644 --- a/src/deepgram/helpers/text_builder.py +++ b/src/deepgram/helpers/text_builder.py @@ -129,7 +129,7 @@ def from_ssml(self, ssml_text: str) -> "TextBuilder": Parse SSML and convert to Deepgram's inline format. Supports: - word → pronunciation() - - → pause() + - → pause() (any attribute order or spacing) - Plain text → text() Returns self for chaining. @@ -255,7 +255,8 @@ def ssml_to_deepgram(ssml_text: str) -> str: Supports: - word - - or + - or , in any attribute order and + alongside other attributes such as `strength`, which are ignored - Strips wrapper tags Args: @@ -290,7 +291,13 @@ def ssml_to_deepgram(ssml_text: str) -> str: # Handle tags. Attribute order is not significant in SSML, so match # the attributes as a group and pull `ph` out of it rather than requiring # `alphabet` before `ph` (which silently dropped the pronunciation otherwise). - phoneme_pattern = r"]*?)\s*>([^<]*)" + # A single `\s` separator with no trailing `\s*`: three whitespace-capable + # quantifiers in a row (`\s+`, `[^<>]*?`, `\s*`) backtrack cubically on an + # unterminated tag (measured at about 8x per doubling of the whitespace run), + # so `]*?)>([^<]*)" def replace_phoneme(match): attributes = match.group(1) @@ -304,8 +311,15 @@ def replace_phoneme(match): ssml_text = re.sub(phoneme_pattern, replace_phoneme, ssml_text) - # Handle tags - break_pattern = r"]*?)\s*/>" + # Handle tags. Attribute order and spacing are not significant in SSML, + # so match the attributes as a group and pull `time` out of it rather than + # requiring `time` to be the only attribute written without spaces around the + # `=` (which silently dropped the pause otherwise). Quantifiers kept + # non-overlapping for the same cubic-backtracking reason as `phoneme_pattern` + # above. Note the lookup below is not quote-aware: a `time=` written inside + # another attribute's quoted value is read as the real one. See + # `test_break_reads_a_decoy_time_inside_another_attribute_value`. + break_pattern = r"]*?)/>" def replace_break(match): time_match = re.search( diff --git a/tests/custom/test_text_builder.py b/tests/custom/test_text_builder.py index 9d69c600..8a437aea 100644 --- a/tests/custom/test_text_builder.py +++ b/tests/custom/test_text_builder.py @@ -2,6 +2,8 @@ Tests for TextBuilder and TTS helper utilities """ +import time + import pytest from deepgram.helpers import ( @@ -350,6 +352,100 @@ def test_break_out_of_range(self): with pytest.raises(ValueError, match="at least 500ms"): ssml_to_deepgram(ssml) + @pytest.mark.parametrize( + "markup", + [ + '', + "", + '', + '', + ], + ) + def test_break_accepts_attribute_spacing_and_order(self, markup): + """`time` is found wherever it sits, so the pause is not silently dropped.""" + ssml = f"Hello{markup}world" + + assert ssml_to_deepgram(ssml) == r"Hello\{pause:500ms\}world" + assert TextBuilder().from_ssml(ssml).build() == r"Hello\{pause:500ms\}world" + + def test_break_with_attributes_enforces_duration_floor(self): + """An attributed break is validated exactly as a bare break already was.""" + ssml = 'ab' + with pytest.raises(ValueError, match="at least 500ms"): + ssml_to_deepgram(ssml) + + def test_break_with_attributes_enforces_duration_ceiling(self): + """An attributed break over the Flux batch maximum raises rather than vanishing.""" + ssml = 'ab' + with pytest.raises(ValueError, match="must not exceed 3000ms"): + ssml_to_deepgram(ssml) + + def test_break_with_attributes_rejects_mixed_controls(self): + """An attributed break counts toward the pronunciation/pause exclusion.""" + ssml = ( + 'med' + 'now' + ) + with pytest.raises(ValueError, match="cannot be combined"): + ssml_to_deepgram(ssml) + + def test_break_with_attributes_counts_toward_pause_limit(self): + """An attributed break counts toward the eight-pause Flux batch limit.""" + ssml = "" + '' * 9 + "" + with pytest.raises(ValueError, match="Maximum 8 pauses"): + ssml_to_deepgram(ssml) + + @pytest.mark.parametrize("attribute", ["break-time", "xtime", "TIME"]) + def test_break_ignores_attributes_that_merely_end_in_time(self, attribute): + """Only a whole `time` attribute sets the pause; near-misses are not pauses.""" + ssml = f'ab' + + assert ssml_to_deepgram(ssml) == "ab" + + @pytest.mark.parametrize("duration", ['550ms', '0.55s']) + def test_break_with_attributes_enforces_increment_grid(self, duration): + """An attributed break off the 100ms grid raises, as a bare break already did.""" + ssml = f'ab' + with pytest.raises(ValueError, match="100ms increments"): + ssml_to_deepgram(ssml) + + def test_break_reads_a_decoy_time_inside_another_attribute_value(self): + """Known limitation: the `time` lookup is not quote-aware. + + The attributes are searched as one string, and a space inside a quoted + value satisfies the `(?:^|\\s)` and `(?=\\s|$)` boundaries, so a `time=` + written inside another attribute's value is read as the real one and wins + on `re.search` order. The markup is malformed, so no valid SSML is + affected, and the same shape already applies to `ph` on ``. + Recorded so a future quote-aware rewrite has a case to flip. + """ + decoy_only = 'ab' + assert ssml_to_deepgram(decoy_only) == r"a\{pause:500ms\}b" + + decoy_wins = 'ab' + assert ssml_to_deepgram(decoy_wins) == r"a\{pause:600ms\}b" + + with pytest.raises(ValueError, match="at least 500ms"): + ssml_to_deepgram('ab') + + @pytest.mark.parametrize("tag", ["` case guards a defect that shipped: in 7.20.0 and + earlier this input takes roughly 22s at n=4000. The `` case guards + the same shape in the wider matcher added alongside this test; the + released `` pattern was never affected. The bound is generous, the + margin is about 200x, so ordinary CI jitter cannot trip it. + """ + ssml = "ok " + tag + " " * 4000 + "x" + + started = time.perf_counter() + ssml_to_deepgram(ssml) + assert time.perf_counter() - started < 2.0 + class TestFromSsml: """Tests for TextBuilder.from_ssml() method""" @@ -554,19 +650,3 @@ def test_standalone_function_workflow(self): assert '"pronounce": "ˌæzəˈθaɪəpriːn"' in text assert '"word": "dupilumab"' in text assert '"pronounce": "duːˈpɪljuːmæb"' in text - - -@pytest.mark.parametrize( - "markup", - [ - '', - "", - '', - '', - ], -) -def test_ssml_break_time_accepts_attribute_spacing_and_order(markup): - ssml = f"Hello{markup}world" - - assert ssml_to_deepgram(ssml) == r"Hello\{pause:500ms\}world" - assert TextBuilder().from_ssml(ssml).build() == r"Hello\{pause:500ms\}world"