Datasets:
Tasks:
Text Generation
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
Tags:
academic-poster-generation
instruction-tuning
text-generation
document-understanding
poster-generation
License:
File size: 12,332 Bytes
ec21fa4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | #!/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()
|