interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

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
3The page records a short clip and posts the raw bytes (no JSON, no base64) with
4Content-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
8Audio never touches a disk. The body is read into one bytearray; Opus is decoded
9by a pinned-version ffmpeg inside the same bubblewrap sandbox shape as the
10compiler (no network, empty root, no host files beyond read-only /usr for its
11shared libraries), stdin to stdout. The PCM goes over a pipe to a pinned static
12whisper-cli (whisper.cpp) in a second sandbox that sees only its binary and the
13pinned model, read-only. Both buffers are zeroed and dropped before the reply is
14sent. The transcript is returned and never logged; only aggregate counters are
15kept.
16
17Limits: --transcribe-max-bytes body, MAX_SECONDS of audio (longer clips are
18refused, never truncated), the chat route's per-address bucket parameters (own
19bucket), at most --transcribe-cap transcriptions at once (503 busy otherwise).
20"""
21
22import hashlib
23import re
24import os
25import resource
26import signal
27import struct
28import subprocess
29import threading
30import time
31
32BWRAP = "/usr/bin/bwrap"
33RATE = 16000
34MAX_SECONDS = 15
35MIN_SECONDS = 0.3
36PCM_CAP = MAX_SECONDS * RATE * 2
37TYPES = {"audio/webm": "webm", "video/webm": "webm", "audio/ogg": "ogg",
38 "audio/wav": "wav", "audio/wave": "wav", "audio/x-wav": "wav", "audio/vnd.wave": "wav"}
39DEMUX = {"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).
42WHISPER_PIN = "0b3d63f4a90d5df14031479ed039fe1f96ffc52fff8b193e85f71daa3762ed5a"
43# ggerganov/whisper.cpp model repo revision 5359861c739e955e79d9a303bcbc70fb988958b1 (LFS sha256).
44MODEL_PINS = {"a03779c86df3323075f5e796cb2ce5029f00ec8869eee3fdfb897afe36c6d002": "base.en",
45 "921e4cf8686fdd993dcd081a5da5b6c365bfde1162e72b08d75ac75289920b1f": "tiny.en"}
46
47
48def 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
58def 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("<I", data, pos + 4)[0]
63 body = pos + 8
64 if cid == b"fmt ":
65 if size < 16 or body + 16 > len(data):
66 return "the WAV format chunk is truncated"
67 tag, ch, rate, _, _, bits = struct.unpack_from("<HHIIHH", data, body)
68 if tag not in (1, 0xFFFE) or bits != 16 or ch not in (1, 2) or not 8000 <= rate <= 48000:
69 return "only 16-bit PCM WAV, mono or stereo, 8 to 48 kHz"
70 fmt = (rate, ch)
71 elif cid == b"data":
72 if fmt is None:
73 return "the WAV data chunk comes before its format"
74 end = min(body + size, len(data))
75 n = (end - body) // (2 * fmt[1]) * (2 * fmt[1])
76 return memoryview(data)[body:body + n], fmt[0], fmt[1]
77 pos = body + size + (size & 1)
78 return "the WAV file has no audio data"
79
80
81def wav_header(n):
82 return (b"RIFF" + struct.pack("<I", 36 + n) + b"WAVEfmt " + struct.pack("<IHHIIHH", 16, 1, 1, RATE, RATE * 2, 2, 16)
83 + b"data" + struct.pack("<I", n))
84
85
86def sha256_file(path):
87 h = hashlib.sha256()
88 with open(path, "rb") as f:
89 for block in iter(lambda: f.read(1 << 20), b""):
90 h.update(block)
91 return h.hexdigest()
92
93
94def limits(cpu_s, mem):
95 def apply():
96 os.setsid()
97 resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s + 1))
98 resource.setrlimit(resource.RLIMIT_AS, (mem, mem))
99 resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0))
100 resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
101 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
102 return apply
103
104
105def run(binds, argv, data, wall_s, out_cap, cpu_s, mem):
106 """One sandboxed run, stdin to stdout. Nothing is bound writable; /tmp is a 1 MiB tmpfs."""
107 cmd = [BWRAP, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", "--cap-drop", "ALL"]
108 for src, dst in binds:
109 cmd += ["--ro-bind", src, dst]
110 cmd += ["--size", str(1 << 20), "--tmpfs", "/tmp", "--dev", "/dev", "--remount-ro", "/", "--chdir", "/tmp",
111 "--"] + argv
112 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
113 preexec_fn=limits(cpu_s, mem), close_fds=True)
114 try:
115 out, err = p.communicate(data, timeout=wall_s)
116 except subprocess.TimeoutExpired:
117 os.killpg(p.pid, signal.SIGKILL)
118 p.communicate()
119 return None, b"timeout", -9
120 if len(out) > out_cap:
121 return None, b"output too large", -1
122 return out, err[-2048:], p.returncode
123
124
125class 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("<I", 36 + len(pcm)) + b"WAVEfmt "
186 + struct.pack("<IHHIIHH", 16, 1, ch, rate, rate * ch * 2, ch * 2, 16)
187 + b"data" + struct.pack("<I", len(pcm))) + pcm
188 pcm.release()
189 else:
190 pcm = self.decode(data, kind)
191 if isinstance(pcm, str):
192 return pcm
193 seconds = len(pcm) / (2.0 * RATE)
194 wav = bytearray(wav_header(len(pcm))) + pcm
195 pcm[:] = bytes(len(pcm))
196 try:
197 if seconds < MIN_SECONDS:
198 return "the clip is too short"
199 argv = ["/tool", "-m", "/model", "-t", str(self.threads), "-l", "en", "-bs", "1", "-bo", "1",
200 # With stdin input whisper-cli would name its output "-" and open /dev/stdout,
201 # which needs /proc; a named -of (no -o* format, so no file is written)
202 # keeps its segment printer on stdout instead.
203 "-nt", "-np", "-sns", "-of", "/tmp/none", "-f", "-"]
204 out, err, rc = run([(self.whisper, "/tool"), (self.model, "/model")], argv, wav, 15, 64 << 10,
205 60, 1 << 30)
206 finally:
207 wav[:] = bytes(len(wav))
208 if rc != 0 or out is None:
209 return "transcription failed (%s)" % ("timeout" if rc == -9 else "exit %d" % rc)
210 return clean(out.decode("utf-8", "replace")), seconds
211
212
213def clean(text):
214 """Join segment lines; drop whisper's non-speech markers such as [BLANK_AUDIO] and (music)."""
215 words = []
216 for line in text.splitlines():
217 line = line.strip()
218 while line[:1] in "[(" and line[-1:] in "])" and line:
219 close = "]" if line[0] == "[" else ")"
220 cut = line.find(close)
221 line = line[cut + 1:].strip() if cut >= 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.
231ODD = re.compile(r"\b(?:Ayen|Aien|Aian|Een|Eean|Ean)\b", re.I)
232VOCATIVE = 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
236def aien(text):
237 text = ODD.sub("Aien", text)
238 return VOCATIVE.sub(lambda m: m.group(1) + "Aien", text)
239
240
241def 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})