Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ def install(self, patch, reference, config):
class Callback(module.ResultCallback):
def __init__(self, callback):
self.callback = callback
self.request_id = getattr(callback, "request_id", None)

def on_data(self, data):
reference.capture("audio", data)
request_id = getattr(self.callback, "request_id", None)
reference.capture("audio", data, request_id=request_id)
return self.callback.on_data(data)

def on_open(self):
Expand All @@ -39,7 +41,9 @@ def borrow(pool, *args, **kwargs):
return original_borrow(pool, *args, **kwargs)

def streaming_call(synthesizer, text, *args, **kwargs):
reference.capture("text", text)
callback = getattr(synthesizer, "callback", None)
request_id = getattr(callback, "request_id", None)
reference.capture("text", text, request_id=request_id)
return original_call(synthesizer, text, *args, **kwargs)

patch.setattr(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,51 @@ def borrow_synthesizer(self, callback):
pool.synthesizer.streaming_call("Hello")
assert received == [b"audio"]
assert reference.elapsed_ms("first") == 20


def test_cosy_hook_binds_late_audio_to_original_callback(monkeypatch, clock):
from .provider_ttfb_hooks.cosy import Hook

class Synthesizer:
def streaming_call(self, text):
self.callback.on_data(text.encode())

class Pool:
def __init__(self):
self.synthesizer = Synthesizer()

def borrow_synthesizer(self, callback):
self.synthesizer.callback = callback
return self.synthesizer

module = SimpleNamespace(
SpeechSynthesizer=Synthesizer,
SpeechSynthesizerObjectPool=Pool,
ResultCallback=object,
)
monkeypatch.setattr(
"tests.provider_ttfb_hooks.cosy.import_module", lambda name: module
)
pool = Pool()
reference = Reference()
Hook().install(monkeypatch, reference, {})

reference.begin_request("first")
old_callback = pool.borrow_synthesizer(
callback=SimpleNamespace(request_id="first", on_data=lambda data: None)
).callback
reference.capture("text", "first")
clock[0] = 20_000_000
old_callback.on_data(b"old-audio")

reference.begin_request("second")
new_callback = pool.borrow_synthesizer(
callback=SimpleNamespace(request_id="second", on_data=lambda data: None)
).callback
reference.capture("text", "second")
clock[0] = 30_000_000
old_callback.on_data(b"late-old-audio")
assert reference.elapsed_ms("second") is None
new_callback.on_data(b"new-audio")
assert reference.elapsed_ms("first") == 20
assert reference.elapsed_ms("second") == 30
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from .timing_hooks.bytedance import ByteDanceTimingHook
from .timing_hooks.bytedance_duplex import ByteDanceDuplexTimingHook
from .timing_hooks.cartesia import _add_spacing_groups
from .timing_hooks.cosy import CosyTimingHook
from .timing_hooks.elevenlabs import ElevenLabsTimingHook
from .timing_hooks.minimax import MiniMaxTimingHook

Expand Down Expand Up @@ -182,7 +183,9 @@ def test_minimax_reference_keeps_request_relative_word_times():


def _duplex_message(event, payload=None, payload_json=None):
return SimpleNamespace(event=event, payload=payload, payload_json=payload_json)
return SimpleNamespace(
event=event, payload=payload, payload_json=payload_json
)


def _duplex_hook():
Expand Down Expand Up @@ -252,7 +255,9 @@ def test_bytedance_reference_keeps_leading_silence_offset():
hook = ByteDanceTimingHook()
hook.sample_rate = 16000
hook.begin_request("req-1")
session = SimpleNamespace(original_request_id="req-1", tts_input=SimpleNamespace())
session = SimpleNamespace(
original_request_id="req-1", tts_input=SimpleNamespace()
)

hook._observe_frontend_msg(
session,
Expand Down Expand Up @@ -298,3 +303,46 @@ def test_bytedance_reference_keeps_leading_silence_offset():
assert words[0].end_ms == 130
assert words[1].start_ms == 140
assert words[1].end_ms == 240


def test_cosy_reference_deduplicates_request_scoped_indexes_across_sentences():
hook = CosyTimingHook()
hook.sample_rate = 24000
hook.begin_request("req-cosy")

def message(index, event_type, words):
return json.dumps(
{
"header": {"event": "result-generated"},
"payload": {
"output": {
"type": event_type,
"sentence": {"index": index, "words": words},
}
},
}
)

words = [
{
"text": "今",
"begin_time": 0,
"end_time": 100,
"begin_index": 98,
"end_index": 99,
},
{
"text": "道",
"begin_time": 100,
"end_time": 200,
"begin_index": 99,
"end_index": 100,
},
]
hook.observe_receive(message(5, "sentence-end", words))
hook.observe_receive(message(6, "sentence-end", words))

reference = hook.reference("req-cosy")
assert [[word.word for word in group] for group in reference.captions] == [
["今道"]
]
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def __init__(self):
self.pcm_bytes = 0
self.groups = []
self.emitted = {}
self.emitted_index_end = None
self.error = None

def install(self, monkeypatch, config):
Expand Down Expand Up @@ -70,6 +71,7 @@ def begin_request(self, request_id):
self.pcm_bytes = 0
self.groups = []
self.emitted = {}
self.emitted_index_end = None
self.error = None

def observe_send(self, payload):
Expand All @@ -92,26 +94,48 @@ def observe_receive(self, payload):
text = item.get("text")
begin = item.get("begin_time")
end = item.get("end_time")
begin_index = item.get("begin_index")
end_index = item.get("end_index")
if (
isinstance(text, str)
and text
and isinstance(begin, (int, float))
and isinstance(end, (int, float))
):
raw_words.append((text, begin, end))
emitted = self.emitted.get(index, 0)
raw_words.append(
(text, begin, end, begin_index, end_index)
)
indexed = all(
begin_index is not None and end_index is not None
for _, _, _, begin_index, end_index in raw_words
) and bool(raw_words)
if indexed:
boundary = self.emitted_index_end
unseen = [
word
for word in raw_words
if boundary is None or word[3] >= boundary
]
else:
emitted = self.emitted.get(index, 0)
unseen = raw_words[emitted:]
limit = (
len(raw_words)
len(unseen)
if output.get("type") == "sentence-end"
else max(0, len(raw_words) - 1)
else max(0, len(unseen) - 1)
)
if limit <= emitted:
if limit <= 0:
return
words = [
ReferenceWord(text, Fraction(begin), Fraction(end))
for text, begin, end in raw_words[emitted:limit]
for text, begin, end, _, _ in unseen[:limit]
]
self.emitted[index] = limit
if indexed:
self.emitted_index_end = max(
word[4] for word in unseen[:limit]
)
else:
self.emitted[index] = emitted + limit
if words:
self.groups.append(tuple(words))
except (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ class _RawWord:
word: str
begin_ms: int
end_ms: int
begin_index: int | None = None
end_index: int | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -444,7 +446,15 @@ def __init__(
self._pcm_samples = 0
self._sentence_origin_samples: dict[int, int] = {}
self._sentence_time_offset: dict[int, int] = {}
self._emitted_words: dict[int, int] = {}
# Provider word indexes are request-scoped, not sentence-scoped. Keep
# only the contiguous published character boundary for bounded memory.
self._emitted_end_index: int | None = None
self._fallback_end_ms: dict[int, int] = {}
# Keep all identities at the current time boundary. A provider can
# report several distinct zero-duration words at the same timestamp;
# retaining only the last one republishes the earlier entries when a
# cumulative event is repeated.
self._fallback_boundary_keys: dict[int, set[tuple[str, int, int]]] = {}
self._current_sentence_index: int | None = None

def bind_task(self, task_id: str) -> None:
Expand Down Expand Up @@ -616,26 +626,67 @@ def _handle_output(self, payload: Any) -> None:
index,
self._pcm_samples,
)
emitted = self._emitted_words.get(index, 0)
if len(words) < emitted:
# A shorter list would reopen published words; wait for the complete
# list in `sentence-end` instead of publishing them twice.
boundary = self._emitted_end_index
offset_ms = self._sentence_word_offset(index, words, origin_samples)
unseen = [
word
for word in words
if (
(boundary is None or word.begin_index >= boundary)
if word.begin_index is not None and word.end_index is not None
else self._fallback_is_new(index, word, offset_ms)
)
]
if not unseen:
return

limit = (
len(words)
len(unseen)
if event_type == "sentence-end"
else max(0, len(words) - SUBTITLE_LAG_WORDS)
else max(0, len(unseen) - SUBTITLE_LAG_WORDS)
)
if limit <= emitted:
if limit <= 0:
return

subtitle = self._build_subtitle(
index,
words[emitted:limit],
unseen[:limit],
origin_samples,
)
self._emitted_words[index] = limit
published = unseen[:limit]
indexed_ends = [
word.end_index for word in published if word.end_index is not None
]
if indexed_ends:
self._emitted_end_index = max(indexed_ends)
fallback_words = [
word for word in published if word.begin_index is None
]
if fallback_words:
old_boundary = self._fallback_end_ms.get(index, -1)
adjusted = [
(
word.word,
word.begin_ms + offset_ms,
word.end_ms + offset_ms,
)
for word in fallback_words
]
new_boundary = max(
old_boundary,
max(end for _, _, end in adjusted),
)
boundary_keys = {
(word, begin, end)
for word, begin, end in adjusted
if begin == new_boundary
}
if new_boundary == old_boundary:
boundary_keys.update(
self._fallback_boundary_keys.get(index, set())
)
self._fallback_end_ms[index] = new_boundary
self._fallback_boundary_keys[index] = boundary_keys
if subtitle is None:
return
self._put(
Expand Down Expand Up @@ -666,6 +717,18 @@ def _sentence_index(self, event_type: str, sentence: dict[str, Any]) -> int:
)
return self._current_sentence_index

def _fallback_is_new(
self, index: int, word: _RawWord, offset_ms: int
) -> bool:
begin = word.begin_ms + offset_ms
end = word.end_ms + offset_ms
boundary = self._fallback_end_ms.get(index, -1)
key = (word.word, begin, end)
return begin > boundary or (
begin == boundary
and key not in self._fallback_boundary_keys.get(index, set())
)

@staticmethod
def _parse_words(raw_words: Any) -> list[_RawWord]:
if not isinstance(raw_words, list):
Expand All @@ -682,7 +745,21 @@ def _parse_words(raw_words: Any) -> list[_RawWord]:
end_ms = _as_milliseconds(entry.get("end_time"))
if begin_ms is None or end_ms is None or end_ms < begin_ms:
continue
words.append(_RawWord(word=text, begin_ms=begin_ms, end_ms=end_ms))
begin_index = entry.get("begin_index")
end_index = entry.get("end_index")
if not isinstance(begin_index, int) or not isinstance(
end_index, int
):
begin_index = end_index = None
words.append(
_RawWord(
word=text,
begin_ms=begin_ms,
end_ms=end_ms,
begin_index=begin_index,
end_index=end_index,
)
)
return words

def _build_subtitle(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"type": "extension",
"name": "cosy_tts_python",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": [
{
"type": "system",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "cosy-tts-python"
version = "0.5.0"
version = "0.5.1"
requires-python = ">=3.10"
dependencies = [
"dashscope==1.26.4",
Expand Down
Loading
Loading