HAIM / scripts /generation /convert_wav_to_mp3.py
seonghyeongo's picture
scripts: add generation pipeline (A2/B/C) with secrets removed
b347b70 verified
Raw
History Blame Contribute Delete
3.66 kB
#!/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()