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
 
 
 
 
 
 
 
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#!/usr/bin/env python3

import argparse
import re
from pathlib import Path
from typing import Any, Dict, List, Optional

from utils import *


def sanitize_filename(name: str) -> str:
    cleaned = re.sub(r"[^\w\-. ]+", "_", (name or "untitled").strip())
    cleaned = re.sub(r"\s+", "_", cleaned)
    return cleaned[:140] if cleaned else "untitled"


def normalize_tags(raw_tags: Any) -> List[str]:
    if isinstance(raw_tags, list):
        return [str(t).strip() for t in raw_tags if str(t).strip()]
    if isinstance(raw_tags, str):
        return [t.strip() for t in raw_tags.split(",") if t.strip()]
    return []


def dget(obj: Any, key: str) -> Any:
    if isinstance(obj, dict):
        return obj.get(key)
    return None


def walk_for_song_lists(payload: Any) -> List[Dict[str, Any]]:
    if isinstance(payload, list):
        return [
            x
            for x in payload
            if isinstance(x, dict)
            and (x.get("id") or x.get("audio_url") or x.get("song_path"))
        ]
    if not isinstance(payload, dict):
        return []

    for key in ("songs", "items", "results", "data"):
        value = payload.get(key)
        if isinstance(value, list):
            return [x for x in value if isinstance(x, dict)]
        if isinstance(value, dict):
            nested = walk_for_song_lists(value)
            if nested:
                return nested

    for value in payload.values():
        if isinstance(value, (dict, list)):
            nested = walk_for_song_lists(value)
            if nested:
                return nested
    return []


def detect_version(song: Dict[str, Any], fallback: str) -> str:
    if not isinstance(song, dict):
        return fallback
    raw_metadata = dget(song, "metadata")
    metadata: Dict[str, Any] = {}
    if isinstance(raw_metadata, dict):
        metadata = raw_metadata
    candidates = [
        dget(song, "model_version"),
        dget(song, "version"),
        dget(song, "modelVersion"),
        dget(metadata, "model_version"),
        dget(metadata, "version"),
        dget(metadata, "modelVersion"),
    ]
    for c in candidates:
        if c:
            return str(c)
    return fallback


def resolve_download_url(song: Dict[str, Any]) -> Optional[str]:
    audio_url = song.get("audio_url")
    if isinstance(audio_url, str) and audio_url.strip():
        return audio_url.strip()

    song_path = song.get("song_path")
    if isinstance(song_path, str) and song_path.strip():
        path = song_path.strip()
        if path.startswith("http"):
            return path
        return f"https://www.udio.com{path if path.startswith('/') else '/' + path}"
    return None


VERSION_DATE_RANGES = {
    "v1": ("2024-01-01", "2024-06-15"),
    "v1.5": ("2024-06-15", "2025-01-01"),
    "v2": ("2025-01-01", "2030-01-01"),
}


VERSION_SORT_MAP = {"v1": "likes", "v1.5": "plays", "v2": "newest"}
ALL_SORT_MODES = ["likes", "plays", "newest"]
MAX_PAGE_PER_SORT = 120
VERSION_SEARCH_TERMS = {
    "v1": [
        "",
        "rock",
        "pop",
        "hip hop",
        "jazz",
        "country",
        "R&B",
        "electronic",
        "folk",
        "blues",
        "indie",
        "metal",
        "soul",
        "funk",
        "reggae",
        "classical",
        "ambient",
        "lo-fi",
        "dance",
        "trap",
        "acoustic",
        "cinematic",
        "latin",
        "punk",
        "alternative",
        "gospel",
        "disco",
        "house",
        "techno",
        "synthwave",
        "grunge",
        "shoegaze",
        "new wave",
        "psychedelic",
        "bossa nova",
        "swing",
        "ballad",
        "chillhop",
        "dubstep",
        "drill",
        "emo",
        "hardcore",
        "ska",
        "surf rock",
        "math rock",
        "post punk",
        "vaporwave",
    ],
    "v1.5": [
        "",
        "ambient",
        "lo-fi",
        "dance",
        "trap",
        "acoustic",
        "cinematic",
        "latin",
        "punk",
        "alternative",
        "gospel",
        "disco",
        "house",
        "techno",
        "rock",
        "pop",
        "hip hop",
        "jazz",
        "country",
        "R&B",
        "electronic",
        "folk",
        "blues",
        "indie",
        "metal",
        "soul",
        "funk",
        "reggae",
        "classical",
        "synthwave",
        "K-pop",
        "afrobeat",
        "phonk",
        "orchestral",
        "reggaeton",
        "drill",
        "grunge",
        "shoegaze",
        "new wave",
        "psychedelic",
        "dubstep",
        "emo",
    ],
    "v2": [
        "",
        "pop",
        "rock",
        "hip hop",
        "electronic",
        "R&B",
        "jazz",
        "country",
        "ambient",
        "lo-fi",
        "dance",
        "trap",
        "acoustic",
        "cinematic",
        "latin",
        "indie",
        "metal",
        "soul",
        "funk",
        "reggae",
        "house",
        "techno",
        "drum and bass",
        "synthwave",
        "K-pop",
        "afrobeat",
        "phonk",
        "orchestral",
        "reggaeton",
        "drill",
    ],
}


def fetch_page(
    session: requests.Session,
    page_param: int,
    page_size: int,
    limiter: RateLimiter,
    version: str = "v1.5",
    search_term: str = "",
    sort_mode: Optional[str] = None,
) -> List[Dict[str, Any]]:
    import json as _json
    import subprocess as _sp

    url = "https://www.udio.com/api/songs/search"
    sort_field = sort_mode or VERSION_SORT_MAP.get(version, "plays")
    payload = {
        "searchQuery": {"sort": sort_field, "searchTerm": search_term},
        "pageParam": page_param,
        "pageSize": page_size,
    }
    limiter.wait()

    result = _sp.run(
        [
            "curl",
            "-s",
            "-X",
            "POST",
            url,
            "-H",
            "Content-Type: application/json",
            "-H",
            "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "-H",
            "Origin: https://www.udio.com",
            "-H",
            "Referer: https://www.udio.com/",
            "-H",
            "Accept: application/json, text/plain, */*",
            "-H",
            "Accept-Language: en-US,en;q=0.9",
            "-d",
            _json.dumps(payload),
            "--max-time",
            "30",
        ],
        capture_output=True,
        text=True,
        timeout=35,
    )

    if result.returncode != 0:
        raise RuntimeError(
            f"curl failed with exit code {result.returncode}: {result.stderr.strip()}"
        )

    body = result.stdout.strip()
    if not body:
        raise ValueError("Empty response from Udio API")

    data = _json.loads(body)
    raw_songs = walk_for_song_lists(data)

    date_lo, date_hi = VERSION_DATE_RANGES.get(version, ("2024-01-01", "2030-01-01"))
    filtered = []
    for s in raw_songs:
        created = str(s.get("created_at") or "")[:10]
        if created and date_lo <= created < date_hi:
            filtered.append(s)
    return filtered if filtered else raw_songs


def resolve_output_dir(version: str, output_dir: Optional[str]) -> Path:
    if output_dir:
        return Path(output_dir)
    return FAKE_DIR / "A_commercial" / f"udio_{version}"


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", type=int, default=2000)
    parser.add_argument(
        "--version", type=str, default="v1.5", choices=["v1", "v1.5", "v2"]
    )
    parser.add_argument("--output-dir", type=str, default=None)
    args = parser.parse_args()

    output_dir = resolve_output_dir(args.version, args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    metadata_manager = MetadataManager(output_dir)
    existing = metadata_manager.get_count()
    if existing >= args.target:
        logger.info(f"Target already reached in {output_dir}: {existing}/{args.target}")
        metadata_manager.update_summary()
        return

    def make_session() -> requests.Session:
        s = requests.Session()
        s.headers.update(
            {
                "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "Accept": "application/json, text/plain, */*",
                "Content-Type": "application/json",
                "Origin": "https://www.udio.com",
                "Referer": "https://www.udio.com/",
                "Accept-Language": "en-US,en;q=0.9",
                "Connection": "close",
            }
        )
        return s

    session = make_session()

    api_limiter = RateLimiter(requests_per_second=0.5)
    download_limiter = RateLimiter(requests_per_second=1.5)
    progress = tqdm(
        total=args.target, initial=existing, desc=f"udio_{args.version}", unit="track"
    )

    import time as _time

    page_size = 50
    downloaded_since_summary = 0
    search_terms = VERSION_SEARCH_TERMS.get(args.version, [""])

    def download_song(song: Dict[str, Any]) -> bool:
        nonlocal downloaded_since_summary
        if not isinstance(song, dict):
            return False

        song_id = str(song.get("id") or "").strip()
        if not song_id:
            return False

        title = str(song.get("title") or "untitled").strip()
        raw_metadata = dget(song, "metadata")
        song_metadata: Dict[str, Any] = {}
        if isinstance(raw_metadata, dict):
            song_metadata = raw_metadata
        prompt = dget(song_metadata, "prompt") or dget(song, "prompt")
        tags = normalize_tags(dget(song_metadata, "tags") or dget(song, "tags"))
        genre = dget(song_metadata, "genre") or dget(song, "genre")
        if not genre and tags:
            genre = ", ".join(tags)

        filename = f"{song_id}_{sanitize_filename(title)}.mp3"
        file_path = output_dir / filename

        if (
            metadata_manager.has_track(song_id)
            and file_path.exists()
            and file_path.stat().st_size > 0
        ):
            return False

        download_url = resolve_download_url(song)
        if not download_url:
            return False

        download_limiter.wait()
        try:
            ok = download_file(download_url, file_path, headers=dict(session.headers))
            if not ok:
                return False
        except Exception as e:
            logger.warning(f"Download failed for Udio track {song_id}: {e}")
            return False

        audio_info = get_audio_info(file_path)
        version = detect_version(song, args.version)
        lyrics_raw = dget(song, "lyrics")
        lyrics = str(lyrics_raw).strip() if lyrics_raw else None

        meta = TrackMetadata(
            track_id=song_id,
            filename=filename,
            category="A_commercial",
            subcategory=f"udio_{version}",
            source_platform="udio",
            source_type="commercial",
            model_name="Udio",
            model_version=version,
            title=title,
            prompt=str(prompt) if prompt else None,
            genre=str(genre) if genre else None,
            tags=tags,
            lyrics=lyrics,
            source_url=f"https://www.udio.com/songs/{song_id}",
            download_url=download_url,
            collection_method="crawl",
            duration_sec=audio_info.get("duration_sec"),
            sample_rate=audio_info.get("sample_rate"),
            channels=audio_info.get("channels"),
            bitrate_kbps=audio_info.get("bitrate_kbps"),
            file_size_bytes=audio_info.get("file_size_bytes")
            or file_path.stat().st_size,
            audio_format="mp3",
            md5_hash=compute_md5(file_path),
        )

        if not metadata_manager.has_track(song_id):
            metadata_manager.add_track(meta)
            progress.update(1)
            downloaded_since_summary += 1

        if downloaded_since_summary >= 25:
            metadata_manager.update_summary()
            downloaded_since_summary = 0
        return True

    try:
        for term_idx, current_term in enumerate(search_terms):
            if metadata_manager.get_count() >= args.target:
                break
            if not ensure_disk_space():
                logger.warning("Stopping due to insufficient disk space")
                break

            for sort_mode in ALL_SORT_MODES:
                if metadata_manager.get_count() >= args.target:
                    break

                consecutive_empty = 0
                page_param = 0
                for page_param in range(MAX_PAGE_PER_SORT):
                    if metadata_manager.get_count() >= args.target:
                        break

                    retries = 0
                    songs: List[Dict[str, Any]] = []
                    while retries < 3:
                        try:
                            songs = fetch_page(
                                session,
                                page_param,
                                page_size,
                                api_limiter,
                                version=args.version,
                                search_term=current_term,
                                sort_mode=sort_mode,
                            )
                            break
                        except Exception as e:
                            retries += 1
                            if retries < 3:
                                _time.sleep(3.0 * retries)
                            else:
                                logger.debug(
                                    f"page={page_param} sort={sort_mode} "
                                    f"term={current_term!r}: {e}"
                                )

                    if not songs:
                        consecutive_empty += 1
                        if consecutive_empty >= 5:
                            break
                        continue

                    consecutive_empty = 0
                    for song in songs:
                        if metadata_manager.get_count() >= args.target:
                            break
                        download_song(song)

                logger.info(
                    f"[{args.version}] term={current_term!r} sort={sort_mode} "
                    f"done at page={page_param} | "
                    f"total={metadata_manager.get_count()}/{args.target}"
                )

    finally:
        metadata_manager.update_summary()
        progress.close()

    logger.info(
        f"Finished Udio crawl: {metadata_manager.get_count()}/{args.target} in {output_dir}"
    )


if __name__ == "__main__":
    main()