HAIM / scripts /generation /utils.py
seonghyeongo's picture
scripts: add generation pipeline (A2/B/C) with secrets removed
b347b70 verified
Raw
History Blame Contribute Delete
15.6 kB
#!/usr/bin/env python3
"""
Common utilities for AI Music Dataset collection pipeline.
- Metadata management (JSON per-track + summary CSV)
- Disk space monitoring
- Download helpers with retry/rate-limit
- Audio validation
"""
import json
import csv
import os
import shutil
import time
import hashlib
import logging
import subprocess
from pathlib import Path
from datetime import datetime, timezone
from dataclasses import dataclass, field, asdict
from typing import Optional, List, Dict, Any
from functools import wraps
import requests
from tqdm import tqdm
# ─── Configuration ───────────────────────────────────────────
BASE_DIR = Path("/ssd_data/dataset/ai_music_dataset")
FAKE_DIR = BASE_DIR / "fake"
METADATA_DIR = BASE_DIR / "metadata"
SCRIPTS_DIR = BASE_DIR / "scripts"
TARGET_PER_FOLDER = 2000
MIN_FREE_SPACE_GB = 50 # Stop collection if disk < 50GB free
MAX_RETRIES = 3
RETRY_DELAY = 2 # seconds
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.StreamHandler(),
logging.FileHandler(BASE_DIR / "collection.log", mode="a"),
],
)
logger = logging.getLogger("ai_music_dataset")
# ─── Metadata Schema ────────────────────────────────────────
@dataclass
class TrackMetadata:
"""Per-track metadata schema."""
# Core identification
track_id: str # Unique ID (UUID or platform ID)
filename: str # Local filename
category: str # A_commercial, A_opensource, B_hybrid, C_mixing
subcategory: str # e.g., suno_v4, musicgen_large, B1_ai_cover_of_human
# Source information
source_platform: str # suno, udio, mureka, musicgen, acestep, etc.
source_type: str # "commercial" or "open-source"
model_name: str # Full model name
model_version: str # v3, v3.5, v4, Small, Large, etc.
# Audio properties
duration_sec: Optional[float] = None
sample_rate: Optional[int] = None
channels: Optional[int] = None
bitrate_kbps: Optional[int] = None
file_size_bytes: Optional[int] = None
audio_format: str = "mp3"
# Content metadata
title: Optional[str] = None
prompt: Optional[str] = None # Generation prompt (if available)
genre: Optional[str] = None
tags: List[str] = field(default_factory=list)
lyrics: Optional[str] = None
# Source URLs
source_url: Optional[str] = None
download_url: Optional[str] = None
page_url: Optional[str] = None
# For hybrid (B-category) tracks
original_source: Optional[str] = None # Original human/AI track used
processing_method: Optional[str] = None # How it was processed
ai_component: Optional[str] = None # Which part is AI
human_component: Optional[str] = None # Which part is human
# Collection metadata
collected_at: str = ""
collection_method: str = "" # "crawl", "api", "generate", "process"
md5_hash: Optional[str] = None
# Quality flags
is_valid: bool = True
validation_notes: Optional[str] = None
def __post_init__(self):
if not self.collected_at:
self.collected_at = datetime.now(timezone.utc).isoformat()
class MetadataManager:
"""Manages per-folder metadata as JSONL + summary CSV."""
def __init__(self, folder_path: Path):
self.folder_path = Path(folder_path)
self.jsonl_path = self.folder_path / "metadata.jsonl"
self.summary_path = self.folder_path / "summary.json"
self._existing_ids = set()
self._load_existing()
def _load_existing(self):
"""Load existing track IDs to avoid duplicates."""
if self.jsonl_path.exists():
with open(self.jsonl_path, "r", encoding="utf-8") as f:
for line in f:
try:
data = json.loads(line.strip())
self._existing_ids.add(data.get("track_id", ""))
except json.JSONDecodeError:
continue
def has_track(self, track_id: str) -> bool:
return track_id in self._existing_ids
def add_track(self, meta: TrackMetadata):
"""Append track metadata to JSONL file."""
if meta.track_id in self._existing_ids:
return # Skip duplicate
with open(self.jsonl_path, "a", encoding="utf-8") as f:
f.write(json.dumps(asdict(meta), ensure_ascii=False) + "\n")
self._existing_ids.add(meta.track_id)
def get_count(self) -> int:
return len(self._existing_ids)
def update_summary(self):
"""Write summary.json with aggregate stats."""
tracks = []
total_size = 0
total_duration = 0.0
if self.jsonl_path.exists():
with open(self.jsonl_path, "r", encoding="utf-8") as f:
for line in f:
try:
data = json.loads(line.strip())
tracks.append(data)
total_size += data.get("file_size_bytes", 0) or 0
total_duration += data.get("duration_sec", 0) or 0
except json.JSONDecodeError:
continue
summary = {
"folder": str(self.folder_path),
"total_tracks": len(tracks),
"target_tracks": TARGET_PER_FOLDER,
"total_size_mb": round(total_size / (1024 * 1024), 2),
"total_duration_hours": round(total_duration / 3600, 2),
"avg_duration_sec": round(total_duration / max(len(tracks), 1), 1),
"collection_progress": f"{len(tracks)}/{TARGET_PER_FOLDER}",
"last_updated": datetime.now(timezone.utc).isoformat(),
"versions": {},
}
# Count by version
for t in tracks:
ver = t.get("model_version", "unknown")
summary["versions"][ver] = summary["versions"].get(ver, 0) + 1
with open(self.summary_path, "w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
return summary
# ─── Disk Space Monitor ─────────────────────────────────────
def check_disk_space(path: str = "/ssd_data") -> Dict[str, float]:
"""Check available disk space in GB."""
usage = shutil.disk_usage(path)
return {
"total_gb": round(usage.total / (1024**3), 1),
"used_gb": round(usage.used / (1024**3), 1),
"free_gb": round(usage.free / (1024**3), 1),
"usage_percent": round(usage.used / usage.total * 100, 1),
}
def ensure_disk_space(min_free_gb: float = MIN_FREE_SPACE_GB) -> bool:
"""Return True if enough disk space, False otherwise."""
space = check_disk_space()
if space["free_gb"] < min_free_gb:
logger.warning(
f"Low disk space! {space['free_gb']:.1f}GB free "
f"(minimum: {min_free_gb}GB). Stopping collection."
)
return False
return True
# ─── Download Helpers ────────────────────────────────────────
def download_file(
url: str,
output_path: Path,
headers: Optional[Dict] = None,
timeout: int = 60,
max_retries: int = MAX_RETRIES,
) -> bool:
"""Download a file with retry logic."""
output_path = Path(output_path)
if output_path.exists() and output_path.stat().st_size > 0:
return True # Already downloaded
for attempt in range(max_retries):
try:
resp = requests.get(url, headers=headers, timeout=timeout, stream=True)
resp.raise_for_status()
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
# Verify non-empty
if output_path.stat().st_size > 1000: # At least 1KB
return True
else:
output_path.unlink(missing_ok=True)
logger.warning(f"Downloaded file too small: {output_path}")
except requests.RequestException as e:
logger.warning(f"Download attempt {attempt + 1}/{max_retries} failed: {e}")
if attempt < max_retries - 1:
time.sleep(RETRY_DELAY * (attempt + 1))
return False
def compute_md5(filepath: Path) -> str:
"""Compute MD5 hash of a file."""
md5 = hashlib.md5()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
md5.update(chunk)
return md5.hexdigest()
# ─── Audio Validation ───────────────────────────────────────
def get_audio_info(filepath: Path) -> Dict[str, Any]:
"""Get audio metadata using ffprobe."""
try:
cmd = [
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
str(filepath),
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
return {}
info = json.loads(result.stdout)
fmt = info.get("format", {})
streams = info.get("streams", [{}])
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), {})
return {
"duration_sec": float(fmt.get("duration", 0)),
"sample_rate": int(audio_stream.get("sample_rate", 0)),
"channels": int(audio_stream.get("channels", 0)),
"bitrate_kbps": int(fmt.get("bit_rate", 0)) // 1000,
"file_size_bytes": int(fmt.get("size", 0)),
"audio_format": fmt.get("format_name", "unknown"),
}
except Exception as e:
logger.error(f"ffprobe failed for {filepath}: {e}")
return {}
def validate_audio(filepath: Path, min_duration: float = 5.0) -> bool:
"""Validate that an audio file is playable and meets minimum duration."""
info = get_audio_info(filepath)
if not info:
return False
duration = info.get("duration_sec", 0)
return duration >= min_duration
# ─── Rate Limiter ────────────────────────────────────────────
class RateLimiter:
"""Simple rate limiter for API/crawl requests."""
def __init__(self, requests_per_second: float = 2.0):
self.min_interval = 1.0 / requests_per_second
self.last_request = 0.0
def wait(self):
elapsed = time.time() - self.last_request
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
self.last_request = time.time()
# ─── Progress Reporter ──────────────────────────────────────
def print_collection_status():
"""Print overall collection status across all folders."""
print("\n" + "=" * 80)
print("AI Music Dataset Collection Status")
print("=" * 80)
space = check_disk_space()
print(
f"Disk: {space['used_gb']:.1f}GB used / {space['total_gb']:.1f}GB total "
f"({space['free_gb']:.1f}GB free, {space['usage_percent']:.1f}%)"
)
print()
categories = ["A_commercial", "A_opensource", "B_hybrid", "C_mixing"]
total_tracks = 0
total_size = 0
for cat in categories:
cat_dir = FAKE_DIR / cat
if not cat_dir.exists():
continue
print(f" [{cat}]")
for sub in sorted(cat_dir.iterdir()):
if sub.is_dir():
meta_mgr = MetadataManager(sub)
count = meta_mgr.get_count()
# Also count actual audio files as fallback
audio_files = (
list(sub.glob("*.mp3"))
+ list(sub.glob("*.wav"))
+ list(sub.glob("*.flac"))
)
file_count = len(audio_files)
actual_count = max(count, file_count)
total_tracks += actual_count
folder_size = sum(
f.stat().st_size for f in sub.rglob("*") if f.is_file()
)
total_size += folder_size
bar = "█" * (actual_count * 30 // TARGET_PER_FOLDER) + "░" * (
30 - actual_count * 30 // TARGET_PER_FOLDER
)
print(
f" {sub.name:<25} [{bar}] {actual_count:>5}/{TARGET_PER_FOLDER} "
f"({folder_size / 1024 / 1024:.0f}MB)"
)
print()
print(f" Total: {total_tracks} tracks, {total_size / 1024 / 1024 / 1024:.2f}GB")
print("=" * 80)
# ─── Prompt Generators ──────────────────────────────────────
MUSIC_PROMPTS = [
# Genre variety for open-source generation
"upbeat pop song with catchy melody and electronic beats",
"ambient electronic music with atmospheric pads and gentle rhythms",
"acoustic folk song with fingerpicked guitar and warm vocals",
"hip hop beat with heavy bass and trap hi-hats",
"classical piano sonata in the style of Chopin",
"jazz fusion with complex chord progressions and saxophone",
"heavy metal with distorted guitars and double bass drums",
"lo-fi hip hop chill beats for studying",
"reggae song with offbeat guitar and bass groove",
"country music with acoustic guitar and slide steel",
"EDM festival anthem with big drops and synth leads",
"R&B smooth vocals over neo-soul chords",
"indie rock with jangly guitars and reverb",
"orchestral film score with dramatic strings and brass",
"bossa nova with nylon guitar and soft percussion",
"synthwave retro 80s electronic music",
"punk rock fast tempo with power chords",
"blues guitar solo with emotional bends",
"K-pop song with catchy chorus and dance beat",
"Latin reggaeton with dembow rhythm",
"psychedelic rock with wah guitar and space effects",
"minimal techno with hypnotic loops",
"gospel choir with powerful harmonies",
"Celtic folk music with fiddle and tin whistle",
"Afrobeat with polyrhythmic percussion and horn section",
"drum and bass with fast breakbeats",
"soul music with Motown-style arrangement",
"grunge alternative rock with distortion",
"world music fusion with tabla and sitar",
"chiptune 8-bit video game music",
"tropical house with marimba and steel drums",
"progressive rock epic with time signature changes",
"acoustic singer-songwriter ballad",
"dubstep with heavy wobble bass",
"flamenco guitar with passionate rhythm",
"new age meditation music with nature sounds",
"big band swing jazz",
"post-rock with atmospheric guitar layers",
"dancehall with Caribbean rhythm",
"shoegaze with wall of sound guitars",
]
def get_diverse_prompts(n: int) -> List[str]:
"""Get n diverse music prompts, cycling through the list."""
prompts = []
for i in range(n):
prompts.append(MUSIC_PROMPTS[i % len(MUSIC_PROMPTS)])
return prompts
if __name__ == "__main__":
print_collection_status()