#!/usr/bin/env python3 import argparse import json import re import subprocess import time from collections import deque from pathlib import Path from typing import Any, Deque, Dict, Iterable, List, Optional, Set, Tuple from urllib.parse import urlencode from bs4 import BeautifulSoup from utils import * USER_AGENT = ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" ) UUID_RE = re.compile( r"\b([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\b", re.IGNORECASE, ) SUNO_SONG_URL_RE = re.compile( r"https?://(?:www\.)?suno\.com/song/([a-f0-9\-]{36})", re.IGNORECASE ) RAW_VERSION_RE = re.compile(r'"model_version"\s*:\s*"([^"]+)"', re.IGNORECASE) RAW_MODEL_NAME_RE = re.compile(r'"model_name"\s*:\s*"([^"]+)"', re.IGNORECASE) RAW_TAGS_RE = re.compile(r'"tags"\s*:\s*"((?:\\.|[^"])*)"', re.IGNORECASE) TARGET_VERSIONS = ["studio"] VERSION_TO_SUBDIR = { "v3": "suno_v3", "v3.5": "suno_v3.5", "v4": "suno_v4", "v5": "suno_v5.5", "v5.5": "suno_v5.5", "studio": "suno_studio", "unknown": "suno_v4", } REDDIT_SUBREDDITS = [ "SunoAI", "suno", "aimusic", "musicproduction", "AIGeneratedMusic", ] REDDIT_SEARCH_QUERIES = [ "suno.com/song", "suno song", "made with suno", "suno ai", "suno v3", "suno v4", "suno v5", "suno studio", ] REDDIT_LISTING_ENDPOINTS = [ "https://www.reddit.com/r/SunoAI/new.json", "https://www.reddit.com/r/SunoAI/hot.json", "https://www.reddit.com/r/SunoAI/top.json?t=all", ] YOUTUBE_QUERIES = [ "suno v3 song", "suno v3.5 song", "suno v4 song", "suno v5 song", "suno v5.5 song", "suno studio", "made with suno", "suno ai generated music", ] SUNO_SEED_PAGES = [ "https://suno.com/", "https://suno.com/explore", "https://suno.com/feed", "https://suno.com/create", "https://suno.com/search?q=suno", ] HF_DATASET_URL = "https://huggingface.co/datasets/nyuuzyou/suno/resolve/main/data/train-00000-of-00001.parquet" HF_CACHE_DIR = BASE_DIR / "cache" HF_DATASET_PARQUET_PATH = HF_CACHE_DIR / "suno_hf_dataset.parquet" SUNO_FEED_API_URL = "https://studio-api.prod.suno.com/api/feed/v2" 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 decode_json_string(value: str) -> str: try: return json.loads(f'"{value}"') except Exception: return value def is_valid_uuid(song_id: str) -> bool: return bool(UUID_RE.fullmatch(song_id.strip().lower())) def extract_song_ids_from_text(text: str) -> List[str]: if not text: return [] found: List[str] = [] for match in SUNO_SONG_URL_RE.finditer(text): song_id = match.group(1).strip().lower() if is_valid_uuid(song_id): found.append(song_id) for match in UUID_RE.finditer(text): found.append(match.group(1).strip().lower()) return found def request_with_retry( session: requests.Session, method: str, url: str, limiter: RateLimiter, *, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, Any]] = None, stream: bool = False, timeout: int = 30, max_attempts: int = 5, ) -> Optional[requests.Response]: delay = 1.5 for attempt in range(1, max_attempts + 1): limiter.wait() try: resp = session.request( method=method.upper(), url=url, params=params, headers=headers, timeout=timeout, stream=stream, ) except requests.RequestException as exc: if attempt == max_attempts: logger.warning(f"Request failed for {url}: {exc}") return None time.sleep(delay) delay = min(delay * 2, 30) continue if resp.status_code == 429: retry_after = resp.headers.get("Retry-After") wait_seconds = delay if retry_after: try: wait_seconds = max(wait_seconds, float(retry_after)) except ValueError: pass logger.warning(f"429 rate limited for {url}; sleeping {wait_seconds:.1f}s") resp.close() time.sleep(wait_seconds) delay = min(delay * 2, 30) continue if resp.status_code >= 500: logger.warning( f"Server error {resp.status_code} for {url} attempt {attempt}/{max_attempts}" ) resp.close() if attempt == max_attempts: return None time.sleep(delay) delay = min(delay * 2, 30) continue return resp return None def extract_title_from_html(html_text: str) -> str: if not html_text: return "untitled" soup = BeautifulSoup(html_text, "html.parser") og_title = soup.find("meta", attrs={"property": "og:title"}) if og_title and og_title.get("content"): title = str(og_title.get("content") or "").strip() if title: return title if soup.title and soup.title.text: title = soup.title.text.strip() if title: return title return "untitled" def detect_version_from_page( html_text: str, raw_version: Optional[str], raw_model_name: Optional[str] ) -> str: lowered_html = (html_text or "").lower() version = (raw_version or "").strip().lower() model_name = (raw_model_name or "").strip().lower() if "studio" in lowered_html and ( "suno studio" in lowered_html or '"studio"' in lowered_html or "studio mode" in lowered_html ): return "studio" if version in {"v3", "3", "v3.0"}: return "v3" if version in {"v3.5", "3.5"}: return "v3.5" if version in {"v4", "4", "v4.0"}: return "v4" if version in {"v5", "5", "v5.5", "5.5"}: if "chirp-crow" in model_name: if "studio" in lowered_html: return "studio" return "v5.5" if "studio" in lowered_html: return "studio" return "v5.5" if "chirp-v3" in model_name: return "v3" if "chirp-v4" in model_name: return "v4" if "chirp-crow" in model_name: if "studio" in lowered_html: return "studio" return "v5.5" if 'model_version":"v3.5' in lowered_html: return "v3.5" if 'model_version":"v3' in lowered_html: return "v3" if 'model_version":"v4' in lowered_html: return "v4" if 'model_version":"v5.5' in lowered_html or 'model_version":"v5' in lowered_html: return "v5.5" if "studio" in lowered_html: return "studio" return "unknown" def map_version_for_folder(version: str) -> str: canonical = version.strip().lower() if version else "unknown" if canonical == "v5": canonical = "v5.5" if canonical not in {"v3", "v3.5", "v4", "v5.5", "studio"}: canonical = "unknown" folder = VERSION_TO_SUBDIR.get(canonical, VERSION_TO_SUBDIR["unknown"]) if folder.endswith("v3"): return "v3" if folder.endswith("v3.5"): return "v3.5" if folder.endswith("v4"): return "v4" if folder.endswith("v5.5"): return "v5.5" if folder.endswith("studio"): return "studio" return "v4" def ensure_track_path(output_dir: Path, track_id: str) -> Optional[Path]: for path in output_dir.glob(f"{track_id}_*.mp3"): if path.exists() and path.stat().st_size > 1000: return path return None def maybe_add_uuid( song_id: str, source: str, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> bool: normalized = song_id.strip().lower() if not is_valid_uuid(normalized): return False discovery_sources.setdefault(normalized, set()).add(source) if normalized in seen_uuids: return False seen_uuids.add(normalized) candidate_queue.append(normalized) return True def parse_reddit_posts( payload: Dict[str, Any], ) -> Tuple[List[Dict[str, Any]], Optional[str]]: data = payload.get("data") if isinstance(payload, dict) else None children = data.get("children") if isinstance(data, dict) else None after = data.get("after") if isinstance(data, dict) else None posts: List[Dict[str, Any]] = [] if isinstance(children, list): for child in children: post = child.get("data") if isinstance(child, dict) else None if isinstance(post, dict): posts.append(post) return posts, after if isinstance(after, str) else None def discover_reddit_paginated( session: requests.Session, limiter: RateLimiter, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> int: added = 0 for subreddit in REDDIT_SUBREDDITS: for query in REDDIT_SEARCH_QUERIES: after: Optional[str] = None pages = 0 while True: params: Dict[str, Any] = { "q": query, "restrict_sr": "on", "sort": "new", "limit": "100", "t": "all", } if after: params["after"] = after url = f"https://www.reddit.com/r/{subreddit}/search.json" resp = request_with_retry(session, "GET", url, limiter, params=params) if resp is None: logger.warning( f"Reddit search failed for r/{subreddit} query '{query}'" ) break if resp.status_code >= 400: logger.warning( f"Reddit search HTTP {resp.status_code} for r/{subreddit} query '{query}'" ) resp.close() break try: payload = resp.json() except ValueError: logger.warning( f"Failed to parse Reddit JSON for r/{subreddit} query '{query}'" ) resp.close() break finally: resp.close() posts, next_after = parse_reddit_posts(payload) if not posts: break source_tag = f"reddit:search:{subreddit}:{query}" for post in posts: combined = "\n".join( [ str(post.get("title") or ""), str(post.get("selftext") or ""), str(post.get("url") or ""), ] ) for song_id in extract_song_ids_from_text(combined): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 pages += 1 if not next_after or pages >= 300: break after = next_after for endpoint in REDDIT_LISTING_ENDPOINTS: after = None pages = 0 while True: params = {"limit": "100"} if after: params["after"] = after separator = "&" if "?" in endpoint else "?" listing_url = f"{endpoint}{separator}{urlencode(params)}" resp = request_with_retry(session, "GET", listing_url, limiter) if resp is None: logger.warning(f"Reddit listing failed for {endpoint}") break if resp.status_code >= 400: logger.warning(f"Reddit listing HTTP {resp.status_code} for {endpoint}") resp.close() break try: payload = resp.json() except ValueError: logger.warning(f"Failed to parse Reddit listing JSON for {endpoint}") resp.close() break finally: resp.close() posts, next_after = parse_reddit_posts(payload) if not posts: break source_tag = f"reddit:listing:{endpoint.split('/')[-1].split('?')[0]}" for post in posts: combined = "\n".join( [ str(post.get("title") or ""), str(post.get("selftext") or ""), str(post.get("url") or ""), ] ) for song_id in extract_song_ids_from_text(combined): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 pages += 1 if not next_after or pages >= 300: break after = next_after logger.info(f"Reddit discovery added {added} UUIDs") return added def run_cmd(cmd: List[str], timeout: int = 240) -> Tuple[bool, str, str]: try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) except Exception as exc: logger.warning(f"Command failed: {' '.join(cmd[:4])}... ({exc})") return False, "", str(exc) if result.returncode != 0: stderr = (result.stderr or "").strip() if stderr: logger.warning(stderr[-800:]) return False, result.stdout or "", stderr return True, result.stdout or "", result.stderr or "" def discover_from_youtube( limiter: RateLimiter, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> int: added = 0 for query in YOUTUBE_QUERIES: limiter.wait() ok, stdout, _ = run_cmd( [ "yt-dlp", "--skip-download", "--dump-json", "--no-warnings", "--playlist-end", "30", f"ytsearch30:{query}", ], timeout=180, ) if not ok: logger.warning(f"yt-dlp query failed: {query}") continue for line in stdout.splitlines(): line = line.strip() if not line: continue try: item = json.loads(line) except ValueError: continue combined = "\n".join( [ str(item.get("title") or ""), str(item.get("description") or ""), str(item.get("webpage_url") or ""), ] ) for song_id in extract_song_ids_from_text(combined): if maybe_add_uuid( song_id, f"youtube:{query}", seen_uuids, candidate_queue, discovery_sources, ): added += 1 logger.info(f"YouTube discovery added {added} UUIDs") return added def discover_from_suno_seed_pages( session: requests.Session, limiter: RateLimiter, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> int: added = 0 for page_url in SUNO_SEED_PAGES: resp = request_with_retry(session, "GET", page_url, limiter, timeout=40) if resp is None: logger.warning(f"Failed to fetch Suno seed page: {page_url}") continue if resp.status_code >= 400: logger.warning(f"Suno seed page HTTP {resp.status_code}: {page_url}") resp.close() continue html_text = resp.text or "" resp.close() for song_id in extract_song_ids_from_text(html_text): if maybe_add_uuid( song_id, f"suno_seed:{page_url}", seen_uuids, candidate_queue, discovery_sources, ): added += 1 logger.info(f"Suno seed pages added {added} UUIDs") return added def extract_uuid_candidates_from_object(obj: Any) -> Set[str]: found: Set[str] = set() stack: List[Any] = [obj] while stack: item = stack.pop() if isinstance(item, dict): for value in item.values(): if isinstance(value, (dict, list, tuple)): stack.append(value) elif isinstance(value, str): for song_id in extract_song_ids_from_text(value): found.add(song_id) elif isinstance(item, (list, tuple)): for value in item: if isinstance(value, (dict, list, tuple)): stack.append(value) elif isinstance(value, str): for song_id in extract_song_ids_from_text(value): found.add(song_id) elif isinstance(item, str): for song_id in extract_song_ids_from_text(item): found.add(song_id) return found def ensure_hf_cache( session: requests.Session, limiter: RateLimiter, ) -> Optional[Path]: HF_CACHE_DIR.mkdir(parents=True, exist_ok=True) if ( not HF_DATASET_PARQUET_PATH.exists() or HF_DATASET_PARQUET_PATH.stat().st_size == 0 ): logger.info( f"Downloading HuggingFace Suno dataset to {HF_DATASET_PARQUET_PATH}" ) resp = request_with_retry( session, "GET", HF_DATASET_URL, limiter, stream=True, timeout=300, max_attempts=6, ) if resp is None: logger.warning("Failed to download HuggingFace Suno dataset") return None if resp.status_code >= 400: logger.warning( f"HuggingFace dataset HTTP {resp.status_code} for {HF_DATASET_URL}" ) resp.close() return None tmp_path = HF_DATASET_PARQUET_PATH.with_suffix(".parquet.part") try: with open(tmp_path, "wb") as fout: for chunk in resp.iter_content(chunk_size=1024 * 1024): if chunk: fout.write(chunk) if tmp_path.stat().st_size < 10000: logger.warning("Downloaded HuggingFace dataset is too small") tmp_path.unlink(missing_ok=True) return None tmp_path.replace(HF_DATASET_PARQUET_PATH) logger.info( f"Downloaded HuggingFace dataset: {HF_DATASET_PARQUET_PATH.stat().st_size / 1024 / 1024:.1f} MB" ) except Exception as exc: logger.warning(f"Failed writing HuggingFace dataset cache: {exc}") tmp_path.unlink(missing_ok=True) return None finally: resp.close() return HF_DATASET_PARQUET_PATH def discover_from_huggingface( session: requests.Session, limiter: RateLimiter, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> int: parquet_path = ensure_hf_cache(session, limiter) if parquet_path is None: return 0 source_tag = "huggingface:nyuuzyou/suno" added = 0 try: import pyarrow.parquet as pq pf = pq.ParquetFile(str(parquet_path)) total_rows = pf.metadata.num_rows logger.info(f"HuggingFace Parquet has {total_rows} rows, scanning for UUIDs...") for batch in pf.iter_batches(batch_size=10000): columns = batch.column_names id_col = None for col_name in ["id", "song_id", "uuid", "clip_id"]: if col_name in columns: id_col = col_name break if id_col is not None: for value in batch.column(id_col).to_pylist(): if value is None: continue song_id = str(value).strip().lower() if is_valid_uuid(song_id): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 else: for col_name in columns: for value in batch.column(col_name).to_pylist(): if value is None or not isinstance(value, str): continue for song_id in extract_song_ids_from_text(str(value)): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 if added > 0 and added % 50000 == 0: logger.info(f"HuggingFace discovery progress: {added} new UUIDs added") except ImportError: logger.warning("pyarrow not installed; trying pandas fallback for parquet") try: import pandas as pd df = pd.read_parquet(str(parquet_path)) logger.info(f"HuggingFace Parquet loaded with {len(df)} rows via pandas") id_col = None for col_name in ["id", "song_id", "uuid", "clip_id"]: if col_name in df.columns: id_col = col_name break if id_col is not None: for value in df[id_col].dropna(): song_id = str(value).strip().lower() if is_valid_uuid(song_id): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 else: for col in df.columns: if df[col].dtype == object: for value in df[col].dropna(): for song_id in extract_song_ids_from_text(str(value)): if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 except Exception as exc: logger.warning(f"Failed reading HuggingFace parquet with pandas: {exc}") return added except Exception as exc: logger.warning(f"Failed reading HuggingFace parquet: {exc}") return added logger.info(f"HuggingFace discovery added {added} UUIDs") return added def discover_from_feed_api( session: requests.Session, limiter: RateLimiter, seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], max_pages: int = 200, ) -> int: added = 0 empty_pages = 0 for page in range(1, max_pages + 1): params = {"is_public": "true", "page": str(page)} resp = request_with_retry( session, "GET", SUNO_FEED_API_URL, limiter, params=params, timeout=40, max_attempts=4, ) if resp is None: logger.warning(f"Suno feed API request failed at page {page}") break if resp.status_code >= 400: logger.warning(f"Suno feed API HTTP {resp.status_code} at page {page}") resp.close() break try: payload = resp.json() except ValueError: logger.warning(f"Failed to parse Suno feed API JSON at page {page}") resp.close() break finally: resp.close() page_ids = extract_uuid_candidates_from_object(payload) if not page_ids: empty_pages += 1 if empty_pages >= 3: break continue empty_pages = 0 source_tag = f"suno_feed_api:page:{page}" for song_id in page_ids: if maybe_add_uuid( song_id, source_tag, seen_uuids, candidate_queue, discovery_sources, ): added += 1 logger.info(f"Suno feed API discovery added {added} UUIDs") return added def generate_pattern_candidates( seed_ids: Iterable[str], limit: int = 2500 ) -> List[str]: candidates: Set[str] = set() for idx, seed in enumerate(seed_ids): if idx >= 500: break parts = seed.lower().split("-") if len(parts) != 5: continue try: block4_value = int(parts[3], 16) tail_value = int(parts[4], 16) except ValueError: continue for delta in range(-12, 13): if delta == 0: continue next_tail = (tail_value + delta) & ((1 << 48) - 1) candidate = f"{parts[0]}-{parts[1]}-{parts[2]}-{parts[3]}-{next_tail:012x}" if is_valid_uuid(candidate): candidates.add(candidate) for delta in (-2, -1, 1, 2): next_block4 = (block4_value + delta) & 0xFFFF candidate = f"{parts[0]}-{parts[1]}-{parts[2]}-{next_block4:04x}-{parts[4]}" if is_valid_uuid(candidate): candidates.add(candidate) if len(candidates) >= limit: break return list(candidates)[:limit] def probe_cdn_exists( session: requests.Session, song_id: str, limiter: RateLimiter, ) -> bool: cdn_url = f"https://cdn1.suno.ai/{song_id}.mp3" headers = dict(session.headers) headers["Range"] = "bytes=0-0" resp = request_with_retry( session, "GET", cdn_url, limiter, headers=headers, stream=True, timeout=25, max_attempts=4, ) if resp is None: logger.warning(f"CDN probe failed for {song_id}") return False try: if resp.status_code in {200, 206}: return True if resp.status_code in {403, 404}: return False logger.warning(f"Unexpected CDN probe status {resp.status_code} for {song_id}") return False finally: resp.close() def discover_from_cdn_patterns( session: requests.Session, limiter: RateLimiter, seed_ids: Iterable[str], seen_uuids: Set[str], candidate_queue: Deque[str], discovery_sources: Dict[str, Set[str]], ) -> int: added = 0 probe_candidates = generate_pattern_candidates(seed_ids) for song_id in probe_candidates: normalized = song_id.lower() if normalized in seen_uuids: continue if probe_cdn_exists(session, normalized, limiter): if maybe_add_uuid( normalized, "cdn_pattern", seen_uuids, candidate_queue, discovery_sources, ): added += 1 logger.info(f"CDN pattern probing added {added} UUIDs") return added def fetch_song_page_info( session: requests.Session, song_id: str, limiter: RateLimiter, ) -> Dict[str, Any]: page_url = f"https://suno.com/song/{song_id}" resp = request_with_retry(session, "GET", page_url, limiter, timeout=40) if resp is None: logger.warning(f"Failed to fetch Suno song page: {page_url}") return { "title": "untitled", "version": "unknown", "tags": [], "model_name": "", "source_url": page_url, "html": "", "related_ids": [], } if resp.status_code >= 400: logger.warning(f"Song page HTTP {resp.status_code} for {page_url}") resp.close() return { "title": "untitled", "version": "unknown", "tags": [], "model_name": "", "source_url": page_url, "html": "", "related_ids": [], } html_text = resp.text or "" resp.close() raw_version_match = RAW_VERSION_RE.search(html_text) raw_model_name_match = RAW_MODEL_NAME_RE.search(html_text) raw_version = raw_version_match.group(1).strip() if raw_version_match else None raw_model_name = ( raw_model_name_match.group(1).strip() if raw_model_name_match else None ) detected_version = detect_version_from_page(html_text, raw_version, raw_model_name) title = extract_title_from_html(html_text) tags: List[str] = [] tags_match = RAW_TAGS_RE.search(html_text) if tags_match: raw_tags = decode_json_string(tags_match.group(1)) tags = normalize_tags(raw_tags) related_ids = [] for related in extract_song_ids_from_text(html_text): if related != song_id.lower(): related_ids.append(related) return { "title": title, "version": detected_version, "tags": tags, "model_name": raw_model_name or "", "source_url": page_url, "html": html_text, "related_ids": related_ids, } def download_track_with_retry( session: requests.Session, song_id: str, output_path: Path, limiter: RateLimiter, ) -> bool: cdn_url = f"https://cdn1.suno.ai/{song_id}.mp3" if not probe_cdn_exists(session, song_id, limiter): return False delay = 2.0 tmp_path = output_path.with_suffix(output_path.suffix + ".part") for attempt in range(1, 5): limiter.wait() try: resp = session.get(cdn_url, timeout=60, stream=True) except requests.RequestException as exc: logger.warning(f"Download request failed for {song_id}: {exc}") if attempt == 4: return False time.sleep(delay) delay = min(delay * 2, 30) continue if resp.status_code == 429: retry_after = resp.headers.get("Retry-After") wait_seconds = delay if retry_after: try: wait_seconds = max(wait_seconds, float(retry_after)) except ValueError: pass logger.warning(f"CDN 429 for {song_id}; retrying after {wait_seconds:.1f}s") resp.close() time.sleep(wait_seconds) delay = min(delay * 2, 30) continue if resp.status_code in {403, 404}: resp.close() return False if resp.status_code >= 400: logger.warning( f"CDN download HTTP {resp.status_code} for {song_id} attempt {attempt}/4" ) resp.close() if attempt == 4: return False time.sleep(delay) delay = min(delay * 2, 30) continue try: output_path.parent.mkdir(parents=True, exist_ok=True) with open(tmp_path, "wb") as fout: for chunk in resp.iter_content(chunk_size=8192): if chunk: fout.write(chunk) except Exception as exc: logger.warning(f"Failed writing file for {song_id}: {exc}") resp.close() tmp_path.unlink(missing_ok=True) if attempt == 4: return False time.sleep(delay) delay = min(delay * 2, 30) continue finally: resp.close() if not tmp_path.exists() or tmp_path.stat().st_size < 1000: logger.warning(f"Downloaded file too small for {song_id}") tmp_path.unlink(missing_ok=True) if attempt == 4: return False time.sleep(delay) delay = min(delay * 2, 30) continue tmp_path.replace(output_path) return True return False def build_progress_desc(counts: Dict[str, int], total_target: int) -> str: total_done = sum(counts.get(v, 0) for v in TARGET_VERSIONS) return ( f"suno_all: {total_done}/{total_target} " f"[versions: v3={counts.get('v3', 0)}, " f"v3.5={counts.get('v3.5', 0)}, " f"v4={counts.get('v4', 0)}, " f"v5.5={counts.get('v5.5', 0)}, " f"studio={counts.get('studio', 0)}]" ) def initialize_managers(base_output_dir: Path) -> Dict[str, MetadataManager]: managers: Dict[str, MetadataManager] = {} for version in TARGET_VERSIONS: folder_name = VERSION_TO_SUBDIR[version] folder = base_output_dir / folder_name folder.mkdir(parents=True, exist_ok=True) managers[version] = MetadataManager(folder) return managers def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--target", type=int, default=2000) parser.add_argument( "--output-dir", type=str, default=str(FAKE_DIR / "A_commercial"), ) args = parser.parse_args() base_output_dir = Path(args.output_dir) base_output_dir.mkdir(parents=True, exist_ok=True) managers = initialize_managers(base_output_dir) counts = {version: mgr.get_count() for version, mgr in managers.items()} downloads_since_summary = {version: 0 for version in TARGET_VERSIONS} completed_versions: Set[str] = { version for version in TARGET_VERSIONS if counts.get(version, 0) >= args.target } if len(completed_versions) == len(TARGET_VERSIONS): logger.info("All Suno folders already satisfy target") for manager in managers.values(): manager.update_summary() return session = requests.Session() session.headers.update( { "User-Agent": USER_AGENT, "Accept": "text/html,application/json;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9", "Referer": "https://suno.com/", } ) search_limiter = RateLimiter(requests_per_second=1.0) download_limiter = RateLimiter(requests_per_second=1.5) total_target = args.target * len(TARGET_VERSIONS) progress = tqdm( total=total_target, initial=sum(counts.values()), desc=build_progress_desc(counts, total_target), unit="track", ) seen_uuids: Set[str] = set() processed_uuids: Set[str] = set() discovery_sources: Dict[str, Set[str]] = {} candidate_queue: Deque[str] = deque() for version, manager in managers.items(): folder = base_output_dir / VERSION_TO_SUBDIR[version] jsonl_path = folder / "metadata.jsonl" if not jsonl_path.exists(): continue try: with open(jsonl_path, "r", encoding="utf-8") as fin: for line in fin: try: data = json.loads(line.strip()) except json.JSONDecodeError: continue track_id = str(data.get("track_id") or "").strip().lower() if is_valid_uuid(track_id): seen_uuids.add(track_id) processed_uuids.add(track_id) except Exception as exc: logger.warning(f"Failed loading existing IDs from {jsonl_path}: {exc}") no_progress_rounds = 0 try: discover_reddit_paginated( session, search_limiter, seen_uuids, candidate_queue, discovery_sources ) discover_from_youtube( search_limiter, seen_uuids, candidate_queue, discovery_sources ) discover_from_suno_seed_pages( session, search_limiter, seen_uuids, candidate_queue, discovery_sources ) discover_from_huggingface( session, search_limiter, seen_uuids, candidate_queue, discovery_sources ) discover_from_feed_api( session, search_limiter, seen_uuids, candidate_queue, discovery_sources ) while len(completed_versions) < len(TARGET_VERSIONS): if not ensure_disk_space(): logger.warning("Stopping due to insufficient disk space") break if not candidate_queue: added = discover_from_cdn_patterns( session, search_limiter, seen_uuids, seen_uuids, candidate_queue, discovery_sources, ) if added == 0: no_progress_rounds += 1 if no_progress_rounds >= 2: logger.warning("No more candidate UUIDs available; stopping") break else: no_progress_rounds = 0 continue song_id = candidate_queue.popleft() if song_id in processed_uuids: continue processed_uuids.add(song_id) if not probe_cdn_exists(session, song_id, download_limiter): continue page_info = fetch_song_page_info(session, song_id, search_limiter) for related_id in page_info.get("related_ids", []): maybe_add_uuid( related_id, f"song_page_related:{song_id}", seen_uuids, candidate_queue, discovery_sources, ) detected_version = str(page_info.get("version") or "unknown") folder_version = map_version_for_folder(detected_version) if folder_version not in managers: continue if counts.get(folder_version, 0) >= args.target: completed_versions.add(folder_version) continue manager = managers[folder_version] out_dir = base_output_dir / VERSION_TO_SUBDIR[folder_version] if manager.has_track(song_id): existing = ensure_track_path(out_dir, song_id) if existing: continue title = str(page_info.get("title") or "untitled") filename = f"{song_id}_{sanitize_filename(title)}.mp3" file_path = out_dir / filename if file_path.exists() and file_path.stat().st_size > 1000: continue source_list = sorted(discovery_sources.get(song_id, {"unknown"})) logger.info(f"Processing {song_id} from sources: {','.join(source_list)}") ok = download_track_with_retry( session, song_id, file_path, download_limiter ) if not ok: continue audio_info = get_audio_info(file_path) tags = normalize_tags(page_info.get("tags") or []) meta = TrackMetadata( track_id=song_id, filename=filename, category="A_commercial", subcategory=VERSION_TO_SUBDIR[folder_version], source_platform="suno", source_type="commercial", model_name="Suno", model_version=folder_version, title=title, prompt=None, genre=None, tags=tags, source_url=f"https://suno.com/song/{song_id}", download_url=f"https://cdn1.suno.ai/{song_id}.mp3", 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), ) manager.add_track(meta) counts[folder_version] = manager.get_count() progress.update(1) progress.set_description(build_progress_desc(counts, total_target)) downloads_since_summary[folder_version] += 1 if downloads_since_summary[folder_version] >= 25: manager.update_summary() downloads_since_summary[folder_version] = 0 if counts.get(folder_version, 0) >= args.target: completed_versions.add(folder_version) no_progress_rounds = 0 finally: for manager in managers.values(): manager.update_summary() progress.close() logger.info( "Finished Suno crawl with counts: " + ", ".join(f"{v}={counts.get(v, 0)}" for v in TARGET_VERSIONS) ) if __name__ == "__main__": main()