Datasets:
File size: 7,437 Bytes
33fba32 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | 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),
}
|