Upload build_data.py with huggingface_hub
Browse files- build_data.py +140 -0
build_data.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
from multiprocessing import Pool
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
from diffusers.pipelines.deprecated.audio_diffusion.mel import Mel
|
| 13 |
+
from transformers import AutoTokenizer, ClapModel
|
| 14 |
+
|
| 15 |
+
X_RES, Y_RES = 384, 256
|
| 16 |
+
HOP, NFFT, SR, TOPDB = 1024, 2048, 22050, 80
|
| 17 |
+
MAX_TOKENS = 32
|
| 18 |
+
|
| 19 |
+
def read_captions(csv_path):
|
| 20 |
+
rows = []
|
| 21 |
+
with open(csv_path, newline="", encoding="utf-8", errors="replace") as f:
|
| 22 |
+
reader = csv.DictReader(f)
|
| 23 |
+
for row in reader:
|
| 24 |
+
fn = row["file_name"]
|
| 25 |
+
caps = [row[f"caption_{i}"] for i in range(1, 6) if row.get(f"caption_{i}")]
|
| 26 |
+
rows.append((fn, caps))
|
| 27 |
+
return rows
|
| 28 |
+
|
| 29 |
+
_mel = None
|
| 30 |
+
def _get_mel():
|
| 31 |
+
global _mel
|
| 32 |
+
if _mel is None:
|
| 33 |
+
_mel = Mel(x_res=X_RES, y_res=Y_RES, sample_rate=SR, n_fft=NFFT, hop_length=HOP, top_db=TOPDB)
|
| 34 |
+
return _mel
|
| 35 |
+
|
| 36 |
+
def to_mel_array(path):
|
| 37 |
+
try:
|
| 38 |
+
mel = _get_mel()
|
| 39 |
+
mel.load_audio(audio_file=path)
|
| 40 |
+
img = mel.audio_slice_to_image(0)
|
| 41 |
+
return path, np.array(img, dtype=np.uint8)
|
| 42 |
+
except Exception:
|
| 43 |
+
return path, None
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
ap = argparse.ArgumentParser()
|
| 47 |
+
ap.add_argument("--audio-dir", required=True)
|
| 48 |
+
ap.add_argument("--captions-csv", required=True)
|
| 49 |
+
ap.add_argument("--split", required=True)
|
| 50 |
+
ap.add_argument("--out", default="/root/data")
|
| 51 |
+
ap.add_argument("--clap", default="laion/clap-htsat-unfused")
|
| 52 |
+
ap.add_argument("--workers", type=int, default=16)
|
| 53 |
+
ap.add_argument("--batch", type=int, default=128)
|
| 54 |
+
ap.add_argument("--device", default="cuda")
|
| 55 |
+
args = ap.parse_args()
|
| 56 |
+
os.makedirs(args.out, exist_ok=True)
|
| 57 |
+
|
| 58 |
+
rows = read_captions(args.captions_csv)
|
| 59 |
+
print(f"[build] {args.split}: {len(rows)} clips listed in captions csv", flush=True)
|
| 60 |
+
|
| 61 |
+
paths = [os.path.join(args.audio_dir, fn) for fn, _ in rows]
|
| 62 |
+
missing = [p for p in paths if not os.path.exists(p)]
|
| 63 |
+
if missing:
|
| 64 |
+
print(f"[build] WARNING {len(missing)} missing audio files, e.g. {missing[:3]}", flush=True)
|
| 65 |
+
|
| 66 |
+
t0 = time.time()
|
| 67 |
+
mel_by_path, failed = {}, 0
|
| 68 |
+
with Pool(args.workers) as pool:
|
| 69 |
+
for i, (p, arr) in enumerate(pool.imap(to_mel_array, paths, chunksize=8)):
|
| 70 |
+
if arr is None:
|
| 71 |
+
failed += 1
|
| 72 |
+
else:
|
| 73 |
+
mel_by_path[p] = arr
|
| 74 |
+
if (i + 1) % 500 == 0:
|
| 75 |
+
print(f"[build] mel {i+1}/{len(paths)} failed={failed} {time.time()-t0:.0f}s", flush=True)
|
| 76 |
+
print(f"[build] mel done: {len(mel_by_path)} ok, {failed} failed, {time.time()-t0:.0f}s", flush=True)
|
| 77 |
+
|
| 78 |
+
clip_paths = list(mel_by_path.keys())
|
| 79 |
+
clip_index = {p: i for i, p in enumerate(clip_paths)}
|
| 80 |
+
mel_arr = np.stack([mel_by_path[p] for p in clip_paths])
|
| 81 |
+
print(f"[build] mel_arr {mel_arr.shape} {mel_arr.nbytes/2**20:.0f} MiB", flush=True)
|
| 82 |
+
|
| 83 |
+
pair_clip_idx, pair_captions = [], []
|
| 84 |
+
for fn, caps in rows:
|
| 85 |
+
p = os.path.join(args.audio_dir, fn)
|
| 86 |
+
if p not in clip_index:
|
| 87 |
+
continue
|
| 88 |
+
for c in caps:
|
| 89 |
+
pair_clip_idx.append(clip_index[p])
|
| 90 |
+
pair_captions.append(c)
|
| 91 |
+
print(f"[build] {len(pair_captions)} (clip, caption) pairs", flush=True)
|
| 92 |
+
|
| 93 |
+
dev = args.device
|
| 94 |
+
tok = AutoTokenizer.from_pretrained(args.clap)
|
| 95 |
+
clap = ClapModel.from_pretrained(args.clap).to(dev).eval()
|
| 96 |
+
pool_dim = clap.config.projection_dim
|
| 97 |
+
seq_dim = clap.config.text_config.hidden_size
|
| 98 |
+
|
| 99 |
+
@torch.no_grad()
|
| 100 |
+
def encode(strings):
|
| 101 |
+
enc = tok(strings, padding="max_length", truncation=True, max_length=MAX_TOKENS,
|
| 102 |
+
return_tensors="pt").to(dev)
|
| 103 |
+
out = clap.text_model(**enc)
|
| 104 |
+
seq = out.last_hidden_state.float()
|
| 105 |
+
pooled = clap.text_projection(out.pooler_output).float()
|
| 106 |
+
return seq.cpu().numpy().astype(np.float16), pooled.cpu().numpy().astype(np.float16)
|
| 107 |
+
|
| 108 |
+
seq_chunks, pool_chunks = [], []
|
| 109 |
+
t0 = time.time()
|
| 110 |
+
for i in range(0, len(pair_captions), args.batch):
|
| 111 |
+
chunk = pair_captions[i:i + args.batch]
|
| 112 |
+
s, p = encode(chunk)
|
| 113 |
+
seq_chunks.append(s)
|
| 114 |
+
pool_chunks.append(p)
|
| 115 |
+
if (i // args.batch) % 20 == 0:
|
| 116 |
+
print(f"[build] clap {i}/{len(pair_captions)} {time.time()-t0:.0f}s", flush=True)
|
| 117 |
+
text_seq = np.concatenate(seq_chunks)
|
| 118 |
+
text_pool = np.concatenate(pool_chunks)
|
| 119 |
+
print(f"[build] text_seq {text_seq.shape} text_pool {text_pool.shape}", flush=True)
|
| 120 |
+
|
| 121 |
+
np.save(f"{args.out}/{args.split}_mel.npy", mel_arr)
|
| 122 |
+
np.save(f"{args.out}/{args.split}_text_seq.npy", text_seq)
|
| 123 |
+
np.save(f"{args.out}/{args.split}_text_pool.npy", text_pool)
|
| 124 |
+
json.dump({"pair_clip_idx": pair_clip_idx, "captions": pair_captions,
|
| 125 |
+
"clip_files": [os.path.basename(p) for p in clip_paths],
|
| 126 |
+
"n_clips": len(clip_paths), "seq_dim": seq_dim, "pool_dim": pool_dim,
|
| 127 |
+
"x_res": X_RES, "y_res": Y_RES, "hop_length": HOP, "n_fft": NFFT,
|
| 128 |
+
"sample_rate": SR, "top_db": TOPDB, "max_tokens": MAX_TOKENS},
|
| 129 |
+
open(f"{args.out}/{args.split}_meta.json", "w"))
|
| 130 |
+
|
| 131 |
+
if args.split == "development":
|
| 132 |
+
ns, npz = encode([""])
|
| 133 |
+
np.save(f"{args.out}/null_seq.npy", ns[0])
|
| 134 |
+
np.save(f"{args.out}/null_pool.npy", npz[0])
|
| 135 |
+
print("[build] wrote null embeddings", flush=True)
|
| 136 |
+
|
| 137 |
+
print("BUILDDONE", flush=True)
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
main()
|