# Teaching a file converter to listen and to read

> Source: <https://dev.to/freerave/teaching-a-file-converter-to-listen-and-to-read-2mb3>
> Published: 2026-11-28 11:11:00+00:00

**Recommendation:** 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.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

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.

It 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.

OpenAI'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.

[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:

```
WHISPER = Requirement("whisper-cli", {"apt": "whisper.cpp-tools", "dnf": "whisper-cpp",
                                      "pacman": "whisper.cpp", "zypper": "whisper-cpp"},
                      "speech to text")
TARGETS = {"txt", "srt", "vtt", "copy-text"}

class WhisperBackend(Backend):
    name = "whisper"
    requirements = (WHISPER, FFMPEG, MODEL)
```

Three 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.

The 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.

```
sudo apt install whisper.cpp-tools
dotmorph whisper --download          # base, 142 MB
dotmorph whisper --download small    # or tiny, medium, large-v3-turbo
dotmorph whisper --list              # what's installed, and where
```

This 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.

Finding the model is a small function with an order that matters:

``` php
def find_model() -> Path | None:
    """$DOTMORPH_WHISPER_MODEL, else the default model, else the best one installed."""
    env = os.environ.get("DOTMORPH_WHISPER_MODEL")
    if env:
        return Path(env) if Path(env).is_file() else None
    models = installed_models()
    return models.get(DEFAULT_MODEL) or next(iter(models.values()), None)
```

The 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.

whisper.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:

```
code, err = run_tool(
    [ffmpeg, "-nostdin", "-hide_banner", "-y", "-i", str(src),
     "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(wav)],
    ctx, timeout=opts.timeout,
)
...
code, err = run_tool(
    [exe, "-m", str(model), "-f", str(wav), "-l", spoken(opts.language),
     OUTPUT_FLAG[job.action], "-of", str(tmpdir / "out"), "-pp", "-t", threads],
    ctx, timeout=opts.timeout, on_err_line=progress,
)
```

Because 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.

Everything 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.

The 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.

`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:

```
for chunk in proc.stderr:
    err_chunks.append(chunk)
    if on_err_line:
        on_err_line(chunk.rstrip("\n"))
```

and the backend turns those lines into the arc, keeping the first 5% for the ffmpeg step:

``` php
_PROGRESS = re.compile(r"progress\s*=\s*(\d+)%")

def progress(line: str) -> None:
    if m := _PROGRESS.search(line):
        ctx.progress(0.05 + 0.9 * int(m.group(1)) / 100)
```

Cancel works the same as for a video encode: the whole process group is killed, the temp folder disappears, nothing is left behind.

To 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`:

```
espeak -v en-us -s 150 -w memo-en.wav "Meeting notes. We ship version two point two on Friday. \
  Kareem writes the release notes, and the tests must pass on Python three ten."
dotmorph convert memo-en.wav --to srt
php
1
00:00:00,000 --> 00:00:06,720
 meeting notes. We ship version 2.2 on Friday. Karim writes the release notes, and the

2
00:00:06,720 --> 00:00:09,200
 test must pass on Python 310.
```

That'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.

The 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:

``` php
def _copy_commands() -> list[list[str]]:
    cmds = []
    if os.environ.get("WAYLAND_DISPLAY") and shutil.which("wl-copy"):
        cmds.append(["wl-copy", "--type", "text/plain;charset=utf-8"])
    if os.environ.get("DISPLAY"):
        if shutil.which("xclip"):
            cmds.append(["xclip", "-selection", "clipboard", "-in"])
        if shutil.which("xsel"):
            cmds.append(["xsel", "--clipboard", "--input"])
    return cmds
```

One 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.

It 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.

Once "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:

That invoice is a synthetic scan I generated: slightly rotated, blurred, with paper speckle. Tesseract read every line correctly.

Scanned **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:

```
pages = self._pages(src, tmpdir, job)       # pdftoppm -r 300 -gray: one PNG per page
for i, page in enumerate(pages):
    self._tesseract(page, tmpdir / f"ocr-{i:04d}", lang, "pdf", job)   # page -> PDF + text
# then Ghostscript merges the per-page PDFs back into one
```

On the same invoice saved as a PDF, `pdftotext` found exactly 1 character before (a form feed) and all of the text after.

Tesseract 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:

```
no OCR language pack for ara: install tesseract-ocr-ara
```

`--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.

CI 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.

OCR 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.

Listening 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*.

DotMorph 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.
