Merge master into the transcript queue branch

This commit is contained in:
2026-08-27 15:35:08 +03:00
37 changed files with 3297 additions and 432 deletions
+89 -29
View File
@@ -58,17 +58,22 @@ class Pipeline(QObject):
def busy(self):
return self._thread is not None and self._thread.is_alive()
def run(self, wav_path, duration, rms_values=(), ask=False, paste=None):
def run(self, wav_path, duration, rms_values=(), ask=False, paste=None,
focus=None):
"""`paste` overrides the setting for this one run, which is what a
dictation asked for from a terminal wants: the text comes back down the
socket, and pasting it into whatever had focus is nobody's intention.
`focus` is the application that was in front when the recording began,
as a process id, and is where the paste is meant to land.
A run started while one is going waits its turn rather than being
dropped: the next dictation can be spoken while the last one is still
being cleaned up, and each one is finished, pasted and reported in the
order it was spoken."""
with self._jobs_lock:
self._jobs.append((wav_path, duration, list(rms_values), ask, paste))
self._jobs.append((wav_path, duration, list(rms_values), ask, paste,
focus))
if self._draining:
return
self._draining = True
@@ -94,7 +99,8 @@ class Pipeline(QObject):
"""
self._stop.set()
def _work(self, wav_path, duration, rms_values, ask, paste_override=None):
def _work(self, wav_path, duration, rms_values, ask, paste_override=None,
focus=None):
conf = self.conf
started = time.monotonic()
raw = ""
@@ -128,11 +134,16 @@ class Pipeline(QObject):
text = raw
warning = ""
# Remembered rather than re-derived at the history write below: the
# ask path runs cleanup under a different setting, and the record
# should say what happened, not what one of the two gates implies.
cleaned = False
# Claude reads through “eee” and “hani” without help, so a dictation
# on its way there is normally sent as it was heard, one API call and
# a second or two lighter.
if (conf["assistant_cleanup"] if ask else conf["cleanup_enabled"]):
self.stage.emit(t("Cleaning up…"))
cleaned = True
try:
text = cleanup.run(raw, conf, conf.cleanup_prompt())
except api.ApiError as exc:
@@ -158,62 +169,111 @@ class Pipeline(QObject):
if paste_override is not None:
wants_paste = paste_override
with _paste_lock:
previous = (paste.read_clipboard()
if conf["restore_clipboard"] and wants_paste else None)
try:
paste.copy(text)
if wants_paste:
self.stage.emit(t("Pasting…"))
paste.press(conf["paste_shortcut"])
finally:
if previous is not None:
# Let the focused application consume the temporary
# transcription before putting every old clipboard type
# back. This also runs when key injection fails.
time.sleep(0.35)
paste.copy_bytes(previous)
cfg.append_history({
# Into the history before the paste is attempted: the record says
# what was dictated, not whether a key press landed, and a paste
# that fails must not take the transcript down with it.
record = {
"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
"duration": round(duration, 1),
"elapsed": round(time.monotonic() - started, 1),
"model": target.model,
"cleanup_model": cleanup.model(conf) if conf["cleanup_enabled"] else "",
"cleanup_model": cleanup.model(conf) if cleaned else "",
"cleanup_error": warning,
"mode": "ask" if ask else "",
"question": question,
"assistant_model": conf["assistant_model"] if ask else "",
"raw": raw,
"text": text,
})
}
cfg.append_history(record)
try:
cfg.trim_history(conf["history_limit"])
except OSError as exc:
print(f"dikte: could not trim the history: {exc}", file=sys.stderr)
with _paste_lock:
previous = (paste.read_clipboard()
if conf["restore_clipboard"] and wants_paste else None)
paste.copy(text)
if wants_paste:
self.stage.emit(t("Pasting…"))
try:
paste.press(conf["paste_shortcut"], focus=focus)
except paste.PasteError as exc:
# The transcript is on the clipboard and in the history;
# a key press that would not land is a warning, not a
# failure, and the old clipboard is NOT put back over
# the text the user now has to paste by hand.
previous = None
warning = "\n".join(x for x in (
warning,
t("Copied, but pasting failed: {error}", error=exc),
) if x)
# The row above was written before the paste, so it
# has to be told what the paste then did.
record = cfg.amend_history(
record, cleanup_error=warning) or record
if previous is not None:
# Let the focused application consume the temporary
# transcription before putting every old clipboard type
# back.
time.sleep(0.35)
paste.copy_bytes(previous)
self.finished.emit(raw, text, warning)
except assistant.Cancelled:
self.cancelled.emit()
except (api.ApiError, paste.PasteError, assistant.AssistantError) as exc:
print(f"dikte: {exc}", file=sys.stderr)
self.failed.emit(str(exc))
self.failed.emit(self._keeping(wav_path, str(exc)))
except Exception as exc: # never fail silently
traceback.print_exc()
self.failed.emit(t("Unexpected error: {error}", error=exc))
self.failed.emit(self._keeping(wav_path, t("Unexpected error: {error}",
error=exc)))
finally:
self._discard(wav_path)
def _keeping(self, wav_path, message):
"""Put the failed run's audio somewhere a retry can find it.
A dictation that died on the way to the model is speech the user cannot
say again from memory; deleting it because a server was down turns one
failure into two. Kept regardless of the keep_audio setting, which is
about the runs that succeeded.
"""
kept = self._keep(wav_path)
if not kept:
return message
return message + "\n" + t("The recording was kept: {path}", path=kept)
def _keep(self, wav_path):
"""Move the WAV into the recordings directory; its new path, or ''."""
try:
cfg.RECORDINGS_DIR.mkdir(parents=True, exist_ok=True)
base = time.strftime("%Y%m%d-%H%M%S")
# Two runs can finish inside the same second; the first one kept
# must not be overwritten by the second.
for suffix in ("",) + tuple(f"-{n}" for n in range(1, 100)):
target = cfg.RECORDINGS_DIR / f"{base}{suffix}.wav"
if not target.exists():
shutil.move(wav_path, target)
return str(target)
return ""
except OSError as exc:
print(f"dikte: could not keep the audio: {exc}", file=sys.stderr)
return ""
def _discard(self, wav_path):
if not os.path.exists(wav_path):
return
if self.conf["keep_audio"]:
try:
cfg.RECORDINGS_DIR.mkdir(parents=True, exist_ok=True)
shutil.move(wav_path, cfg.RECORDINGS_DIR / (time.strftime("%Y%m%d-%H%M%S") + ".wav"))
if self._keep(wav_path):
return
except OSError:
pass
# The move failing is no reason to delete what the user asked to
# keep: the temporary file stays where it is, named in the log.
print(f"dikte: the audio stays at {wav_path}", file=sys.stderr)
return
try:
os.unlink(wav_path)
except OSError: