Repository navigation
feat(media): transcribe voice notes and video notes with a local Whisper program - #183
Conversation
…per program tg media transcribe turns voice notes and video notes into text with a speech-to-text program on this machine (whisper.cpp or an openai-whisper-compatible CLI), stores it in message_transcripts and shows it in the transcript field of message items. tg finds the program on PATH or runs transcribe.command, and never bundles or downloads a model. Setup errors carry the commands to run in their suggestion. Refs neoromantic#102 Co-Authored-By: Claude Fable 5.2 <[email protected]>
The setup errors suggested <data dir>/models/. The model file is not specific to tg: any program that runs whisper.cpp can use it, so the suggestion is now $XDG_CACHE_HOME/whisper-cli/, else ~/.cache/whisper-cli/. Co-Authored-By: Claude Fable 5.2 <[email protected]>
helpers.ts: a message item gets the transcript and the rich text (neoromantic#186). CHANGELOG: both sides' entries kept. Per-message error lines and the docs example carry retryable (neoromantic#177). Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#179 (neoromantic#188). No conflict. Co-Authored-By: Claude Fable 5.2 <[email protected]>
main is now the 0.14.0 release (neoromantic#189). This PR's changelog entries move back under Unreleased: a plain merge left them in the released section. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Design research for #102The local Whisper implementation gives us a concrete starting point. We want to design transcription as a full CLI feature before accepting an implementation. Transcript search is in scope for the first release. Let's use this PR to discuss the design. The command names, provider integrations, queue design and acceptance cases below are proposals. Implementation and merge are pending that discussion. What setup should feel likeTranscription starts off for every account. After a successful interactive phone or QR login, ask once in the terminal whether to configure it. The same settings should be available later through the CLI. The existing One possible terminal interaction, with made-up data: Selecting history opens a chat and date-range choice. New messages and history can be selected independently. Before saving, show which program or service receives the audio, which receives the text, and any spending limit. Keep language auto-detection and the option to specify a local command. Discover local programs and the presence of known ENV keys without sending a sample, printing a key or enabling a provider. An agent should be able to inspect and apply the same choices using flags or structured input. Providers and readable textSupport both direct provider credentials and a user-selected Vercel AI Gateway key. Evaluate the Vercel AI SDK to avoid maintaining a separate client for every model. Show models by what they can do. The audio candidates include ElevenLabs Scribe, OpenAI, Gemini Transcribe and xAI Grok STT, alongside local tools and Telegram's own transcription. Claude is a candidate for editing the text. A Gateway choice should name the actual model. Decide which direct and Gateway combinations we can test and support before advertising them. The source order in #102, particularly what should happen when Telegram returns a flood wait, remains a design question. A fallback that changes where audio goes or incurs a charge needs to be part of the user's selection. AI SDK transcription · Gateway audio · Gemini transcription · xAI speech to text Save the original transcript as soon as recognition succeeds. Optional cleanup gives a fast model the text. The message shows the cleaned version when accepted and the original remains accessible. A failed edit leaves the original readable. Running cleanup again should cost one text operation and zero audio operations. For search, the proposal is to index the displayed version, identify a transcript match and return the message once. The exact search flag and whether ordinary message searches should include transcripts are open. Large imports, overload and spendingMessage sync should finish independently of speech recognition. If the user selects only new messages, importing 400 old recordings should create zero speech jobs. For an explicitly selected history run, preview eligible and already completed counts, known audio duration, incomplete cache coverage, estimated cost and, once measured, an ETA. The PR's M4 Pro benchmark took about 38 seconds with whisper.cpp and 281 seconds with CPU Whisper for the same 295 seconds of audio. That difference matters more to a user than a generic progress spinner. Use a resumable per-account queue with bounded concurrency. Give incoming notes priority over the next history batch. Pausing, restarting or opening settings twice must preserve completed work and avoid duplicate charges. Include recognition and cleanup in the cost preview. One candidate is an account budget plus an optional cap per history run, with a reservation before a paid submission. Honor provider backoff. If a response is lost after a provider may have accepted the request, reconcile its job ID or show an unknown outcome before offering a potentially billable retry. Acceptance cases to discuss
The current head already gives us regression cases. At The decisions worth discussing here first are the search default, provider/fallback choices and how to make a history run's time and cost clear before starting it. Those decisions should determine how we refactor the local command and split the work. |
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. helpers.ts: the item reader takes main's raw string, with the transcript kept. sql.test.ts uses main's cache helper. CHANGELOG: both sides kept. Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#195: Knip in bun run check, and long as a runtime dependency. No conflict; the check is clean. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A changed attachment returned the old transcript, SIGTERM left the converted audio behind, a missing program hid a ready result in a batch, and a stored transcript skipped the content-protection check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…regressions The local programs become a provider behind TranscriptionProvider, and one pipeline gives every provider the same steps: eligibility before reuse, reuse keyed to the file as it is now, setup per message, download and audio only for providers that read audio, a second check before saving, temporary audio removed on interrupt (exit 130). Co-Authored-By: Claude Opus 5.5 <[email protected]>
… providers Co-Authored-By: Claude Opus 5.5 <[email protected]>
…holds now tg messages hid no stale transcript after an attachment changed, and a transcript copied from the same file in another message skipped the save-time check. Also covers cancellation during ffmpeg. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…behaviour Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the detailed review. I reworked the branch around one provider protocol instead of patching the local path, and kept the scope to what exists today. The protocol. A provider declares, before anything runs: where the audio or message reference goes, whether a request can cost money, its input (the message itself, or audio as the original file or 16 kHz WAV), batch size, concurrency and maximum duration. It returns text, language and model, or a failure marked rejected, retry later, or outcome unknown (never retried, nothing stored). One pipeline runs the same steps for every provider: eligibility, reuse keyed to the current file, setup, limits, audio only if needed, the provider, a second eligibility check before each save, temp cleanup. It was shaped against three cases (a local program, a cloud API that takes bytes and bills, Telegram's own transcription that takes a message ID), and only the local provider is implemented. Your four regressions are offline tests now and fixed: a changed attachment, SIGTERM (exit 130, child stopped, WAV removed), a missing runner in a mixed batch, protection before reuse. The description has the details. Proposed split into separate issues, each on top of this protocol: cloud and Telegram providers, the queue with budgets, the setup flow, text clean-up, search. Your three questions:
Does this split work for you? |
Conflicts came from main's oxfmt reformat, comment and return-type sweeps and the test colocation; the transcribe additions were reapplied onto main's versions (access, media, helpers, config, schema, types, download-media's shared cached/online checks, README) and the config and sql test cases moved into main's colocated files. The branch's new code and tests now follow main's lint (no prose comments, inferred return types with satisfies contracts), its tests sit beside their modules or in src/test, and the SIGTERM e2e waits on a file watch instead of polling with a raised timeout. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A runner that wrote parseable JSON and then exited with an error still produced a stored transcript. Any non-zero exit now fails every message of that run. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A provider's rejected result kept the retryable flag of its error, so a rejection caused by a network error read as retryable. rejected is now never retryable; retry_later always is. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…sages For a message the cache does not hold, the pipeline asked Telegram for it before reporting that ffmpeg or the runner was missing, so without credentials the setup error was hidden behind a credentials error. Such a message now fails with the setup problem when the provider is not ready. Co-Authored-By: Claude Fable 5.2 <[email protected]>
SIGHUP killed tg without removing the converted audio, and a second interrupt exited before the pipeline removed it. A signal that arrived while the runner's output was read still let the results be stored and printed with exit 0. SIGHUP now stops a run like SIGINT and SIGTERM, the temporary root is removed on every exit, and cancellation is checked after the provider call and before the results are printed. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Yes, the split works for me. Thanks for reworking the local path and adding the four regression tests. Let's keep #183 focused on the local command and shared provider interface, with linked issues under #102 for terminal setup, the queue and spending limits, Telegram and cloud providers, optional text cleanup, and search. Transcript search is part of the first release. #102 should carry the acceptance criteria that span those issues. Before we settle the individual designs, I'd like us to agree on one end-to-end CLI scenario here. Here is the first-release experience I propose we test with a synthetic chat:
One concrete follow-up for #183 is consistent handling of protected content. Once the cache learns that a previously transcribed message or its chat is protected, Does that sequence work with the proposed split? In particular, I'd like to hear how you would handle a Telegram flood wait during a history run when the user has only authorized Telegram. That is a useful case for agreeing on the queue and provider behavior together. |
…anscribe # Conflicts: # CHANGELOG.md # src/commands/media/download-media.ts
The message reader now applies the offline protection check that tg media transcribe and tg media download use (message flags, the chat's cached noforwards and its last online check), from one function in src/commands/media/protection.ts. The regression case covers a message and a chat that become protected after they were transcribed. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
The sequence works with the split. Protected content is fixed in 5252139. The message reader now makes the same offline check as First result: today the pipeline checks every ID, then downloads and converts all the audio, then calls the provider, and the local provider declares one batch for the whole run. For the queue issue I'd prepare each batch inside its worker, so temp audio is bounded by concurrency × batch size, and give the local provider a finite batch size. I'd leave that out of #183 unless you want it here. Flood wait with only Telegram authorized: |
…anscribe # Conflicts: # CHANGELOG.md
# Conflicts: # CHANGELOG.md # docs/media.md
Release scope
Run
tg media transcribe --chat me --id 42to recognize one voice or video note with local Whisper. Import and sync perform no recognition. Configure the executable and model usingtranscribe.local.commandandtranscribe.local.model. Language detection is the default.tg messages search --query "harbor" --count --snippetincludes stored transcripts for the selected account. Every message counts once. A spoken match hastranscriptMatch: trueand its snippet quotes the speech. Replaced attachments and known protected notes or chats cannot match through stored speech.The implementation checks attachment identity before processing, saving and returning results. Interrupting the CLI stops the local process tree and removes temporary WAV files. Identical audio in a batch is recognized once. Full offline verification on the updated branch passed 1,338 unit tests and 438 CLI tests. A live Saved Messages run for the release candidate is outstanding.
Issue #102 tracks additional providers, opt-in onboarding, history and queue controls, spending limits and optional text cleanup.
Original proposal and earlier verification
What and why
tg media transcribe --chat <peer> --id <id> [--id …]turns voice notes and video notes into text with a speech-to-text program installed on this machine (whisper.cpp, or an openai-whisper-compatible CLI such as mlx-whisper), stores the text, andtg messagesshows it in each item'stranscript. This is the local-model part of #102. Refs #102The need: an agent reading a chat skips every voice note and video note. One real chat had about 400 of them, 170 minutes of audio. What worked there was a hand-written pipeline: download each file, convert it with ffmpeg, run a local Whisper model. This PR is that pipeline as one command.
Before
After (real output from the e2e fakes: message 1 is already stored, 3 is a photo, 4 is silent)
tg messages getthen shows the stored text on voice and video notes, andtranscript: nullon every other item:A setup dead end says what to run. Real output of the real
whisper-cliwith no model set (home directory shortened to~):suggestionPATHTRANSCRIBER_NOT_FOUND(new code, exit 1)Install whisper.cpp: brew install whisper-cpp ffmpeg, thenthe download and config commands above; on Apple Silicon alsouv tool install mlx-whisper; on Windowsuv tool install whisper-ctranslate2TRANSCRIBER_NOT_FOUNDbrew install ffmpegtranscribe.modelnot setINVALID_ARGStg config set transcribe.model …transcribe.modelnames a missing fileINVALID_ARGSGENERAL_ERRORfor that messagedetailshas its exit code and the end of its stderrThe issue's three questions
Telegram's own transcription can't cover a chat. A Premium account transcribed one message through
messages.transcribeAudio, then got a flood wait of about 1,950 s. So it is not in this PR; it can come later as an explicit per-message source.Size and speed of a local model, Russian and English. Nine made-up clips, 295 s of English and Russian speech, on an M4 Pro, all with large-v3-turbo:
ggml-large-v3-turbo-q5_0, 574 MB)Each program differed from the script by 0 to 7 words per clip, mostly number formatting ("десять" and "10"). All three answer digital silence with "Thank you.", and
no_speech_probdoesn't flag it, so tg stores audio whose peak is below -60 dB as empty text without running the program.Where the audio goes. The file is downloaded from Telegram into the account's media cache, as
tg media downloaddoes, converted by ffmpeg in a temp directory that is removed afterwards, and given to the program on this machine. Nothing leaves the machine. The Python programs download their model on first use; tg never downloads a model.docs/media.mdsays this.How it works
transcribe.command, or the first ofwhisper-cli,mlx_whisper,whisper-ctranslate2andwhisperonPATH. whisper.cpp comes first: it is one native program for macOS, Linux and Windows and within about 25% of the fastest here. mlx-whisper is the faster option on Apple Silicon.tg media download's code path, unchanged: cache first, resume, content protection refused. Read-only mode allows the command andallowedChatsapplies, as formedia download.message_transcriptstable, keyed by chat and message. A second run, or the same file in another message, is answered from it withcached: true;--forcetranscribes again.--idorder, and exit 1 when any failed, as feat(media): download several messages in one run, with name templates #181 does for downloads.transcribe.command,transcribe.modelandtranscribe.language, on a new string value type in the config module. feat(media): download several messages in one run, with name templates #181 left itsconfig.jsondefaults out because that type was missing; it can use this one.Decisions you may want to change:
~/.cache/whisper-cli/(under$XDG_CACHE_HOMEwhen that is set), not tg's data directory: other programs that run whisper.cpp can use the same file.large-v3-turbotowhisperandwhisper-ctranslate2, whose own defaults areturboandsmall.runner,modelandlanguageas null.transcriptis on every message item, null unless a voice or video note has a stored transcript. Only those rows query the table.modelis the model file's name, not its path, so output holds no home directory.Left out of #102, on purpose:
messages.transcribeAudioand an external API as sources.messages_cacheand needs its own change.--type,--since,--untiland--limit: feat(messages): filter messages list by --type, --since and --until #180 adds the first three totg messages list, and this command should reuse them once that lands. Until then any command that prints IDs can feed it.src/__integration__/: not added. I checked live by hand (below).One edit to a shared test helper:
src/__e2e__/helpers/cli.tsstarts the CLI withprocess.execPathinstead ofbun. The transcribe tests give the CLI aPATHthat holds only the fakes, so Bun has to be named by path; otherwise Homebrew'sbin, with a real ffmpeg and Whisper, would come along.This touches
src/commands/messages/helpers.ts,src/types/index.tsandsrc/utils/output.ts, as #176, #177 and #178 did;mainis merged in, see the update below.Rework after the design comment (69349cd..d386ff1)
The local path now sits behind one provider protocol, and the four regressions from the comment are fixed with tests. Where this section and the sections above disagree, this one is current.
src/commands/media/transcription-provider.ts). A provider declares, before anything runs: where the audio or message reference goes (sendsTo,nullfor this machine), whether a request can cost money, its input (the message itself, or audio as the original file or 16 kHz WAV), batch size, concurrency and maximum duration. It returns text, language and model, or a failure markedrejected,retry_lateroroutcome_unknown(never retried, nothing stored).transcription-pipeline.ts) for every provider: eligibility (the same check astg media download, before any reuse), reuse keyed to the file the message holds now, setup, limits, audio only if the provider reads audio and only in the format it takes, the provider, a second eligibility check before each save, temp cleanup.local-provider.ts): the same programs, config keys, output and stored columns as before. No schema change; existing rows stay valid.tg messageshides the stale transcript; SIGTERM and SIGINT stop ffmpeg or the program, remove the temporary audio and exit 130; a missing program fails only the messages that need it, ready results are printed; content protection is checked before a stored transcript is returned.--forcein 4.5 s with the same result; a photo refused;tg messages getshows the transcript; no temporary files left.bun run checkclean (Knip included),bun run test2058 pass,bun run test:e2e477 pass, 0 fail.Update:
mainmerged in (5443e73)mainmoved to oxfmt and oxlint with the landmines rules, and moved every test beside its code. This branch follows: the same behaviour and output, the code restyled, prose comments and explicit return types removed.main's layout:src/test/media-transcribe.e2e.test.ts, andlocal-provider.test.tsandtranscription-pipeline.test.tsinsrc/commands/media/.download-media.ts(both rework the online check); whichever lands second gets the fold-in from me.bun run checkclean (format, lint, types, Knip),bun run test1217 pass,bun run test:e2e359 pass, 0 fail. Totals are lower than before becausemainmerged and removed many tests.How I checked it
E2E with a fake ffmpeg and one fake program per output shape (15 tests): one voice note stored and shown by
tg messages get; several IDs with the program started once; mlx_whisper once per file; whisper.cpp with a model file and-l auto; silent audio stored empty with no program call; a stored transcript reused, by message and by file, and--force; a content-protected message refused exactly astg media downloadrefuses it; each setup error with its suggestion; the converted audio removed from the temp directory when the whole run fails.Unit tests for both JSON parsers on real output of whisper.cpp 1.9.5 and mlx-whisper 0.4.3, for detection, and for the suggestion on macOS, Linux and Windows.
Real programs on an M4 Pro, from the media cache of a scratch data directory with made-up clips: whisper.cpp, mlx-whisper and openai-whisper each transcribed an English voice note, a Russian voice note and an English video note correctly, and stored the silent clip as empty.
Live, on a personal account with whisper.cpp: a voice note and a video note in Saved Messages, neither in the media cache, transcribed in one command in 8 s including the two downloads; the same command again answered both with
cached: true;tg messages getshowed thetranscript.Not verified: whisper-ctranslate2 and Windows (flags checked in its source), Linux, and Homebrew's whisper.cpp on Linux.
bun run check: clean.bun run test: 2315 pass, 0 fail.bun run test:e2e: 448 pass, 0 fail. Two tests incommands.e2e.test.tsthat try the network ("should try to fetch from API…") hit their 5 s timeout in some runs on this machine; they do the same onmain(1 of 8 runs) and this PR doesn't touch them.Tests pass locally and use made-up data only
README, docs and affected demos follow the product content standard (
docs/media.md,docs/cli-commands.md,docs/configuration.md,docs/database-schema.md,docs/api-design.md, README, CHANGELOG)Title follows the repo's commit style: Conventional Commits (
feat: …,fix: …) unlessAGENTS.mdsays otherwiseUpdate: second code review (5c91284)
A second, independent review of this branch. Each point below was first shown by a failing test, then fixed.
SIGHUPis handled likeSIGINTandSIGTERM, and the temp directory is removed on every exit, a second interrupt included.rejectedresult is never retryable (a network error kept its own flag);retry_lateralways is.outcome_unknownis unchanged:details.outcome: "unknown", not retryable, nothing stored.After these commits:
bun run checkclean,bun run test1219 pass,bun run test:e2e362 pass, 0 fail.Update:
mainmerged in (649eef9)mainup to #220 merged in, no conflicts and no changes to this branch's code.After the merge:
bun run checkclean,bun run test1230 pass,bun run test:e2e363 pass, 0 fail.Update:
mainmerged in (853a651)mainup to 0.15.1 and #232 merged in. Conflicts:CHANGELOG.md(the entry of this PR now sits under the new## [Unreleased]) andsrc/commands/media/download-media.ts.getClientForAccount()is async since #226, sotg media transcribeandcheckedAttachmentawait the client. No behaviour change. The follow-up of 19 November (protected content in the message reader) is not in this merge.After the merge:
bun run checkclean,bun run test1242 pass,bun run test:e2e389 pass, 0 fail.Update: stored transcripts of protected content (5252139)
The message reader applies the offline protection check that
tg media transcribeandtg media downloadmake, from one function (cachedProtectioninsrc/commands/media/protection.ts). Once the cache knows a message or its chat is protected, everytg messagesitem hastranscript: nullfor it; the stored row stays. The e2e cases cover a message and a chat that become protected after they were transcribed, on both paths:tg media transcriberefuses,tg messages getandlistshow no transcript. Both failed on the reader before the change.bun run checkclean,bun run test1242 pass,bun run test:e2e390 pass, 0 fail.Update:
mainmerged in (ac85803)mainup to 0.15.2 (#234) merged in. One conflict:CHANGELOG.md(the entry of this PR stays under## [Unreleased], above the new 0.15.2 section). No code change in this PR. The Windows download fix of #234 insrc/commands/media/download-media.tsmerged without a conflict.After the merge:
bun run checkclean,bun run test1242 pass,bun run test:e2e390 pass, 0 fail.🤖 Generated with Claude Code