#!/usr/bin/env python3 """Two-stage synthetic MCQ annotation for egocentric video, in EgoLongQA style. STAGE A (vision): a large VLM watches ~100 uniform frames and writes a DETAILED timestamped description — the same 'overview' shape the junior emits. STAGE B (text) : a strong text LLM turns that description into EgoLongQA-style MCQs: two-hop / temporal, first-person, with distractors drawn from OTHER real moments in the same video (not invented), gold letter balanced. Verification is deliberately NOT done here — see verify_questions.py, which runs the two independent checks (text-only degeneracy filter, and video-grounded correctness) so that a hallucinated description cannot self-confirm. Usage: python scripts/annotate_videos.py --frames qaego4d_data/frames --videos v1 v2 v3 \ --out annot_out.jsonl --n-questions 3 """ import argparse, asyncio, json, os, re, sys, time from pathlib import Path import aiohttp sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from ambient.config import settings OPENROUTER = "https://openrouter.ai/api/v1" DESC_SYS = """You are a video analysis expert. You are given ~100 frames sampled uniformly across an ENTIRE egocentric (first-person) video, in temporal order. Write a DETAILED, TIMESTAMPED description of the whole video. This description is the only record another system will have of this video, so it must be concrete and specific. Requirements: - Group the narrative by approximate timestamp ranges (e.g. "0-45s: ...", "45-120s: ..."). - Name concrete objects, text on signs/labels/screens, prices, colours, people, locations, and actions. - Record the ORDER of events explicitly — what happened before/after what. - Note anything distinctive that a question could later be asked about (a specific product, a sign, a brief interaction, an object the camera-wearer picked up or put down). - Do NOT speculate about things you cannot see. If text is unreadable, say so rather than guessing. Output ONLY the description inside: {description} """ QGEN_SYS = """You write multiple-choice questions about long egocentric (first-person) videos, in the exact style of the EgoLongQA benchmark. You are given a detailed timestamped description of ONE video. Write questions that can be answered ONLY by someone who watched the whole video attentively. STYLE (match this closely — these are real examples): - "After I saw the 'PARKING FOR LIBRARY USE ONLY' sign, I walked through a gate into a garden with engraved bricks. One brick referenced a local music festival; what was the name of that festival?" - "Earlier in the video, I saw two condiment products with prices $8.58 and $9.98 in the same aisle. Later, I reached for one of them. What was the price of the product I interacted with?" - "After I finished sautéing the chopped vegetables, what did I add to the pan, and what had the recipe on my phone instructed me to do with it earlier?" HARD REQUIREMENTS: 1. First person ("I", "my"). The camera-wearer is the narrator. 2. TWO-HOP / TEMPORAL: anchor the question to one moment ("After I ...", "Earlier I ...") and ask about a DIFFERENT moment. The answer must require connecting events across time, not a single glance. 3. Ground every question in facts that are EXPLICITLY present in the description. Never invent details. 4. Exactly 4 options. The three distractors must be drawn from OTHER real moments/objects in the SAME video (things that genuinely appear elsewhere), so they are plausible and cannot be eliminated by common sense. 5. Do NOT make the question answerable from general knowledge or from the option wording alone. 6. Vary which letter is correct across questions. Return ONLY JSON: {"questions": [{"question": "...", "options": ["A. ...","B. ...","C. ...","D. ..."], "answer": "A", "evidence": "the sentence(s) from the description supporting the answer", "timestamps": "e.g. 120-150s and 400-430s"}]}""" async def call(session, model, messages, key, max_tokens, temperature=0.7, resp_format=None): body = {"model": model, "messages": messages, "max_tokens": max_tokens, "temperature": temperature} if resp_format: body["response_format"] = resp_format async with session.post(f"{OPENROUTER}/chat/completions", headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}, json=body) as r: r.raise_for_status() d = await r.json() return (d["choices"][0]["message"].get("content") or ""), d.get("usage", {}) async def annotate_one(session, vid, args, key, sem, out_f, lock, stats): from ambient.utils.s3 import get_s3_client async with sem: man = Path(args.frames) / vid / "frames.json" if not man.exists(): stats["no_frames"] += 1 return paths = json.load(open(man))[:args.num_frames] s3 = get_s3_client(); ts = int(time.time() * 1000) def up(i_p): i, p = i_p k = f"videos/_annot/{vid}_{ts}_{i:03d}.jpg" s3.upload_file(p, k, extra_args={"ContentType": "image/jpeg"}) return s3.get_presigned_url(k, expires_in=7200), k res = await asyncio.gather(*[asyncio.to_thread(up, x) for x in enumerate(paths)]) urls = [u for u, _ in res]; keys = [k for _, k in res] try: # ---- STAGE A: timestamped description from the frames ---- content = [{"type": "image_url", "image_url": {"url": u}} for u in urls] content.append({"type": "text", "text": "Write the timestamped description now."}) txt, u1 = await call(session, args.desc_model, [{"role": "system", "content": DESC_SYS}, {"role": "user", "content": content}], key, args.desc_max_tokens, 0.4) m = re.search(r"\s*(.*?)\s*", txt, re.S | re.I) desc = m.group(1).strip() if m else txt.strip() if len(desc) < 200: stats["bad_desc"] += 1 return # ---- STAGE B: questions grounded in the description ---- qtxt, u2 = await call(session, args.qgen_model, [{"role": "system", "content": QGEN_SYS}, {"role": "user", "content": f"Video description:\n{desc}\n\n" f"Write {args.n_questions} questions as JSON."}], key, args.qgen_max_tokens, 0.8, resp_format={"type": "json_object"}) try: qs = json.loads(qtxt).get("questions", []) except Exception: qs = [] stats["qparse_fail"] += 1 good = [q for q in qs if isinstance(q, dict) and q.get("question") and len(q.get("options") or []) == 4 and str(q.get("answer", "")).upper()[:1] in "ABCD"] if good: rec = {"video_id": vid, "description": desc, "questions": good, "desc_model": args.desc_model, "qgen_model": args.qgen_model, "usage": {"desc": u1, "qgen": u2}} async with lock: out_f.write(json.dumps(rec) + "\n"); out_f.flush() stats["videos"] += 1; stats["questions"] += len(good) except Exception as e: stats["err"] += 1 stats.setdefault("last_err", str(e)[:120]) finally: for k in keys: try: s3.s3.delete_object(Bucket=s3.bucket, Key=k) except Exception: pass stats["done"] += 1 if stats["done"] % 5 == 0: print(f" {stats['done']} videos | {stats['questions']} questions | " f"err={stats['err']}", flush=True) async def main_async(a): key = settings.llm_api_key or os.getenv("LLM_API_KEY") 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 a.resume and Path(a.out).exists(): done = {json.loads(l)["video_id"] for l in open(a.out)} 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) 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("--n-questions", type=int, default=3) ap.add_argument("--num-frames", type=int, default=100) ap.add_argument("--desc-max-tokens", type=int, default=3000) ap.add_argument("--qgen-max-tokens", type=int, default=3000) ap.add_argument("--concurrency", type=int, default=4) ap.add_argument("--timeout", type=int, default=1800) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--resume", action="store_true", default=True) asyncio.run(main_async(ap.parse_args())) if __name__ == "__main__": main()