#!/usr/bin/env python3 # pyright: reportMissingTypeStubs=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportUnusedCallResult=false, reportDeprecated=false, reportUnknownArgumentType=false import argparse import hashlib import json import logging import random import subprocess import sys import tempfile from datetime import datetime from pathlib import Path from collections.abc import Mapping from typing import cast import librosa import numpy as np import soundfile as sf from tqdm import tqdm SEED = 42 SR = 44100 MAX_DURATION = 120 MP3_BITRATE = "192k" BASE = Path("/ssd_data/nhn_backup/data/datasets/ai_detection_dataset") AI_SOURCE_DIRS = [ BASE / "fake" / "suno_v4", BASE / "fake" / "suno_v4_5", BASE / "fake" / "suno_v5", BASE / "fake" / "suno_v4_5_plus", BASE / "fake" / "suno_other", ] HUMAN_SOURCE_DIRS = { "sonics": BASE / "real" / "Sonics_real", "mtg": BASE / "real" / "MTG", } OUTPUTS = { "B2": {"sonics": "B2_suno_sonics", "mtg": "B2_suno_mtg"}, "B3": {"sonics": "B3_suno_sonics", "mtg": "B3_suno_mtg"}, "B4": {"sonics": "B4_suno_sonics", "mtg": "B4_suno_mtg"}, "B5": {"sonics": "B5_suno_sonics", "mtg": "B5_suno_mtg"}, "B7": {"sonics": "B7_suno_sonics", "mtg": "B7_suno_mtg"}, "B8": {"sonics": "B8_suno_sonics", "mtg": "B8_suno_mtg"}, "C1": {"sonics": "C1_suno_sonics", "mtg": "C1_suno_mtg"}, "C2": {"sonics": "C2_suno_sonics", "mtg": "C2_suno_mtg"}, } B2_FILTER = "acompressor=threshold=-20dB:ratio=4:attack=5:release=50,equalizer=f=100:t=h:w=200:g=3,equalizer=f=3000:t=h:w=2000:g=2,loudnorm=I=-14:LRA=11:TP=-1" B3_FILTER = "acompressor=threshold=-25dB:ratio=2:attack=10:release=100,equalizer=f=80:t=h:w=100:g=2,loudnorm=I=-16:LRA=9:TP=-2" B4_FILTER = "atempo=0.95,asetrate=44100*1.02,aresample=44100,aecho=0.8:0.88:60:0.4" B5_FILTERS = [ "atempo=1.05,asetrate=44100*0.98,aresample=44100", "atempo=0.92,highpass=f=80,lowpass=f=12000", "chorus=0.5:0.9:50:0.4:0.25:2", "flanger=delay=5:depth=2:speed=0.5", ] ALLOWED_EXTS = {".mp3", ".wav", ".flac", ".m4a", ".ogg"} def configure_logger(category: str, source_set: str) -> logging.Logger: logger_name = f"hybrid_{category}_{source_set}" logger = logging.getLogger(logger_name) logger.setLevel(logging.INFO) logger.propagate = False if logger.handlers: return logger formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setFormatter(formatter) log_path = BASE / f"{category}_{source_set}.log" file_handler = logging.FileHandler(log_path, encoding="utf-8") file_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.addHandler(file_handler) return logger def stable_seed(category: str, source_set: str) -> int: digest = hashlib.md5(f"{category}:{source_set}".encode("utf-8")).hexdigest() return SEED + int(digest[:8], 16) def discover_audio_files(directories: list[Path]) -> list[Path]: files: list[Path] = [] for directory in directories: if not directory.exists(): continue for path in directory.rglob("*"): if path.is_file() and path.suffix.lower() in ALLOWED_EXTS: files.append(path) return sorted(files) def run_command( cmd: list[str], logger: logging.Logger, timeout: int = 1800 ) -> tuple[bool, str]: try: completed = subprocess.run( cmd, check=False, capture_output=True, text=True, timeout=timeout, ) except Exception as exc: # noqa: BLE001 return False, str(exc) if completed.returncode != 0: message = ( completed.stderr.strip() or completed.stdout.strip() or "unknown command failure" ) logger.error("Command failed: %s", " ".join(cmd)) logger.error("Error: %s", message) return False, message return True, completed.stdout.strip() def encode_wav_to_mp3(wav_path: Path, output_mp3: Path, logger: logging.Logger) -> bool: cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(wav_path), "-t", str(MAX_DURATION), "-ar", str(SR), "-ac", "2", "-b:a", MP3_BITRATE, str(output_mp3), ] ok, _ = run_command(cmd, logger) return ok and output_mp3.exists() and output_mp3.stat().st_size > 0 def ffmpeg_transform( input_path: Path, output_path: Path, af_filter: str, logger: logging.Logger ) -> bool: cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(input_path), "-t", str(MAX_DURATION), "-af", af_filter, "-ar", str(SR), "-ac", "2", "-b:a", MP3_BITRATE, str(output_path), ] ok, _ = run_command(cmd, logger) return ok and output_path.exists() and output_path.stat().st_size > 0 def trim_for_demucs( input_path: Path, trimmed_wav: Path, logger: logging.Logger ) -> bool: cmd = [ "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", "-i", str(input_path), "-t", str(MAX_DURATION), "-ar", str(SR), "-ac", "2", "-vn", "-c:a", "pcm_s16le", str(trimmed_wav), ] ok, _ = run_command(cmd, logger, timeout=300) return ok and trimmed_wav.exists() and trimmed_wav.stat().st_size > 0 def separate_stems_cached( src_audio: Path, cache_root: Path, logger: logging.Logger, ) -> tuple[Path | None, Path | None]: cache_key = hashlib.sha1(str(src_audio).encode("utf-8")).hexdigest()[:16] sample_dir = cache_root / cache_key stem_root = sample_dir / "htdemucs" vocals = None no_vocals = None if stem_root.exists(): stem_subdirs = [p for p in stem_root.iterdir() if p.is_dir()] if stem_subdirs: candidate = stem_subdirs[0] vocals = candidate / "vocals.wav" no_vocals = candidate / "no_vocals.wav" if vocals.exists() and no_vocals.exists(): return vocals, no_vocals sample_dir.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="demucs_clip_") as tmp_dir: clipped = Path(tmp_dir) / "clip.wav" if not trim_for_demucs(src_audio, clipped, logger): return None, None cmd_base = [ sys.executable, "-m", "demucs", "--two-stems", "vocals", "-o", str(sample_dir), str(clipped), ] ok, _ = run_command(cmd_base + ["--device", "cuda"], logger, timeout=3600) if not ok: logger.info("Demucs cuda failed; retrying on cpu for %s", src_audio.name) ok, _ = run_command(cmd_base + ["--device", "cpu"], logger, timeout=3600) if not ok: return None, None if not stem_root.exists(): return None, None stem_subdirs = [p for p in stem_root.iterdir() if p.is_dir()] if not stem_subdirs: return None, None stem_dir = stem_subdirs[0] vocals = stem_dir / "vocals.wav" no_vocals = stem_dir / "no_vocals.wav" if not vocals.exists() or not no_vocals.exists(): return None, None return vocals, no_vocals def load_audio(path: Path) -> np.ndarray: audio, _ = librosa.load(str(path), sr=SR, mono=False, duration=MAX_DURATION) if audio.ndim == 1: audio = np.stack([audio, audio], axis=0) return audio def ensure_stereo(samples: np.ndarray) -> np.ndarray: if samples.ndim == 1: return np.stack([samples, samples], axis=1) if samples.shape[1] == 1: return np.repeat(samples, 2, axis=1) return samples def mix_stems( vocal_path: Path, instrumental_path: Path ) -> tuple[np.ndarray, int] | tuple[None, None]: vocal, sr_v = sf.read(str(vocal_path), always_2d=True) inst, sr_i = sf.read(str(instrumental_path), always_2d=True) if sr_v != sr_i: return None, None vocal = ensure_stereo(cast(np.ndarray, vocal)) inst = ensure_stereo(cast(np.ndarray, inst)) min_len = min(len(vocal), len(inst), int(SR * MAX_DURATION)) if min_len <= 0: return None, None mixed = vocal[:min_len] * 1.0 + inst[:min_len] * 0.8 peak = np.max(np.abs(mixed)) if peak > 0.95: mixed = mixed * (0.95 / peak) return mixed, sr_v def concat_mix( human_audio: np.ndarray, ai_audio: np.ndarray, rng: random.Random ) -> tuple[np.ndarray, dict[str, str | float]]: split_ratio = rng.uniform(0.3, 0.7) h_len = int(human_audio.shape[1] * split_ratio) a_len = int(ai_audio.shape[1] * (1 - split_ratio)) ai_first = rng.random() > 0.5 if not ai_first: mixed = np.concatenate([human_audio[:, :h_len], ai_audio[:, :a_len]], axis=1) human_start = 0.0 human_end = h_len / SR ai_start = h_len / SR ai_end = (h_len + a_len) / SR else: mixed = np.concatenate([ai_audio[:, :a_len], human_audio[:, :h_len]], axis=1) ai_start = 0.0 ai_end = a_len / SR human_start = a_len / SR human_end = (a_len + h_len) / SR mixed = mixed[:, : int(SR * MAX_DURATION)] mixed_duration = mixed.shape[1] / SR info: dict[str, str | float] = { "order": "ai_first" if ai_first else "human_first", "human_start_sec": round(min(human_start, mixed_duration), 3), "human_end_sec": round(min(human_end, mixed_duration), 3), "ai_start_sec": round(min(ai_start, mixed_duration), 3), "ai_end_sec": round(min(ai_end, mixed_duration), 3), } return mixed, info def crossfade_mix( human_audio: np.ndarray, ai_audio: np.ndarray, rng: random.Random ) -> tuple[np.ndarray, dict[str, str | float]]: fade_samples = int(3.0 * SR) h_len = human_audio.shape[1] a_len = ai_audio.shape[1] if h_len < fade_samples or a_len < fade_samples: fade_samples = max(1, min(h_len, a_len) // 2) split_point = rng.randint(int(h_len * 0.3), max(int(h_len * 0.7), 1)) split_point = min(max(split_point, fade_samples), h_len) part1 = human_audio[:, :split_point] part2 = ai_audio fade_out = np.linspace(1.0, 0.0, fade_samples) fade_in = np.linspace(0.0, 1.0, fade_samples) overlap = part1[:, -fade_samples:] * fade_out + part2[:, :fade_samples] * fade_in mixed = np.concatenate( [ part1[:, :-fade_samples], overlap, part2[:, fade_samples:], ], axis=1, ) mixed = mixed[:, : int(SR * MAX_DURATION)] peak = np.max(np.abs(mixed)) if mixed.size else 0.0 if peak > 0.95: mixed = mixed * (0.95 / peak) mixed_duration = mixed.shape[1] / SR crossfade_start = (split_point - fade_samples) / SR crossfade_end = split_point / SR info: dict[str, str | float] = { "order": "human_first", "human_only_start_sec": 0.0, "human_only_end_sec": round(min(crossfade_start, mixed_duration), 3), "crossfade_start_sec": round(min(crossfade_start, mixed_duration), 3), "crossfade_end_sec": round(min(crossfade_end, mixed_duration), 3), "crossfade_duration_sec": round(fade_samples / SR, 3), "ai_only_start_sec": round(min(crossfade_end, mixed_duration), 3), "ai_only_end_sec": round(mixed_duration, 3), } return mixed, info def write_metadata( output_mp3: Path, record: Mapping[str, str | float], metadata_jsonl: Path ) -> None: sidecar = output_mp3.with_suffix(".json") sidecar.write_text( json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8" ) with metadata_jsonl.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record, ensure_ascii=False) + "\n") def generate_track( category: str, ai_file: Path, human_file: Path, output_mp3: Path, rng: random.Random, demucs_cache: Path, logger: logging.Logger, ) -> tuple[bool, dict[str, str | float] | None]: try: if category == "B2": return ffmpeg_transform(human_file, output_mp3, B2_FILTER, logger), None if category == "B3": return ffmpeg_transform(ai_file, output_mp3, B3_FILTER, logger), None if category == "B4": return ffmpeg_transform(ai_file, output_mp3, B4_FILTER, logger), None if category == "B5": af_filter = rng.choice(B5_FILTERS) return ffmpeg_transform(ai_file, output_mp3, af_filter, logger), None if category in {"B7", "B8"}: logger.warning("B7/B8 use YouTube crawling, not generate_track()") return False, None if category in {"C1", "C2"}: human_audio = load_audio(human_file) ai_audio = load_audio(ai_file) if category == "C1": mixed, mix_info = concat_mix(human_audio, ai_audio, rng) else: mixed, mix_info = crossfade_mix(human_audio, ai_audio, rng) if mixed.size == 0: return False, None with tempfile.TemporaryDirectory(prefix="mix_c1c2_") as tmp_dir: temp_wav = Path(tmp_dir) / "mixed.wav" sf.write(str(temp_wav), mixed.T, SR) ok = encode_wav_to_mp3(temp_wav, output_mp3, logger) return ok, mix_info if ok else None raise ValueError(f"Unsupported category: {category}") except Exception as exc: # noqa: BLE001 logger.exception( "Track generation failed for %s (%s): %s", output_mp3.name, category, exc ) return False, None def process_category_source(category: str, source_set: str, target: int) -> None: logger = configure_logger(category, source_set) rng = random.Random(stable_seed(category, source_set)) ai_files = discover_audio_files(AI_SOURCE_DIRS) human_files = discover_audio_files([HUMAN_SOURCE_DIRS[source_set]]) rng.shuffle(ai_files) rng.shuffle(human_files) if not ai_files or not human_files: logger.error( "No source files found for category=%s source_set=%s", category, source_set ) return output_dir = BASE / "fake" / OUTPUTS[category][source_set] output_dir.mkdir(parents=True, exist_ok=True) metadata_jsonl = output_dir / "metadata.jsonl" demucs_cache = BASE / "demucs_separated_hybrid" / source_set demucs_cache.mkdir(parents=True, exist_ok=True) existing = [p for p in output_dir.glob("*.mp3") if p.stat().st_size > 0] if len(existing) >= target: logger.info( "%s/%s already has %d files (target=%d), skipping", category, source_set, len(existing), target, ) return logger.info( "Start %s/%s | ai=%d human=%d existing=%d target=%d", category, source_set, len(ai_files), len(human_files), len(existing), target, ) required = target - len(existing) created = 0 attempts = 0 file_index = 0 max_attempts = max(required * 20, required + 100) progress = tqdm(total=required, desc=f"{category}_{source_set}", unit="track") while created < required and attempts < max_attempts: output_name = f"{category.lower()}_{source_set}_{file_index:05d}.mp3" output_mp3 = output_dir / output_name file_index += 1 if output_mp3.exists() and output_mp3.stat().st_size > 0: continue idx = attempts % min(len(ai_files), len(human_files)) ai_file = ai_files[idx % len(ai_files)] human_file = human_files[idx % len(human_files)] attempts += 1 ok, mix_info = generate_track( category=category, ai_file=ai_file, human_file=human_file, output_mp3=output_mp3, rng=rng, demucs_cache=demucs_cache, logger=logger, ) if not ok: if output_mp3.exists() and output_mp3.stat().st_size == 0: output_mp3.unlink(missing_ok=True) continue if not output_mp3.exists() or output_mp3.stat().st_size == 0: logger.error("Generated output is missing or empty: %s", output_mp3) if output_mp3.exists(): output_mp3.unlink(missing_ok=True) continue record: dict[str, str | float] = { "source_ai": ai_file.name, "source_human": human_file.name, "processing_method": category, "source_set": source_set, "timestamp": datetime.now().isoformat(), "output_filename": output_mp3.name, } if mix_info: record.update(mix_info) write_metadata(output_mp3, record, metadata_jsonl) created += 1 progress.update(1) progress.close() logger.info( "Finished %s/%s | created=%d required=%d attempts=%d", category, source_set, created, required, attempts, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Generate B-hybrid and C-mixing datasets." ) parser.add_argument( "--category", type=str, default="all", choices=["B2", "B3", "B4", "B5", "B7", "B8", "C1", "C2", "all"], help="Category to generate", ) parser.add_argument( "--source-set", type=str, default="all", choices=["sonics", "mtg", "all"], help="Human source set", ) parser.add_argument( "--target", type=int, default=2000, help="Target number of tracks per output folder", ) return parser.parse_args() def main() -> None: random.seed(SEED) args = parse_args() categories = ( [args.category] if args.category != "all" else ["B2", "B3", "B4", "B5", "B7", "B8", "C1", "C2"] ) source_sets = [args.source_set] if args.source_set != "all" else ["sonics", "mtg"] for category in categories: for source_set in source_sets: process_category_source(category, source_set, args.target) if __name__ == "__main__": main()