SocialEmbodiedAI / eval.py
qiufuyu123's picture
Upload full dataset
fbff792 verified
Raw History Blame Contribute Delete
26.2 kB
"""
Parallel VQA evaluation using Gemini API (google-genai SDK).
Usage:
set GOOGLE_API_KEY=your_key
python eval.py [--model MODEL] [--workers N] [--rpm N]
Results saved to eval_results.json (supports resume).
"""
import argparse
import json
import os
import re
import signal
import sys
import threading
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]
# ── Dependency check ─────────────────────────────────────────────────
try:
from google import genai
from google.genai import types as genai_types
except ImportError:
print("google-genai SDK not found.")
print("Install: pip install google-genai")
sys.exit(1)
# ── Config ───────────────────────────────────────────────────────────
BASE_DIR = Path(__file__).parent
CLIPS_DIR = BASE_DIR / "clips"
META_FULL = BASE_DIR / "meta_full.json"
RESULTS_FILE = BASE_DIR / "eval_results.json"
DEFAULT_MODEL = "gemini-3.1-pro-preview"
DEFAULT_WORKERS = 6
DEFAULT_RPM = 10
DEFAULT_THINKING_BUDGET = 8192
# ── Rate limiter ─────────────────────────────────────────────────────
class RateLimiter:
"""Simple per-minute rate limiter (thread-safe)."""
def __init__(self, rpm: int):
self._interval = 60.0 / rpm
self._lock = threading.Lock()
self._last = 0.0
def wait(self):
with self._lock:
now = time.monotonic()
gap = self._last + self._interval - now
if gap > 0:
time.sleep(gap)
self._last = time.monotonic()
# ── Helpers ──────────────────────────────────────────────────────────
def build_prompt(question: str, choices: list[str]) -> str:
opts = "\n".join(f"{chr(65 + i)}. {c}" for i, c in enumerate(choices))
return (
"Watch the video clip carefully, then answer the multiple-choice "
"question.\n\n"
f"Question: {question}\n\n"
f"{opts}\n\n"
"Respond with ONLY the letter (A, B, C, or D) of the correct answer."
)
def parse_answer(text: str) -> int:
"""Parse model response -> answer index (0-3), or -1 if unparseable."""
text = text.strip()
if not text:
return -1
# 1) First character is a letter
if text[0].upper() in "ABCD":
return ord(text[0].upper()) - 65
# 2) Pattern like "A." / "A)" / "A:"
m = re.search(r"\b([A-Da-d])[.):\s]", text)
if m:
return ord(m.group(1).upper()) - 65
# 3) Standalone letter
m = re.search(r"\b([A-Da-d])\b", text)
if m:
return ord(m.group(1).upper()) - 65
return -1
# ── Core evaluation ──────────────────────────────────────────────────
SAFETY = [
genai_types.SafetySetting(
category=genai_types.HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=genai_types.HarmBlockThreshold.BLOCK_NONE,
),
genai_types.SafetySetting(
category=genai_types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=genai_types.HarmBlockThreshold.BLOCK_NONE,
),
genai_types.SafetySetting(
category=genai_types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=genai_types.HarmBlockThreshold.BLOCK_NONE,
),
genai_types.SafetySetting(
category=genai_types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=genai_types.HarmBlockThreshold.BLOCK_NONE,
),
]
def _build_item_meta(item: dict, idx: int) -> dict:
"""Extract all metadata fields common to both success and error results."""
tags = item.get("tag", [])
correct = item.get("answer", -1)
choices = item.get("choices", [])
return {
"idx": idx,
# ── identification ──
"task": item.get("task", ""),
"scenario": item.get("scenario", ""),
"source_video": item.get("source_video", ""),
"clip": item.get("clip", ""),
"duration": item.get("duration", []),
"perspective": tags[0] if len(tags) >= 1 else "",
"question_type": tags[1] if len(tags) >= 2 else "",
"tag": tags,
# ── question content ──
"question": item.get("question", ""),
"choices": choices,
# ── ground truth ──
"correct_answer": correct,
"correct_letter": chr(65 + correct) if 0 <= correct < len(choices) else "?",
"correct_text": choices[correct] if 0 <= correct < len(choices) else "",
}
def _extract_thinking_and_response(resp) -> tuple[str, str, str]:
"""Separate thinking/response from a Gemini response.
Returns (thinking, response, diagnosis).
diagnosis is empty on success, otherwise explains the failure.
"""
thinking_parts: list[str] = []
response_parts: list[str] = []
# No candidates at all β†’ blocked before generation
if not resp.candidates:
reason = "no candidates"
if hasattr(resp, "prompt_feedback") and resp.prompt_feedback:
reason += f" | prompt_feedback={resp.prompt_feedback}"
return "", "", reason
cand = resp.candidates[0]
# Candidate exists but finish_reason indicates a block
finish = getattr(cand, "finish_reason", None)
if finish and str(finish) not in ("STOP", "FinishReason.STOP", "1", "MAX_TOKENS",
"FinishReason.MAX_TOKENS", "2"):
safety_ratings = getattr(cand, "safety_ratings", None)
return "", "", f"finish_reason={finish} | safety={safety_ratings}"
# Candidate content might be None
content = getattr(cand, "content", None)
if content is None:
return "", "", "candidate.content is None"
parts = getattr(content, "parts", None)
if not parts:
return "", "", "candidate.content.parts is empty"
for part in parts:
text = getattr(part, "text", None) or ""
if not text:
continue
if hasattr(part, "thought") and part.thought:
thinking_parts.append(text)
else:
response_parts.append(text)
thinking = "\n".join(thinking_parts)
response = "\n".join(response_parts)
if not response.strip():
# Model only produced thinking, no actual answer
return thinking, "", "only thinking returned, no answer part"
return thinking, response, ""
def evaluate_one(
client: genai.Client,
model_name: str,
item: dict,
idx: int,
limiter: RateLimiter,
thinking_budget: int = 0,
max_retries: int = 3,
) -> dict:
"""Upload clip -> generate -> parse -> cleanup. Returns result dict."""
clip_path = BASE_DIR / item["clip"]
prompt = build_prompt(item["question"], item["choices"])
meta = _build_item_meta(item, idx)
meta["prompt"] = prompt # always record what we sent
if not clip_path.exists():
return {**meta, "error": f"clip not found: {clip_path.name}"}
last_err = ""
# Build generation config (with optional thinking)
gen_kwargs: dict = {
"temperature": 0,
"max_output_tokens": 64,
"safety_settings": SAFETY,
}
if thinking_budget > 0:
gen_kwargs["thinking_config"] = genai_types.ThinkingConfig(
thinking_budget=thinking_budget,
)
for attempt in range(max_retries):
uploaded = None
try:
limiter.wait()
# Upload
uploaded = client.files.upload(
file=str(clip_path),
config=genai_types.UploadFileConfig(mime_type="video/mp4"),
)
# Poll until processing completes
for _ in range(60):
if uploaded.state and uploaded.state.name != "PROCESSING":
break
time.sleep(2)
uploaded = client.files.get(name=uploaded.name or "")
if uploaded.state and uploaded.state.name == "FAILED":
last_err = "file processing failed"
continue
# Generate
resp = client.models.generate_content(
model=model_name,
contents=[uploaded, prompt],
config=genai_types.GenerateContentConfig(**gen_kwargs),
)
thinking_text, resp_text, diag = _extract_thinking_and_response(resp)
if diag or not resp_text.strip():
last_err = diag or "empty response"
continue
pred = parse_answer(resp_text)
choices = item.get("choices", [])
valid = 0 <= pred < len(choices)
return {
**meta,
# ── model I/O ──
"thinking": thinking_text,
"response": resp_text.strip(),
# ── model prediction ──
"predicted": pred if valid else -1,
"predicted_letter": chr(65 + pred) if valid else "?",
"predicted_text": choices[pred] if valid else "",
# ── evaluation ──
"is_correct": (pred == item.get("answer", -1)) if valid else False,
"missing": not valid, # True = unparseable / bad format
}
except Exception as e:
last_err = str(e)
if attempt < max_retries - 1:
time.sleep(2 ** attempt * 5)
finally:
if uploaded:
try:
client.files.delete(name=uploaded.name or "")
except Exception:
pass
return {**meta, "error": last_err}
# ── Result I/O ───────────────────────────────────────────────────────
def load_existing() -> dict[int, dict]:
if not RESULTS_FILE.exists():
return {}
with open(RESULTS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
return {r["idx"]: r for r in data.get("items", [])}
def save_results(items: list[dict], model_name: str):
items_sorted = sorted(items, key=lambda x: x["idx"])
errors = [r for r in items_sorted if "error" in r]
missing = [r for r in items_sorted if "error" not in r and r.get("missing")]
scored = [r for r in items_sorted if "error" not in r and not r.get("missing")]
correct = sum(1 for r in scored if r.get("is_correct"))
total_scored = len(scored)
# per-task (only scored items)
per_task: dict[str, dict] = {}
for r in scored:
t = r["task"]
if t not in per_task:
per_task[t] = {"total": 0, "correct": 0, "accuracy": 0.0}
per_task[t]["total"] += 1
if r["is_correct"]:
per_task[t]["correct"] += 1
for v in per_task.values():
v["accuracy"] = round(v["correct"] / v["total"], 4) if v["total"] else 0.0
# per-tag (only scored items)
per_tag: dict[str, dict] = {}
for r in scored:
tags = r.get("tag", [])
if len(tags) >= 2:
tag = tags[1]
if tag not in per_tag:
per_tag[tag] = {"total": 0, "correct": 0, "accuracy": 0.0}
per_tag[tag]["total"] += 1
if r["is_correct"]:
per_tag[tag]["correct"] += 1
for v in per_tag.values():
v["accuracy"] = round(v["correct"] / v["total"], 4) if v["total"] else 0.0
output = {
"model": model_name,
"timestamp": datetime.now(timezone.utc).isoformat(),
"summary": {
"submitted": len(items_sorted),
"scored": total_scored,
"missing": len(missing),
"errors": len(errors),
"correct": correct,
"accuracy": round(correct / total_scored, 4) if total_scored else 0,
},
"per_task": dict(per_task),
"per_tag": dict(per_tag),
"items": items_sorted,
}
with open(RESULTS_FILE, "w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=2)
# ── Display ──────────────────────────────────────────────────────────
def print_summary(items: list[dict], model_name: str):
try:
from rich.console import Console # noqa: F401
_rich_summary(items, model_name)
except ImportError:
_ascii_summary(items, model_name)
def _collect_stats(items):
"""Collect all accuracy breakdowns from result items."""
errors = [r for r in items if "error" in r]
missing = [r for r in items if "error" not in r and r.get("missing")]
evaluated = [r for r in items if "error" not in r and not r.get("missing")]
correct = sum(1 for r in evaluated if r["is_correct"])
total = len(evaluated)
def _acc_map(key_fn):
m: dict[str, list[int]] = {}
for r in evaluated:
k = key_fn(r)
if k is None:
continue
if k not in m:
m[k] = [0, 0]
m[k][1] += 1
if r["is_correct"]:
m[k][0] += 1
return m
per_task = _acc_map(lambda r: r.get("task", ""))
per_qtype = _acc_map(lambda r: r.get("question_type") or (r.get("tag", [None, None])[1] if len(r.get("tag", [])) >= 2 else None))
per_persp = _acc_map(lambda r: r.get("perspective") or (r.get("tag", [None])[0] if len(r.get("tag", [])) >= 1 else None))
# per scenario (grouped under task)
per_scenario: dict[str, dict[str, list[int]]] = {}
for r in evaluated:
t = r.get("task", "")
s = r.get("scenario", "")
if t not in per_scenario:
per_scenario[t] = {}
if s not in per_scenario[t]:
per_scenario[t][s] = [0, 0]
per_scenario[t][s][1] += 1
if r["is_correct"]:
per_scenario[t][s][0] += 1
return {
"evaluated": evaluated, "errors": errors, "missing": missing,
"correct": correct, "total": total,
"per_task": per_task, "per_qtype": per_qtype,
"per_persp": per_persp, "per_scenario": per_scenario,
}
def _rich_summary(items, model_name):
from rich.console import Console
from rich.table import Table
from rich import box
console = Console()
s = _collect_stats(items)
total, correct = s["total"], s["correct"]
acc = correct / total if total else 0
bar_w = 20
def _bar(c, t, color="green"):
if t == 0:
return ""
ratio = c / t
filled = int(ratio * bar_w)
return f"[{color}]{'#' * filled}[/][bright_black]{'.' * (bar_w - filled)}[/]"
# ── Header ──
console.print()
console.rule(f"[bold cyan]Evaluation Results - {model_name}[/]")
console.print()
hdr = Table(box=None, show_header=False, padding=(0, 2))
hdr.add_column(style="white")
hdr.add_column(style="bold")
hdr.add_row("Model", f"[cyan]{model_name}[/]")
hdr.add_row("Submitted / Scored / Missing / Errors",
f"{len(items)} / {total} / {len(s['missing'])} / {len(s['errors'])}")
hdr.add_row("Overall Accuracy", f"[bold green]{acc:.1%}[/] ({correct}/{total})")
console.print(hdr)
console.print()
# ── Per Task + Scenario (nested) ──
tbl = Table(
title="Accuracy by Task & Scenario",
box=box.ROUNDED, border_style="bright_black", show_lines=False, padding=(0, 1),
)
tbl.add_column("Task", style="cyan bold", min_width=8)
tbl.add_column("Scenario", style="green", min_width=26)
tbl.add_column("Correct", justify="right", style="white", min_width=8)
tbl.add_column("Total", justify="right", style="white", min_width=6)
tbl.add_column("Accuracy", justify="right", style="yellow bold", min_width=8)
tbl.add_column("", min_width=bar_w + 2)
for task in sorted(s["per_scenario"]):
scenarios = s["per_scenario"][task]
first = True
for sc in sorted(scenarios):
c, t = scenarios[sc]
a = c / t if t else 0
tbl.add_row(
task if first else "", sc, str(c), str(t),
f"{a:.1%}", _bar(c, t),
)
first = False
# task subtotal
tc, tt = s["per_task"].get(task, [0, 0])
ta = tc / tt if tt else 0
tbl.add_row(
f"[bold]{task}[/]", "[dim]-------- Subtotal --------[/]",
f"[bold]{tc}[/]", f"[bold]{tt}[/]",
f"[bold]{ta:.1%}[/]", _bar(tc, tt, "yellow"),
style="on grey11",
)
# grand total
tbl.add_row(
"[bold white]TOTAL", "",
f"[bold white]{correct}", f"[bold white]{total}",
f"[bold white]{acc:.1%}", _bar(correct, total, "cyan"),
style="on grey19",
)
console.print(tbl)
# ── Per Question Type ──
tbl2 = Table(
title="Accuracy by Question Type",
box=box.ROUNDED, border_style="bright_black", padding=(0, 1),
)
tbl2.add_column("Type", style="magenta bold", min_width=12)
tbl2.add_column("Correct", justify="right", style="white", min_width=8)
tbl2.add_column("Total", justify="right", style="white", min_width=6)
tbl2.add_column("Accuracy", justify="right", style="yellow bold", min_width=8)
tbl2.add_column("", min_width=bar_w + 2)
for tag in sorted(s["per_qtype"]):
c, t = s["per_qtype"][tag]
tbl2.add_row(tag, str(c), str(t), f"{c / t:.1%}" if t else "-", _bar(c, t))
console.print()
console.print(tbl2)
# ── Per Perspective ──
tbl3 = Table(
title="Accuracy by Perspective",
box=box.ROUNDED, border_style="bright_black", padding=(0, 1),
)
tbl3.add_column("Perspective", style="cyan bold", min_width=12)
tbl3.add_column("Correct", justify="right", style="white", min_width=8)
tbl3.add_column("Total", justify="right", style="white", min_width=6)
tbl3.add_column("Accuracy", justify="right", style="yellow bold", min_width=8)
tbl3.add_column("", min_width=bar_w + 2)
for p in sorted(s["per_persp"]):
c, t = s["per_persp"][p]
tbl3.add_row(p, str(c), str(t), f"{c / t:.1%}" if t else "-", _bar(c, t))
console.print()
console.print(tbl3)
# ── Missing / Error list ──
problems = s["missing"] + s["errors"]
if problems:
console.print()
tbl4 = Table(
title=f"Missing & Errors ({len(problems)} items)",
box=box.ROUNDED, border_style="red", padding=(0, 1),
)
tbl4.add_column("#", style="white", min_width=4)
tbl4.add_column("Task", style="cyan", min_width=6)
tbl4.add_column("Scenario", style="green", min_width=20)
tbl4.add_column("Clip", style="white", min_width=30)
tbl4.add_column("Reason", style="red", min_width=30)
for r in sorted(problems, key=lambda x: x.get("idx", 0)):
if "error" in r:
reason = f"[red]API Error: {r['error'][:60]}[/]"
else:
reason = f"[yellow]Bad format: {r.get('response', '')[:60]}[/]"
tbl4.add_row(
str(r.get("idx", "?")),
r.get("task", ""),
r.get("scenario", ""),
r.get("clip", ""),
reason,
)
console.print(tbl4)
console.print()
def _ascii_summary(items, model_name):
s = _collect_stats(items)
total, correct = s["total"], s["correct"]
acc = correct / total if total else 0
print(f"\n{'=' * 60}")
print(f" Model: {model_name}")
print(f" Submitted: {len(items)} Scored: {total} "
f"Missing: {len(s['missing'])} Errors: {len(s['errors'])}")
print(f" Overall Accuracy: {acc:.1%} ({correct}/{total})")
print(f"{'=' * 60}")
print("\n Per Task:")
for t in sorted(s["per_task"]):
c, n = s["per_task"][t]
print(f" {t:<8} {c:>3}/{n:<3} {c/n:.1%}" if n else f" {t:<8} -")
print("\n Per Question Type:")
for t in sorted(s["per_qtype"]):
c, n = s["per_qtype"][t]
print(f" {t:<12} {c:>3}/{n:<3} {c/n:.1%}" if n else f" {t:<12} -")
print("\n Per Perspective:")
for p in sorted(s["per_persp"]):
c, n = s["per_persp"][p]
print(f" {p:<12} {c:>3}/{n:<3} {c/n:.1%}" if n else f" {p:<12} -")
print()
# ── Main ─────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Evaluate VQA dataset with Gemini")
parser.add_argument("--model", default=os.environ.get("GEMINI_MODEL", DEFAULT_MODEL),
help=f"Model name (default: {DEFAULT_MODEL})")
parser.add_argument("--workers", type=int,
default=int(os.environ.get("EVAL_WORKERS", DEFAULT_WORKERS)),
help=f"Parallel workers (default: {DEFAULT_WORKERS})")
parser.add_argument("--rpm", type=int,
default=int(os.environ.get("EVAL_RPM", DEFAULT_RPM)),
help=f"Max requests per minute (default: {DEFAULT_RPM})")
parser.add_argument("--thinking-budget", type=int,
default=int(os.environ.get("EVAL_THINKING", DEFAULT_THINKING_BUDGET)),
help=f"Thinking token budget (0=off, default: {DEFAULT_THINKING_BUDGET})")
parser.add_argument("--no-resume", action="store_true",
help="Ignore previous results, start fresh")
args = parser.parse_args()
# API key: .env -> environment variable
from dotenv import load_dotenv
load_dotenv(BASE_DIR / ".env")
api_key = os.environ.get("GOOGLE_API_KEY", "")
if not api_key:
print("[ERROR] GOOGLE_API_KEY not found. Set it in .env or environment.")
sys.exit(1)
client = genai.Client(api_key=api_key)
# Load dataset
if not META_FULL.exists():
print(f"[ERROR] {META_FULL} not found - run clip.py first")
sys.exit(1)
with open(META_FULL, "r", encoding="utf-8") as f:
vqa_list = json.load(f)
print(f"Loaded {len(vqa_list)} VQA items")
# Resume
existing = {} if args.no_resume else load_existing()
if existing:
print(f"Resuming: {len(existing)} already evaluated")
pending = [(i, item) for i, item in enumerate(vqa_list) if i not in existing]
if not pending:
print("All items already evaluated.")
all_items = list(existing.values())
print_summary(all_items, args.model)
return
think_label = f"thinking={args.thinking_budget}" if args.thinking_budget else "thinking=off"
print(f"Pending: {len(pending)} | Model: {args.model} | "
f"Workers: {args.workers} | RPM: {args.rpm} | {think_label}")
limiter = RateLimiter(args.rpm)
results = list(existing.values())
lock = threading.Lock()
done = 0
ok_count = sum(1 for r in results if "error" not in r and r.get("is_correct"))
eval_count = sum(1 for r in results if "error" not in r)
err_count = sum(1 for r in results if "error" in r)
# ── Ctrl+C: save checkpoint and force exit ──
stop_flag = threading.Event()
def _on_sigint(sig, frame):
if stop_flag.is_set():
# Second Ctrl+C: force kill
print("\n\nForce quit.")
os._exit(1)
stop_flag.set()
print("\n\nCtrl+C received - finishing current items then stopping...")
signal.signal(signal.SIGINT, _on_sigint)
t0 = time.monotonic()
executor = ThreadPoolExecutor(max_workers=args.workers)
futures = {
executor.submit(
evaluate_one, client, args.model, item, idx, limiter,
thinking_budget=args.thinking_budget,
): idx
for idx, item in pending
}
try:
for future in as_completed(futures):
if stop_flag.is_set():
# Cancel remaining futures
for f in futures:
f.cancel()
break
result = future.result()
with lock:
results.append(result)
done += 1
if "error" not in result and not result.get("missing"):
eval_count += 1
if result.get("is_correct"):
ok_count += 1
elif "error" in result:
err_count += 1
# Progress
elapsed = time.monotonic() - t0
speed = done / elapsed if elapsed > 0 else 0
eta = (len(pending) - done) / speed if speed > 0 else 0
cur_acc = ok_count / eval_count if eval_count else 0
status = "OK" if "error" not in result else f"ERR: {result.get('error', '')[:40]}"
print(
f"\r[{done}/{len(pending)}] "
f"acc={cur_acc:.1%} err={err_count} "
f"eta={eta:.0f}s | {result.get('clip', ''):40s} {status}",
end="", flush=True,
)
# Realtime checkpoint
save_results(results, args.model)
finally:
executor.shutdown(wait=False, cancel_futures=True)
print()
save_results(results, args.model)
print(f"\nResults saved to {RESULTS_FILE} ({len(results)} items)")
print_summary(results, args.model)
if __name__ == "__main__":
main()