{"slug": "teaching-a-file-converter-to-listen-and-to-read", "title": "Teaching a file converter to listen and to read", "summary": "A developer added local speech-to-text and OCR-style transcription to DotMorph, an open-source Linux file converter, using whisper.cpp's whisper-cli binary instead of the PyTorch-based Python package to avoid gigabytes of dependencies. The transcription backend is registered like any other converter, requires whisper-cli, ffmpeg and a ggml model file, and defaults to the 142 MB base model; missing requirements simply hide TXT, SRT and VTT targets and are reported by dotmorph doctor. Audio is converted to 16 kHz mono PCM via ffmpeg before transcription, and models are downloaded only on explicit command, verified against server length, and stored locally so nothing leaves the machine.", "body_md": "A few weeks after [part 1](https://dev.to/freerave/i-built-a-radial-menu-that-converts-any-file-on-linux-4c4m) went out, someone opened an issue on DotMorph asking for one thing: drag an audio file onto the wheel and get its text back, as a file or straight to the clipboard.\n\nIt was a good request, and it changed how I thought about the app. Until then DotMorph converted *formats*: PNG to WebP, MOV to MP4. A transcript isn't another format of the same audio. It's what the audio *says*. The same goes for a screenshot of an error message, or a scanned invoice. So 2.2 teaches DotMorph to listen and to read, without breaking the rule that nothing leaves your machine.\n\nOpenAI's Whisper is the obvious model. The obvious way to run it is the Python package, which pulls in PyTorch: gigabytes of dependencies for one feature of a file converter. That was never going to ship in a .deb.\n\n[whisper.cpp](https://github.com/ggml-org/whisper.cpp) runs the same models in plain C++ on the CPU, and it's already packaged: `whisper.cpp-tools` on Debian and Kali, `whisper-cpp` on Fedora, `whisper.cpp` on Arch. It gives you a `whisper-cli` binary, and DotMorph is built around exactly that kind of tool. In [part 2](https://dev.to/freerave/8-backends-one-engine-and-the-svg-bug-that-started-it-all-3ooo) I described how every converter is a backend that declares what it needs, and the registry only offers what's installed. Transcription is just one more backend:\n\n```\nWHISPER = Requirement(\"whisper-cli\", {\"apt\": \"whisper.cpp-tools\", \"dnf\": \"whisper-cpp\",\n                                      \"pacman\": \"whisper.cpp\", \"zypper\": \"whisper-cpp\"},\n                      \"speech to text\")\nTARGETS = {\"txt\", \"srt\", \"vtt\", \"copy-text\"}\n\nclass WhisperBackend(Backend):\n    name = \"whisper\"\n    requirements = (WHISPER, FFMPEG, MODEL)\n```\n\nThree requirements: the binary, ffmpeg (more on that below), and a model file. If any of them is missing, TXT, SRT and VTT simply don't appear for audio files, and `dotmorph doctor` says what to install. No error dialogs, no half-working menu entries.\n\nThe binary is small, but it needs a model: a `ggml-*.bin` file from the whisper.cpp project. They range from 75 MB (`tiny`) to 1.6 GB (` large-v3-turbo`). DotMorph defaults to `base`, 142 MB, which handles clear speech in most languages and runs fine on a laptop CPU.\n\n```\nsudo apt install whisper.cpp-tools\ndotmorph whisper --download          # base, 142 MB\ndotmorph whisper --download small    # or tiny, medium, large-v3-turbo\ndotmorph whisper --list              # what's installed, and where\n```\n\nThis is the only time DotMorph goes online, and only because you typed that command. Models go to `~/.local/share/dotmorph/whisper/`, are downloaded to a `.part` file first and checked against the server's length before being renamed, so a dropped connection never leaves a broken model behind.\n\nFinding the model is a small function with an order that matters:\n\n``` php\ndef find_model() -> Path | None:\n    \"\"\"$DOTMORPH_WHISPER_MODEL, else the default model, else the best one installed.\"\"\"\n    env = os.environ.get(\"DOTMORPH_WHISPER_MODEL\")\n    if env:\n        return Path(env) if Path(env).is_file() else None\n    models = installed_models()\n    return models.get(DEFAULT_MODEL) or next(iter(models.values()), None)\n```\n\nThe model check is itself a `Requirement` subclass whose `present()` calls `find_model()`, and whose install hint is `dotmorph whisper --download`. So the doctor, the wheel and the CLI all agree on one answer.\n\nwhisper.cpp wants 16 kHz mono PCM. Your files are MP3s, Opus voice notes from your phone, MKV screen recordings. So the backend runs ffmpeg first, then whisper-cli:\n\n```\ncode, err = run_tool(\n    [ffmpeg, \"-nostdin\", \"-hide_banner\", \"-y\", \"-i\", str(src),\n     \"-vn\", \"-ac\", \"1\", \"-ar\", \"16000\", \"-c:a\", \"pcm_s16le\", str(wav)],\n    ctx, timeout=opts.timeout,\n)\n...\ncode, err = run_tool(\n    [exe, \"-m\", str(model), \"-f\", str(wav), \"-l\", spoken(opts.language),\n     OUTPUT_FLAG[job.action], \"-of\", str(tmpdir / \"out\"), \"-pp\", \"-t\", threads],\n    ctx, timeout=opts.timeout, on_err_line=progress,\n)\n```\n\nBecause the audio goes through ffmpeg anyway, video works for free: any MP4 or MKV becomes SRT subtitles. `-l auto` lets Whisper detect the language; `--lang ar` on the command line pins it.\n\nEverything runs inside the same `workdir()` + `finalize()` pattern as every other backend: whisper writes into a private temp folder, and only a finished file is moved next to your original, under a name that never overwrites anything.\n\nThe wheel has a progress arc, and a long recording can take minutes. whisper.cpp has a `-pp` flag that prints lines like `progress = 37%`, but on **stderr**, while ffmpeg's `-progress` output (which the rest of DotMorph already parsed) is on stdout.\n\n`run_tool()`, the one function every backend uses to run a tool (process group, cancel, timeout), already pumped stderr in a thread to keep its last lines for error messages. It got one new hook:\n\n```\nfor chunk in proc.stderr:\n    err_chunks.append(chunk)\n    if on_err_line:\n        on_err_line(chunk.rstrip(\"\\n\"))\n```\n\nand the backend turns those lines into the arc, keeping the first 5% for the ffmpeg step:\n\n``` php\n_PROGRESS = re.compile(r\"progress\\s*=\\s*(\\d+)%\")\n\ndef progress(line: str) -> None:\n    if m := _PROGRESS.search(line):\n        ctx.progress(0.05 + 0.9 * int(m.group(1)) / 100)\n```\n\nCancel works the same as for a video encode: the whole process group is killed, the temp folder disappears, nothing is left behind.\n\nTo have something I can show without anyone's voice, I made a 9-second clip with `espeak` and ran it through DotMorph with the smallest model, `tiny`:\n\n```\nespeak -v en-us -s 150 -w memo-en.wav \"Meeting notes. We ship version two point two on Friday. \\\n  Kareem writes the release notes, and the tests must pass on Python three ten.\"\ndotmorph convert memo-en.wav --to srt\nphp\n1\n00:00:00,000 --> 00:00:06,720\n meeting notes. We ship version 2.2 on Friday. Karim writes the release notes, and the\n\n2\n00:00:06,720 --> 00:00:09,200\n test must pass on Python 310.\n```\n\nThat's unedited. Notice what it got right: \"two point two\" became `2.2`, the punctuation is there, the timestamps split at a sensible point. And what it didn't: my name became Karim, \"tests\" lost its s, and \"Python three ten\" became `310`. That's the tiny model on a robotic voice. `base` and `small` do noticeably better on real speech, which is why `base` is the default.\n\nThe issue asked for \"copy/paste of the transcribed file\", and that's the most useful form: you record a voice note, right-click it, and the text is in your clipboard. **Copy text** is a tool in the wheel:\n\n``` php\ndef _copy_commands() -> list[list[str]]:\n    cmds = []\n    if os.environ.get(\"WAYLAND_DISPLAY\") and shutil.which(\"wl-copy\"):\n        cmds.append([\"wl-copy\", \"--type\", \"text/plain;charset=utf-8\"])\n    if os.environ.get(\"DISPLAY\"):\n        if shutil.which(\"xclip\"):\n            cmds.append([\"xclip\", \"-selection\", \"clipboard\", \"-in\"])\n        if shutil.which(\"xsel\"):\n            cmds.append([\"xsel\", \"--clipboard\", \"--input\"])\n    return cmds\n```\n\nOne subtlety: on Linux the clipboard isn't a buffer you write into. The program that copied the text has to *stay alive* and hand it out when someone pastes. `wl-copy` and `xclip` fork into the background to do that. If one of them doesn't, `communicate()` times out while it's busy serving the selection, which is exactly what success looks like, so a timeout counts as copied.\n\nIt also keeps a `.txt` next to the file. A transcript can take minutes to compute; a clipboard is gone the next time you copy something.\n\nOnce \"the text of this file\" existed for audio, it was a small step to images. [Tesseract](https://github.com/tesseract-ocr/tesseract) is the OCR engine every distro ships, so OCR became another backend with the same three outputs:\n\nThat invoice is a synthetic scan I generated: slightly rotated, blurred, with paper speckle. Tesseract read every line correctly.\n\nScanned **PDFs** are harder, because Tesseract reads images, not PDFs. If [ocrmypdf](https://github.com/ocrmypdf/OCRmyPDF) is installed, DotMorph hands the whole job to it: it keeps the original images, skips pages that already have text and does a better job overall. Without it, DotMorph does the same thing in three steps:\n\n```\npages = self._pages(src, tmpdir, job)       # pdftoppm -r 300 -gray: one PNG per page\nfor i, page in enumerate(pages):\n    self._tesseract(page, tmpdir / f\"ocr-{i:04d}\", lang, \"pdf\", job)   # page -> PDF + text\n# then Ghostscript merges the per-page PDFs back into one\n```\n\nOn the same invoice saved as a PDF, `pdftotext` found exactly 1 character before (a form feed) and all of the text after.\n\nTesseract needs a language pack per language, and guessing wrong gives garbage. DotMorph reads English plus your interface language, if its pack is installed; an Arabic desktop gets `eng+ara`. Ask for a language whose pack is missing and the error names the exact package, so the fix is one command:\n\n```\nno OCR language pack for ara: install tesseract-ocr-ara\n```\n\n`--lang` takes the same ISO codes as everywhere else in DotMorph (`ar`, `de`, `pt-BR`), mapped to Tesseract's own names (` ara`, `deu`, `por`). Getting that mapping right for `pt-BR` and `ar+en` was one of the things a review of this release caught before it shipped.\n\nCI can't download a speech model on every run, and the tests must not depend on how well a model hears. So the whisper tests use a **fake `whisper-cli`**: a tiny Python script that checks its arguments, prints `progress = N%` lines on stderr and writes a known transcript. That tests everything DotMorph is responsible for (the ffmpeg step, the flags, `--lang`, progress, SRT and VTT, the clipboard, the safe file names) in milliseconds.\n\nOCR is different: Tesseract is small and in every distro, so CI installs it and the tests run the real thing on images drawn with Pillow, including a two-page scanned PDF that must come out searchable.\n\nListening and reading were about what a file *says*. **Part 6** is about a much older question: why won't Discord take my video? It's about \"Fit under 10 MB\", where the interesting part turned out to be the math: a binary search on JPEG quality, the bitrate a video's length allows, and a Ghostscript setting that made PDFs *bigger*.\n\nDotMorph is free and open source: [github.com/kareem2099/DotMorph](https://github.com/kareem2099/DotMorph). Version 2.2 is on PyPI, as an AppImage, a .deb and on Arch.", "url": "https://wpnews.pro/news/teaching-a-file-converter-to-listen-and-to-read", "canonical_source": "https://dev.to/freerave/teaching-a-file-converter-to-listen-and-to-read-2mb3", "published_at": "2026-11-28 11:11:00+00:00", "updated_at": "2026-11-28 11:13:45.756336+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "artificial-intelligence"], "entities": ["DotMorph", "whisper.cpp", "OpenAI", "Whisper", "ffmpeg", "PyTorch", "Debian", "Fedora"], "also_reported_by": [], "takeaway": "Running Whisper via whisper.cpp's whisper-cli with a 142 MB base ggml model avoids PyTorch's multi-gigabyte dependency chain, and ffmpeg must first resample audio to 16 kHz mono PCM for whisper.cpp.", "recommendation": {"advice": "Use whisper.cpp's packaged whisper-cli with the base ggml model instead of the PyTorch Whisper package, and always resample input to 16 kHz mono PCM with ffmpeg before transcribing.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/teaching-a-file-converter-to-listen-and-to-read", "markdown": "https://wpnews.pro/news/teaching-a-file-converter-to-listen-and-to-read.md", "text": "https://wpnews.pro/news/teaching-a-file-converter-to-listen-and-to-read.txt", "jsonld": "https://wpnews.pro/news/teaching-a-file-converter-to-listen-and-to-read.jsonld"}}