Ouzhang commited on
Commit
6183886
·
verified ·
1 Parent(s): f84bdd3

Upload folder using huggingface_hub

Browse files
top5000_clipframe_dino_clipt_dedup/README_gemini_label.md CHANGED
@@ -1,6 +1,14 @@
1
  # Gemini Pro Aesthetic Labeling
2
 
3
  This directory contains the deduplicated Top5000 high/low video package.
 
 
 
 
 
 
 
 
4
 
5
  Generate API input and run a 10-item smoke test:
6
 
 
1
  # Gemini Pro Aesthetic Labeling
2
 
3
  This directory contains the deduplicated Top5000 high/low video package.
4
+ It is standalone: the runner uses scripts inside this directory, not
5
+ `reference/benchmarks/critic/aesthetic_rm/label_aesthetic_api.py`.
6
+
7
+ Required Python packages:
8
+
9
+ ```bash
10
+ pip install openai imageio imageio-ffmpeg pillow
11
+ ```
12
 
13
  Generate API input and run a 10-item smoke test:
14
 
top5000_clipframe_dino_clipt_dedup/__pycache__/label_aesthetic_standalone.cpython-314.pyc ADDED
Binary file (19.5 kB). View file
 
top5000_clipframe_dino_clipt_dedup/label_aesthetic_standalone.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import base64
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ DIMENSIONS = [
13
+ "narrative_emotional_fit",
14
+ "style_world_consistency",
15
+ "composition_lighting_design",
16
+ "color_texture_refinement",
17
+ "visual_hierarchy_readability",
18
+ ]
19
+
20
+ SYSTEM_PROMPT = """You are a strict cinematic/VFX aesthetic rater.
21
+ You are doing pointwise standalone aesthetic scoring: you see sampled frames
22
+ from the edited video, but you do not see the source video. Use the editing
23
+ instruction only as weak context for the intended visual direction. Do not judge
24
+ whether the edit accurately followed the instruction, because the source video is
25
+ not provided.
26
+
27
+ Scoring scale for every dimension:
28
+ 4 = excellent / strongly successful
29
+ 3 = good with minor issues
30
+ 2 = weak with clear issues
31
+ 1 = failed or harms the aesthetic goal
32
+
33
+ Rules:
34
+ - Score each dimension independently.
35
+ - There is no neutral middle score. Choose 2 or 3 when uncertain between weak and good.
36
+ - If a video matches multiple descriptions, assign the lowest applicable score.
37
+ - For object removal, cleanup, denoising, de-watermarking, or other utility edits,
38
+ a seamless and visually natural result can be aesthetically successful even if
39
+ it is not dramatic or cinematic.
40
+ - Do not penalize a candidate because the requested edit removes an interesting
41
+ object or makes the scene simpler.
42
+ - Do not give high artistic scores just because the image is sharp or expensive-looking.
43
+ - Do not give high color scores just because colors are saturated.
44
+ - Penalize visible inpainting seams, visual clutter, incoherent style mixing,
45
+ cheap texture/filter look, and unclear focal hierarchy when they are visible in
46
+ the edited frames.
47
+ - Return valid JSON only, with no markdown.
48
+ """
49
+
50
+ USER_TEMPLATE = """Editing instruction / intended effect:
51
+ {instruction}
52
+
53
+ Inferred task type:
54
+ {task_type}
55
+
56
+ Important: you do not see the source video. Do not evaluate whether the edit was
57
+ completed relative to the source. Evaluate the final edited video as a standalone
58
+ visual result. For removal or cleanup tasks, invisible/seamless blending is a
59
+ positive aesthetic outcome.
60
+
61
+ Evaluate the edited video frames on these five dimensions:
62
+ 1. narrative_emotional_fit: whether the final edited result naturally integrates with the scene mood, emotional tone, and visual context without artificial or distracting anomalies.
63
+ 2. style_world_consistency: whether the final visual style fits the world, era, genre, and style language such as classical, wuxia, sci-fi, realistic, fantasy, or cinematic.
64
+ 3. composition_lighting_design: composition, contrast, lighting hierarchy, lens/cinematic design, and shot-level visual arrangement.
65
+ 4. color_texture_refinement: color harmony, saturation control, material/texture/filter refinement, and whether it avoids cheap or generic looks.
66
+ 5. visual_hierarchy_readability: whether the main visual intent is clear, focal hierarchy is readable, and important content is not obscured.
67
+
68
+ "overall_aesthetic_score" should be a holistic assessment of final visual
69
+ quality from 1.0 to 4.0, not a simple mathematical average of the five
70
+ dimensions.
71
+
72
+ Return this exact JSON schema:
73
+ {{
74
+ "scores": {{
75
+ "narrative_emotional_fit": 1,
76
+ "style_world_consistency": 1,
77
+ "composition_lighting_design": 1,
78
+ "color_texture_refinement": 1,
79
+ "visual_hierarchy_readability": 1
80
+ }},
81
+ "overall_aesthetic_score": 1.0,
82
+ "uncertain": false,
83
+ "reason": "one concise sentence"
84
+ }}
85
+ """
86
+
87
+
88
+ def infer_task_type(instruction: str) -> str:
89
+ text = instruction.lower()
90
+ if any(word in text for word in ["remove", "erase", "delete", "hide", "clean up", "de-watermark", "watermark", "logo"]):
91
+ return "removal_or_cleanup"
92
+ if any(word in text for word in ["add", "insert", "place", "put ", "introduce", "include"]):
93
+ return "addition_or_insertion"
94
+ if any(word in text for word in ["replace", "swap", "change into", "turn into", "transform", "convert"]):
95
+ return "replacement_or_transformation"
96
+ if any(word in text for word in ["style", "aesthetic", "cinematic", "film", "color", "lighting", "tone", "grain", "texture"]):
97
+ return "style_or_look_change"
98
+ if any(word in text for word in ["enhance", "restore", "sharpen", "denoise", "improve", "refine"]):
99
+ return "quality_refinement"
100
+ return "general_edit"
101
+
102
+
103
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
104
+ rows: list[dict[str, Any]] = []
105
+ with path.open("r", encoding="utf-8") as handle:
106
+ for line in handle:
107
+ text = line.strip()
108
+ if text:
109
+ rows.append(json.loads(text))
110
+ return rows
111
+
112
+
113
+ def append_jsonl(path: Path, row: dict[str, Any]) -> None:
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ with path.open("a", encoding="utf-8") as handle:
116
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
117
+
118
+
119
+ def load_done_ids(path: Path) -> set[str]:
120
+ if not path.exists():
121
+ return set()
122
+ done: set[str] = set()
123
+ for row in read_jsonl(path):
124
+ if row.get("candidate_id") and not row.get("api_error"):
125
+ done.add(str(row["candidate_id"]))
126
+ return done
127
+
128
+
129
+ def sample_video_frames(video_path: Path, max_frames: int, resize: int) -> list[bytes]:
130
+ try:
131
+ import imageio.v3 as iio
132
+ from PIL import Image
133
+ except Exception as exc:
134
+ raise RuntimeError("Please install imageio, imageio-ffmpeg, and pillow") from exc
135
+
136
+ frames = [Image.fromarray(frame).convert("RGB") for frame in iio.imiter(str(video_path))]
137
+ if not frames:
138
+ raise RuntimeError(f"no frames decoded from {video_path}")
139
+ if max_frames < len(frames):
140
+ if max_frames > 1:
141
+ indices = [round(i * (len(frames) - 1) / (max_frames - 1)) for i in range(max_frames)]
142
+ else:
143
+ indices = [len(frames) // 2]
144
+ frames = [frames[i] for i in indices]
145
+
146
+ output: list[bytes] = []
147
+ for frame in frames:
148
+ if resize:
149
+ frame.thumbnail((resize, resize))
150
+ import io
151
+
152
+ buf = io.BytesIO()
153
+ frame.save(buf, format="JPEG", quality=85)
154
+ output.append(buf.getvalue())
155
+ return output
156
+
157
+
158
+ def build_messages(instruction: str, frames: list[bytes]) -> list[dict[str, Any]]:
159
+ content: list[dict[str, Any]] = [
160
+ {"type": "text", "text": USER_TEMPLATE.format(instruction=instruction, task_type=infer_task_type(instruction))}
161
+ ]
162
+ for frame in frames:
163
+ encoded = base64.b64encode(frame).decode("ascii")
164
+ content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encoded}"}})
165
+ return [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": content}]
166
+
167
+
168
+ def parse_json_response(text: str) -> dict[str, Any]:
169
+ text = text.strip()
170
+ if text.startswith("```"):
171
+ text = text.strip("`")
172
+ if text.startswith("json"):
173
+ text = text[4:].strip()
174
+ if not text.startswith("{"):
175
+ start = text.find("{")
176
+ end = text.rfind("}")
177
+ if start >= 0 and end > start:
178
+ text = text[start : end + 1]
179
+ data = json.loads(text)
180
+ scores = data.get("scores", {})
181
+ for dim in DIMENSIONS:
182
+ value = int(scores[dim])
183
+ if value < 1 or value > 4:
184
+ raise ValueError(f"{dim} score out of range: {value}")
185
+ scores[dim] = value
186
+ data["scores"] = scores
187
+ data["overall_aesthetic_score"] = float(data.get("overall_aesthetic_score", sum(scores.values()) / len(scores)))
188
+ data["uncertain"] = bool(data.get("uncertain", False))
189
+ data["reason"] = str(data.get("reason", ""))[:500]
190
+ return data
191
+
192
+
193
+ def estimate_cost(usage: Any, input_per_1m: float, output_per_1m: float) -> dict[str, Any]:
194
+ prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0) if usage else 0
195
+ completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0) if usage else 0
196
+ total_tokens = int(getattr(usage, "total_tokens", 0) or prompt_tokens + completion_tokens) if usage else 0
197
+ cost = prompt_tokens / 1_000_000 * input_per_1m + completion_tokens / 1_000_000 * output_per_1m
198
+ return {
199
+ "prompt_tokens": prompt_tokens,
200
+ "completion_tokens": completion_tokens,
201
+ "total_tokens": total_tokens,
202
+ "estimated_cost_usd": round(cost, 6),
203
+ }
204
+
205
+
206
+ def main() -> None:
207
+ parser = argparse.ArgumentParser(description="Standalone Gemini/OpenAI-compatible aesthetic scorer.")
208
+ parser.add_argument("--input", type=Path, default=Path("aesthetic_api_input.jsonl"))
209
+ parser.add_argument("--output", type=Path, default=Path("aesthetic_scores_gemini_pro.jsonl"))
210
+ parser.add_argument("--base-url", default="http://35.220.164.252:3888/v1")
211
+ parser.add_argument("--api-key-env", default="AESTHETIC_RM_API_KEY")
212
+ parser.add_argument("--model", default="gemini-3.1-pro-preview-thinking")
213
+ parser.add_argument("--request-timeout", type=float, default=180.0)
214
+ parser.add_argument("--max-retries", type=int, default=3)
215
+ parser.add_argument("--limit", type=int, default=0)
216
+ parser.add_argument("--max-frames", type=int, default=4)
217
+ parser.add_argument("--resize", type=int, default=512)
218
+ parser.add_argument("--input-cost-per-1m", type=float, default=3.0)
219
+ parser.add_argument("--output-cost-per-1m", type=float, default=15.0)
220
+ args = parser.parse_args()
221
+
222
+ api_key = os.environ.get(args.api_key_env)
223
+ if not api_key:
224
+ raise RuntimeError(f"Set {args.api_key_env} before calling the API")
225
+
226
+ from openai import OpenAI
227
+
228
+ client = OpenAI(api_key=api_key, base_url=args.base_url, timeout=args.request_timeout, max_retries=args.max_retries)
229
+
230
+ rows = read_jsonl(args.input)
231
+ if args.limit:
232
+ rows = rows[: args.limit]
233
+ done = load_done_ids(args.output)
234
+ pending = [row for row in rows if str(row.get("candidate_id", "")) not in done]
235
+
236
+ processed = 0
237
+ total_prompt_tokens = 0
238
+ total_completion_tokens = 0
239
+ total_tokens = 0
240
+ total_cost = 0.0
241
+
242
+ for row in pending:
243
+ try:
244
+ frames = sample_video_frames(Path(str(row["edited_video"])), args.max_frames, args.resize)
245
+ response = client.chat.completions.create(
246
+ model=args.model,
247
+ messages=build_messages(str(row["instruction"]), frames),
248
+ temperature=0,
249
+ response_format={"type": "json_object"},
250
+ )
251
+ text = response.choices[0].message.content or "{}"
252
+ usage_cost = estimate_cost(response.usage, args.input_cost_per_1m, args.output_cost_per_1m)
253
+ parsed = parse_json_response(text)
254
+ result = {**row, **parsed, "api_model": args.model, "backend": "api", **usage_cost, "api_error": ""}
255
+ except Exception as exc:
256
+ result = {**row, "api_model": args.model, "backend": "api", "api_error": f"{type(exc).__name__}: {exc}"}
257
+
258
+ append_jsonl(args.output, result)
259
+ processed += 1
260
+ total_prompt_tokens += int(result.get("prompt_tokens", 0) or 0)
261
+ total_completion_tokens += int(result.get("completion_tokens", 0) or 0)
262
+ total_tokens += int(result.get("total_tokens", 0) or 0)
263
+ total_cost += float(result.get("estimated_cost_usd", 0.0) or 0.0)
264
+ print(
265
+ f"processed={processed} candidate={row.get('candidate_id')} "
266
+ f"error={bool(result.get('api_error'))} cost=${float(result.get('estimated_cost_usd', 0.0) or 0.0):.6f}",
267
+ flush=True,
268
+ )
269
+
270
+ print(json.dumps({"processed": processed, "prompt_tokens": total_prompt_tokens, "completion_tokens": total_completion_tokens, "total_tokens": total_tokens, "estimated_cost_usd": round(total_cost, 6), "output": str(args.output)}, ensure_ascii=False, indent=2))
271
+
272
+
273
+ if __name__ == "__main__":
274
+ main()
top5000_clipframe_dino_clipt_dedup/run_gemini_pro_label.sh CHANGED
@@ -2,7 +2,6 @@
2
  set -euo pipefail
3
 
4
  BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5
- REPO_ROOT="$(cd "$BASE_DIR/../../.." && pwd)"
6
 
7
  MODEL="${MODEL:-gemini-3.1-pro-preview-thinking}"
8
  BASE_URL="${BASE_URL:-http://35.220.164.252:3888/v1}"
@@ -11,15 +10,15 @@ RESIZE="${RESIZE:-512}"
11
  LIMIT="${LIMIT:-0}"
12
  OUTPUT="${OUTPUT:-$BASE_DIR/aesthetic_scores_gemini_pro.jsonl}"
13
 
14
- cd "$REPO_ROOT"
15
 
16
- python3 "$BASE_DIR/prepare_aesthetic_api_input.py" \
17
  --base-dir "$BASE_DIR" \
18
  --input "$BASE_DIR/prompt.jsonl" \
19
  --output "$BASE_DIR/aesthetic_api_input.jsonl"
20
 
21
  cmd=(
22
- python3 reference/benchmarks/critic/aesthetic_rm/label_aesthetic_api.py
23
  --input "$BASE_DIR/aesthetic_api_input.jsonl"
24
  --output "$OUTPUT"
25
  --base-url "$BASE_URL"
 
2
  set -euo pipefail
3
 
4
  BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 
5
 
6
  MODEL="${MODEL:-gemini-3.1-pro-preview-thinking}"
7
  BASE_URL="${BASE_URL:-http://35.220.164.252:3888/v1}"
 
10
  LIMIT="${LIMIT:-0}"
11
  OUTPUT="${OUTPUT:-$BASE_DIR/aesthetic_scores_gemini_pro.jsonl}"
12
 
13
+ cd "$BASE_DIR"
14
 
15
+ python3 prepare_aesthetic_api_input.py \
16
  --base-dir "$BASE_DIR" \
17
  --input "$BASE_DIR/prompt.jsonl" \
18
  --output "$BASE_DIR/aesthetic_api_input.jsonl"
19
 
20
  cmd=(
21
+ python3 label_aesthetic_standalone.py
22
  --input "$BASE_DIR/aesthetic_api_input.jsonl"
23
  --output "$OUTPUT"
24
  --base-url "$BASE_URL"