Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/allen_transcribe.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / allen_transcribe.py` 295 lines ยท 13481 bytes Raw Blame History 1 """Push-to-talk transcription for public Allen: POST /allen/api/transcribe. 2 3 The page records a short clip and posts the raw bytes (no JSON, no base64) with 4 Content-Type audio/webm, audio/ogg (Opus) or audio/wav. The reply is 5 {"text", "ms", "seconds", "model"}; refusals use the gateway's {"error", 6 "message"} shape. 7 8 Audio never touches a disk. The body is read into one bytearray; Opus is decoded 9 by a pinned-version ffmpeg inside the same bubblewrap sandbox shape as the 10 compiler (no network, empty root, no host files beyond read-only /usr for its 11 shared libraries), stdin to stdout. The PCM goes over a pipe to a pinned static 12 whisper-cli (whisper.cpp) in a second sandbox that sees only its binary and the 13 pinned model, read-only. Both buffers are zeroed and dropped before the reply is 14 sent. The transcript is returned and never logged; only aggregate counters are 15 kept. 16 17 Limits: --transcribe-max-bytes body, MAX_SECONDS of audio (longer clips are 18 refused, never truncated), the chat route's per-address bucket parameters (own 19 bucket), at most --transcribe-cap transcriptions at once (503 busy otherwise). 20 """ 21 22 import hashlib 23 import re 24 import os 25 import resource 26 import signal 27 import struct 28 import subprocess 29 import threading 30 import time 31 32 BWRAP = "/usr/bin/bwrap" 33 RATE = 16000 34 MAX_SECONDS = 15 35 MIN_SECONDS = 0.3 36 PCM_CAP = MAX_SECONDS * RATE * 2 37 TYPES = {"audio/webm": "webm", "video/webm": "webm", "audio/ogg": "ogg", 38 "audio/wav": "wav", "audio/wave": "wav", "audio/x-wav": "wav", "audio/vnd.wave": "wav"} 39 DEMUX = {"webm": "matroska", "ogg": "ogg"} 40 # whisper.cpp v1.9.5 (commit `d1be6fde11ac6e0407606b4e42fe72d34add8037`), static, CPU only, 41 # GGML_OPENMP=OFF, GGML_NATIVE=ON on the Spark (build steps: DEPENDENCIES.md). 42 WHISPER_PIN = "`0b3d63f4a90d5df14031479ed039fe1f96ffc52fff8b193e85f71daa3762ed5a`" 43 # ggerganov/whisper.cpp model repo revision `5359861c739e955e79d9a303bcbc70fb988958b1` (LFS sha256). 44 MODEL_PINS = {"`a03779c86df3323075f5e796cb2ce5029f00ec8869eee3fdfb897afe36c6d002`": "base.en", 45 "`921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f`": "tiny.en"} 46 47 48 def sniff(data): 49 if data[:4] == b"\x1a\x45\xdf\xa3": 50 return "webm" 51 if data[:4] == b"OggS": 52 return "ogg" 53 if data[:4] == b"RIFF" and data[8:12] == b"WAVE": 54 return "wav" 55 return None 56 57 58 def wav_pcm(data): 59 """(pcm16 bytes view, rate, channels) from a RIFF/WAVE PCM 16-bit file, or a reason string.""" 60 pos, fmt = 12, None 61 while pos + 8 <= len(data): 62 cid, size = data[pos:pos + 4], struct.unpack_from(" len(data): 66 return "the WAV format chunk is truncated" 67 tag, ch, rate, _, _, bits = struct.unpack_from(" out_cap: 121 return None, b"output too large", -1 122 return out, err[-2048:], p.returncode 123 124 125 class Transcriber: 126 def __init__(self, whisper, model, ffmpeg, threads, cap, max_bytes): 127 have = sha256_file(whisper) 128 if have != WHISPER_PIN: 129 raise SystemExit("allen-chat: %s sha256 %s, pinned %s" % (whisper, have, WHISPER_PIN)) 130 have = sha256_file(model) 131 if have not in MODEL_PINS: 132 raise SystemExit("allen-chat: %s sha256 %s is not a pinned whisper model" % (model, have)) 133 if not os.access(ffmpeg, os.X_OK) or not os.access(BWRAP, os.X_OK): 134 raise SystemExit("allen-chat: transcription needs %s and %s" % (ffmpeg, BWRAP)) 135 self.whisper, self.model, self.ffmpeg = whisper, model, ffmpeg 136 self.model_name = MODEL_PINS[have] 137 self.threads = threads 138 self.max_bytes = max_bytes 139 self.slots = threading.BoundedSemaphore(cap) 140 # Fail closed: both sandboxes must work here, or the gateway does not start. 141 silent = bytearray(RATE // 2 * 2) 142 text = self.transcribe(bytearray(wav_header(len(silent)) + silent), "wav") 143 if not isinstance(text, tuple): 144 raise SystemExit("allen-chat: the transcription sandbox does not work here: %s" % text) 145 out, _, rc = run(self.usr(), [ffmpeg, "-hide_banner", "-version"], b"", 5, 1 << 16, 5, 1 << 30) 146 if rc != 0 or not out: 147 raise SystemExit("allen-chat: the decoder sandbox does not work here (rc %s)" % rc) 148 149 @staticmethod 150 def usr(): 151 """ffmpeg is the distribution's dynamic build: it sees /usr, /lib and the loader's 152 /etc/ld.so.cache and /etc/alternatives (library symlinks) read-only, nothing else.""" 153 return [(p, p) for p in ("/usr", "/lib", "/etc/ld.so.cache", "/etc/alternatives") if os.path.exists(p)] 154 155 def decode(self, data, kind): 156 """16 kHz mono PCM16 (bytearray) or a reason string. Never truncates: too long is refused. 157 Only the forced demuxer and the native Opus decoder are reachable; only pipe: I/O.""" 158 argv = [self.ffmpeg, "-hide_banner", "-loglevel", "error", "-nostats", "-threads", "1", 159 "-protocol_whitelist", "pipe", "-f", DEMUX[kind], "-c:a", "opus", "-i", "pipe:0", 160 "-map", "0:a:0", "-t", str(MAX_SECONDS + 0.05), "-ac", "1", "-ar", str(RATE), 161 "-f", "s16le", "pipe:1"] 162 out, _, rc = run(self.usr(), argv, data, 5, PCM_CAP + RATE * 2, 10, 1 << 30) 163 if rc != 0 or out is None: 164 return "the audio could not be decoded as Opus" 165 pcm = bytearray(out) 166 del out # the immutable pipe copy is dropped here; the bytearray is zeroed by the caller 167 if len(pcm) > PCM_CAP: 168 pcm[:] = bytes(len(pcm)) 169 return "too_long" 170 return pcm 171 172 def transcribe(self, data, kind): 173 """(text, seconds) or a reason string ("too_long" for over-length audio).""" 174 if kind == "wav": 175 got = wav_pcm(data) 176 if isinstance(got, str): 177 return got 178 pcm, rate, ch = got 179 seconds = len(pcm) / (2.0 * rate * ch) 180 if seconds > MAX_SECONDS: 181 return "too_long" 182 if rate == RATE and ch == 1: 183 wav = bytearray(wav_header(len(pcm))) + pcm 184 else: # whisper-cli resamples and downmixes WAV itself; pass a canonical header 185 wav = bytearray(b"RIFF" + struct.pack("= 0 else "" 222 if line: 223 words.append(line) 224 return aien(" ".join(words))[:2000] 225 226 227 # "Aien" is said like "Ian"; the English model writes what it hears. Spellings that are never 228 # another English word become Aien anywhere; "Ian" only when the visitor addresses him: at the 229 # start of the clip ("Ian, ..."), after a greeting ("hey Ian"), or alone before punctuation/end 230 # after a comma ("thanks, Ian."). "My friend Ian wrote this" keeps its Ian. 231 ODD = re.compile(r"\b(?:Ayen|Aien|Aian|Een|Eean|Ean)\b", re.I) 232 VOCATIVE = re.compile(r"(^|\b(?:hey|hi|hello|hiya|yo|okay|ok|thanks|thank you|dear)[ ,]+|,\s*)Ian\b(?=\s*[,.!?]|\s*$|\s+(?:can|could|would|will|do|did|are|is|what|how|why|who|where|when|please|tell|show|help)\b)", 233 re.I) 234 235 236 def aien(text): 237 text = ODD.sub("Aien", text) 238 return VOCATIVE.sub(lambda m: m.group(1) + "Aien", text) 239 240 241 def handle(h): 242 """POST /allen/api/transcribe on the gateway's Handler `h`.""" 243 app = h.app 244 t = app.transcriber 245 if t is None: 246 return h.send_json(404, {"error": "not_found"}) 247 app.stats.add("transcribe_requests") 248 try: 249 n = int(h.headers.get("Content-Length", "")) 250 except ValueError: 251 return h.refuse(411, "length", "Send the clip with a Content-Length.") 252 if n > t.max_bytes: 253 return h.refuse(413, "too_long", "Voice clips are limited to %d KiB and %d seconds here." 254 % (t.max_bytes >> 10, MAX_SECONDS)) 255 if n <= 0: 256 return h.refuse(400, "bad_request", "The clip is empty.") 257 ctype = h.headers.get("Content-Type", "").split(";")[0].strip().lower() 258 kind = TYPES.get(ctype) 259 if kind is None: 260 return h.refuse(415, "format", "Send audio/webm or audio/ogg (Opus) or audio/wav (16-bit PCM).") 261 retry = app.transcribe_rate.take(app.client_key(h)) 262 if retry: 263 return h.refuse(429, "rate", "You are sending clips quickly. Try again shortly.", retry) 264 data = bytearray(n) 265 try: 266 got = h.rfile.readinto(data) 267 except (OSError, ValueError): 268 got = -1 269 if got != n: 270 data[:] = bytes(n) 271 h.close_connection = True 272 return 273 h.body_read = True 274 try: 275 if sniff(data) != kind: 276 return h.refuse(415, "format", "The clip is not the format its Content-Type says.") 277 if not t.slots.acquire(blocking=False): 278 return h.refuse(503, "busy", "Voice input is busy right now. Try again in a moment.", 2) 279 try: 280 t0 = time.monotonic() 281 got = t.transcribe(data, kind) 282 finally: 283 t.slots.release() 284 finally: 285 data[:] = bytes(n) 286 del data 287 if got == "too_long": 288 return h.refuse(413, "too_long", "Voice clips are limited to %d seconds here." % MAX_SECONDS) 289 if isinstance(got, str): 290 app.stats.add("transcribe_fail") 291 return h.refuse(422, "audio", "Aien could not hear that clip: %s." % got) 292 text, seconds = got 293 app.stats.add("transcribe_ok") 294 h.send_json(200, {"text": text, "ms": int((time.monotonic() - t0) * 1000), "seconds": round(seconds, 2), 295 "model": t.model_name})