File size: 32,586 Bytes
371b96b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/usr/bin/env python3
"""EgoLongQA-style synthetic MCQ annotation, v2.

Rebuilt after measuring WHY v1 output was unusable (see reports/annotation-quality-v1.md):
  * v1 questions restated their own answer  -> 9/12 solvable with no video at all
  * v1 options averaged 22 chars vs 67 real -> distractors collapsed into near-synonyms
  * v1 had 0% compound and 0% quoted-literal questions vs 32% / 20% in the real benchmark
  * v1 ran on randomly-drawn Ego4D (57% household manipulation) vs a benchmark that is
    59% travel / sightseeing / shopping

The three structural fixes here:
  1. DESCRIBE FROM THE STUDENT'S OWN FRAMES. The description is built from exactly the frames
     the student will see, and is pushed hard to transcribe visible TEXT verbatim. A question
     grounded in detail the student cannot see trains hallucination.
  2. SPEC-DRIVEN GENERATION. The measured shape of real questions is stated numerically
     (compound rate, option length, quoted-literal rate), not left to taste.
  3. ADVERSARIAL REJECTION IN THE LOOP. Every question is attacked by a text-only model with a
     REAL token budget. Anything it solves is thrown out and regenerated -- not merely counted.

Usage:
  python scripts/annotate_v2.py --frames good_frames --out annot_v2.jsonl --n-questions 4
"""
import argparse, asyncio, collections, json, os, re, sys, time
from pathlib import Path

import aiohttp

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

# Frames are staged on Cloudflare R2, which only accepts region "auto". A stray AWS_DEFAULT_REGION
# or ~/.aws/config left over from an Ego4D pull (region = us-west-1) makes every upload fail with
# InvalidRegionName, so pin it here rather than depending on the caller's environment.
os.environ["AWS_DEFAULT_REGION"] = "auto"

OPENROUTER = "https://openrouter.ai/api/v1"

# ---------------------------------------------------------------- stage A: describe

DESC_SYS = """You are analysing frames sampled uniformly across an ENTIRE egocentric (first-person)
video, in temporal order. These are the ONLY frames anyone downstream will ever see.

Write a DETAILED, TIMESTAMPED description grouped by time ranges (e.g. "0-45s: ...", "45-120s: ...").

Priorities, in order:
1. TRANSCRIBE VISIBLE TEXT VERBATIM, in quotes. Street signs, shop names, product labels, prices,
   book titles, screens, posters, notices, number plates, menus, packaging. This is the single most
   valuable thing you can record. Write "the sign read 'PARKING FOR LIBRARY USE ONLY'", not
   "a sign". If text is partially legible, transcribe what you can and mark the rest [unclear].
   If you cannot read it at all, say so -- NEVER invent text.
2. Name concrete objects with distinguishing attributes: colour, brand, size, material, condition.
3. Record PLACES and TRANSITIONS: entering/leaving shops, streets, rooms, vehicles.
4. Record the ORDER of events explicitly, and anything the camera-wearer picked up, put down,
   paid for, read, or interacted with.

Do not speculate about what is off-frame. Output ONLY:
<video_description>
{description}
</video_description>"""

# ---------------------------------------------------------------- stage B: generate

QGEN_SYS = """You write multiple-choice questions about long egocentric (first-person) videos, matching
the EgoLongQA benchmark. Real examples:

- "What did the historical marker I read at the entrance say about the 'wooden' railings I later saw
   on the stone bridge?"
- "I first interacted with a product that had a 'Scratch for Scent' sticker and later with a product
   that had a '$2.50 back' sticker. What were these products?"
- "What was the name on the first sign I saw after stepping onto the sidewalk, and what speed limit
   was indicated on the last sign I saw before stepping off the sidewalk?"

MEASURED SHAPE OF REAL QUESTIONS -- match these rates:
- 89% use a temporal anchor (After I .../Earlier I .../before .../the first .../the last ...)
- 32% are COMPOUND: they ask for TWO linked facts in one question ("what X, and what Y?")
- 20% quote LITERAL TEXT read from the world ('Scratch for Scent', '$2.50 back')
- question length ~146 characters
- OPTION LENGTH ~67 CHARACTERS -- full descriptive phrases, never one or two words

HARD REQUIREMENTS
1. First person ("I", "my").
2. TWO-HOP: the anchor moment and the asked-about moment must be in DIFFERENT, well-separated time
   ranges. Answering must require connecting them.
3. THE QUESTION MUST NOT CONTAIN, PARAPHRASE, OR HINT AT THE CORRECT OPTION'S CONTENT.
   Fatal failure: "Later I carried a piece of wood to the oven. What was I carrying?" -> "The wood".
   The anchor clause may reference a DIFFERENT moment than the one being asked about; it may never
   name the answer.
4. Exactly 4 options, each a full descriptive phrase of ~67 characters. All four must be the SAME
   KIND of thing and similar length. Distractors must be OTHER REAL details from the SAME video --
   never invented, never near-synonyms of the answer ("the wood"/"the plank" is a fatal pair).
5. Use ONLY facts explicitly present in the material. Never invent.
6. Make roughly one in three questions compound (two linked facts).
7. Where the material contains quoted literal text, prefer building questions on it.
8. Vary which letter is correct.

9. NEVER reuse the same component across options. In a COMPOUND question each slot must take at
   least THREE distinct values across the four options. This is fatal and common:
       A. sign read FORTY and second sign read EIGHT
       B. sign read EIGHT and second sign read FORTY
       C. sign read FORTY and second sign read FORTY
       D. sign read EIGHT and second sign read EIGHT
   -- only two values exist, so it is a coin flip, not a 4-way choice. Equally fatal is a pair
   differing by a synonym ("a minivan was waiting" vs "a van was waiting"). Every option must be
   distinguishable by someone who watched, and no two may describe the same thing.

COMMON WAYS QUESTIONS LEAK THEIR ANSWER -- check for all of these before emitting:
- the answer's distinctive noun appears in the question itself
- only one option is the right TYPE of thing (the others are a different category)
- one option is conspicuously longer, more specific, or more plausible than the rest
- three options are obviously absurd, leaving the answer by elimination
- two options are near-synonyms, so neither can be correct and the field narrows to two

BEFORE YOU EMIT, apply this test to every question: could someone who never saw the video pick the
right option using ONLY the question and the four options? If yes, the question is worthless --
rewrite it so the answer is recoverable only from having watched.

Return ONLY JSON:
{"questions":[{"question":"...","options":["A. ...","B. ...","C. ...","D. ..."],
"answer":"A","evidence":"supporting text from the material","timestamps":"e.g. 120-150s and 400-430s"}]}"""

REGEN_SYS = QGEN_SYS + """

You are being called again because the questions below were SOLVED BY A TEXT-ONLY MODEL that never
saw the video. They leak their answers. Diagnose the leak in each and write REPLACEMENTS that do not.
Common leaks: the answer's noun appears in the question; only one option is the right TYPE of thing;
one option is conspicuously more detailed or more plausible than the rest."""

ANSWER_SYS = "Answer the multiple-choice question. Reply with ONLY the single letter A, B, C or D."

# ------------------------------------------------- "activity" style (low-signage footage)
#
# Measured on the real benchmark: "Daily Activities" is its LARGEST category (127/700 = 18%) and
# only 9% of those questions involve signage, 12% anything outdoors. Together with Hobbies,
# Gardening and Pets that is ~31% of EgoLongQA built on indoor household video -- the cooking /
# cleaning / crafting footage that the signage-oriented prompt handles badly. Real examples:
#   "Which ingredient that I retrieved from the refrigerator did I chop and add to the pan with
#    ground meat before using the last of the tomatoes?"
#   "Why did I open the refrigerator near the end of the video, and what earlier activity
#    prompted this?"
# So the lever on this footage is ORDER, CAUSE and OBJECT STATE, not text on signs.

DESC_SYS_ACTIVITY = """You are analysing frames sampled uniformly across an ENTIRE egocentric
(first-person) video, in temporal order. These are the ONLY frames anyone downstream will ever see.

Write a DETAILED, TIMESTAMPED description grouped by time ranges (e.g. "0-45s: ...", "45-120s: ...").

This is a hands-on activity video. Priorities, in order:
1. THE ORDER OF OPERATIONS. What was done, in what sequence, and what had to happen first. Be
   explicit about before/after: "the onions were already chopped when the pan was heated".
2. OBJECT STATE CHANGES. Track individual objects across the video: raw -> chopped -> cooked,
   empty -> filled, dirty -> clean, unassembled -> assembled, closed -> open. Say WHEN each
   change happened and what caused it.
3. TOOLS, INGREDIENTS AND CONTAINERS, named with distinguishing attributes (colour, size, material),
   and where each came from and went: fridge, drawer, shelf, sink, bin.
4. CAUSE AND PURPOSE. Why an action was taken, when the frames make it evident (fetched a cloth
   because something spilled; re-opened the fridge because an ingredient was missed).
5. Any visible text (labels, packaging, screens) transcribed verbatim in quotes -- useful when
   present, but do NOT force it; this footage often has none.

Do not speculate about what is off-frame. Output ONLY:
<video_description>
{description}
</video_description>"""

QGEN_SYS_ACTIVITY = """You write multiple-choice questions about long egocentric (first-person)
videos, matching the "Daily Activities" category of the EgoLongQA benchmark. Real examples:

- "Which ingredient that I retrieved from the refrigerator did I chop and add to the pan with ground
   meat before using the last of the tomatoes?"
- "Why did I open the refrigerator near the end of the video, and what earlier activity prompted this?"
- "Which did I paint first, the house's exterior siding or the adjacent wooden fence, and what visual
   evidence indicates the order?"

This footage is INDOOR HANDS-ON ACTIVITY. It usually has no signs or prices, so do NOT build
questions on text. Build them on ORDER, CAUSE and OBJECT STATE.

GOOD QUESTION TYPES for this material:
- ORDERING: which of two things was done first, and what shows it
- CAUSAL: why an action was taken, linked to an earlier event that prompted it
- OBJECT TRACKING: an object is used early and again much later -- what happened to it in between,
  or what state it was in the second time
- OMISSION / COMPLETION: what remained undone, or what was fetched only after being forgotten

MEASURED SHAPE -- match these rates:
- 89% use a temporal anchor (After I .../Earlier I .../before .../the first .../the last ...)
- 32% are COMPOUND: two linked facts in one question ("what X, and what Y?")
- question length ~146 characters
- OPTION LENGTH ~67 CHARACTERS -- full descriptive phrases, never one or two words

HARD REQUIREMENTS
1. First person ("I", "my").
2. TWO-HOP: the anchor moment and the asked-about moment must be in DIFFERENT, well-separated time
   ranges. Answering must require connecting them.
3. THE QUESTION MUST NOT CONTAIN, PARAPHRASE, OR HINT AT THE CORRECT OPTION'S CONTENT.
   Fatal failure: "Later I carried a piece of wood to the oven. What was I carrying?" -> "The wood".
4. Exactly 4 options, each a full descriptive phrase of ~67 characters, all the SAME KIND of thing
   and similar length. Distractors must be OTHER REAL details from the SAME video -- never invented,
   never near-synonyms of the answer ("the wood"/"the plank" is a fatal pair).
5. Use ONLY facts explicitly present in the material. Never invent.
6. Make roughly one in three questions compound.
7. Vary which letter is correct.

9. NEVER reuse the same component across options. In a COMPOUND question each slot must take at
   least THREE distinct values across the four options. This is fatal and common:
       A. sign read FORTY and second sign read EIGHT
       B. sign read EIGHT and second sign read FORTY
       C. sign read FORTY and second sign read FORTY
       D. sign read EIGHT and second sign read EIGHT
   -- only two values exist, so it is a coin flip, not a 4-way choice. Equally fatal is a pair
   differing by a synonym ("a minivan was waiting" vs "a van was waiting"). Every option must be
   distinguishable by someone who watched, and no two may describe the same thing.

COMMON WAYS QUESTIONS LEAK THEIR ANSWER -- check for all of these before emitting:
- the answer's distinctive noun appears in the question itself
- only one option is the right TYPE of thing
- one option is conspicuously longer, more specific, or more plausible than the rest
- three options are obviously absurd, leaving the answer by elimination
- two options are near-synonyms, narrowing the field to two

BEFORE YOU EMIT, apply this test to every question: could someone who never saw the video pick the
right option using ONLY the question and the four options? If yes, rewrite it.

Return ONLY JSON:
{"questions":[{"question":"...","options":["A. ...","B. ...","C. ...","D. ..."],
"answer":"A","evidence":"supporting text from the material","timestamps":"e.g. 120-150s and 400-430s"}]}"""

REGEN_TAIL = """

You are being called again because the questions below were SOLVED BY A TEXT-ONLY MODEL that never
saw the video. They leak their answers. Diagnose the leak in each and write REPLACEMENTS that do not."""

DURATION_NOTE = """DURATION (critical): the frames you are given span the ENTIRE video, which is {duration_sec:.0f}
SECONDS long -- roughly one frame every {frame_gap:.1f} seconds. Your time ranges MUST cover the full
0 to {duration_sec:.0f}s span. Do NOT compress the video into the first minute: a measured median of
0.28x showed exactly that failure, which makes every citation point at the wrong moment."""

DURATIONS = {}

STYLES = {
    "signage":  (DESC_SYS,          QGEN_SYS),
    "activity": (DESC_SYS_ACTIVITY, QGEN_SYS_ACTIVITY),
}


async def call(session, model, messages, key, max_tokens, temperature=0.7, resp_format=None,
               retries=3):
    body = {"model": model, "messages": messages, "max_tokens": max_tokens,
            "temperature": temperature}
    if resp_format:
        body["response_format"] = resp_format
    for attempt in range(retries):
        try:
            async with session.post(f"{OPENROUTER}/chat/completions",
                                    headers={"Authorization": f"Bearer {key}",
                                             "Content-Type": "application/json"},
                                    json=body) as r:
                if r.status in (429, 500, 502, 503):
                    await asyncio.sleep(4 * (attempt + 1))
                    continue
                r.raise_for_status()
                d = await r.json()
                # An upstream error (rate limit, provider fault, content filter) comes back 200
                # with choices absent or null -- indexing it blindly raises TypeError and kills
                # the whole video, so degrade to an empty completion and let the caller retry.
                ch = d.get("choices") or []
                if not ch:
                    if attempt == retries - 1:
                        return "", d.get("usage", {})
                    await asyncio.sleep(4 * (attempt + 1))
                    continue
                return ((ch[0].get("message") or {}).get("content") or ""), d.get("usage", {})
        except (aiohttp.ClientError, asyncio.TimeoutError):
            if attempt == retries - 1:
                raise
            await asyncio.sleep(4 * (attempt + 1))
    return "", {}


def parse_questions(txt):
    """Reasoning models often wrap the JSON in prose or a ```json fence despite response_format,
    and sometimes run out of budget mid-object. Recover what we can instead of dropping the round."""
    if not txt:
        return []
    qs = None
    for cand in (txt,
                 (re.search(r"```(?:json)?\s*(.*?)```", txt, re.S) or [None, None])[1],
                 (re.search(r"\{.*\}", txt, re.S) or [None])[0]):
        if not cand:
            continue
        try:
            obj = json.loads(cand)
            if isinstance(obj, dict):
                qs = obj.get("questions")
            elif isinstance(obj, list):
                qs = obj
            if qs:
                break
        except Exception:
            continue
    if not qs:
        # last resort: pull individual question objects out of a truncated array
        qs = []
        for m in re.finditer(r'\{[^{}]*"question"\s*:.*?\}(?=\s*[,\]])', txt, re.S):
            try:
                qs.append(json.loads(m.group(0)))
            except Exception:
                pass
    if not qs:
        return []
    out = []
    for q in qs:
        if not isinstance(q, dict) or not q.get("question"):
            continue
        opts = q.get("options") or []
        if len(opts) != 4 or str(q.get("answer", "")).upper()[:1] not in "ABCD":
            continue
        out.append(q)
    return out


BATCH_SYS = ("Answer each numbered multiple-choice question independently. "
             'Reply with ONLY JSON mapping question number to letter, e.g. {"1":"A","2":"C"}. '
             "Answer every question; if unsure, still give your best single letter.")


def _numbered(questions):
    return "\n\n".join(f"{i+1}. {q['question']}\n" + "\n".join(q["options"])
                       for i, q in enumerate(questions))


def _parse_letters(txt, n):
    """Return list of picks (or None) for n questions from a JSON map, tolerating fences/prose."""
    picks = [None] * n
    if not txt:
        return picks
    obj = None
    for cand in (txt,
                 (re.search(r"```(?:json)?\s*(.*?)```", txt, re.S) or [None, None])[1],
                 (re.search(r"\{.*\}", txt, re.S) or [None])[0]):
        if not cand:
            continue
        try:
            obj = json.loads(cand)
            break
        except Exception:
            continue
    if isinstance(obj, dict):
        for k, v in obj.items():
            m_i = re.search(r"\d+", str(k)); m_v = re.search(r"[A-D]", str(v).upper())
            if m_i and m_v:
                i = int(m_i.group(0)) - 1
                if 0 <= i < n:
                    picks[i] = m_v.group(0)
    if all(p is None for p in picks):   # fall back to positional letters
        found = re.findall(r"\b([A-D])\b", (txt or "").upper())
        for i, f in enumerate(found[:n]):
            picks[i] = f
    return picks


_WORD = re.compile(r"[a-z0-9']{4,}")
_STOP = set("""that this with from into over under after before then than which what were was
been being have has had will would could should there here they them their your mine ours
first second third fourth i my me the and or of to in on at for a an it its is are be""".split())


def _content(s):
    return {w for w in _WORD.findall(re.sub(r"^\s*[A-D][\.\)]\s*", "", s or "").lower())
            if w not in _STOP}


def structural_issues(q, desc):
    """Shape defects a blind-attack filter does not reliably catch.

    Measured on the first 362 questions: 12% had two near-duplicate options and 5% had a gold
    option whose content never appeared in the description. Compound questions are the main
    offender -- built as a factorial grid over only TWO values per slot, they collapse into a
    2-way guess ("'Luyben Av' + minivan" vs "'Luyben Av' + van")."""
    issues = []
    opts = q.get("options") or []
    gold = str(q.get("answer", "")).upper()[:1]
    if len(opts) != 4 or gold not in "ABCD":
        return ["malformed"]
    bodies = [re.sub(r"^\s*[A-D][\.\)]\s*", "", o).strip() for o in opts]
    sets = [_content(b) for b in bodies]

    for i in range(4):
        for j in range(i + 1, 4):
            if sets[i] and sets[j]:
                jac = len(sets[i] & sets[j]) / len(sets[i] | sets[j])
                if jac > 0.8:
                    issues.append("dup_options")
                    break
        if issues:
            break

    # a compound option set must not reuse the same component across most options
    if len(bodies) == 4:
        counts = collections.Counter()
        for b in bodies:
            for part in re.split(r"\s+and\s+|,\s+", b):
                p = " ".join(sorted(_content(part)))
                if p:
                    counts[p] += 1
        if counts and max(counts.values()) >= 3:
            issues.append("repeated_component")

    gi = "ABCD".index(gold)
    others = [len(b) for k, b in enumerate(bodies) if k != gi]
    if abs(len(bodies[gi]) - (sum(others) / 3)) > 30:
        issues.append("gold_len_outlier")

    dw = _content(desc)
    gw = sets[gi]
    if gw and len(gw - dw) / len(gw) > 0.7:
        issues.append("gold_unsupported_by_desc")
    return issues


async def blind_attack_batch(session, questions, key, model, max_tokens):
    """Can a text-only model solve these with no video? ONE call for all of them.

    Needs a REAL token budget: these are reasoning models, and a small budget returns empty
    content that silently scores as 'not solved' -- the bug that made v1's filter useless.
    Batching means the model sees the whole set at once, which if anything makes it a STRONGER
    adversary (cross-question cues are available to it), so the filter does not get weaker."""
    txt, _ = await call(session, model,
                        [{"role": "system", "content": BATCH_SYS},
                         {"role": "user", "content": _numbered(questions)}],
                        key, max_tokens, 0.0, resp_format={"type": "json_object"})
    picks = _parse_letters(txt, len(questions))
    return [p is not None and p == str(q["answer"]).upper()[:1]
            for p, q in zip(picks, questions)]


async def frame_verify_batch(session, questions, urls, key, model, max_tokens=8000):
    """Are these answerable from the STUDENT's own frames? ONE call carrying the frames once.

    Sending the 100-frame payload per question was ~60% of the pipeline's vision cost for no
    benefit. Caveat: the model now sees all questions together, so verification is marginally
    less independent per question -- acceptable for a gate whose job is to catch questions
    grounded in detail the student cannot see at all."""
    content = [{"type": "image_url", "image_url": {"url": u}} for u in urls]
    content.append({"type": "text", "text": _numbered(questions)})
    txt, _ = await call(session, model,
                        [{"role": "system", "content": BATCH_SYS},
                         {"role": "user", "content": content}],
                        key, max_tokens, 0.0, resp_format={"type": "json_object"})
    picks = _parse_letters(txt, len(questions))
    return [p is not None and p == str(q["answer"]).upper()[:1]
            for p, q in zip(picks, questions)]


async def annotate_one(session, vid, a, key, sem, out_f, lock, stats):
    from ambient.utils.s3 import get_s3_client
    async with sem:
        man = Path(a.frames) / vid / "frames.json"
        if not man.exists():
            stats["no_frames"] += 1
            return
        paths = json.load(open(man))
        # the student sees N uniformly sampled frames; describe from EXACTLY those
        step = max(1, len(paths) // a.num_frames)
        student_paths = paths[::step][:a.num_frames]
        s3 = get_s3_client(); ts = int(time.time() * 1000)

        def up(i_p):
            i, p = i_p
            k = f"videos/_annot2/{vid}_{ts}_{i:03d}.jpg"
            s3.upload_file(p, k, extra_args={"ContentType": "image/jpeg"})
            return s3.get_presigned_url(k, expires_in=10800), k
        res = await asyncio.gather(*[asyncio.to_thread(up, x) for x in enumerate(student_paths)])
        urls = [u for u, _ in res]; keys = [k for _, k in res]

        try:
            # ---- A: description from the student's own frames ----
            content = [{"type": "image_url", "image_url": {"url": u}} for u in urls]
            content.append({"type": "text", "text": "Write the timestamped description now."})
            desc_sys, qgen_sys_base = STYLES[a.style]
            vdur = DURATIONS.get(vid)
            if vdur:
                desc_sys = desc_sys + DURATION_NOTE.format(
                    duration_sec=vdur, frame_gap=vdur / max(1, len(urls)))
            desc, _ = await call(session, a.desc_model,
                                 [{"role": "system", "content": desc_sys},
                                  {"role": "user", "content": content}],
                                 key, a.desc_max_tokens, 0.4)
            m = re.search(r"<video_description>\s*(.*?)\s*</video_description>", desc, re.S | re.I)
            desc = (m.group(1) if m else desc).strip()
            if len(desc) < 300:
                stats["bad_desc"] += 1
                return

            # ---- B/C: generate, attack, regenerate ----
            kept, rejected = [], []
            material = f"Video description (from the {len(urls)} frames the student sees):\n{desc}"
            sys_p, ask = qgen_sys_base, a.n_questions
            for rnd in range(a.max_rounds):
                if ask <= 0:
                    break
                user = f"{material}\n\nWrite {ask} questions as JSON."
                if rnd and rejected:
                    leaked = "\n\n".join(
                        q["question"] + "\n" + "\n".join(q["options"]) for q in rejected[-ask:])
                    user = f"{material}\n\nThese leaked their answers:\n{leaked}\n\n" \
                           f"Write {ask} REPLACEMENT questions as JSON."
                    sys_p = qgen_sys_base + REGEN_TAIL
                txt, _ = await call(session, a.qgen_model,
                                    [{"role": "system", "content": sys_p},
                                     {"role": "user", "content": user}],
                                    key, a.qgen_max_tokens, 0.85,
                                    resp_format={"type": "json_object"})
                qs = parse_questions(txt)
                if not qs:
                    stats["qparse_fail"] += 1
                    continue
                # cheap structural gate first -- no API call needed
                clean = []
                for q in qs:
                    iss = structural_issues(q, desc)
                    if iss:
                        rejected.append(q)
                        for i in iss:
                            stats["struct_" + i] = stats.get("struct_" + i, 0) + 1
                    else:
                        clean.append(q)
                if not clean:
                    ask = a.n_questions - len(kept)
                    continue
                qs = clean
                solved = await blind_attack_batch(session, qs, key, a.blind_model,
                                                  a.blind_max_tokens)
                for q, bad in zip(qs, solved):
                    (rejected if bad else kept).append(q)
                stats["blind_rejected"] += sum(1 for x in solved if x)
                ask = a.n_questions - len(kept)

            if not kept:
                stats["all_leaked"] += 1
                return

            # ---- D: frame-grounded verification ----
            vis = await frame_verify_batch(session, kept, urls, key, a.verify_model)
            final = [q for q, ok in zip(kept, vis) if ok]
            stats["not_visible"] += sum(1 for ok in vis if not ok)
            if not final:
                stats["none_visible"] += 1
                return

            rec = {"video_id": vid, "description": desc, "questions": final,
                   "n_frames_described": len(urls),
                   "rejected_blind": len(rejected),
                   "models": {"desc": a.desc_model, "qgen": a.qgen_model,
                              "blind": a.blind_model, "verify": a.verify_model}}
            async with lock:
                out_f.write(json.dumps(rec) + "\n"); out_f.flush()
            stats["videos"] += 1; stats["questions"] += len(final)
        except Exception as e:
            stats["err"] += 1
            stats["last_err"] = f"{type(e).__name__}: {str(e)[:120]}"
        finally:
            for k in keys:
                try:
                    s3.s3.delete_object(Bucket=s3.bucket, Key=k)
                except Exception:
                    pass
        stats["done"] += 1
        print(f"  [{stats['done']}] {vid[:12]} kept={stats['questions']} "
              f"blind_rej={stats['blind_rejected']} not_vis={stats['not_visible']} "
              f"err={stats['err']}", flush=True)


async def main_async(a):
    key = os.getenv("LLM_API_KEY")
    if not key:
        for line in open(Path(__file__).resolve().parents[1] / ".env"):
            if line.startswith("LLM_API_KEY"):
                key = line.split("=", 1)[1].strip()
    if a.durations:
        DURATIONS.update({k: float(v) for k, v in json.load(open(a.durations)).items()})
        print(f"durations loaded for {len(DURATIONS)} videos")
    vids = a.videos or sorted(p.name for p in Path(a.frames).iterdir() if p.is_dir())
    if a.limit:
        vids = vids[:a.limit]
    done = set()
    if Path(a.out).exists():
        done = {json.loads(l)["video_id"] for l in open(a.out) if l.strip()}
    vids = [v for v in vids if v not in done]
    print(f"annotating {len(vids)} videos | desc={a.desc_model} qgen={a.qgen_model}")
    stats = dict(done=0, videos=0, questions=0, err=0, no_frames=0, bad_desc=0, qparse_fail=0,
                 blind_rejected=0, not_visible=0, all_leaked=0, none_visible=0)
    sem = asyncio.Semaphore(a.concurrency); lock = asyncio.Lock()
    with open(a.out, "a") as f:
        async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=a.timeout)) as s:
            await asyncio.gather(*[annotate_one(s, v, a, key, sem, f, lock, stats) for v in vids])
    print(f"DONE {stats}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", required=True)
    ap.add_argument("--videos", nargs="*", default=None)
    ap.add_argument("--out", required=True)
    ap.add_argument("--desc-model", default="qwen/qwen3.5-122b-a10b")
    ap.add_argument("--qgen-model", default="deepseek/deepseek-v4-flash-0731")
    ap.add_argument("--blind-model", default="deepseek/deepseek-v4-flash-0731")
    ap.add_argument("--verify-model", default="qwen/qwen3.5-27b",
                    help="MUST differ from --desc-model: the describer will happily confirm\n                         a question built on its own misreading. qwen3.6-27b was the\n                         first pick but REASONS: it burned 3000 completion tokens,\n                         hit finish=length, returned nothing, and every question was\n                         silently scored not-visible. qwen3.5-27b answers in ~14\n                         tokens and is 4x cheaper per call.")
    ap.add_argument("--durations", default=None,
                    help="JSON map video_id -> seconds. Without it the VLM guesses the "
                         "timeline and compresses it ~4x, making every citation wrong.")
    ap.add_argument("--style", choices=list(STYLES), default="signage",
                    help="signage = travel/shopping footage (text-rich); "
                         "activity = indoor hands-on footage (order/cause/state). "
                         "EgoLongQA needs BOTH: ~31%% of it is low-signage Daily Activities.")
    ap.add_argument("--n-questions", type=int, default=4)
    ap.add_argument("--num-frames", type=int, default=100)
    ap.add_argument("--max-rounds", type=int, default=3,
                    help="generate -> blind-attack -> regenerate cycles")
    ap.add_argument("--desc-max-tokens", type=int, default=6000)
    ap.add_argument("--qgen-max-tokens", type=int, default=24000,
                    help="reasoning model: too small a budget returns EMPTY content")
    ap.add_argument("--blind-max-tokens", type=int, default=10000,
                    help="MUST be large: at 8 tokens a reasoning model returns None and every "
                         "question silently passes the leak filter (the v1 bug)")
    ap.add_argument("--concurrency", type=int, default=12)
    ap.add_argument("--timeout", type=int, default=3600)
    ap.add_argument("--limit", type=int, default=0)
    asyncio.run(main_async(ap.parse_args()))


if __name__ == "__main__":
    main()