#!/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".*?", "", 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()