File size: 5,523 Bytes
8337fa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import os
from pathlib import Path
import tempfile
import traceback

import numpy as np
import torch
from tqdm import tqdm


def parse_args():
    parser = argparse.ArgumentParser(
        description="Batch encode MP3 files to MuCodec codes (recursive)."
    )
    parser.add_argument("input_dir", type=Path, help="Input folder (recursive scan)")
    parser.add_argument("output_dir", type=Path, help="Output folder for saved codes")
    parser.add_argument(
        "--ckpt",
        type=Path,
        default=Path(__file__).resolve().parent / "ckpt" / "mucodec.pt",
        help="Path to MuCodec checkpoint",
    )
    parser.add_argument(
        "--layer-num",
        type=int,
        default=7,
        help="MuCodec layer num (default follows generate.py)",
    )
    parser.add_argument(
        "--device",
        default="cuda:0",
        help="Torch device, e.g. cuda:0",
    )
    parser.add_argument(
        "--ext",
        nargs="+",
        default=[".mp3"],
        help="Audio extensions to include, e.g. .mp3 .wav .flac",
    )
    parser.add_argument(
        "--format",
        choices=["npz", "pt", "npy", "both", "all"],
        default="npz",
        help="Output format for code files",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Recompute files even if output already exists (disable resume)",
    )
    parser.add_argument(
        "--strict",
        action="store_true",
        help="Stop immediately on first failed file",
    )
    return parser.parse_args()


def list_audio_files(root: Path, exts):
    ext_set = {e.lower() if e.startswith(".") else f".{e.lower()}" for e in exts}
    files = [
        p
        for p in root.rglob("*")
        if p.is_file() and p.suffix.lower() in ext_set
    ]
    files.sort()
    return files


def expected_output_paths(output_stem: Path, fmt: str):
    if fmt == "npz":
        return [output_stem.with_suffix(".npz")]
    if fmt == "pt":
        return [output_stem.with_suffix(".pt")]
    if fmt == "npy":
        return [output_stem.with_suffix(".npy")]
    if fmt == "both":
        return [output_stem.with_suffix(".pt"), output_stem.with_suffix(".npy")]
    if fmt == "all":
        return [
            output_stem.with_suffix(".npz"),
            output_stem.with_suffix(".pt"),
            output_stem.with_suffix(".npy"),
        ]
    raise ValueError(f"Unsupported format: {fmt}")


def save_npz_atomic(codes_np: np.ndarray, output_path: Path):
    output_path.parent.mkdir(parents=True, exist_ok=True)
    tmp_path = None
    try:
        with tempfile.NamedTemporaryFile(
            mode="wb",
            suffix=".npz",
            dir=output_path.parent,
            delete=False,
        ) as tmp_file:
            tmp_path = Path(tmp_file.name)
            np.savez_compressed(tmp_file, codes=codes_np)
        os.replace(tmp_path, output_path)
    except Exception:
        if tmp_path is not None and tmp_path.exists():
            tmp_path.unlink()
        raise


def save_codes(codes: torch.Tensor, output_stem: Path, fmt: str):
    codes_cpu = codes.detach().cpu()
    codes_np = codes_cpu.numpy()
    if fmt in ("npz", "all"):
        save_npz_atomic(codes_np, output_stem.with_suffix(".npz"))
    if fmt in ("pt", "both", "all"):
        torch.save(codes_cpu, output_stem.with_suffix(".pt"))
    if fmt in ("npy", "both", "all"):
        np.save(output_stem.with_suffix(".npy"), codes_np)


def main():
    args = parse_args()

    from generate import MuCodec

    if not args.input_dir.exists() or not args.input_dir.is_dir():
        raise ValueError(f"input_dir does not exist or is not a directory: {args.input_dir}")

    if not args.ckpt.exists():
        raise FileNotFoundError(f"Checkpoint not found: {args.ckpt}")

    if args.device.startswith("cuda") and not torch.cuda.is_available():
        raise RuntimeError("CUDA device requested but torch.cuda.is_available() is False")

    audio_files = list_audio_files(args.input_dir, args.ext)
    if not audio_files:
        print("No audio files found.")
        return

    args.output_dir.mkdir(parents=True, exist_ok=True)

    mucodec = MuCodec(
        model_path=str(args.ckpt),
        layer_num=args.layer_num,
        load_main_model=True,
        device=args.device,
    )

    resume_enabled = not args.overwrite
    ok = 0
    skipped = 0
    failed = []

    for src in tqdm(audio_files, desc="Encoding", unit="file"):
        rel = src.relative_to(args.input_dir)
        output_stem = (args.output_dir / rel).with_suffix("")
        output_paths = expected_output_paths(output_stem, args.format)

        if resume_enabled and all(p.exists() for p in output_paths):
            skipped += 1
            continue

        output_stem.parent.mkdir(parents=True, exist_ok=True)

        try:
            codes = mucodec.file2code(str(src))
            save_codes(codes, output_stem, args.format)
            ok += 1
        except Exception as e:
            failed.append((src, str(e)))
            print(f"[FAILED] {src}: {e}")
            if args.strict:
                print("--strict enabled, stopping on first failure.")
                traceback.print_exc()
                break

    print(
        "Done. "
        f"success={ok}, skipped={skipped}, failed={len(failed)}, total={len(audio_files)}"
    )
    if failed:
        print("Failed files:")
        for path, err in failed:
            print(f"- {path}: {err}")


if __name__ == "__main__":
    main()