#!/usr/bin/env python3 """Replacement for vpgen.procedural_caption(). WHY A REPLACEMENT AND NOT A PATCH --------------------------------- The VoiceNet classification heads return, as `label`, the multi-sentence TRAINING ANCHOR for the predicted level, e.g. AGEV bucket 4 is: "The acoustic signature reflects a fully developed, mature adult, characterized by a highly settled, grounded, and authoritative resonant weight. The vocal folds exhibit ..." vpgen's `lab()` does `" ".join(t.split(".")[0].split(",")[0].strip().split()[:9])` and pastes the result into a noun slot, producing the known-broken output "A The acoustic signature reflects a fully developed, The audio delivers a standard masculine..." Truncating prose can never yield an adjective, so there is no patch to the slicing that fixes it. The anchors are not tags and must not be used as tags. WHAT THIS DOES INSTEAD ---------------------- An ordinal tag table keyed by (dimension, bucket, n_levels). Every VoiceNet head is an ordinal classifier with a known level count (57 dims: 54 x 7 levels, BKGN 5, EXPL 3), so bucket index + level count is exactly the information a short tag needs. Curated wording for the dimensions that actually carry a caption; a generic ordinal ("markedly high Roughness") for the rest, built from the head's own `name` field so nothing is invented. Style dimensions (S_*) are reported only when their regression score clears a threshold, and emotions come from Empathic Insight, not VoiceNet. """ import json, os, re # 7-level ordinal ladders (index 0..6). Curated per dimension where the wording matters. L7 = { "AGEV": ["infant","child","adolescent","young adult","adult","middle-aged","elderly"], # POLARITY FIX 2026-08-22. This ladder ran BACKWARDS relative to the data: high GEND is # MASCULINE, not feminine. Measured on 80,620 vprof_base rows, vn_GEND_reg correlates # +0.842 with vn_R_CHST_reg (chest resonance, a masculine marker), -0.484 with vn_R_HEAD_reg # (head resonance) and -0.352 with vn_BRGT_reg (brightness). Bucket 6 was therefore captioned # "strongly feminine" for the most masculine voices in the corpus. Numeric columns were always # correct; only this prose inverted. Order below is now low bucket -> feminine. "GEND": ["strongly feminine","feminine","somewhat feminine","androgynous", "somewhat masculine","masculine","strongly masculine"], "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"], } # POLARITY FIX 2026-08-22. Also backwards: high BKGN is CLEANER, not noisier. vn_BKGN_reg # correlates +0.699 with vn_RCQL_reg (recording quality) and +0.29 with qual_background_quality, # an INDEPENDENT model head -- so the top bucket is the quiet one. Order is now low -> noisy. # (The +0.29 is measured on 80,620 rows here; an earlier note quoted +0.402.) L5 = {"BKGN": ["very noisy background","noisy background","some background noise", "quiet background","no background noise"]} L3 = {"EXPL": ["clean content","mildly explicit content","explicit content"]} GENERIC7 = ["minimal","very low","low","moderate","elevated","high","extreme"] 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"} def tag(code, d): """(dim code, its score dict) -> short human tag, or '' if the dimension has nothing to say.""" if not d: return "" b = d.get("bucket") if b is None: return "" b = int(b) 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)] # generic ordinal built from the head's own display name name = (d.get("name") or code).replace(" Style", "") return f"{GENERIC7[min(b,6)]} {name.lower()}" def procedural_caption(f, text, dur, lang, *, style_thr=3.0, emo_thr=1.0, max_text=400, emo_rel=0.45, bursts=None): """f: one FastScorer.score_batch() dict. Returns (general, script). PRODUCTION CHANGES over the survey version (see WORKLOG "caption"): * emotions are gated relatively, not by a fixed 0.30 on an Empathic-Insight 0-7 scale -- 0.30 admitted essentially every emotion, which is why the survey's sample captions all read "concentration, emotional numbness, contemplation" regardless of the clip. * a stance/affect clause (VALN, STNC, VULN, RESP) and an explicit-content flag (EXPL) are emitted; those five heads were computed and then thrown away. * language is dropped when unknown instead of being rendered as "XX". * vocal bursts, when they cannot be placed inline, are named here (generic-GENERAL policy). """ vn = f.get("voicenet", {}) or {} bits = f.get("_caption_bits", {}) or {} g = lambda c: tag(c, vn.get(c)) who = " ".join(x for x in (g("AGEV"), g("GEND")) if x) or "unspecified" art = "An" if who[:1].lower() in "aeiou" else "A" # "A adult voice" -> "An adult voice" clauses = [f"{art} {who} voice"] delivery = [x for x in (g("AROU"), g("TEMP"), g("TENS"), g("VOLT")) if x] if delivery: clauses.append("delivery is " + ", ".join(delivery)) timbre = [x for x in (g("WARM"), g("BRGT"), g("ROUG"), g("FULL")) if x] if timbre: clauses.append("timbre is " + ", ".join(timbre)) speech = [x for x in (g("CLRT"), g("DFLU"), g("RANG"), g("RESP")) if x] if speech: clauses.append(", ".join(speech)) stance = [x for x in (g("VALN"), g("STNC"), g("VULN")) if x] if stance: clauses.append("affect is " + ", ".join(stance)) scored = (bits.get("top_emotions_scored") or []) if scored: hi = max(v for _, v in scored) thr = max(emo_thr, emo_rel * hi) emo = [e.replace("_", " ").replace("/", " or ").lower() for e, v in scored[:3] if v >= thr] if emo: clauses.append("reads as " + ", ".join(emo)) st = [STYLE_NAME.get(c, c) for c, r, _ in (bits.get("styles_scored") or []) if r >= style_thr] if st: clauses.append("style: " + ", ".join(st[:2])) rec = [x for x in (g("RCQL"), g("BKGN")) if x] if rec: clauses.append(", ".join(rec)) ex = vn.get("EXPL") or {} if int(ex.get("bucket", 0) or 0) > 0: clauses.append(tag("EXPL", ex)) if bursts: clauses.append("contains vocal bursts: " + ", ".join(sorted({b["label"] for b in bursts}))) clauses.append(f"genuineness {f.get('genuineness_0_6', 0):.1f}/6") clauses.append(f"vocal-burst blend {f.get('blend_0_10', 0):.1f}/10") tail = f"{dur:.1f}s" if lang and str(lang).lower() not in ("xx", "none", ""): tail += f", {str(lang).upper()}" clauses.append(tail) general = "; ".join(clauses) + "." script = (text or "").strip()[:max_text] return general, script def render(general, script): return f"GENERAL: {general}\nSCRIPT:\n{script}" if script else f"GENERAL: {general}"