Spaces:
Sleeping

arkanum / scripts /fetch_transcripts.py
benny4982's picture
Claude Opus 4.6
Add YouTube transcripts to RAG, walkthrough voice guide, and intro story
60a07be
Raw History Blame
7.67 kB
"""
YouTube-Transkript Download
============================
Lädt Untertitel/Transkripte von konfigurierten YouTube-Videos herunter.
Verwendung:
python scripts/fetch_transcripts.py --game stalker
"""
import argparse
import json
import os
import re
import subprocess
import sys
# Bekannte Learn-to-Play Videos pro Spiel
VIDEOS = {
"stalker": [
{
"url": "https://www.youtube.com/watch?v=YSfUp1fqjTI",
"lang": "de",
"channel": "GenusSolo",
"title": "S.T.A.L.K.E.R. Das Brettspiel - S01E01 - Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=gDYsanuIwM4",
"lang": "de",
"channel": "GenusSolo",
"title": "S.T.A.L.K.E.R. Das Brettspiel - S01E02 - Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=dMlB7ykqJz8",
"lang": "de",
"channel": "GenusSolo",
"title": "S.T.A.L.K.E.R. Das Brettspiel - S01E03 - Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=JzosvGvLyq0",
"lang": "de",
"channel": "GenusSolo",
"title": "S.T.A.L.K.E.R. Das Brettspiel - S01E04 - Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=o8PpRY5BAug",
"lang": "de",
"channel": "GenusSolo",
"title": "S.T.A.L.K.E.R. Das Brettspiel - S01E05 - Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=_MBnU9kv89E",
"lang": "en",
"channel": "BoardGameCo",
"title": "S.T.A.L.K.E.R. The Board Game - How To Play",
},
{
"url": "https://www.youtube.com/watch?v=nfy0L2dLklM",
"lang": "en",
"channel": "Gaming Rules!",
"title": "STALKER The Board Game - Tutorial & Playthrough",
},
{
"url": "https://www.youtube.com/watch?v=d1jsQX9J9hs",
"lang": "en",
"channel": "Epitrapaizoume.gr",
"title": "S.T.A.L.K.E.R. The Board Game - How to Play",
},
{
"url": "https://www.youtube.com/watch?v=X07gJGgDdzk",
"lang": "en",
"channel": "Awaken Realms",
"title": "S.T.A.L.K.E.R. The Board Game - Gameplay Preview",
},
],
}
def _sanitize_filename(text: str) -> str:
"""Erzeugt einen sicheren Dateinamen aus einem Text."""
text = text.lower()
text = re.sub(r"[^a-z0-9]+", "_", text)
text = text.strip("_")
return text
def _build_filename(video: dict) -> str:
"""Baut den Basis-Dateinamen für ein Video."""
channel = _sanitize_filename(video["channel"])
title = _sanitize_filename(video["title"])
# Kürzen falls zu lang
if len(title) > 60:
title = title[:60].rstrip("_")
return f"{channel}_{title}"
def fetch_transcript(video: dict, output_dir: str) -> bool:
"""
Lädt das Transkript eines Videos mit yt-dlp herunter.
Returns:
True wenn erfolgreich oder bereits vorhanden, False bei Fehler.
"""
base_name = _build_filename(video)
lang = video["lang"]
# Prüfen ob bereits vorhanden
vtt_path = os.path.join(output_dir, f"{base_name}.{lang}.vtt")
if os.path.exists(vtt_path):
print(f" ⏭ Bereits vorhanden: {base_name}.{lang}.vtt")
return True
print(f" ⬇ Lade Transkript: {video['title']} ({lang})")
# yt-dlp Aufruf: nur Untertitel, kein Video-Download
cmd = [
"yt-dlp",
"--write-auto-sub",
"--write-sub",
"--sub-lang", lang,
"--sub-format", "vtt",
"--skip-download",
"--output", os.path.join(output_dir, f"{base_name}.%(ext)s"),
video["url"],
]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=120,
)
except FileNotFoundError:
print(" ❌ yt-dlp nicht gefunden. Bitte installieren: pip install yt-dlp")
return False
except subprocess.TimeoutExpired:
print(f" ❌ Timeout beim Download: {video['url']}")
return False
# yt-dlp benennt die Dateien mit Sprachcode, finden und umbenennen
# Mögliche Dateinamen: base_name.lang.vtt oder base_name.lang-orig.vtt
found_vtt = None
for f in os.listdir(output_dir):
if f.startswith(base_name) and f.endswith(".vtt"):
found_vtt = os.path.join(output_dir, f)
# Normalisieren zum erwarteten Dateinamen
if found_vtt != vtt_path:
os.rename(found_vtt, vtt_path)
break
if not found_vtt and not os.path.exists(vtt_path):
print(f" ⚠ Kein Transkript verfügbar: {video['title']}")
if result.stderr:
# Nur relevante Zeilen ausgeben
for line in result.stderr.splitlines():
if "WARNING" in line or "ERROR" in line:
print(f" {line.strip()}")
return False
# Metadaten speichern
meta_path = os.path.join(output_dir, f"{base_name}.meta.json")
if not os.path.exists(meta_path):
meta = {
"title": video["title"],
"channel": video["channel"],
"language": lang,
"url": video["url"],
"filename": f"{base_name}.{lang}.vtt",
}
with open(meta_path, "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2, ensure_ascii=False)
print(f" ✅ Gespeichert: {base_name}.{lang}.vtt")
return True
def list_videos(game: str) -> None:
"""Listet alle konfigurierten Videos für ein Spiel auf."""
if game not in VIDEOS:
print(f"Keine Videos konfiguriert für '{game}'")
print(f"Verfügbare Spiele: {', '.join(VIDEOS.keys())}")
sys.exit(1)
videos = VIDEOS[game]
output_dir = os.path.join("data", "raw", game, "youtube_transcripts")
print(f"Konfigurierte Videos für '{game}' ({len(videos)}):\n")
for i, video in enumerate(videos, 1):
base_name = _build_filename(video)
vtt_path = os.path.join(output_dir, f"{base_name}.{video['lang']}.vtt")
status = "heruntergeladen" if os.path.exists(vtt_path) else "ausstehend"
print(f" {i}. [{video['lang'].upper()}] {video['channel']} – {video['title']}")
print(f" URL: {video['url']}")
print(f" Status: {status}")
print()
def fetch_all(game: str) -> None:
"""Lädt alle konfigurierten Transkripte für ein Spiel herunter."""
if game not in VIDEOS:
print(f"Keine Videos konfiguriert für '{game}'")
print(f"Verfügbare Spiele: {', '.join(VIDEOS.keys())}")
sys.exit(1)
output_dir = os.path.join("data", "raw", game, "youtube_transcripts")
os.makedirs(output_dir, exist_ok=True)
videos = VIDEOS[game]
print(f"Lade Transkripte für '{game}' ({len(videos)} Videos)...\n")
success = 0
for video in videos:
if fetch_transcript(video, output_dir):
success += 1
print(f"\nFertig: {success}/{len(videos)} Transkripte geladen")
print(f"Verzeichnis: {output_dir}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="YouTube-Transkripte für Brettspiel-Tutorials herunterladen"
)
parser.add_argument("--game", required=True, help="Spielname (z.B. stalker)")
parser.add_argument("--list", action="store_true", help="Konfigurierte Videos auflisten")
args = parser.parse_args()
if args.list:
list_videos(args.game)
else:
fetch_all(args.game)