Wikipedia offline que te lee el artículo mientras lo leés (kiwix + espeak + mpv + tmux)

· offline, wikipedia, audio, tmux

Escuchar este artículo

Descargar MP3 · Ver en Internet Archive

Tenía las dos wikis descargadas en ZIM (wikipedia_es_all_maxi y wikipedia_en_all_nopic), un wikiesp y un wikip que abrían el artículo con w3m, y el paso manual de siempre: bajar el texto, generar un .wav con espeak y reproducirlo con mpv porque espeak no se puede pausar y mpv sí.

La idea fue juntar todo en el mismo comando: escribís wikiesp "Alan Turing" y paso lo siguiente:

  1. Arranca kiwix-serve con el ZIM correspondiente (si no está sirviendo ese, mata el anterior y levanta el otro).
  2. Busca el artículo con kiwix-search y arma la URL con el título encodeado.
  3. Baja el HTML y extrae solo los párrafos del cuerpo (sin infobox, sin referencias, sin menú).
  4. Genera el .wav y lo guarda en caché.
  5. Abre mpv en pausa con un socket IPC y abre w3m con el artículo.
  6. F12 hace play/pausa sin salir de w3m.

Las dos voces

Acá hay un detalle: para el español uso espeak-ng -v es y para el inglés espeak (voz por defecto, inglesa). No es lo mismo el motor ni la voz:

comando wiki motor
wikiesp "tema" español, all_maxi espeak-ng -v es
wikip "tema" inglés, all_nopic espeak

Extraer el texto limpio

w3m -dump tira todo el texto de la página, incluido el infobox y las notas al pie, y eso se escucha horrible. Con HTMLParser de la stdlib (no hay que instalar bs4 ni nada) alcanza con quedarse con los <p> que están dentro de #mw-content-text, y saltar script, style, sup, table y figure:

#!/usr/bin/env python3
import re
import sys
from html.parser import HTMLParser


class Prose(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.divstack = []
        self.in_content = 0
        self.in_p = 0
        self.skip = {}
        self.buf = []
        self.out = []

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag in ("script", "style", "sup", "table", "figure"):
            self.skip[tag] = self.skip.get(tag, 0) + 1
        if tag == "div":
            cls = attrs.get("class") or ""
            is_content = attrs.get("id") == "mw-content-text" or "mw-parser-output" in cls
            self.divstack.append(is_content)
            self.in_content += is_content
        if tag == "p" and self.in_content and not any(self.skip.values()):
            self.in_p = 1
            self.buf = ["\n"]

    def handle_endtag(self, tag):
        if tag in self.skip and self.skip[tag]:
            self.skip[tag] -= 1
        if tag == "div" and self.divstack and self.divstack.pop():
            self.in_content -= 1
        if tag == "p" and self.in_p:
            self.out.append("".join(self.buf) + "\n")
            self.in_p = 0

    def handle_data(self, data):
        if self.in_p and not any(self.skip.values()):
            self.buf.append(data)


def main():
    parser = Prose()
    parser.feed(sys.stdin.read())
    text = "".join(parser.out)
    text = re.sub(r"\[\d+\]", "", text)
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r"\n\s*\n+", "\n\n", text).strip()
    if text:
        print(text)


if __name__ == "__main__":
    main()

Guardarlo como ~/.local/bin/wiki-prose y chmod +x. El detalle del divstack es importante: los ZIM de wikipedia tienen un montón de <div> anidados y si solo llevás un contador loss los párrafos después del primero.

Las funciones en .bashrc

_wiki_leer() {
  local lang="$1" zim="$2" archive="$3" engine="$4"
  shift 4
  local query="$*" base="http://localhost"
  local first slug enc url dir key txt wav sock

  if [[ -z "$query" ]]; then
    echo "Uso: wikiesp <tema> | wikip <tema>"
    return 1
  fi

  if ! curl -s "$base/catalog/v2/entries" 2>/dev/null | grep -qF "/content/$archive"; then
    sudo pkill -f kiwix-serve 2>/dev/null
    sudo kiwix-serve "$zim" >/dev/null 2>&1 &
    for _ in {1..15}; do
      curl -s "$base/catalog/v2/entries" 2>/dev/null | grep -qF "/content/$archive" && break
      sleep 1
    done
  fi

  first=$(kiwix-search "$zim" "$query" 2>/dev/null | head -1)
  if [[ -z "$first" ]]; then
    echo "Sin resultados para: $query"
    return 1
  fi

  slug="${first// /_}"
  enc=$(printf '%s' "$slug" | jq -sRr @uri)
  url="$base/content/$archive/$enc"

  dir="$HOME/.cache/wiki-audio/$lang"
  mkdir -p "$dir"
  key="${slug//[^[:alnum:]_-]/_}"
  key="${key:0:72}"
  txt="$dir/$key.txt"
  wav="$dir/$key.wav"

  if [[ ! -s "$txt" ]]; then
    echo "Extrayendo texto: $first"
    curl -sL "$url" | wiki-prose > "$txt.tmp" || return 1
    if [[ ! -s "$txt.tmp" ]]; then
      echo "No se pudo extraer el texto de: $url"
      return 1
    fi
    mv "$txt.tmp" "$txt"
  fi

  if [[ ! -s "$wav" ]]; then
    echo "Generando audio ($engine)... puede tardar un momento"
    case "$engine" in
      ng-es) espeak-ng -v es -f "$txt" -w "$wav.tmp" ;;
      espeak) espeak -f "$txt" -w "$wav.tmp" ;;
    esac
    if [[ ! -s "$wav.tmp" ]]; then
      echo "Error generando el audio."
      return 1
    fi
    mv "$wav.tmp" "$wav"
  fi

  sock="/tmp/wiki-mpv-$USER.sock"
  if [[ -S "$sock" ]]; then
    printf '%s\n' '{"command":["quit"]}' | ncat -U "$sock" 2>/dev/null
    rm -f "$sock"
  fi

  mpv --input-ipc-server="$sock" --input-terminal=no --no-video --pause \
    "$wav" </dev/null >/dev/null 2>&1 &
  for _ in {1..20}; do
    [[ -S "$sock" ]] && break
    sleep 0.2
  done

  printf '\n  %s\n  Audio: %s\n  F12 = play/pausa   wiki-audio-ctl stop = detener\n\n' "$first" "$wav"
  w3m "$url"
}

wikiesp() {
  _wiki_leer es \
    "/home/esotericwarfare/Downloads/kiwix/wikipedia_es_all_maxi_2026-10.zim" \
    "wikipedia_es_all_maxi_2026-10" ng-es "$@"
}

wikip() {
  _wiki_leer en \
    "/home/esotericwarfare/Downloads/kiwix/wikipedia_en_all_nopic_2026-06.zim" \
    "wikipedia_en_all_nopic_2026-06" espeak "$@"
}

alias wiki-audio='wiki-audio-ctl'
alias wikistop='wiki-audio-ctl stop'

El --input-terminal=no es clave: si no, mpv en background te roba el stdin y w3m se queda sin teclado. El socket tarda un instante en crearse, por eso el for con sleep 0.2 antes de devolver el control.

El control de play/pausa

~/.local/bin/wiki-audio-ctl:

#!/usr/bin/env bash
sock="/tmp/wiki-mpv-$USER.sock"
case "${1:-toggle}" in
  toggle) cmd='{"command":["cycle","pause"]}' ;;
  play)   cmd='{"command":["set_property","pause",false]}' ;;
  pause)  cmd='{"command":["set_property","pause",true]}' ;;
  stop|quit) cmd='{"command":["quit"]}' ;;
  *) echo "Uso: wiki-audio-ctl [toggle|play|pause|stop]" >&2; exit 2 ;;
esac
if [[ ! -S "$sock" ]]; then
  echo "No hay audio de wiki en reproducción." >&2
  exit 1
fi
printf '%s\n' "$cmd" | ncat -U "$sock" 2>/dev/null | jq -r '.error // empty' 2>/dev/null

Y en ~/.tmux.conf para no tener que abrir otra terminal:

bind-key -n F12 run-shell "/home/esotericwarfare/.local/bin/wiki-audio-ctl toggle"

Si no estás en tmux, wiki-audio hace lo mismo y wikistop corta el audio.

Uso

wikiesp "alan turing"
wikip "alan turing"
wiki-audio          # play/pausa
wikistop            # detener

Arranca en pausa: le das F12 cuando ya estás cómodo leyendo. El texto y el wav quedan en ~/.cache/wiki-audio/{es,en}/, así que la segunda vez que abras el mismo artículo entra directo. Dependencias: kiwix-tools, w3m, jq, ncat, espeak/espeak-ng y mpv.