#!/usr/bin/env python3 """Evaluate candidate captions against TCA-Bench GT. Reads candidate captions from captions/{folder}/captions.json, evaluates them against GT from gt/, and outputs results to results/{name}/{timestamp}/. Usage: python evaluate.py --input my-model # folder name under captions/ python evaluate.py -i my-model --name run1 # custom result folder name python evaluate.py -i my-model --explain # include per-dimension explanations python evaluate.py -i my-model --stage 1v 2 # only run visual + binding eval python evaluate.py -i my-model --dry-run # preview what would run python evaluate.py -i my-model --force # re-evaluate even if results exist Stages: 1v = Stage 1 Visual (3 dimensions, 0-10 each) 1a = Stage 1 Audio (2 dimensions, 0-10 each) 2 = Stage 2 AV-Binding (correct/total ratio) 3 = Stage 3 Temporal (correct/total ratio) Output structure: results/{name}/{YYYY-MM-DD-HH-MM-SS}/ ├── summary.json # Aggregate scores + metadata ├── report.md # Human-readable report └── details.json # Per-video parsed results (merged) """ from __future__ import annotations import argparse import json import os import random import re import shutil import sys import threading import time from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone, timedelta from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar from rich.console import Console from rich.panel import Panel from rich.progress import ( BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn, ) from rich.table import Table console = Console(highlight=False) # --------------------------------------------------------------------------- # OpenAI-compatible judge API configuration # --------------------------------------------------------------------------- # Set credentials through the environment before running the evaluator. BASE_URL = ( os.getenv("TCA_EVAL_BASE_URL") or os.getenv("OPENAI_BASE_URL") or "https://openrouter.ai/api/v1" ) API_KEY = ( os.getenv("TCA_EVAL_API_KEY") or os.getenv("OPENROUTER_API_KEY") or os.getenv("OPENAI_API_KEY") or "" ) MODEL = os.getenv("TCA_EVAL_MODEL", "gpt-4.1") # --------------------------------------------------------------------------- # Paths (relative to this script's location) # --------------------------------------------------------------------------- SCRIPT_DIR = Path(__file__).resolve().parent # scripts/ PROMPTS_DIR = SCRIPT_DIR / "prompts" # scripts/prompts/ MAIN_DIR = SCRIPT_DIR.parent # benchmark root GT_DIR = MAIN_DIR / "gt" # gt/ CAPTIONS_DIR = MAIN_DIR / "captions" # captions/ RESULTS_DIR = MAIN_DIR / "results" # results/ # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- ALL_STAGES = ["1v", "1a", "2", "3"] DEFAULT_CONCURRENCY = 16 MAX_RETRIES = 60 RETRY_DELAY_MIN = 2 RETRY_DELAY_MAX = 5 T = TypeVar("T") # Thread-safe retry stats _retry_lock = threading.Lock() _retry_active: Dict[str, int] = {} _retry_total = 0 # Dimension keys VISUAL_DIMS = ["subject_and_action", "scene_and_atmosphere", "cinematography"] AUDIO_DIMS = ["transcription_accuracy", "tone_and_emotion"] VISUAL_DIM_LABELS = { "subject_and_action": "Subject+Action", "scene_and_atmosphere": "Scene+Atmos", "cinematography": "Cinematography", } AUDIO_DIM_LABELS = { "transcription_accuracy": "Transcription", "tone_and_emotion": "Tone+Emotion", } # --------------------------------------------------------------------------- # File I/O helpers # --------------------------------------------------------------------------- def load_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) def load_captions(path: Path) -> List[Dict]: """Load captions from JSON array or JSONL, normalising key names. Accepts: - Standard JSON array: [{"id": ..., "caption": ...}, ...] - JSONL (one JSON object per line) - 'video_id' as alias for 'id' - Strips .mp4 / other video extensions from id values """ text = path.read_text(encoding="utf-8").strip() items: List[Dict] = [] # Try standard JSON first try: parsed = json.loads(text) if isinstance(parsed, list): items = parsed elif isinstance(parsed, dict): items = [parsed] else: raise ValueError(f"Unexpected top-level type: {type(parsed)}") except json.JSONDecodeError: # Fall back to JSONL for lineno, line in enumerate(text.splitlines(), 1): line = line.strip() if not line: continue try: obj = json.loads(line) items.append(obj) except json.JSONDecodeError as e: console.print(f"[yellow]⚠ Skipping line {lineno}: {e}[/yellow]") # Normalise keys: video_id -> id normalised: List[Dict] = [] for item in items: if not isinstance(item, dict): continue vid = item.get("id") or item.get("video_id", "") caption = item.get("caption", "") if not vid: continue normalised.append({"id": _normalize_id(str(vid)), "caption": caption}) return normalised def save_json(path: Path, data: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def save_text(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") def extract_json_block(text: str) -> str: """Strip markdown code fences from LLM JSON output.""" t = text.strip() if t.startswith("```json"): t = t[7:] elif t.startswith("```"): t = t[3:] if t.endswith("```"): t = t[:-3] return t.strip() # --------------------------------------------------------------------------- # OpenAI-compatible API client # --------------------------------------------------------------------------- def _build_client(base_url: str, api_key: str): """Build an OpenAI-compatible client.""" try: from openai import OpenAI except ImportError: console.print("[bold red]✗[/bold red] openai package not installed. " "Run: pip install openai") sys.exit(1) return OpenAI(base_url=base_url, api_key=api_key) def call_llm( client, model: str, prompt: str, *, temperature: float = 1.0, max_retries: int = MAX_RETRIES, ) -> str: """Call LLM via OpenAI-compatible API with retry. Returns text response.""" global _retry_total tid = str(threading.current_thread().ident) last_err: Optional[Exception] = None for attempt in range(max_retries): try: # Original resp = client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], temperature=temperature, ) # My Co-worker # messages = [{"role": "user", "content": prompt}] # payload = create_gemini_payload(model, messages, temperature) # resp = requests.post(client.url, headers=client.headers, json=payload, timeout=240) text = resp.choices[0].message.content if text: with _retry_lock: _retry_active.pop(tid, None) return text raise RuntimeError("Empty response from LLM") except Exception as e: last_err = e if attempt < max_retries - 1: delay = random.uniform(RETRY_DELAY_MIN, RETRY_DELAY_MAX) with _retry_lock: _retry_active[tid] = attempt + 1 _retry_total += 1 time.sleep(delay) with _retry_lock: _retry_active.pop(tid, None) raise RuntimeError(f"LLM call failed after {max_retries} retries: {last_err}") # --------------------------------------------------------------------------- # Prompt loading with explain toggle # --------------------------------------------------------------------------- def _load_local_prompt(name: str) -> str: """Load a prompt from scripts/prompts/.""" p = PROMPTS_DIR / name if not p.exists(): raise FileNotFoundError(f"Prompt not found: {p}") return p.read_text(encoding="utf-8") def get_prompt(stage: str, *, explain: bool) -> str: """Return the appropriate prompt template for a stage.""" suffix = "" if explain else "-score-only" mapping = { "1v": f"stage-1-visual-eval{suffix}.txt", "1a": f"stage-1-audio-eval{suffix}.txt", "2": f"stage-2-eval{suffix}.txt", "3": f"stage-3-eval{suffix}.txt", } return _load_local_prompt(mapping[stage]) # --------------------------------------------------------------------------- # Rich concurrent runner # --------------------------------------------------------------------------- def run_concurrent_rich( tasks: List[Tuple[str, Callable]], *, max_workers: int = DEFAULT_CONCURRENCY, label: str = "Evaluating", ) -> Dict[str, Any]: """Run named tasks concurrently with a rich progress bar.""" total = len(tasks) results: Dict[str, Any] = {} failed: List[Tuple[str, Exception]] = [] with Progress( SpinnerColumn(spinner_name="dots", style="bold cyan"), TextColumn("[bold cyan]{task.description}"), BarColumn(bar_width=28, style="cyan", complete_style="green", finished_style="bright_green"), MofNCompleteColumn(), TaskProgressColumn(), TimeElapsedColumn(), TimeRemainingColumn(), TextColumn("{task.fields[status]}"), console=console, refresh_per_second=10, transient=False, ) as progress: task_id = progress.add_task(label, total=total, status="") def _status_text(last_name: str, ok: bool): short = last_name.split("__")[-1] if "__" in last_name else last_name[-30:] icon = "[green]✓[/green]" if ok else "[red]✗[/red]" with _retry_lock: active = len(_retry_active) total_r = _retry_total retry_part = f" [yellow]⟳ {active} retrying ({total_r} total)[/yellow]" if active else "" return f"{icon} [dim]{short}[/dim]{retry_part}" with ThreadPoolExecutor(max_workers=max_workers) as pool: future_map = {pool.submit(fn): name for name, fn in tasks} for future in as_completed(future_map): name = future_map[future] try: results[name] = future.result() progress.update(task_id, advance=1, status=_status_text(name, True)) except Exception as exc: failed.append((name, exc)) results[name] = {"_error": str(exc)} progress.update(task_id, advance=1, status=_status_text(name, False)) if failed: console.print(f"\n[bold red]⚠ {len(failed)} task(s) failed:[/bold red]") for name, exc in failed: console.print(f" [red]•[/red] {name}: {exc}") return results # --------------------------------------------------------------------------- # Score parsing # --------------------------------------------------------------------------- def parse_visual_json(text: str, *, explain: bool) -> Dict[str, Any]: fallback = {dim: {"score": None, "reason": "parse error"} for dim in VISUAL_DIMS} fallback["overall_average"] = None try: data = json.loads(extract_json_block(text)) except (json.JSONDecodeError, ValueError): return fallback result: Dict[str, Any] = {} for dim in VISUAL_DIMS: entry = data.get(dim, {}) if isinstance(entry, dict): score = entry.get("score") reason = entry.get("reason", "") score = int(score) if isinstance(score, (int, float)) else None elif isinstance(entry, (int, float)): score = int(entry) reason = "" else: score, reason = None, "missing" result[dim] = {"score": score, "reason": reason} valid = [result[d]["score"] for d in VISUAL_DIMS if result[d]["score"] is not None] oa = data.get("overall_average") if isinstance(oa, (int, float)): result["overall_average"] = round(float(oa), 2) elif valid: result["overall_average"] = round(sum(valid) / len(valid), 2) else: result["overall_average"] = None return result def parse_audio_json(text: str, *, explain: bool) -> Dict[str, Any]: fallback = {dim: {"score": None, "reason": "parse error"} for dim in AUDIO_DIMS} fallback["overall_average"] = None try: data = json.loads(extract_json_block(text)) except (json.JSONDecodeError, ValueError): return fallback result: Dict[str, Any] = {} for dim in AUDIO_DIMS: entry = data.get(dim, {}) if isinstance(entry, dict): score = entry.get("score") reason = entry.get("reason", "") score = int(score) if isinstance(score, (int, float)) else None elif isinstance(entry, (int, float)): score = int(entry) reason = "" else: score, reason = None, "missing" result[dim] = {"score": score, "reason": reason} valid = [result[d]["score"] for d in AUDIO_DIMS if result[d]["score"] is not None] result["overall_average"] = round(sum(valid) / len(valid), 2) if valid else None return result def parse_stage2_json(text: str, *, explain: bool) -> Tuple[Optional[int], Optional[int], str, List[Dict[str, Any]]]: """Parse Stage-2 JSON response with 3-way verdict support. Supports both old ("correct": bool) and new ("verdict": str) formats. Score = correct / (correct + incorrect). Skipped items excluded from denominator. Returns (correct, evaluated, summary, results_list). """ try: data = json.loads(extract_json_block(text)) except (json.JSONDecodeError, ValueError): return None, None, "parse error", [] results = data.get("results") if isinstance(data, dict) else None if not isinstance(results, list): return None, None, "missing results", [] correct = 0 incorrect_indices: List[int] = [] skipped = 0 parsed_items: List[Dict[str, Any]] = [] for item in results: if not isinstance(item, dict): continue # Support both old ("correct": bool) and new ("verdict": str) formats verdict_raw = item.get("verdict") if verdict_raw is not None: verdict = str(verdict_raw).strip().lower() elif "correct" in item: verdict = "correct" if item["correct"] else "incorrect" else: continue idx = item.get("index") if verdict == "skipped": skipped += 1 parsed_items.append({ "index": idx, "verdict": "skipped", "correct": False, "reason": item.get("reason", ""), }) elif verdict == "correct": correct += 1 parsed_items.append({ "index": idx, "verdict": "correct", "correct": True, "reason": item.get("reason", ""), }) else: # incorrect if isinstance(idx, int): incorrect_indices.append(idx) parsed_items.append({ "index": idx, "verdict": "incorrect", "correct": False, "reason": item.get("reason", ""), }) incorrect_count = sum(1 for p in parsed_items if p["verdict"] == "incorrect") evaluated = correct + incorrect_count if evaluated == 0 and skipped == 0: return None, None, "empty results", [] parts = [f"{correct}/{evaluated}"] if incorrect_indices: parts.append(f"incorrect: {', '.join(map(str, incorrect_indices))}") if skipped: parts.append(f"skipped: {skipped}") summary = "; ".join(parts) return correct, evaluated, summary, parsed_items def parse_ratio(text: str) -> Tuple[Optional[int], Optional[int], str]: m = re.search(r"(\d+)\s*/\s*(\d+)", text) if m: return int(m.group(1)), int(m.group(2)), text.strip().split("\n")[0] return None, None, text.strip().split("\n")[0] def parse_stage3_json(text: str) -> Tuple[Optional[int], Optional[int], str, List[Dict[str, Any]]]: """Parse structured Stage-3 JSON response (explain mode). Supports 3-way verdicts: correct / incorrect / skipped. Score = correct / (correct + incorrect). Skipped items are excluded from the denominator. Returns (correct, evaluated, summary, results_list). """ try: data = json.loads(extract_json_block(text)) except (json.JSONDecodeError, ValueError): return None, None, "parse error", [] results = data.get("results") if isinstance(data, dict) else None if not isinstance(results, list): return None, None, "missing results", [] correct = 0 incorrect_indices: List[int] = [] skipped = 0 parsed_items: List[Dict[str, Any]] = [] for item in results: if not isinstance(item, dict): continue # Support both old ("correct": bool) and new ("verdict": str) formats verdict_raw = item.get("verdict") if verdict_raw is not None: verdict = str(verdict_raw).strip().lower() elif "correct" in item: verdict = "correct" if bool(item["correct"]) else "incorrect" else: continue idx = item.get("index") if verdict == "skipped": skipped += 1 parsed_items.append({ "index": idx, "correct": None, "verdict": "skipped", "reason": item.get("reason", ""), }) elif verdict == "correct": correct += 1 parsed_items.append({ "index": idx, "correct": True, "verdict": "correct", "reason": item.get("reason", ""), }) else: # incorrect if isinstance(idx, int): incorrect_indices.append(idx) parsed_items.append({ "index": idx, "correct": False, "verdict": "incorrect", "reason": item.get("reason", ""), }) evaluated = correct + len(incorrect_indices) + sum( 1 for p in parsed_items if p["verdict"] == "incorrect" and not isinstance(p["index"], int) ) # Simpler: evaluated = correct + incorrect_count incorrect_count = sum(1 for p in parsed_items if p["verdict"] == "incorrect") evaluated = correct + incorrect_count if evaluated == 0 and skipped == 0: return None, None, "empty results", [] parts = [f"{correct}/{evaluated}"] if incorrect_indices: parts.append(f"incorrect: {', '.join(map(str, incorrect_indices))}") if skipped: parts.append(f"skipped: {skipped}") summary = "; ".join(parts) return correct, evaluated, summary, parsed_items # --------------------------------------------------------------------------- # Single-video evaluation # --------------------------------------------------------------------------- def evaluate_one_video( vid: str, caption: str, client, model: str, *, stages: List[str], explain: bool, gt_captions: Dict[str, str], gt_stage2: Dict[str, str], gt_stage3: Dict[str, str], details_dir: Path, save_raw: bool = False, ) -> Dict[str, Any]: """Run requested eval stages for one video. Saves detail JSON immediately.""" result: Dict[str, Any] = {"id": vid} gt0 = gt_captions.get(vid, "") gt2 = gt_stage2.get(vid, "") gt3 = gt_stage3.get(vid, "") calls: Dict[str, str] = {} if "1v" in stages: p = get_prompt("1v", explain=explain) calls["1v"] = p.replace("{{Ground_Truth}}", gt0).replace("{{Candidate}}", caption) if "1a" in stages: p = get_prompt("1a", explain=explain) calls["1a"] = p.replace("{{Ground_Truth}}", gt0).replace("{{Candidate}}", caption) if "2" in stages: p = get_prompt("2", explain=explain) calls["2"] = p.replace("{{Candidate}}", caption).replace("{{Ground_Truth}}", gt2) if "3" in stages: # Stage 3 always uses the structured (explain) prompt because the F1 # metric requires per-relation verdicts (correct/incorrect/skipped). p = get_prompt("3", explain=True) calls["3"] = p.replace("{{Ground_Truth_Relations}}", gt3).replace("{{Candidate}}", caption) raw_responses: Dict[str, str] = {} with ThreadPoolExecutor(max_workers=len(calls)) as pool: futs = { pool.submit(call_llm, client, model, prompt): stage for stage, prompt in calls.items() } for fut in as_completed(futs): stage = futs[fut] try: raw_responses[stage] = fut.result() except Exception as e: raw_responses[stage] = f"ERROR: {e}" # Parse if "1v" in raw_responses: vis = parse_visual_json(raw_responses["1v"], explain=explain) s1v_entry: Dict[str, Any] = { "dimensions": {d: vis[d] for d in VISUAL_DIMS}, "overall_average": vis["overall_average"], } if save_raw: s1v_entry["raw"] = raw_responses["1v"].strip() result["stage1_visual"] = s1v_entry if "1a" in raw_responses: aud = parse_audio_json(raw_responses["1a"], explain=explain) s1a_entry: Dict[str, Any] = { "dimensions": {d: aud[d] for d in AUDIO_DIMS}, "overall_average": aud["overall_average"], } if save_raw: s1a_entry["raw"] = raw_responses["1a"].strip() result["stage1_audio"] = s1a_entry if "2" in raw_responses: s2_num, s2_den, s2_summary, s2_items = parse_stage2_json(raw_responses["2"], explain=explain) s2_entry: Dict[str, Any] = { "numerator": s2_num, "denominator": s2_den, "ratio": f"{s2_num}/{s2_den}" if s2_num is not None else "N/A", "summary": s2_summary, "results": s2_items, } if save_raw: s2_entry["raw"] = raw_responses["2"].strip() result["stage2"] = s2_entry if "3" in raw_responses: # Always parse as structured JSON (explain prompt is always used for S3) s3_num, s3_den, s3_summary, s3_items = parse_stage3_json(raw_responses["3"]) if not explain: # Strip verbose reason strings when not in explain mode s3_items = [{k: v for k, v in it.items() if k != "reason"} for it in s3_items] s3_entry: Dict[str, Any] = { "numerator": s3_num, "denominator": s3_den, "ratio": f"{s3_num}/{s3_den}" if s3_num is not None else "N/A", "summary": s3_summary, "results": s3_items, } if save_raw: s3_entry["raw"] = raw_responses["3"].strip() result["stage3"] = s3_entry save_json(details_dir / f"{vid}.json", result) return result # --------------------------------------------------------------------------- # Load GT data (consolidated files) # --------------------------------------------------------------------------- def _normalize_id(vid: str) -> str: """Strip .mp4 (or other video extensions) so IDs match regardless of suffix.""" for ext in (".mp4", ".mkv", ".webm", ".avi", ".mov"): if vid.endswith(ext): return vid[: -len(ext)] return vid def load_gt_map(path: Path, caption_key: str = "caption") -> Dict[str, str]: if not path.exists(): return {} data = load_json(path) out: Dict[str, str] = {} for item in data: if isinstance(item, dict) and "id" in item: val = item.get(caption_key, "") if isinstance(val, dict) or isinstance(val, list): val = json.dumps(val, ensure_ascii=False) out[_normalize_id(item["id"])] = str(val) return out def load_gt_map_full(path: Path) -> Dict[str, str]: if not path.exists(): return {} data = load_json(path) out: Dict[str, str] = {} for item in data: if isinstance(item, dict) and "id" in item: entry = {k: v for k, v in item.items() if k != "id"} out[_normalize_id(item["id"])] = json.dumps(entry, ensure_ascii=False) return out def load_gt_raw(path: Path) -> Dict[str, Dict[str, Any]]: """Load GT as raw dicts (not stringified) keyed by normalised ID.""" if not path.exists(): return {} data = load_json(path) out: Dict[str, Dict[str, Any]] = {} for item in data: if isinstance(item, dict) and "id" in item: out[_normalize_id(item["id"])] = {k: v for k, v in item.items() if k != "id"} return out # --------------------------------------------------------------------------- # Aggregate summary # --------------------------------------------------------------------------- def compute_summary( video_results: List[Dict[str, Any]], stages: List[str], *, gt_stage2_raw: Optional[Dict[str, Any]] = None, gt_stage3_raw: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: n = len(video_results) if n == 0: return {"num_videos": 0} def safe_avg(vals): return round(sum(vals) / len(vals), 3) if vals else None def ratio_avg(pairs): ratios = [n / d for n, d in pairs if d and d > 0] return round(sum(ratios) / len(ratios), 3) if ratios else None def _f1(prec: float, cov: float) -> float: return round(2 * prec * cov / (prec + cov), 3) if (prec + cov) > 0 else 0.0 summary: Dict[str, Any] = {"num_videos": n} if "1v" in stages: vis_dim_scores: Dict[str, List[int]] = {d: [] for d in VISUAL_DIMS} vis_overall: List[float] = [] for r in video_results: sv = r.get("stage1_visual", {}) for d in VISUAL_DIMS: s = sv.get("dimensions", {}).get(d, {}).get("score") if s is not None: vis_dim_scores[d].append(s) oa = sv.get("overall_average") if oa is not None: vis_overall.append(oa) summary["stage1_visual"] = { "overall_mean": safe_avg(vis_overall), "dimensions": { d: {"mean": safe_avg(vis_dim_scores[d]), "valid_count": len(vis_dim_scores[d])} for d in VISUAL_DIMS }, "valid_count": len(vis_overall), "max_possible": 10, } if "1a" in stages: aud_scores = [ r.get("stage1_audio", {}).get("overall_average") for r in video_results ] aud_scores = [s for s in aud_scores if s is not None] aud_dim_scores: Dict[str, List[int]] = {d: [] for d in AUDIO_DIMS} for r in video_results: sa = r.get("stage1_audio", {}) for d in AUDIO_DIMS: s = sa.get("dimensions", {}).get(d, {}).get("score") if s is not None: aud_dim_scores[d].append(s) summary["stage1_audio"] = { "overall_mean": safe_avg(aud_scores), "dimensions": { d: {"mean": safe_avg(aud_dim_scores[d]), "valid_count": len(aud_dim_scores[d])} for d in AUDIO_DIMS }, "valid_count": len(aud_scores), "max_possible": 10, } # ------------------------------------------------------------------ # Stage 2: Binding — Accuracy (correct / total_gt) # Overall + character / non-character sub-dimensions # ------------------------------------------------------------------ if "2" in stages: # Sub-dimension counters: character vs non-character sub: Dict[str, Dict[str, int]] = { "character": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0}, "non_character": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0}, } for r in video_results: vid = r["id"] items = r.get("stage2", {}).get("results", []) gt_raw = (gt_stage2_raw or {}).get(vid) if gt_raw is None or not items: continue gt_sounds = gt_raw.get("sounds", []) for item in items: idx = item.get("index") if idx is None or idx >= len(gt_sounds): continue src = gt_sounds[idx].get("source", "") is_char = src.startswith("Foreground character") cat = "character" if is_char else "non_character" sub[cat]["total_gt"] += 1 verdict = item.get("verdict", "correct" if item.get("correct") else "incorrect") if verdict == "correct": sub[cat]["correct"] += 1 elif verdict == "incorrect": sub[cat]["incorrect"] += 1 else: sub[cat]["skipped"] += 1 # Compute accuracy = correct / total_gt for each sub-dimension sub_summary: Dict[str, Any] = {} for cat in ("character", "non_character"): c = sub[cat]["correct"] i = sub[cat]["incorrect"] s = sub[cat]["skipped"] t = sub[cat]["total_gt"] accuracy = round(c / t, 3) if t > 0 else None sub_summary[cat] = { "correct": c, "incorrect": i, "skipped": s, "total_gt": t, "accuracy": accuracy, } # Overall accuracy = pooled correct / total_gt total_c = sum(sub[cat]["correct"] for cat in ("character", "non_character")) total_gt = sum(sub[cat]["total_gt"] for cat in ("character", "non_character")) overall_acc = round(total_c / total_gt, 3) if total_gt > 0 else None summary["stage2_binding"] = { "accuracy": overall_acc, "correct": total_c, "total_gt": total_gt, "valid_count": sum(1 for r in video_results if r.get("stage2", {}).get("numerator") is not None), "character": sub_summary["character"], "non_character": sub_summary["non_character"], } # ------------------------------------------------------------------ # Stage 3: Temporal — overall + sequential / simultaneous F1 # ------------------------------------------------------------------ if "3" in stages: s3_ratios = [ (r["stage3"]["numerator"], r["stage3"]["denominator"]) for r in video_results if r.get("stage3", {}).get("numerator") is not None ] # Sub-dimension: sequential vs simultaneous SEQUENTIAL_TYPES = {"A_triggers_V", "V_triggers_A", "A_triggers_A", "V_triggers_V"} SIMULTANEOUS_TYPES = {"AV_simultaneous"} sub: Dict[str, Dict[str, int]] = { "sequential": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0}, "simultaneous": {"correct": 0, "incorrect": 0, "skipped": 0, "total_gt": 0}, } for r in video_results: vid = r["id"] items = r.get("stage3", {}).get("results", []) gt_raw = (gt_stage3_raw or {}).get(vid) if gt_raw is None or not items: continue gt_rels = gt_raw.get("sequential_relations", gt_raw.get("relations", [])) for item in items: idx = item.get("index") if idx is None or idx >= len(gt_rels): continue rtype = gt_rels[idx].get("type", "") if rtype in SEQUENTIAL_TYPES: cat = "sequential" elif rtype in SIMULTANEOUS_TYPES: cat = "simultaneous" else: continue sub[cat]["total_gt"] += 1 verdict = item.get("verdict", "correct" if item.get("correct") else "incorrect") if verdict == "correct": sub[cat]["correct"] += 1 elif verdict == "incorrect": sub[cat]["incorrect"] += 1 else: sub[cat]["skipped"] += 1 # Compute precision, coverage, F1 for each sub-dimension sub_summary: Dict[str, Any] = {} for cat in ("sequential", "simultaneous"): c = sub[cat]["correct"] i = sub[cat]["incorrect"] s = sub[cat]["skipped"] t = sub[cat]["total_gt"] evaluated = c + i precision = round(c / evaluated, 3) if evaluated > 0 else None coverage = round(evaluated / t, 3) if t > 0 else None f1 = _f1(precision, coverage) if (precision is not None and coverage is not None) else None sub_summary[cat] = { "correct": c, "incorrect": i, "skipped": s, "total_gt": t, "precision": precision, "coverage": coverage, "f1": f1, } # Overall F1 = pooled from all items (naturally weighted by category size) total_c = sum(sub[cat]["correct"] for cat in ("sequential", "simultaneous")) total_i = sum(sub[cat]["incorrect"] for cat in ("sequential", "simultaneous")) total_gt = sum(sub[cat]["total_gt"] for cat in ("sequential", "simultaneous")) total_eval = total_c + total_i overall_prec = round(total_c / total_eval, 3) if total_eval > 0 else None overall_cov = round(total_eval / total_gt, 3) if total_gt > 0 else None overall_f1 = _f1(overall_prec, overall_cov) if (overall_prec is not None and overall_cov is not None) else None summary["stage3_temporal"] = { "f1": overall_f1, "precision": overall_prec, "coverage": overall_cov, "valid_count": len(s3_ratios), "sequential": sub_summary["sequential"], "simultaneous": sub_summary["simultaneous"], } return summary # --------------------------------------------------------------------------- # Markdown report # --------------------------------------------------------------------------- def _render_score_table_md( summary: Dict[str, Any], stages: List[str], *, title: str = "Aggregate Scores", ) -> List[str]: """Render a Markdown score table for one summary dict.""" lines: List[str] = [] lines.append(f"## {title}\n") lines.append("| Metric | Score |") lines.append("|--------|-------|") def fmt_mean(val, mx=None): if val is None: return "N/A" return f"{val:.2f} / {mx}" if mx else f"{val:.3f}" if "1v" in stages: s1v = summary.get("stage1_visual", {}) lines.append(f"| **Stage 1 Visual Overall (0-10)** | {fmt_mean(s1v.get('overall_mean'), 10)} |") for d in VISUAL_DIMS: dm = s1v.get("dimensions", {}).get(d, {}).get("mean") lines.append(f"| ↳ {VISUAL_DIM_LABELS[d]} | {fmt_mean(dm, 10)} |") if "1a" in stages: s1a = summary.get("stage1_audio", {}) lines.append(f"| **Stage 1 Audio Overall (0-10)** | {fmt_mean(s1a.get('overall_mean'), 10)} |") for d in AUDIO_DIMS: dm = s1a.get("dimensions", {}).get(d, {}).get("mean") lines.append(f"| ↳ {AUDIO_DIM_LABELS[d]} | {fmt_mean(dm, 10)} |") if "2" in stages: s2 = summary.get("stage2_binding", {}) lines.append(f"| **Stage 2 AV-Binding Accuracy** | {fmt_mean(s2.get('accuracy'))} |") char = s2.get("character", {}) nchar = s2.get("non_character", {}) lines.append(f"| ↳ Character Acc | {fmt_mean(char.get('accuracy'))} " f"({char.get('correct', 0)}/{char.get('total_gt', 0)}) |") lines.append(f"| ↳ Non-Character Acc | {fmt_mean(nchar.get('accuracy'))} " f"({nchar.get('correct', 0)}/{nchar.get('total_gt', 0)}) |") if "3" in stages: s3 = summary.get("stage3_temporal", {}) lines.append(f"| **Stage 3 Temporal F1** | {fmt_mean(s3.get('f1'))} |") seq = s3.get("sequential", {}) sim = s3.get("simultaneous", {}) lines.append(f"| ↳ Sequential F1 | {fmt_mean(seq.get('f1'))} " f"(P={fmt_mean(seq.get('precision'))} C={fmt_mean(seq.get('coverage'))}) |") lines.append(f"| ↳ Simultaneous F1 | {fmt_mean(sim.get('f1'))} " f"(P={fmt_mean(sim.get('precision'))} C={fmt_mean(sim.get('coverage'))}) |") lines.append("") return lines def generate_report_md( summary: Dict[str, Any], video_results: List[Dict[str, Any]], meta: Dict[str, Any], stages: List[str], ) -> str: lines: List[str] = [] lines.append("# TCA-Bench Evaluation Report\n") lines.append(f"- **Run name**: `{meta.get('run_name', 'N/A')}`") lines.append(f"- **Timestamp**: {meta.get('timestamp', 'N/A')}") lines.append(f"- **Judge model**: {meta.get('judge_model', 'N/A')}") lines.append(f"- **Videos evaluated**: {summary.get('num_videos', 0)}") lines.append(f"- **Stages**: {', '.join(stages)}") lines.append(f"- **Explain mode**: {meta.get('explain', False)}\n") lines += _render_score_table_md(summary, stages, title="Aggregate Scores (All)") lines.append("## Per-Video Results\n") header = ["ID"] if "1v" in stages: header += [VISUAL_DIM_LABELS[d] for d in VISUAL_DIMS] + ["Vis Avg"] if "1a" in stages: header += ["S1-Aud"] if "2" in stages: header += ["S2"] if "3" in stages: header += ["S3"] lines.append("| " + " | ".join(header) + " |") lines.append("|" + "|".join(["----"] * len(header)) + "|") for r in sorted(video_results, key=lambda x: x["id"]): cols = [r["id"]] if "1v" in stages: sv = r.get("stage1_visual", {}) for d in VISUAL_DIMS: s = sv.get("dimensions", {}).get(d, {}).get("score") cols.append(str(s) if s is not None else "N/A") oa = sv.get("overall_average") cols.append(f"{oa:.1f}" if oa is not None else "N/A") if "1a" in stages: aud = r.get("stage1_audio", {}).get("overall_average") cols.append(f"{aud:.1f}" if aud is not None else "N/A") if "2" in stages: cols.append(r.get("stage2", {}).get("ratio", "N/A")) if "3" in stages: cols.append(r.get("stage3", {}).get("ratio", "N/A")) lines.append("| " + " | ".join(cols) + " |") lines.append("") if meta.get("explain"): lines.append("## Details\n") for r in sorted(video_results, key=lambda x: x["id"]): vid = r["id"] lines.append(f"### {vid}\n") if "1v" in stages: sv = r.get("stage1_visual", {}) lines.append(f"- **S1-Visual** (avg {sv.get('overall_average', 'N/A')}):") for d in VISUAL_DIMS: dd = sv.get("dimensions", {}).get(d, {}) lines.append(f" - {VISUAL_DIM_LABELS[d]} ({dd.get('score', 'N/A')}): {dd.get('reason', '')}") if "1a" in stages: sa = r.get("stage1_audio", {}) lines.append(f"- **S1-Audio** (avg {sa.get('overall_average', 'N/A')}):") for d in AUDIO_DIMS: dd = sa.get("dimensions", {}).get(d, {}) lines.append(f" - {AUDIO_DIM_LABELS[d]} ({dd.get('score', 'N/A')}): {dd.get('reason', '')}") if "2" in stages: lines.append(f"- **S2-Binding**: {r.get('stage2', {}).get('summary', 'N/A')}") if "3" in stages: lines.append(f"- **S3-Temporal**: {r.get('stage3', {}).get('summary', 'N/A')}") lines.append("") return "\n".join(lines) # --------------------------------------------------------------------------- # Incremental: load already-evaluated IDs # --------------------------------------------------------------------------- def load_existing_details(run_dir: Path) -> Dict[str, Dict]: existing: Dict[str, Dict] = {} merged = run_dir / "details.json" if merged.exists(): try: data = load_json(merged) if isinstance(data, list): for item in data: if isinstance(item, dict) and "id" in item: existing[item["id"]] = item return existing except Exception: pass details_dir = run_dir / "details" if details_dir.exists(): for p in details_dir.glob("*.json"): try: data = load_json(p) if isinstance(data, dict) and "id" in data: existing[data["id"]] = data except Exception: pass return existing def detail_has_stages(detail: Dict, stages: List[str]) -> bool: stage_keys = { "1v": "stage1_visual", "1a": "stage1_audio", "2": "stage2", "3": "stage3", } return all(stage_keys[s] in detail for s in stages) # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser( description="Evaluate candidate captions against TCA-Bench GT", ) parser.add_argument("--input", "-i", required=True, help="Folder name under captions/ (reads captions.json), or a direct path") parser.add_argument("--name", "-n", default=None, help="Result folder name under results/ (default: same as input)") parser.add_argument("--model", default=None, help=f"Judge model name (default: {MODEL})") parser.add_argument("--base-url", default=None, help=f"OpenAI-compatible API base URL (default: {BASE_URL})") parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY, help=f"Max concurrent evaluations (default: {DEFAULT_CONCURRENCY})") parser.add_argument("--stage", nargs="+", choices=ALL_STAGES, default=ALL_STAGES, help="Which eval stages to run (default: all). E.g. --stage 1v 1a") parser.add_argument("--explain", action="store_true", help="Include per-dimension explanations (default: scores only)") parser.add_argument("--save-raw", action="store_true", help="Save raw LLM responses in detail results (default: omitted)") parser.add_argument("--force", action="store_true", help="Re-evaluate even if detail results already exist") parser.add_argument("--dry-run", action="store_true", help="Show plan without calling API") parser.add_argument("--limit", type=int, default=None, help="Randomly sample N captions for a quick test run (output folder suffixed with --test)") parser.add_argument("--seed", type=int, default=42, help="Random seed for --limit sampling (default: 42)") args = parser.parse_args() model = args.model or MODEL base_url = args.base_url or BASE_URL # Validate configuration if not args.dry_run and not API_KEY: console.print("[bold red]✗[/bold red] API_KEY is empty. " "Set TCA_EVAL_API_KEY, OPENROUTER_API_KEY, or OPENAI_API_KEY.") sys.exit(1) # Resolve input input_arg = Path(args.input) if input_arg.is_file(): input_path = input_arg.resolve() input_folder_name = input_path.parent.name elif (CAPTIONS_DIR / args.input / "captions.json").exists(): input_path = CAPTIONS_DIR / args.input / "captions.json" input_folder_name = args.input else: console.print(f"[bold red]✗[/bold red] Cannot find input: tried " f"{CAPTIONS_DIR / args.input / 'captions.json'} and {input_arg}") sys.exit(1) candidates_raw: List[Dict] = load_captions(input_path) candidates: Dict[str, str] = {item["id"]: item["caption"] for item in candidates_raw} # --limit: randomly sample a subset for quick testing if args.limit is not None and args.limit < len(candidates): random.seed(args.seed) sampled_ids = sorted(random.sample(sorted(candidates.keys()), args.limit)) candidates = {vid: candidates[vid] for vid in sampled_ids} result_name = args.name or input_folder_name if args.limit is not None: result_name += "--test" stages = sorted(set(args.stage), key=ALL_STAGES.index) stages_label = " + ".join(stages) tz = timezone(timedelta(hours=8)) ts = datetime.now(tz).strftime("%Y-%m-%d-%H-%M-%S") run_dir = RESULTS_DIR / result_name / ts details_dir = run_dir / "details" console.print(Panel( f"[bold cyan]evaluate[/bold cyan] [dim]·[/dim] " f"[white]{len(candidates)}[/white] captions [dim]·[/dim] " f"[green]{stages_label}[/green]\n" f"[dim]model=[/dim][yellow]{model}[/yellow] " f"[dim]concurrency=[/dim][yellow]{args.concurrency}[/yellow]\n" f"[dim]explain=[/dim][yellow]{args.explain}[/yellow] " f"[dim]save_raw=[/dim][yellow]{args.save_raw}[/yellow] " f"[dim]force=[/dim][yellow]{args.force}[/yellow] " f"[dim]limit=[/dim][yellow]{args.limit or 'all'}[/yellow]\n" f"[dim]output=[/dim][yellow]{result_name}/{ts}[/yellow]", expand=False, border_style="cyan", )) # Load GT gt_captions = load_gt_map(GT_DIR / "captions.json") gt_stage2 = load_gt_map_full(GT_DIR / "stage-2.json") if "2" in stages else {} gt_stage3 = load_gt_map_full(GT_DIR / "stage-3.json") if "3" in stages else {} gt_stage2_raw = load_gt_raw(GT_DIR / "stage-2.json") if "2" in stages else {} gt_stage3_raw = load_gt_raw(GT_DIR / "stage-3.json") if "3" in stages else {} eval_ids: List[str] = [] missing_gt: List[str] = [] for vid in sorted(candidates.keys()): has = True if vid not in gt_captions: has = False if "2" in stages and vid not in gt_stage2: has = False if "3" in stages and vid not in gt_stage3: has = False if has: eval_ids.append(vid) else: missing_gt.append(vid) if missing_gt: console.print(f"[yellow]⚠ {len(missing_gt)} caption(s) have no matching GT, skipping[/yellow]") existing_details = load_existing_details(run_dir) if not args.force else {} tasks_to_run: List[str] = [] for vid in eval_ids: if vid in existing_details and detail_has_stages(existing_details[vid], stages): continue tasks_to_run.append(vid) skip_count = len(eval_ids) - len(tasks_to_run) console.print( f"[bold white]{len(tasks_to_run)}[/bold white] to evaluate " f"[dim]·[/dim] [dim]{skip_count} already done[/dim] " f"[dim]·[/dim] [dim]{len(missing_gt)} no GT[/dim]" ) if not tasks_to_run and not existing_details: console.print("\n[bold green]✓ Nothing to do.[/bold green]") return if args.dry_run: table = Table(title="[bold]Dry-run plan[/bold]", show_header=True, header_style="bold magenta", border_style="dim") table.add_column("#", style="dim", width=5) table.add_column("ID", style="cyan", no_wrap=False) table.add_column("Stages", style="yellow", width=14) for i, vid in enumerate(tasks_to_run[:20], 1): table.add_row(str(i), vid, stages_label) if len(tasks_to_run) > 20: table.add_row("…", f"… and {len(tasks_to_run) - 20} more", "") console.print(table) console.print(f"\n[bold green]✓ Dry run complete.[/bold green]") return if not tasks_to_run: video_results = [existing_details[vid] for vid in eval_ids if vid in existing_details] else: console.print(f"\n[dim]Connecting to {base_url} …[/dim]") client = _build_client(base_url, API_KEY) console.print(f"[dim]Model:[/dim] [yellow]{model}[/yellow]\n") details_dir.mkdir(parents=True, exist_ok=True) task_pairs = [ (vid, (lambda v=vid: evaluate_one_video( v, candidates[v], client, model, stages=stages, explain=args.explain, gt_captions=gt_captions, gt_stage2=gt_stage2, gt_stage3=gt_stage3, details_dir=details_dir, save_raw=args.save_raw, ))) for vid in tasks_to_run ] new_results = run_concurrent_rich(task_pairs, max_workers=args.concurrency, label="Evaluating") all_details = {**existing_details} for vid, res in new_results.items(): if isinstance(res, dict) and "_error" not in res: all_details[vid] = res video_results = [all_details[vid] for vid in eval_ids if vid in all_details] # Compute & save summary = compute_summary(video_results, stages, gt_stage2_raw=gt_stage2_raw, gt_stage3_raw=gt_stage3_raw) meta = { "run_name": result_name, "timestamp": ts, "judge_model": model, "input_file": str(input_path), "stages": stages, "explain": args.explain, "save_raw": args.save_raw, "concurrency": args.concurrency, "num_evaluated": len(video_results), } run_dir.mkdir(parents=True, exist_ok=True) summary_data: Dict[str, Any] = {"meta": meta, "summary": summary} save_json(run_dir / "summary.json", summary_data) details_list = sorted(video_results, key=lambda r: r["id"]) save_json(run_dir / "details.json", details_list) if details_dir.exists(): shutil.rmtree(details_dir) report = generate_report_md(summary, video_results, meta, stages) save_text(run_dir / "report.md", report) # Terminal summary tbl = Table(title="\n[bold]Evaluation Summary[/bold]", show_header=True, border_style="dim", padding=(0, 2), header_style="bold") tbl.add_column("Metric", style="dim") tbl.add_column(f"All ({summary['num_videos']})", style="bold white") def fmt(val, mx=None): if val is None: return "[dim]N/A[/dim]" if mx: return f"[green]{val:.2f}[/green] / {mx}" return f"[green]{val:.3f}[/green]" def add_row(label, get_val, mx=None): vals = [fmt(get_val(summary), mx)] tbl.add_row(label, *vals) if "1v" in stages: add_row("S1 Visual Overall", lambda s: s.get("stage1_visual", {}).get("overall_mean"), 10) for d in VISUAL_DIMS: add_row(f" ↳ {VISUAL_DIM_LABELS[d]}", lambda s, _d=d: s.get("stage1_visual", {}).get("dimensions", {}).get(_d, {}).get("mean"), 10) if "1a" in stages: add_row("S1 Audio Overall", lambda s: s.get("stage1_audio", {}).get("overall_mean"), 10) for d in AUDIO_DIMS: add_row(f" ↳ {AUDIO_DIM_LABELS[d]}", lambda s, _d=d: s.get("stage1_audio", {}).get("dimensions", {}).get(_d, {}).get("mean"), 10) if "2" in stages: add_row("S2 AV-Binding Acc", lambda s: s.get("stage2_binding", {}).get("accuracy")) add_row(" ↳ Character Acc", lambda s: s.get("stage2_binding", {}).get("character", {}).get("accuracy")) add_row(" ↳ Non-Char Acc", lambda s: s.get("stage2_binding", {}).get("non_character", {}).get("accuracy")) if "3" in stages: add_row("S3 Temporal F1", lambda s: s.get("stage3_temporal", {}).get("f1")) add_row(" ↳ Sequential F1", lambda s: s.get("stage3_temporal", {}).get("sequential", {}).get("f1")) add_row(" ↳ Simultaneous F1", lambda s: s.get("stage3_temporal", {}).get("simultaneous", {}).get("f1")) tbl.add_row("Videos evaluated", f"[cyan]{len(video_results)}[/cyan]") tbl.add_row("Output", f"[dim]{run_dir.relative_to(MAIN_DIR)}[/dim]") console.print(tbl) error_count = sum( 1 for r in video_results if any(r.get(k, {}).get("ratio") == "N/A" for k in ["stage2", "stage3"] if k.replace("stage", "") in stages) ) if error_count: console.print(f"\n[yellow]⚠ {error_count} video(s) had parse failures in some stages[/yellow]") console.print("\n[bold green]✓ Done![/bold green]") if __name__ == "__main__": main()