Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / prepare-radio-library.py

Raw 4.0 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1#!/usr/bin/env python3
2"""Verify the exact Suno takes and prepare AAC copies plus an R2-ready catalog.
3
4Example:
5 python3 scripts/prepare-radio-library.py --handoff /path/to/HANDOFF.md --output build/radio
6Original audio is read only. No network requests or uploads are made.
7"""
8import argparse
9import hashlib
10import json
11from pathlib import Path
12import re
13import subprocess
14import unicodedata
15
16
17def probe(path):
18 return json.loads(subprocess.check_output([
19 "ffprobe", "-v", "error", "-show_format", "-show_streams", "-of", "json", str(path)
20 ]))
21
22
23def prepare(handoff, output, downloads):
24 text = handoff.read_text()
25 entries = re.split(r"^## \d+\. ", text, flags=re.M)[1:]
26 if not entries:
27 raise ValueError("No numbered song entries in handoff")
28 tracks = []
29 audio_dir = output / "audio"
30 audio_dir.mkdir(parents=True, exist_ok=True)
31 for entry in entries:
32 title = entry.splitlines()[0].strip()
33 song_id = re.search(r"\*\*Suno song ID:\*\* `([a-f0-9-]+)`", entry)[1]
34 genre = re.search(r"\*\*Genre:\*\* (.+)", entry)[1].strip()
35 name = unicodedata.normalize("NFC", title + ".m4a")
36 matches = [p for p in downloads.glob("*.m4a") if unicodedata.normalize("NFC", p.name) == name]
37 if len(matches) != 1:
38 raise ValueError(f"Expected exactly one original for {title}")
39 source = matches[0]
40 original = probe(source)
41 comment = original["format"].get("tags", {}).get("comment", "")
42 if f"id={song_id}" not in comment:
43 raise ValueError(f"Suno take ID does not match handoff: {title}")
44 temporary = audio_dir / (song_id + ".partial.m4a")
45 try:
46 subprocess.run([
47 "ffmpeg", "-nostdin", "-v", "error", "-y", "-i", str(source),
48 "-map", "0:a:0", "-map_metadata", "-1", "-c:a", "aac", "-b:a", "256k",
49 "-ar", "48000", "-ac", "2", "-movflags", "+faststart",
50 "-metadata", "title=" + title, "-metadata", "genre=" + genre, str(temporary)
51 ], check=True)
52 converted = probe(temporary)
53 if len(converted["streams"]) != 1 or converted["streams"][0]["codec_name"] != "aac":
54 raise ValueError(f"Expected one AAC audio stream: {title}")
55 duration = float(converted["format"]["duration"])
56 if abs(duration - float(original["format"]["duration"])) > 0.1:
57 raise ValueError(f"Converted duration differs from original: {title}")
58 data = temporary.read_bytes()
59 digest = hashlib.sha256(data).hexdigest()
60 filename = song_id + "-" + digest[:16] + ".m4a"
61 temporary.replace(audio_dir / filename)
62 tracks.append(dict(id=song_id, title=title, genre=genre, duration=duration,
63 audio="audio/" + filename, sha256=digest, byteCount=len(data)))
64 print(f"Prepared {title}: {duration:.2f}s, {len(data):,} bytes", flush=True)
65 finally:
66 temporary.unlink(missing_ok=True)
67 catalog = dict(version=1, title="PulseCanvas Radio", tracks=tracks)
68 catalog_path = output / "catalog.json"
69 pending = output / "catalog.partial.json"
70 pending.write_text(json.dumps(catalog, indent=2, ensure_ascii=False) + "\n")
71 pending.replace(catalog_path)
72 subprocess.run(["python3", str(Path(__file__).with_name("build-radio-stations.py")),
73 "--catalog", str(catalog_path), "--output", str(output)], check=True)
74 print(f"Ready: {len(tracks)} tracks, {sum(t['duration'] for t in tracks) / 60:.1f} minutes")
75 print(catalog_path.resolve())
76
77
78if __name__ == "__main__":
79 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
80 parser.add_argument("--handoff", required=True, type=Path)
81 parser.add_argument("--output", default=Path("build/radio"), type=Path)
82 parser.add_argument("--downloads", default=Path.home() / "Downloads", type=Path)
83 args = parser.parse_args()
84 prepare(args.handoff, args.output, args.downloads)