from __future__ import annotations import json import os import re from dataclasses import dataclass from pathlib import Path def parse_json_object(text: str) -> dict: cleaned = text.strip() cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned, flags=re.IGNORECASE) cleaned = re.sub(r"\s*```$", "", cleaned) try: value = json.loads(cleaned) except json.JSONDecodeError: start = cleaned.find("{") end = cleaned.rfind("}") if start < 0 or end <= start: raise ValueError(f"Judge response does not contain a JSON object: {text[:300]}") value = json.loads(cleaned[start : end + 1]) if not isinstance(value, dict): raise ValueError("Judge response must be a JSON object") return value def validate_scores(result: dict, metric_names: list[str], minimum: int, maximum: int) -> dict: validated = dict(result) for metric in metric_names: if metric in result: key = metric else: key = metric if metric.endswith("_score") else f"{metric}_score" if key not in result: raise ValueError(f"Judge response is missing {key}") value = int(result[key]) if not minimum <= value <= maximum: raise ValueError(f"{key}={value} is outside [{minimum}, {maximum}]") validated[key] = value return validated def sample_video_frames(video_path: str | Path, max_frames: int = 16) -> list[bytes]: try: import cv2 import numpy as np except ImportError as exc: raise RuntimeError("Install the package dependencies to read videos") from exc capture = cv2.VideoCapture(str(video_path)) if not capture.isOpened(): raise ValueError(f"Cannot open video: {video_path}") total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) if total <= 0: capture.release() raise ValueError(f"Video contains no readable frames: {video_path}") indices = np.linspace(0, total - 1, num=min(max_frames, total), dtype=int) frames = [] for index in indices: capture.set(cv2.CAP_PROP_POS_FRAMES, int(index)) ok, frame = capture.read() if not ok: continue ok, encoded = cv2.imencode(".jpg", frame) if ok: frames.append(encoded.tobytes()) capture.release() if not frames: raise ValueError(f"No frames could be decoded from {video_path}") return frames @dataclass class GeminiJudge: model: str api_key: str | None = None def __post_init__(self) -> None: try: from google import genai except ImportError as exc: raise RuntimeError("Install google-genai before running evaluation") from exc key = self.api_key or os.getenv("GEMINI_API_KEY") if not key: raise RuntimeError("Set GEMINI_API_KEY; credentials are never read from source files") self._genai = genai self._client = genai.Client(api_key=key) def _generate(self, prompt: str, images: list[bytes]) -> dict: from google.genai import types parts = [ types.Part.from_bytes(data=image, mime_type="image/jpeg") for image in images ] parts.append(types.Part.from_text(text=prompt)) response = self._client.models.generate_content( model=self.model, contents=[types.Content(role="user", parts=parts)], config=types.GenerateContentConfig( temperature=0, response_mime_type="application/json", ), ) text = getattr(response, "text", None) if not text: candidates = getattr(response, "candidates", []) or [] chunks = [] for candidate in candidates: content = getattr(candidate, "content", None) for part in getattr(content, "parts", []) or []: if getattr(part, "text", None) and not getattr(part, "thought", False): chunks.append(part.text) text = "\n".join(chunks) if not text: raise ValueError("Judge returned no textual response") return parse_json_object(text) def evaluate_frames(self, prompt: str, frames: list[bytes]) -> dict: return self._generate(prompt, frames)