| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| from pathlib import Path |
| from typing import Any |
|
|
| from PIL import Image |
|
|
|
|
| WEIGHTS = {"iaa": 0.40, "iqa": 0.20, "ista": 0.40} |
|
|
|
|
| def read_tasks(root: Path) -> dict[str, dict[str, Any]]: |
| data = json.loads((root / "benchmark" / "tasks.json").read_text(encoding="utf-8")) |
| return {item["task_id"]: item for item in data["tasks"] if item.get("enabled", True)} |
|
|
|
|
| def read_submission(path: Path) -> list[dict[str, str]]: |
| with path.open("r", encoding="utf-8-sig", newline="") as f: |
| return list(csv.DictReader(f)) |
|
|
|
|
| def resolve_image(path_text: str, submission_root: Path) -> Path: |
| path = Path(path_text) |
| if path.is_absolute(): |
| return path |
| return submission_root / path |
|
|
|
|
| def normalize_score(value: Any) -> float: |
| if value is None: |
| return 0.0 |
| score = float(value) |
| if score > 1.5: |
| score = score / 100.0 |
| return max(0.0, min(1.0, score)) |
|
|
|
|
| def m_qs(iaa: float, iqa: float, ista: float) -> float: |
| return WEIGHTS["iaa"] * iaa + WEIGHTS["iqa"] * iqa + WEIGHTS["ista"] * ista |
|
|
|
|
| def is_readable_image(path: Path) -> bool: |
| if not path.exists() or not path.is_file(): |
| return False |
| try: |
| with Image.open(path) as img: |
| img.verify() |
| return True |
| except Exception: |
| return False |
|
|
|
|
| def load_unipercept(device: str): |
| try: |
| from unipercept_reward import UniPerceptRewardInferencer |
| except ImportError as exc: |
| raise SystemExit( |
| "Missing dependency: unipercept-reward. Install it with " |
| "`pip install unipercept-reward` and follow the UniPercept " |
| "repository instructions for model setup." |
| ) from exc |
| return UniPerceptRewardInferencer(device=device) |
|
|
|
|
| def score_batch(inferencer: Any, image_paths: list[str]) -> list[dict[str, Any]]: |
| rewards = inferencer.reward(image_paths=image_paths) |
| if len(rewards) != len(image_paths): |
| raise RuntimeError( |
| f"UniPercept returned {len(rewards)} rewards for {len(image_paths)} images." |
| ) |
| return rewards |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description="Score VPhotoBench images with UniPercept.") |
| parser.add_argument("--benchmark-root", default=".", help="Path to the VPhotoBench release root.") |
| parser.add_argument("--submission", required=True, help="CSV submission file.") |
| parser.add_argument( |
| "--submission-root", |
| default=None, |
| help="Root for relative image paths. Defaults to the submission file directory.", |
| ) |
| parser.add_argument("--output", required=True, help="Output score CSV path.") |
| parser.add_argument("--device", default="cuda", help="UniPercept device, e.g. cuda or cpu.") |
| parser.add_argument("--batch-size", type=int, default=8) |
| args = parser.parse_args() |
|
|
| benchmark_root = Path(args.benchmark_root).resolve() |
| submission = Path(args.submission).resolve() |
| submission_root = Path(args.submission_root).resolve() if args.submission_root else submission.parent |
| output = Path(args.output).resolve() |
| output.parent.mkdir(parents=True, exist_ok=True) |
|
|
| tasks = read_tasks(benchmark_root) |
| rows = read_submission(submission) |
| row_by_task: dict[str, dict[str, str]] = {} |
| for row in rows: |
| task_id = row.get("task_id", "").strip() |
| if task_id: |
| row_by_task[task_id] = row |
|
|
| records: list[dict[str, Any]] = [] |
| valid_indices: list[int] = [] |
| valid_paths: list[str] = [] |
|
|
| for task_id, task in tasks.items(): |
| submission_row = row_by_task.get(task_id, {}) |
| image_text = submission_row.get("image_path", "").strip() |
| status = submission_row.get("status", "ok").strip() or "ok" |
| image_path = resolve_image(image_text, submission_root) if image_text else Path("") |
| valid = status == "ok" and bool(image_text) and is_readable_image(image_path) |
| record = { |
| "task_id": task_id, |
| "scene_id": task["scene_id"], |
| "mission_type": task["mission_type"], |
| "image_path": str(image_path) if image_text else "", |
| "status": "ok" if valid else (status if status != "ok" else "missing_or_invalid_image"), |
| "iaa": 0.0, |
| "iqa": 0.0, |
| "ista": 0.0, |
| "m_qs": 0.0, |
| "succ_at_0_55": 0, |
| "error": "" if valid else "Image missing, failed, or unreadable.", |
| } |
| if valid: |
| valid_indices.append(len(records)) |
| valid_paths.append(str(image_path)) |
| records.append(record) |
|
|
| inferencer = load_unipercept(args.device) if valid_paths else None |
| for start in range(0, len(valid_paths), args.batch_size): |
| batch_paths = valid_paths[start : start + args.batch_size] |
| rewards = score_batch(inferencer, batch_paths) |
| for offset, reward in enumerate(rewards): |
| record = records[valid_indices[start + offset]] |
| iaa = normalize_score(reward.get("iaa")) |
| iqa = normalize_score(reward.get("iqa")) |
| ista = normalize_score(reward.get("ista")) |
| score = m_qs(iaa, iqa, ista) |
| record.update( |
| { |
| "iaa": iaa, |
| "iqa": iqa, |
| "ista": ista, |
| "m_qs": score, |
| "succ_at_0_55": int(score >= 0.55), |
| "error": "", |
| } |
| ) |
|
|
| fieldnames = [ |
| "task_id", |
| "scene_id", |
| "mission_type", |
| "image_path", |
| "status", |
| "iaa", |
| "iqa", |
| "ista", |
| "m_qs", |
| "succ_at_0_55", |
| "error", |
| ] |
| with output.open("w", encoding="utf-8", newline="") as f: |
| writer = csv.DictWriter(f, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(records) |
|
|
| print(f"Wrote {len(records)} scored task rows to {output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|