Upload VideoX-Fun/build_yanyu_pairwise_qa.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352#!/usr/bin/env python3"""Build pairwise QA tables from Yanyu video evaluation JSON and prompt decompositions."""
import argparseimport astimport csvimport jsonimport osimport refrom pathlib import Pathfrom typing import Any
DEFAULT_SOURCE_JSON = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0 (1).json"DEFAULT_DECOMP_JSON = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_prompts_decompsed.json"DEFAULT_PAIRWISE_TSV = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_pairwise_qa.tsv"DEFAULT_SINGLE_TSV = "/nfs/ywang29/yanyu_vidgen_evaluation_drf_2026_01_26_final-0_single_video_qa.tsv"
CATEGORY_ALIASES = { "background": "Environment", "environment": "Environment", "objects": "Object(s)", "object(s)": "Object(s)", "object motion": "Objects' Motion", "objects motion": "Objects' Motion", "objects' motion": "Objects' Motion", "objects'motion": "Objects' Motion", "object location/spatial distribution": "Object Location / Spatial Distribution", "object location / spatial distribution": "Object Location / Spatial Distribution", "spatial distribution": "Object Location / Spatial Distribution", "color": "Color Requirement", "color requirement": "Color Requirement", "lighting": "Lighting", "letter/text presence": "Letter/Text Presence", "text presence": "Letter/Text Presence", "letter presence": "Letter/Text Presence", "camera motion": "Camera Motion",}
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Create pairwise and single-video QA TSV files using prompt decompositions " "as question lists." ) ) parser.add_argument("--source_json", type=str, default=DEFAULT_SOURCE_JSON) parser.add_argument("--decomp_json", type=str, default=DEFAULT_DECOMP_JSON) parser.add_argument("--output_pairwise_tsv", type=str, default=DEFAULT_PAIRWISE_TSV) parser.add_argument("--output_single_tsv", type=str, default=DEFAULT_SINGLE_TSV) parser.add_argument( "--skip_single_tsv", action="store_true", help="Only write the pairwise TSV.", ) parser.add_argument( "--strict", action="store_true", help="Raise an error if any prompt in source_json has no decomposition.", ) return parser.parse_args()
def clean_text(value: Any) -> str: if value is None: return "" if isinstance(value, list): return ", ".join(clean_text(item) for item in value if clean_text(item)) if isinstance(value, dict): return json.dumps(value, ensure_ascii=False) if isinstance(value, str): stripped = value.strip() if (stripped.startswith("[") and stripped.endswith("]")) or ( stripped.startswith("{") and stripped.endswith("}") ): try: parsed = ast.literal_eval(stripped) if parsed is not value: return clean_text(parsed) except (ValueError, SyntaxError): pass value = stripped return re.sub(r"\s+", " ", str(value)).strip()
def prompt_lookup_key(prompt: str, strip_terminal_punctuation: bool = False) -> str: prompt = clean_text(prompt).lower() if strip_terminal_punctuation: prompt = prompt.rstrip(" .。") return prompt
def normalize_category(category: str) -> str: category = clean_text(category) return CATEGORY_ALIASES.get(category.lower(), category)
def normalize_decomposition(raw_decomp: dict[str, Any]) -> dict[str, str]: normalized = {} for category, requirement in raw_decomp.items(): normalized[normalize_category(category)] = clean_text(requirement) return normalized
def load_decompositions(path: str) -> dict[str, dict[str, str]]: with open(path, "r", encoding="utf-8") as f: raw = json.load(f) if not isinstance(raw, dict): raise ValueError(f"Expected decomposition JSON to be a dict, got {type(raw)}")
lookup = {} for prompt, decomp in raw.items(): if not isinstance(decomp, dict): continue normalized_decomp = normalize_decomposition(decomp) prompt_text = clean_text(prompt) lookup[prompt_lookup_key(prompt_text)] = normalized_decomp lookup[prompt_lookup_key(prompt_text, strip_terminal_punctuation=True)] = normalized_decomp return lookup
def extract_prompt(question: str) -> str: question = clean_text(question) match = re.search(r"aligned with prompt:\s*(.*)$", question, flags=re.IGNORECASE) if match: return clean_text(match.group(1)) match = re.search(r"^Prompt:\s*(.*)$", question, flags=re.IGNORECASE) if match: return clean_text(match.group(1)) return question
def iter_pages(source: dict[str, Any]): for result_index, result in enumerate(source.get("results", [])): if not isinstance(result, dict): continue result_id = result.get("Id", "") performer = result.get("Performer", "") pages = result.get("Payload", {}).get("Pages", []) for page_index, page in enumerate(pages): if isinstance(page, dict): yield result_index, result_id, performer, page_index, page
def selected_paths(node: Any) -> list[str]: paths = [] if isinstance(node, dict): if node.get("Selected"): path = node.get("path") if isinstance(path, list): paths.append("/".join(str(item) for item in path)) else: paths.append(clean_text(node.get("name"))) for child in node.get("children", []) or []: paths.extend(selected_paths(child)) elif isinstance(node, list): for child in node: paths.extend(selected_paths(child)) return paths
def extract_selected_index(page: dict[str, Any]) -> str: for path in selected_paths(page.get("DescriptorsTree")): leaf = path.split("/")[-1].strip() if leaf in {"1", "2"}: return leaf return ""
def model_name_from_url(url: str) -> str: parts = clean_text(url).split("/") if len(parts) >= 2: folder = parts[-2] match = re.search(r"folder(\d+)$", folder) if match: return f"folder{match.group(1)}" return folder return ""
def video_id_from_url(url: str) -> str: return os.path.basename(clean_text(url))
def build_question(category: str, requirement: str) -> str: requirement = clean_text(requirement).rstrip(" .。") return ( f"Given this AI-generated video, does it successfully fulfill the '{category}' " f"condition: {requirement}? Respond with 'Yes' or 'No'. Answer 'Yes' if the " "video largely matches the description. Answer 'No' if the video clearly " "contradicts the description. The presence of additional elements in the video " "is acceptable as long as they do not conflict with the core description. " "Please provide a brief explanation for your answer.\n" "Provide your analysis and explanation in JSON with keys: answer (e.g., Yes or No), explanation." )
def build_questions(decomposition: dict[str, str]) -> list[str]: return [ build_question(category, requirement) for category, requirement in decomposition.items() if clean_text(requirement) ]
def write_tsv(path: str, rows: list[dict[str, Any]], columns: list[str]) -> None: output_path = Path(path) output_path.parent.mkdir(parents=True, exist_ok=True) with output_path.open("w", newline="", encoding="utf-8-sig") as f: writer = csv.DictWriter(f, fieldnames=columns, delimiter="\t") writer.writeheader() writer.writerows(rows)
def build_rows(source_json: str, decomp_json: str, strict: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str]]: with open(source_json, "r", encoding="utf-8") as f: source = json.load(f) decompositions = load_decompositions(decomp_json)
pairwise_rows = [] single_rows = [] missing_prompts = []
for _, result_id, performer, page_index, page in iter_pages(source): prompt = extract_prompt(page.get("Question", "")) decomp = decompositions.get(prompt_lookup_key(prompt)) if decomp is None: decomp = decompositions.get(prompt_lookup_key(prompt, strip_terminal_punctuation=True)) if decomp is None: missing_prompts.append(prompt) if strict: continue decomp = {}
questions = build_questions(decomp) inputs = page.get("labelingInputs", []) video_a = clean_text(inputs[0].get("url")) if len(inputs) > 0 and isinstance(inputs[0], dict) else "" video_b = clean_text(inputs[1].get("url")) if len(inputs) > 1 and isinstance(inputs[1], dict) else "" selected_index = extract_selected_index(page) human_preference = {"1": "A", "2": "B"}.get(selected_index, "") selected_video = video_a if human_preference == "A" else video_b if human_preference == "B" else "" pair_id = f"{result_id}_{page_index:03d}"
pairwise_row = { "pair_id": pair_id, "result_id": result_id, "performer": performer, "page_idx": page_index, "prompt": prompt, "path_A": video_a, "path_B": video_b, "A_model": model_name_from_url(video_a), "B_model": model_name_from_url(video_b), "video_id_A": video_id_from_url(video_a), "video_id_B": video_id_from_url(video_b), "questions": json.dumps(questions, ensure_ascii=False), "decomposition": json.dumps(decomp, ensure_ascii=False), "human_preference": human_preference, "selected_index": selected_index, "selected_video": selected_video, "selected_paths": json.dumps(selected_paths(page.get("DescriptorsTree")), ensure_ascii=False), "original_question": clean_text(page.get("Question", "")), "selected_count": page.get("SelectedCount", ""), } pairwise_rows.append(pairwise_row)
for side, video_path, opponent_path, preference_label in [ ("A", video_a, video_b, "chosen" if human_preference == "A" else "rejected" if human_preference == "B" else ""), ("B", video_b, video_a, "chosen" if human_preference == "B" else "rejected" if human_preference == "A" else ""), ]: single_rows.append( { "pair_id": pair_id, "side": side, "video_id": video_id_from_url(video_path), "real_video_path": video_path, "ref_video": opponent_path, "prompt": prompt, "questions": json.dumps(questions, ensure_ascii=False), "gt_answers": json.dumps([], ensure_ascii=False), "human_preference": human_preference, "preference_label": preference_label, "result_id": result_id, "page_idx": page_index, } )
if strict and missing_prompts: examples = "\n".join(missing_prompts[:5]) raise ValueError(f"Missing decompositions for {len(missing_prompts)} prompts. Examples:\n{examples}")
return pairwise_rows, single_rows, missing_prompts
def main() -> None: args = parse_args() pairwise_rows, single_rows, missing_prompts = build_rows( source_json=args.source_json, decomp_json=args.decomp_json, strict=args.strict, )
pairwise_columns = [ "pair_id", "result_id", "performer", "page_idx", "prompt", "path_A", "path_B", "A_model", "B_model", "video_id_A", "video_id_B", "questions", "decomposition", "human_preference", "selected_index", "selected_video", "selected_paths", "original_question", "selected_count", ] write_tsv(args.output_pairwise_tsv, pairwise_rows, pairwise_columns)
if not args.skip_single_tsv: single_columns = [ "pair_id", "side", "video_id", "real_video_path", "ref_video", "prompt", "questions", "gt_answers", "human_preference", "preference_label", "result_id", "page_idx", ] write_tsv(args.output_single_tsv, single_rows, single_columns)
print(f"Saved {len(pairwise_rows)} pairwise rows to {args.output_pairwise_tsv}") if not args.skip_single_tsv: print(f"Saved {len(single_rows)} single-video QA rows to {args.output_single_tsv}") if missing_prompts: print(f"Warning: {len(missing_prompts)} prompts did not have decompositions.")
if __name__ == "__main__": main()VideoX-Fun/build_yanyu_pairwise_qa.pyAdded+352