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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env python
"""Corpus-wide regeneration of `caption_general`.

TWO defects are repaired in ONE pass over the index parquets.

Defect 1 -- the emotion clause was gated on an ABSOLUTE raw threshold (emo_thr=1.0).
  The 40 Empathic-Insight heads are not on a common scale: emo_Interest has median
  2.082 and 0.0 % zeros, emo_Infatuation median -0.017 and 87.7 % zeros. The absolute
  gate therefore named Interest on 94.8 % of clips and Sadness on almost none -- it was
  reporting the scale of the head, not the emotion of the clip.
  FIX: name an emotion when it is in the top 10 % FOR THAT EMOTION against the pooled
  tie-aware mid-rank ECDF in emonorm/out/capnorm.npz (132,833,726 rows), max 3 named.
  A clip that clears nothing says "no dominant emotion".

Defect 2 -- the GEND and BKGN ordinal ladders ran BACKWARDS.
  High vn_GEND is MASCULINE (+0.842 with chest resonance, -0.484 with head resonance)
  but was rendered "feminine". High vn_BKGN is CLEANER (+0.786 with recording quality,
  +0.29 with the independent qual_background_quality head) but was rendered "noisy".
  caption2.py was fixed 2026-08-22 (md5 ec55b223) but the corpus rows were never redone.

WHY THIS IS DRIVEN FROM THE BUCKET COLUMN, NOT BY FLIPPING THE STRING
  STATE AS OF 2026-08-23, AFTER THIS PASS: every tree is corrected. All 48,556 shards /
  165,516,420 rows carry the corrected polarity and a `caption_general_v1` column holding
  the previous text. Do not read the paragraph below as a description of the corpus today.

  AS MEASURED BEFORE THE PASS (2026-08-22, the reason for this design): part of the corpus
  was ALREADY correct. The `laion-tts-annotated-v1-reann` tree (vprof_base +
  vprof_repaired, 28.2 M rows) had been regenerated after the caption2.py fix and measured
  100 % new-polarity, while all nine live-tree datasets measured 100 % old-polarity. A
  blind string flip would therefore have re-inverted those 28.2 M rows. Instead the correct
  tag is recomputed from vn_GEND_bucket / vn_BKGN_bucket and substituted, which is
  IDEMPOTENT: running this twice is the same as running it once -- which is also why this
  file is safe to re-run now that the whole corpus is already correct.

ONLY three clauses may change. The caption is split on "; ", the GEND token is replaced
inside clause 0, the BKGN token inside the recording clause, and the "reads as" clause is
replaced wholesale. Every other clause is carried across byte-identical and that is
asserted per shard, so delivery, timbre, speech, affect, style, recording quality, the
explicit flag, burst handling, genuineness, blend, duration and language cannot move.
"""
import glob, json, os, re, socket, sys, traceback
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

NB = "/e/data1/datasets/playground/mmlaion/schuhmann1/dramabox"
CAPNORM = f"{NB}/emonorm/out/capnorm.npz"

NAME_RANK = None
U_FLOOR = 0.90
TOP_N = 3
NBIN = 4096
NONE_CLAUSE = "no dominant emotion"
V1COL = "caption_general_v1"

# corrected ladders, identical to caption2.py md5 ec55b223 (low bucket -> feminine / noisy)
GEND = ["strongly feminine", "feminine", "somewhat feminine", "androgynous",
        "somewhat masculine", "masculine", "strongly masculine"]
BKGN = ["very noisy background", "noisy background", "some background noise",
        "quiet background", "no background noise"]

# every token either ladder can have produced, longest first so "very noisy background"
# is matched before "noisy background".
_G_ALL = sorted(set(GEND), key=len, reverse=True)
_B_ALL = sorted(set(BKGN), key=len, reverse=True)
G_RE = re.compile(r"\b(" + "|".join(map(re.escape, _G_ALL)) + r")\b")
B_RE = re.compile(r"\b(" + "|".join(map(re.escape, _B_ALL)) + r")\b")
READS_RE = re.compile(r"^reads as\b", re.I)
EXPL_TAGS = {"clean content", "mildly explicit content", "explicit content"}
RCQL_TAGS = ["very poor recording", "poor recording", "below-average recording",
             "average recording", "good recording", "very good recording",
             "studio-grade recording"]
RCQL_RE = re.compile(r"\b(" + "|".join(map(re.escape,
                     sorted(RCQL_TAGS, key=len, reverse=True))) + r")\b")


def pretty(e):
    return e[4:].replace("_", " ").replace("/", " or ").lower()


# Alphabetical rank of each emotion's DISPLAY name, in capnorm field order. Used only to
# break genuine exact ties, deterministically and independently of input order.
def _name_rank(fields):
    names = [pretty(f) for f in fields]
    order = sorted(range(len(names)), key=lambda i: names[i])
    rank = np.empty(len(names), np.int64)
    for r, i in enumerate(order):
        rank[i] = r
    return rank


class Norm:
    """Pooled tie-aware mid-rank ECDF, loaded from capnorm.npz. Not re-fitted."""

    def __init__(self, path=CAPNORM):
        z = np.load(path, allow_pickle=True)
        self.fields = [str(x) for x in z["fields"]]
        h = z["hist"].astype(np.float64)
        n = np.maximum(h.sum(1, keepdims=True), 1.0)
        below = np.cumsum(h, axis=1) - h
        # float64, NOT float32. Casting the mid-rank table to float32 collapses
        # genuinely different percentiles onto one value: emo_Relief 0.99780922730421640
        # and emo_Contentment 0.99780920848369492 both become 0.99780923128128052, so the
        # renderer saw a tie that does not exist and resolved it arbitrarily. Measured
        # cost of that artefact: 10 disagreements with the templates in 361,277 rows, two
        # of which changed WHICH emotion took the third slot. float64 also matches
        # capgate.py and caption_render.py, which never cast.
        self.tab = (below + 0.5 * h) / n
        self.lo = z["lo"].astype(np.float64)
        self.hi = z["hi"].astype(np.float64)
        self.n = int(z["n"][0])
        self.w = (self.hi - self.lo) / NBIN
        global NAME_RANK
        NAME_RANK = _name_rank(self.fields)

    def u(self, X):
        k = np.floor((np.asarray(X, np.float64) - self.lo) / self.w) + 1.0
        np.clip(k, 0, NBIN + 1, out=k)
        k = k.astype(np.int32)
        Y = np.empty(k.shape, np.float64)
        for d in range(k.shape[1]):
            Y[:, d] = self.tab[d][k[:, d]]
        return Y


def split_clauses(cap):
    """'a; b; c.' -> (['a','b','c'], True)   trailing-dot flag preserved."""
    s = cap.rstrip()
    dot = s.endswith(".")
    if dot:
        s = s[:-1]
    return [c.strip() for c in s.split(";")], dot


def join_clauses(parts, dot):
    return "; ".join(parts) + ("." if dot else "")


def fix_one(cap, gb, bb, names, stat):
    """Return the regenerated caption. Only clause 0 (GEND), the recording clause
    (BKGN) and the emotion clause may differ; everything else is carried across."""
    if not cap:
        return cap
    parts, dot = split_clauses(cap)
    if not parts:
        return cap

    # ---- GEND, inside clause 0 only ----
    if gb is not None and gb == gb:                       # not NaN
        want = GEND[min(max(int(gb), 0), 6)]
        m = G_RE.search(parts[0])
        if m:
            if m.group(1) != want:
                stat["gend_changed"] += 1
            parts[0] = parts[0][:m.start()] + want + parts[0][m.end():]
            # the article depends on the first letter of the who-phrase; recompute it.
            # (no ladder term starts with a vowel except "androgynous", which is the
            #  self-symmetric middle bucket, so this is a no-op in practice -- asserted.)
            mm = re.match(r"^(An?) (.+)$", parts[0])
            if mm:
                art = "An" if mm.group(2)[:1].lower() in "aeiou" else "A"
                if art != mm.group(1):
                    stat["article_changed"] += 1
                    parts[0] = f"{art} {mm.group(2)}"

    # ---- BKGN, inside whichever clause carries a background token ----
    if bb is not None and bb == bb:
        want = BKGN[min(max(int(bb), 0), 4)]
        for i, p in enumerate(parts):
            m = B_RE.search(p)
            if m:
                if m.group(1) != want:
                    stat["bkgn_changed"] += 1
                parts[i] = p[:m.start()] + want + p[m.end():]
                break

    # ---- emotion clause ----
    # Always remove any existing emotion clause and re-insert at the CANONICAL
    # position, so the result is independent of whether the old caption happened to
    # carry one. caption2.py emits, in order:
    #   who; delivery; timbre; speech; affect; EMOTION; style; recording; explicit;
    #   bursts; genuineness; blend; tail
    # so the emotion clause belongs immediately before the first of
    # {style, recording, explicit, bursts, genuineness}. An earlier version inserted
    # it just before "genuineness", which put it AFTER the recording and burst
    # clauses on the 12.5 M rows that previously had no emotion clause at all -- same
    # content, wrong slot, and enough to make caption_general disagree with a fresh
    # caption_clausal render. Removing first also makes this idempotent.
    new = ("reads as " + ", ".join(names)) if names else NONE_CLAUSE
    had = [i for i, p in enumerate(parts) if READS_RE.match(p) or p == NONE_CLAUSE]
    prev = parts[had[0]] if had else None
    for i in reversed(had):
        parts.pop(i)

    def _is_anchor(c):
        cl = c.lower()
        if cl.startswith(("style: ", "genuineness", "contains vocal bursts")):
            return True
        if c in EXPL_TAGS:
            return True
        return bool(B_RE.search(c)) or bool(RCQL_RE.search(c))

    pos = next((i for i, c in enumerate(parts) if _is_anchor(c)), len(parts))
    parts.insert(pos, new)
    if prev is None:
        stat["emo_inserted"] += 1
    elif prev != new:
        stat["emo_changed"] += 1
    return join_clauses(parts, dot)


def already_done(path):
    """A shard carrying the v1 column has been through this pass. Cheap metadata read."""
    try:
        return V1COL in pq.ParquetFile(path).schema_arrow.names
    except Exception:
        return False


def process(path, norm, floor=U_FLOOR, top=TOP_N, dry=False, outdir=None, attempts=4):
    """Rewrite one shard, retrying transient filesystem faults. Never raises.

    RETRY EXISTS BECAUSE OF A MEASURED FAULT, not as decoration. On the first
    corpus-wide run (16 nodes x 36 workers = 576 processes creating and renaming
    files inside the same directories) ~11 % of shards failed with the freshly
    written temp file reported missing -- ENOENT from pq.ParquetFile(tmp) or from
    os.replace(tmp, path). The identical workload on ONE node (600 shards, 36
    workers) failed 0 times, so this is cross-node metadata contention on the
    parallel filesystem, not a defect in the shard.

    Two things make it safe to simply retry: the temp name is now unique per
    process, so nothing can collide; and every failure happens strictly BEFORE
    os.replace, so the original shard is still the original shard. A shard that
    exhausts its attempts is left untouched and reported, never half-written.
    """
    last = None
    for k in range(attempts):
        st = _process_once(path, norm, floor, top, dry, outdir)
        if st.get("ok") or dry:
            if k:
                st["retries"] = k
            return st
        last = st
        e = st.get("err", "")
        transient = ("No such file or directory" in e or "Failed to open local file" in e
                     or "magic bytes" in e or "File too short" in e
                     or "smaller than the minimum file footer" in e
                     or "Couldn't deserialize thrift" in e)
        if not transient:
            return st
        time.sleep(0.4 * (k + 1) + random.random() * 0.4)
    last["retries"] = attempts
    return last


def _process_once(path, norm, floor=U_FLOOR, top=TOP_N, dry=False, outdir=None):
    """Rewrite one shard. Returns a stats dict. Never raises."""
    st = dict(path=path, ok=0, rows=0, rows_after=0, uid_n=0, uid_uniq=0,
              gend_changed=0, bkgn_changed=0, emo_changed=0, emo_inserted=0,
              article_changed=0, none=0, named=0, err="", had_v1=0,
              emo_hist={}, emo_count={}, before_count={}, before_hist={},
              before_none=0, bytes_before=0, bytes_after=0, other_clause_moved=0)
    tmp = None
    try:
        # ONE authoritative read. Previously the schema came from a separate
        # pq.ParquetFile(path) open and the data from pq.read_table(path); a
        # concurrent job replacing the file between those two reads made
        # `names_in` describe the OLD file while `tab` was the NEW one, so the
        # code appended caption_general_v1 to a table that already had it. That
        # produced 22 shards with a duplicated column. Reading the schema off the
        # very table being transformed makes the race impossible.
        # ParquetFile.read(), NOT pq.read_table(): read_table goes through the
        # pyarrow.dataset layer, which resolves columns by FieldRef.Name and dies
        # with "Multiple matches for FieldRef.Name(caption_general_v1)" on exactly
        # the duplicated-column shards this function is meant to self-heal. The
        # file-level reader has no such name resolution and reads duplicates fine.
        tab = pq.ParquetFile(path).read()
        names_in = list(tab.schema.names)
        st["rows"] = tab.num_rows
        n = tab.num_rows
        if "caption_general" not in names_in:
            st["err"] = "no caption_general"
            return st
        # self-heal any shard already damaged by that race: keep the FIRST
        # caption_general_v1 (the true original caption) and drop the later one
        # (which holds an already-rewritten caption and is not a baseline).
        while names_in.count(V1COL) > 1:
            last = len(names_in) - 1 - names_in[::-1].index(V1COL)
            tab = tab.remove_column(last)
            names_in = list(tab.schema.names)
            st["dup_v1_dropped"] = st.get("dup_v1_dropped", 0) + 1

        # ---- pre-checks ----
        if "uid" in names_in:
            uid = tab.column("uid").to_pylist()
            st["uid_n"] = len(uid)
            st["uid_uniq"] = len(set(uid))

        cap = tab.column("caption_general").to_pylist()
        st["had_v1"] = int(V1COL in names_in)

        gb = tab.column("vn_GEND_bucket").to_pylist() if "vn_GEND_bucket" in names_in else [None] * n
        bb = tab.column("vn_BKGN_bucket").to_pylist() if "vn_BKGN_bucket" in names_in else [None] * n

        # ---- emotion percentiles ----
        X = np.empty((n, len(norm.fields)), np.float64)
        for j, f in enumerate(norm.fields):
            if f in names_in:
                col = tab.column(f).to_numpy(zero_copy_only=False).astype(np.float64)
            else:
                col = np.zeros(n)
            X[:, j] = np.nan_to_num(col, nan=0.0, posinf=0.0, neginf=0.0)
        U = norm.u(X)
        # EXPLICIT tie-break: descending percentile, then ASCENDING EMOTION NAME.
        # Not merely a stable sort -- a stable sort preserves *input* order, which a
        # consumer of the corpus cannot see or reason about. Ordering genuine ties by
        # display name is a rule anyone can reproduce from the caption alone, and it is
        # the same rule caption_render.py and capgate.py now use, so the column and the
        # 16 templates cannot disagree. np.lexsort takes the LAST key as primary.
        order = np.lexsort((NAME_RANK[None, :].repeat(U.shape[0], 0), -U), axis=1)[:, :top]

        # ---- what the OLD caption named, for the before/after report ----
        # If v1 already exists this shard was rewritten by an earlier (cancelled) run, so
        # the TRUE baseline is v1, not the current caption_general. Reading the wrong one
        # would make the before/after report describe the fix against itself.
        base = (tab.column(V1COL).to_pylist() if V1COL in names_in else cap)
        bcount, bhist = {}, {}
        for c in base:
            if not c:
                continue
            names_old = []
            for p in split_clauses(c)[0]:
                if READS_RE.match(p):
                    names_old = [x.strip() for x in p[len("reads as"):].split(",") if x.strip()]
                    break
            bhist[len(names_old)] = bhist.get(len(names_old), 0) + 1
            if not names_old:
                st["before_none"] += 1
            for x in names_old:
                bcount[x] = bcount.get(x, 0) + 1
        st["before_count"] = bcount
        st["before_hist"] = bhist

        newcap = []
        ecount = {}
        ehist = {}
        for i in range(n):
            sel = [norm.fields[j] for j in order[i] if U[i, j] >= floor]
            nm = [pretty(e) for e in sel]
            ehist[len(nm)] = ehist.get(len(nm), 0) + 1
            if nm:
                st["named"] += 1
                for x in nm:
                    ecount[x] = ecount.get(x, 0) + 1
            else:
                st["none"] += 1
            newcap.append(fix_one(cap[i], gb[i], bb[i], nm, st))
        st["emo_count"] = ecount
        st["emo_hist"] = ehist

        # ---- requirement 4: assert nothing else moved ----
        moved = 0
        for o, nw in zip(cap, newcap):
            if not o or not nw:
                continue
            po, _ = split_clauses(o)
            pn, _ = split_clauses(nw)
            # drop the emotion / none clause from both sides, then the remaining
            # clause lists must differ only where GEND/BKGN tokens live
            fo = [c for c in po if not READS_RE.match(c) and c != NONE_CLAUSE]
            fn = [c for c in pn if not READS_RE.match(c) and c != NONE_CLAUSE]
            if len(fo) != len(fn):
                moved += 1
                continue
            for a, b in zip(fo, fn):
                if a == b:
                    continue
                if G_RE.sub("", a) == G_RE.sub("", b) or B_RE.sub("", a) == B_RE.sub("", b):
                    continue
                moved += 1
                break
        st["other_clause_moved"] = moved

        if dry:
            st["ok"] = 1
            st["rows_after"] = n
            st["_sample"] = [(cap[i], newcap[i]) for i in range(min(3, n))]
            return st

        # ---- write ----
        if V1COL in names_in:
            # already preserved on an earlier run: keep the ORIGINAL v1, do not overwrite
            tab = tab.set_column(names_in.index("caption_general"), "caption_general",
                                 pa.array(newcap, pa.string()))
        else:
            tab = tab.set_column(names_in.index("caption_general"), "caption_general",
                                 pa.array(newcap, pa.string()))
            tab = tab.append_column(V1COL, pa.array(cap, pa.string()))

        st["bytes_before"] = os.path.getsize(path)
        # UNIQUE tmp name. Two array jobs were once launched against the same shard list
        # (1460437 by a sibling agent, 1460453 by me) and a shared "<path>.tmp-capfix"
        # means two processes truncating the SAME file while each verifies it. The
        # transform is deterministic so the output would agree, but a half-written file
        # must never be a candidate for os.replace. Unique per process + a re-check that
        # the source has not changed under us makes concurrent runs merely wasteful.
        uniq = f"{os.getpid()}-{socket.gethostname()}-{os.urandom(4).hex()}"
        tmp = ((outdir + "/" + os.path.basename(path)) if outdir
               else f"{path}.tmp-capfix-{uniq}")
        os.makedirs(os.path.dirname(tmp), exist_ok=True)
        pq.write_table(tab, tmp, compression="zstd", compression_level=7,
                       use_dictionary=True, version="2.6")

        # ---- verify BEFORE replacing ----
        chk = pq.ParquetFile(tmp)
        st["rows_after"] = chk.metadata.num_rows
        if st["rows_after"] != st["rows"]:
            os.remove(tmp)
            st["err"] = f"row count {st['rows']} -> {st['rows_after']}"
            return st
        if "uid" in names_in:
            u2 = pq.read_table(tmp, columns=["uid"]).column("uid").to_pylist()
            if len(u2) != st["uid_n"] or len(set(u2)) != st["uid_uniq"]:
                os.remove(tmp)
                st["err"] = "uid check failed"
                return st
        if V1COL not in pq.ParquetFile(tmp).schema_arrow.names:
            os.remove(tmp)
            st["err"] = "v1 column missing after write"
            return st

        st["bytes_after"] = os.path.getsize(tmp)
        if not outdir:
            os.replace(tmp, path)     # atomic; original stays intact until this instant
        st["ok"] = 1
        return st
    except Exception as e:
        st["err"] = f"{type(e).__name__}: {e}"
        st["tb"] = traceback.format_exc()[-800:]
        try:
            if not outdir:
                for junk in glob.glob(path + ".tmp-capfix.*"):
                    os.remove(junk)
        except Exception:
            pass
        return st
    finally:
        # never leave a stale unique tmp behind if anything above bailed out
        try:
            if (not outdir) and tmp and os.path.exists(tmp):
                os.remove(tmp)
        except Exception:
            pass