Skip to content
Merged
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
34 changes: 27 additions & 7 deletions src/deepgram/helpers/text_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def from_ssml(self, ssml_text: str) -> "TextBuilder":
Parse SSML and convert to Deepgram's inline format.
Supports:
- <phoneme alphabet="ipa" ph="...">word</phoneme> → pronunciation()
- <break time="500ms"/> → pause()
- <break time="500ms"/> → pause() (any attribute order or spacing)
- Plain text → text()
Returns self for chaining.

Expand Down Expand Up @@ -255,7 +255,8 @@ def ssml_to_deepgram(ssml_text: str) -> str:

Supports:
- <phoneme alphabet="ipa" ph="...">word</phoneme>
- <break time="500ms"/> or <break time="0.5s"/>
- <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

Args:
Expand Down Expand Up @@ -290,7 +291,13 @@ def ssml_to_deepgram(ssml_text: str) -> str:
# Handle <phoneme> 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"<phoneme\s+([^<>]*?)\s*>([^<]*)</phoneme>"
# 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 `<phoneme ` followed by a few kilobytes of spaces hangs the call. The
# attribute lookups below are anchored on `(?:^|\s)`, so the group may keep
# its surrounding whitespace.
phoneme_pattern = r"<phoneme\s([^<>]*?)>([^<]*)</phoneme>"

def replace_phoneme(match):
attributes = match.group(1)
Expand All @@ -304,12 +311,25 @@ def replace_phoneme(match):

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

# Handle <break> tags
break_pattern = r'<break\s+time=["\'](\d+(?:\.\d+)?)(ms|s)["\']\s*/>'
# Handle <break> 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"<break\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():
Expand Down
96 changes: 96 additions & 0 deletions tests/custom/test_text_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Tests for TextBuilder and TTS helper utilities
"""

import time

import pytest

from deepgram.helpers import (
Expand Down Expand Up @@ -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",
[
'<break time = "500ms"/>',
"<break time='0.5s' strength='medium'/>",
'<break strength="medium" time="500ms"/>',
'<break\nstrength="medium"\ntime = "0.5s" />',
],
)
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"<speak>Hello{markup}world</speak>"

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 = '<speak>a<break strength="medium" time="250ms"/>b</speak>'
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 = '<speak>a<break strength="medium" time="4000ms"/>b</speak>'
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 = (
'<speak><phoneme alphabet="ipa" ph="x">med</phoneme>'
'<break strength="medium" time="500ms"/>now</speak>'
)
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 = "<speak>" + '<break strength="x" time="500ms"/>' * 9 + "</speak>"
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'<speak>a<break {attribute}="500ms"/>b</speak>'

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'<speak>a<break strength="x" time="{duration}"/>b</speak>'
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 `<phoneme>`.
Recorded so a future quote-aware rewrite has a case to flip.
"""
decoy_only = '<speak>a<break foo="x time=\'500ms\' y"/>b</speak>'
assert ssml_to_deepgram(decoy_only) == r"a\{pause:500ms\}b"

decoy_wins = '<speak>a<break foo="x time=\'600ms\' y" time="500ms"/>b</speak>'
assert ssml_to_deepgram(decoy_wins) == r"a\{pause:600ms\}b"

with pytest.raises(ValueError, match="at least 500ms"):
ssml_to_deepgram('<speak>a<break foo="x time=\'250ms\' y"/>b</speak>')

@pytest.mark.parametrize("tag", ["<break ", "<phoneme "])
def test_unterminated_tag_does_not_backtrack(self, tag):
"""An unclosed tag with a long whitespace run must not hang the matcher.

The attribute group and its separator must not both be able to match
whitespace, or the match backtracks cubically, about 8x per doubling of
the run. The `<phoneme>` case guards a defect that shipped: in 7.20.0 and
earlier this input takes roughly 22s at n=4000. The `<break>` case guards
the same shape in the wider matcher added alongside this test; the
released `<break>` pattern was never affected. The bound is generous, the
margin is about 200x, so ordinary CI jitter cannot trip it.
"""
ssml = "<speak>ok " + tag + " " * 4000 + "x</speak>"

started = time.perf_counter()
ssml_to_deepgram(ssml)
assert time.perf_counter() - started < 2.0


class TestFromSsml:
"""Tests for TextBuilder.from_ssml() method"""
Expand Down
Loading