<!--
  canonical-url: https://www.avonture.be/blog/ollama-ai-docs
  published:     2026-09-21
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# ai-translate & ai-summarize: Confidential Documents, Handled 100% Locally

> Two zsh functions that translate or summarize a Word, PDF, PowerPoint or Excel document without a single byte leaving your machine — Docling extracts the text locally, a local Ollama model does the translation or summary. Built for the document you'd never paste into a cloud translation tool.

---
![ai-translate & ai-summarize: Confidential Documents, Handled 100% Locally](/img/v2/ai_doc.webp)

**TL;DR**

This article adds `ai-translate` and `ai-summarize` to the "Ollama daily use" series. Both accept a `.pdf`, `.docx`, `.pptx`, `.xlsx` or `.html` file — extracted to Markdown by [Docling](/blog/docling) — or a plain `.md`/`.txt` file directly, then hand the text to the local Ollama model to translate or condense into bullet points. The entire round trip stays on your machine: no cloud translation API, no document upload anywhere, which is precisely the point for a contract, an HR document, or anything else you'd think twice about pasting into Google Translate.

I work in an office where a `.docx` lands in my inbox in Dutch, English or French. For a lot of good reasons, I sometimes need to translate from one language to another.

When it's not confidential at all, a reflex everyone has is to open the browser, paste into a translation tool, hope nobody minds that a client contract just passed through a third party's servers. Nobody ever explicitly told me not to. That's exactly the kind of thing you should not need permission to avoid.

## Demo — ai-translate

Translation of a contract from any language to French:

```bash
$ ai-translate contract.docx French

→ Converting 'contract.docx' with docling-convert...

## Note de livraison trimestrielle

*Périmètre, jalons et résiliation — diffusion interne uniquement*

### Article 1

À la suite de la revue trimestrielle tenue le 3 septembre, la présente note consacre le périmètre convenu, les jalons de livraison ainsi que les conditions de résiliation applicables à l'une ou l'autre des parties. Elle se substitue au projet diffusé en juillet. En cas de conflit entre une disposition des présentes et l'accord-cadre, c'est l'accord-cadre qui prévaut, sauf pour l'échéancier de paiement défini à l'article trois, qui est conçu pour le remplacer intégralement.

### Article 2

Le prestataire livrera la première tranche dans un délai de six semaines à compter de la signature, et chaque tranche subséquente à des intervalles n'excédant pas quatre semaines. Une tranche est réputée livrée dès qu'elle a été déployée dans l'environnement de staging et que les tests de réception consignés dans l'annexe B ont été validés. La livraison hors heures ouvrables ne réduit pas le délai de vérification, qui court pendant cinq jours ouvrables à compter de l'avis de livraison.

### Article 3

Les factures sont payables trente jours après réception. Le client peut retenir le paiement d'une tranche ayant échoué aux tests de réception, mais uniquement pour cette tranche et seulement jusqu'à la régularisation du défaut. Les intérêts de retard courent au taux légal. Aucune des parties ne peut compenser les sommes dues au titre des présentes avec celles dues au titre de tout autre accord sans le consentement écrit de l'autre partie.

### Article 4

Toute partie peut résilier le contrat sur préavis écrit de soixante jours. En cas de résiliation, le prestataire devra remettre tout avancement, y compris le code source, la configuration de build et la documentation, sous une forme permettant à un tiers compétent de poursuivre le travail. Le client devra payer les travaux achevés et acceptés jusqu'à la date de résiliation.

| Tranche   | Échéance   | Statut      |
| ------ | --- | --- |
| Première  | 6 semaines | Livrée      |
| Deuxième  | 10 semaines| En cours    |
```

And the same to Dutch:

```bash
$ ai-translate contract.docx Dutch

→ Converting 'contract.docx' with docling-convert...

## Kwartaal Leveringsnota

*Reikwijdte, mijlpalen en beëindiging — uitsluitend voor intern gebruik*

### Artikel 1

Naar aanleiding van het kwartaaloverleg van 3 september houdt deze nota de overeengekomen reikwijdte, de leveringsmijlpalen en de voorwaarden vast onder welke elke partij kan opzeggen. Deze nota vervangt de in juli verspreide conceptversie. Indien een bepaling in deze nota strijdig is met de raamovereenkomst, heeft de raamovereenkomst voorrang, met uitzondering van de in afdeling drie genoemde betalingsregeling, die geheel ter vervanging daarvan is bedoeld.

### Artikel 2

De leverancier levert de eerste levering binnen zes weken na ondertekening, en elke daaropvolgende levering in intervallen van maximaal vier weken. Een levering wordt geacht geleverd te zijn wanneer deze is geïmplementeerd in de staging-omgeving en de acceptatietests in appendix B zijn geslaagd. Levering buiten werkuren verkort het acceptatievenster niet, dat vijf werkdagen duurt te rekenen vanaf de kennisgeving van levering.

### Artikel 3

Facturen zijn betaalbaar binnen dertig dagen na ontvangst. De opdrachtgever mag de betaling voor een levering die niet is geaccepteerd, inhouden, maar uitsluitend voor die specifieke levering en alleen totdat het gebrek is verholpen. Rentevergoeding bij late betaling loopt tegen het wettelijk rentepercentage. Geen van beide partijen mag vorderingen uit deze nota verrekenen met vorderingen uit enige andere overeenkomst zonder schriftelijke toestemming van de andere partij.

### Artikel 4

Elke partij kan opzeggen met een opzegtermijn van zestig dagen schriftelijk. Bij beëindiging draagt de leverancier alle werk in uitvoering, inclusief broncode, buildconfiguratie en documentatie, over in een vorm die door een kundige derde kan worden voortgezet. De opdrachtgever betaalt voor het tot de datum van beëindiging voltooide en geaccepteerde werk.

| Levering    | Te leveren | Status      |
| ------ | --- | --- |
| Eerste      | 6 weken  | Geleverd   |
| Tweede      | 10 weken | In uitvoering |
```

That's a fictional service agreement, converted from `.docx` and translated into French/Dutch, with every heading and every bold term intact — the kind of document I would genuinely not paste into a browser-based translator.

Same document, so you can try it yourself before adapting either function to your own files:

contract.docx — the source document: `./files/contract.docx`

## Demo — ai-summarize

The same contract, condensed to four bullet points instead of translated:

```bash
$ ai-summarize contract.docx 4

→ Converting 'contract.docx' with docling-convert...

- First increment delivery due within 6 weeks of signature; subsequent increments delivered every ≤4 weeks, requiring staging deployment and Appendix B test completion within a 5-working-day acceptance window.
- Invoices payable 30 days from receipt; payment withholding permitted only for failed increments until remedied, with late interest accruing at the statutory rate.
- Either party may terminate with 60 days written notice, mandating handover of all work-in-progress, source code, and documentation, plus immediate payment for completed and accepted work.
- Framework agreement prevails except for the payment schedule, which is entirely replaced; first increment is delivered, second increment is due at 10 weeks.
```

Delivery deadlines, payment terms, the termination clause and which parts of the framework agreement get overridden — the four points that matter, pulled out without reading the full document.

## Reusing Docling for Extraction

Both functions below share one job before they ever talk to Ollama: turning a document into plain text. I already built that piece in [my Docling article](/blog/docling) — `docling-convert file.docx` produces `file.md` locally, GPU-accelerated if you set it up that way. Rather than duplicate that logic twice, it lives in one small helper:

No need to copy anything yet: the `.zsh` files shown in this article are here to be read, and [Installing It](#installing-it) at the end creates every one of them in `~/.zsh/fns/` for you.

**\~/.zsh/fns/\_ai-docs.zsh**

```bash
# Shared document-to-text extraction for ai-translate and ai-summarize.
# .pdf/.docx/.pptx/.xlsx/.html go through docling-convert (see /blog/docling)
# first; .md/.markdown/.txt files are read directly, no conversion needed.
#
# Leading underscore: loads after _ollama.zsh (still alphabetically before
# ai-summarize.zsh and ai-translate.zsh), so _ollama_query is always ready.

_ai_extract_text() {
  local file="$1"
  local ext="${file:e:l}"

  case "$ext" in
    md|markdown|txt)
      cat "$file"
      ;;
    pdf|docx|pptx|xlsx|html|htm)
      if ! command -v docling-convert >/dev/null 2>&1; then
        echo "_ai_extract_text: docling-convert not found — see /blog/docling to set it up" >&2
        return 1
      fi
      local dir filename base mdfile
      dir="${file:h}"
      filename="${file:t}"
      base="${filename%.*}"
      mdfile="${dir}/${base}.md"
      echo "→ Converting '$file' with docling-convert..." >&2
      ( cd "$dir" && docling-convert "$filename" >/dev/null 2>&1 ) || {
        echo "_ai_extract_text: docling-convert failed on '$file'" >&2
        return 1
      }
      cat "$mdfile"
      ;;
    *)
      echo "_ai_extract_text: unsupported extension .$ext (expected pdf/docx/pptx/xlsx/html/md/txt)" >&2
      return 1
      ;;
  esac
}
```

> **Markdown and text files skip conversion entirely:**
>
> If you already have a `.md` or `.txt` file, `_ai_extract_text` just `cat`s it — no Docling call, no dependency. The conversion step only kicks in for actual office formats.

> **Why the subshell around docling-convert:**
>
> `docling-convert` (from the previous article) mounts the *current directory* into its container and expects a filename relative to it — it wasn't built to resolve an arbitrary absolute path. `( cd "$dir" && docling-convert "$filename" )` runs it from the document's own folder, in a subshell, so your actual working directory is untouched when the function returns.

## ai-translate

**\~/.zsh/fns/ai-translate.zsh**

```bash
# ai-translate <file> [language] — translate a document into the given
# language (default: French), entirely locally. Accepts .pdf/.docx/.pptx/
# .xlsx/.html (via docling-convert) or plain .md/.txt files directly.

AI_COMMANDS[translate]="ai-translate <file> [language]  — translate a document locally (default: French)"

ai-translate() {
  local file="$1"
  local lang="${2:-French}"

  if [[ -z "$file" || ! -f "$file" ]]; then
    echo "Usage: ai-translate <file> [target-language]" >&2
    return 1
  fi

  local text
  text=$(_ai_extract_text "$file") || return 1

  local prompt="Translate the following document into $lang. Preserve the Markdown structure exactly — headings, lists, tables, emphasis. Output only the translated document, no commentary and no notes about the translation.

$text"

  _ollama_query "$prompt"
}
```

Extract, then ask the model to translate into whatever language you pass as the second argument (French by default — the language I need most often), with an explicit instruction to preserve the Markdown structure so headings, lists, and tables survive the round trip instead of collapsing into a wall of text.

## ai-summarize

**\~/.zsh/fns/ai-summarize.zsh**

```bash
# ai-summarize <file> [points] — summarize a document in N bullet points
# (default: 5), entirely locally. Accepts .pdf/.docx/.pptx/.xlsx/.html (via
# docling-convert) or plain .md/.txt files directly.

AI_COMMANDS[summarize]="ai-summarize <file> [points]  — summarize a document locally (default: 5 points)"

ai-summarize() {
  local file="$1"
  local points="${2:-5}"

  if [[ -z "$file" || ! -f "$file" ]]; then
    echo "Usage: ai-summarize <file> [number-of-points]" >&2
    return 1
  fi

  local text
  text=$(_ai_extract_text "$file") || return 1

  local prompt="Summarize the following document in exactly $points bullet points, written in the same language as the document. Prioritize decisions, numbers, deadlines and action items over generic description. Output only the bullet points, nothing else.

$text"

  _ollama_query "$prompt"
}
```

Same extraction step, different prompt: a fixed number of bullet points (5 by default), explicitly told to prioritize decisions, numbers, deadlines and action items over generic description — and to answer in whatever language the source document is already in, rather than silently switching to English.

## Registered in the ai Menu

Two lines — `AI_COMMANDS[translate]=...` and `AI_COMMANDS[summarize]=...` — and both are reachable as `ai translate` / `ai summarize`, or directly as `ai-translate` / `ai-summarize`, alongside every other function in this series.

Both functions call `_ollama_query` and register into `AI_COMMANDS`, which live in the shared `_ollama.zsh` foundation introduced in [ai-test](/blog/ollama-test-generator). If you already followed an earlier article in this series, it's already sitting in `~/.zsh/fns/` and sourced by your autoloader — nothing more to do. Starting here instead? It is one of the files created in [Installing It](#installing-it) below.

> **Docling and Ollama don't have to be on the same machine:**
>
> `docling-convert` always runs locally, no GPU required — converting a document to Markdown works on any laptop. Translating or summarizing still needs an Ollama server reachable somewhere, though: both functions connect to `OLLAMA_HOST`, same setup as [accessing Ollama across your local network](/blog/accessing-ollama-across-your-local-network) — a shared LAN, or a VPN/tunnel across two separate networks.
>
> ```mermaid
> flowchart TD
>     subgraph C["💻 Your computer"]
>         F["📄 .docx / .pdf / …"] --> D["🐳 docling-convert"]
>         D --> T["📝 plain text (.md)"]
>     end
>
>     subgraph S["🧠 Ollama server"]
>         O["Ollama"]
>     end
>
>     T -->|OLLAMA_HOST| O
>     O -->|"translated / summarized,\nback on your computer"| R["✅ result"]
>
>     style D fill:#4a90d9,color:#fff
>     style O fill:#27ae60,color:#fff
> ```

## Key Takeaways

**ai-translate / ai-summarize quick reference**

* **Shared extraction** — `_ai_extract_text` in `_ai-docs.zsh`, reused by both functions

* **Docling for office formats** — `.pdf`/`.docx`/`.pptx`/`.xlsx`/`.html` go through `docling-convert` first

* **Markdown/text skip conversion** — `.md`/`.txt` files are read directly

* **Nothing leaves the machine** — extraction and translation/summary both run locally, end to end

* **Registers into `ai`** — reachable as `ai translate` and `ai summarize`

## Installing It

Everything runs on your machine: zsh, `curl` and `jq` (which builds the request sent to Ollama), and an Ollama server you can reach — see [installing Ollama](/blog/ollama-installation) if you don't have one yet. For `.pdf`, `.docx`, `.pptx`, `.xlsx` and `.html` files, you also need `docling-convert`, from [my Docling article](/blog/docling).

**1. Create the files.** Every function of this series lives in its own file in `~/.zsh/fns/`. The one-liner below creates that folder and the four files in one go — or download the ZIP, or create each file by hand and paste its content. `_ollama.zsh` is the foundation the whole series shares: if an earlier article already gave it to you, the copy here is the same file.

**Project: \~/.zsh/fns**

**\_ollama.zsh**

````bash
# Foundation file for every "ai-*" function in this series. Named with a
# leading underscore: the ~/.zsh/fns/*.zsh loader sources files in
# alphabetical order, and "_" sorts before any letter — so this file is
# always loaded first, no matter how many ai-* functions get added later.
#
# Provides:
#   - _ollama_check       reachability guard for Ollama
#   - _ollama_query       shared HTTP client (curl + jq)
#   - _ai_strip_fences    removes the Markdown fences models add anyway
#   - _ai_bat             resolves "bat" vs Debian's "batcat"
#   - _ai_confirm         yes/no prompt
#   - _git_staged_diff    validated staged-diff fetcher (shared by pre-commit functions)
#   - AI_COMMANDS         registry each ai-* function adds itself to
#   - AI_PARAMS           registry of interactive parameter types (file/language/number/text/none)
#   - _ai_prompt_*        FZF/read helpers for interactive argument collection
#   - ai                  entry-point dispatcher / interactive menu

typeset -gA AI_COMMANDS
typeset -gA AI_PARAMS

# ---------------------------------------------------------------------------
# Ollama helpers
# ---------------------------------------------------------------------------

# _ollama_check — verify that the Ollama daemon is reachable.
# Fails loudly so callers can bail early rather than watching curl hang.
_ollama_check() {
  local host="${OLLAMA_HOST:-http://localhost:11434}"
  if ! curl --silent --max-time 2 "${host}/api/tags" >/dev/null 2>&1; then
    echo "ollama: cannot reach ${host} — is the Ollama container running?" >&2
    return 1
  fi
}

# _ollama_query <prompt> — send a prompt to the local model and print the response.
# Assumes Ollama is reachable; call _ollama_check first if you need an early guard.
_ollama_query() {
  local prompt="$1"
  local model="${OLLAMA_MODEL:-qwen3-coder:30b}"
  local host="${OLLAMA_HOST:-http://localhost:11434}"

  _ollama_check || return 1

  # The prompt is piped into jq rather than passed with "--arg": Linux caps a
  # single argv entry at 128 KB (MAX_ARG_STRLEN), and a large staged diff or a
  # long source file sails straight through that ceiling — jq then dies with
  # "argument list too long". "-R -s" slurps stdin as one raw string, which jq
  # escapes exactly like --arg would.
  print -r -- "$prompt" \
    | jq -Rs --arg model "$model" '{model: $model, prompt: ., stream: false}' \
    | curl --silent "${host}/api/generate" --data-binary @- \
    | jq -r '.response // empty'
}

# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------

# _ai_strip_fences <text> — return only the code, without the Markdown fences.
#
# Every prompt in this series ends with "no markdown fences" and models still
# wrap their answer in ```language … ``` often enough that the output can't be
# piped or pasted as-is. When at least one fence is present, only the fenced
# regions are kept (which also drops the "Here is your test suite:" preamble);
# when there is none, the text is returned untouched.
_ai_strip_fences() {
  local text="$1"

  if [[ "$text" != *'```'* ]]; then
    print -r -- "$text"
    return 0
  fi

  print -r -- "$text" | awk '
    /^[[:space:]]*```/ { inside = !inside; next }
    inside             { print }
  '
}

# _ai_bat — print the name of the "bat" binary installed on this machine, if any.
# Debian and Ubuntu ship the package as "batcat" because the "bat" name was
# already taken by bacula-console-qt, so both spellings have to be probed.
_ai_bat() {
  local candidate
  for candidate in bat batcat; do
    if command -v "$candidate" >/dev/null 2>&1; then
      print -- "$candidate"
      return 0
    fi
  done
  return 1
}

# _ai_relpath <path> — print <path> relative to the current folder when it sits
# below it. Purely cosmetic: it keeps prompts readable instead of asking
# "Save as /home/christophe/projects/…/tests/backup.bats?".
_ai_relpath() {
  local path="${1:A}"
  print -- "${path#${PWD}/}"
}

# _ai_confirm <question> — ask a yes/no question; return 0 only on an explicit yes.
_ai_confirm() {
  local answer
  print -n "${1} [y/N] "
  read -r answer
  [[ "$answer" == [yY]* ]]
}

# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------

# _git_staged_diff <caller> — validate the git context and return the staged diff.
# Handles three early-exit cases (not a repo, nothing staged, oversized diff)
# so every pre-commit function gets them for free without repeating the guards.
#
# Past AI_DIFF_MAX_CHARS the full diff is *not* returned: a diff of several
# hundred kilobytes overflows the model's context window, and the answer that
# comes back is worse than the one you get from a summary. The fallback keeps
# the shape of the change — per-file stat, plus the file and hunk headers,
# which carry the enclosing function names git puts after each "@@" — and
# drops the line-by-line content.
_git_staged_diff() {
  local caller="${1:-ai}"
  local max="${AI_DIFF_MAX_CHARS:-12000}"

  if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    echo "${caller}: not inside a git repository" >&2
    return 1
  fi

  local diff
  diff=$(git diff --staged)

  if [[ -z "$diff" ]]; then
    echo "${caller}: nothing staged — run 'git add' first" >&2
    return 1
  fi

  # "print -r" everywhere below: without it, print expands escape sequences and
  # a literal \n or \t inside the diff would come back mangled.
  if (( ${#diff} <= max )); then
    print -r -- "$diff"
    return 0
  fi

  echo "${caller}: staged diff is large (${#diff} chars) — sending a structural summary instead of the full diff. Commit in smaller chunks for a more precise answer." >&2

  local summary
  summary="$(git diff --staged --stat)

--- FILE AND HUNK HEADERS ONLY (full diff omitted, ${#diff} chars) ---
$(print -r -- "$diff" | grep -E '^(diff --git|new file|deleted file|rename (from|to)|@@)')"

  # Even the summary can exceed the ceiling on a very wide change.
  if (( ${#summary} > max )); then
    summary="${summary[1,$max]}
[…summary truncated…]"
  fi

  print -r -- "$summary"
}

# ---------------------------------------------------------------------------
# Interactive argument helpers (used by the ai() dispatcher)
# ---------------------------------------------------------------------------

# _ai_prompt_file [label] — open an fzf file picker; print the chosen path.
_ai_prompt_file() {
  local label="${1:-Select a file:}"
  local bat_bin preview='cat {}'
  bat_bin=$(_ai_bat) && preview="${bat_bin} --color=always {} 2>/dev/null || cat {}"

  if command -v fd >/dev/null 2>&1; then
    fd --type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  else
    find . -type f | fzf --prompt="${label} " --height=50% --reverse --preview="$preview"
  fi
}

# _ai_prompt_language — open an fzf language picker; print the chosen language.
_ai_prompt_language() {
  printf '%s\n' English French Dutch German Spanish Italian Portuguese Japanese Chinese Korean \
    | fzf --prompt='Target language: ' --height=40% --reverse
}

# _ai_prompt_number [label] — read a positive integer; print it (or nothing on Enter, which
# lets the caller fall back to its own default). Returns 1 only on invalid input.
_ai_prompt_number() {
  local label="${1:-Number (Enter for default):}"
  print -n "${label} "
  local n
  read n
  if [[ -z "$n" ]]; then
    return 0
  fi
  if [[ ! "$n" =~ ^[1-9][0-9]*$ ]]; then
    echo "Expected a positive integer." >&2
    return 1
  fi
  print -- "$n"
}

# _ai_prompt_text [label] — read a free-form string; print it. Returns 1 if empty.
_ai_prompt_text() {
  local label="${1:-Input:}"
  print -n "${label} "
  local t
  read t
  if [[ -z "$t" ]]; then
    echo "No input given." >&2
    return 1
  fi
  print -- "$t"
}

# ---------------------------------------------------------------------------
# Entry-point dispatcher
# ---------------------------------------------------------------------------

# ai              → interactive fzf menu of every registered ai-* command
# ai <cmd> [args] → dispatch straight to ai-<cmd> [args]
#
# When opened via the fzf menu, each command's declared AI_PARAMS type triggers
# a secondary picker before the command runs:
#   file     → fzf file picker (fd + preview if available)
#   language → fzf language list
#   number   → read prompt, empty input uses the command's own default
#   text     → read prompt, required
#   none     → run the command directly (it collects its own input)
# Space-separated values declare multiple parameters in order, e.g. "file language".
ai() {
  local cmd="$1"

  # Direct dispatch: ai <cmd> [args]
  if [[ -n "$cmd" && "$cmd" != "help" && "$cmd" != "list" ]]; then
    if (( ${+AI_COMMANDS[$cmd]} )); then
      shift
      "ai-${cmd}" "$@"
      return
    fi
    echo "ai: unknown command '${cmd}'" >&2
    echo >&2
  fi

  # Interactive menu
  if ! command -v fzf >/dev/null 2>&1; then
    echo "Available ai commands:"
    for key in ${(ok)AI_COMMANDS}; do
      printf "  ai %-10s %s\n" "$key" "$AI_COMMANDS[$key]"
    done
    return
  fi

  local picked
  picked=$(
    for key in ${(ok)AI_COMMANDS}; do
      printf '%s\t%s\n' "$key" "$AI_COMMANDS[$key]"
    done \
      | fzf --delimiter='\t' --with-nth=2 --prompt='ai > ' --height=40% --reverse \
      | cut -f1
  )
  [[ -z "$picked" ]] && return

  # Collect arguments interactively based on AI_PARAMS declaration
  local -a args=()
  local param_type
  for param_type in ${(s: :)${AI_PARAMS[$picked]:-none}}; do
    case "$param_type" in
      file)
        local f
        f=$(_ai_prompt_file "File for ai-${picked}:") || return 1
        args+=("$f")
        ;;
      language)
        local l
        l=$(_ai_prompt_language) || return 1
        args+=("$l")
        ;;
      number)
        local n
        n=$(_ai_prompt_number) || return 1
        [[ -n "$n" ]] && args+=("$n")
        ;;
      text)
        local t
        t=$(_ai_prompt_text) || return 1
        args+=("$t")
        ;;
      none) ;;
    esac
  done

  "ai-${picked}" "${args[@]}"
}
````

**\_ai-docs.zsh**

```bash
# Shared document-to-text extraction for ai-translate and ai-summarize.
# .pdf/.docx/.pptx/.xlsx/.html go through docling-convert (see /blog/docling)
# first; .md/.markdown/.txt files are read directly, no conversion needed.
#
# Leading underscore: loads after _ollama.zsh (still alphabetically before
# ai-summarize.zsh and ai-translate.zsh), so _ollama_query is always ready.

_ai_extract_text() {
  local file="$1"
  local ext="${file:e:l}"

  case "$ext" in
    md|markdown|txt)
      cat "$file"
      ;;
    pdf|docx|pptx|xlsx|html|htm)
      if ! command -v docling-convert >/dev/null 2>&1; then
        echo "_ai_extract_text: docling-convert not found — see /blog/docling to set it up" >&2
        return 1
      fi
      local dir filename base mdfile
      dir="${file:h}"
      filename="${file:t}"
      base="${filename%.*}"
      mdfile="${dir}/${base}.md"
      echo "→ Converting '$file' with docling-convert..." >&2
      ( cd "$dir" && docling-convert "$filename" >/dev/null 2>&1 ) || {
        echo "_ai_extract_text: docling-convert failed on '$file'" >&2
        return 1
      }
      cat "$mdfile"
      ;;
    *)
      echo "_ai_extract_text: unsupported extension .$ext (expected pdf/docx/pptx/xlsx/html/md/txt)" >&2
      return 1
      ;;
  esac
}
```

**ai-translate.zsh**

```bash
# ai-translate <file> [language] — translate a document into the given
# language (default: French), entirely locally. Accepts .pdf/.docx/.pptx/
# .xlsx/.html (via docling-convert) or plain .md/.txt files directly.

AI_COMMANDS[translate]="ai-translate <file> [language]  — translate a document locally (default: French)"

ai-translate() {
  local file="$1"
  local lang="${2:-French}"

  if [[ -z "$file" || ! -f "$file" ]]; then
    echo "Usage: ai-translate <file> [target-language]" >&2
    return 1
  fi

  local text
  text=$(_ai_extract_text "$file") || return 1

  local prompt="Translate the following document into $lang. Preserve the Markdown structure exactly — headings, lists, tables, emphasis. Output only the translated document, no commentary and no notes about the translation.

$text"

  _ollama_query "$prompt"
}
```

**ai-summarize.zsh**

```bash
# ai-summarize <file> [points] — summarize a document in N bullet points
# (default: 5), entirely locally. Accepts .pdf/.docx/.pptx/.xlsx/.html (via
# docling-convert) or plain .md/.txt files directly.

AI_COMMANDS[summarize]="ai-summarize <file> [points]  — summarize a document locally (default: 5 points)"

ai-summarize() {
  local file="$1"
  local points="${2:-5}"

  if [[ -z "$file" || ! -f "$file" ]]; then
    echo "Usage: ai-summarize <file> [number-of-points]" >&2
    return 1
  fi

  local text
  text=$(_ai_extract_text "$file") || return 1

  local prompt="Summarize the following document in exactly $points bullet points, written in the same language as the document. Prioritize decisions, numbers, deadlines and action items over generic description. Output only the bullet points, nothing else.

$text"

  _ollama_query "$prompt"
}
```

**2. Load the folder from `~/.zshrc`.** Already done if you followed an earlier article of this series. Otherwise, add these lines at the end of `~/.zshrc` — they source every `.zsh` file in the folder, so the next function you add needs no change here:

```zsh title="~/.zshrc"
for fn_file in ~/.zsh/fns/*.zsh; do
  source "$fn_file"
done
```

**3. Open a new terminal** (or run `exec zsh` in the current one), and check that the shell knows the new functions:

```zsh
type ai-translate ai-summarize
```

`ai-translate is a shell function from …/ai-translate.zsh` means you're ready. `ai-translate not found` means step 2 is missing.

## Conclusion

The actual privacy story here isn't a policy or a promise — it's an architecture. A document goes in, Docling turns it into text without a network call, Ollama processes that text without a network call, and the result lands in my terminal. There's no step in that chain where "trust the vendor" is required, which is exactly what makes it usable for the documents I'd never risk on a cloud tool in the first place. Between this, `ai-ci` for pipelines, `ai-standup` for the morning recap and the rest of this series, the local model I already had running for other reasons keeps finding one more thing worth doing quietly, in the background, without asking anything of me except a file path.
