#!/usr/bin/env python3 """Statistics over all voice profiles, all 40 emotions and all 57 VoiceNet dimensions. python build_stats.py --src /index --dst /stats [--workers 32] Writes three CSVs, each split by `origin`: stats_profiles.csv one row per (voice, origin) -- counts, hours, duration distribution stats_emotions.csv one row per (emotion, origin) -- intensity distribution + argmax counts stats_dimensions.csv one row per (vn dim, origin) -- reg distribution + bucket histogram Percentiles are computed from fixed-width histograms (4096 bins over a per-column fixed range), which is exact in mean/count/min/max and accurate to one bin width in the percentiles -- about 0.002 on the 0-7 emotion scale and 0.003 on the VoiceNet reg scale. This is what lets 26 M rows be summarised in bounded memory in a single streaming pass. The bin width is reported in each file. """ import argparse, os, glob, csv, math import numpy as np, pyarrow.parquet as pq from concurrent.futures import ProcessPoolExecutor EMO = ["Affection","Amusement","Anger","Astonishment_Surprise","Awe","Bitterness","Concentration", "Confusion","Contemplation","Contempt","Contentment","Disappointment","Disgust","Distress","Doubt", "Elation","Embarrassment","Emotional_Numbness","Fatigue_Exhaustion","Fear","Helplessness", "Hope_Enthusiasm_Optimism","Impatience_and_Irritability","Infatuation","Interest", "Intoxication_Altered_States_of_Consciousness","Longing","Malevolence_Malice","Pain", "Pleasure_Ecstasy","Pride","Relief","Sadness","Sexual_Lust","Shame","Sourness","Teasing", "Thankfulness_Gratitude","Triumph","Jealousy_and_Envy"] VN = ["AGEV","AROU","ARSH","ATCK","BKGN","BRGT","CHNK","CLRT","COGL","DARC","DFLU","EMPH","ESTH", "EXPL","FOCS","FULL","GEND","HARM","METL","RANG","RCQL","REGS","RESP","ROUG","R_CHST","R_HEAD", "R_MASK","R_MIXD","R_NASL","R_ORAL","R_THRT","SMTH","STNC","STRU","S_ASMR","S_AUTH","S_CART", "S_CASU","S_CONV","S_DRAM","S_FORM","S_MONO","S_NARR","S_NEWS","S_PLAY","S_RANT","S_STRY", "S_TECH","S_WHIS","TEMP","TENS","VALN","VALS","VFLX","VOLT","VULN","WARM"] NB = 4096 RANGES = {"emo": (0.0, 8.0), "vn": (-6.0, 10.0), "dur": (0.0, 120.0)} class Hist: __slots__ = ("lo","hi","h","n","s","mn","mx") def __init__(self, lo, hi): self.lo, self.hi = lo, hi self.h = np.zeros(NB, np.int64); self.n = 0; self.s = 0.0 self.mn = math.inf; self.mx = -math.inf def add(self, x): x = x[np.isfinite(x)] if x.size == 0: return self.n += x.size; self.s += float(x.sum()) self.mn = min(self.mn, float(x.min())); self.mx = max(self.mx, float(x.max())) i = np.clip(((x - self.lo) / (self.hi - self.lo) * NB).astype(np.int64), 0, NB - 1) self.h += np.bincount(i, minlength=NB) def merge(self, o): self.h += o.h; self.n += o.n; self.s += o.s self.mn = min(self.mn, o.mn); self.mx = max(self.mx, o.mx); return self def pct(self, qs): if self.n == 0: return [None] * len(qs) c = np.cumsum(self.h); out = [] for q in qs: k = np.searchsorted(c, q / 100.0 * self.n) out.append(self.lo + (min(k, NB - 1) + 0.5) * (self.hi - self.lo) / NB) return out def row(self): p = self.pct([1, 10, 25, 50, 75, 90, 99]) return dict(count=self.n, mean=(self.s / self.n if self.n else None), min=(self.mn if self.n else None), max=(self.mx if self.n else None), p1=p[0], p10=p[1], p25=p[2], median=p[3], p75=p[4], p90=p[5], p99=p[6]) def blank(): return dict(emo={e: Hist(*RANGES["emo"]) for e in EMO}, vn={d: Hist(*RANGES["vn"]) for d in VN}, bucket={d: np.zeros(8, np.int64) for d in VN}, top=({e: 0 for e in EMO}), voice={}) def scan(f): cols = (["voice","origin","dur_s","top_emotion","n_bursts","genuineness_0_6","blend_0_10"] + [f"emo_{e}" for e in EMO] + [f"vn_{d}_reg" for d in VN] + [f"vn_{d}_bucket" for d in VN]) t = pq.read_table(f, columns=[c for c in cols]) acc = {} origins = np.array(t["origin"].to_pylist()) for org in np.unique(origins): m = origins == org A = acc.setdefault(str(org), blank()) for e in EMO: A["emo"][e].add(np.asarray(t[f"emo_{e}"].to_numpy(zero_copy_only=False))[m]) for d in VN: A["vn"][d].add(np.asarray(t[f"vn_{d}_reg"].to_numpy(zero_copy_only=False))[m]) b = np.asarray(t[f"vn_{d}_bucket"].to_numpy(zero_copy_only=False))[m] b = b[np.isfinite(b)].astype(np.int64) A["bucket"][d] += np.bincount(np.clip(b, 0, 7), minlength=8) for te in np.asarray(t["top_emotion"].to_pylist())[m]: if te in A["top"]: A["top"][te] += 1 vs = np.asarray(t["voice"].to_pylist())[m] du = np.asarray(t["dur_s"].to_numpy(zero_copy_only=False))[m] gn = np.asarray(t["genuineness_0_6"].to_numpy(zero_copy_only=False))[m] bl = np.asarray(t["blend_0_10"].to_numpy(zero_copy_only=False))[m] nb = np.asarray(t["n_bursts"].to_numpy(zero_copy_only=False))[m] for v in np.unique(vs): mm = vs == v V = A["voice"].setdefault(str(v), dict(d=Hist(*RANGES["dur"]), n=0, sg=0.0, sb=0.0, nb=0)) V["d"].add(du[mm]); V["n"] += int(mm.sum()) V["sg"] += float(np.nansum(gn[mm])); V["sb"] += float(np.nansum(bl[mm])) V["nb"] += int(np.nansum(nb[mm])) return acc def merge(A, B): for org, b in B.items(): a = A.setdefault(org, blank()) for e in EMO: a["emo"][e].merge(b["emo"][e]) for d in VN: a["vn"][d].merge(b["vn"][d]); a["bucket"][d] += b["bucket"][d] for e, v in b["top"].items(): a["top"][e] += v for v, s in b["voice"].items(): t = a["voice"].setdefault(v, dict(d=Hist(*RANGES["dur"]), n=0, sg=0.0, sb=0.0, nb=0)) t["d"].merge(s["d"]); t["n"] += s["n"]; t["sg"] += s["sg"]; t["sb"] += s["sb"]; t["nb"] += s["nb"] return A def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", required=True); ap.add_argument("--dst", required=True) ap.add_argument("--workers", type=int, default=32) A = ap.parse_args() fs = sorted(glob.glob(os.path.join(A.src, "origin=*", "*.parquet"))) print(f"{len(fs)} parquet files", flush=True) acc = {} with ProcessPoolExecutor(A.workers) as ex: for k, r in enumerate(ex.map(scan, fs, chunksize=2), 1): merge(acc, r) if k % 500 == 0: print(f" {k}/{len(fs)}", flush=True) os.makedirs(A.dst, exist_ok=True) bw_e = (RANGES["emo"][1]-RANGES["emo"][0])/NB; bw_v = (RANGES["vn"][1]-RANGES["vn"][0])/NB F = ["count","mean","min","max","p1","p10","p25","median","p75","p90","p99"] with open(os.path.join(A.dst, "stats_emotions.csv"), "w", newline="") as fh: w = csv.writer(fh); w.writerow(["# percentile bin width", f"{bw_e:.6f}"]) w.writerow(["emotion","origin"]+F+["n_top_emotion","frac_top_emotion"]) for org in sorted(acc): tot = sum(acc[org]["top"].values()) or 1 for e in EMO: r = acc[org]["emo"][e].row() w.writerow([e,org]+[r[k] for k in F]+[acc[org]["top"][e], acc[org]["top"][e]/tot]) with open(os.path.join(A.dst, "stats_dimensions.csv"), "w", newline="") as fh: w = csv.writer(fh); w.writerow(["# percentile bin width", f"{bw_v:.6f}"]) w.writerow(["dimension","origin"]+F+[f"bucket_{i}" for i in range(8)]) for org in sorted(acc): for d in VN: r = acc[org]["vn"][d].row() w.writerow([d,org]+[r[k] for k in F]+list(acc[org]["bucket"][d])) with open(os.path.join(A.dst, "stats_profiles.csv"), "w", newline="") as fh: w = csv.writer(fh) w.writerow(["voice","origin","n_utterances","hours","dur_mean","dur_min","dur_max", "dur_p10","dur_median","dur_p90","mean_genuineness","mean_blend","total_bursts"]) for org in sorted(acc): for v in sorted(acc[org]["voice"]): s = acc[org]["voice"][v]; r = s["d"].row(); n = s["n"] or 1 w.writerow([v,org,s["n"], (s["d"].s/3600.0), r["mean"], r["min"], r["max"], r["p10"], r["median"], r["p90"], s["sg"]/n, s["sb"]/n, s["nb"]]) # ---- shipped normalisation artifact ------------------------------------------------- # Descriptive statistics of THIS population, recomputed from the re-annotated output. # NOTE: the captions do not consume these. `vn_*_bucket` is the argmax of an ordinal # classifier trained on absolute prose anchors, so caption wording is population-independent. # These are published so that users who WANT population-relative normalisation have a # reference that is (a) specific to the voice profiles and (b) free of the half-speed values. import json norm = dict( _about=("Descriptive statistics of the LAION voice-profile population, computed from the " "re-annotated (stereo-fixed) output. NOT used by the caption renderer: vn_*_bucket " "is an absolute ordinal-classifier argmax, not a percentile of this population. " "Provided for users who want population-relative normalisation."), _scope="voice profiles only (origin=original + origin=repair); not the wider 8-dataset corpus", _bin_width=dict(emotion=bw_e, voicenet_reg=bw_v), per_origin={}) for org in sorted(acc): norm["per_origin"][org] = dict( emotions={e: acc[org]["emo"][e].row() for e in EMO}, voicenet={d: dict(acc[org]["vn"][d].row(), bucket_counts=[int(x) for x in acc[org]["bucket"][d]]) for d in VN}, n_voices=len(acc[org]["voice"]), n_utterances=sum(v["n"] for v in acc[org]["voice"].values())) with open(os.path.join(A.dst, "norm_stats_vprof.json"), "w") as fh: json.dump(norm, fh, indent=1) print("wrote 3 CSVs + norm_stats_vprof.json to", A.dst) if __name__ == "__main__": main()