Buckets:
| #!/usr/bin/env python3 | |
| """Side-scrape the SAO-approved FMA tracks missing from fma_full.zip. | |
| The zip covers ids <= ~155k (pre-2017). The SAO attribution list spans ids | |
| up to 217,288; the ~7.5k tracks not in the zip must come from the live site. | |
| Strategy per track: | |
| 1. GET https://freemusicarchive.org/track/{id}/download (302 -> file, or page) | |
| 2. If HTML, parse for the trackfile download link and GET it. | |
| 3. Bank to /data/audio/{id}.mp3 (bucket, persistent), upload in batches. | |
| Politeness: >=0.5s between requests, single worker, per-track timeout, | |
| failures recorded and skipped. Resume: repo listing + bank scan + state file. | |
| """ | |
| import csv, io, json, os, re, sys, time | |
| import requests | |
| from huggingface_hub import HfApi, hf_hub_download, list_repo_files, create_commit, CommitOperationAdd | |
| DEST_REPO = "sassoshots/stableaudio-fma-music" | |
| ATTRIB_REPOS = ["audo/stable-audio-open-1.0", "stabilityai/stable-audio-open-1.0"] | |
| ATTRIB_FILE = "fma_dataset_attribution2.csv" | |
| BANK_DIR = "/data/audio" | |
| STATE_PATH = "/data/scrape_state.json" | |
| UPLOAD_EVERY = 200 | |
| TOKEN = os.environ.get("HF_TOKEN") | |
| UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) dataset-fetch/1.0"} | |
| DL_TIMEOUT = 60 | |
| MIN_BYTES = 32 * 1024 # refuse sub-32KB "mp3s" (error pages) | |
| def log(*a): | |
| print(*a, flush=True) | |
| def load_attribution(): | |
| last = None | |
| for repo in ATTRIB_REPOS: | |
| try: | |
| p = hf_hub_download(repo, ATTRIB_FILE, repo_type="model") | |
| rows = [] | |
| with open(p, newline="", encoding="utf-8") as f: | |
| for r in csv.DictReader(f): | |
| rows.append({"id": int(r["id"]), "url": (r.get("url") or "").strip()}) | |
| log(f"[attrib] {len(rows)} rows from {repo}") | |
| return rows | |
| except Exception as e: | |
| last = e | |
| raise RuntimeError(f"attribution fetch failed: {last}") | |
| def covered_ids(): | |
| ids = set() | |
| api = HfApi(token=TOKEN) | |
| for f in list_repo_files(DEST_REPO, repo_type="dataset", token=TOKEN): | |
| m = re.search(r"(?:^|/)(\d{6})", os.path.basename(f)) | |
| if m and f.endswith(".mp3"): | |
| ids.add(int(m.group(1))) | |
| if os.path.isdir(BANK_DIR): | |
| for n in os.listdir(BANK_DIR): | |
| m = re.match(r"^(\d{6})\.mp3$", n) | |
| if m: | |
| ids.add(int(m.group(1))) | |
| try: | |
| with open("/data/scrape_done.json") as f: | |
| ids |= set(json.load(f)) | |
| except Exception: | |
| pass | |
| return ids | |
| def resolve_download(tid, page_url, sess=None): | |
| # 1) canonical per-track download endpoint (302 -> file) | |
| for url in (f"https://freemusicarchive.org/track/{tid}/download", | |
| f"https://freemusicarchive.org/track/{tid}/download/"): | |
| try: | |
| r = requests.get(url, headers=UA, timeout=30, allow_redirects=True) | |
| if r.ok and r.headers.get("content-type", "").startswith(("audio", "application/octet-stream", "binary")): | |
| return r.content | |
| except Exception: | |
| pass | |
| time.sleep(0.6) | |
| # 2) page scrape fallback | |
| page = page_url or f"https://freemusicarchive.org/track/{tid}" | |
| try: | |
| r = requests.get(page, headers=UA, timeout=30) | |
| if not r.ok: | |
| return None | |
| m = re.search(r'href="([^"]+/trackfile/[^"]+)"', r.text) | |
| if not m: | |
| return None | |
| href = m.group(1) | |
| if href.startswith("/"): | |
| href = "https://freemusicarchive.org" + href | |
| r2 = requests.get(href, headers=UA, timeout=DL_TIMEOUT) | |
| if r2.ok and len(r2.content) > MIN_BYTES: | |
| return r2.content | |
| except Exception: | |
| pass | |
| return None | |
| def main(): | |
| os.makedirs(BANK_DIR, exist_ok=True) | |
| attrib = load_attribution() | |
| done = covered_ids() | |
| wanted = [r for r in attrib if r["id"] not in done] | |
| log(f"[plan] covered={len(done)} want={len(wanted)}") | |
| session_upload = [] | |
| ok = fail = 0 | |
| for i, row in enumerate(wanted): | |
| tid = row["id"] | |
| try: | |
| blob = resolve_download(tid, row["url"]) | |
| if blob is None or len(blob) <= MIN_BYTES: | |
| fail += 1 | |
| log(f"[miss] {tid}") | |
| else: | |
| path = os.path.join(BANK_DIR, f"{tid:06d}.mp3") | |
| with open(path, "wb") as w: | |
| w.write(blob) | |
| ok += 1 | |
| session_upload.append((tid, path, len(blob))) | |
| except Exception as e: | |
| fail += 1 | |
| log(f"[err] {tid}: {e!r}") | |
| if (i + 1) % 25 == 0: | |
| log(f"[progress] {i+1}/{len(wanted)} ok={ok} fail={fail}") | |
| time.sleep(0.5) # politeness | |
| # flush uploads | |
| if len(session_upload) >= UPLOAD_EVERY: | |
| flush(session_upload) | |
| flush(session_upload) | |
| log(f"[done] scraped={ok} failed={fail} total_covered={len(done)+ok}/13874") | |
| def flush(batch): | |
| if not batch: | |
| return | |
| from huggingface_hub import CommitOperationAdd | |
| ops = [CommitOperationAdd(path_in_repo=f"audio/{tid:06d}.mp3", | |
| path_or_fileobj=p) for tid, p, _ in batch] | |
| for attempt in range(5): | |
| try: | |
| create_commit(DEST_REPO, ops, repo_type="dataset", token=TOKEN, | |
| commit_message=f"FMA SAO scrape batch ({len(batch)} tracks)") | |
| log(f"[upload] +{len(batch)} (total banked this run)") | |
| batch.clear() | |
| return | |
| except Exception as e: | |
| log(f"[retry] upload attempt {attempt+1}: {e!r}") | |
| time.sleep(30 * (attempt + 1)) | |
| log("[error] upload failed after retries; blobs remain in bank, will resume") | |
| if __name__ == "__main__": | |
| main() |
Xet Storage Details
- Size:
- 5.66 kB
- Xet hash:
- 039cccfe40a4a8606b303793a91bd8439356bd532c1c93deeafa11eefa9e5a5e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.