| from __future__ import annotations |
|
|
| import traceback |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from pathlib import Path |
|
|
| from .io import append_jsonl, metadata_path, read_json, read_jsonl, write_jsonl |
| from .judge import GeminiJudge, sample_video_frames, validate_scores |
| from .prompts import last_frame_prompt, mme_cof_prompt, video_prompt |
|
|
|
|
| def parse_seeds(value: str) -> list[int]: |
| seeds = [int(part.strip()) for part in value.split(",") if part.strip()] |
| if not seeds: |
| raise ValueError("At least one seed is required") |
| return seeds |
|
|
|
|
| def video_path( |
| videos_dir: str | Path, |
| row: dict, |
| seed: int, |
| filename_template: str, |
| ) -> Path: |
| name = filename_template.format( |
| id=row["id"], |
| id06=f"{row['id']:06d}", |
| seed=seed, |
| ) |
| return Path(videos_dir) / name |
|
|
|
|
| def _evaluate_vwg_job( |
| judge: GeminiJudge, |
| row: dict, |
| seed: int, |
| path: Path, |
| max_frames: int, |
| ) -> dict: |
| frames = sample_video_frames(path, max_frames=max_frames) |
| final_result = judge.evaluate_frames(last_frame_prompt(row), [frames[-1]]) |
| final_result = validate_scores(final_result, ["last_frame_goal"], 1, 5) |
|
|
| prompt, metric_names = video_prompt(row) |
| video_result = judge.evaluate_frames(prompt, frames) |
| video_result = validate_scores(video_result, metric_names, 1, 5) |
| return { |
| "id": row["id"], |
| "seed": seed, |
| "result_id": f"{row['id']}_seed{seed}", |
| "video_file": str(path), |
| "dimension_id": row["dimension_id"], |
| "task_group_id": row["task_group_id"], |
| **video_result, |
| **final_result, |
| } |
|
|
|
|
| def evaluate_vwg( |
| dataset_root: str | Path, |
| videos_dir: str | Path, |
| output_path: str | Path, |
| seeds: list[int], |
| model: str, |
| filename_template: str = "{id}_seed{seed}.mp4", |
| workers: int = 4, |
| max_frames: int = 16, |
| limit: int | None = None, |
| strict_missing: bool = False, |
| ) -> dict: |
| rows = read_jsonl(metadata_path(dataset_root)) |
| if limit is not None: |
| rows = rows[:limit] |
| output = Path(output_path) |
| existing = read_jsonl(output) if output.exists() else [] |
| done = {row["result_id"] for row in existing} |
| errors_path = output.with_name(output.stem + ".errors.jsonl") |
|
|
| jobs = [] |
| missing = [] |
| for row in rows: |
| for seed in seeds: |
| result_id = f"{row['id']}_seed{seed}" |
| if result_id in done: |
| continue |
| path = video_path(videos_dir, row, seed, filename_template) |
| if not path.is_file(): |
| missing.append({"result_id": result_id, "video_file": str(path)}) |
| continue |
| jobs.append((row, seed, path)) |
|
|
| if strict_missing and missing: |
| raise FileNotFoundError( |
| f"{len(missing)} expected videos are missing; first: {missing[0]}" |
| ) |
|
|
| completed = list(existing) |
| failed = 0 |
| judge = GeminiJudge(model=model) if jobs else None |
| with ThreadPoolExecutor(max_workers=max(1, workers)) as executor: |
| future_map = { |
| executor.submit( |
| _evaluate_vwg_job, |
| judge, |
| row, |
| seed, |
| path, |
| max_frames, |
| ): (row, seed, path) |
| for row, seed, path in jobs |
| } |
| for future in as_completed(future_map): |
| row, seed, path = future_map[future] |
| try: |
| result = future.result() |
| completed.append(result) |
| append_jsonl(output, result) |
| except Exception as exc: |
| failed += 1 |
| append_jsonl( |
| errors_path, |
| { |
| "result_id": f"{row['id']}_seed{seed}", |
| "video_file": str(path), |
| "error_type": type(exc).__name__, |
| "error": str(exc), |
| "traceback": traceback.format_exc(), |
| }, |
| ) |
|
|
| completed.sort(key=lambda row: (row["id"], row["seed"])) |
| write_jsonl(output, completed) |
| return { |
| "expected": len(rows) * len(seeds), |
| "already_present": len(existing), |
| "submitted": len(jobs), |
| "completed_total": len(completed), |
| "missing_videos": len(missing), |
| "failed": failed, |
| "output_path": str(output), |
| "errors_path": str(errors_path) if failed else None, |
| } |
|
|
|
|
| def _evaluate_mme_job( |
| judge: GeminiJudge, |
| row: dict, |
| seed: int, |
| path: Path, |
| max_frames: int, |
| ) -> dict: |
| metrics = [ |
| "instruction_alignment", |
| "temporal_consistency", |
| "visual_stability", |
| "content_fidelity", |
| "focus_relevance", |
| ] |
| frames = sample_video_frames(path, max_frames=max_frames) |
| result = judge.evaluate_frames(mme_cof_prompt(row["user_prompt"]), frames) |
| result = validate_scores(result, metrics, 0, 4) |
| return { |
| "id": row["id"], |
| "seed": seed, |
| "result_id": f"{row['id']}_seed{seed}", |
| "video_file": str(path), |
| "task_name": row.get("task_name"), |
| **result, |
| } |
|
|
|
|
| def evaluate_mme_cof( |
| metadata_json: str | Path, |
| videos_dir: str | Path, |
| output_path: str | Path, |
| seeds: list[int], |
| model: str, |
| filename_template: str = "{id}_seed{seed}.mp4", |
| workers: int = 4, |
| max_frames: int = 16, |
| ) -> dict: |
| rows = read_json(metadata_json) |
| output = Path(output_path) |
| existing = read_jsonl(output) if output.exists() else [] |
| done = {row["result_id"] for row in existing} |
| completed = list(existing) |
| missing = 0 |
| failed = 0 |
| errors_path = output.with_name(output.stem + ".errors.jsonl") |
| jobs = [] |
| for row in rows: |
| for seed in seeds: |
| result_id = f"{row['id']}_seed{seed}" |
| if result_id in done: |
| continue |
| path = video_path(videos_dir, row, seed, filename_template) |
| if not path.is_file(): |
| missing += 1 |
| continue |
| jobs.append((row, seed, path)) |
|
|
| judge = GeminiJudge(model=model) if jobs else None |
| with ThreadPoolExecutor(max_workers=max(1, workers)) as executor: |
| future_map = { |
| executor.submit(_evaluate_mme_job, judge, row, seed, path, max_frames): ( |
| row, |
| seed, |
| path, |
| ) |
| for row, seed, path in jobs |
| } |
| for future in as_completed(future_map): |
| row, seed, path = future_map[future] |
| try: |
| result = future.result() |
| completed.append(result) |
| append_jsonl(output, result) |
| except Exception as exc: |
| failed += 1 |
| append_jsonl( |
| errors_path, |
| { |
| "result_id": f"{row['id']}_seed{seed}", |
| "video_file": str(path), |
| "error_type": type(exc).__name__, |
| "error": str(exc), |
| }, |
| ) |
|
|
| completed.sort(key=lambda row: (row["id"], row["seed"])) |
| write_jsonl(output, completed) |
| return { |
| "expected": len(rows) * len(seeds), |
| "completed_total": len(completed), |
| "missing_videos": missing, |
| "failed": failed, |
| "output_path": str(output), |
| } |
|
|