Lucasgitguy-co's picture
Turbo-Kev Dictate release
20149a3 verified
Raw History Blame Contribute Delete
4.18 kB
"""Teacher transcripts: whisper-large-v3-turbo GGUF (oxide-lab, whisper.cpp format) through whisper-server.
python -m tk.teacher --quant q4_k --sets fleurs-en-dev --out data/teacher-q4_k # quant check
python -m tk.teacher --quant <chosen> --sets dis-train ... # default out: data/teacher
Resumable (finished ids are skipped). English, beam 5, whisper.cpp default temperature fallback.
"""
from __future__ import annotations
import argparse
import io
import json
import subprocess
import sys
import time
from pathlib import Path
import requests
import soundfile as sf
from tk import paths
from tk.wer import read_jsonl
PORT = 8781
class Server:
def __init__(self, model: Path, port: int = PORT, beam: int = 5):
self.url = f"http://127.0.0.1:{port}/inference"
self.log = open(paths.RUNS / f"whisper-server-{model.stem}.log", "w")
self.p = subprocess.Popen(["whisper-server", "-m", str(model), "--port", str(port), "-l", "en", "-bs", str(beam),
"-t", "4"], stdout=self.log, stderr=subprocess.STDOUT)
for _ in range(240):
try:
requests.get(f"http://127.0.0.1:{port}/", timeout=1)
return
except Exception:
if self.p.poll() is not None:
raise RuntimeError("whisper-server exited; see " + self.log.name)
time.sleep(0.5)
raise RuntimeError("whisper-server did not start")
def transcribe(self, flac: Path) -> str:
w, sr = sf.read(flac, dtype="int16")
buf = io.BytesIO()
sf.write(buf, w, sr, format="WAV", subtype="PCM_16")
for attempt in range(4): # a frozen/resumed process (memory pressure) times out once; retry, don't die
try:
r = requests.post(self.url, files={"file": ("a.wav", buf.getvalue(), "audio/wav")},
data={"response_format": "json", "temperature": "0.0", "temperature_inc": "0.2"},
timeout=600)
r.raise_for_status()
return " ".join(r.json()["text"].split())
except requests.RequestException as e:
if attempt == 3 or self.p.poll() is not None:
raise
print(f" retry {flac.name}: {e!r}", flush=True)
time.sleep(30)
def close(self):
self.p.terminate()
try:
self.p.wait(10)
except subprocess.TimeoutExpired:
self.p.kill()
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--quant", required=True)
ap.add_argument("--sets", nargs="+", required=True)
ap.add_argument("--out", default=str(paths.TEACHER))
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--beam", type=int, default=5)
a = ap.parse_args()
sfx = "-smoke" if a.smoke else ""
model = paths.MODELS / "oxide" / "whisper.cpp" / f"whisper-large-v3-turbo-{a.quant}.gguf"
out_dir = Path(a.out + sfx)
out_dir.mkdir(parents=True, exist_ok=True)
srv = None
try:
for s in a.sets:
rows = read_jsonl(paths.DATA / f"manifest{sfx}" / f"{s}.jsonl")
out = out_dir / f"{s}.jsonl"
done = {r["id"] for r in read_jsonl(out)}
t0, n = time.time(), 0
with out.open("a") as f:
for r in rows:
if r["id"] in done:
continue
if srv is None:
srv = Server(model, beam=a.beam)
hyp = srv.transcribe(paths.DATA / f"audio{sfx}" / s / f"{r['id']}.flac")
f.write(json.dumps({"id": r["id"], "hyp": hyp, "quant": a.quant}, ensure_ascii=False) + "\n")
f.flush()
n += 1
if n % 500 == 0:
print(f" {s}: {n} in {time.time() - t0:.0f} s", flush=True)
print(f"{s}: {n} new rows in {time.time() - t0:.0f} s -> {out}", flush=True)
finally:
if srv is not None:
srv.close()
if __name__ == "__main__":
sys.exit(main())