Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions extensions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ statusbot every minute. While term7 is closed, it just tries again on the next r

Reads Claude's replies aloud with [Kokoro-82M](https://github.com/thewh1teagle/kokoro-onnx), generated on your own
machine: no internet, no quota, and the text never leaves the computer. Unlike the others, this extension doesn't use
the API: term7 itself calls it for each chunk of the reply.
the API: term7 opens it once per reading (`--serve`), so the model loads once and the next chunks are generated
while the current one plays.

Install it from the screen (Settings → Extensions → Local voice). Installing creates a venv in
`~/.local/share/term7/kokoro` with `kokoro-onnx` and downloads the int8 model (~120 MB). Then, in Settings → Read
Expand All @@ -88,7 +89,7 @@ aloud, pick “Local voice (extension)”.
the English voices (`af_heart`, `am_michael`…).
- **Speed:** 1.0 is normal; 0.8 speaks slower.
- **CPU cores:** how many to use while generating (default 4). Each reply read aloud keeps the CPU busy for a few
seconds.
seconds. With 1 core generation barely keeps up with speech; use 2 or more if you hear pauses.
- Try it outside term7: `echo "Hello" | python3 /usr/share/term7/extensions/kokoro/term7-kokoro /tmp/hello.wav`
- Remove: from the screen, or delete `~/.local/share/term7/kokoro` and `~/.config/term7/kokoro.env`.

Expand Down
4 changes: 3 additions & 1 deletion extensions/README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ a cada minuto. Com o term7 fechado, ele só tenta de novo na volta seguinte.

Lê as respostas do Claude em voz alta com o [Kokoro-82M](https://github.com/thewh1teagle/kokoro-onnx), gerado na
própria máquina: sem internet, sem cota e sem o texto sair do computador. Diferente das outras, essa extensão não usa a
API: quem chama é o próprio term7, a cada trecho da resposta.
API: o term7 abre ela uma vez por leitura (`--serve`), então o modelo carrega uma vez só e os próximos trechos são
gerados enquanto o atual toca.

Instale pela tela (Configurações → Extensões → Voz local). A instalação cria um venv em `~/.local/share/term7/kokoro`
com o `kokoro-onnx` e baixa o modelo int8 (~120 MB). Depois, em Configurações → Leitura em voz alta, escolha
Expand All @@ -89,6 +90,7 @@ com o `kokoro-onnx` e baixa o modelo int8 (~120 MB). Depois, em Configurações
(`af_heart`, `am_michael`…).
- **Velocidade:** 1.0 é o normal; 0.8 fala mais devagar.
- **Núcleos da CPU:** quantos usar pra gerar (padrão 4). Cada resposta lida ocupa a CPU por alguns segundos.
Com 1 núcleo a geração fica quase no ritmo da fala; use 2 ou mais se ouvir pausas.
- Testar fora do term7: `echo "Olá" | python3 /usr/share/term7/extensions/kokoro/term7-kokoro /tmp/ola.wav`
- Remover: pela tela, ou apagar `~/.local/share/term7/kokoro` e `~/.config/term7/kokoro.env`.

Expand Down
41 changes: 33 additions & 8 deletions extensions/kokoro/term7-kokoro
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
Gera a fala na própria máquina com o Kokoro-82M (int8, via kokoro-onnx): nada sai
da máquina e não tem cota. O term7 chama uma vez por trecho:

term7-kokoro OUT.wav < texto gera o .wav do texto
term7-kokoro --serve fica aberto durante a leitura: carrega o modelo
uma vez; cada linha {"text", "out"} no stdin
vira um .wav e responde "ok" (ou "erro: ...")
term7-kokoro OUT.wav < texto gera um .wav só (pra testar na mão)
term7-kokoro --setup cria o ambiente e baixa o modelo (~120 MB)

As dependências (kokoro-onnx, onnxruntime) ficam num venv próprio em
Expand All @@ -18,6 +21,7 @@ Configuração ($XDG_CONFIG_HOME/term7/kokoro.env, gravada pela tela de extensõ
KOKORO_THREADS núcleos usados pra gerar (padrão 4)
"""

import json
import os
import subprocess
import sys
Expand Down Expand Up @@ -105,9 +109,8 @@ def setup():
print("Pronto.")


def speak(out_path, text):
def load_voice():
import onnxruntime as ort
import soundfile as sf
from kokoro_onnx import Kokoro

cfg = load_settings()
Expand All @@ -118,24 +121,46 @@ def speak(out_path, text):
opts.inter_op_num_threads = 1
session = ort.InferenceSession(os.path.join(root, MODEL_FILES[0]), opts, providers=["CPUExecutionProvider"])
kokoro = Kokoro.from_session(session, os.path.join(root, MODEL_FILES[1]))
samples, rate = kokoro.create(text, voice=cfg["voice"], speed=cfg["speed"], lang=cfg["lang"])
sf.write(out_path, samples, rate, subtype="PCM_16")

def speak(out_path, text):
import soundfile as sf

samples, rate = kokoro.create(text, voice=cfg["voice"], speed=cfg["speed"], lang=cfg["lang"])
sf.write(out_path, samples, rate, subtype="PCM_16")

return speak


def serve(speak, lines, reply):
"""Um pedido por linha; um erro num trecho não derruba os seguintes."""
for line in lines:
if not line.strip():
continue
try:
req = json.loads(line)
speak(req["out"], req["text"])
reply("ok")
except Exception as e: # noqa: BLE001 - qualquer falha vira resposta, não silêncio
reply("erro: " + " ".join(str(e).split()))


def main(argv):
if argv[1:] == ["--setup"]:
return setup()
if len(argv) != 2 or argv[1].startswith("-"):
sys.exit("Uso: term7-kokoro OUT.wav < texto | term7-kokoro --setup")
serving = argv[1:] == ["--serve"]
if not serving and (len(argv) != 2 or argv[1].startswith("-")):
sys.exit("Uso: term7-kokoro --serve | term7-kokoro OUT.wav < texto | term7-kokoro --setup")
if not os.path.exists(os.path.join(data_dir(), "ready")):
sys.exit("a extensão Kokoro não terminou de instalar (Configurações → Extensões)")
# Rodando com o python3 do sistema: passa pro do venv, onde estão as dependências.
if os.path.realpath(sys.prefix) != os.path.realpath(os.path.join(data_dir(), "venv")):
os.execv(venv_python(), [venv_python(), os.path.abspath(__file__), *argv[1:]])
if serving:
return serve(load_voice(), sys.stdin, lambda msg: print(msg, flush=True))
text = sys.stdin.read().strip()
if not text:
sys.exit("texto vazio")
speak(argv[1], text)
load_voice()(argv[1], text)


if __name__ == "__main__":
Expand Down
17 changes: 17 additions & 0 deletions extensions/kokoro/test_term7_kokoro.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@
loader.exec_module(ext)


class Servidor(unittest.TestCase):
def test_um_pedido_por_linha_e_erro_nao_derruba(self):
made, replies = [], []

def speak(out, text):
if text == "quebra":
raise ValueError("voz\ninexistente")
made.append((out, text))

lines = ['{"text": "Olá.", "out": "/t/0.wav"}\n', "\n", "não é json\n", '{"text": "quebra", "out": "/t/1.wav"}\n', '{"text": "Fim.", "out": "/t/2.wav"}\n']
ext.serve(speak, lines, replies.append)
self.assertEqual(made, [("/t/0.wav", "Olá."), ("/t/2.wav", "Fim.")])
self.assertEqual(replies[0], "ok")
self.assertTrue(replies[1].startswith("erro: "))
self.assertEqual(replies[2:], ["erro: voz inexistente", "ok"])


class Configuracao(unittest.TestCase):
def test_le_o_arquivo_que_o_term7_grava(self):
# Formato do render_env do extensions.rs.
Expand Down
Loading