#!/usr/bin/env python3 """Generate PosterEval IR from poster PNG/JPEG images. The public flow intentionally uses two IR prompts: - content IR for Order, Completeness, and Claim F1. - figure IR for Local Text-Figure Alignment. """ import argparse import json import re from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple from openrouter_client import call_openrouter_json DEFAULT_WORKERS = 8 PROMPT_DIR = Path(__file__).resolve().parent / "prompts" PARSER_TO_PROMPT = { "content": PROMPT_DIR / "content_ir_prompt.md", "figure": PROMPT_DIR / "figure_grounding_ir_prompt.md", } def normalize_key(text: str) -> str: return re.sub(r"[^a-z0-9]+", "", text.lower()) def extract_key(name: str, pattern: Optional[str]) -> str: if pattern: match = re.search(pattern, name) if match: return match.groupdict().get("key") or match.group(1) if re.fullmatch(r"\d+", name): return name return normalize_key(name) def should_ignore(name: str, patterns: Iterable[str]) -> bool: return any(re.search(pattern, name) for pattern in patterns) def choose_image(dir_path: Path, image_filename: Optional[str]) -> Optional[Path]: if image_filename: candidate = dir_path / image_filename if candidate.exists(): return candidate priority = [ "poster.png", "paper.png", "poster.jpg", "paper.jpg", "poster.jpeg", "paper.jpeg", ] for name in priority: candidate = dir_path / name if candidate.exists(): return candidate images = [] for pattern in ("*.png", "*.jpg", "*.jpeg"): images.extend(dir_path.glob(pattern)) return sorted(images, key=lambda p: p.name)[0] if images else None def discover_images( input_root: Path, layout: str, image_filename: Optional[str], image_glob: str, key_regex: Optional[str], ignore_dir_regex: List[str], ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: items: List[Dict[str, Any]] = [] missing: List[Dict[str, Any]] = [] if layout == "flat": for image_path in sorted(input_root.glob(image_glob), key=lambda p: p.name): if not image_path.is_file(): continue key = extract_key(image_path.stem, key_regex) items.append( { "key": key, "source_name": image_path.stem, "image_path": image_path, "input_relpath": image_path.name, } ) return items, missing for child in sorted(input_root.iterdir(), key=lambda p: p.name): if not child.is_dir() or should_ignore(child.name, ignore_dir_regex): continue key = extract_key(child.name, key_regex) image_path = choose_image(child, image_filename) if image_path is None: missing.append({"key": key, "source_name": child.name}) continue items.append( { "key": key, "source_name": child.name, "image_path": image_path, "input_relpath": str(image_path.relative_to(input_root)), } ) return items, missing def infer_role(title: str, text_content: str) -> str: text = f"{title} {text_content}".lower() problem_kw = ["problem", "motivation", "challenge", "background"] approach_kw = ["approach", "method", "framework", "model", "pipeline"] evidence_kw = ["result", "evaluation", "experiment", "ablation", "analysis"] if any(keyword in text for keyword in problem_kw): return "Problem" if any(keyword in text for keyword in evidence_kw): return "Evidence" if any(keyword in text for keyword in approach_kw): return "Approach" return "Approach" def normalize_figure_ir(data: Dict[str, Any]) -> Dict[str, Any]: if not isinstance(data, dict): return {"sections": []} sections = [] for section_index, section in enumerate(data.get("sections", []), start=1): if not isinstance(section, dict): continue title = section.get("title", "") or "" text_content = section.get("text_content", "") or "" out_section = { "id": section.get("id") or f"s{section_index}", "title": title, "bbox": section.get("bbox"), "text_content": text_content, "meta_role": section.get("meta_role") or infer_role(title, text_content), "contains_figures": [], } figures = section.get("contains_figures") or section.get("figures") or [] for fig_index, figure in enumerate(figures, start=1): if not isinstance(figure, dict): continue description = figure.get("description", "") or "" out_section["contains_figures"].append( { "id": figure.get("id") or f"f{section_index}_{fig_index}", "bbox": figure.get("bbox"), "type": figure.get("type", "Chart"), "caption": figure.get("caption") or description, "semantic_summary": figure.get("semantic_summary") or description, "visual_description": figure.get("visual_description") or description, } ) sections.append(out_section) payload: Dict[str, Any] = {"sections": sections} if "meta" in data: payload["meta"] = data["meta"] return payload def parser_output_dir(output_root: Path, parser_name: str) -> Path: if parser_name == "content": return output_root / "content_ir" if parser_name == "figure": return output_root / "figure_ir" raise ValueError(f"Unknown parser: {parser_name}") def write_ir( output_root: Path, parser_name: str, key: str, payload: Dict[str, Any], ) -> Path: out_dir = parser_output_dir(output_root, parser_name) / key out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / "poster_ir.json" out_path.write_text( json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) return out_path def run_one_parser( item: Dict[str, Any], output_root: Path, parser_name: str, model: str, temperature: float, include_paths: bool, ) -> Dict[str, Any]: prompt_path = PARSER_TO_PROMPT[parser_name] prompt = prompt_path.read_text(encoding="utf-8") record = { "key": item["key"], "source_name": item["source_name"], "input_relpath": item["input_relpath"], "parser": parser_name, "model": model, "prompt_file": str(prompt_path.relative_to(PROMPT_DIR.parent)), "error": "", } if include_paths: record["image_path"] = str(item["image_path"]) try: raw = call_openrouter_json( prompt=prompt, model=model, image_path=item["image_path"], max_tokens=16384, temperature=temperature, response_format_json=True, ) if raw.get("parse_error"): raise RuntimeError(raw.get("error", "model response JSON parse error")) payload = normalize_figure_ir(raw) if parser_name == "figure" else raw payload.setdefault("_postereval", {}) payload["_postereval"].update( { "source_name": item["source_name"], "parser": parser_name, "model": model, "prompt_file": record["prompt_file"], } ) if include_paths: payload["_postereval"]["image_path"] = str(item["image_path"]) else: payload["_postereval"]["input_relpath"] = item["input_relpath"] out_path = write_ir(output_root, parser_name, item["key"], payload) record["output_relpath"] = str(out_path.relative_to(output_root)) except Exception as exc: record["error"] = repr(exc) return record def expand_parsers(value: str) -> List[str]: if value == "both": return ["content", "figure"] parsers = [] for part in value.split(","): part = part.strip() if part in {"content", "figure"}: parsers.append(part) elif part in {"content_ir"}: parsers.append("content") elif part in {"figure_ir"}: parsers.append("figure") else: raise ValueError(f"Unknown parser: {part}") return list(dict.fromkeys(parsers)) def run(args: argparse.Namespace) -> None: input_root = Path(args.input_root).expanduser() output_root = Path(args.output_root).expanduser() output_root.mkdir(parents=True, exist_ok=True) items, missing = discover_images( input_root=input_root, layout=args.layout, image_filename=args.image_filename, image_glob=args.image_glob, key_regex=args.key_regex, ignore_dir_regex=args.ignore_dir_regex, ) parsers = expand_parsers(args.parser) records = [] with ThreadPoolExecutor(max_workers=args.workers) as executor: futures = [] for item in items: for parser_name in parsers: futures.append( executor.submit( run_one_parser, item, output_root, parser_name, args.model, args.temperature, args.include_paths, ) ) for future in as_completed(futures): records.append(future.result()) records.sort(key=lambda r: (r["parser"], r["key"], r["source_name"])) summary = { "input_root_exists": input_root.exists(), "layout": args.layout, "n_images": len(items), "parsers": parsers, "model": args.model, "temperature": args.temperature, "n_records": len(records), "n_errors": sum(1 for record in records if record.get("error")), "missing_images": missing, "records": records, } if args.include_paths: summary["input_root"] = str(input_root) (output_root / "summary.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate PosterEval IR from poster images.") parser.add_argument("--input-root", required=True, help="Poster image root.") parser.add_argument("--output-root", required=True, help="IR output root.") parser.add_argument( "--parser", default="both", help="content / figure / both, or a comma-separated combination.", ) parser.add_argument( "--layout", choices=["directories", "flat"], default="directories", help="Input layout: one image per subdirectory, or flat image files.", ) parser.add_argument("--image-filename", help="Expected image filename inside each directory.") parser.add_argument("--image-glob", default="*.png", help="Glob used when --layout flat.") parser.add_argument("--key-regex", help="Regex with optional named group 'key'.") parser.add_argument( "--ignore-dir-regex", action="append", default=[r"^_", r"^\.", r"^__pycache__$"], help="Directory regex to skip. Can be repeated.", ) parser.add_argument("--model", default="qwen3-vl-235b", help="OpenRouter model alias or id.") parser.add_argument( "--temperature", type=float, default=0.02, help="IR parser sampling temperature. Default matches the paper protocol.", ) parser.add_argument("--workers", type=int, default=DEFAULT_WORKERS) parser.add_argument( "--include-paths", action="store_true", help="Include absolute local paths in outputs. Keep off for anonymous artifacts.", ) return parser.parse_args() def main() -> None: run(parse_args()) if __name__ == "__main__": main()