#!/usr/bin/env python3 """Regenerate the procedural caption from the FLAT numeric columns shipped in the index parquet. WHY THIS EXISTS --------------- `caption2.procedural_caption()` renders from the nested in-memory scorer output (`f`), which is not what the release ships. The release ships flat columns: 57 `vn_*_reg` / `vn_*_bucket`, 40 `emo_*`, 4 `qual_*`, `genuineness_0_6`, `blend_0_10`, `n_bursts` / `burst_labels` / `burst_placement`, `dur_s`, `lang`. This module renders a caption from exactly those columns and nothing else, so a downstream user can re-word every caption in the corpus without re-running a single GPU model. That is the stated regenerability requirement. TWO POLARITY VERSIONS --------------------- `polarity="v1_buggy"` reproduces the strings ACTUALLY ON DISK, including the inverted GEND and BKGN ladders. `polarity="v2"` is the corrected wording. v1 is kept so the shipped `caption_general_v1_buggy` column is reproducible and so this module can be regression-tested against the on-disk captions -- see selftest_vs_disk() below, which is how it was validated. CORRECTNESS NOTE. The v1 output is byte-identical to the on-disk caption only where the on-disk caption itself was well-formed. It is validated on `vprof_vc`, whose annotations are sound. It is NOT validated on vprof_base / vprof_repaired, whose annotation layer was computed from a half-speed decode (see the dataset card, "Known issues"); the renderer is fine there, the INPUTS are not. """ import math, os # ---------------------------------------------------------------- ordinal ladders _GEND_V1 = ["strongly masculine","masculine","somewhat masculine","androgynous", "somewhat feminine","feminine","strongly feminine"] _GEND_V2 = ["strongly feminine","feminine","somewhat feminine","androgynous", "somewhat masculine","masculine","strongly masculine"] _BKGN_V1 = ["no background noise","quiet background","some background noise", "noisy background","very noisy background"] _BKGN_V2 = ["very noisy background","noisy background","some background noise", "quiet background","no background noise"] def ladders(polarity="v2"): """(L7, L5, L3) for the requested polarity. v1_buggy == what is on disk.""" L7 = { "AGEV": ["infant","child","adolescent","young adult","adult","middle-aged","elderly"], "GEND": _GEND_V1 if polarity == "v1_buggy" else _GEND_V2, "AROU": ["lethargic","very low-energy","subdued","normally alert","energised","highly aroused","frantic"], "VALN": ["deeply negative","negative","mildly negative","neutral","mildly positive","positive","elated"], "TEMP": ["very slow","slow","measured","normal-paced","brisk","fast","very fast"], "WARM": ["cold","cool","slightly cool","neutral-toned","slightly warm","warm","very warm"], "BRGT": ["very dark","dark","slightly dark","neutral-bright","slightly bright","bright","very bright"], "TENS": ["fully relaxed","relaxed","slightly relaxed","neutral tension","slightly tense","tense","very tense"], "VOLT": ["completely steady","steady","fairly steady","moderately variable","variable","volatile","highly volatile"], "ROUG": ["very smooth","smooth","fairly smooth","slightly rough","rough","very rough","gravelly"], "RCQL": ["very poor recording","poor recording","below-average recording","average recording", "good recording","very good recording","studio-grade recording"], "CLRT": ["very slurred","slurred","somewhat unclear","average clarity","clear","very clear","crisply articulate"], "DFLU": ["no disfluency","almost no disfluency","little disfluency","some disfluency", "frequent disfluency","heavy disfluency","severely disfluent"], "RESP": ["no audible breath","minimal breath","light breath","normal breath", "audible breath","heavy breath","breathless"], "RANG": ["monotone pitch","narrow pitch range","fairly narrow pitch","moderate pitch range", "wide pitch range","very wide pitch range","extreme pitch range"], "FULL": ["very thin","thin","slightly thin","balanced body","full","very full","booming"], "VULN": ["guarded","fairly guarded","slightly guarded","neutral openness", "slightly vulnerable","vulnerable","very vulnerable"], "STNC": ["very submissive","submissive","slightly submissive","neutral stance", "slightly dominant","dominant","very dominant"], "ESTH": ["very unpleasant","unpleasant","slightly unpleasant","neutral","pleasant","very pleasant","beautiful"], } L5 = {"BKGN": _BKGN_V1 if polarity == "v1_buggy" else _BKGN_V2} L3 = {"EXPL": ["clean content","mildly explicit content","explicit content"]} return L7, L5, L3 STYLE_NAME = {"S_ASMR":"ASMR","S_AUTH":"authoritative","S_CART":"cartoonish","S_CASU":"casual", "S_CONV":"conversational","S_DRAM":"dramatic","S_FORM":"formal","S_MONO":"monologue", "S_NARR":"narration","S_NEWS":"newsreading","S_PLAY":"playful","S_RANT":"ranting", "S_STRY":"storytelling","S_TECH":"didactic","S_WHIS":"whispered"} STYLE_DIMS = sorted(STYLE_NAME) # EmoNet taxonomy, in the order the scorer emitted it. Ties in the top-5 selection resolve by # THIS order (Python's sort is stable), so it must not be re-sorted. 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_&_Envy"] # `&` is not legal in a column name; the flattener wrote `and`. Map back so the rendered wording # matches what the original in-memory dict produced. EMO_COL = {e: "emo_" + e.replace("&", "and") for e in EMO} def _tag(code, bucket, L7, L5, L3): if bucket is None: return "" try: b = int(bucket) except (TypeError, ValueError): return "" if code in L3: return L3[code][min(b, 2)] if code in L5: return L5[code][min(b, 4)] if code in L7: t = L7[code]; return t[min(b, len(t) - 1)] return "" def _num(row, key): v = row.get(key) if v is None: return None try: f = float(v) return None if math.isnan(f) else f except (TypeError, ValueError): return None def _emo_label(e): """Display form of an emotion name. "&" -> "and" so this matches the `caption_general` column, which is produced by a separate code path (capfix.py) that derives the label from the corpus column name `emo_Jealousy_and_Envy`. Before this, `caption_clausal` and `caption_general` disagreed on exactly one token across the whole corpus. """ return (e.replace("_", " ").replace("/", " or ").replace("&", "and") .replace(" ", " ").lower()) # --------------------------------------------------------------------------- # # EMOTION GATE -- percentile, not an absolute threshold. added 2026-08-23 # # `emo_thr=1.0` was an ABSOLUTE cut applied to 40 Empathic-Insight heads that are # not on a common scale. `emo_Interest` has median 2.082 and is never zero; # `emo_Infatuation` has median -0.017 and is zero on 87.7 % of the corpus. The cut # therefore selected whichever head sits highest on its own scale, not whichever # emotion the clip actually carries: measured across 165,516,420 regenerated # captions it named Interest on 90.6 % of all rows and Bitterness on 0.1 %. # # An emotion is now named when it lands in the top 10 % FOR THAT EMOTION against # `capnorm.npz` -- a pooled tie-aware mid-rank ECDF over 132,833,726 utterances, # the same artefact used to regenerate `caption_general`, so the templates and the # corpus column agree. `emo_gate="absolute"` reproduces the pre-2026-08-23 strings. NBIN_EMO = 4096 EMO_FLOOR = 0.90 EMO_TOP_N = 3 _CAPNORM = None def _capnorm(path=None): """Lazy singleton. Returns (fields, table, lo, hi, width) or None if absent.""" global _CAPNORM if _CAPNORM is None: import numpy as _np p = path or os.path.join(os.path.dirname(os.path.abspath(__file__)), "capnorm.npz") z = _np.load(p, allow_pickle=True) h = z["hist"].astype("float64") n = _np.maximum(h.sum(1, keepdims=True), 1.0) below = _np.cumsum(h, axis=1) - h # float64. The .astype("float32") that used to be here collapsed genuinely # different percentiles onto one value (emo_Relief 0.99780922730421640 and # emo_Contentment 0.99780920848369492 both became 0.99780923128128052), # manufacturing ties that then had to be broken arbitrarily. capfix.py, which # writes caption_general, and capgate.py both keep full precision, so this must # too or the templates disagree with the column. tab = (below + 0.5 * h) / n # tie-aware mid-rank, float64 lo, hi = z["lo"].astype("float64"), z["hi"].astype("float64") _CAPNORM = ([str(x) for x in z["fields"]], tab, lo, hi, (hi - lo) / NBIN_EMO) return _CAPNORM def emo_percentile(col, value): """Empirical percentile of `value` for corpus column `col`, or None.""" import math as _m fields, tab, lo, hi, w = _capnorm() try: d = fields.index(col) except ValueError: return None if value is None or (isinstance(value, float) and _m.isnan(value)): return None k = int(_m.floor((float(value) - lo[d]) / w[d])) + 1 k = min(max(k, 0), NBIN_EMO + 1) return float(tab[d][k]) def features(row, polarity="v2", style_thr=3.0, emo_thr=1.0, emo_rel=0.45, emo_gate="percentile", emo_floor=EMO_FLOOR): """Flat parquet row -> the intermediate the templates consume. Pure; no model, no audio.""" L7, L5, L3 = ladders(polarity) g = lambda c: _tag(c, row.get(f"vn_{c}_bucket"), L7, L5, L3) emo_vals = [(e, _num(row, EMO_COL[e])) for e in EMO] emo_vals = [(e, v) for e, v in emo_vals if v is not None] emo = [] if emo_gate == "percentile": ranked = [] for e, v in emo_vals: u = emo_percentile(EMO_COL[e], v) if u is not None and u >= emo_floor: ranked.append((u, e)) # EXPLICIT tie-break: descending percentile, then ASCENDING DISPLAY NAME. # Not a stable sort -- that preserves input order, which a consumer of the # published caption cannot see. Ordering ties by the name that appears in the # caption is reproducible from the caption alone, and is the identical rule used # by capfix.py (which writes caption_general) and capgate.py, so the column and # the 16 templates cannot disagree. Genuine ties are rare now that capfix no # longer casts its ECDF table to float32 (that cast alone manufactured ties: # emo_Relief 0.997809227 and emo_Contentment 0.997809208 both became one float32). ranked.sort(key=lambda t: (-t[0], _emo_label(t[1]))) emo = [_emo_label(e) for _, e in ranked[:EMO_TOP_N]] else: scored = sorted(emo_vals, key=lambda x: -x[1])[:5] if scored: hi = max(v for _, v in scored) thr = max(emo_thr, emo_rel * hi) emo = [_emo_label(e) for e, v in scored[:3] if v >= thr] st_scored = sorted(((d, _num(row, f"vn_{d}_reg")) for d in STYLE_DIMS), key=lambda x: -(x[1] if x[1] is not None else -1e9))[:3] styles = [STYLE_NAME.get(d, d) for d, r in st_scored if r is not None and r >= style_thr][:2] expl_b = row.get("vn_EXPL_bucket") try: expl_on = int(expl_b or 0) > 0 except (TypeError, ValueError): expl_on = False bursts = [] if str(row.get("burst_placement") or "") == "general": bl = row.get("burst_labels") or [] bursts = sorted({str(x) for x in bl}) lang = row.get("lang") lang = str(lang).upper() if lang and str(lang).lower() not in ("xx", "none", "") else None return dict( who=" ".join(x for x in (g("AGEV"), g("GEND")) if x) or "unspecified", delivery=[x for x in (g("AROU"), g("TEMP"), g("TENS"), g("VOLT")) if x], timbre=[x for x in (g("WARM"), g("BRGT"), g("ROUG"), g("FULL")) if x], speech=[x for x in (g("CLRT"), g("DFLU"), g("RANG"), g("RESP")) if x], stance=[x for x in (g("VALN"), g("STNC"), g("VULN")) if x], emotions=emo, styles=styles, recording=[x for x in (g("RCQL"), g("BKGN")) if x], explicit=_tag("EXPL", expl_b, L7, L5, L3) if expl_on else None, bursts=bursts, genuineness=_num(row, "genuineness_0_6") or 0.0, blend=_num(row, "blend_0_10") or 0.0, dur=_num(row, "dur_s") or 0.0, lang=lang, ) # ---------------------------------------------------------------- templates def _t_clausal(F): """The shipped wording: semicolon-separated clauses. Structurally identical to caption2.""" who = F["who"] art = "An" if who[:1].lower() in "aeiou" else "A" c = [f"{art} {who} voice"] if F["delivery"]: c.append("delivery is " + ", ".join(F["delivery"])) if F["timbre"]: c.append("timbre is " + ", ".join(F["timbre"])) if F["speech"]: c.append(", ".join(F["speech"])) if F["stance"]: c.append("affect is " + ", ".join(F["stance"])) c.append(("reads as " + ", ".join(F["emotions"])) if F["emotions"] else "no dominant emotion") # matches the caption_general column if F["styles"]: c.append("style: " + ", ".join(F["styles"])) if F["recording"]:c.append(", ".join(F["recording"])) if F["explicit"]: c.append(F["explicit"]) if F["bursts"]: c.append("contains vocal bursts: " + ", ".join(F["bursts"])) c.append(f"genuineness {F['genuineness']:.1f}/6") c.append(f"vocal-burst blend {F['blend']:.1f}/10") tail = f"{F['dur']:.1f}s" if F["lang"]: tail += f", {F['lang']}" c.append(tail) return "; ".join(c) + "." def _t_prose(F): """Flowing sentences; no metric tail. Intended for caption-conditioned TTS training.""" who = F["who"] art = "An" if who[:1].lower() in "aeiou" else "A" s = [f"{art} {who} voice."] mid = [] if F["delivery"]: mid.append("delivered " + ", ".join(F["delivery"])) if F["timbre"]: mid.append("with a " + ", ".join(F["timbre"]) + " timbre") if F["speech"]: mid.append(", ".join(F["speech"])) if mid: s.append("It is " + "; ".join(mid) + ".") if F["emotions"]: s.append("The speaker reads as " + ", ".join(F["emotions"]) + ".") if F["stance"]: s.append("The affect is " + ", ".join(F["stance"]) + ".") if F["styles"]: s.append("The register is " + " and ".join(F["styles"]) + ".") if F["bursts"]: s.append("It contains vocal bursts: " + ", ".join(F["bursts"]) + ".") if F["recording"]:s.append("Recording: " + ", ".join(F["recording"]) + ".") if F["explicit"]: s.append(F["explicit"].capitalize() + ".") return " ".join(s) def _t_terse(F): """Comma-separated tag list, no scaffolding. Shortest useful form.""" parts = [F["who"]] + F["delivery"] + F["timbre"] + F["speech"] + F["stance"] \ + F["emotions"] + F["styles"] + F["recording"] if F["explicit"]: parts.append(F["explicit"]) if F["bursts"]: parts += [f"burst:{b}" for b in F["bursts"]] return ", ".join(parts) def _t_tags(F): """Machine-readable key=value form for filtering and conditioning.""" kv = [("who", F["who"])] for k in ("delivery", "timbre", "speech", "stance", "emotions", "styles", "recording"): if F[k]: kv.append((k, "|".join(F[k]))) if F["explicit"]: kv.append(("explicit", F["explicit"])) if F["bursts"]: kv.append(("bursts", "|".join(F["bursts"]))) kv += [("genuineness", f"{F['genuineness']:.1f}"), ("blend", f"{F['blend']:.1f}"), ("dur_s", f"{F['dur']:.1f}")] if F["lang"]: kv.append(("lang", F["lang"])) return " ".join(f"{k}={v}" for k, v in kv) # ---------------------------------------------------------------- extended template set # 16 genuinely distinct wordings. They vary along four axes so a caption-conditioned model sees # real paraphrase rather than cosmetic reshuffling: CLAUSE ORDER (who-first / emotion-first / # recording-first), VERBOSITY (minimal .. verbose), REGISTER (neutral description, casting call, # stage direction, second-person directive, structured record), and BURST HANDLING (appended, # woven into the delivery clause, or omitted). def _join(xs, last=" and "): xs = [x for x in xs if x] if not xs: return "" if len(xs) == 1: return xs[0] return ", ".join(xs[:-1]) + last + xs[-1] def _bursts_phrase(F): return ("vocal bursts: " + ", ".join(F["bursts"])) if F["bursts"] else "" def _t_casting(F): """Casting-call register.""" p = [f"Casting: {F['who']} voice."] if F["delivery"]: p.append("Delivery: " + _join(F["delivery"]) + ".") if F["timbre"]: p.append("Timbre: " + _join(F["timbre"]) + ".") if F["emotions"]: p.append("Read: " + _join(F["emotions"]) + ".") if F["styles"]: p.append("Register: " + _join(F["styles"]) + ".") n = [x for x in (_bursts_phrase(F), F["explicit"]) if x] if n: p.append("Notes: " + "; ".join(n) + ".") return " ".join(p) def _t_stage(F): """Bracketed stage direction, as a script annotation.""" head = ", ".join([F["who"]] + F["delivery"][:2]) inner = [head] if F["emotions"]: inner.append(_join(F["emotions"][:2])) if F["bursts"]: inner.append("with " + ", ".join(F["bursts"])) return "[" + "; ".join(inner) + "]" def _t_directive(F): """Second-person imperative — instructs a performer.""" p = [f"Speak with {'an' if F['who'][:1].lower() in 'aeiou' else 'a'} {F['who']} voice."] if F["delivery"]: p.append("Keep the delivery " + _join(F["delivery"]) + ".") if F["timbre"]: p.append("Let the timbre sit " + _join(F["timbre"]) + ".") if F["emotions"]: p.append("Colour it with " + _join(F["emotions"]) + ".") if F["stance"]: p.append("The affect should read " + _join(F["stance"]) + ".") if F["bursts"]: p.append("Include " + ", ".join(F["bursts"]) + ".") return " ".join(p) def _t_dossier(F): """Labelled record, one field per line.""" L = [("VOICE", F["who"]), ("DELIVERY", ", ".join(F["delivery"])), ("TIMBRE", ", ".join(F["timbre"])), ("SPEECH", ", ".join(F["speech"])), ("AFFECT", ", ".join(F["stance"])), ("EMOTION", ", ".join(F["emotions"])), ("STYLE", ", ".join(F["styles"])), ("RECORDING", ", ".join(F["recording"])), ("BURSTS", ", ".join(F["bursts"])), ("EXPLICIT", F["explicit"] or ""), ("GENUINENESS", f"{F['genuineness']:.1f}/6"), ("BLEND", f"{F['blend']:.1f}/10"), ("DURATION", f"{F['dur']:.1f}s"), ("LANG", F["lang"] or "")] return "\n".join(f"{k}: {v}" for k, v in L if v) def _t_minimal(F): """Shortest useful form: who, one emotion, duration.""" e = F["emotions"][0] if F["emotions"] else "" return ", ".join(x for x in (F["who"], e, f"{F['dur']:.1f}s") if x) def _t_emotive(F): """Emotion-first ordering.""" lead = ("Reads as " + _join(F["emotions"])) if F["emotions"] else "Affectively neutral" p = [f"{lead}, in {'an' if F['who'][:1].lower() in 'aeiou' else 'a'} {F['who']} voice."] if F["stance"]: p.append("Affect " + _join(F["stance"]) + ".") if F["delivery"]: p.append("Delivered " + _join(F["delivery"]) + ".") if F["bursts"]: p.append("Contains " + ", ".join(F["bursts"]) + ".") return " ".join(p) def _t_technical(F): """Recording-and-quality first, voice second.""" p = [] if F["recording"]: p.append(_join(F["recording"]).capitalize() + ".") p.append(f"Source is {'an' if F['who'][:1].lower() in 'aeiou' else 'a'} {F['who']} voice.") if F["speech"]: p.append("Articulation: " + _join(F["speech"]) + ".") if F["timbre"]: p.append("Spectral character: " + _join(F["timbre"]) + ".") p.append(f"Genuineness {F['genuineness']:.1f}/6, burst blend {F['blend']:.1f}/10, {F['dur']:.1f}s.") return " ".join(p) def _t_bullets(F): """Markdown bullet list.""" B = [("voice", F["who"]), ("delivery", ", ".join(F["delivery"])), ("timbre", ", ".join(F["timbre"])), ("speech", ", ".join(F["speech"])), ("affect", ", ".join(F["stance"])), ("emotion", ", ".join(F["emotions"])), ("style", ", ".join(F["styles"])), ("recording", ", ".join(F["recording"])), ("bursts", ", ".join(F["bursts"]))] return "\n".join(f"- {k}: {v}" for k, v in B if v) def _t_verbose(F): """Maximal: every clause spelled out in full sentences.""" art = "An" if F["who"][:1].lower() in "aeiou" else "A" p = [f"{art} {F['who']} voice is speaking."] if F["delivery"]: p.append("The delivery is " + _join(F["delivery"]) + ".") if F["timbre"]: p.append("The timbre is " + _join(F["timbre"]) + ".") if F["speech"]: p.append("In terms of articulation it is " + _join(F["speech"]) + ".") if F["stance"]: p.append("The affective stance is " + _join(F["stance"]) + ".") if F["emotions"]: p.append("Emotionally it reads as " + _join(F["emotions"]) + ".") if F["styles"]: p.append("The register is " + _join(F["styles"]) + ".") if F["recording"]:p.append("The recording is " + _join(F["recording"]) + ".") if F["explicit"]: p.append("Content is flagged " + F["explicit"] + ".") if F["bursts"]: p.append("It contains " + _join(F["bursts"]) + ".") p.append(f"Perceived genuineness is {F['genuineness']:.1f} of 6 and vocal-burst blend " f"{F['blend']:.1f} of 10. The clip runs {F['dur']:.1f} seconds" + (f" in {F['lang']}." if F["lang"] else ".")) return " ".join(p) def _t_headline(F): """Headline, then detail after a colon.""" head = F["who"] if F["emotions"]: head += f", {F['emotions'][0]}" rest = _join(F["delivery"][:2] + F["timbre"][:2]) return f"{head}: {rest}." if rest else f"{head}." def _t_burst_inline(F): """Bursts woven into the delivery clause instead of appended at the end.""" art = "An" if F["who"][:1].lower() in "aeiou" else "A" d = list(F["delivery"]) if F["bursts"]: d.append("punctuated by " + ", ".join(F["bursts"])) p = [f"{art} {F['who']} voice"] if d: p.append("delivery is " + ", ".join(d)) if F["timbre"]: p.append("timbre is " + ", ".join(F["timbre"])) if F["emotions"]: p.append("reads as " + ", ".join(F["emotions"])) if F["recording"]:p.append(", ".join(F["recording"])) return "; ".join(p) + "." def _t_narrative(F): """Descriptive, avoids asserting speaker identity — describes the voice, not the person.""" art = "an" if F["who"][:1].lower() in "aeiou" else "a" s = f"The recording carries {art} {F['who']} voice" if F["emotions"]: s += " that sounds " + _join(F["emotions"]) s += "." if F["delivery"] or F["timbre"]: s += " It comes across as " + _join(F["delivery"][:2] + F["timbre"][:2]) + "." if F["bursts"]: s += " " + _bursts_phrase(F).capitalize() + " are audible." return s TEMPLATES = { "clausal": _t_clausal, "prose": _t_prose, "terse": _t_terse, "tags": _t_tags, "casting": _t_casting, "stage": _t_stage, "directive": _t_directive, "dossier": _t_dossier, "minimal": _t_minimal, "emotive": _t_emotive, "technical": _t_technical, "bullets": _t_bullets, "verbose": _t_verbose, "headline": _t_headline, "burst_inline": _t_burst_inline, "narrative": _t_narrative, } def render(row, template="clausal", polarity="v2", **kw): """Flat parquet row -> caption string. `row` may be a dict or a pandas Series.""" if hasattr(row, "to_dict"): row = row.to_dict() return TEMPLATES[template](features(row, polarity=polarity, **kw))