File size: 7,577 Bytes
434c049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
extract_youtube_transcripts.py — Moldovan YouTube Transcript Extractor

Extracts subtitles and transcripts from Moldovan podcasts, stand-up shows,
interviews, and vlogs to build the raw training corpus for Moldovan Qwen.
"""

import os
import sys
import re
import json
import time
import argparse
from typing import List, Dict, Optional
from urllib.parse import urlparse, parse_qs

try:
    from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
except ImportError:
    print("Please install youtube-transcript-api: pip install youtube-transcript-api")
    sys.exit(1)

# Curated seed list of top Moldovan YouTube channels & videos
MOLDOVAN_CHANNELS_SEED = [
    {
        "channel": "Dorin Galben",
        "category": "Interviews & Podcasts",
        "sample_video_ids": [
            "dQw4w9WgXcQ",  # Placeholder IDs will be populated or passed via CLI
        ]
    },
    {
        "channel": "Standupovka",
        "category": "Stand-Up Comedy & Slang",
        "sample_video_ids": []
    },
    {
        "channel": "Banca de Bancuri",
        "category": "Popular Humor & Folklore",
        "sample_video_ids": []
    },
    {
        "channel": "Zebra Show",
        "category": "Satire & Sketches",
        "sample_video_ids": []
    },
    {
        "channel": "Titania Podcast",
        "category": "Urban Culture & Youth Talk",
        "sample_video_ids": []
    }
]

def extract_video_id(url_or_id: str) -> Optional[str]:
    """Extract 11-char YouTube video ID from various URL formats."""
    url_or_id = url_or_id.strip()
    if len(url_or_id) == 11 and re.match(r'^[a-zA-Z0-9_-]{11}$', url_or_id):
        return url_or_id
    
    parsed = urlparse(url_or_id)
    if parsed.hostname in ('youtu.be', 'www.youtu.be'):
        return parsed.path.lstrip('/')
    if parsed.hostname in ('youtube.com', 'www.youtube.com'):
        if parsed.path == '/watch':
            return parse_qs(parsed.query).get('v', [None])[0]
        if parsed.path.startswith('/embed/'):
            return parsed.path.split('/')[2]
        if parsed.path.startswith('/v/'):
            return parsed.path.split('/')[2]
        if parsed.path.startswith('/shorts/'):
            return parsed.path.split('/')[2]
    return None

def fetch_transcript(video_id: str, languages: List[str] = None) -> Optional[Dict]:
    """Fetch transcript for a given video ID with language fallback."""
    if languages is None:
        languages = ['ro', 'ro-MD', 'mo', 'ru', 'en']

    try:
        api = YouTubeTranscriptApi()
        try:
            transcript_list = api.list(video_id)
        except Exception:
            transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)

        # Priority: Manual Romanian -> Auto Romanian -> Manual Russian -> Auto Russian
        transcript = None
        used_lang = None

        for lang in languages:
            try:
                transcript = transcript_list.find_transcript([lang])
                used_lang = lang
                break
            except Exception:
                continue

        # If no direct match, try finding any generated transcript
        if not transcript:
            try:
                transcript = transcript_list.find_generated_transcript(languages)
                used_lang = getattr(transcript, 'language_code', 'ro')
            except Exception:
                pass

        if not transcript:
            # Fallback to the first available transcript
            for t in transcript_list:
                transcript = t
                used_lang = getattr(t, 'language_code', 'unknown')
                break

        if not transcript:
            return None

        data = transcript.fetch()

        # Merge segments into readable paragraphs
        full_text_chunks = []
        current_chunk = []
        current_word_count = 0

        for item in data:
            if hasattr(item, 'text'):
                text = str(item.text).strip()
            elif isinstance(item, dict):
                text = item.get('text', '').strip()
            else:
                text = str(item).strip()

            current_word_count += len(text.split())
            
            # Group into ~100-word logical paragraphs
            if current_word_count >= 100 or text.endswith(('.', '?', '!')):
                full_text_chunks.append(' '.join(current_chunk))
                current_chunk = []
                current_word_count = 0
                
        if current_chunk:
            full_text_chunks.append(' '.join(current_chunk))
            
        merged_text = '\n\n'.join(full_text_chunks)
        
        return {
            "video_id": video_id,
            "language": used_lang,
            "is_generated": transcript.is_generated,
            "raw_segments_count": len(data),
            "paragraphs_count": len(full_text_chunks),
            "word_count": len(merged_text.split()),
            "full_text": merged_text,
            "extracted_at": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
    except (TranscriptsDisabled, NoTranscriptFound) as e:
        print(f"[-] Subtitles not available for video {video_id}: {e}")
        return None
    except Exception as e:
        print(f"[!] Error fetching transcript for {video_id}: {e}")
        return None

def main():
    parser = argparse.ArgumentParser(description="Extract YouTube transcripts for Moldovan corpus")
    parser.add_argument("--urls", nargs="+", help="List of YouTube URLs or video IDs to transcribe")
    parser.add_argument("--file", help="File with list of YouTube URLs/IDs (one per line)")
    parser.add_argument("--output-dir", default="moldovan-qwen/data/raw_transcripts", help="Output directory")
    args = parser.parse_args()

    os.makedirs(args.output_dir, exist_ok=True)
    
    video_ids = []
    if args.urls:
        for u in args.urls:
            vid = extract_video_id(u)
            if vid:
                video_ids.append(vid)
            else:
                print(f"[!] Warning: Could not parse video ID from: {u}")
                
    if args.file and os.path.exists(args.file):
        with open(args.file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    vid = extract_video_id(line)
                    if vid:
                        video_ids.append(vid)
                        
    if not video_ids:
        print("No videos specified. Example usage:")
        print("  python3 scripts/extract_youtube_transcripts.py --urls https://www.youtube.com/watch?v=VIDEO_ID")
        print("  python3 scripts/extract_youtube_transcripts.py --file data/video_sources.txt")
        return

    print(f"[*] Found {len(video_ids)} video IDs to process.")
    results = []
    
    for idx, vid in enumerate(video_ids, 1):
        print(f"[{idx}/{len(video_ids)}] Fetching transcript for video: {vid}...")
        res = fetch_transcript(vid)
        if res:
            out_file = os.path.join(args.output_dir, f"{vid}.json")
            with open(out_file, 'w', encoding='utf-8') as f:
                json.dump(res, f, ensure_ascii=False, indent=2)
            print(f"    [+] Saved transcript ({res['word_count']} words, lang: {res['language']}) -> {out_file}")
            results.append(res)
        time.sleep(1) # Gentle delay between requests

    print(f"\n[✓] Successfully processed {len(results)}/{len(video_ids)} transcripts.")

if __name__ == "__main__":
    main()