返回 last30days-skill
transcribe.py
根目录 / skills / last30days / scripts / lib / transcribe.py
1 """Caption-free transcription: compress -> chunk -> provider-fallback.
2
3 When a video/audio item has no captions, this turns the media into text via a
4 Whisper API. Source-agnostic: the input is a media URL or local path, the output
5 is transcript text. The pipeline:
6
7 1. Acquire audio (yt-dlp for a URL, or use a local file as-is).
8 2. Re-encode to a low-bitrate mono stream so most clips fit under the provider
9 upload limit.
10 3. If still over the limit, split into bounded-duration chunks.
11 4. Transcribe each chunk through an ordered provider list (Groq free tier
12 first, OpenAI paid backstop), with per-chunk fallback, then join.
13
14 Never raises. Returns a typed :class:`TranscriptResult`; missing prerequisites
15 (no ffmpeg, no provider key) yield a degraded result with a reason, consumed by
16 the source-health layer, rather than a crash.
17 """
18
19 from __future__ import annotations
20
21 import os
22 import re
23 import secrets
24 import selectors
25 import shutil
26 import socket
27 import tempfile
28 import threading
29 from dataclasses import dataclass, field
30 from typing import Callable, Optional
31 from urllib.parse import urlsplit
32
33 from . import auth_safety, env, health, http, log, public_host, subproc, usage
34
35 # Whisper's documented upload ceiling. We compress to stay under it and chunk
36 # when a single clip still exceeds it.
37 MAX_UPLOAD_BYTES = 25 * 1024 * 1024
38 MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024
39 MAX_DOWNLOAD_SIZE_ARG = "200M"
40 CHUNK_SECONDS = 600 # 10-minute chunks when splitting is required
41 _PROXY_MAX_HEADER_BYTES = 64 * 1024
42 _PROXY_MAX_REQUEST_BODY_BYTES = 1024 * 1024
43 _PROXY_CHUNK_BYTES = 65536
44 _HTTP_METHOD_RE = re.compile(r"^[A-Z]+$")
45 _HOP_BY_HOP_HEADERS = frozenset({
46 "connection",
47 "keep-alive",
48 "proxy-authenticate",
49 "proxy-authorization",
50 "proxy-connection",
51 "te",
52 "trailers",
53 "upgrade",
54 })
55
56 _PROVIDER_ENDPOINTS = {
57 "groq": "https://api.groq.com/openai/v1/audio/transcriptions",
58 "openai": "https://api.openai.com/v1/audio/transcriptions",
59 }
60 _PROVIDER_MODELS = {
61 "groq": "whisper-large-v3",
62 "openai": "whisper-1",
63 }
64
65
66 @dataclass
67 class TranscriptResult:
68 text: str = ""
69 ok: bool = False
70 reason: str = ""
71 provider: str = ""
72 chunks: int = 0
73 health: Optional[health.SourceHealth] = field(default=None)
74
75
76 def is_available(config: dict) -> bool:
77 """True when ffmpeg is present AND at least one Whisper provider key is set."""
78 return bool(shutil.which("ffmpeg")) and bool(env.transcription_providers(config))
79
80
81 def transcribe_media(
82 source: str,
83 config: dict,
84 timeout: float = 120.0,
85 ) -> TranscriptResult:
86 """Transcribe a media URL or local path. Never raises.
87
88 Returns a degraded result (ok=False, reason set) when prerequisites are
89 missing or every provider fails, so callers can report the gap honestly.
90 """
91 if not shutil.which("ffmpeg"):
92 return _degraded("ffmpeg not installed", health.MISSING)
93 providers = env.transcription_providers(config)
94 if not providers:
95 return _degraded(
96 "no transcription provider key (set GROQ_API_KEY or OPENAI_API_KEY)",
97 health.MISSING,
98 )
99
100 workdir = tempfile.mkdtemp(prefix="l30d-transcribe-")
101 try:
102 audio_path = _acquire_audio(source, workdir, timeout=timeout)
103 if not audio_path:
104 return _degraded("could not acquire/compress audio", health.ERROR)
105
106 chunk_paths = _chunk_audio(audio_path, workdir)
107 if not chunk_paths:
108 return _degraded("audio chunking produced no segments", health.ERROR)
109
110 texts: list[str] = []
111 used_provider = ""
112 for chunk in chunk_paths:
113 chunk_text, provider = _transcribe_chunk(chunk, providers, timeout=timeout)
114 if chunk_text is None:
115 return _degraded(
116 f"all providers failed on a chunk ({len(texts)}/{len(chunk_paths)} done)",
117 health.ERROR,
118 )
119 texts.append(chunk_text)
120 used_provider = provider or used_provider
121
122 joined = "\n".join(t.strip() for t in texts if t.strip())
123 if not joined:
124 return _degraded("transcription produced empty text", health.DEGRADED)
125 return TranscriptResult(
126 text=joined,
127 ok=True,
128 provider=used_provider,
129 chunks=len(chunk_paths),
130 health=health.SourceHealth(name="transcribe", state=health.OK),
131 )
132 finally:
133 shutil.rmtree(workdir, ignore_errors=True)
134
135
136 def _degraded(reason: str, state: str) -> TranscriptResult:
137 return TranscriptResult(
138 ok=False,
139 reason=reason,
140 health=health.SourceHealth(name="transcribe", state=state, reason=reason),
141 )
142
143
144 _ASF_GUID = b"\x30\x26\xb2\x75\x8e\x66\xcf\x11\xa6\xd9\x00\xaa\x00\x62\xce\x6c"
145
146
147 def _detect_safe_audio_demuxer(path: str) -> Optional[str]:
148 """Identify an explicit self-contained ffmpeg demuxer from magic bytes, or None.
149
150 Rejects playlists/manifests (HLS #EXTM3U, ffconcat, DASH XML, SDP) and any
151 unrecognized file so ffmpeg cannot follow external local file references.
152 """
153 try:
154 with open(path, "rb") as fh:
155 header = fh.read(32)
156 except OSError:
157 return None
158 if len(header) < 4:
159 return None
160 if len(header) >= 12 and header[4:8] == b"ftyp":
161 return "mov,mp4,m4a,3gp,3g2,mj2"
162 if header.startswith(b"\x1a\x45\xdf\xa3"):
163 return "matroska,webm"
164 if header.startswith(b"OggS"):
165 return "ogg"
166 if header.startswith(b"fLaC"):
167 return "flac"
168 if len(header) >= 12 and header[:4] == b"RIFF" and header[8:12] == b"WAVE":
169 return "wav"
170 if len(header) >= 12 and header[:4] == b"FORM" and header[8:12] in (b"AIFF", b"AIFC"):
171 return "aiff"
172 if header.startswith(b"ID3"):
173 return "mp3"
174 if header[0] == 0xFF and (header[1] & 0xF6) == 0xF0:
175 return "aac"
176 if header[0] == 0xFF and (header[1] & 0xE0) == 0xE0 and (header[1] & 0x06) != 0x00:
177 return "mp3"
178 if header.startswith(_ASF_GUID):
179 return "asf"
180 return None
181
182
183 def _is_safe_remote_media_url(source: str) -> bool:
184 """Return True only for http(s) URLs with valid public host syntax.
185
186 DNS resolution is deferred to ``_PublicMediaProxy`` so slow DNS remains
187 inside the downloader's timeout budget and every hop is pinned at connect time.
188 """
189 if not isinstance(source, str) or not source or source.startswith("-"):
190 return False
191 try:
192 parts = urlsplit(source)
193 except ValueError:
194 return False
195 if "\\" in parts.netloc:
196 return False
197 return public_host.is_public_address_syntax(source)
198
199
200 def _sanitized_ytdlp_env(proxy_url: str) -> dict[str, str]:
201 """Pin proxy env vars and clear NO_PROXY so yt-dlp cannot bypass the validating proxy."""
202 clean = {
203 k: v
204 for k, v in os.environ.items()
205 if k.lower() not in ("http_proxy", "https_proxy", "all_proxy", "no_proxy")
206 }
207 clean["HTTP_PROXY"] = proxy_url
208 clean["HTTPS_PROXY"] = proxy_url
209 clean["http_proxy"] = proxy_url
210 clean["https_proxy"] = proxy_url
211 clean["NO_PROXY"] = ""
212 clean["no_proxy"] = ""
213 return clean
214
215
216 class _PublicMediaProxy:
217 """Loopback HTTP/CONNECT proxy enforcing public-IP pinning and mid-transfer byte caps.
218
219 Every yt-dlp hop — initial URL, 3xx redirects, HLS/DASH manifests and segments,
220 and HTTPS CONNECT tunnels — resolves fresh and connects only to verified public IPs,
221 closing active sockets immediately once cumulative downstream bytes exceed ``max_bytes``.
222 """
223
224 def __init__(
225 self,
226 *,
227 max_bytes: int = MAX_DOWNLOAD_BYTES,
228 connect_timeout: float = 15.0,
229 io_timeout: float = 60.0,
230 resolver: Optional[Callable[[str, int], list[tuple]]] = None,
231 ) -> None:
232 self._max_bytes = max_bytes
233 self._connect_timeout = connect_timeout
234 self._io_timeout = max(connect_timeout, io_timeout)
235 self._resolver = resolver or public_host.resolve_public_addresses
236 self._lock = threading.Lock()
237 self._bytes_transferred = 0
238 self._blocked_count = 0
239 self._limit_exceeded = False
240 self._closed = False
241 self._active_sockets: set[socket.socket] = set()
242 self._server: Optional[socket.socket] = None
243 self._thread: Optional[threading.Thread] = None
244 self.port: int = 0
245
246 @property
247 def url(self) -> str:
248 return f"http://127.0.0.1:{self.port}"
249
250 @property
251 def limit_exceeded(self) -> bool:
252 with self._lock:
253 return self._limit_exceeded
254
255 @property
256 def blocked_count(self) -> int:
257 with self._lock:
258 return self._blocked_count
259
260 def _note_blocked(self) -> None:
261 with self._lock:
262 self._blocked_count += 1
263
264 def __enter__(self) -> "_PublicMediaProxy":
265 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
266 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
267 srv.bind(("127.0.0.1", 0))
268 srv.listen(32)
269 srv.settimeout(0.2)
270 self._server = srv
271 self.port = srv.getsockname()[1]
272 self._thread = threading.Thread(
273 target=self._accept_loop, name="l30d-media-proxy", daemon=True,
274 )
275 self._thread.start()
276 return self
277
278 def __exit__(self, *exc) -> None:
279 self.close()
280
281 def close(self) -> None:
282 with self._lock:
283 self._closed = True
284 sockets = list(self._active_sockets)
285 self._active_sockets.clear()
286 srv = self._server
287 self._server = None
288 if srv is not None:
289 try:
290 srv.close()
291 except OSError:
292 pass
293 for sock in sockets:
294 try:
295 sock.shutdown(socket.SHUT_RDWR)
296 except OSError:
297 pass
298 try:
299 sock.close()
300 except OSError:
301 pass
302 if self._thread is not None and self._thread.is_alive():
303 self._thread.join(timeout=2.0)
304
305 def _track_socket(self, sock: socket.socket) -> bool:
306 with self._lock:
307 if self._closed:
308 return False
309 self._active_sockets.add(sock)
310 return True
311
312 def _untrack_socket(self, sock: socket.socket) -> None:
313 with self._lock:
314 self._active_sockets.discard(sock)
315 try:
316 sock.close()
317 except OSError:
318 pass
319
320 def _abort_all_connections(self) -> None:
321 with self._lock:
322 sockets = list(self._active_sockets)
323 for sock in sockets:
324 try:
325 sock.shutdown(socket.SHUT_RDWR)
326 except OSError:
327 pass
328
329 def _account_bytes(self, count: int) -> bool:
330 if count <= 0:
331 return True
332 with self._lock:
333 if self._closed or self._limit_exceeded:
334 return False
335 self._bytes_transferred += count
336 if self._bytes_transferred > self._max_bytes:
337 self._limit_exceeded = True
338 return False
339 return True
340
341 def _accept_loop(self) -> None:
342 while True:
343 srv = self._server
344 if srv is None:
345 return
346 try:
347 client, _addr = srv.accept()
348 except socket.timeout:
349 with self._lock:
350 if self._closed:
351 return
352 continue
353 except OSError:
354 return
355 if not self._track_socket(client):
356 try:
357 client.close()
358 except OSError:
359 pass
360 return
361 threading.Thread(
362 target=self._handle_client, args=(client,), daemon=True,
363 ).start()
364
365 def _connect_public(self, host: str, port: int) -> socket.socket:
366 if (
367 not host
368 or not isinstance(port, int)
369 or port < 1
370 or port > 65535
371 or "\\" in host
372 or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in host)
373 ):
374 raise public_host.NonPublicAddressError("refused invalid proxy destination")
375 verified = self._resolver(host, port)
376 last_err: Optional[OSError] = None
377 for af, socktype, proto, _canonname, sockaddr in verified:
378 sock: Optional[socket.socket] = None
379 try:
380 sock = socket.socket(af, socktype, proto)
381 sock.settimeout(self._connect_timeout)
382 sock.connect(sockaddr)
383 sock.settimeout(self._io_timeout)
384 if not self._track_socket(sock):
385 sock.close()
386 raise OSError("proxy closed")
387 return sock
388 except OSError as exc:
389 last_err = exc
390 if sock is not None:
391 try:
392 sock.close()
393 except OSError:
394 pass
395 if last_err is not None:
396 raise last_err
397 raise public_host.NonPublicAddressError("refused non-public address")
398
399 @staticmethod
400 def _send_error(client: socket.socket, status: str) -> None:
401 try:
402 client.sendall(f"HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n".encode("ascii"))
403 except OSError:
404 pass
405
406 def _handle_client(self, client: socket.socket) -> None:
407 try:
408 client.settimeout(self._connect_timeout)
409 buf = bytearray()
410 while b"\r\n\r\n" not in buf:
411 chunk = client.recv(4096)
412 if not chunk:
413 return
414 buf.extend(chunk)
415 if len(buf) > _PROXY_MAX_HEADER_BYTES:
416 self._send_error(client, "431 Request Header Fields Too Large")
417 return
418 header_end = buf.index(b"\r\n\r\n")
419 header_blob = bytes(buf[:header_end])
420 remainder = bytes(buf[header_end + 4:])
421
422 lines = header_blob.split(b"\r\n")
423 if not lines:
424 self._send_error(client, "400 Bad Request")
425 return
426 try:
427 req_line = lines[0].decode("latin-1")
428 except UnicodeDecodeError:
429 self._send_error(client, "400 Bad Request")
430 return
431 parts = req_line.split(" ")
432 if len(parts) != 3:
433 self._send_error(client, "400 Bad Request")
434 return
435 method, target, version = parts
436 if not _HTTP_METHOD_RE.fullmatch(method) or not version.startswith("HTTP/"):
437 self._send_error(client, "400 Bad Request")
438 return
439
440 if self.limit_exceeded:
441 self._send_error(client, "413 Payload Too Large")
442 return
443
444 if method == "CONNECT":
445 self._handle_connect(client, target, remainder)
446 else:
447 self._handle_http(client, method, target, lines[1:], remainder)
448 except OSError:
449 pass
450 finally:
451 self._untrack_socket(client)
452
453 def _handle_connect(
454 self,
455 client: socket.socket,
456 target: str,
457 remainder: bytes,
458 ) -> None:
459 if "\\" in target or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in target):
460 self._send_error(client, "400 Bad Request")
461 return
462 try:
463 parsed = urlsplit(f"//{target}")
464 port = parsed.port
465 except ValueError:
466 self._send_error(client, "400 Bad Request")
467 return
468 if (
469 not parsed.hostname
470 or port is None
471 or parsed.username is not None
472 or parsed.password is not None
473 or parsed.path
474 or parsed.query
475 or parsed.fragment
476 ):
477 self._send_error(client, "400 Bad Request")
478 return
479 try:
480 upstream = self._connect_public(parsed.hostname, port)
481 except (public_host.NonPublicAddressError, ValueError):
482 self._note_blocked()
483 self._send_error(client, "403 Forbidden")
484 return
485 except OSError:
486 self._send_error(client, "502 Bad Gateway")
487 return
488
489 try:
490 client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
491 if remainder:
492 upstream.sendall(remainder)
493
494 sel = selectors.DefaultSelector()
495 try:
496 sel.register(client, selectors.EVENT_READ, "client")
497 sel.register(upstream, selectors.EVENT_READ, "upstream")
498 client_eof = False
499 upstream_eof = False
500 while not (client_eof and upstream_eof):
501 with self._lock:
502 if self._closed or self._limit_exceeded:
503 break
504 events = sel.select(timeout=0.5)
505 for key, _mask in events:
506 if key.data == "client":
507 data = client.recv(_PROXY_CHUNK_BYTES)
508 if not data:
509 client_eof = True
510 sel.unregister(client)
511 try:
512 upstream.shutdown(socket.SHUT_WR)
513 except OSError:
514 pass
515 else:
516 upstream.sendall(data)
517 else:
518 data = upstream.recv(_PROXY_CHUNK_BYTES)
519 if not data:
520 upstream_eof = True
521 sel.unregister(upstream)
522 try:
523 client.shutdown(socket.SHUT_WR)
524 except OSError:
525 pass
526 else:
527 if not self._account_bytes(len(data)):
528 self._abort_all_connections()
529 return
530 client.sendall(data)
531 finally:
532 sel.close()
533 finally:
534 self._untrack_socket(upstream)
535
536 def _handle_http(
537 self,
538 client: socket.socket,
539 method: str,
540 target: str,
541 raw_headers: list[bytes],
542 remainder: bytes,
543 ) -> None:
544 if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in target):
545 self._send_error(client, "400 Bad Request")
546 return
547 try:
548 parsed = urlsplit(target)
549 port = parsed.port
550 except ValueError:
551 self._send_error(client, "400 Bad Request")
552 return
553 if (
554 parsed.scheme.lower() != "http"
555 or not parsed.hostname
556 or parsed.username is not None
557 or parsed.password is not None
558 or "\\" in parsed.netloc
559 ):
560 self._note_blocked()
561 self._send_error(client, "403 Forbidden")
562 return
563 effective_port = port if port is not None else 80
564 try:
565 upstream = self._connect_public(parsed.hostname, effective_port)
566 except (public_host.NonPublicAddressError, ValueError):
567 self._note_blocked()
568 self._send_error(client, "403 Forbidden")
569 return
570 except OSError:
571 self._send_error(client, "502 Bad Gateway")
572 return
573
574 try:
575 forwarded_headers: list[tuple[str, str]] = []
576 has_host = False
577 content_length = 0
578 for line in raw_headers:
579 if not line or b":" not in line:
580 continue
581 name_b, val_b = line.split(b":", 1)
582 name = name_b.decode("latin-1").strip()
583 val = val_b.decode("latin-1").strip()
584 lower = name.lower()
585 if lower in _HOP_BY_HOP_HEADERS:
586 continue
587 if lower == "transfer-encoding":
588 self._send_error(client, "501 Not Implemented")
589 return
590 if lower == "content-length":
591 try:
592 content_length = int(val)
593 except ValueError:
594 self._send_error(client, "400 Bad Request")
595 return
596 if content_length < 0 or content_length > _PROXY_MAX_REQUEST_BODY_BYTES:
597 self._send_error(client, "413 Payload Too Large")
598 return
599 if lower == "host":
600 has_host = True
601 forwarded_headers.append((name, val))
602 if not has_host:
603 forwarded_headers.insert(0, ("Host", parsed.netloc))
604 forwarded_headers.append(("Connection", "close"))
605
606 origin_target = (parsed.path or "/") + (f"?{parsed.query}" if parsed.query else "")
607 head = [f"{method} {origin_target} HTTP/1.1"]
608 head.extend(f"{k}: {v}" for k, v in forwarded_headers)
609 upstream.sendall(("\r\n".join(head) + "\r\n\r\n").encode("latin-1"))
610
611 if content_length > 0:
612 body_chunks = [remainder[:content_length]]
613 remaining = content_length - len(body_chunks[0])
614 while remaining > 0:
615 chunk = client.recv(min(_PROXY_CHUNK_BYTES, remaining))
616 if not chunk:
617 break
618 body_chunks.append(chunk)
619 remaining -= len(chunk)
620 upstream.sendall(b"".join(body_chunks))
621
622 while True:
623 chunk = upstream.recv(_PROXY_CHUNK_BYTES)
624 if not chunk:
625 break
626 if not self._account_bytes(len(chunk)):
627 self._abort_all_connections()
628 return
629 client.sendall(chunk)
630 finally:
631 self._untrack_socket(upstream)
632
633
634 def _acquire_audio(source: str, workdir: str, timeout: float) -> Optional[str]:
635 """Produce a compressed mono/16kHz/low-bitrate audio file, or None.
636
637 For a URL, extract audio with yt-dlp; for a local path, transcode it. The
638 re-encode keeps most clips under the upload ceiling.
639 """
640 if not isinstance(source, str) or not source:
641 return None
642 if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in source):
643 return None
644
645 abs_workdir = os.path.abspath(workdir)
646 try:
647 parts = urlsplit(source)
648 except ValueError:
649 return None
650 scheme = parts.scheme.lower()
651
652 demuxer: Optional[str] = None
653 if scheme in ("http", "https"):
654 if not _is_safe_remote_media_url(source):
655 log.debug(f"transcribe: refused unsafe media URL: {source!r}")
656 return None
657 raw = os.path.join(abs_workdir, "raw.m4a")
658 with _PublicMediaProxy(
659 max_bytes=MAX_DOWNLOAD_BYTES,
660 connect_timeout=min(15.0, max(1.0, float(timeout))),
661 io_timeout=max(15.0, float(timeout)),
662 ) as media_proxy:
663 ok = _run([
664 "yt-dlp",
665 "--ignore-config",
666 "--no-plugin-dirs",
667 "--no-cookies-from-browser",
668 "--no-playlist",
669 "--no-live-from-start",
670 "--match-filter", "!is_live",
671 "--max-filesize", MAX_DOWNLOAD_SIZE_ARG,
672 "--downloader", "dash,m3u8:native",
673 "--proxy", media_proxy.url,
674 "-f", "bestaudio[protocol*=http]/bestaudio[protocol^=m3u8]",
675 "-o", raw,
676 "--",
677 source,
678 ], timeout=timeout, env=_sanitized_ytdlp_env(media_proxy.url))
679 if not ok or media_proxy.limit_exceeded:
680 return None
681 if not os.path.isfile(raw):
682 return None
683 try:
684 if os.path.getsize(raw) > MAX_DOWNLOAD_BYTES:
685 return None
686 except OSError:
687 return None
688 # Require an explicit self-contained container format on remote downloads
689 # so ffmpeg cannot parse a downloaded HLS/ffconcat playlist and read local files.
690 demuxer = _detect_safe_audio_demuxer(raw)
691 if demuxer is None:
692 log.debug("transcribe: refused downloaded media with unrecognized or playlist format")
693 return None
694 elif "://" in source or (scheme and len(scheme) > 1):
695 # Reject non-http(s) URI schemes and ffmpeg protocol prefixes (file://, ftp://, concat:, etc.).
696 log.debug(f"transcribe: refused unsupported media scheme: {source!r}")
697 return None
698 else:
699 raw = os.path.abspath(source)
700 if not os.path.isfile(raw):
701 return None
702 demuxer = _detect_safe_audio_demuxer(raw)
703
704 out = os.path.join(abs_workdir, "audio.mp3")
705 # Mono, 16kHz, 32kbps keeps speech intelligible while shrinking the file.
706 ffmpeg_cmd = [
707 "ffmpeg",
708 "-nostdin",
709 "-y",
710 "-protocol_whitelist", "file",
711 ]
712 if demuxer is not None:
713 ffmpeg_cmd.extend(["-f", demuxer])
714 ffmpeg_cmd.extend([
715 "-i", raw,
716 "-vn",
717 "-map_metadata", "-1",
718 "-ac", "1",
719 "-ar", "16000",
720 "-b:a", "32k",
721 out,
722 ])
723 if not _run(ffmpeg_cmd, timeout=timeout):
724 return None
725 return out if os.path.isfile(out) else None
726
727
728 def _chunk_audio(audio_path: str, workdir: str) -> list[str]:
729 """Return [audio_path] when small enough, else ffmpeg-segmented chunk paths."""
730 try:
731 size = os.path.getsize(audio_path)
732 except OSError:
733 return []
734 if size <= MAX_UPLOAD_BYTES:
735 return [audio_path]
736
737 abs_workdir = os.path.abspath(workdir)
738 abs_audio = os.path.abspath(audio_path)
739 pattern = os.path.join(abs_workdir, "chunk_%03d.mp3")
740 if not _run([
741 "ffmpeg",
742 "-nostdin",
743 "-y",
744 "-protocol_whitelist", "file",
745 "-i", abs_audio,
746 "-map_metadata", "-1",
747 "-f", "segment",
748 "-segment_time", str(CHUNK_SECONDS),
749 "-c", "copy",
750 pattern,
751 ]):
752 # Fall back to the single (oversized) file; the provider may still accept it.
753 return [audio_path]
754 chunks = sorted(
755 os.path.join(abs_workdir, f) for f in os.listdir(abs_workdir) if f.startswith("chunk_")
756 )
757 return chunks or [audio_path]
758
759
760 _SAFE_UPLOAD_FILENAME_RE = re.compile(r"^[A-Za-z0-9_-]+\.mp3$")
761
762
763 def _safe_upload_filename(path: str) -> str:
764 """Return a strictly sanitized ASCII upload filename for Content-Disposition."""
765 name = os.path.basename(path or "")
766 if _SAFE_UPLOAD_FILENAME_RE.fullmatch(name):
767 return name
768 return "audio.mp3"
769
770
771 def _generate_multipart_boundary(audio: bytes) -> str:
772 """Generate a per-request CSPRNG multipart boundary absent from ``audio``."""
773 for _ in range(16):
774 candidate = f"----l30d-{secrets.token_hex(16)}"
775 if candidate.encode("ascii") not in audio:
776 return candidate
777 raise ValueError("Unable to generate collision-free multipart boundary")
778
779
780 def _transcribe_chunk(
781 path: str,
782 providers: list[tuple[str, str]],
783 timeout: float,
784 ) -> tuple[Optional[str], str]:
785 """Try each provider in order; return (text, provider) or (None, '')."""
786 for name, key in providers:
787 try:
788 text = _post_audio(name, path, key, timeout=timeout)
789 except Exception as exc: # noqa: BLE001 - any provider failure -> try the next
790 # Surface the failing provider + error (e.g. Groq's Cloudflare 403,
791 # "error code: 1010") under LAST30DAYS_DEBUG instead of silently
792 # degrading to an empty transcript (#983).
793 safe_exc = auth_safety.scrub_secrets(repr(exc), (key,))
794 log.debug(f"transcribe: provider {name} failed on a chunk: {safe_exc}")
795 text = None
796 if text is not None:
797 return text, name
798 return None, ""
799
800
801 def _post_audio(provider: str, path: str, api_key: str, timeout: float) -> Optional[str]:
802 """POST one audio file to a Whisper-compatible endpoint; return text or None."""
803 import json
804 import urllib.request
805
806 clean_key, key_err = auth_safety.normalize_header_token(api_key)
807 if key_err or not clean_key:
808 raise ValueError(key_err or "Invalid token format")
809
810 endpoint = _PROVIDER_ENDPOINTS[provider]
811 model = _PROVIDER_MODELS[provider]
812 with open(path, "rb") as fh:
813 audio = fh.read()
814 boundary = _generate_multipart_boundary(audio)
815 filename = _safe_upload_filename(path)
816
817 parts: list[bytes] = []
818 parts.append(f"--{boundary}\r\n".encode("ascii"))
819 parts.append(b'Content-Disposition: form-data; name="model"\r\n\r\n')
820 parts.append(f"{model}\r\n".encode("ascii"))
821 parts.append(f"--{boundary}\r\n".encode("ascii"))
822 parts.append(
823 (
824 f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
825 "Content-Type: audio/mpeg\r\n\r\n"
826 ).encode("ascii")
827 )
828 parts.append(audio)
829 parts.append(f"\r\n--{boundary}--\r\n".encode("ascii"))
830 body = b"".join(parts)
831
832 req = urllib.request.Request(
833 endpoint,
834 data=body,
835 headers={
836 "Authorization": f"Bearer {clean_key}",
837 "Content-Type": f"multipart/form-data; boundary={boundary}",
838 # A plain-urllib UA is fingerprinted and 403'd by Cloudflare-style
839 # edges (Groq returns "error code: 1010", #983). Send the skill's
840 # canonical identity instead, same as lib/http.py's get/post.
841 "User-Agent": http.USER_AGENT,
842 },
843 method="POST",
844 )
845 usage.begin(provider)
846 with http.open_request(req, timeout) as resp:
847 data = json.loads(resp.read().decode("utf-8"))
848 return data.get("text")
849
850
851 def _run(
852 command: list[str],
853 timeout: float = 120.0,
854 *,
855 env: Optional[dict[str, str]] = None,
856 ) -> bool:
857 """Run a subprocess; return True on exit 0, False on any failure. No raise.
858
859 Uses subproc.run_with_timeout so a timed-out yt-dlp/ffmpeg is killed at the
860 process-group level (os.setsid/killpg) instead of orphaning child trees.
861 """
862 try:
863 kwargs: dict = {"timeout": int(timeout)}
864 if env is not None:
865 kwargs["env"] = env
866 result = subproc.run_with_timeout(command, **kwargs)
867 except (subproc.SubprocTimeout, FileNotFoundError, OSError):
868 return False
869 return result.returncode == 0
870
870 lines PYTHON