Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(voice): preserve words after transcript overlap seams

rubenluetke10-beep146e770f7f8f
diff --git a/jarvis/dictation/merge.py b/jarvis/dictation/merge.py
index c226672b82..437470867d 100644
--- a/jarvis/dictation/merge.py
+++ b/jarvis/dictation/merge.py
@@ -140,20 +140,41 @@ def _drop_leading_words(text: str, count: int) -> str:
"""
if count <= 0:
return text
- seen = 0
- index = 0
- length = len(text)
- while index < length and seen < count:
- while index < length and text[index].isspace():
- index += 1
- start = index
- while index < length and not text[index].isspace():
- index += 1
- if index > start and _normalize(text[start:index]):
- # A run of pure punctuation is not a word; the normalised token
- # list did not count it either, so it must not consume a step.
- seen += 1
- return text[index:].lstrip()
+ prefix = " ".join(_normalize(text).split()[:count])
+ return _drop_normalized_prefix(text, prefix)
+
+
+def _drop_normalized_prefix(text: str, prefix: str) -> str:
+ """Map an overlap back to an exact source boundary, or keep the text.
+
+ A space-delimited source token can represent several comparison tokens
+ (``read-only``, ``it's``, ``2.5``). Counting source words would discard
+ unrelated words after the seam, including negations. Normalize prefixes
+ with the SAME function used for matching instead. Whole-prefix Unicode
+ normalization also keeps composed characters and compatibility expansions
+ intact; normalizing one character at a time cannot do that.
+
+ Only the matched prefix and its trailing separators are scanned. If the
+ seam falls inside an indivisible expansion, retain the original text:
+ repeating part of a word is preferable to deleting the rest of it.
+ """
+ if not prefix:
+ return text
+ if prefix == _normalize(text):
+ return ""
+ end: int | None = None
+ for index in range(1, len(text) + 1):
+ normalized = _normalize(text[:index])
+ if normalized == prefix and (
+ end is None or all(unicodedata.category(c).startswith("M") for c in text[end:index])
+ ):
+ end = index
+ elif len(normalized) > len(prefix):
+ break
+ # Remove punctuation attached to the matched word, then whitespace. Do
+ # not skip every non-word character: a following "-5" or "--verbose"
+ # belongs to the continuation, including its sign/prefix.
+ return text[end:].lstrip(",.;:!?、。,;:!?").lstrip() if end is not None else text
def merge_transcripts(parts: Sequence[str]) -> str:
@@ -236,19 +257,13 @@ def transcript_token_count(text: str) -> int:
def _drop_leading_chars(text: str, count: int) -> str:
"""``text`` without the first ``count`` characters OF ITS NORMALISED view.
- The original and the normalised string do not line up character for
- character (punctuation disappears, NFKC can merge a pair), so this consumes
- the original one character at a time and stops when the normalised budget
- is spent.
+ Use the same source-boundary mapping as the word search: punctuation adds
+ separators and NFKC can combine or expand characters, so per-character
+ counts are not offsets in the normalized whole string.
"""
if count <= 0:
return text
- spent = 0
- index = 0
- while index < len(text) and spent < count:
- spent += len(_normalize(text[index]))
- index += 1
- return text[index:].lstrip()
+ return _drop_normalized_prefix(text, _normalize(text)[:count])
__all__ = [
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index f6e84454b0..bda004ce6d 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1984,8 +1984,6 @@ def _merge_partial_transcript(current: str, incoming: str) -> str:
if not incoming:
return current
- current_words = current.split()
- incoming_words = incoming.split()
current_norm = _normalized_partial_words(current)
incoming_norm = _normalized_partial_words(incoming)
@@ -1994,11 +1992,16 @@ def _merge_partial_transcript(current: str, incoming: str) -> str:
if _is_likely_repeated_tail(current_norm, incoming_norm):
return current
- max_overlap = min(len(current_words), len(incoming_words))
+ max_overlap = min(len(current_norm), len(incoming_norm))
for overlap in range(max_overlap, 0, -1):
if current_norm[-overlap:] == incoming_norm[:overlap]:
- return " ".join([*current_words, *incoming_words[overlap:]])
+ # Match and slice the SAME tokens. Whitespace splitting counts
+ # "read-only" once while the comparison counts it twice, which
+ # used to delete the next meaningful word from the live text.
+ spans = list(re.finditer(r"[\w']+", incoming, flags=re.UNICODE))
+ tail = incoming[spans[overlap - 1].end():].lstrip(",.;:!?、。,;:!?").lstrip()
+ return f"{current} {tail}" if tail else current
if incoming.lower() in current.lower():
return current
if current.lower() in incoming.lower():
@@ -2007,11 +2010,11 @@ def _merge_partial_transcript(current: str, incoming: str) -> str:
def _normalized_partial_words(text: str) -> list[str]:
- words = re.findall(r"[\w']+", text.lower(), flags=re.UNICODE)
+ words = re.findall(r"[\w']+", text, flags=re.UNICODE)
normalized: list[str] = []
for word in words:
word = (
- word.replace("ä", "ae")
+ word.lower().replace("ä", "ae")
.replace("ö", "oe")
.replace("ü", "ue")
.replace("ß", "ss")
diff --git a/tests/unit/dictation/test_final_quality_windows.py b/tests/unit/dictation/test_final_quality_windows.py
index be0da407f6..f6893353a6 100644
--- a/tests/unit/dictation/test_final_quality_windows.py
+++ b/tests/unit/dictation/test_final_quality_windows.py
@@ -1,5 +1,7 @@
"""Final dictation windows and their lossless text seam."""
+import pytest
+
from jarvis.dictation.merge import merge_transcripts
from jarvis.dictation.segment import quality_windows
@@ -81,3 +83,44 @@ def test_merge_does_not_insert_spaces_into_cjk_text() -> None:
"東京へ行きます明日は大阪です", # i18n-allow: Japanese transcription fixture
]
) == "今日は東京へ行きます明日は大阪です" # i18n-allow: Japanese fixture
+
+
+ ("left", "right", "expected"),
+ [
+ ("I said do not", "do-not delete these files.", "I said do not delete these files."),
+ ("Use read only", "read-only mode today.", "Use read only mode today."),
+ ("We know it s", "it's not ready.", "We know it s not ready."),
+ ("Use version 2 5", "2.5 without upgrading.", "Use version 2 5 without upgrading."),
+ ("The host is example com", "example.com stays local.",
+ "The host is example com stays local."),
+ ("Keep alpha beta", "alpha,beta,gamma intact.", "Keep alpha beta gamma intact."),
+ ("Keep alpha beta", "alpha / beta: gamma intact.", "Keep alpha beta gamma intact."),
+ ("Keep the value", "the value -5 unchanged.", "Keep the value -5 unchanged."),
+ ("Keep the value", "the value:-5 unchanged.", "Keep the value -5 unchanged."),
+ ("Use this flag", "this flag --verbose today.", "Use this flag --verbose today."),
+ ("Use the ffi key", "\ufb03-key carefully.", "Use the ffi key carefully."),
+ ("Use cafe\u0301 mode", "café-mode quietly.", "Use cafe\u0301 mode quietly."),
+ ("Use café mode", "cafe\u0301-mode quietly.", "Use café mode quietly."),
+ # i18n-allow: German speech with a hyphenated provider rendering
+ ("Bitte den Schreib Schutz", "Schreib-Schutz nicht entfernen.", # i18n-allow
+ "Bitte den Schreib Schutz nicht entfernen."), # i18n-allow
+ # i18n-allow: punctuation and compatibility forms at a Japanese seam
+ ("今日は東京、大阪", "東京、大阪へ行きます", "今日は東京、大阪へ行きます"),
+ ("今日はガイド", "ガイドを見ます", "今日はガイドを見ます"),
+ ],
+)
+def test_merge_only_removes_the_matched_original_span(
+ left: str, right: str, expected: str,
+) -> None:
+ assert merge_transcripts([left, right]) == expected
+
+
+def test_merge_keeps_an_indivisible_unicode_expansion() -> None:
+ # The seam ends INSIDE a single source character (square corporation).
+ # Keep that character whole, even if it means repeating the matched prefix.
+ assert merge_transcripts(["株式", "㍿へ行く"]) == "株式 ㍿へ行く" # i18n-allow
+
+
+def test_merge_of_an_entire_repeated_window_drops_its_closing_punctuation() -> None:
+ assert merge_transcripts(["Please stop now.", "“stop now.”"]) == "Please stop now."
diff --git a/tests/unit/dictation/test_incremental_final_pass.py b/tests/unit/dictation/test_incremental_final_pass.py
index ed7bac9edb..951ba5d479 100644
--- a/tests/unit/dictation/test_incremental_final_pass.py
+++ b/tests/unit/dictation/test_incremental_final_pass.py
@@ -22,7 +22,7 @@ from typing import Any
import pytest
from jarvis.core.config import DictationConfig
-from jarvis.core.events import DictationCompleted
+from jarvis.core.events import DictationCompleted, DictationTranscript
from jarvis.dictation.segment import next_quality_window, quality_windows
from jarvis.speech.pipeline import SpeechPipeline
from jarvis.speech.stt_fallback import FallbackSTT
@@ -241,6 +241,53 @@ async def test_a_short_recording_is_one_window_read_at_release(_no_preview: None
assert _completed(events).raw_text.startswith("alpha")
[email protected]("concurrent", [False, True])
[email protected]("polish_enabled", [False, True])
+async def test_final_delivery_preserves_content_after_window_seam(
+ _no_preview: None, concurrent: bool, polish_enabled: bool, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Both provider answers are complete. The merger used to count "read-only"
+ # as two normalized words but discard two SPACE-separated words, losing
+ # the negation "never" before cleanup and delivery even got to see it.
+ stt = _CountingSTT(concurrent=concurrent, script=[
+ "Please keep all of these important files marked read only",
+ "read-only never delete any of the original files from this folder.",
+ ])
+ mic = _FakeMic(_voiced(6.0))
+ pipe, events = _session_pipeline(stt, mic, segment_seconds=0.0, partial_interval_s=0.0)
+ pipe._dictation_cfg.polish = polish_enabled
+ pipe._dictation_cfg.polish_min_words = 1
+ polish_inputs: list[str] = []
+
+ async def _identity_polish(raw: str, **_kwargs: Any) -> Any:
+ from jarvis.dictation.polish import PolishOutcome
+
+ polish_inputs.append(raw)
+ return PolishOutcome(
+ text=raw, status="unchanged", provider="fake", model="", latency_ms=0, reason="",
+ )
+
+ monkeypatch.setattr("jarvis.dictation.polish.polish_transcript", _identity_polish)
+ task = asyncio.create_task(pipe._dictation_session())
+ await asyncio.wait_for(mic.delivered.wait(), timeout=10)
+ pipe._dictation_stop_event.set()
+ await asyncio.wait_for(task, timeout=30)
+
+ expected = (
+ "Please keep all of these important files marked read only "
+ "never delete any of the original files from this folder."
+ )
+ assert stt.calls == 2
+ assert _completed(events).raw_text == expected
+ assert _completed(events).text == expected
+ final = next(e for e in events if isinstance(e, DictationTranscript) and e.is_final)
+ assert final.text == expected
+ if polish_enabled:
+ assert "never delete" in " ".join(polish_inputs)
+ else:
+ assert polish_inputs == []
+
+
# --------------------------------------------------------------------------
# What is left at release is read together, when the provider allows it
# --------------------------------------------------------------------------
diff --git a/tests/unit/speech/test_live_transcription_merge.py b/tests/unit/speech/test_live_transcription_merge.py
index 238e0ce303..39fbe213a7 100644
--- a/tests/unit/speech/test_live_transcription_merge.py
+++ b/tests/unit/speech/test_live_transcription_merge.py
@@ -4,6 +4,23 @@ from jarvis.core.protocols import Transcript
from jarvis.speech.pipeline import SpeechPipeline, _merge_partial_transcript
+ ("left", "right", "expected"),
+ [
+ ("I said do not", "do-not delete these files.", "I said do not delete these files."),
+ ("Use alpha beta", "alpha,beta,gamma today.", "Use alpha beta gamma today."),
+ ("Use read only", "read-only mode", "Use read only mode"),
+ ("Use alpha beta", "alpha / beta: gamma today.", "Use alpha beta gamma today."),
+ ("Keep the value", "the value -5 unchanged.", "Keep the value -5 unchanged."),
+ ("Use this flag", "this flag --verbose today.", "Use this flag --verbose today."),
+ ],
+)
+def test_partial_merge_preserves_words_after_punctuated_overlap(
+ left: str, right: str, expected: str,
+) -> None:
+ assert _merge_partial_transcript(left, right) == expected
+
+
def test_merge_partial_transcript_appends_non_overlapping_tail() -> None:
assert (
_merge_partial_transcript("Hallo ich bin", "bin cool")