File size: 3,656 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
#!/usr/bin/env python3
"""
Convert all WAV files to MP3 (192 kbps) and delete originals.

Usage:
    taskset -c 11-23 python scripts/convert_wav_to_mp3.py          # default: entire dataset
    taskset -c 11-23 python scripts/convert_wav_to_mp3.py --dry-run # preview only
    taskset -c 11-23 python scripts/convert_wav_to_mp3.py --dir fake/acestep
"""

import argparse
import subprocess
import sys
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

from tqdm import tqdm

BASE_DIR = Path("/ssd_data/dataset/ai_music_dataset")


def convert_one(wav_path: Path, keep_original: bool = False) -> tuple[Path, bool, str]:
    mp3_path = wav_path.with_suffix(".mp3")
    if mp3_path.exists() and mp3_path.stat().st_size > 1000:
        if not keep_original:
            wav_path.unlink(missing_ok=True)
        return wav_path, True, "mp3 already exists"

    cmd = [
        "ffmpeg",
        "-y",
        "-hide_banner",
        "-loglevel",
        "error",
        "-i",
        str(wav_path),
        "-ac",
        "2",
        "-ar",
        "44100",
        "-c:a",
        "libmp3lame",
        "-b:a",
        "192k",
        str(mp3_path),
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
        if result.returncode != 0:
            return wav_path, False, result.stderr.strip()[:200]
    except Exception as exc:
        return wav_path, False, str(exc)[:200]

    if not mp3_path.exists() or mp3_path.stat().st_size < 500:
        return wav_path, False, "output mp3 too small or missing"

    if not keep_original:
        wav_path.unlink(missing_ok=True)
    return wav_path, True, "ok"


def main():
    parser = argparse.ArgumentParser(
        description="Convert WAV → MP3 (192kbps) across dataset"
    )
    parser.add_argument(
        "--dir",
        type=str,
        default=None,
        help="Subdirectory relative to BASE_DIR (e.g. fake/acestep)",
    )
    parser.add_argument(
        "--dry-run", action="store_true", help="List files without converting"
    )
    parser.add_argument(
        "--keep-wav", action="store_true", help="Keep original WAV after conversion"
    )
    parser.add_argument(
        "--workers", type=int, default=6, help="Parallel ffmpeg workers"
    )
    args = parser.parse_args()

    search_root = BASE_DIR / args.dir if args.dir else BASE_DIR
    if not search_root.exists():
        print(f"Directory not found: {search_root}")
        sys.exit(1)

    wav_files = sorted(search_root.rglob("*.wav"))
    if not wav_files:
        print("No WAV files found.")
        return

    total_size = sum(f.stat().st_size for f in wav_files)
    print(f"Found {len(wav_files)} WAV files ({total_size / 1024**3:.1f} GB)")

    if args.dry_run:
        for f in wav_files[:20]:
            print(f"  {f.relative_to(BASE_DIR)}")
        if len(wav_files) > 20:
            print(f"  ... and {len(wav_files) - 20} more")
        return

    success = 0
    failed = 0
    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        futures = {pool.submit(convert_one, f, args.keep_wav): f for f in wav_files}
        with tqdm(total=len(wav_files), desc="WAV→MP3", unit="file") as pbar:
            for future in as_completed(futures):
                path, ok, msg = future.result()
                if ok:
                    success += 1
                else:
                    failed += 1
                    tqdm.write(f"FAIL: {path.relative_to(BASE_DIR)}{msg}")
                pbar.update(1)

    print(f"\nDone: {success} converted, {failed} failed")


if __name__ == "__main__":
    main()