YFanwang commited on
Commit
3f8d105
·
verified ·
1 Parent(s): 3f2b212

Upload VideoX-Fun/build_yanyu_pairwise_qa.py

Browse files
Files changed (1) hide show
  1. VideoX-Fun/build_yanyu_pairwise_qa.py +352 -0
VideoX-Fun/build_yanyu_pairwise_qa.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build pairwise QA tables from Yanyu video evaluation JSON and prompt decompositions."""
3
+
4
+ import argparse
5
+ import ast
6
+ import csv
7
+ import json
8
+ import os
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ DEFAULT_SOURCE_JSON = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0 (1).json"
15
+ DEFAULT_DECOMP_JSON = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_prompts_decompsed.json"
16
+ DEFAULT_PAIRWISE_TSV = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_pairwise_qa.tsv"
17
+ DEFAULT_SINGLE_TSV = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_single_video_qa.tsv"
18
+
19
+ CATEGORY_ALIASES = {
20
+ "background": "Environment",
21
+ "environment": "Environment",
22
+ "objects": "Object(s)",
23
+ "object(s)": "Object(s)",
24
+ "object motion": "Objects' Motion",
25
+ "objects motion": "Objects' Motion",
26
+ "objects' motion": "Objects' Motion",
27
+ "objects'motion": "Objects' Motion",
28
+ "object location/spatial distribution": "Object Location / Spatial Distribution",
29
+ "object location / spatial distribution": "Object Location / Spatial Distribution",
30
+ "spatial distribution": "Object Location / Spatial Distribution",
31
+ "color": "Color Requirement",
32
+ "color requirement": "Color Requirement",
33
+ "lighting": "Lighting",
34
+ "letter/text presence": "Letter/Text Presence",
35
+ "text presence": "Letter/Text Presence",
36
+ "letter presence": "Letter/Text Presence",
37
+ "camera motion": "Camera Motion",
38
+ }
39
+
40
+
41
+ def parse_args() -> argparse.Namespace:
42
+ parser = argparse.ArgumentParser(
43
+ description=(
44
+ "Create pairwise and single-video QA TSV files using prompt decompositions "
45
+ "as question lists."
46
+ )
47
+ )
48
+ parser.add_argument("--source_json", type=str, default=DEFAULT_SOURCE_JSON)
49
+ parser.add_argument("--decomp_json", type=str, default=DEFAULT_DECOMP_JSON)
50
+ parser.add_argument("--output_pairwise_tsv", type=str, default=DEFAULT_PAIRWISE_TSV)
51
+ parser.add_argument("--output_single_tsv", type=str, default=DEFAULT_SINGLE_TSV)
52
+ parser.add_argument(
53
+ "--skip_single_tsv",
54
+ action="store_true",
55
+ help="Only write the pairwise TSV.",
56
+ )
57
+ parser.add_argument(
58
+ "--strict",
59
+ action="store_true",
60
+ help="Raise an error if any prompt in source_json has no decomposition.",
61
+ )
62
+ return parser.parse_args()
63
+
64
+
65
+ def clean_text(value: Any) -> str:
66
+ if value is None:
67
+ return ""
68
+ if isinstance(value, list):
69
+ return ", ".join(clean_text(item) for item in value if clean_text(item))
70
+ if isinstance(value, dict):
71
+ return json.dumps(value, ensure_ascii=False)
72
+ if isinstance(value, str):
73
+ stripped = value.strip()
74
+ if (stripped.startswith("[") and stripped.endswith("]")) or (
75
+ stripped.startswith("{") and stripped.endswith("}")
76
+ ):
77
+ try:
78
+ parsed = ast.literal_eval(stripped)
79
+ if parsed is not value:
80
+ return clean_text(parsed)
81
+ except (ValueError, SyntaxError):
82
+ pass
83
+ value = stripped
84
+ return re.sub(r"\s+", " ", str(value)).strip()
85
+
86
+
87
+ def prompt_lookup_key(prompt: str, strip_terminal_punctuation: bool = False) -> str:
88
+ prompt = clean_text(prompt).lower()
89
+ if strip_terminal_punctuation:
90
+ prompt = prompt.rstrip(" .。")
91
+ return prompt
92
+
93
+
94
+ def normalize_category(category: str) -> str:
95
+ category = clean_text(category)
96
+ return CATEGORY_ALIASES.get(category.lower(), category)
97
+
98
+
99
+ def normalize_decomposition(raw_decomp: dict[str, Any]) -> dict[str, str]:
100
+ normalized = {}
101
+ for category, requirement in raw_decomp.items():
102
+ normalized[normalize_category(category)] = clean_text(requirement)
103
+ return normalized
104
+
105
+
106
+ def load_decompositions(path: str) -> dict[str, dict[str, str]]:
107
+ with open(path, "r", encoding="utf-8") as f:
108
+ raw = json.load(f)
109
+ if not isinstance(raw, dict):
110
+ raise ValueError(f"Expected decomposition JSON to be a dict, got {type(raw)}")
111
+
112
+ lookup = {}
113
+ for prompt, decomp in raw.items():
114
+ if not isinstance(decomp, dict):
115
+ continue
116
+ normalized_decomp = normalize_decomposition(decomp)
117
+ prompt_text = clean_text(prompt)
118
+ lookup[prompt_lookup_key(prompt_text)] = normalized_decomp
119
+ lookup[prompt_lookup_key(prompt_text, strip_terminal_punctuation=True)] = normalized_decomp
120
+ return lookup
121
+
122
+
123
+ def extract_prompt(question: str) -> str:
124
+ question = clean_text(question)
125
+ match = re.search(r"aligned with prompt:\s*(.*)$", question, flags=re.IGNORECASE)
126
+ if match:
127
+ return clean_text(match.group(1))
128
+ match = re.search(r"^Prompt:\s*(.*)$", question, flags=re.IGNORECASE)
129
+ if match:
130
+ return clean_text(match.group(1))
131
+ return question
132
+
133
+
134
+ def iter_pages(source: dict[str, Any]):
135
+ for result_index, result in enumerate(source.get("results", [])):
136
+ if not isinstance(result, dict):
137
+ continue
138
+ result_id = result.get("Id", "")
139
+ performer = result.get("Performer", "")
140
+ pages = result.get("Payload", {}).get("Pages", [])
141
+ for page_index, page in enumerate(pages):
142
+ if isinstance(page, dict):
143
+ yield result_index, result_id, performer, page_index, page
144
+
145
+
146
+ def selected_paths(node: Any) -> list[str]:
147
+ paths = []
148
+ if isinstance(node, dict):
149
+ if node.get("Selected"):
150
+ path = node.get("path")
151
+ if isinstance(path, list):
152
+ paths.append("/".join(str(item) for item in path))
153
+ else:
154
+ paths.append(clean_text(node.get("name")))
155
+ for child in node.get("children", []) or []:
156
+ paths.extend(selected_paths(child))
157
+ elif isinstance(node, list):
158
+ for child in node:
159
+ paths.extend(selected_paths(child))
160
+ return paths
161
+
162
+
163
+ def extract_selected_index(page: dict[str, Any]) -> str:
164
+ for path in selected_paths(page.get("DescriptorsTree")):
165
+ leaf = path.split("/")[-1].strip()
166
+ if leaf in {"1", "2"}:
167
+ return leaf
168
+ return ""
169
+
170
+
171
+ def model_name_from_url(url: str) -> str:
172
+ parts = clean_text(url).split("/")
173
+ if len(parts) >= 2:
174
+ folder = parts[-2]
175
+ match = re.search(r"folder(\d+)$", folder)
176
+ if match:
177
+ return f"folder{match.group(1)}"
178
+ return folder
179
+ return ""
180
+
181
+
182
+ def video_id_from_url(url: str) -> str:
183
+ return os.path.basename(clean_text(url))
184
+
185
+
186
+ def build_question(category: str, requirement: str) -> str:
187
+ requirement = clean_text(requirement).rstrip(" .。")
188
+ return (
189
+ f"Given this AI-generated video, does it successfully fulfill the '{category}' "
190
+ f"condition: {requirement}? Respond with 'Yes' or 'No'. Answer 'Yes' if the "
191
+ "video largely matches the description. Answer 'No' if the video clearly "
192
+ "contradicts the description. The presence of additional elements in the video "
193
+ "is acceptable as long as they do not conflict with the core description. "
194
+ "Please provide a brief explanation for your answer.\n"
195
+ "Provide your analysis and explanation in JSON with keys: answer (e.g., Yes or No), explanation."
196
+ )
197
+
198
+
199
+ def build_questions(decomposition: dict[str, str]) -> list[str]:
200
+ return [
201
+ build_question(category, requirement)
202
+ for category, requirement in decomposition.items()
203
+ if clean_text(requirement)
204
+ ]
205
+
206
+
207
+ def write_tsv(path: str, rows: list[dict[str, Any]], columns: list[str]) -> None:
208
+ output_path = Path(path)
209
+ output_path.parent.mkdir(parents=True, exist_ok=True)
210
+ with output_path.open("w", newline="", encoding="utf-8-sig") as f:
211
+ writer = csv.DictWriter(f, fieldnames=columns, delimiter="\t")
212
+ writer.writeheader()
213
+ writer.writerows(rows)
214
+
215
+
216
+ def build_rows(source_json: str, decomp_json: str, strict: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str]]:
217
+ with open(source_json, "r", encoding="utf-8") as f:
218
+ source = json.load(f)
219
+ decompositions = load_decompositions(decomp_json)
220
+
221
+ pairwise_rows = []
222
+ single_rows = []
223
+ missing_prompts = []
224
+
225
+ for _, result_id, performer, page_index, page in iter_pages(source):
226
+ prompt = extract_prompt(page.get("Question", ""))
227
+ decomp = decompositions.get(prompt_lookup_key(prompt))
228
+ if decomp is None:
229
+ decomp = decompositions.get(prompt_lookup_key(prompt, strip_terminal_punctuation=True))
230
+ if decomp is None:
231
+ missing_prompts.append(prompt)
232
+ if strict:
233
+ continue
234
+ decomp = {}
235
+
236
+ questions = build_questions(decomp)
237
+ inputs = page.get("labelingInputs", [])
238
+ video_a = clean_text(inputs[0].get("url")) if len(inputs) > 0 and isinstance(inputs[0], dict) else ""
239
+ video_b = clean_text(inputs[1].get("url")) if len(inputs) > 1 and isinstance(inputs[1], dict) else ""
240
+ selected_index = extract_selected_index(page)
241
+ human_preference = {"1": "A", "2": "B"}.get(selected_index, "")
242
+ selected_video = video_a if human_preference == "A" else video_b if human_preference == "B" else ""
243
+ pair_id = f"{result_id}_{page_index:03d}"
244
+
245
+ pairwise_row = {
246
+ "pair_id": pair_id,
247
+ "result_id": result_id,
248
+ "performer": performer,
249
+ "page_idx": page_index,
250
+ "prompt": prompt,
251
+ "path_A": video_a,
252
+ "path_B": video_b,
253
+ "A_model": model_name_from_url(video_a),
254
+ "B_model": model_name_from_url(video_b),
255
+ "video_id_A": video_id_from_url(video_a),
256
+ "video_id_B": video_id_from_url(video_b),
257
+ "questions": json.dumps(questions, ensure_ascii=False),
258
+ "decomposition": json.dumps(decomp, ensure_ascii=False),
259
+ "human_preference": human_preference,
260
+ "selected_index": selected_index,
261
+ "selected_video": selected_video,
262
+ "selected_paths": json.dumps(selected_paths(page.get("DescriptorsTree")), ensure_ascii=False),
263
+ "original_question": clean_text(page.get("Question", "")),
264
+ "selected_count": page.get("SelectedCount", ""),
265
+ }
266
+ pairwise_rows.append(pairwise_row)
267
+
268
+ for side, video_path, opponent_path, preference_label in [
269
+ ("A", video_a, video_b, "chosen" if human_preference == "A" else "rejected" if human_preference == "B" else ""),
270
+ ("B", video_b, video_a, "chosen" if human_preference == "B" else "rejected" if human_preference == "A" else ""),
271
+ ]:
272
+ single_rows.append(
273
+ {
274
+ "pair_id": pair_id,
275
+ "side": side,
276
+ "video_id": video_id_from_url(video_path),
277
+ "real_video_path": video_path,
278
+ "ref_video": opponent_path,
279
+ "prompt": prompt,
280
+ "questions": json.dumps(questions, ensure_ascii=False),
281
+ "gt_answers": json.dumps([], ensure_ascii=False),
282
+ "human_preference": human_preference,
283
+ "preference_label": preference_label,
284
+ "result_id": result_id,
285
+ "page_idx": page_index,
286
+ }
287
+ )
288
+
289
+ if strict and missing_prompts:
290
+ examples = "\n".join(missing_prompts[:5])
291
+ raise ValueError(f"Missing decompositions for {len(missing_prompts)} prompts. Examples:\n{examples}")
292
+
293
+ return pairwise_rows, single_rows, missing_prompts
294
+
295
+
296
+ def main() -> None:
297
+ args = parse_args()
298
+ pairwise_rows, single_rows, missing_prompts = build_rows(
299
+ source_json=args.source_json,
300
+ decomp_json=args.decomp_json,
301
+ strict=args.strict,
302
+ )
303
+
304
+ pairwise_columns = [
305
+ "pair_id",
306
+ "result_id",
307
+ "performer",
308
+ "page_idx",
309
+ "prompt",
310
+ "path_A",
311
+ "path_B",
312
+ "A_model",
313
+ "B_model",
314
+ "video_id_A",
315
+ "video_id_B",
316
+ "questions",
317
+ "decomposition",
318
+ "human_preference",
319
+ "selected_index",
320
+ "selected_video",
321
+ "selected_paths",
322
+ "original_question",
323
+ "selected_count",
324
+ ]
325
+ write_tsv(args.output_pairwise_tsv, pairwise_rows, pairwise_columns)
326
+
327
+ if not args.skip_single_tsv:
328
+ single_columns = [
329
+ "pair_id",
330
+ "side",
331
+ "video_id",
332
+ "real_video_path",
333
+ "ref_video",
334
+ "prompt",
335
+ "questions",
336
+ "gt_answers",
337
+ "human_preference",
338
+ "preference_label",
339
+ "result_id",
340
+ "page_idx",
341
+ ]
342
+ write_tsv(args.output_single_tsv, single_rows, single_columns)
343
+
344
+ print(f"Saved {len(pairwise_rows)} pairwise rows to {args.output_pairwise_tsv}")
345
+ if not args.skip_single_tsv:
346
+ print(f"Saved {len(single_rows)} single-video QA rows to {args.output_single_tsv}")
347
+ if missing_prompts:
348
+ print(f"Warning: {len(missing_prompts)} prompts did not have decompositions.")
349
+
350
+
351
+ if __name__ == "__main__":
352
+ main()