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 | |
| # pyright: basic, reportDeprecated=false, reportUnknownParameterType=false, reportMissingTypeArgument=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnusedCallResult=false, reportUnusedImport=false | |
| import argparse | |
| import html | |
| import json | |
| import re | |
| import time | |
| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| from typing import Any, Dict, Iterable, List, Optional, Set, Tuple | |
| from urllib.parse import urljoin, urlparse | |
| 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" | |
| ) | |
| SITEMAP_URL = "https://www.mureka.ai/sitemap.xml" | |
| HOME_URL = "https://www.mureka.ai/home" | |
| API_BASE = "https://www.mureka.ai" | |
| CDN_BASE = "https://static-cos.mureka.ai" | |
| SUPPORTED_VERSIONS = ["v6", "v7.5", "v8"] | |
| DEFAULT_TARGET = 2000 | |
| MAX_GENRE_PAGES = 300 | |
| 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 detect_version_from_text(text: str) -> Optional[str]: | |
| t = (text or "").lower() | |
| if "v7.5" in t or "7.5" in t or re.search(r"\bv7\b", t): | |
| return "v7.5" | |
| if re.search(r"\bv8\b", t): | |
| return "v8" | |
| if re.search(r"\bv6\b", t): | |
| return "v6" | |
| return None | |
| def detect_version( | |
| song: Dict[str, Any], feed: Optional[Dict[str, Any]] = None | |
| ) -> Optional[str]: | |
| candidates = [ | |
| song.get("model"), | |
| song.get("model_version"), | |
| song.get("modelVersion"), | |
| (song.get("model_bandage") or {}).get("display_name") | |
| if isinstance(song.get("model_bandage"), dict) | |
| else None, | |
| (feed or {}).get("model"), | |
| song.get("title"), | |
| song.get("description"), | |
| ] | |
| for value in candidates: | |
| detected = detect_version_from_text(str(value) if value is not None else "") | |
| if detected: | |
| return detected | |
| return None | |
| def canonicalize_mp3_url(raw_url: str) -> Optional[str]: | |
| if not raw_url: | |
| return None | |
| value = html.unescape(str(raw_url).strip()) | |
| if not value: | |
| return None | |
| if value.startswith("http://") or value.startswith("https://"): | |
| return value | |
| cleaned = value.lstrip("/") | |
| if not cleaned: | |
| return None | |
| return f"{CDN_BASE}/{cleaned}" | |
| def build_source_url(song: Dict[str, Any]) -> Optional[str]: | |
| share_key = str(song.get("share_key") or "").strip() | |
| if share_key: | |
| return f"https://www.mureka.ai/song-detail/{share_key}?is_from_share=1" | |
| song_id = str(song.get("song_id") or "").strip() | |
| if song_id: | |
| return f"https://www.mureka.ai/song-detail/{song_id}" | |
| return None | |
| def request_with_backoff( | |
| session: requests.Session, | |
| method: str, | |
| url: str, | |
| limiter: RateLimiter, | |
| *, | |
| params: Optional[Dict[str, Any]] = None, | |
| timeout: int = 30, | |
| max_retries: int = 5, | |
| ) -> Optional[requests.Response]: | |
| delay = 1.0 | |
| for attempt in range(1, max_retries + 1): | |
| limiter.wait() | |
| try: | |
| resp = session.request( | |
| method=method.upper(), url=url, params=params, timeout=timeout | |
| ) | |
| except requests.RequestException as exc: | |
| if attempt == max_retries: | |
| logger.warning(f"Request failed for {url}: {exc}") | |
| return None | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| 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 from {url}; retrying in {wait_seconds:.1f}s") | |
| resp.close() | |
| time.sleep(min(wait_seconds, 30)) | |
| delay *= 2 | |
| continue | |
| if resp.status_code >= 500: | |
| logger.warning(f"Server error {resp.status_code} from {url}") | |
| resp.close() | |
| if attempt == max_retries: | |
| return None | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| continue | |
| return resp | |
| return None | |
| def fetch_json( | |
| session: requests.Session, | |
| endpoint: str, | |
| limiter: RateLimiter, | |
| params: Optional[Dict[str, Any]] = None, | |
| ) -> Optional[Dict[str, Any]]: | |
| url = endpoint if endpoint.startswith("http") else urljoin(API_BASE, endpoint) | |
| resp = request_with_backoff(session, "GET", url, limiter, params=params) | |
| if resp is None: | |
| return None | |
| try: | |
| if resp.status_code in {403, 404}: | |
| logger.warning(f"Skipping {url} with HTTP {resp.status_code}") | |
| return None | |
| if resp.status_code >= 400: | |
| logger.warning(f"HTTP {resp.status_code} for {url}") | |
| return None | |
| data = resp.json() | |
| if isinstance(data, dict): | |
| return data | |
| return None | |
| except ValueError: | |
| logger.warning(f"Failed to parse JSON from {url}") | |
| return None | |
| finally: | |
| resp.close() | |
| def fetch_text( | |
| session: requests.Session, | |
| url: str, | |
| limiter: RateLimiter, | |
| ) -> Optional[str]: | |
| resp = request_with_backoff(session, "GET", url, limiter) | |
| if resp is None: | |
| return None | |
| try: | |
| if resp.status_code in {403, 404}: | |
| logger.warning(f"Skipping {url} with HTTP {resp.status_code}") | |
| return None | |
| if resp.status_code >= 400: | |
| logger.warning(f"HTTP {resp.status_code} for {url}") | |
| return None | |
| return resp.text | |
| finally: | |
| resp.close() | |
| def parse_genre_pages_from_sitemap(xml_text: str) -> List[Tuple[str, int, str]]: | |
| pages: List[Tuple[str, int, str]] = [] | |
| try: | |
| root = ET.fromstring(xml_text) | |
| except ET.ParseError as exc: | |
| logger.warning(f"Failed to parse sitemap XML: {exc}") | |
| return pages | |
| namespace = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"} | |
| loc_nodes = root.findall("sm:url/sm:loc", namespace) | |
| seen_ids: Set[int] = set() | |
| for loc in loc_nodes: | |
| raw = (loc.text or "").strip() | |
| if "/genre/" not in raw: | |
| continue | |
| match = re.search(r"/genre/([^/]+)/([0-9]+)", raw) | |
| if not match: | |
| continue | |
| slug = match.group(1) | |
| genre_id = int(match.group(2)) | |
| if genre_id in seen_ids: | |
| continue | |
| seen_ids.add(genre_id) | |
| pages.append((raw, genre_id, slug)) | |
| return pages | |
| def extract_api_endpoints_from_text(text: str) -> Set[str]: | |
| found: Set[str] = set() | |
| if not text: | |
| return found | |
| for rel in re.findall(r'"(/api/[^"\s]+)"', text): | |
| if "{" in rel or "}" in rel: | |
| continue | |
| found.add(urljoin(API_BASE, rel)) | |
| for rel in re.findall(r"'(/api/[^'\s]+)'", text): | |
| if "{" in rel or "}" in rel: | |
| continue | |
| found.add(urljoin(API_BASE, rel)) | |
| return found | |
| def collect_song_like_nodes(node: Any, out: List[Dict[str, Any]]) -> None: | |
| if isinstance(node, dict): | |
| if node.get("song_id") and (node.get("mp3_url") or node.get("song_url")): | |
| out.append(node) | |
| for value in node.values(): | |
| if isinstance(value, (dict, list)): | |
| collect_song_like_nodes(value, out) | |
| elif isinstance(node, list): | |
| for value in node: | |
| if isinstance(value, (dict, list)): | |
| collect_song_like_nodes(value, out) | |
| def extract_embedded_song_candidates( | |
| html_text: str, | |
| source_url: str, | |
| genre_hint: Optional[str] = None, | |
| ) -> List[Dict[str, Any]]: | |
| candidates: List[Dict[str, Any]] = [] | |
| if not html_text: | |
| return candidates | |
| json_blobs: List[str] = [] | |
| for pat in [ | |
| r"window\.__INITIAL_STATE__\s*=\s*(\{.*?\});", | |
| r"window\.__NEXT_DATA__\s*=\s*(\{.*?\});", | |
| r"window\.__INITIAL_DATA__\s*=\s*(\{.*?\});", | |
| ]: | |
| json_blobs.extend(re.findall(pat, html_text, flags=re.DOTALL)) | |
| script_json_blobs = re.findall( | |
| r'<script[^>]*type="application/json"[^>]*>(.*?)</script>', | |
| html_text, | |
| flags=re.DOTALL | re.IGNORECASE, | |
| ) | |
| json_blobs.extend(script_json_blobs) | |
| for blob in json_blobs: | |
| text = blob.strip() | |
| if not text.startswith("{"): | |
| continue | |
| try: | |
| payload = json.loads(text) | |
| except ValueError: | |
| continue | |
| nodes: List[Dict[str, Any]] = [] | |
| collect_song_like_nodes(payload, nodes) | |
| for song in nodes: | |
| candidates.append( | |
| { | |
| "song": song, | |
| "feed": {}, | |
| "source_hint": f"embedded:{source_url}", | |
| "genre_hint": genre_hint, | |
| } | |
| ) | |
| return candidates | |
| def to_song_candidate( | |
| song: Dict[str, Any], | |
| feed: Optional[Dict[str, Any]], | |
| source_hint: str, | |
| genre_hint: Optional[str], | |
| ) -> Optional[Dict[str, Any]]: | |
| song_id = str(song.get("song_id") or "").strip() | |
| if not song_id: | |
| return None | |
| download_url = canonicalize_mp3_url( | |
| str(song.get("mp3_url") or song.get("song_url") or "") | |
| ) | |
| if not download_url: | |
| return None | |
| title = str(song.get("title") or "untitled").strip() or "untitled" | |
| version = detect_version(song, feed) | |
| genres = normalize_tags(song.get("genres") or []) | |
| moods = normalize_tags(song.get("moods") or []) | |
| description = str(song.get("description") or "").strip() or None | |
| tags = list(dict.fromkeys([*genres, *moods])) | |
| if genre_hint and genre_hint not in genres: | |
| genres = [*genres, genre_hint] | |
| return { | |
| "track_id": song_id, | |
| "title": title, | |
| "version": version, | |
| "prompt": description, | |
| "genre": genres[0] if genres else genre_hint, | |
| "genres": genres, | |
| "moods": moods, | |
| "tags": tags, | |
| "source_url": build_source_url(song), | |
| "download_url": download_url, | |
| "source_hint": source_hint, | |
| } | |
| def pick_version_for_candidate( | |
| detected: Optional[str], | |
| requested_versions: List[str], | |
| counts: Dict[str, int], | |
| target: int, | |
| fallback_counter: List[int], | |
| ) -> Optional[str]: | |
| pending = [v for v in requested_versions if counts.get(v, 0) < target] | |
| if not pending: | |
| return None | |
| if detected in pending: | |
| return detected | |
| if len(requested_versions) == 1: | |
| only = requested_versions[0] | |
| return only if counts.get(only, 0) < target else None | |
| min_count = min(counts.get(v, 0) for v in pending) | |
| min_versions = [v for v in pending if counts.get(v, 0) == min_count] | |
| idx = fallback_counter[0] % len(min_versions) | |
| fallback_counter[0] += 1 | |
| return min_versions[idx] | |
| def load_existing_track_ids(managers: Dict[str, MetadataManager]) -> Set[str]: | |
| seen: Set[str] = set() | |
| for manager in managers.values(): | |
| jsonl_path = manager.folder_path / "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() | |
| if track_id: | |
| seen.add(track_id) | |
| except Exception as exc: | |
| logger.warning(f"Failed loading existing metadata from {jsonl_path}: {exc}") | |
| return seen | |
| def download_with_backoff( | |
| session: requests.Session, | |
| url: str, | |
| output_path: Path, | |
| limiter: RateLimiter, | |
| max_retries: int = 5, | |
| ) -> bool: | |
| if output_path.exists() and output_path.stat().st_size > 1000: | |
| return True | |
| tmp_path = output_path.with_suffix(output_path.suffix + ".part") | |
| delay = 1.0 | |
| for attempt in range(1, max_retries + 1): | |
| limiter.wait() | |
| try: | |
| resp = session.get(url, timeout=60, stream=True) | |
| except requests.RequestException as exc: | |
| logger.warning(f"Download request failed for {url}: {exc}") | |
| if attempt == max_retries: | |
| return False | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| continue | |
| status = resp.status_code | |
| if status in {403, 404}: | |
| logger.warning(f"CDN returned {status} for {url}") | |
| resp.close() | |
| return False | |
| if status == 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 {url}; retrying in {wait_seconds:.1f}s") | |
| resp.close() | |
| time.sleep(min(wait_seconds, 30)) | |
| delay *= 2 | |
| continue | |
| if status >= 500: | |
| logger.warning(f"CDN server error {status} for {url}") | |
| resp.close() | |
| if attempt == max_retries: | |
| return False | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| continue | |
| if status >= 400: | |
| logger.warning(f"CDN HTTP {status} for {url}") | |
| resp.close() | |
| return False | |
| 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 {output_path}: {exc}") | |
| tmp_path.unlink(missing_ok=True) | |
| resp.close() | |
| if attempt == max_retries: | |
| return False | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| continue | |
| finally: | |
| resp.close() | |
| if not tmp_path.exists() or tmp_path.stat().st_size < 1000: | |
| logger.warning(f"Downloaded file too small for {url}") | |
| tmp_path.unlink(missing_ok=True) | |
| if attempt == max_retries: | |
| return False | |
| time.sleep(min(delay, 30)) | |
| delay *= 2 | |
| continue | |
| tmp_path.replace(output_path) | |
| return True | |
| return False | |
| def create_track_metadata( | |
| candidate: Dict[str, Any], | |
| file_path: Path, | |
| version: str, | |
| ) -> TrackMetadata: | |
| audio_info = get_audio_info(file_path) | |
| tags = normalize_tags(candidate.get("tags") or []) | |
| for extra_tag in [ | |
| *(candidate.get("genres") or []), | |
| *(candidate.get("moods") or []), | |
| ]: | |
| if extra_tag and extra_tag not in tags: | |
| tags.append(extra_tag) | |
| if "mureka" not in [t.lower() for t in tags]: | |
| tags.append("mureka") | |
| return TrackMetadata( | |
| track_id=str(candidate.get("track_id") or ""), | |
| filename=file_path.name, | |
| category="A_commercial", | |
| subcategory=f"mureka_{version}", | |
| source_platform="mureka", | |
| source_type="commercial", | |
| model_name="Mureka", | |
| model_version=version, | |
| title=str(candidate.get("title") or "untitled"), | |
| prompt=str(candidate.get("prompt")) if candidate.get("prompt") else None, | |
| genre=str(candidate.get("genre")) if candidate.get("genre") else None, | |
| tags=tags, | |
| source_url=str(candidate.get("source_url")) | |
| if candidate.get("source_url") | |
| else None, | |
| download_url=str(candidate.get("download_url") or ""), | |
| 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), | |
| ) | |
| def process_candidate( | |
| session: requests.Session, | |
| candidate: Dict[str, Any], | |
| requested_versions: List[str], | |
| managers: Dict[str, MetadataManager], | |
| output_dirs: Dict[str, Path], | |
| counts: Dict[str, int], | |
| seen_song_ids: Set[str], | |
| target: int, | |
| fallback_counter: List[int], | |
| download_limiter: RateLimiter, | |
| progress: tqdm, | |
| ) -> bool: | |
| track_id = str(candidate.get("track_id") or "").strip() | |
| if not track_id or track_id in seen_song_ids: | |
| return False | |
| selected_version = pick_version_for_candidate( | |
| candidate.get("version"), | |
| requested_versions, | |
| counts, | |
| target, | |
| fallback_counter, | |
| ) | |
| if not selected_version: | |
| return False | |
| manager = managers[selected_version] | |
| output_dir = output_dirs[selected_version] | |
| title = str(candidate.get("title") or "untitled").strip() or "untitled" | |
| filename = f"{track_id}_{sanitize_filename(title)}.mp3" | |
| file_path = output_dir / filename | |
| if ( | |
| manager.has_track(track_id) | |
| and file_path.exists() | |
| and file_path.stat().st_size > 1000 | |
| ): | |
| seen_song_ids.add(track_id) | |
| return False | |
| if not ensure_disk_space(): | |
| logger.warning("Stopping due to insufficient disk space") | |
| return False | |
| download_url = str(candidate.get("download_url") or "") | |
| if not download_url: | |
| return False | |
| ok = download_with_backoff(session, download_url, file_path, download_limiter) | |
| if not ok: | |
| return False | |
| meta = create_track_metadata(candidate, file_path, selected_version) | |
| manager.add_track(meta) | |
| counts[selected_version] = manager.get_count() | |
| seen_song_ids.add(track_id) | |
| progress.update(1) | |
| return True | |
| def build_progress_desc( | |
| counts: Dict[str, int], target: int, requested_versions: List[str] | |
| ) -> str: | |
| pieces = [f"{v}={counts.get(v, 0)}/{target}" for v in requested_versions] | |
| total = sum(counts.get(v, 0) for v in requested_versions) | |
| return f"mureka: {total}/{target * len(requested_versions)} [{', '.join(pieces)}]" | |
| def resolve_output_dirs(version: str, output_dir: Optional[str]) -> Dict[str, Path]: | |
| if version == "all": | |
| base = Path(output_dir) if output_dir else FAKE_DIR / "A_commercial" | |
| return {v: base / f"mureka_{v}" for v in SUPPORTED_VERSIONS} | |
| if output_dir: | |
| return {version: Path(output_dir)} | |
| return {version: FAKE_DIR / "A_commercial" / f"mureka_{version}"} | |
| def extract_genre_hint(slug: str) -> str: | |
| return slug.replace("%20", " ").replace("-", " ").strip() | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--target", type=int, default=DEFAULT_TARGET) | |
| parser.add_argument( | |
| "--version", | |
| type=str, | |
| default="all", | |
| choices=["v6", "v7.5", "v8", "all"], | |
| ) | |
| parser.add_argument("--output-dir", type=str, default=None) | |
| args = parser.parse_args() | |
| requested_versions = SUPPORTED_VERSIONS if args.version == "all" else [args.version] | |
| output_dirs = resolve_output_dirs(args.version, args.output_dir) | |
| for out_dir in output_dirs.values(): | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| managers = {v: MetadataManager(output_dirs[v]) for v in requested_versions} | |
| counts = {v: managers[v].get_count() for v in requested_versions} | |
| seen_song_ids = load_existing_track_ids(managers) | |
| if all(counts[v] >= args.target for v in requested_versions): | |
| logger.info("Requested Mureka targets already satisfied") | |
| for manager in managers.values(): | |
| manager.update_summary() | |
| return | |
| session = requests.Session() | |
| session.headers.update( | |
| { | |
| "User-Agent": USER_AGENT, | |
| "Accept": "application/json,text/plain,text/html,*/*", | |
| "Referer": "https://www.mureka.ai/home", | |
| } | |
| ) | |
| page_limiter = RateLimiter(requests_per_second=1.0) | |
| download_limiter = RateLimiter(requests_per_second=2.0) | |
| fallback_counter = [0] | |
| progress = tqdm( | |
| total=args.target * len(requested_versions), | |
| initial=sum(counts.values()), | |
| desc=build_progress_desc(counts, args.target, requested_versions), | |
| unit="track", | |
| ) | |
| known_api_endpoints: Set[str] = { | |
| f"{API_BASE}/api/pgc/song/songs_by_genre", | |
| f"{API_BASE}/api/pgc/home/modules", | |
| f"{API_BASE}/api/pgc/home/modules/featured-songs", | |
| f"{API_BASE}/api/pgc/home/modules/featured-playlist", | |
| f"{API_BASE}/api/pgc/song/recommend_list", | |
| } | |
| def targets_filled() -> bool: | |
| return all(counts.get(v, 0) >= args.target for v in requested_versions) | |
| try: | |
| sitemap_text = fetch_text(session, SITEMAP_URL, page_limiter) | |
| genre_pages = parse_genre_pages_from_sitemap(sitemap_text or "") | |
| logger.info(f"Discovered {len(genre_pages)} genre pages from sitemap") | |
| home_html = fetch_text(session, HOME_URL, page_limiter) | |
| if home_html: | |
| known_api_endpoints.update(extract_api_endpoints_from_text(home_html)) | |
| for embedded in extract_embedded_song_candidates(home_html, HOME_URL): | |
| candidate = to_song_candidate( | |
| embedded.get("song") or {}, | |
| embedded.get("feed") or {}, | |
| embedded.get("source_hint") or "embedded:home", | |
| embedded.get("genre_hint"), | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| progress.set_description( | |
| build_progress_desc(counts, args.target, requested_versions) | |
| ) | |
| if not targets_filled(): | |
| modules_payload = fetch_json( | |
| session, | |
| "/api/pgc/home/modules", | |
| page_limiter, | |
| params={"page_size": 20}, | |
| ) | |
| module_feeds = ( | |
| ((modules_payload or {}).get("data") or {}).get("feeds") | |
| if isinstance((modules_payload or {}).get("data"), dict) | |
| else [] | |
| ) | |
| if isinstance(module_feeds, list): | |
| for module in module_feeds: | |
| if not isinstance(module, dict): | |
| continue | |
| module_id = module.get("id") | |
| module_type = module.get("type") | |
| if not module_id: | |
| continue | |
| endpoint = None | |
| if module_type == 100: | |
| endpoint = "/api/pgc/home/modules/featured-songs" | |
| elif module_type in {101, 102}: | |
| endpoint = "/api/pgc/home/modules/featured-playlist" | |
| if not endpoint: | |
| continue | |
| payload = fetch_json( | |
| session, | |
| endpoint, | |
| page_limiter, | |
| params={"module_id": module_id}, | |
| ) | |
| if not payload: | |
| continue | |
| data = payload.get("data") if isinstance(payload, dict) else None | |
| if not isinstance(data, dict): | |
| continue | |
| if endpoint.endswith("featured-songs"): | |
| raw_featured_song_feeds = data.get("feeds") | |
| featured_song_feeds: List[Any] = ( | |
| raw_featured_song_feeds | |
| if isinstance(raw_featured_song_feeds, list) | |
| else [] | |
| ) | |
| for feed in featured_song_feeds: | |
| if not isinstance(feed, dict): | |
| continue | |
| raw_song = feed.get("song") | |
| module_song_dict: Dict[str, Any] = ( | |
| raw_song if isinstance(raw_song, dict) else {} | |
| ) | |
| candidate = to_song_candidate( | |
| module_song_dict, | |
| feed, | |
| f"home:module:{module_id}", | |
| None, | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| progress.set_description( | |
| build_progress_desc( | |
| counts, args.target, requested_versions | |
| ) | |
| ) | |
| if targets_filled(): | |
| break | |
| if endpoint.endswith("featured-playlist"): | |
| raw_playlists = data.get("play_lists") | |
| playlists: List[Any] = ( | |
| raw_playlists if isinstance(raw_playlists, list) else [] | |
| ) | |
| for playlist in playlists: | |
| if not isinstance(playlist, dict): | |
| continue | |
| raw_playlist_feeds = playlist.get("feeds") | |
| playlist_feeds: List[Any] = ( | |
| raw_playlist_feeds | |
| if isinstance(raw_playlist_feeds, list) | |
| else [] | |
| ) | |
| for feed in playlist_feeds: | |
| if not isinstance(feed, dict): | |
| continue | |
| raw_song = feed.get("song") | |
| playlist_song_dict: Dict[str, Any] = ( | |
| raw_song if isinstance(raw_song, dict) else {} | |
| ) | |
| candidate = to_song_candidate( | |
| playlist_song_dict, | |
| feed, | |
| f"home:playlist:{module_id}:{playlist.get('id')}", | |
| None, | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| progress.set_description( | |
| build_progress_desc( | |
| counts, args.target, requested_versions | |
| ) | |
| ) | |
| if targets_filled(): | |
| break | |
| if targets_filled(): | |
| break | |
| if targets_filled(): | |
| break | |
| for genre_url, genre_id, slug in genre_pages: | |
| if targets_filled(): | |
| break | |
| genre_hint = extract_genre_hint(slug) | |
| genre_html = fetch_text(session, genre_url, page_limiter) | |
| if genre_html: | |
| known_api_endpoints.update(extract_api_endpoints_from_text(genre_html)) | |
| for embedded in extract_embedded_song_candidates( | |
| genre_html, genre_url, genre_hint | |
| ): | |
| candidate = to_song_candidate( | |
| embedded.get("song") or {}, | |
| embedded.get("feed") or {}, | |
| embedded.get("source_hint") or f"embedded:{genre_url}", | |
| embedded.get("genre_hint") or genre_hint, | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| progress.set_description( | |
| build_progress_desc(counts, args.target, requested_versions) | |
| ) | |
| if targets_filled(): | |
| break | |
| last_id = 0 | |
| for _ in range(MAX_GENRE_PAGES): | |
| if targets_filled() or not ensure_disk_space(): | |
| break | |
| params = {"genre_id": genre_id, "size": 20} | |
| if last_id: | |
| params["last_id"] = last_id | |
| payload = fetch_json( | |
| session, | |
| "/api/pgc/song/songs_by_genre", | |
| page_limiter, | |
| params=params, | |
| ) | |
| if not payload: | |
| break | |
| data = payload.get("data") if isinstance(payload, dict) else None | |
| if not isinstance(data, dict): | |
| break | |
| raw_genre_feeds = data.get("feeds") | |
| genre_feeds: List[Any] = ( | |
| raw_genre_feeds if isinstance(raw_genre_feeds, list) else [] | |
| ) | |
| if not genre_feeds: | |
| break | |
| added_this_page = 0 | |
| for feed in genre_feeds: | |
| if not isinstance(feed, dict): | |
| continue | |
| raw_song = feed.get("song") | |
| genre_song_dict: Dict[str, Any] = ( | |
| raw_song if isinstance(raw_song, dict) else {} | |
| ) | |
| candidate = to_song_candidate( | |
| genre_song_dict, | |
| feed, | |
| f"genre_api:{genre_id}", | |
| genre_hint, | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| added_this_page += 1 | |
| progress.set_description( | |
| build_progress_desc(counts, args.target, requested_versions) | |
| ) | |
| if targets_filled(): | |
| break | |
| next_last_id = data.get("last_id") | |
| if not next_last_id or next_last_id == last_id: | |
| break | |
| last_id = int(next_last_id) | |
| if added_this_page == 0 and targets_filled(): | |
| break | |
| if not targets_filled(): | |
| recommend_payload = fetch_json( | |
| session, | |
| "/api/pgc/song/recommend_list", | |
| page_limiter, | |
| params={"size": 20}, | |
| ) | |
| data = ( | |
| recommend_payload.get("data") | |
| if isinstance(recommend_payload, dict) | |
| else None | |
| ) | |
| if isinstance(data, dict): | |
| raw_recommend_feeds = data.get("feeds") | |
| recommend_feeds: List[Any] = ( | |
| raw_recommend_feeds if isinstance(raw_recommend_feeds, list) else [] | |
| ) | |
| else: | |
| recommend_feeds = [] | |
| for feed in recommend_feeds: | |
| if not isinstance(feed, dict): | |
| continue | |
| raw_song = feed.get("song") | |
| recommend_song_dict: Dict[str, Any] = ( | |
| raw_song if isinstance(raw_song, dict) else {} | |
| ) | |
| candidate = to_song_candidate( | |
| recommend_song_dict, | |
| feed, | |
| "recommend_list", | |
| None, | |
| ) | |
| if not candidate: | |
| continue | |
| if process_candidate( | |
| session, | |
| candidate, | |
| requested_versions, | |
| managers, | |
| output_dirs, | |
| counts, | |
| seen_song_ids, | |
| args.target, | |
| fallback_counter, | |
| download_limiter, | |
| progress, | |
| ): | |
| progress.set_description( | |
| build_progress_desc(counts, args.target, requested_versions) | |
| ) | |
| if targets_filled(): | |
| break | |
| finally: | |
| for manager in managers.values(): | |
| manager.update_summary() | |
| progress.close() | |
| logger.info( | |
| "Finished Mureka crawl with counts: " | |
| + ", ".join(f"{v}={counts.get(v, 0)}" for v in requested_versions) | |
| ) | |
| logger.info(f"Discovered API hints: {len(known_api_endpoints)} endpoints") | |
| if __name__ == "__main__": | |
| main() | |