Spaces:
Sleeping

File size: 7,673 Bytes
60a07be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""
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)