Deploy TTS + podcast modules
Browse files- README.md +4 -3
- podcast.py +90 -24
README.md
CHANGED
|
@@ -18,11 +18,12 @@ 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/`
|
| 22 |
|
| 23 |
Set `MODULES` (default `tts,stt,podcast`) to choose which load. `GET /` lists loaded and failed modules.
|
| 24 |
-
The `API_KEY` secret protects
|
| 25 |
-
|
|
|
|
| 26 |
|
| 27 |
Episodes downloaded by the podcast module are transcribed with Whisper in the background; the feed
|
| 28 |
then links each transcript with `<podcast:transcript>` (VTT and SRT), which AntennaPod, Pocket Casts,
|
|
|
|
| 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,
|
podcast.py
CHANGED
|
@@ -3,7 +3,8 @@
|
|
| 3 |
Runs on its own (`python podcast.py`) or as a module mounted into a larger FastAPI app
|
| 4 |
(`root.mount("/podcast", podcast.app)`); every link it generates respects the mount path.
|
| 5 |
|
| 6 |
-
GET /
|
|
|
|
| 7 |
GET /feed/{source} podcast RSS; source is a channel id (UC...), @handle or playlist id (PL...)
|
| 8 |
GET /feed?url=<youtube url> redirects to /feed/{source}
|
| 9 |
GET /audio/{video_id}.m4a the episode audio, downloaded with yt-dlp on first request and cached
|
|
@@ -15,8 +16,10 @@ datacenter IPs; set YTDLP_COOKIES to a cookies.txt export if that happens.
|
|
| 15 |
|
| 16 |
Environment:
|
| 17 |
BASE_URL public URL of this server, used in feed links (default: from the request)
|
| 18 |
-
ACCESS_KEY if set,
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
CACHE_DIR where audio is stored (default ./cache)
|
| 21 |
CACHE_MAX_GB oldest audio is deleted above this size (default 5)
|
| 22 |
PREFETCH newest episodes to download in the background when a feed is read (default 2)
|
|
@@ -31,6 +34,8 @@ Environment:
|
|
| 31 |
the transcript with <podcast:transcript>, which many podcast apps display.
|
| 32 |
"""
|
| 33 |
|
|
|
|
|
|
|
| 34 |
import html
|
| 35 |
import json
|
| 36 |
import os
|
|
@@ -378,11 +383,38 @@ def prefetch(video_ids: list[str]):
|
|
| 378 |
|
| 379 |
# ---------------------------------------------------------------- RSS
|
| 380 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
def check_key(request: Request):
|
| 382 |
if ACCESS_KEYS and request.query_params.get("key", "").strip() not in ACCESS_KEYS:
|
| 383 |
raise HTTPException(401, "Missing or wrong ?key=")
|
| 384 |
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
def base_url(request: Request) -> str:
|
| 387 |
"""Public URL of this app, including the mount path when it runs as a module."""
|
| 388 |
root_path = request.scope.get("root_path", "").rstrip("/")
|
|
@@ -392,8 +424,7 @@ def base_url(request: Request) -> str:
|
|
| 392 |
return f"{proto}://{request.headers.get('host', request.url.netloc)}{root_path}"
|
| 393 |
|
| 394 |
|
| 395 |
-
def build_rss(feed: dict, base: str, include_shorts: bool
|
| 396 |
-
key_query = f"?key={urllib.parse.quote(key)}" if key else ""
|
| 397 |
rss = ET.Element("rss", {"version": "2.0"})
|
| 398 |
ch = ET.SubElement(rss, "channel")
|
| 399 |
|
|
@@ -427,14 +458,14 @@ def build_rss(feed: dict, base: str, include_shorts: bool, key: str = "") -> byt
|
|
| 427 |
sub(item, "description", f"{ep['description']}\n\n{ep['link']}".strip())
|
| 428 |
path = audio_path(ep["id"])
|
| 429 |
size = str(path.stat().st_size) if path.exists() else "0"
|
| 430 |
-
sub(item, "enclosure", url=f"{base}/audio/{ep['id']}.m4a{
|
| 431 |
if ep["thumbnail"]:
|
| 432 |
sub(item, f"{{{ITUNES}}}image", href=ep["thumbnail"])
|
| 433 |
if duration := audio_meta(ep["id"]).get("duration"):
|
| 434 |
sub(item, f"{{{ITUNES}}}duration", str(duration))
|
| 435 |
if transcript := load_transcript(ep["id"]):
|
| 436 |
for fmt in ("vtt", "srt"):
|
| 437 |
-
sub(item, f"{{{PODCAST_NS}}}transcript", url=f"{base}/transcript/{ep['id']}.{fmt}{
|
| 438 |
type=TRANSCRIPT_TYPES[fmt], language=transcript.get("language") or "en")
|
| 439 |
return b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(rss, encoding="utf-8")
|
| 440 |
|
|
@@ -443,14 +474,52 @@ def build_rss(feed: dict, base: str, include_shorts: bool, key: str = "") -> byt
|
|
| 443 |
|
| 444 |
@app.get("/", response_class=HTMLResponse)
|
| 445 |
def index():
|
| 446 |
-
return ""
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
<
|
| 450 |
-
<
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
|
| 455 |
|
| 456 |
@app.get("/status")
|
|
@@ -468,28 +537,25 @@ def status(request: Request):
|
|
| 468 |
|
| 469 |
|
| 470 |
@app.get("/feed")
|
| 471 |
-
def feed_from_url(request: Request, url: str):
|
| 472 |
check_key(request)
|
| 473 |
_, ident = parse_source(url)
|
| 474 |
-
|
| 475 |
-
root_path = request.scope.get("root_path", "").rstrip("/")
|
| 476 |
-
return RedirectResponse(f"{root_path}/feed/{urllib.parse.quote(ident)}" + (f"?{query}" if query else ""), status_code=302)
|
| 477 |
|
| 478 |
|
| 479 |
@app.get("/feed/{source}")
|
| 480 |
def feed(request: Request, source: str, shorts: bool = False):
|
| 481 |
-
check_key(request)
|
| 482 |
kind, ident = parse_source(source)
|
|
|
|
| 483 |
data = load_feed(kind, ident)
|
| 484 |
if PREFETCH > 0:
|
| 485 |
prefetch([e["id"] for e in data["episodes"] if shorts or not e["short"]][:PREFETCH])
|
| 486 |
-
|
| 487 |
-
return Response(build_rss(data, base_url(request), shorts, key), media_type="application/rss+xml; charset=utf-8")
|
| 488 |
|
| 489 |
|
| 490 |
@app.api_route("/audio/{video_id}.m4a", methods=["GET", "HEAD"])
|
| 491 |
def audio(request: Request, video_id: str):
|
| 492 |
-
|
| 493 |
if not VIDEO_ID_RE.match(video_id):
|
| 494 |
raise HTTPException(404, "Unknown video id")
|
| 495 |
try:
|
|
@@ -510,7 +576,7 @@ def audio(request: Request, video_id: str):
|
|
| 510 |
|
| 511 |
@app.get("/transcript/{video_id}.{fmt}")
|
| 512 |
def transcript(request: Request, video_id: str, fmt: str):
|
| 513 |
-
|
| 514 |
if not VIDEO_ID_RE.match(video_id) or fmt not in TRANSCRIPT_TYPES:
|
| 515 |
raise HTTPException(404, "Unknown transcript")
|
| 516 |
if whisper_stt is None:
|
|
|
|
| 3 |
Runs on its own (`python podcast.py`) or as a module mounted into a larger FastAPI app
|
| 4 |
(`root.mount("/podcast", podcast.app)`); every link it generates respects the mount path.
|
| 5 |
|
| 6 |
+
GET / web page: enter the key and a YouTube link to get a feed URL
|
| 7 |
+
GET /api/feed-url?url=&key= what the page calls; returns a signed feed URL
|
| 8 |
GET /feed/{source} podcast RSS; source is a channel id (UC...), @handle or playlist id (PL...)
|
| 9 |
GET /feed?url=<youtube url> redirects to /feed/{source}
|
| 10 |
GET /audio/{video_id}.m4a the episode audio, downloaded with yt-dlp on first request and cached
|
|
|
|
| 16 |
|
| 17 |
Environment:
|
| 18 |
BASE_URL public URL of this server, used in feed links (default: from the request)
|
| 19 |
+
ACCESS_KEY if set, only the web page (and /status) needs the key; comma-separate several keys.
|
| 20 |
+
The page hands out feed URLs signed for one channel (?sig=...), and feeds sign their
|
| 21 |
+
audio and transcript links, so podcast apps never see the key and the server can't
|
| 22 |
+
be used to download arbitrary videos. ?key=<key> is still accepted everywhere.
|
| 23 |
CACHE_DIR where audio is stored (default ./cache)
|
| 24 |
CACHE_MAX_GB oldest audio is deleted above this size (default 5)
|
| 25 |
PREFETCH newest episodes to download in the background when a feed is read (default 2)
|
|
|
|
| 34 |
the transcript with <podcast:transcript>, which many podcast apps display.
|
| 35 |
"""
|
| 36 |
|
| 37 |
+
import hashlib
|
| 38 |
+
import hmac
|
| 39 |
import html
|
| 40 |
import json
|
| 41 |
import os
|
|
|
|
| 383 |
|
| 384 |
# ---------------------------------------------------------------- RSS
|
| 385 |
|
| 386 |
+
def _signature(key: str, value: str) -> str:
|
| 387 |
+
return hmac.new(key.encode(), value.encode(), hashlib.sha256).hexdigest()[:24]
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def sign(value: str) -> str:
|
| 391 |
+
"""Signature for a feed ("feed:<source>") or episode ("episode:<video id>") link."""
|
| 392 |
+
return _signature(ACCESS_KEYS[0], value) if ACCESS_KEYS else ""
|
| 393 |
+
|
| 394 |
+
|
| 395 |
def check_key(request: Request):
|
| 396 |
if ACCESS_KEYS and request.query_params.get("key", "").strip() not in ACCESS_KEYS:
|
| 397 |
raise HTTPException(401, "Missing or wrong ?key=")
|
| 398 |
|
| 399 |
|
| 400 |
+
def check_access(request: Request, signed_value: str):
|
| 401 |
+
"""Allow a valid ?key= or a ?sig= made for this exact feed or episode (by any configured key)."""
|
| 402 |
+
if not ACCESS_KEYS or request.query_params.get("key", "").strip() in ACCESS_KEYS:
|
| 403 |
+
return
|
| 404 |
+
sig = request.query_params.get("sig", "")
|
| 405 |
+
if not any(hmac.compare_digest(sig, _signature(k, signed_value)) for k in ACCESS_KEYS):
|
| 406 |
+
raise HTTPException(401, "This link has no valid signature. Create the feed URL on this server's podcast page.")
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def episode_query(video_id: str) -> str:
|
| 410 |
+
return f"?sig={sign('episode:' + video_id)}" if ACCESS_KEYS else ""
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def signed_feed_url(base: str, ident: str, shorts: bool = False) -> str:
|
| 414 |
+
params = {**({"sig": sign("feed:" + ident)} if ACCESS_KEYS else {}), **({"shorts": "true"} if shorts else {})}
|
| 415 |
+
return f"{base}/feed/{urllib.parse.quote(ident)}" + (f"?{urllib.parse.urlencode(params)}" if params else "")
|
| 416 |
+
|
| 417 |
+
|
| 418 |
def base_url(request: Request) -> str:
|
| 419 |
"""Public URL of this app, including the mount path when it runs as a module."""
|
| 420 |
root_path = request.scope.get("root_path", "").rstrip("/")
|
|
|
|
| 424 |
return f"{proto}://{request.headers.get('host', request.url.netloc)}{root_path}"
|
| 425 |
|
| 426 |
|
| 427 |
+
def build_rss(feed: dict, base: str, include_shorts: bool) -> bytes:
|
|
|
|
| 428 |
rss = ET.Element("rss", {"version": "2.0"})
|
| 429 |
ch = ET.SubElement(rss, "channel")
|
| 430 |
|
|
|
|
| 458 |
sub(item, "description", f"{ep['description']}\n\n{ep['link']}".strip())
|
| 459 |
path = audio_path(ep["id"])
|
| 460 |
size = str(path.stat().st_size) if path.exists() else "0"
|
| 461 |
+
sub(item, "enclosure", url=f"{base}/audio/{ep['id']}.m4a{episode_query(ep['id'])}", type="audio/mp4", length=size)
|
| 462 |
if ep["thumbnail"]:
|
| 463 |
sub(item, f"{{{ITUNES}}}image", href=ep["thumbnail"])
|
| 464 |
if duration := audio_meta(ep["id"]).get("duration"):
|
| 465 |
sub(item, f"{{{ITUNES}}}duration", str(duration))
|
| 466 |
if transcript := load_transcript(ep["id"]):
|
| 467 |
for fmt in ("vtt", "srt"):
|
| 468 |
+
sub(item, f"{{{PODCAST_NS}}}transcript", url=f"{base}/transcript/{ep['id']}.{fmt}{episode_query(ep['id'])}",
|
| 469 |
type=TRANSCRIPT_TYPES[fmt], language=transcript.get("language") or "en")
|
| 470 |
return b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(rss, encoding="utf-8")
|
| 471 |
|
|
|
|
| 474 |
|
| 475 |
@app.get("/", response_class=HTMLResponse)
|
| 476 |
def index():
|
| 477 |
+
return INDEX_HTML.replace("__KEY_FIELD__", "" if ACCESS_KEYS else "hidden")
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
INDEX_HTML = """<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 481 |
+
<title>YouTube to Podcast</title><style>
|
| 482 |
+
body{font:16px/1.5 system-ui,sans-serif;max-width:640px;margin:40px auto;padding:0 16px;color:#1f2328;background:#fff}
|
| 483 |
+
label{display:block;margin:12px 0 4px;font-weight:600}input{width:100%;padding:8px;box-sizing:border-box;font:inherit}
|
| 484 |
+
button{margin-top:12px;padding:8px 16px;font:inherit;cursor:pointer}code{display:block;word-break:break-all;background:#f3f4f6;padding:8px;border-radius:6px}
|
| 485 |
+
.err{color:#b42318}.hidden{display:none}
|
| 486 |
+
@media (prefers-color-scheme:dark){body{background:#0d1117;color:#e6edf3}code{background:#161b22}.err{color:#ff7b72}}
|
| 487 |
+
</style></head><body>
|
| 488 |
+
<h1>YouTube to Podcast</h1>
|
| 489 |
+
<p>Paste a YouTube channel or playlist link to get a podcast feed URL for your podcast app.</p>
|
| 490 |
+
<form id="f">
|
| 491 |
+
<div class="__KEY_FIELD__"><label for="k">API key</label><input id="k" type="password" autocomplete="current-password"></div>
|
| 492 |
+
<label for="u">YouTube link</label><input id="u" placeholder="https://www.youtube.com/@channel or ...playlist?list=PL..." required>
|
| 493 |
+
<label><input id="s" type="checkbox" style="width:auto"> Include Shorts</label>
|
| 494 |
+
<button>Get feed URL</button></form>
|
| 495 |
+
<div id="o" aria-live="polite"></div>
|
| 496 |
+
<script>
|
| 497 |
+
var k=document.getElementById('k'),o=document.getElementById('o');
|
| 498 |
+
try{k.value=localStorage.getItem('podcastKey')||''}catch(e){}
|
| 499 |
+
document.getElementById('f').onsubmit=async function(e){
|
| 500 |
+
e.preventDefault();o.textContent='Checking the channel...';
|
| 501 |
+
var q=new URLSearchParams({url:document.getElementById('u').value,key:k.value});
|
| 502 |
+
if(document.getElementById('s').checked)q.set('shorts','true');
|
| 503 |
+
try{
|
| 504 |
+
var r=await fetch(location.pathname.replace(/\/?$/,'/')+'api/feed-url?'+q),d=await r.json();
|
| 505 |
+
if(!r.ok)throw new Error(d.detail||r.status);
|
| 506 |
+
try{localStorage.setItem('podcastKey',k.value)}catch(e){}
|
| 507 |
+
o.innerHTML='';var p=document.createElement('p');p.textContent='Feed for '+d.title+' ('+d.episodes+' episodes):';
|
| 508 |
+
var c=document.createElement('code');c.textContent=d.feed_url;var b=document.createElement('button');b.textContent='Copy';
|
| 509 |
+
b.onclick=function(){navigator.clipboard.writeText(d.feed_url);b.textContent='Copied'};o.append(p,c,b);
|
| 510 |
+
}catch(err){o.innerHTML='';var p=document.createElement('p');p.className='err';p.textContent=err.message;o.append(p)}
|
| 511 |
+
};
|
| 512 |
+
</script></body></html>"""
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
@app.get("/api/feed-url")
|
| 516 |
+
def api_feed_url(request: Request, url: str, shorts: bool = False):
|
| 517 |
+
if ACCESS_KEYS and request.query_params.get("key", "").strip() not in ACCESS_KEYS:
|
| 518 |
+
raise HTTPException(401, "Wrong API key.")
|
| 519 |
+
kind, ident = parse_source(url)
|
| 520 |
+
data = load_feed(kind, ident) # fails with a clear error if the channel or playlist doesn't exist
|
| 521 |
+
episodes = sum(1 for e in data["episodes"] if shorts or not e["short"])
|
| 522 |
+
return {"feed_url": signed_feed_url(base_url(request), ident, shorts), "title": data["title"], "episodes": episodes}
|
| 523 |
|
| 524 |
|
| 525 |
@app.get("/status")
|
|
|
|
| 537 |
|
| 538 |
|
| 539 |
@app.get("/feed")
|
| 540 |
+
def feed_from_url(request: Request, url: str, shorts: bool = False):
|
| 541 |
check_key(request)
|
| 542 |
_, ident = parse_source(url)
|
| 543 |
+
return RedirectResponse(signed_feed_url(base_url(request), ident, shorts), status_code=302)
|
|
|
|
|
|
|
| 544 |
|
| 545 |
|
| 546 |
@app.get("/feed/{source}")
|
| 547 |
def feed(request: Request, source: str, shorts: bool = False):
|
|
|
|
| 548 |
kind, ident = parse_source(source)
|
| 549 |
+
check_access(request, "feed:" + ident)
|
| 550 |
data = load_feed(kind, ident)
|
| 551 |
if PREFETCH > 0:
|
| 552 |
prefetch([e["id"] for e in data["episodes"] if shorts or not e["short"]][:PREFETCH])
|
| 553 |
+
return Response(build_rss(data, base_url(request), shorts), media_type="application/rss+xml; charset=utf-8")
|
|
|
|
| 554 |
|
| 555 |
|
| 556 |
@app.api_route("/audio/{video_id}.m4a", methods=["GET", "HEAD"])
|
| 557 |
def audio(request: Request, video_id: str):
|
| 558 |
+
check_access(request, "episode:" + video_id)
|
| 559 |
if not VIDEO_ID_RE.match(video_id):
|
| 560 |
raise HTTPException(404, "Unknown video id")
|
| 561 |
try:
|
|
|
|
| 576 |
|
| 577 |
@app.get("/transcript/{video_id}.{fmt}")
|
| 578 |
def transcript(request: Request, video_id: str, fmt: str):
|
| 579 |
+
check_access(request, "episode:" + video_id)
|
| 580 |
if not VIDEO_ID_RE.match(video_id) or fmt not in TRANSCRIPT_TYPES:
|
| 581 |
raise HTTPException(404, "Unknown transcript")
|
| 582 |
if whisper_stt is None:
|