#!/usr/bin/env python3 """Local speech-to-text for Peppa (PEP-108): faster-whisper behind the OpenAI-compatible endpoint Peppa already speaks — POST /v1/audio/transcriptions (multipart: file, model, language, response_format=json) -> {"text": "..."}. Listens on 127.0.0.1 only; audio never leaves this machine. Any format PyAV reads works, Telegram's OGG/Opus voice notes included. """ import io import json import os import sys import threading import time from email.parser import BytesParser from email.policy import HTTP from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from faster_whisper import WhisperModel HOST = os.environ.get("WHISPER_HOST", "127.0.0.1") PORT = int(os.environ.get("WHISPER_PORT", "8178")) MODEL = os.environ.get("WHISPER_MODEL", "large-v3-turbo") MAX_BYTES = int(os.environ.get("WHISPER_MAX_BYTES", str(25 * 1024 * 1024))) print(f"loading model {MODEL}…", flush=True) model = WhisperModel(MODEL, device="cpu", compute_type="int8", cpu_threads=int(os.environ.get("WHISPER_THREADS", "8"))) lock = threading.Lock() # one transcription at a time: the model is not re-entrant print(f"ready on http://{HOST}:{PORT}", flush=True) def parse_multipart(content_type: str, body: bytes) -> dict: msg = BytesParser(policy=HTTP).parsebytes(b"Content-Type: " + content_type.encode() + b"\r\n\r\n" + body) out = {} for part in msg.iter_parts(): name = part.get_param("name", header="content-disposition") if name: out[name] = part.get_payload(decode=True) return out class Handler(BaseHTTPRequestHandler): def _send(self, status: int, body: dict): data = json.dumps(body, ensure_ascii=False).encode() self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): if self.path in ("/health", "/v1/health"): return self._send(200, {"ok": True, "model": MODEL}) self._send(404, {"error": {"message": "not found"}}) def do_POST(self): if self.path.rstrip("/") not in ("/v1/audio/transcriptions", "/audio/transcriptions"): return self._send(404, {"error": {"message": "not found"}}) length = int(self.headers.get("Content-Length") or 0) if length <= 0 or length > MAX_BYTES: return self._send(413, {"error": {"message": f"audio must be 1..{MAX_BYTES} bytes"}}) try: fields = parse_multipart(self.headers.get("Content-Type", ""), self.rfile.read(length)) audio = fields.get("file") if not audio: return self._send(400, {"error": {"message": "no file"}}) language = (fields.get("language") or b"").decode().strip() or None started = time.time() with lock: segments, info = model.transcribe(io.BytesIO(audio), language=language, vad_filter=True, beam_size=5) text = " ".join(s.text.strip() for s in segments).strip() print(f"{time.strftime('%F %T')} {len(audio)} bytes, {info.duration:.1f}s audio, lang={info.language}, {time.time() - started:.1f}s", flush=True) self._send(200, {"text": text}) except Exception as e: # a broken file must not take the service down print(f"error: {e}", file=sys.stderr, flush=True) self._send(400, {"error": {"message": f"could not transcribe: {e}"}}) def log_message(self, *_): pass ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()