Datasets:
Tasks:
Audio Classification
Formats:
parquet
Size:
1K - 10K
ArXiv:
Tags:
arxiv:2606.01686
music
ai-generated-music
ai-generated-music-detection
plagiarism-detection
ace-step
License:
| #!/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() | |