File size: 11,715 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
#!/usr/bin/env python3
"""EgoLongQA-style MCQ annotation with LOCAL vision + a remote text orchestrator.

Cost model (this is the whole point): vision is ~70% of the spend when it runs on OpenRouter
(a 100-frame describe call is ~43k prompt tokens). Serving the vision model locally on a Blackwell
GPU via vLLM NVFP4 drops that to zero and leaves only the cheap text calls:

    per video   OpenRouter-only  ~$0.033      local vision  ~$0.010

Split, following the EgoProactive agent's ANNOTATION_GUIDE:
  * VISION  -> local vLLM (nvidia/Qwen3.6-27B-NVFP4). Frames go as `image_url` data-URIs; this
    model is image-only, so `video_url` would fail. No R2 staging needed either.
  * TEXT    -> OpenRouter (deepseek-v4-flash-0731) for question generation and the blind attack.

Reuses the staged prompt in scripts/egolongqa_annotation_prompt.txt and the structural gate from
annotate_v2.py, so questions face the same defect filters that took v3 to a clean audit.

Usage:
  python scripts/annotate_local_vision.py --frames ~/egoconv/frames --out annot_local.jsonl \
      --vision-url http://localhost:8000/v1 --limit 5
"""
import argparse, asyncio, base64, collections, io, json, os, re, sys, time
from pathlib import Path

import aiohttp

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from annotate_v2_gate import structural_issues, parse_questions  # noqa: E402

PROMPT = (Path(__file__).parent / "egolongqa_annotation_prompt.txt").read_text()

# One call cannot do both jobs: a thorough ledger (196 entries on the first test video) eats the
# token budget before stage 4, so the questions get truncated away -- 4 of 6 videos returned no
# parseable questions. Split it, the way the proven v2/v3 pipeline does: vision builds the ledger,
# a cheap text model turns the ledger into questions.
LEDGER_PROMPT = PROMPT.split("STAGE 3")[0] + """
================================================================================
OUTPUT
================================================================================
Return ONLY this JSON, no prose, no markdown fences:
{"ledger": ["[0-45s] fact", "[45-90s] fact", "..."]}
Do NOT write questions. The ledger is the entire deliverable for this call.
"""

QGEN_PROMPT = ("You write EgoLongQA multiple-choice questions from a timestamped evidence ledger of a "
               "long egocentric video. You did not see the video; the ledger is all you have, so use "
               "ONLY facts in it and never invent.\n\n" + "STAGE 3" + PROMPT.split("STAGE 3", 1)[1])

BLIND_SYS = ('Answer each numbered multiple-choice question. Reply with ONLY JSON mapping question '
             'number to letter, e.g. {"1":"A","2":"C"}. Answer every question; guess if unsure.')


def frame_data_uri(path, max_side=768, quality=72):
    """vLLM takes data URIs directly — no object store, no presigned URLs, no cleanup."""
    from PIL import Image
    im = Image.open(path).convert("RGB")
    if max(im.size) > max_side:
        im.thumbnail((max_side, max_side))
    b = io.BytesIO(); im.save(b, "JPEG", quality=quality)
    return "data:image/jpeg;base64," + base64.b64encode(b.getvalue()).decode()


async def call(session, url, key, model, messages, max_tokens, temperature=0.4,
               resp_format=None, retries=3, timeout=1800):
    body = {"model": model, "messages": messages, "max_tokens": max_tokens,
            "temperature": temperature}
    if resp_format:
        body["response_format"] = resp_format
    hdr = {"Content-Type": "application/json"}
    if key:
        hdr["Authorization"] = f"Bearer {key}"
    for attempt in range(retries):
        try:
            async with session.post(f"{url}/chat/completions", headers=hdr, json=body,
                                    timeout=aiohttp.ClientTimeout(total=timeout)) 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()
                ch = d.get("choices") or []
                if not ch:
                    if attempt == retries - 1:
                        return ""
                    await asyncio.sleep(4 * (attempt + 1)); continue
                txt = (ch[0].get("message") or {}).get("content") or ""
                # Qwen3.6 is a reasoning model: strip the think block before any JSON parsing
                return re.sub(r"<think>.*?</think>", "", txt, flags=re.S).strip()
        except (aiohttp.ClientError, asyncio.TimeoutError):
            if attempt == retries - 1:
                return ""
            await asyncio.sleep(4 * (attempt + 1))
    return ""


async def annotate_one(sess, vid, a, stats, out_f, lock):
    man = Path(a.frames) / vid / "frames.json"
    if not man.exists():
        stats["no_frames"] += 1; return
    paths = json.load(open(man))
    step = max(1, len(paths) // a.num_frames)
    sel = paths[::step][:a.num_frames]
    t0 = time.time()
    imgs = await asyncio.gather(*[asyncio.to_thread(frame_data_uri, p, a.max_side) for p in sel])
    content = [{"type": "image_url", "image_url": {"url": u}} for u in imgs]
    content.append({"type": "text", "text": LEDGER_PROMPT +
                    f"\n\nThis video is {a.duration_hint or 'about 10 minutes'} long and you are "
                    f"given {len(sel)} frames spanning ALL of it."})

    txt = await call(sess, a.vision_url, a.vision_key, a.vision_model,
                     [{"role": "user", "content": content}], a.vision_max_tokens, 0.4,
                     resp_format={"type": "json_object"})
    vis_s = time.time() - t0
    try:
        obj = json.loads(txt) if txt.strip().startswith("{") else {}
    except Exception:
        obj = {}
    if not obj:
        m = re.search(r"\{.*\}", txt, re.S)
        try:
            obj = json.loads(m.group(0)) if m else {}
        except Exception:
            obj = {}
    if not obj.get("questions"):
        # truncated output: pull whole question objects out of a half-finished array
        qs_r = []
        for mm in re.finditer(r'\{[^{}]*"question"\s*:.*?\}(?=\s*[,\]])', txt, re.S):
            try:
                qs_r.append(json.loads(mm.group(0)))
            except Exception:
                pass
        if qs_r:
            obj = {"ledger": obj.get("ledger") or re.findall(r'"(\[\d+-\d+s\][^"]{10,})"', txt),
                   "questions": qs_r}
    ledger = obj.get("ledger") or []
    if len(ledger) < 8:
        stats["thin_ledger"] += 1; return
    ledger_text = "\n".join(map(str, ledger))

    # stage 2: a text model turns the ledger into questions (cheap, and no token contention)
    qtxt = await call(sess, a.text_url, a.text_key, a.text_model,
                      [{"role": "system", "content": QGEN_PROMPT},
                       {"role": "user", "content": f"EVIDENCE LEDGER:\n{ledger_text}\n\n"
                                                   f"Write {a.n_questions} questions as JSON."}],
                      a.qgen_max_tokens, 0.85, resp_format={"type": "json_object"})
    qs = parse_questions(qtxt)
    if not qs:
        stats["no_questions"] += 1; return
    clean, rejected = [], []
    for q in qs:
        iss = structural_issues(q, ledger_text)
        (rejected if iss else clean).append(q)
        for i in iss:
            stats["struct_" + i] += 1
    if not clean:
        stats["all_struct_rejected"] += 1; return

    # blind attack: a text-only model must NOT be able to solve these
    numbered = "\n\n".join(f"{i+1}. {q['question']}\n" + "\n".join(q["options"])
                           for i, q in enumerate(clean))
    btxt = await call(sess, a.text_url, a.text_key, a.text_model,
                      [{"role": "system", "content": BLIND_SYS},
                       {"role": "user", "content": numbered}],
                      a.blind_max_tokens, 0.0, resp_format={"type": "json_object"})
    picks = {}
    try:
        picks = {int(re.search(r'\d+', k).group()): re.search(r'[A-D]', str(v).upper()).group()
                 for k, v in json.loads(re.search(r"\{.*\}", btxt, re.S).group(0)).items()
                 if re.search(r'\d+', k) and re.search(r'[A-D]', str(v).upper())}
    except Exception:
        pass
    kept = []
    for i, q in enumerate(clean, 1):
        if picks.get(i) == str(q["answer"]).upper()[:1]:
            stats["blind_solved"] += 1
        else:
            kept.append(q)
    if not kept:
        stats["all_leaked"] += 1; return

    rec = {"video_id": vid, "ledger": ledger, "questions": kept,
           "n_frames": len(sel), "rejected_struct": len(rejected),
           "vision_seconds": round(vis_s, 1),
           "models": {"vision": a.vision_model, "text": a.text_model}}
    async with lock:
        out_f.write(json.dumps(rec) + "\n"); out_f.flush()
    stats["videos"] += 1; stats["questions"] += len(kept)
    print(f"  [{stats['videos']}] {vid[:12]} kept={stats['questions']} "
          f"struct_rej={sum(v for k,v in stats.items() if k.startswith('struct_'))} "
          f"blind={stats['blind_solved']} vis={vis_s:.0f}s", flush=True)


async def main_async(a):
    if not a.text_key:
        for line in open(Path(__file__).resolve().parents[1] / ".env"):
            if line.startswith("LLM_API_KEY"):
                a.text_key = line.split("=", 1)[1].strip()
    vids = a.videos or sorted(p.name for p in Path(a.frames).iterdir() if p.is_dir())
    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]
    if a.limit:
        vids = vids[:a.limit]
    print(f"annotating {len(vids)} videos | vision={a.vision_model}@{a.vision_url} "
          f"| text={a.text_model}")
    stats = collections.Counter()
    sem = asyncio.Semaphore(a.concurrency); lock = asyncio.Lock()

    async def guarded(s, v):
        async with sem:
            try:
                await annotate_one(s, v, a, stats, f, lock)
            except Exception as e:
                stats["err"] += 1; stats["last_err"] = 0
                print(f"  ERR {v[:12]}: {type(e).__name__}: {str(e)[:120]}", flush=True)

    with open(a.out, "a") as f:
        async with aiohttp.ClientSession() as s:
            await asyncio.gather(*[guarded(s, v) for v in vids])
    print("DONE", dict(stats))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--videos", nargs="*")
    ap.add_argument("--vision-url", default="http://localhost:8000/v1")
    ap.add_argument("--vision-model", default="nvidia/Qwen3.6-27B-NVFP4")
    ap.add_argument("--vision-key", default="EMPTY")
    ap.add_argument("--text-url", default="https://openrouter.ai/api/v1")
    ap.add_argument("--text-model", default="deepseek/deepseek-v4-flash-0731")
    ap.add_argument("--text-key", default="")
    ap.add_argument("--n-questions", type=int, default=4)
    ap.add_argument("--num-frames", type=int, default=100)
    ap.add_argument("--max-side", type=int, default=768)
    ap.add_argument("--duration-hint", default="")
    ap.add_argument("--vision-max-tokens", type=int, default=20000,
                    help="reasoning model + a full ledger; too small returns empty content")
    ap.add_argument("--qgen-max-tokens", type=int, default=16000,
                    help="deepseek is a reasoning model; a small budget returns empty content")
    ap.add_argument("--blind-max-tokens", type=int, default=8000)
    ap.add_argument("--concurrency", type=int, default=3)
    ap.add_argument("--limit", type=int, default=0)
    asyncio.run(main_async(ap.parse_args()))


if __name__ == "__main__":
    main()