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: reportDeprecated=false, reportUnknownParameterType=false, reportMissingTypeArgument=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnusedCallResult=false, reportUnusedImport=false | |
| import argparse | |
| import json | |
| import random | |
| import subprocess | |
| import time | |
| from pathlib import Path | |
| from typing import List, Optional, Sequence, Tuple | |
| from utils import * | |
| AUDIO_EXTS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac"} | |
| DEFAULT_HUMAN_SOURCES = [ | |
| Path("/ssd_data/dataset/ai_music_dataset/real/MTG"), | |
| ] | |
| DEFAULT_AI_SOURCES = [FAKE_DIR / "acestep"] | |
| C_CATEGORY_CONFIG = { | |
| "C1": { | |
| "folder": "C1_mixset_concat", | |
| "processing_method": "concatenation", | |
| "ai_component": "partial_segment", | |
| "human_component": "partial_segment", | |
| }, | |
| "C2": { | |
| "folder": "C2_mixset_crossfade", | |
| "processing_method": "crossfade", | |
| "ai_component": "partial_segment", | |
| "human_component": "partial_segment", | |
| }, | |
| } | |
| def run_cmd(cmd: Sequence[str], timeout: int = 300) -> bool: | |
| try: | |
| result = subprocess.run( | |
| list(cmd), capture_output=True, text=True, timeout=timeout | |
| ) | |
| if result.returncode != 0: | |
| stderr = (result.stderr or "").strip() | |
| if stderr: | |
| logger.warning(stderr[-500:]) | |
| return False | |
| return True | |
| except Exception as exc: | |
| logger.warning(f"Command failed: {exc}") | |
| return False | |
| def collect_audio_files(paths: Sequence[Path]) -> List[Path]: | |
| files: List[Path] = [] | |
| for base in paths: | |
| if not base.exists(): | |
| continue | |
| for p in base.rglob("*"): | |
| if p.is_file() and p.suffix.lower() in AUDIO_EXTS: | |
| files.append(p) | |
| return files | |
| def resolve_output_dir(category: str, output_dir: Optional[str]) -> Path: | |
| if output_dir: | |
| return Path(output_dir) | |
| return FAKE_DIR / "C_mixing" / C_CATEGORY_CONFIG[category]["folder"] | |
| def ffmpeg_mix( | |
| human_path: Path, | |
| ai_path: Path, | |
| output_path: Path, | |
| filter_complex: str, | |
| timeout: int = 600, | |
| ) -> bool: | |
| cmd = [ | |
| "ffmpeg", | |
| "-y", | |
| "-hide_banner", | |
| "-loglevel", | |
| "error", | |
| "-i", | |
| str(human_path), | |
| "-i", | |
| str(ai_path), | |
| "-filter_complex", | |
| filter_complex, | |
| "-map", | |
| "[out]", | |
| "-ac", | |
| "2", | |
| "-ar", | |
| "44100", | |
| "-c:a", | |
| "libmp3lame", | |
| "-b:a", | |
| "192k", | |
| str(output_path), | |
| ] | |
| return run_cmd(cmd, timeout=timeout) | |
| def choose_segment( | |
| info: dict, min_len: float = 15.0, max_len: float = 60.0 | |
| ) -> Optional[Tuple[float, float]]: | |
| duration = float(info.get("duration_sec") or 0) | |
| if duration < min_len + 1: | |
| return None | |
| seg_len = random.uniform(min_len, min(max_len, duration - 0.2)) | |
| start_max = max(0.0, duration - seg_len) | |
| start = random.uniform(0.0, start_max) | |
| return start, seg_len | |
| def build_metadata( | |
| category: str, | |
| track_id: str, | |
| filename: str, | |
| output_path: Path, | |
| human_src: Path, | |
| ai_src: Path, | |
| prompt: Optional[str] = None, | |
| ) -> TrackMetadata: | |
| info = get_audio_info(output_path) | |
| cfg = C_CATEGORY_CONFIG[category] | |
| return TrackMetadata( | |
| track_id=track_id, | |
| filename=filename, | |
| category="C_mixing", | |
| subcategory=cfg["folder"], | |
| source_platform="hybrid_pipeline", | |
| source_type="hybrid", | |
| model_name="temporal_mixing", | |
| model_version="ffmpeg_v1", | |
| duration_sec=info.get("duration_sec"), | |
| sample_rate=info.get("sample_rate"), | |
| channels=info.get("channels"), | |
| bitrate_kbps=info.get("bitrate_kbps"), | |
| file_size_bytes=info.get("file_size_bytes") or output_path.stat().st_size, | |
| audio_format="mp3", | |
| prompt=prompt, | |
| original_source=f"human={human_src}|ai={ai_src}", | |
| processing_method=cfg["processing_method"], | |
| ai_component=cfg["ai_component"], | |
| human_component=cfg["human_component"], | |
| collection_method="process", | |
| md5_hash=compute_md5(output_path), | |
| ) | |
| def add_metadata_if_new(manager: MetadataManager, meta: TrackMetadata) -> bool: | |
| if manager.has_track(meta.track_id): | |
| return False | |
| manager.add_track(meta) | |
| return True | |
| def process_c1( | |
| manager: MetadataManager, | |
| output_dir: Path, | |
| target: int, | |
| human_files: Sequence[Path], | |
| ai_files: Sequence[Path], | |
| ) -> int: | |
| if not human_files or not ai_files: | |
| logger.warning("C1 needs both human and AI source files.") | |
| return 0 | |
| added = 0 | |
| attempts = 0 | |
| while manager.get_count() < target and attempts < target * 8: | |
| attempts += 1 | |
| if not ensure_disk_space(): | |
| break | |
| human = random.choice(human_files) | |
| ai = random.choice(ai_files) | |
| human_seg = choose_segment(get_audio_info(human)) | |
| ai_seg = choose_segment(get_audio_info(ai)) | |
| if not human_seg or not ai_seg: | |
| continue | |
| h_start, h_len = human_seg | |
| a_start, a_len = ai_seg | |
| gap = random.uniform(0.1, 0.5) | |
| ai_first = random.choice([True, False]) | |
| track_id = f"C1_{compute_md5(human)[:8]}_{compute_md5(ai)[:8]}_{attempts}" | |
| if manager.has_track(track_id): | |
| continue | |
| if ai_first: | |
| filt = ( | |
| f"[1:a]atrim=start={a_start:.3f}:end={a_start + a_len:.3f},asetpts=PTS-STARTPTS[a];" | |
| f"[0:a]atrim=start={h_start:.3f}:end={h_start + h_len:.3f},asetpts=PTS-STARTPTS[h];" | |
| f"aevalsrc=0:d={gap:.3f}[g];" | |
| f"[a][g][h]concat=n=3:v=0:a=1[out]" | |
| ) | |
| else: | |
| filt = ( | |
| f"[0:a]atrim=start={h_start:.3f}:end={h_start + h_len:.3f},asetpts=PTS-STARTPTS[h];" | |
| f"[1:a]atrim=start={a_start:.3f}:end={a_start + a_len:.3f},asetpts=PTS-STARTPTS[a];" | |
| f"aevalsrc=0:d={gap:.3f}[g];" | |
| f"[h][g][a]concat=n=3:v=0:a=1[out]" | |
| ) | |
| out_name = f"{track_id}.mp3" | |
| out_path = output_dir / out_name | |
| if not ffmpeg_mix(human, ai, out_path, filt): | |
| continue | |
| if ai_first: | |
| first_label, first_dur = "ai", a_len | |
| second_label, second_dur = "human", h_len | |
| else: | |
| first_label, first_dur = "human", h_len | |
| second_label, second_dur = "ai", a_len | |
| prompt = json.dumps( | |
| { | |
| "order": "ai_first" if ai_first else "human_first", | |
| "human_source": str(human), | |
| "ai_source": str(ai), | |
| f"{first_label}_start_sec": 0.0, | |
| f"{first_label}_end_sec": round(first_dur, 3), | |
| "gap_sec": round(gap, 3), | |
| f"{second_label}_start_sec": round(first_dur + gap, 3), | |
| f"{second_label}_end_sec": round(first_dur + gap + second_dur, 3), | |
| } | |
| ) | |
| meta = build_metadata( | |
| "C1", track_id, out_name, out_path, human, ai, prompt=prompt | |
| ) | |
| if add_metadata_if_new(manager, meta): | |
| added += 1 | |
| manager.update_summary() | |
| return added | |
| def process_c2( | |
| manager: MetadataManager, | |
| output_dir: Path, | |
| target: int, | |
| human_files: Sequence[Path], | |
| ai_files: Sequence[Path], | |
| ) -> int: | |
| if not human_files or not ai_files: | |
| logger.warning("C2 needs both human and AI source files.") | |
| return 0 | |
| added = 0 | |
| attempts = 0 | |
| while manager.get_count() < target and attempts < target * 8: | |
| attempts += 1 | |
| if not ensure_disk_space(): | |
| break | |
| human = random.choice(human_files) | |
| ai = random.choice(ai_files) | |
| human_info = get_audio_info(human) | |
| ai_info = get_audio_info(ai) | |
| human_seg = choose_segment(human_info, min_len=20.0, max_len=70.0) | |
| ai_seg = choose_segment(ai_info, min_len=20.0, max_len=70.0) | |
| if not human_seg or not ai_seg: | |
| continue | |
| h_start, h_len = human_seg | |
| a_start, a_len = ai_seg | |
| crossfade = random.uniform(1.0, 5.0) | |
| if h_len <= crossfade + 0.5 or a_len <= crossfade + 0.5: | |
| continue | |
| ai_first = random.choice([True, False]) | |
| track_id = f"C2_{compute_md5(human)[:8]}_{compute_md5(ai)[:8]}_{attempts}" | |
| if manager.has_track(track_id): | |
| continue | |
| if ai_first: | |
| filt = ( | |
| f"[1:a]atrim=start={a_start:.3f}:end={a_start + a_len:.3f},asetpts=PTS-STARTPTS[a];" | |
| f"[0:a]atrim=start={h_start:.3f}:end={h_start + h_len:.3f},asetpts=PTS-STARTPTS[h];" | |
| f"[a][h]acrossfade=d={crossfade:.3f}:c1=tri:c2=tri[out]" | |
| ) | |
| else: | |
| filt = ( | |
| f"[0:a]atrim=start={h_start:.3f}:end={h_start + h_len:.3f},asetpts=PTS-STARTPTS[h];" | |
| f"[1:a]atrim=start={a_start:.3f}:end={a_start + a_len:.3f},asetpts=PTS-STARTPTS[a];" | |
| f"[h][a]acrossfade=d={crossfade:.3f}:c1=tri:c2=tri[out]" | |
| ) | |
| out_name = f"{track_id}.mp3" | |
| out_path = output_dir / out_name | |
| if not ffmpeg_mix(human, ai, out_path, filt): | |
| continue | |
| if ai_first: | |
| first_label, first_dur = "ai", a_len | |
| second_label, second_dur = "human", h_len | |
| else: | |
| first_label, first_dur = "human", h_len | |
| second_label, second_dur = "ai", a_len | |
| prompt = json.dumps( | |
| { | |
| "order": "ai_first" if ai_first else "human_first", | |
| "human_source": str(human), | |
| "ai_source": str(ai), | |
| f"{first_label}_only_start_sec": 0.0, | |
| f"{first_label}_only_end_sec": round(first_dur - crossfade, 3), | |
| "crossfade_start_sec": round(first_dur - crossfade, 3), | |
| "crossfade_end_sec": round(first_dur, 3), | |
| "crossfade_duration_sec": round(crossfade, 3), | |
| f"{second_label}_only_start_sec": round(first_dur, 3), | |
| f"{second_label}_only_end_sec": round( | |
| first_dur + second_dur - crossfade, 3 | |
| ), | |
| } | |
| ) | |
| meta = build_metadata( | |
| "C2", track_id, out_name, out_path, human, ai, prompt=prompt | |
| ) | |
| if add_metadata_if_new(manager, meta): | |
| added += 1 | |
| manager.update_summary() | |
| return added | |
| def process_category(category: str, args: argparse.Namespace) -> int: | |
| output_dir = resolve_output_dir(category, args.output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| manager = MetadataManager(output_dir) | |
| if manager.get_count() >= args.target: | |
| logger.info( | |
| f"{category} already at target: {manager.get_count()}/{args.target}" | |
| ) | |
| manager.update_summary() | |
| return 0 | |
| human_sources = ( | |
| [Path(args.human_source_dir)] | |
| if args.human_source_dir | |
| else DEFAULT_HUMAN_SOURCES | |
| ) | |
| ai_sources = ( | |
| [Path(args.ai_source_dir)] if args.ai_source_dir else DEFAULT_AI_SOURCES | |
| ) | |
| human_files = collect_audio_files(human_sources) | |
| ai_files = collect_audio_files(ai_sources) | |
| if len(human_files) < args.target: | |
| logger.warning(f"Human source shortage: found {len(human_files)} files.") | |
| if len(ai_files) < args.target: | |
| logger.warning(f"AI source shortage: found {len(ai_files)} files.") | |
| if category == "C1": | |
| return process_c1(manager, output_dir, args.target, human_files, ai_files) | |
| if category == "C2": | |
| return process_c2(manager, output_dir, args.target, human_files, ai_files) | |
| return 0 | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument( | |
| "--category", type=str, default="all", choices=["C1", "C2", "all"] | |
| ) | |
| parser.add_argument("--target", type=int, default=2000) | |
| parser.add_argument("--human-source-dir", type=str, default=None) | |
| parser.add_argument("--ai-source-dir", type=str, default=None) | |
| parser.add_argument("--output-dir", type=str, default=None) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| categories = [args.category] if args.category != "all" else ["C1", "C2"] | |
| total_added = 0 | |
| for category in categories: | |
| start = time.time() | |
| added = process_category(category, args) | |
| elapsed = time.time() - start | |
| total_added += added | |
| logger.info(f"{category} done: +{added} tracks ({elapsed:.1f}s)") | |
| logger.info(f"Mixing collection complete. Added {total_added} track(s).") | |
| if __name__ == "__main__": | |
| main() | |