nxdev-org commited on
Commit
6fdd6ee
·
verified ·
1 Parent(s): e0e78e6

Deploy TTS + podcast modules

Browse files
Files changed (3) hide show
  1. README.md +6 -5
  2. app.py +4 -2
  3. podcast.py +95 -16
README.md CHANGED
@@ -18,16 +18,17 @@ One Space running independent modules, each its own FastAPI app (`app.py` mounts
18
  |---|---|---|
19
  | `tts` | `kokoro_tts.py` | `/v1/audio/speech`, `/v1/models`, `/v1/audio/voices` |
20
  | `stt` | `whisper_stt.py` | `/v1/audio/transcriptions`, `/v1/audio/translations` |
21
- | `podcast` | `podcast.py` (from `youtube-podcast/`) | `/podcast/` page; it asks for `API_KEY` and gives signed feed URLs |
22
 
23
- Set `MODULES` (default `tts,stt,podcast`) to choose which load. `GET /` lists loaded and failed modules.
24
  The `API_KEY` secret protects every module: TTS and STT need `Authorization: Bearer <key>`; the podcast
25
  page asks for it and hands out feed URLs signed for one channel, so podcast apps never see the key
26
  (set a separate `ACCESS_KEY` to use a different key for the podcast page). Podcast settings are described in `youtube-podcast/README.md`.
27
 
28
- Episodes downloaded by the podcast module are transcribed with Whisper in the background; the feed
29
- then links each transcript with `<podcast:transcript>` (VTT and SRT), which AntennaPod, Pocket Casts,
30
- Podverse and others display. `TRANSCRIPTS=off` turns this off.
 
31
 
32
  Deploy from the repo with `HF_TOKEN=... python hf-space/deploy.py <user>/<space>`.
33
 
 
18
  |---|---|---|
19
  | `tts` | `kokoro_tts.py` | `/v1/audio/speech`, `/v1/models`, `/v1/audio/voices` |
20
  | `stt` | `whisper_stt.py` | `/v1/audio/transcriptions`, `/v1/audio/translations` |
21
+ | `podcast` | `podcast.py` (from `youtube-podcast/`) | `/podcast/` page; off by default (see below) |
22
 
23
+ Set `MODULES` (default `tts,stt`) to choose which load. `GET /` lists loaded and failed modules.
24
  The `API_KEY` secret protects every module: TTS and STT need `Authorization: Bearer <key>`; the podcast
25
  page asks for it and hands out feed URLs signed for one channel, so podcast apps never see the key
26
  (set a separate `ACCESS_KEY` to use a different key for the podcast page). Podcast settings are described in `youtube-podcast/README.md`.
27
 
28
+ **Podcast module:** Hugging Face Spaces can't connect to `www.youtube.com`, so the podcast module is
29
+ off here. Run `youtube-podcast/` on a machine that can reach YouTube and set
30
+ `WHISPER_API_URL=https://<user>-<space>.hf.space` and `WHISPER_API_KEY=<API_KEY>`: episodes are then
31
+ transcribed by this Space's STT module and the feed links each transcript with `<podcast:transcript>`.
32
 
33
  Deploy from the repo with `HF_TOKEN=... python hf-space/deploy.py <user>/<space>`.
34
 
app.py CHANGED
@@ -4,7 +4,9 @@
4
  stt whisper_stt.py OpenAI-compatible Whisper STT /v1/audio/transcriptions, /v1/audio/translations
5
  podcast podcast.py YouTube channels as podcasts /podcast/ (feeds at /podcast/feed/<channel>)
6
 
7
- MODULES picks which ones load (default "tts,stt,podcast"). A module that fails to import is
 
 
8
  skipped and reported at /, so one broken service doesn't take the others down.
9
 
10
  Modules either get their own path prefix (podcast -> /podcast) or, to keep OpenAI-style URLs,
@@ -28,7 +30,7 @@ AVAILABLE = {
28
  "stt": ("whisper_stt", None, "/v1/audio/transcriptions"),
29
  "podcast": ("podcast", "/podcast", "/podcast/"),
30
  }
31
- ENABLED = [m.strip() for m in os.environ.get("MODULES", "tts,stt,podcast").split(",") if m.strip()]
32
 
33
  if os.environ.get("API_KEY") and not os.environ.get("ACCESS_KEY"):
34
  os.environ["ACCESS_KEY"] = os.environ["API_KEY"]
 
4
  stt whisper_stt.py OpenAI-compatible Whisper STT /v1/audio/transcriptions, /v1/audio/translations
5
  podcast podcast.py YouTube channels as podcasts /podcast/ (feeds at /podcast/feed/<channel>)
6
 
7
+ MODULES picks which ones load (default "tts,stt"). The podcast module is off by default because
8
+ Hugging Face Spaces can't reach www.youtube.com; run youtube-podcast/ elsewhere and point its
9
+ WHISPER_API_URL at this Space for transcripts. A module that fails to import is
10
  skipped and reported at /, so one broken service doesn't take the others down.
11
 
12
  Modules either get their own path prefix (podcast -> /podcast) or, to keep OpenAI-style URLs,
 
30
  "stt": ("whisper_stt", None, "/v1/audio/transcriptions"),
31
  "podcast": ("podcast", "/podcast", "/podcast/"),
32
  }
33
+ ENABLED = [m.strip() for m in os.environ.get("MODULES", "tts,stt").split(",") if m.strip()]
34
 
35
  if os.environ.get("API_KEY") and not os.environ.get("ACCESS_KEY"):
36
  os.environ["ACCESS_KEY"] = os.environ["API_KEY"]
podcast.py CHANGED
@@ -29,9 +29,12 @@ Environment:
29
  YTDLP_MIN_INTERVAL seconds between yt-dlp runs (default 20); runs never overlap
30
  RATE_LIMIT_COOLDOWN seconds to stop contacting YouTube after a 429 / bot check (default 900,
31
  doubling on each repeat up to 6 hours, reset by a successful download)
32
- TRANSCRIPTS "auto" (default: on when whisper_stt.py and faster-whisper are installed), "on" or "off".
33
- Each downloaded episode is transcribed in the background; once ready, the feed links
34
- the transcript with <podcast:transcript>, which many podcast apps display.
 
 
 
35
  """
36
 
37
  import hashlib
@@ -80,16 +83,26 @@ PODCAST_NS = "https://podcastindex.org/namespace/1.0"
80
  ET.register_namespace("itunes", ITUNES)
81
  ET.register_namespace("podcast", PODCAST_NS)
82
 
83
- # Transcripts use the Whisper module from the same Space when it is installed.
 
84
  TRANSCRIPTS = os.environ.get("TRANSCRIPTS", "auto").lower()
85
- whisper_stt = None
 
 
 
 
86
  if TRANSCRIPTS != "off":
87
- try:
88
- import faster_whisper # noqa: F401
89
- import whisper_stt
90
- except ImportError as e:
91
- if TRANSCRIPTS == "on":
92
- raise RuntimeError("TRANSCRIPTS=on needs whisper_stt.py and faster-whisper") from e
 
 
 
 
 
93
  TRANSCRIPT_TYPES = {"vtt": "text/vtt", "srt": "application/x-subrip", "txt": "text/plain", "json": "application/json"}
94
 
95
  VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
@@ -361,14 +374,73 @@ def load_transcript(video_id: str) -> dict | None:
361
 
362
  _transcribe_queue: "queue.Queue[str]" = queue.Queue()
363
  _transcribe_pending: set[str] = set()
 
364
  _transcribe_worker: threading.Thread | None = None
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  def request_transcript(video_id: str):
368
  """Queue a background transcription of downloaded audio (one at a time, oldest request first)."""
369
  global _transcribe_worker
370
- if whisper_stt is None or transcript_path(video_id).exists() or not audio_path(video_id).exists():
371
  return
 
 
372
  with _locks_guard:
373
  if video_id in _transcribe_pending:
374
  return
@@ -384,11 +456,12 @@ def _transcribe_loop():
384
  video_id = _transcribe_queue.get()
385
  try:
386
  if audio_path(video_id).exists() and not transcript_path(video_id).exists():
387
- result = whisper_stt.transcribe(str(audio_path(video_id)))
388
  tmp = transcript_path(video_id).with_suffix(".tmp")
389
  tmp.write_text(json.dumps(result, ensure_ascii=False))
390
  tmp.replace(transcript_path(video_id))
391
  except Exception as e:
 
392
  print(f"transcript {video_id} failed: {e}", flush=True)
393
  finally:
394
  with _locks_guard:
@@ -597,6 +670,7 @@ def status(request: Request):
597
  "cached_episodes": len(list(CACHE_DIR.glob("*.m4a"))),
598
  "transcripts_pending": len(_transcribe_pending),
599
  "cookies": bool(YTDLP_COOKIES),
 
600
  }
601
 
602
 
@@ -643,16 +717,21 @@ def transcript(request: Request, video_id: str, fmt: str):
643
  check_access(request, "episode:" + video_id)
644
  if not VIDEO_ID_RE.match(video_id) or fmt not in TRANSCRIPT_TYPES:
645
  raise HTTPException(404, "Unknown transcript")
646
- if whisper_stt is None:
647
  raise HTTPException(404, "Transcripts are not enabled on this server")
648
  result = load_transcript(video_id)
649
  if result is None:
650
  request_transcript(video_id)
651
- status = "queued" if audio_path(video_id).exists() else "available after the episode audio has been downloaded"
 
 
 
 
 
652
  raise HTTPException(404, f"Transcript not ready yet ({status})", headers={"Retry-After": "600"})
653
  if fmt == "json":
654
  return result
655
- body = {"vtt": whisper_stt.to_vtt, "srt": whisper_stt.to_srt, "txt": lambda r: r["text"] + "\n"}[fmt](result)
656
  return Response(body, media_type=f"{TRANSCRIPT_TYPES[fmt]}; charset=utf-8")
657
 
658
 
 
29
  YTDLP_MIN_INTERVAL seconds between yt-dlp runs (default 20); runs never overlap
30
  RATE_LIMIT_COOLDOWN seconds to stop contacting YouTube after a 429 / bot check (default 900,
31
  doubling on each repeat up to 6 hours, reset by a successful download)
32
+ TRANSCRIPTS "auto" (default), "on" or "off". Each downloaded episode is transcribed in the
33
+ background; once ready, the feed links it with <podcast:transcript>, which many
34
+ podcast apps display. Uses WHISPER_API_URL if set, else a local whisper_stt.py.
35
+ WHISPER_API_URL an OpenAI-compatible speech-to-text server, e.g. https://<user>-<space>.hf.space
36
+ (the Space in hf-space/). Episodes are sent in 10-minute pieces.
37
+ WHISPER_API_KEY its API key (sent as a Bearer token)
38
  """
39
 
40
  import hashlib
 
83
  ET.register_namespace("itunes", ITUNES)
84
  ET.register_namespace("podcast", PODCAST_NS)
85
 
86
+ # Transcripts come from a remote OpenAI-compatible Whisper API (WHISPER_API_URL) or, when this
87
+ # module runs inside the hf-space app, from the local whisper_stt module.
88
  TRANSCRIPTS = os.environ.get("TRANSCRIPTS", "auto").lower()
89
+ WHISPER_API_URL = os.environ.get("WHISPER_API_URL", "").strip().rstrip("/")
90
+ WHISPER_API_KEY = os.environ.get("WHISPER_API_KEY", "").strip()
91
+ TRANSCRIBE_CHUNK_SECONDS = int(os.environ.get("TRANSCRIBE_CHUNK_SECONDS", "600"))
92
+ TRANSCRIBE_RETRY_AFTER = 3600
93
+ transcribe_audio = None # (path) -> {language, duration, text, segments: [{start, end, text}]}
94
  if TRANSCRIPTS != "off":
95
+ if WHISPER_API_URL:
96
+ transcribe_audio = lambda path: transcribe_remote(path) # defined further down
97
+ else:
98
+ try:
99
+ import faster_whisper # noqa: F401
100
+ import whisper_stt
101
+
102
+ transcribe_audio = whisper_stt.transcribe
103
+ except ImportError as e:
104
+ if TRANSCRIPTS == "on":
105
+ raise RuntimeError("TRANSCRIPTS=on needs WHISPER_API_URL, or whisper_stt.py and faster-whisper") from e
106
  TRANSCRIPT_TYPES = {"vtt": "text/vtt", "srt": "application/x-subrip", "txt": "text/plain", "json": "application/json"}
107
 
108
  VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
 
374
 
375
  _transcribe_queue: "queue.Queue[str]" = queue.Queue()
376
  _transcribe_pending: set[str] = set()
377
+ _transcribe_failed: dict[str, float] = {}
378
  _transcribe_worker: threading.Thread | None = None
379
 
380
 
381
+ def _timestamp(seconds: float, sep: str) -> str:
382
+ ms = int(round(seconds * 1000))
383
+ h, ms = divmod(ms, 3_600_000)
384
+ m, ms = divmod(ms, 60_000)
385
+ s, ms = divmod(ms, 1000)
386
+ return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"
387
+
388
+
389
+ def to_srt(result: dict) -> str:
390
+ return "".join(f"{i}\n{_timestamp(s['start'], ',')} --> {_timestamp(s['end'], ',')}\n{s['text']}\n\n" for i, s in enumerate(result["segments"], 1))
391
+
392
+
393
+ def to_vtt(result: dict) -> str:
394
+ return "WEBVTT\n\n" + "".join(f"{_timestamp(s['start'], '.')} --> {_timestamp(s['end'], '.')}\n{s['text']}\n\n" for s in result["segments"])
395
+
396
+
397
+ def _multipart(fields: dict[str, str], file_name: str, file_bytes: bytes) -> tuple[bytes, str]:
398
+ boundary = f"----podcast{os.urandom(8).hex()}"
399
+ parts = [f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode() for k, v in fields.items()]
400
+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{file_name}"\r\nContent-Type: audio/mpeg\r\n\r\n'.encode() + file_bytes + b"\r\n")
401
+ parts.append(f"--{boundary}--\r\n".encode())
402
+ return b"".join(parts), f"multipart/form-data; boundary={boundary}"
403
+
404
+
405
+ def transcribe_remote(path: str) -> dict:
406
+ """Transcribe with WHISPER_API_URL in TRANSCRIBE_CHUNK_SECONDS pieces of 16 kHz mono MP3, so each
407
+ upload is small (~2.5 MB per 10 minutes) and finishes well inside proxy time limits."""
408
+ probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path], capture_output=True, text=True)
409
+ duration = float(probe.stdout.strip() or 0)
410
+ language, segments, texts = None, [], []
411
+ started = time.time()
412
+ for offset in range(0, max(int(duration), 1), TRANSCRIBE_CHUNK_SECONDS):
413
+ piece = subprocess.run(
414
+ ["ffmpeg", "-v", "error", "-ss", str(offset), "-t", str(TRANSCRIBE_CHUNK_SECONDS), "-i", path,
415
+ "-ac", "1", "-ar", "16000", "-b:a", "32k", "-f", "mp3", "pipe:1"],
416
+ capture_output=True, check=True,
417
+ ).stdout
418
+ fields = {"model": "whisper-1", "response_format": "verbose_json", **({"language": language} if language else {})}
419
+ body, content_type = _multipart(fields, "audio.mp3", piece)
420
+ headers = {"Content-Type": content_type, **({"Authorization": f"Bearer {WHISPER_API_KEY}"} if WHISPER_API_KEY else {})}
421
+ req = urllib.request.Request(f"{WHISPER_API_URL}/v1/audio/transcriptions", data=body, headers=headers, method="POST")
422
+ try:
423
+ with urllib.request.urlopen(req, timeout=1800) as r:
424
+ result = json.load(r)
425
+ except urllib.error.HTTPError as e:
426
+ raise RuntimeError(f"Whisper API returned {e.code}: {e.read()[:300].decode('utf-8', 'replace')}")
427
+ language = language or result.get("language") # keep later pieces in the language of the first
428
+ for seg in result.get("segments") or [{"start": 0, "end": result.get("duration", 0), "text": result.get("text", "")}]:
429
+ if seg.get("text", "").strip():
430
+ segments.append({"id": len(segments), "start": round(seg["start"] + offset, 2), "end": round(seg["end"] + offset, 2), "text": seg["text"].strip()})
431
+ texts.append(result.get("text", "").strip())
432
+ print(f"transcribed {duration:.0f}s via {WHISPER_API_URL} in {time.time() - started:.0f}s", flush=True)
433
+ joiner = "" if language in ("zh", "ja", "yue", "chinese", "japanese") else " "
434
+ return {"language": language, "duration": round(duration, 2), "text": joiner.join(t for t in texts if t), "segments": segments}
435
+
436
+
437
  def request_transcript(video_id: str):
438
  """Queue a background transcription of downloaded audio (one at a time, oldest request first)."""
439
  global _transcribe_worker
440
+ if transcribe_audio is None or transcript_path(video_id).exists() or not audio_path(video_id).exists():
441
  return
442
+ if time.time() - _transcribe_failed.get(video_id, 0) < TRANSCRIBE_RETRY_AFTER:
443
+ return # failed recently; don't resend the audio on every feed refresh
444
  with _locks_guard:
445
  if video_id in _transcribe_pending:
446
  return
 
456
  video_id = _transcribe_queue.get()
457
  try:
458
  if audio_path(video_id).exists() and not transcript_path(video_id).exists():
459
+ result = transcribe_audio(str(audio_path(video_id)))
460
  tmp = transcript_path(video_id).with_suffix(".tmp")
461
  tmp.write_text(json.dumps(result, ensure_ascii=False))
462
  tmp.replace(transcript_path(video_id))
463
  except Exception as e:
464
+ _transcribe_failed[video_id] = time.time()
465
  print(f"transcript {video_id} failed: {e}", flush=True)
466
  finally:
467
  with _locks_guard:
 
670
  "cached_episodes": len(list(CACHE_DIR.glob("*.m4a"))),
671
  "transcripts_pending": len(_transcribe_pending),
672
  "cookies": bool(YTDLP_COOKIES),
673
+ "transcripts": ("remote " + WHISPER_API_URL) if WHISPER_API_URL and transcribe_audio else ("local" if transcribe_audio else "off"),
674
  }
675
 
676
 
 
717
  check_access(request, "episode:" + video_id)
718
  if not VIDEO_ID_RE.match(video_id) or fmt not in TRANSCRIPT_TYPES:
719
  raise HTTPException(404, "Unknown transcript")
720
+ if transcribe_audio is None:
721
  raise HTTPException(404, "Transcripts are not enabled on this server")
722
  result = load_transcript(video_id)
723
  if result is None:
724
  request_transcript(video_id)
725
+ if not audio_path(video_id).exists():
726
+ status = "available after the episode audio has been downloaded"
727
+ elif (failed_at := _transcribe_failed.get(video_id)) and time.time() - failed_at < TRANSCRIBE_RETRY_AFTER:
728
+ status = f"the last attempt failed; retrying in {(int(failed_at + TRANSCRIBE_RETRY_AFTER - time.time()) + 59) // 60} minutes"
729
+ else:
730
+ status = "queued"
731
  raise HTTPException(404, f"Transcript not ready yet ({status})", headers={"Retry-After": "600"})
732
  if fmt == "json":
733
  return result
734
+ body = {"vtt": to_vtt, "srt": to_srt, "txt": lambda r: r["text"] + "\n"}[fmt](result)
735
  return Response(body, media_type=f"{TRANSCRIPT_TYPES[fmt]}; charset=utf-8")
736
 
737