File size: 18,588 Bytes
b347b70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
#!/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()