Add aesthetic reward model data pipeline
Browse files- benchmarks/critic/aesthetic_rm/README.md +87 -0
- benchmarks/critic/aesthetic_rm/build_ditto_aesthetic_manifest.py +169 -0
- benchmarks/critic/aesthetic_rm/derive_pairwise_from_scores.py +121 -0
- benchmarks/critic/aesthetic_rm/label_aesthetic_api.py +246 -0
- benchmarks/critic/aesthetic_rm/select_aesthetic_candidates.py +288 -0
benchmarks/critic/aesthetic_rm/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Aesthetic RM Data Pipeline
|
| 2 |
+
|
| 3 |
+
This folder builds a JSON-first pipeline for selecting and labeling Ditto
|
| 4 |
+
candidates when the local machine has metadata and the remote machine has the
|
| 5 |
+
actual videos.
|
| 6 |
+
|
| 7 |
+
## 1. Build Candidate Manifest
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python3 reference/benchmarks/critic/aesthetic_rm/build_ditto_aesthetic_manifest.py \
|
| 11 |
+
--output out/aesthetic_rm/ditto_candidates.jsonl \
|
| 12 |
+
--metrics-manifest out/aesthetic_rm/ditto_candidates_for_metrics.jsonl
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
On the remote video machine, pass `--prefer-remote-paths` if the JSON contains
|
| 16 |
+
valid remote video paths.
|
| 17 |
+
|
| 18 |
+
## 2. Run Traditional Metrics
|
| 19 |
+
|
| 20 |
+
Use the existing traditional metric runner on the generated metrics manifest:
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python3 reference/benchmarks/edit/run_traditional_metrics.py \
|
| 24 |
+
--manifest out/aesthetic_rm/ditto_candidates_for_metrics.jsonl \
|
| 25 |
+
--output out/aesthetic_rm/ditto_traditional_metrics.csv \
|
| 26 |
+
--frames-per-video 16 \
|
| 27 |
+
--resize 256
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Optional model-backed metrics can be added exactly as in the previous val100
|
| 31 |
+
run: CLIP, DINO, LAION aesthetic predictor, pyiqa MUSIQ/NIQE, and LPIPS.
|
| 32 |
+
|
| 33 |
+
## 3. Select 5k Candidates
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
python3 reference/benchmarks/critic/aesthetic_rm/select_aesthetic_candidates.py \
|
| 37 |
+
--candidates out/aesthetic_rm/ditto_candidates.jsonl \
|
| 38 |
+
--metrics out/aesthetic_rm/ditto_traditional_metrics.csv \
|
| 39 |
+
--target 5000 \
|
| 40 |
+
--output out/aesthetic_rm/selected_5k.jsonl \
|
| 41 |
+
--pairwise-plan out/aesthetic_rm/pairwise_plan.jsonl
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
The selector uses non-aesthetic gates to remove confounds, then stratifies by
|
| 45 |
+
category, method, group, and aesthetic/quality bands. It does not simply select
|
| 46 |
+
the highest LAION aesthetic scores.
|
| 47 |
+
|
| 48 |
+
## 4. Label With API
|
| 49 |
+
|
| 50 |
+
Do not hardcode the API key. Set it in the shell:
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
export AESTHETIC_RM_API_KEY='...'
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Smoke test one item:
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
python3 reference/benchmarks/critic/aesthetic_rm/label_aesthetic_api.py \
|
| 60 |
+
--input out/aesthetic_rm/selected_5k.jsonl \
|
| 61 |
+
--output out/aesthetic_rm/aesthetic_scores_debug.jsonl \
|
| 62 |
+
--model gpt-4o \
|
| 63 |
+
--limit 1 \
|
| 64 |
+
--max-frames 4
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
The script records token usage and estimated cost when the API returns usage.
|
| 68 |
+
Pass `--input-cost-per-1m` and `--output-cost-per-1m` if you want dollar
|
| 69 |
+
estimates based on the model pricing page.
|
| 70 |
+
|
| 71 |
+
## 5. Derive Pairwise Data
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
python3 reference/benchmarks/critic/aesthetic_rm/derive_pairwise_from_scores.py \
|
| 75 |
+
--scores out/aesthetic_rm/aesthetic_scores.jsonl \
|
| 76 |
+
--output out/aesthetic_rm/aesthetic_pairwise.jsonl
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Pointwise dimensions:
|
| 80 |
+
|
| 81 |
+
- `narrative_emotional_fit`
|
| 82 |
+
- `style_world_consistency`
|
| 83 |
+
- `composition_lighting_design`
|
| 84 |
+
- `color_texture_refinement`
|
| 85 |
+
- `visual_hierarchy_readability`
|
| 86 |
+
|
| 87 |
+
All are scored on a 1-4 ordinal scale.
|
benchmarks/critic/aesthetic_rm/build_ditto_aesthetic_manifest.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build a candidate manifest for VFX/cinematic aesthetic RM labeling.
|
| 3 |
+
|
| 4 |
+
The output is JSONL so it can be committed locally and then pulled on the
|
| 5 |
+
remote machine that has the actual videos.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
DEFAULT_MANIFESTS = (
|
| 18 |
+
"datas/ditto_face/manifest.json",
|
| 19 |
+
"datas/ditto_face2/manifest.json",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def read_json(path: Path) -> list[dict[str, Any]]:
|
| 24 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 25 |
+
if not isinstance(data, list):
|
| 26 |
+
raise TypeError(f"{path} must contain a JSON list")
|
| 27 |
+
return data
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def stable_id(*parts: str, length: int = 16) -> str:
|
| 31 |
+
text = "\n".join(parts)
|
| 32 |
+
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:length]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def method_from_row(row: dict[str, Any]) -> str:
|
| 36 |
+
for key in ("target_bucket", "task_family"):
|
| 37 |
+
value = str(row.get(key, "") or "")
|
| 38 |
+
if value:
|
| 39 |
+
return value.split("/", 1)[0].replace("_filtered", "")
|
| 40 |
+
high_rel = str(row.get("high_rel", "") or "")
|
| 41 |
+
return high_rel.split("/", 1)[0].replace("_filtered", "") if high_rel else ""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def rel_category(row: dict[str, Any]) -> str:
|
| 45 |
+
high_rel = str(row.get("high_rel", "") or "")
|
| 46 |
+
parts = high_rel.split("/")
|
| 47 |
+
if len(parts) >= 2:
|
| 48 |
+
return parts[0].replace("_filtered", "")
|
| 49 |
+
return method_from_row(row)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def local_path(repo_root: Path, value: str) -> str:
|
| 53 |
+
if not value:
|
| 54 |
+
return ""
|
| 55 |
+
path = Path(value)
|
| 56 |
+
if path.is_absolute():
|
| 57 |
+
return str(path)
|
| 58 |
+
return str(repo_root / path)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def build_rows(repo_root: Path, manifest_paths: list[Path]) -> list[dict[str, Any]]:
|
| 62 |
+
rows: list[dict[str, Any]] = []
|
| 63 |
+
seen: set[tuple[str, str, str, str]] = set()
|
| 64 |
+
|
| 65 |
+
for manifest_path in manifest_paths:
|
| 66 |
+
path = manifest_path if manifest_path.is_absolute() else repo_root / manifest_path
|
| 67 |
+
dataset = path.parent.name
|
| 68 |
+
for row in read_json(path):
|
| 69 |
+
prompt = str(row.get("prompt", "") or "").strip()
|
| 70 |
+
low_rel = str(row.get("low_rel", "") or row.get("low_video_relpath", "") or "")
|
| 71 |
+
high_rel = str(row.get("high_rel", "") or row.get("high_video_relpath", "") or "")
|
| 72 |
+
if not prompt or not low_rel or not high_rel:
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
group_id = stable_id(dataset, low_rel, prompt)
|
| 76 |
+
method = method_from_row(row)
|
| 77 |
+
candidate_key = (dataset, low_rel, high_rel, prompt)
|
| 78 |
+
if candidate_key in seen:
|
| 79 |
+
continue
|
| 80 |
+
seen.add(candidate_key)
|
| 81 |
+
|
| 82 |
+
sample_id = str(row.get("sample_id", "") or stable_id(dataset, low_rel, high_rel, prompt))
|
| 83 |
+
candidate_id = stable_id(dataset, sample_id, low_rel, high_rel, prompt, length=20)
|
| 84 |
+
|
| 85 |
+
rows.append(
|
| 86 |
+
{
|
| 87 |
+
"dataset": dataset,
|
| 88 |
+
"group_id": group_id,
|
| 89 |
+
"candidate_id": candidate_id,
|
| 90 |
+
"sample_id": sample_id,
|
| 91 |
+
"row_index": row.get("row_index", ""),
|
| 92 |
+
"method": method,
|
| 93 |
+
"category": rel_category(row),
|
| 94 |
+
"instruction": prompt,
|
| 95 |
+
"source_rel": low_rel,
|
| 96 |
+
"edited_rel": high_rel,
|
| 97 |
+
"source_video": local_path(
|
| 98 |
+
repo_root,
|
| 99 |
+
str(row.get("low_materialized") or row.get("low_video_path") or row.get("low") or ""),
|
| 100 |
+
),
|
| 101 |
+
"edited_video": local_path(
|
| 102 |
+
repo_root,
|
| 103 |
+
str(row.get("high_materialized") or row.get("high_video_path") or row.get("high") or ""),
|
| 104 |
+
),
|
| 105 |
+
"remote_source_video": str(row.get("low_video_path", "") or ""),
|
| 106 |
+
"remote_edited_video": str(row.get("high_video_path", "") or ""),
|
| 107 |
+
}
|
| 108 |
+
)
|
| 109 |
+
return rows
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 113 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 115 |
+
for row in rows:
|
| 116 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def write_metrics_manifest(path: Path, rows: list[dict[str, Any]], prefer_remote: bool) -> None:
|
| 120 |
+
metrics_rows = []
|
| 121 |
+
for row in rows:
|
| 122 |
+
source = row["remote_source_video"] if prefer_remote and row["remote_source_video"] else row["source_video"]
|
| 123 |
+
edited = row["remote_edited_video"] if prefer_remote and row["remote_edited_video"] else row["edited_video"]
|
| 124 |
+
metrics_rows.append(
|
| 125 |
+
{
|
| 126 |
+
"split": row["dataset"],
|
| 127 |
+
"sample_id": row["candidate_id"],
|
| 128 |
+
"method": row["method"],
|
| 129 |
+
"instruction": row["instruction"],
|
| 130 |
+
"source_video": source,
|
| 131 |
+
"edited_video": edited,
|
| 132 |
+
}
|
| 133 |
+
)
|
| 134 |
+
write_jsonl(path, metrics_rows)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def main() -> None:
|
| 138 |
+
parser = argparse.ArgumentParser()
|
| 139 |
+
parser.add_argument("--repo-root", type=Path, default=Path.cwd())
|
| 140 |
+
parser.add_argument("--manifest", type=Path, action="append", default=[])
|
| 141 |
+
parser.add_argument("--output", type=Path, default=Path("out/aesthetic_rm/ditto_candidates.jsonl"))
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--metrics-manifest",
|
| 144 |
+
type=Path,
|
| 145 |
+
default=Path("out/aesthetic_rm/ditto_candidates_for_metrics.jsonl"),
|
| 146 |
+
help="JSONL compatible with reference/benchmarks/edit/run_traditional_metrics.py.",
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument("--prefer-remote-paths", action="store_true")
|
| 149 |
+
args = parser.parse_args()
|
| 150 |
+
|
| 151 |
+
manifest_paths = args.manifest or [Path(p) for p in DEFAULT_MANIFESTS]
|
| 152 |
+
rows = build_rows(args.repo_root, manifest_paths)
|
| 153 |
+
write_jsonl(args.output, rows)
|
| 154 |
+
write_metrics_manifest(args.metrics_manifest, rows, args.prefer_remote_paths)
|
| 155 |
+
|
| 156 |
+
group_count = len({row["group_id"] for row in rows})
|
| 157 |
+
multi_group_count = 0
|
| 158 |
+
counts: dict[str, int] = {}
|
| 159 |
+
for row in rows:
|
| 160 |
+
counts[row["group_id"]] = counts.get(row["group_id"], 0) + 1
|
| 161 |
+
multi_group_count = sum(1 for value in counts.values() if value >= 2)
|
| 162 |
+
|
| 163 |
+
print(f"wrote {len(rows)} candidates -> {args.output}")
|
| 164 |
+
print(f"wrote metrics manifest -> {args.metrics_manifest}")
|
| 165 |
+
print(f"groups={group_count}, groups_with_2+_candidates={multi_group_count}")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
main()
|
benchmarks/critic/aesthetic_rm/derive_pairwise_from_scores.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Derive pairwise aesthetic preferences from pointwise 1-4 scores."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
DIMENSIONS = [
|
| 14 |
+
"narrative_emotional_fit",
|
| 15 |
+
"style_world_consistency",
|
| 16 |
+
"composition_lighting_design",
|
| 17 |
+
"color_texture_refinement",
|
| 18 |
+
"visual_hierarchy_readability",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 23 |
+
rows = []
|
| 24 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 25 |
+
for line in handle:
|
| 26 |
+
if line.strip():
|
| 27 |
+
rows.append(json.loads(line))
|
| 28 |
+
return rows
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 32 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 34 |
+
for row in rows:
|
| 35 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def score(row: dict[str, Any]) -> float:
|
| 39 |
+
if row.get("overall_aesthetic_score") not in (None, ""):
|
| 40 |
+
return float(row["overall_aesthetic_score"])
|
| 41 |
+
scores = row.get("scores", {})
|
| 42 |
+
return sum(float(scores[d]) for d in DIMENSIONS) / len(DIMENSIONS)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main() -> None:
|
| 46 |
+
parser = argparse.ArgumentParser()
|
| 47 |
+
parser.add_argument("--scores", type=Path, required=True)
|
| 48 |
+
parser.add_argument("--output", type=Path, default=Path("out/aesthetic_rm/aesthetic_pairwise.jsonl"))
|
| 49 |
+
parser.add_argument("--winner-margin", type=float, default=0.6)
|
| 50 |
+
parser.add_argument("--tie-margin", type=float, default=0.3)
|
| 51 |
+
parser.add_argument("--dimension-margin", type=float, default=1.0)
|
| 52 |
+
parser.add_argument("--max-pairs-per-group", type=int, default=12)
|
| 53 |
+
args = parser.parse_args()
|
| 54 |
+
|
| 55 |
+
rows = [row for row in read_jsonl(args.scores) if not row.get("api_error") and row.get("scores")]
|
| 56 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 57 |
+
for row in rows:
|
| 58 |
+
groups[row["group_id"]].append(row)
|
| 59 |
+
|
| 60 |
+
pairs = []
|
| 61 |
+
for group_id, group in groups.items():
|
| 62 |
+
if len(group) < 2:
|
| 63 |
+
continue
|
| 64 |
+
count = 0
|
| 65 |
+
for i in range(len(group)):
|
| 66 |
+
for j in range(i + 1, len(group)):
|
| 67 |
+
a, b = group[i], group[j]
|
| 68 |
+
sa, sb = score(a), score(b)
|
| 69 |
+
diff = sa - sb
|
| 70 |
+
if abs(diff) < args.tie_margin:
|
| 71 |
+
preference = "tie"
|
| 72 |
+
winner = ""
|
| 73 |
+
loser = ""
|
| 74 |
+
elif abs(diff) >= args.winner_margin:
|
| 75 |
+
winner, loser = (a, b) if diff > 0 else (b, a)
|
| 76 |
+
preference = "winner"
|
| 77 |
+
winner = winner["candidate_id"]
|
| 78 |
+
loser = loser["candidate_id"]
|
| 79 |
+
else:
|
| 80 |
+
continue
|
| 81 |
+
|
| 82 |
+
dim_preferences = []
|
| 83 |
+
for dim in DIMENSIONS:
|
| 84 |
+
da = float(a["scores"][dim])
|
| 85 |
+
db = float(b["scores"][dim])
|
| 86 |
+
if abs(da - db) >= args.dimension_margin:
|
| 87 |
+
dim_preferences.append(
|
| 88 |
+
{
|
| 89 |
+
"dimension": dim,
|
| 90 |
+
"winner": a["candidate_id"] if da > db else b["candidate_id"],
|
| 91 |
+
"loser": b["candidate_id"] if da > db else a["candidate_id"],
|
| 92 |
+
"margin": abs(da - db),
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
pairs.append(
|
| 97 |
+
{
|
| 98 |
+
"pair_id": f"{group_id}_{count:03d}",
|
| 99 |
+
"group_id": group_id,
|
| 100 |
+
"candidate_a": a["candidate_id"],
|
| 101 |
+
"candidate_b": b["candidate_id"],
|
| 102 |
+
"score_a": sa,
|
| 103 |
+
"score_b": sb,
|
| 104 |
+
"preference": preference,
|
| 105 |
+
"winner": winner,
|
| 106 |
+
"loser": loser,
|
| 107 |
+
"dimension_preferences": dim_preferences,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
count += 1
|
| 111 |
+
if count >= args.max_pairs_per_group:
|
| 112 |
+
break
|
| 113 |
+
if count >= args.max_pairs_per_group:
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
write_jsonl(args.output, pairs)
|
| 117 |
+
print(f"wrote {len(pairs)} pairs -> {args.output}")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
main()
|
benchmarks/critic/aesthetic_rm/label_aesthetic_api.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Label selected candidates with an OpenAI-compatible multimodal API.
|
| 3 |
+
|
| 4 |
+
The API key is read from AESTHETIC_RM_API_KEY or --api-key-env. Do not commit
|
| 5 |
+
keys. Use --limit for smoke tests and --dry-run to inspect payloads.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import base64
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
DIMENSIONS = [
|
| 19 |
+
"narrative_emotional_fit",
|
| 20 |
+
"style_world_consistency",
|
| 21 |
+
"composition_lighting_design",
|
| 22 |
+
"color_texture_refinement",
|
| 23 |
+
"visual_hierarchy_readability",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
SYSTEM_PROMPT = """You are a strict cinematic/VFX aesthetic rater.
|
| 27 |
+
Score only the aesthetic and cinematic qualities requested below. Do not reward
|
| 28 |
+
basic prompt compliance, source preservation, or technical stability unless the
|
| 29 |
+
issue visibly affects the aesthetic judgment.
|
| 30 |
+
|
| 31 |
+
Scoring scale for every dimension:
|
| 32 |
+
4 = excellent / strongly successful
|
| 33 |
+
3 = good with minor issues
|
| 34 |
+
2 = weak with clear issues
|
| 35 |
+
1 = failed or harms the aesthetic goal
|
| 36 |
+
|
| 37 |
+
Rules:
|
| 38 |
+
- Score each dimension independently.
|
| 39 |
+
- There is no neutral middle score. Choose 2 or 3 when uncertain between weak and good.
|
| 40 |
+
- If a video matches multiple descriptions, assign the lowest applicable score.
|
| 41 |
+
- Do not give high artistic scores just because the image is sharp or expensive-looking.
|
| 42 |
+
- Do not give high color scores just because colors are saturated.
|
| 43 |
+
- Penalize visual clutter, incoherent style mixing, cheap texture/filter look, and unclear focal hierarchy.
|
| 44 |
+
- Return valid JSON only, with no markdown.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
USER_TEMPLATE = """Editing instruction / intended effect:
|
| 48 |
+
{instruction}
|
| 49 |
+
|
| 50 |
+
Evaluate the edited video frames on these five dimensions:
|
| 51 |
+
1. narrative_emotional_fit: whether the effect serves the theme, emotion, narrative, or character state.
|
| 52 |
+
2. style_world_consistency: whether it fits the world, era, genre, and style language such as classical, wuxia, sci-fi, realistic, fantasy, or cinematic.
|
| 53 |
+
3. composition_lighting_design: composition, contrast, lighting hierarchy, lens/cinematic design, and shot-level visual arrangement.
|
| 54 |
+
4. color_texture_refinement: color harmony, saturation control, material/texture/filter refinement, and whether it avoids cheap or generic looks.
|
| 55 |
+
5. visual_hierarchy_readability: whether the main visual intent is clear, focal hierarchy is readable, and important content is not obscured.
|
| 56 |
+
|
| 57 |
+
Return this exact JSON schema:
|
| 58 |
+
{{
|
| 59 |
+
"scores": {{
|
| 60 |
+
"narrative_emotional_fit": 1,
|
| 61 |
+
"style_world_consistency": 1,
|
| 62 |
+
"composition_lighting_design": 1,
|
| 63 |
+
"color_texture_refinement": 1,
|
| 64 |
+
"visual_hierarchy_readability": 1
|
| 65 |
+
}},
|
| 66 |
+
"overall_aesthetic_score": 1.0,
|
| 67 |
+
"uncertain": false,
|
| 68 |
+
"reason": "one concise sentence"
|
| 69 |
+
}}
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 74 |
+
rows = []
|
| 75 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 76 |
+
for line in handle:
|
| 77 |
+
if line.strip():
|
| 78 |
+
rows.append(json.loads(line))
|
| 79 |
+
return rows
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def append_jsonl(path: Path, row: dict[str, Any]) -> None:
|
| 83 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
with path.open("a", encoding="utf-8") as handle:
|
| 85 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def load_done_ids(path: Path) -> set[str]:
|
| 89 |
+
if not path.exists():
|
| 90 |
+
return set()
|
| 91 |
+
done = set()
|
| 92 |
+
for row in read_jsonl(path):
|
| 93 |
+
if row.get("candidate_id"):
|
| 94 |
+
done.add(str(row["candidate_id"]))
|
| 95 |
+
return done
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def sample_video_frames(video_path: Path, max_frames: int, resize: int) -> list[bytes]:
|
| 99 |
+
try:
|
| 100 |
+
import imageio.v3 as iio
|
| 101 |
+
from PIL import Image
|
| 102 |
+
except Exception as exc:
|
| 103 |
+
raise RuntimeError("Please install imageio, imageio-ffmpeg, and pillow") from exc
|
| 104 |
+
|
| 105 |
+
frames = [Image.fromarray(frame).convert("RGB") for frame in iio.imiter(str(video_path))]
|
| 106 |
+
if not frames:
|
| 107 |
+
raise RuntimeError(f"no frames decoded from {video_path}")
|
| 108 |
+
if max_frames < len(frames):
|
| 109 |
+
indices = [round(i * (len(frames) - 1) / (max_frames - 1)) for i in range(max_frames)] if max_frames > 1 else [len(frames) // 2]
|
| 110 |
+
frames = [frames[i] for i in indices]
|
| 111 |
+
output = []
|
| 112 |
+
for frame in frames:
|
| 113 |
+
if resize:
|
| 114 |
+
frame.thumbnail((resize, resize))
|
| 115 |
+
import io
|
| 116 |
+
|
| 117 |
+
buf = io.BytesIO()
|
| 118 |
+
frame.save(buf, format="JPEG", quality=85)
|
| 119 |
+
output.append(buf.getvalue())
|
| 120 |
+
return output
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def image_part(jpeg_bytes: bytes) -> dict[str, Any]:
|
| 124 |
+
encoded = base64.b64encode(jpeg_bytes).decode("ascii")
|
| 125 |
+
return {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded}"}}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def parse_json_response(text: str) -> dict[str, Any]:
|
| 129 |
+
text = text.strip()
|
| 130 |
+
if text.startswith("```"):
|
| 131 |
+
text = text.strip("`")
|
| 132 |
+
if text.startswith("json"):
|
| 133 |
+
text = text[4:].strip()
|
| 134 |
+
data = json.loads(text)
|
| 135 |
+
scores = data.get("scores", {})
|
| 136 |
+
for dim in DIMENSIONS:
|
| 137 |
+
value = int(scores[dim])
|
| 138 |
+
if value < 1 or value > 4:
|
| 139 |
+
raise ValueError(f"{dim} score out of range: {value}")
|
| 140 |
+
scores[dim] = value
|
| 141 |
+
data["scores"] = scores
|
| 142 |
+
data["overall_aesthetic_score"] = float(data.get("overall_aesthetic_score", sum(scores.values()) / len(scores)))
|
| 143 |
+
data["uncertain"] = bool(data.get("uncertain", False))
|
| 144 |
+
data["reason"] = str(data.get("reason", ""))[:500]
|
| 145 |
+
return data
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def estimate_cost(usage: Any, input_per_1m: float, output_per_1m: float) -> dict[str, Any]:
|
| 149 |
+
prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0) if usage else 0
|
| 150 |
+
completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0) if usage else 0
|
| 151 |
+
cost = prompt_tokens / 1_000_000 * input_per_1m + completion_tokens / 1_000_000 * output_per_1m
|
| 152 |
+
return {
|
| 153 |
+
"prompt_tokens": prompt_tokens,
|
| 154 |
+
"completion_tokens": completion_tokens,
|
| 155 |
+
"estimated_cost_usd": round(cost, 6),
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def main() -> None:
|
| 160 |
+
parser = argparse.ArgumentParser()
|
| 161 |
+
parser.add_argument("--input", type=Path, required=True)
|
| 162 |
+
parser.add_argument("--output", type=Path, default=Path("out/aesthetic_rm/aesthetic_scores.jsonl"))
|
| 163 |
+
parser.add_argument("--base-url", default="http://35.220.164.252:3888/v1")
|
| 164 |
+
parser.add_argument("--api-key-env", default="AESTHETIC_RM_API_KEY")
|
| 165 |
+
parser.add_argument("--model", default="gpt-4o")
|
| 166 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 167 |
+
parser.add_argument("--max-frames", type=int, default=4)
|
| 168 |
+
parser.add_argument("--resize", type=int, default=512)
|
| 169 |
+
parser.add_argument("--prefer-remote-paths", action="store_true")
|
| 170 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 171 |
+
parser.add_argument("--input-cost-per-1m", type=float, default=0.0)
|
| 172 |
+
parser.add_argument("--output-cost-per-1m", type=float, default=0.0)
|
| 173 |
+
args = parser.parse_args()
|
| 174 |
+
|
| 175 |
+
rows = read_jsonl(args.input)
|
| 176 |
+
done = load_done_ids(args.output)
|
| 177 |
+
if args.limit:
|
| 178 |
+
rows = rows[: args.limit]
|
| 179 |
+
|
| 180 |
+
if args.dry_run:
|
| 181 |
+
print(f"dry run: would process {len([r for r in rows if r['candidate_id'] not in done])} rows")
|
| 182 |
+
if rows:
|
| 183 |
+
print(json.dumps({k: rows[0].get(k) for k in ("candidate_id", "instruction", "edited_video")}, ensure_ascii=False, indent=2))
|
| 184 |
+
return
|
| 185 |
+
|
| 186 |
+
api_key = os.environ.get(args.api_key_env)
|
| 187 |
+
if not api_key:
|
| 188 |
+
raise RuntimeError(f"Set {args.api_key_env} before calling the API")
|
| 189 |
+
|
| 190 |
+
from openai import OpenAI
|
| 191 |
+
|
| 192 |
+
client = OpenAI(api_key=api_key, base_url=args.base_url)
|
| 193 |
+
processed = 0
|
| 194 |
+
total_prompt_tokens = 0
|
| 195 |
+
total_completion_tokens = 0
|
| 196 |
+
total_cost = 0.0
|
| 197 |
+
|
| 198 |
+
for row in rows:
|
| 199 |
+
if row["candidate_id"] in done:
|
| 200 |
+
continue
|
| 201 |
+
video_value = row.get("remote_edited_video") if args.prefer_remote_paths and row.get("remote_edited_video") else row.get("edited_video")
|
| 202 |
+
video_path = Path(str(video_value))
|
| 203 |
+
frames = sample_video_frames(video_path, args.max_frames, args.resize)
|
| 204 |
+
content = [{"type": "text", "text": USER_TEMPLATE.format(instruction=row["instruction"])}]
|
| 205 |
+
content.extend(image_part(frame) for frame in frames)
|
| 206 |
+
|
| 207 |
+
try:
|
| 208 |
+
response = client.chat.completions.create(
|
| 209 |
+
model=args.model,
|
| 210 |
+
messages=[
|
| 211 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 212 |
+
{"role": "user", "content": content},
|
| 213 |
+
],
|
| 214 |
+
temperature=0,
|
| 215 |
+
response_format={"type": "json_object"},
|
| 216 |
+
)
|
| 217 |
+
text = response.choices[0].message.content or "{}"
|
| 218 |
+
parsed = parse_json_response(text)
|
| 219 |
+
usage_cost = estimate_cost(response.usage, args.input_cost_per_1m, args.output_cost_per_1m)
|
| 220 |
+
result = {**row, **parsed, "api_model": args.model, **usage_cost, "api_error": ""}
|
| 221 |
+
except Exception as exc:
|
| 222 |
+
result = {**row, "api_model": args.model, "api_error": f"{type(exc).__name__}: {exc}"}
|
| 223 |
+
|
| 224 |
+
append_jsonl(args.output, result)
|
| 225 |
+
processed += 1
|
| 226 |
+
total_prompt_tokens += int(result.get("prompt_tokens", 0) or 0)
|
| 227 |
+
total_completion_tokens += int(result.get("completion_tokens", 0) or 0)
|
| 228 |
+
total_cost += float(result.get("estimated_cost_usd", 0.0) or 0.0)
|
| 229 |
+
print(
|
| 230 |
+
f"processed={processed} candidate={row['candidate_id']} "
|
| 231 |
+
f"error={bool(result.get('api_error'))} cost=${float(result.get('estimated_cost_usd', 0.0) or 0.0):.6f}",
|
| 232 |
+
flush=True,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
summary = {
|
| 236 |
+
"processed": processed,
|
| 237 |
+
"prompt_tokens": total_prompt_tokens,
|
| 238 |
+
"completion_tokens": total_completion_tokens,
|
| 239 |
+
"estimated_cost_usd": round(total_cost, 6),
|
| 240 |
+
"output": str(args.output),
|
| 241 |
+
}
|
| 242 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|
benchmarks/critic/aesthetic_rm/select_aesthetic_candidates.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Select a 5k-ish aesthetic-labeling set using non-aesthetic metrics.
|
| 3 |
+
|
| 4 |
+
This script intentionally uses traditional/pretrained metrics as gates and
|
| 5 |
+
keeps aesthetic metrics only for stratification. The goal is to reduce
|
| 6 |
+
non-aesthetic confounds before training a custom VFX/cinematic aesthetic RM.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
+
from collections import defaultdict, deque
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from statistics import median
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
GATE_METRICS = {
|
| 22 |
+
"source_edit_l1": "lower",
|
| 23 |
+
"global_ssim": "higher",
|
| 24 |
+
"lpips_source_edit": "lower",
|
| 25 |
+
"clip_source_edit_similarity": "higher",
|
| 26 |
+
"edited_frame_diff_mae": "lower",
|
| 27 |
+
"temporal_flicker_score": "higher",
|
| 28 |
+
"clip_frame_consistency": "higher",
|
| 29 |
+
"dino_frame_consistency": "higher",
|
| 30 |
+
"clip_t": "higher",
|
| 31 |
+
"pyiqa_musiq": "higher",
|
| 32 |
+
"pyiqa_niqe": "lower",
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
AESTHETIC_STRATA_METRICS = ("laion_aesthetic", "pyiqa_musiq")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 39 |
+
rows = []
|
| 40 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 41 |
+
for line in handle:
|
| 42 |
+
if line.strip():
|
| 43 |
+
rows.append(json.loads(line))
|
| 44 |
+
return rows
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def to_float(value: Any) -> float | None:
|
| 48 |
+
if value is None or value == "":
|
| 49 |
+
return None
|
| 50 |
+
try:
|
| 51 |
+
result = float(value)
|
| 52 |
+
except (TypeError, ValueError):
|
| 53 |
+
return None
|
| 54 |
+
if math.isnan(result) or math.isinf(result):
|
| 55 |
+
return None
|
| 56 |
+
return result
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def percentile(values: list[float], q: float) -> float:
|
| 60 |
+
if not values:
|
| 61 |
+
return float("nan")
|
| 62 |
+
values = sorted(values)
|
| 63 |
+
index = (len(values) - 1) * q
|
| 64 |
+
lo = math.floor(index)
|
| 65 |
+
hi = math.ceil(index)
|
| 66 |
+
if lo == hi:
|
| 67 |
+
return values[lo]
|
| 68 |
+
return values[lo] * (hi - index) + values[hi] * (index - lo)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_metrics(path: Path) -> dict[str, dict[str, Any]]:
|
| 72 |
+
with path.open("r", encoding="utf-8", newline="") as handle:
|
| 73 |
+
reader = csv.DictReader(handle)
|
| 74 |
+
return {str(row.get("sample_id", "")): row for row in reader if row.get("sample_id")}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def normalized(value: float | None, values: list[float], direction: str) -> float | None:
|
| 78 |
+
if value is None or not values:
|
| 79 |
+
return None
|
| 80 |
+
lo = percentile(values, 0.05)
|
| 81 |
+
hi = percentile(values, 0.95)
|
| 82 |
+
if hi <= lo:
|
| 83 |
+
return 0.5
|
| 84 |
+
score = (value - lo) / (hi - lo)
|
| 85 |
+
score = max(0.0, min(1.0, score))
|
| 86 |
+
return 1.0 - score if direction == "lower" else score
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def band(value: float | None, cuts: tuple[float, float]) -> str:
|
| 90 |
+
if value is None:
|
| 91 |
+
return "unknown"
|
| 92 |
+
if value < cuts[0]:
|
| 93 |
+
return "low"
|
| 94 |
+
if value < cuts[1]:
|
| 95 |
+
return "mid"
|
| 96 |
+
return "high"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def enrich_rows(candidates: list[dict[str, Any]], metrics: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
|
| 100 |
+
metric_values: dict[str, list[float]] = defaultdict(list)
|
| 101 |
+
for row in metrics.values():
|
| 102 |
+
if row.get("error"):
|
| 103 |
+
continue
|
| 104 |
+
for metric in set(GATE_METRICS) | set(AESTHETIC_STRATA_METRICS):
|
| 105 |
+
value = to_float(row.get(metric))
|
| 106 |
+
if value is not None:
|
| 107 |
+
metric_values[metric].append(value)
|
| 108 |
+
|
| 109 |
+
enriched = []
|
| 110 |
+
for row in candidates:
|
| 111 |
+
item = dict(row)
|
| 112 |
+
metric_row = metrics.get(str(row["candidate_id"]), {})
|
| 113 |
+
item["metric_error"] = metric_row.get("error", "")
|
| 114 |
+
gate_scores = []
|
| 115 |
+
failed_gates = []
|
| 116 |
+
for metric, direction in GATE_METRICS.items():
|
| 117 |
+
value = to_float(metric_row.get(metric))
|
| 118 |
+
item[metric] = value
|
| 119 |
+
score = normalized(value, metric_values.get(metric, []), direction)
|
| 120 |
+
if score is not None:
|
| 121 |
+
gate_scores.append(score)
|
| 122 |
+
if score < 0.20:
|
| 123 |
+
failed_gates.append(metric)
|
| 124 |
+
item["non_aesthetic_gate_score"] = sum(gate_scores) / len(gate_scores) if gate_scores else 0.0
|
| 125 |
+
item["failed_gate_count"] = len(failed_gates)
|
| 126 |
+
item["failed_gates"] = failed_gates
|
| 127 |
+
for metric in AESTHETIC_STRATA_METRICS:
|
| 128 |
+
item[metric] = to_float(metric_row.get(metric))
|
| 129 |
+
enriched.append(item)
|
| 130 |
+
return enriched
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def choose_group_candidates(group: list[dict[str, Any]], max_per_group: int) -> list[dict[str, Any]]:
|
| 134 |
+
group = sorted(group, key=lambda x: x["non_aesthetic_gate_score"], reverse=True)
|
| 135 |
+
return group[:max_per_group]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def select_rows(
|
| 139 |
+
rows: list[dict[str, Any]],
|
| 140 |
+
target: int,
|
| 141 |
+
max_failed_gates: int,
|
| 142 |
+
min_gate_score: float,
|
| 143 |
+
min_group_size: int,
|
| 144 |
+
max_per_group: int,
|
| 145 |
+
) -> list[dict[str, Any]]:
|
| 146 |
+
usable = [
|
| 147 |
+
row
|
| 148 |
+
for row in rows
|
| 149 |
+
if not row.get("metric_error")
|
| 150 |
+
and int(row["failed_gate_count"]) <= max_failed_gates
|
| 151 |
+
and float(row["non_aesthetic_gate_score"]) >= min_gate_score
|
| 152 |
+
]
|
| 153 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 154 |
+
for row in usable:
|
| 155 |
+
groups[row["group_id"]].append(row)
|
| 156 |
+
|
| 157 |
+
preferred_groups = [group for group in groups.values() if len(group) >= min_group_size]
|
| 158 |
+
fallback_groups = [group for group in groups.values() if len(group) < min_group_size]
|
| 159 |
+
|
| 160 |
+
aesthetic_values = [row.get("laion_aesthetic") for row in usable if row.get("laion_aesthetic") is not None]
|
| 161 |
+
if len(aesthetic_values) >= 10:
|
| 162 |
+
cuts = (percentile(aesthetic_values, 1 / 3), percentile(aesthetic_values, 2 / 3))
|
| 163 |
+
else:
|
| 164 |
+
musiq_values = [row.get("pyiqa_musiq") for row in usable if row.get("pyiqa_musiq") is not None]
|
| 165 |
+
cuts = (percentile(musiq_values, 1 / 3), percentile(musiq_values, 2 / 3)) if musiq_values else (0.33, 0.66)
|
| 166 |
+
|
| 167 |
+
buckets: dict[tuple[str, str, str], deque[list[dict[str, Any]]]] = defaultdict(deque)
|
| 168 |
+
for group in preferred_groups:
|
| 169 |
+
chosen = choose_group_candidates(group, max_per_group)
|
| 170 |
+
med_gate = median([float(row["non_aesthetic_gate_score"]) for row in chosen])
|
| 171 |
+
aesthetic_value = chosen[0].get("laion_aesthetic")
|
| 172 |
+
if aesthetic_value is None:
|
| 173 |
+
aesthetic_value = chosen[0].get("pyiqa_musiq")
|
| 174 |
+
key = (
|
| 175 |
+
str(chosen[0].get("category", "")),
|
| 176 |
+
str(chosen[0].get("method", "")),
|
| 177 |
+
band(aesthetic_value, cuts),
|
| 178 |
+
)
|
| 179 |
+
for row in chosen:
|
| 180 |
+
row["selection_reason"] = f"grouped_candidate;gate={med_gate:.3f};aesthetic_band={key[2]}"
|
| 181 |
+
buckets[key].append(chosen)
|
| 182 |
+
|
| 183 |
+
selected: list[dict[str, Any]] = []
|
| 184 |
+
while buckets and len(selected) < target:
|
| 185 |
+
for key in list(buckets.keys()):
|
| 186 |
+
if len(selected) >= target:
|
| 187 |
+
break
|
| 188 |
+
queue = buckets[key]
|
| 189 |
+
if not queue:
|
| 190 |
+
del buckets[key]
|
| 191 |
+
continue
|
| 192 |
+
group = queue.popleft()
|
| 193 |
+
remaining = target - len(selected)
|
| 194 |
+
selected.extend(group[:remaining])
|
| 195 |
+
if not queue:
|
| 196 |
+
del buckets[key]
|
| 197 |
+
|
| 198 |
+
if len(selected) < target:
|
| 199 |
+
selected_ids = {row["candidate_id"] for row in selected}
|
| 200 |
+
fallback = []
|
| 201 |
+
for group in fallback_groups:
|
| 202 |
+
fallback.extend(choose_group_candidates(group, max_per_group))
|
| 203 |
+
fallback = sorted(fallback, key=lambda x: x["non_aesthetic_gate_score"], reverse=True)
|
| 204 |
+
for row in fallback:
|
| 205 |
+
if len(selected) >= target:
|
| 206 |
+
break
|
| 207 |
+
if row["candidate_id"] not in selected_ids:
|
| 208 |
+
row["selection_reason"] = "fallback_single_candidate"
|
| 209 |
+
selected.append(row)
|
| 210 |
+
selected_ids.add(row["candidate_id"])
|
| 211 |
+
|
| 212 |
+
return selected[:target]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 216 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 217 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 218 |
+
for row in rows:
|
| 219 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def write_pairwise_plan(path: Path, rows: list[dict[str, Any]], max_pairs_per_group: int) -> None:
|
| 223 |
+
groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
| 224 |
+
for row in rows:
|
| 225 |
+
groups[row["group_id"]].append(row)
|
| 226 |
+
pairs = []
|
| 227 |
+
for group_id, group in groups.items():
|
| 228 |
+
if len(group) < 2:
|
| 229 |
+
continue
|
| 230 |
+
group = sorted(group, key=lambda x: (x.get("method", ""), x["candidate_id"]))
|
| 231 |
+
count = 0
|
| 232 |
+
for i in range(len(group)):
|
| 233 |
+
for j in range(i + 1, len(group)):
|
| 234 |
+
pairs.append(
|
| 235 |
+
{
|
| 236 |
+
"pair_id": f"{group_id}_{count:03d}",
|
| 237 |
+
"group_id": group_id,
|
| 238 |
+
"candidate_a": group[i]["candidate_id"],
|
| 239 |
+
"candidate_b": group[j]["candidate_id"],
|
| 240 |
+
"status": "pending_pointwise_scores",
|
| 241 |
+
}
|
| 242 |
+
)
|
| 243 |
+
count += 1
|
| 244 |
+
if count >= max_pairs_per_group:
|
| 245 |
+
break
|
| 246 |
+
if count >= max_pairs_per_group:
|
| 247 |
+
break
|
| 248 |
+
write_jsonl(path, pairs)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def main() -> None:
|
| 252 |
+
parser = argparse.ArgumentParser()
|
| 253 |
+
parser.add_argument("--candidates", type=Path, required=True)
|
| 254 |
+
parser.add_argument("--metrics", type=Path, required=True)
|
| 255 |
+
parser.add_argument("--output", type=Path, default=Path("out/aesthetic_rm/selected_5k.jsonl"))
|
| 256 |
+
parser.add_argument("--pairwise-plan", type=Path, default=Path("out/aesthetic_rm/pairwise_plan.jsonl"))
|
| 257 |
+
parser.add_argument("--target", type=int, default=5000)
|
| 258 |
+
parser.add_argument("--max-failed-gates", type=int, default=2)
|
| 259 |
+
parser.add_argument("--min-gate-score", type=float, default=0.35)
|
| 260 |
+
parser.add_argument("--min-group-size", type=int, default=2)
|
| 261 |
+
parser.add_argument("--max-per-group", type=int, default=4)
|
| 262 |
+
parser.add_argument("--max-pairs-per-group", type=int, default=6)
|
| 263 |
+
args = parser.parse_args()
|
| 264 |
+
|
| 265 |
+
candidates = read_jsonl(args.candidates)
|
| 266 |
+
metrics = load_metrics(args.metrics)
|
| 267 |
+
enriched = enrich_rows(candidates, metrics)
|
| 268 |
+
selected = select_rows(
|
| 269 |
+
enriched,
|
| 270 |
+
args.target,
|
| 271 |
+
args.max_failed_gates,
|
| 272 |
+
args.min_gate_score,
|
| 273 |
+
args.min_group_size,
|
| 274 |
+
args.max_per_group,
|
| 275 |
+
)
|
| 276 |
+
write_jsonl(args.output, selected)
|
| 277 |
+
write_pairwise_plan(args.pairwise_plan, selected, args.max_pairs_per_group)
|
| 278 |
+
|
| 279 |
+
groups = defaultdict(int)
|
| 280 |
+
for row in selected:
|
| 281 |
+
groups[row["group_id"]] += 1
|
| 282 |
+
print(f"selected {len(selected)} rows -> {args.output}")
|
| 283 |
+
print(f"selected groups={len(groups)}, grouped rows={sum(v for v in groups.values() if v >= 2)}")
|
| 284 |
+
print(f"pairwise plan -> {args.pairwise_plan}")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
if __name__ == "__main__":
|
| 288 |
+
main()
|