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61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/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()