| """Build the audio2face-emotion-arkit-teacher HuggingFace dataset from V19 teacher NPZs. |
| |
| Input : 14,082 NPZ files at /home/antonios/research/audio2face-assessment/outputs/v19_teacher/ |
| Output : ./data/{train,validation,test}-*.parquet + dataset_infos.json |
| |
| Each NPZ contains: audio_16k, nim_bs (T, 52), lam_bs (T, 52), emotion_26d, clip_id, T. |
| |
| Reference-only design: we DROP audio_16k from every row and keep only labels + the |
| two teacher blendshape sequences + the 26-D emotion vector + parsed metadata. Users |
| join with the original audio themselves (see README + examples/join_with_audio.py). |
| |
| Splits: train / validation / test at 90 / 5 / 5, stratified by (source × emotion_label) |
| so each split keeps the same class distribution. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import os |
| import sys |
| from pathlib import Path |
| from collections import Counter, defaultdict |
|
|
| import numpy as np |
| from datasets import Dataset, DatasetDict, Features, Sequence, Value |
| from tqdm import tqdm |
|
|
| sys.path.insert(0, str(Path(__file__).parent)) |
| from parse_metadata import parse_filename |
|
|
| V19_TEACHER_DIR = Path( |
| "/home/antonios/research/audio2face-assessment/outputs/v19_teacher" |
| ) |
|
|
|
|
| |
| |
| |
|
|
| FEATURES = Features({ |
| "clip_id": Value("string"), |
| "source": Value("string"), |
| "actor_id": Value("string"), |
| "emotion_label": Value("string"), |
| "emotion_label_native": Value("string"), |
| "intensity": Value("string"), |
| "audio_path_hint": Value("string"), |
| "audio_sr": Value("int32"), |
| "num_frames": Value("int32"), |
| |
| |
| "nim_bs": Sequence(Sequence(Value("float32"), length=52)), |
| "lam_bs": Sequence(Sequence(Value("float32"), length=52)), |
| "emotion_26d": Sequence(Value("float32"), length=26), |
| }) |
|
|
|
|
| |
| |
| |
|
|
| def npz_to_row(npz_path: Path) -> dict | None: |
| """Load one NPZ + parse filename → one HF row dict. |
| Returns None if the file is malformed (logged + skipped).""" |
| meta = parse_filename(npz_path.name) |
| d = np.load(npz_path, allow_pickle=False) |
| needed = {"nim_bs", "lam_bs", "emotion_26d"} |
| missing = needed - set(d.files) |
| if missing: |
| print(f" SKIP {npz_path.name}: missing keys {missing}", file=sys.stderr) |
| return None |
|
|
| nim = d["nim_bs"].astype(np.float32, copy=False) |
| lam = d["lam_bs"].astype(np.float32, copy=False) |
| emo = d["emotion_26d"].astype(np.float32, copy=False).reshape(-1) |
| if nim.ndim != 2 or nim.shape[1] != 52: |
| print(f" SKIP {npz_path.name}: nim_bs bad shape {nim.shape}", file=sys.stderr) |
| return None |
| if lam.shape != nim.shape: |
| print(f" SKIP {npz_path.name}: lam_bs shape {lam.shape} != nim {nim.shape}", file=sys.stderr) |
| return None |
| if emo.shape != (26,): |
| print(f" SKIP {npz_path.name}: emotion_26d shape {emo.shape}", file=sys.stderr) |
| return None |
|
|
| T = int(nim.shape[0]) |
| return { |
| "clip_id": meta["clip_id"], |
| "source": meta["source"], |
| "actor_id": meta["actor_id"], |
| "emotion_label": meta["emotion_label"], |
| "emotion_label_native": meta["emotion_label_native"], |
| "intensity": meta["intensity"], |
| "audio_path_hint": meta["audio_path_hint"], |
| "audio_sr": 16000, |
| "num_frames": T, |
| "nim_bs": nim.tolist(), |
| "lam_bs": lam.tolist(), |
| "emotion_26d": emo.tolist(), |
| } |
|
|
|
|
| |
| |
| |
|
|
| def stratified_indices(rows: list[dict], |
| train_frac: float = 0.90, |
| val_frac: float = 0.05, |
| seed: int = 0) -> dict[str, list[int]]: |
| """Stratify by (source, emotion_label). |
| |
| For each group, deterministic shuffle then split into train/val/test by the |
| given fractions. Returns a dict {split_name: [row_idx, ...]}. |
| """ |
| rng = np.random.default_rng(seed) |
| by_group: dict[tuple[str, str], list[int]] = defaultdict(list) |
| for i, r in enumerate(rows): |
| by_group[(r["source"], r["emotion_label"])].append(i) |
|
|
| splits = {"train": [], "validation": [], "test": []} |
| for key, idxs in by_group.items(): |
| idxs = list(idxs) |
| rng.shuffle(idxs) |
| n = len(idxs) |
| n_train = int(round(n * train_frac)) |
| n_val = int(round(n * val_frac)) |
| |
| train_part = idxs[:n_train] |
| val_part = idxs[n_train : n_train + n_val] |
| test_part = idxs[n_train + n_val :] |
| |
| if n >= 20 and not val_part: val_part = [test_part.pop(0)] |
| if n >= 20 and not test_part: test_part = [val_part.pop(0)] |
| splits["train"].extend(train_part) |
| splits["validation"].extend(val_part) |
| splits["test"].extend(test_part) |
| return splits |
|
|
|
|
| |
| |
| |
|
|
| def parse_args(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--input-dir", type=Path, default=V19_TEACHER_DIR) |
| p.add_argument("--output-dir", type=Path, default=Path(__file__).parent / "data") |
| p.add_argument("--seed", type=int, default=0) |
| p.add_argument("--limit", type=int, default=0, |
| help="if >0, process only the first N NPZs (smoke test)") |
| p.add_argument("--save-mode", choices=["parquet", "arrow"], default="parquet") |
| return p.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| files = sorted(p for p in args.input_dir.iterdir() |
| if p.is_file() and p.suffix == ".npz") |
| if args.limit > 0: |
| files = files[:args.limit] |
| print(f"Found {len(files)} NPZ files in {args.input_dir}") |
|
|
| rows: list[dict] = [] |
| skipped = 0 |
| for p in tqdm(files, desc="loading NPZs"): |
| row = npz_to_row(p) |
| if row is None: |
| skipped += 1 |
| continue |
| rows.append(row) |
| print(f"\nKept {len(rows)} rows, skipped {skipped}") |
|
|
| |
| split_idxs = stratified_indices(rows, seed=args.seed) |
| for name, idxs in split_idxs.items(): |
| print(f" {name:10} {len(idxs):>6} rows") |
|
|
| |
| ds_dict = {} |
| for split, idxs in split_idxs.items(): |
| subset = [rows[i] for i in idxs] |
| |
| cols = {k: [r[k] for r in subset] for k in FEATURES.keys()} |
| ds_dict[split] = Dataset.from_dict(cols, features=FEATURES) |
| dd = DatasetDict(ds_dict) |
| print(dd) |
|
|
| |
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| if args.save_mode == "parquet": |
| for split, ds in dd.items(): |
| out = args.output_dir / f"{split}.parquet" |
| ds.to_parquet(out) |
| mb = out.stat().st_size / 1024 / 1024 |
| print(f" wrote {out.name}: {mb:.1f} MB") |
| else: |
| dd.save_to_disk(str(args.output_dir / "arrow")) |
| print(f" wrote Arrow shards under {args.output_dir/'arrow'}") |
|
|
| |
| print("\n=== emotion × split sanity check ===") |
| print(f"{'emotion':<13}{'train':>8}{'val':>6}{'test':>6}") |
| train_c = Counter(r["emotion_label"] for r in (rows[i] for i in split_idxs["train"])) |
| val_c = Counter(r["emotion_label"] for r in (rows[i] for i in split_idxs["validation"])) |
| test_c = Counter(r["emotion_label"] for r in (rows[i] for i in split_idxs["test"])) |
| for e in sorted(set(train_c) | set(val_c) | set(test_c)): |
| print(f" {e:<13}{train_c[e]:>6}{val_c[e]:>6}{test_c[e]:>6}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|