Datasets:
Tasks:
Visual Question Answering
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
Tags:
table-question-answering
table-understanding
markup-driven-understanding
visual-document-understanding
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import colorsys | |
| import re | |
| from dataclasses import dataclass, field | |
| import copy | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Tuple | |
| from PIL import Image, ImageDraw, ImageFont | |
| from name_pools import CONFIG_FLAG_POOL | |
| from config_tag import build_config_info, embed_code_in_image | |
| # ========================= | |
| # ========================= | |
| class PTCell: | |
| row: int | |
| col: int | |
| row_span: int = 1 | |
| col_span: int = 1 | |
| text: str = "" | |
| value: Optional[float] = None | |
| kind: str = "data" # header/group/item/data | |
| bbox: Optional[Tuple[int, int, int, int]] = None | |
| extra: Dict[str, str] = field(default_factory=dict) | |
| class TableSpec: | |
| n_rows: int | |
| n_cols: int | |
| header_rows: int | |
| data_row_start: int | |
| left_cols: int | |
| top_levels: int | |
| left_levels: int | |
| cells: List[PTCell] | |
| data_cols: List[Dict] | |
| delta_col: Optional[int] = None | |
| # ========================= | |
| # ========================= | |
| def _auto_font_path() -> Optional[str]: | |
| candidates = [ | |
| "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf", | |
| "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", | |
| "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf", | |
| "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", | |
| ] | |
| for p in candidates: | |
| if Path(p).exists(): | |
| return p | |
| return None | |
| def _auto_symbol_font_candidates() -> List[str]: | |
| return [ | |
| "/usr/share/fonts/truetype/noto/NotoSansSymbols2-Regular.ttf", | |
| "/usr/share/fonts/truetype/noto/NotoSansSymbols-Regular.ttf", | |
| "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", | |
| "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf", | |
| "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", | |
| "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf", | |
| ] | |
| def _pick_font_for_text(paths: List[str], text: str, size: int) -> Optional[ImageFont.FreeTypeFont]: | |
| for p in paths: | |
| if not Path(p).exists(): | |
| continue | |
| try: | |
| f = ImageFont.truetype(p, size) | |
| mask = f.getmask(text) | |
| if mask.getbbox(): | |
| return f | |
| except Exception: | |
| continue | |
| return None | |
| def _format_delta(v: float) -> str: | |
| sign = "+" if v >= 0 else "−" | |
| return f"{sign}{abs(v):.2f}" | |
| def _clear_style_marks(cells: List[PTCell]) -> None: | |
| for c in cells: | |
| if isinstance(c.extra, dict): | |
| c.extra.pop("highlight", None) | |
| c.extra.pop("highlight_color", None) | |
| c.extra.pop("highlight_color_name", None) | |
| c.extra.pop("underline", None) | |
| c.extra.pop("bold", None) | |
| def _metric_prefers_lower(metric_text: Optional[str]) -> bool: | |
| t = str(metric_text or "") | |
| return "↓" in t | |
| def _metric_text_by_col_index(col_idx: int, *, left_cols: int, col_metrics: Optional[List[str]]) -> str: | |
| if not col_metrics: | |
| return "" | |
| rel = int(col_idx) - int(left_cols) | |
| if 0 <= rel < len(col_metrics): | |
| return str(col_metrics[rel] or "") | |
| return "" | |
| def _pick_best_cell_by_metric(vals: List[PTCell], metric_text: Optional[str]) -> PTCell: | |
| if _metric_prefers_lower(metric_text): | |
| return min(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| return max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| def _sort_cells_for_metric(vals: List[PTCell], metric_text: Optional[str]) -> None: | |
| vals.sort(key=lambda x: x.value, reverse=(not _metric_prefers_lower(metric_text))) # type: ignore[call-arg] | |
| def _apply_highlight_by_column_rank( | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| colors: List[str], | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| if not data_cells: | |
| return | |
| palette = list(colors) if colors else ["#E6F2FF", "#BFD8FF", "#7FAEFF"] | |
| palette_rev = list(reversed(palette)) | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| _sort_cells_for_metric(vals, metric_text) | |
| top_k = min(len(palette_rev), len(vals)) | |
| for i in range(top_k): | |
| c = vals[i] | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = palette_rev[i].upper() | |
| def _apply_highlight_by_column_wrong( | |
| rng: random.Random, | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| colors: List[str], | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| if not data_cells: | |
| return | |
| palette = list(colors) if colors else ["#FFD2E6"] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| c = rng.choice(pool) | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = rng.choice(palette).upper() | |
| def _apply_highlight_best_per_col( | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| color_hex: str, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| if not data_cells: | |
| return | |
| hx = str(color_hex).upper() | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| best.extra["highlight"] = "true" | |
| best.extra["highlight_color"] = hx | |
| def _apply_underline_best_per_col( | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| best.extra["underline"] = "true" | |
| def _apply_underline_wrong_per_col( | |
| rng: random.Random, | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| rng.choice(pool).extra["underline"] = "true" | |
| def _apply_underline_second_per_col( | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| vals_sorted = list(vals) | |
| _sort_cells_for_metric(vals_sorted, metric_text) | |
| second = vals_sorted[1] | |
| second.extra["underline"] = "true" | |
| def _apply_bold_best_per_col( | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| best.extra["bold"] = "true" | |
| def _apply_bold_wrong_per_col( | |
| rng: random.Random, | |
| cells: List[PTCell], | |
| *, | |
| left_cols: int, | |
| data_cols_len: int, | |
| col_metrics: Optional[List[str]] = None, | |
| ) -> None: | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| for col_idx in range(left_cols, left_cols + data_cols_len): | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| metric_text = _metric_text_by_col_index(col_idx, left_cols=left_cols, col_metrics=col_metrics) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| rng.choice(pool).extra["bold"] = "true" | |
| def _apply_text_color_mark(cell: PTCell, *, color_hex: str, role: str) -> None: | |
| color_hex_u = str(color_hex).upper() | |
| cell.extra["text_color"] = "true" | |
| cell.extra["text_color_hex"] = color_hex_u | |
| cell.extra["text_color_role"] = role | |
| try: | |
| rgb = _hex_to_rgb(color_hex_u) | |
| cell.extra["text_color_name"] = _color_base_name(rgb) | |
| except Exception: | |
| cell.extra["text_color_name"] = "color" | |
| def _hex_to_rgb(h: str) -> Tuple[int, int, int]: | |
| h = h.strip().lstrip("#") | |
| if len(h) != 6: | |
| raise ValueError(f"Bad hex color: {h}") | |
| return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)) | |
| def _color_base_name(rgb: Tuple[int, int, int]) -> str: | |
| r, g, b = rgb | |
| h, s, v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) | |
| # keep near-neutral colors as white/gray/black, but avoid classifying pale blue as white | |
| if s < 0.08: | |
| if v > 0.92: | |
| return "white" | |
| if v < 0.2: | |
| return "black" | |
| return "gray" | |
| deg = h * 360.0 | |
| if deg < 20 or deg >= 340: | |
| return "red" | |
| if 20 <= deg < 45: | |
| return "orange" | |
| if 45 <= deg < 70: | |
| return "yellow" | |
| if 70 <= deg < 160: | |
| return "green" | |
| if 160 <= deg < 200: | |
| return "cyan" | |
| if 200 <= deg < 250: | |
| return "blue" | |
| if 250 <= deg < 290: | |
| return "purple" | |
| return "pink" | |
| def _build_palette_color_names(colors: List[str], explicit: Optional[Dict[str, str]] = None) -> Dict[str, str]: | |
| """ | |
| Give each palette color an English name (light/medium/dark + base). | |
| """ | |
| if explicit: | |
| return {k.upper(): v for k, v in explicit.items()} | |
| items = [] | |
| for c in colors: | |
| try: | |
| rgb = _hex_to_rgb(c) | |
| except Exception: | |
| continue | |
| r, g, b = rgb | |
| h, s, v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) | |
| base = _color_base_name(rgb) | |
| items.append({"hex": c.upper(), "base": base, "v": v}) | |
| by_base: Dict[str, List[Dict]] = {} | |
| for it in items: | |
| by_base.setdefault(it["base"], []).append(it) | |
| name_map: Dict[str, str] = {} | |
| for base, arr in by_base.items(): | |
| arr.sort(key=lambda x: x["v"], reverse=True) # Higher brightness means a lighter shade. | |
| n = len(arr) | |
| if n == 1: | |
| prefixes = [""] | |
| elif n == 2: | |
| prefixes = ["light", "dark"] | |
| elif n == 3: | |
| prefixes = ["light", "medium", "dark"] | |
| elif n == 4: | |
| prefixes = ["very light", "light", "dark", "very dark"] | |
| elif n == 5: | |
| prefixes = ["very light", "light", "medium", "dark", "very dark"] | |
| else: | |
| prefixes = [] | |
| for i in range(n): | |
| if i == 0: | |
| prefixes.append("very light") | |
| elif i == 1: | |
| prefixes.append("light") | |
| elif i == n - 2: | |
| prefixes.append("dark") | |
| elif i == n - 1: | |
| prefixes.append("very dark") | |
| else: | |
| prefixes.append("medium") | |
| for it, pref in zip(arr, prefixes): | |
| if pref: | |
| name_map[it["hex"]] = f"{pref} {base}" | |
| else: | |
| name_map[it["hex"]] = base | |
| return name_map | |
| def _parse_palette(s: str) -> List[str]: | |
| return [p.strip() for p in s.split(",") if p.strip()] | |
| def _parse_palettes(s: str) -> List[List[str]]: | |
| """ | |
| Parse multiple palettes: | |
| "c1,c2,c3; d1,d2,d3" -> [[c1..], [d1..]] | |
| """ | |
| palettes: List[List[str]] = [] | |
| for part in s.split(";"): | |
| part = part.strip() | |
| if not part: | |
| continue | |
| colors = _parse_palette(part) | |
| if colors: | |
| palettes.append(colors) | |
| return palettes | |
| def _clamp_int(v: int, lo: int = 1, hi: Optional[int] = None) -> int: | |
| x = int(v) | |
| if x < lo: | |
| x = lo | |
| if hi is not None and x > hi: | |
| x = hi | |
| return x | |
| def _palette_group_from_id(pid: str) -> str: | |
| if not pid: | |
| return "X" | |
| head = pid.strip()[0].upper() | |
| if head in ("A", "B", "C"): | |
| return head | |
| return "X" | |
| def _rand_name(rng: random.Random, pool: List[str], suffix: bool = True) -> str: | |
| base = rng.choice(pool) | |
| if suffix: | |
| tail = rng.choice(["A", "B", "C", "D", "E", "F", "X", "Y", "Z"]) | |
| return f"{base}-{tail}" | |
| return base | |
| def _maybe_add_arrow(rng: random.Random, metric: str, prob: float) -> str: | |
| if "↑" in metric or "↓" in metric: | |
| return metric | |
| if rng.random() > prob: | |
| return metric | |
| return metric + rng.choice(["↑", "↓"]) | |
| def _rand_metric(rng: random.Random, pool: List[str], arrow_prob: float) -> str: | |
| metric = rng.choice(pool) | |
| return _maybe_add_arrow(rng, metric, arrow_prob) | |
| def _insert_suffix_before_arrow(label: str, suffix: str) -> str: | |
| if label.endswith("↑") or label.endswith("↓"): | |
| return f"{label[:-1]}{suffix}{label[-1]}" | |
| return f"{label}{suffix}" | |
| def _sample_unique_label( | |
| rng: random.Random, | |
| used: set[str], | |
| sampler, | |
| *, | |
| fallback_prefix: str, | |
| ) -> str: | |
| for _ in range(256): | |
| cand = str(sampler()) | |
| if cand not in used: | |
| used.add(cand) | |
| return cand | |
| base = str(sampler()) | |
| for i in range(2, 10000): | |
| cand = _insert_suffix_before_arrow(base, f"-{i}") | |
| if cand not in used: | |
| used.add(cand) | |
| return cand | |
| for i in range(1, 100000): | |
| cand = f"{fallback_prefix}-{i}" | |
| if cand not in used: | |
| used.add(cand) | |
| return cand | |
| raise RuntimeError("Failed to sample a unique label") | |
| def _format_number(rng: random.Random, dec_min: int, dec_max: int) -> Tuple[str, float]: | |
| dec = rng.randint(dec_min, dec_max) | |
| v = rng.uniform(0, 100) | |
| text = f"{v:.{dec}f}" | |
| return text, float(text) | |
| def _split_citation(text: str) -> Tuple[str, str]: | |
| if "[" in text and text.endswith("]"): | |
| i = text.rfind("[") | |
| return text[:i].rstrip(), text[i:] | |
| return text, "" | |
| # ========================= | |
| # ========================= | |
| def build_paper_table( | |
| rng: random.Random, | |
| *, | |
| group_count: int, | |
| min_items: int, | |
| max_items: int, | |
| block_count: int, | |
| min_metrics: int, | |
| max_metrics: int, | |
| mid_group_min: int, | |
| mid_group_max: int, | |
| section_count: int, | |
| unique_numbers: bool, | |
| top_levels: int, | |
| left_levels: int, | |
| merge_group_prob: float, | |
| citation_prob: float, | |
| missing_prob: float, | |
| dec_min: int, | |
| dec_max: int, | |
| highlight: bool, | |
| highlight_mode: str, | |
| highlight_rate: float, | |
| highlight_count: int, | |
| highlight_colors: List[str], | |
| highlight_use_all_colors: bool, | |
| highlight_strategy: str, | |
| highlight_rank_k: int, | |
| underline_rate: float, | |
| underline_best_per_col: bool, | |
| underline_second_per_col: bool, | |
| underline_wrong_per_col: bool, | |
| bold_rate: float, | |
| bold_best_per_col: bool, | |
| bold_wrong_per_col: bool, | |
| text_color_delta_sign: bool, | |
| text_color_best_per_col: bool, | |
| text_color_pos_hex: str, | |
| text_color_neg_hex: str, | |
| text_color_best_hex: str, | |
| arrow_rate: float, | |
| arrow_up_ratio: float, | |
| data_arrows: bool, | |
| metric_arrow_prob: float, | |
| config_rows: bool, | |
| config_flag_pool: List[str], | |
| config_shade_best_row: bool, | |
| ) -> TableSpec: | |
| group_pool = ["Group", "Category", "Setting", "Scenario", "Domain", "Subset", "Task", "Condition"] | |
| item_pool = ["Method", "Model", "System", "Approach", "Variant", "Baseline"] | |
| group_header_name = rng.choice(group_pool) | |
| item_header_name = rng.choice(item_pool) | |
| groups = [] | |
| used_item_names: set[str] = set() | |
| for gi in range(group_count): | |
| gname = f"{group_header_name} {chr(65+gi)}" | |
| item_n = rng.randint(min_items, max_items) | |
| items = [] | |
| for _ in range(item_n): | |
| name = _sample_unique_label( | |
| rng, | |
| used_item_names, | |
| lambda: _rand_name(rng, item_pool, suffix=True), | |
| fallback_prefix=str(item_header_name), | |
| ) | |
| if rng.random() < citation_prob: | |
| cid = rng.randint(1, 99) | |
| name = f"{name} [{cid}]" | |
| items.append(name) | |
| groups.append({"name": gname, "items": items}) | |
| if int(left_levels) >= 2: | |
| uniq_group_names = {str(g.get("name", "")).strip() for g in groups if str(g.get("name", "")).strip()} | |
| if len(uniq_group_names) <= 1: | |
| left_levels = 1 | |
| effective_section_count = max(0, min(3, int(section_count))) | |
| if effective_section_count < 2: | |
| effective_section_count = 0 | |
| section_pool = ["Type", "Model", "Family", "Category", "Subset"] | |
| sections = [] | |
| if effective_section_count > 0: | |
| section_n = min(effective_section_count, max(1, len(groups))) | |
| base = len(groups) // section_n | |
| rem = len(groups) % section_n | |
| idx = 0 | |
| section_prefix: Optional[str] = None | |
| for si in range(section_n): | |
| size = base + (1 if si < rem else 0) | |
| chunk = groups[idx : idx + size] | |
| idx += size | |
| sampled_prefix = rng.choice(section_pool) | |
| if section_prefix is None: | |
| section_prefix = sampled_prefix | |
| sname = f"{section_prefix}-{chr(65+si)}" | |
| sections.append({"name": sname, "groups": chunk}) | |
| else: | |
| sections.append({"name": "", "groups": groups}) | |
| block_pool = ["Blk", "Grp", "Sect", "Part", "Set", "Cfg", "Zone", "Slot"] | |
| mid_pool = ["Err", "Qual", "Rate", "Score", "Cost", "Stat", "Comp", "Perf", "Gain", "Loss"] | |
| metric_pool = [ | |
| "MetA", "MetB", "MetC", "MetD", "MetE", | |
| "Score", "Val", "Idx", "Rate", "Rank", | |
| "Err", "Cost", "Eff", "Qual", "Stat", | |
| "S-A", "S-C", "S-D", | |
| ] | |
| blocks = [] | |
| used_metric_labels: set[str] = set() | |
| for bi in range(block_count): | |
| bname = f"{rng.choice(block_pool)}-{chr(65+bi)}" | |
| if top_levels == 3: | |
| mid_n = rng.randint(mid_group_min, mid_group_max) | |
| mid_groups = [] | |
| for _ in range(max(1, mid_n)): | |
| mid_name = rng.choice(mid_pool) | |
| m = rng.randint(min_metrics, max_metrics) | |
| metrics = [ | |
| _sample_unique_label( | |
| rng, | |
| used_metric_labels, | |
| lambda: _rand_metric(rng, metric_pool, metric_arrow_prob), | |
| fallback_prefix="Met", | |
| ) | |
| for _ in range(max(1, m)) | |
| ] | |
| mid_groups.append({"name": mid_name, "metrics": metrics}) | |
| blocks.append({"name": bname, "mid_groups": mid_groups}) | |
| else: | |
| m = rng.randint(min_metrics, max_metrics) | |
| metrics = [ | |
| _sample_unique_label( | |
| rng, | |
| used_metric_labels, | |
| lambda: _rand_metric(rng, metric_pool, metric_arrow_prob), | |
| fallback_prefix="Met", | |
| ) | |
| for _ in range(max(1, m)) | |
| ] | |
| blocks.append({"name": bname, "metrics": metrics}) | |
| data_cols = [] | |
| if top_levels == 3: | |
| for b in blocks: | |
| for mg in b["mid_groups"]: | |
| for m in mg["metrics"]: | |
| data_cols.append({"block": b["name"], "mid": mg["name"], "metric": m}) | |
| else: | |
| for b in blocks: | |
| for m in b["metrics"]: | |
| data_cols.append({"block": b["name"], "metric": m}) | |
| data_rows = sum(len(g["items"]) for g in groups) | |
| section_rows = 0 | |
| if effective_section_count > 0: | |
| section_rows = len(sections) | |
| n_rows = top_levels + data_rows | |
| n_rows += section_rows | |
| left_cols = max(1, int(left_levels)) | |
| n_cols = left_cols + len(data_cols) # Left label columns plus metric columns. | |
| cells: List[PTCell] = [] | |
| # 5) Header | |
| if top_levels == 3: | |
| if left_cols == 2: | |
| cells.append(PTCell(row=0, col=0, row_span=3, text=group_header_name, kind="header")) | |
| cells.append(PTCell(row=0, col=1, row_span=3, text=item_header_name, kind="header")) | |
| else: | |
| cells.append(PTCell(row=0, col=0, row_span=3, text=item_header_name, kind="header")) | |
| c = left_cols | |
| for b in blocks: | |
| span = sum(len(mg["metrics"]) for mg in b["mid_groups"]) | |
| cells.append(PTCell(row=0, col=c, col_span=span, text=b["name"], kind="header")) | |
| c += span | |
| c = left_cols | |
| for b in blocks: | |
| for mg in b["mid_groups"]: | |
| span = len(mg["metrics"]) | |
| cells.append(PTCell(row=1, col=c, col_span=span, text=mg["name"], kind="header")) | |
| c += span | |
| c = left_cols | |
| for b in blocks: | |
| for mg in b["mid_groups"]: | |
| for m in mg["metrics"]: | |
| cells.append(PTCell(row=2, col=c, text=m, kind="header")) | |
| c += 1 | |
| elif top_levels == 2: | |
| if left_cols == 2: | |
| cells.append(PTCell(row=0, col=0, row_span=2, text=group_header_name, kind="header")) | |
| cells.append(PTCell(row=0, col=1, row_span=2, text=item_header_name, kind="header")) | |
| else: | |
| cells.append(PTCell(row=0, col=0, row_span=2, text=item_header_name, kind="header")) | |
| c = left_cols | |
| for b in blocks: | |
| span = len(b["metrics"]) | |
| cells.append(PTCell(row=0, col=c, col_span=span, text=b["name"], kind="header")) | |
| c += span | |
| # Metric row | |
| c = left_cols | |
| for b in blocks: | |
| for m in b["metrics"]: | |
| cells.append(PTCell(row=1, col=c, text=m, kind="header")) | |
| c += 1 | |
| else: | |
| if left_cols == 2: | |
| cells.append(PTCell(row=0, col=0, text=group_header_name, kind="header")) | |
| cells.append(PTCell(row=0, col=1, text=item_header_name, kind="header")) | |
| else: | |
| cells.append(PTCell(row=0, col=0, text=item_header_name, kind="header")) | |
| c = left_cols | |
| used = {} | |
| idx = 0 | |
| for b in blocks: | |
| for m in b["metrics"]: | |
| base = m | |
| arrow = "" | |
| if base.endswith("↑") or base.endswith("↓"): | |
| arrow = base[-1] | |
| base = base[:-1] | |
| count = used.get(base, 0) | |
| used[base] = count + 1 | |
| if count > 0: | |
| suffix = chr(64 + min(26, count + 1)) # A,B,C... | |
| text = f"{base}{suffix}{arrow}" | |
| else: | |
| text = f"{base}{arrow}" | |
| if idx < len(data_cols): | |
| data_cols[idx]["metric"] = text | |
| idx += 1 | |
| cells.append(PTCell(row=0, col=c, text=text, kind="header")) | |
| c += 1 | |
| r = top_levels | |
| used_numbers: set[str] = set() | |
| for sec in sections: | |
| if effective_section_count > 0: | |
| cells.append(PTCell(row=r, col=0, col_span=left_cols, text=sec["name"], kind="section")) | |
| c = left_cols | |
| for colinfo in data_cols: | |
| cells.append(PTCell(row=r, col=c, text=colinfo["metric"], kind="header")) | |
| c += 1 | |
| r += 1 | |
| for g in sec["groups"]: | |
| items = g["items"] | |
| if left_cols == 2: | |
| if rng.random() < merge_group_prob: | |
| cells.append(PTCell(row=r, col=0, row_span=len(items), text=g["name"], kind="group")) | |
| for i, item in enumerate(items): | |
| cells.append(PTCell(row=r + i, col=1, text=item, kind="item")) | |
| else: | |
| for i, item in enumerate(items): | |
| cells.append(PTCell(row=r + i, col=0, text=g["name"], kind="group")) | |
| cells.append(PTCell(row=r + i, col=1, text=item, kind="item")) | |
| else: | |
| for i, item in enumerate(items): | |
| cells.append(PTCell(row=r + i, col=0, text=item, kind="item")) | |
| for i, item in enumerate(items): | |
| cidx = left_cols | |
| for col_meta in data_cols: | |
| metric_text = str(col_meta.get("metric", "")) | |
| allow_missing_here = not _metric_prefers_lower(metric_text) | |
| if allow_missing_here and (rng.random() < missing_prob): | |
| txt = rng.choice(["—", "N/A"]) | |
| val = None | |
| else: | |
| if unique_numbers: | |
| for _try in range(1000): | |
| txt, val = _format_number(rng, dec_min, dec_max) | |
| if txt not in used_numbers: | |
| used_numbers.add(txt) | |
| break | |
| else: | |
| txt, val = _format_number(rng, dec_min, dec_max) | |
| else: | |
| txt, val = _format_number(rng, dec_min, dec_max) | |
| cells.append(PTCell(row=r + i, col=cidx, text=txt, value=val, kind="data")) | |
| cidx += 1 | |
| r += len(items) | |
| delta_col: Optional[int] = None | |
| if config_rows and len(data_cols) > 0: | |
| delta_col = left_cols + len(data_cols) - 1 | |
| delta_label = rng.choice(["ΔGain↑", "ΔDiff↑", "ΔChange↑", "ΔDelta↑"]) | |
| data_cols[-1]["metric"] = delta_label | |
| for c in cells: | |
| if c.kind == "header" and c.col == delta_col and c.col_span == 1: | |
| c.text = delta_label | |
| delta_vals: Dict[int, float] = {} | |
| for c in cells: | |
| if c.kind == "data" and c.col == delta_col: | |
| base = rng.uniform(-2.5, 2.5) | |
| pm = rng.uniform(0.05, 0.80) | |
| c.text = f"{_format_delta(base)} ±{pm:.2f}" | |
| c.value = None # Keep delta annotations out of ordinary numeric tasks. | |
| c.extra["delta_col"] = True | |
| c.extra["delta_base"] = float(base) | |
| delta_vals[c.row] = float(base) | |
| if config_shade_best_row and delta_vals: | |
| best_row = max(delta_vals, key=lambda r: delta_vals[r]) | |
| for c in cells: | |
| if c.row == best_row: | |
| c.extra["shade_row"] = True | |
| data_cells = [c for c in cells if c.kind == "data" and c.value is not None] | |
| delta_cells = [c for c in cells if c.kind == "data" and c.extra.get("delta_col")] | |
| style_cells = data_cells + [c for c in delta_cells if c not in data_cells] | |
| all_data_cells = style_cells | |
| if style_cells: | |
| if highlight and highlight_strategy == "by_column_rank": | |
| palette = list(highlight_colors) | |
| if not palette: | |
| palette = ["#E6F2FF", "#BFD8FF", "#7FAEFF"] | |
| if not highlight_use_all_colors: | |
| k = highlight_rank_k if highlight_rank_k > 0 else min(3, len(palette)) | |
| palette = palette[:k] | |
| if not data_cells and delta_cells: | |
| if highlight_count > 0: | |
| k = min(highlight_count, len(delta_cells)) | |
| else: | |
| k = max(1, int(round(len(delta_cells) * max(0.0, highlight_rate)))) | |
| chosen = rng.sample(delta_cells, k=min(k, len(delta_cells))) | |
| for i, c in enumerate(chosen): | |
| color_hex = palette[i % len(palette)] if highlight_use_all_colors else rng.choice(palette) | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = color_hex.upper() | |
| else: | |
| palette_rev = list(reversed(palette)) | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if not vals: | |
| continue | |
| vals.sort(key=lambda x: float(x.extra.get("delta_base", -1e9)), reverse=True) | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| _sort_cells_for_metric(vals, metric_text) | |
| top_k = min(len(palette_rev), len(vals)) | |
| for i in range(top_k): | |
| c = vals[i] | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = palette_rev[i].upper() | |
| elif highlight and highlight_strategy == "by_column_wrong": | |
| palette = list(highlight_colors) or ["#FFD2E6"] | |
| color_idx = 0 | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| c = rng.choice(pool) | |
| if highlight_use_all_colors and palette: | |
| color_hex = palette[color_idx % len(palette)] | |
| color_idx += 1 | |
| else: | |
| color_hex = rng.choice(palette) | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = color_hex.upper() | |
| elif highlight: | |
| if highlight_count > 0: | |
| k = min(highlight_count, len(style_cells)) | |
| else: | |
| k = max(1, int(round(len(style_cells) * max(0.0, highlight_rate)))) | |
| mode = highlight_mode | |
| if mode == "random": | |
| mode = rng.choice(["single", "multi"]) | |
| if mode == "single": | |
| palette = [rng.choice(highlight_colors)] | |
| else: | |
| if highlight_use_all_colors: | |
| palette = list(highlight_colors) | |
| else: | |
| max_n = min(4, len(highlight_colors)) | |
| pick_n = rng.randint(2, max_n) if max_n >= 2 else 1 | |
| palette = rng.sample(highlight_colors, k=pick_n) | |
| if highlight_use_all_colors and len(palette) > 0: | |
| k = max(k, len(palette)) | |
| chosen = rng.sample(style_cells, k=min(k, len(style_cells))) | |
| for i, c in enumerate(chosen): | |
| if highlight_use_all_colors and palette: | |
| color_hex = palette[i % len(palette)] | |
| else: | |
| color_hex = rng.choice(palette) | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = color_hex.upper() | |
| allow_underline = not ( | |
| highlight | |
| and highlight_strategy == "by_column_rank" | |
| and not (underline_best_per_col or underline_second_per_col or underline_wrong_per_col) | |
| ) | |
| if allow_underline: | |
| if underline_best_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if not vals: | |
| continue | |
| best = max(vals, key=lambda x: float(x.extra.get("delta_base", -1e9))) | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| best.extra["underline"] = "true" | |
| elif underline_second_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if len(vals) <= 1: | |
| continue | |
| vals.sort(key=lambda x: float(x.extra.get("delta_base", -1e9)), reverse=True) | |
| vals[1].extra["underline"] = "true" | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| _sort_cells_for_metric(vals, metric_text) | |
| vals[1].extra["underline"] = "true" | |
| elif underline_wrong_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if len(vals) <= 1: | |
| continue | |
| best = max(vals, key=lambda x: float(x.extra.get("delta_base", -1e9))) | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| rng.choice(pool).extra["underline"] = "true" | |
| elif underline_rate > 0: | |
| k = max(1, int(round(len(style_cells) * max(0.0, underline_rate)))) | |
| chosen = rng.sample(style_cells, k=min(k, len(style_cells))) | |
| for c in chosen: | |
| c.extra["underline"] = "true" | |
| allow_bold = not (highlight and highlight_strategy == "by_column_rank" and not (bold_best_per_col or bold_wrong_per_col)) | |
| if allow_bold: | |
| if bold_best_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if not vals: | |
| continue | |
| best = max(vals, key=lambda x: float(x.extra.get("delta_base", -1e9))) | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| best.extra["bold"] = "true" | |
| elif bold_wrong_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| if delta_col is not None and col_idx == delta_col: | |
| vals = [c for c in all_data_cells if c.col == col_idx and c.extra.get("delta_col")] | |
| if len(vals) <= 1: | |
| continue | |
| best = max(vals, key=lambda x: float(x.extra.get("delta_base", -1e9))) | |
| else: | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if len(vals) <= 1: | |
| continue | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| pool = [c for c in vals if c is not best] | |
| if not pool: | |
| continue | |
| rng.choice(pool).extra["bold"] = "true" | |
| elif bold_rate > 0: | |
| k = max(1, int(round(len(style_cells) * max(0.0, bold_rate)))) | |
| chosen = rng.sample(style_cells, k=min(k, len(style_cells))) | |
| for c in chosen: | |
| c.extra["bold"] = "true" | |
| if text_color_delta_sign: | |
| for c in delta_cells: | |
| base = c.extra.get("delta_base") | |
| if base is None: | |
| continue | |
| try: | |
| base_f = float(base) | |
| except Exception: | |
| continue | |
| if base_f > 0: | |
| _apply_text_color_mark(c, color_hex=text_color_pos_hex, role="delta_positive") | |
| elif base_f < 0: | |
| _apply_text_color_mark(c, color_hex=text_color_neg_hex, role="delta_negative") | |
| if text_color_best_per_col: | |
| for col_idx in range(left_cols, left_cols + len(data_cols)): | |
| if delta_col is not None and col_idx == delta_col: | |
| continue | |
| vals = [c for c in data_cells if c.col == col_idx and c.value is not None] | |
| if not vals: | |
| continue | |
| metric_text = str(data_cols[col_idx - left_cols].get("metric", "")) | |
| best = _pick_best_cell_by_metric(vals, metric_text) | |
| _apply_text_color_mark(best, color_hex=text_color_best_hex, role="best_per_col") | |
| if data_arrows and arrow_rate > 0: | |
| k = max(1, int(round(len(data_cells) * max(0.0, arrow_rate)))) | |
| chosen = rng.sample(data_cells, k=min(k, len(data_cells))) | |
| for c in chosen: | |
| c.extra["arrow"] = "up" if rng.random() < arrow_up_ratio else "down" | |
| return TableSpec( | |
| n_rows=n_rows, | |
| n_cols=n_cols, | |
| header_rows=top_levels, | |
| data_row_start=top_levels, | |
| left_cols=left_cols, | |
| top_levels=top_levels, | |
| left_levels=left_levels, | |
| cells=cells, | |
| data_cols=data_cols, | |
| delta_col=delta_col, | |
| ) | |
| # ========================= | |
| # ========================= | |
| def render_table( | |
| spec: TableSpec, | |
| *, | |
| out_path: Path, | |
| canvas_width: int, | |
| canvas_height: int, | |
| margins: Tuple[int, int, int, int], | |
| font_path: Optional[str], | |
| font_size: int, | |
| line_style: str, # none | grid | three-line | sparse-grid | |
| block_sep: bool, | |
| number_align: str, | |
| arrow_offset: Tuple[int, int], | |
| arrow_scale: float, | |
| delta_pm_scale: float = 1.00, | |
| crop_to_table: bool = True, | |
| crop_pad: int = 12, | |
| ) -> None: | |
| left, top, right, bottom = margins | |
| avail_w = canvas_width - left - right | |
| avail_h = canvas_height - top - bottom | |
| fpath = font_path or _auto_font_path() | |
| if fpath and Path(fpath).exists(): | |
| font = ImageFont.truetype(fpath, font_size) | |
| else: | |
| font = ImageFont.load_default() | |
| symbol_paths = _auto_symbol_font_candidates() | |
| if fpath: | |
| symbol_paths.append(fpath) | |
| font_check = _pick_font_for_text(symbol_paths, "✓✗", int(round(font_size * 1.15))) or font | |
| _measure = ImageDraw.Draw(Image.new("RGB", (10, 10))) | |
| if spec.left_cols == 2: | |
| left_ratios = [0.14, 0.22] | |
| else: | |
| left_ratios = [0.22] | |
| data_col_count = max(1, (spec.n_cols - spec.left_cols)) | |
| pad_est = max(2, font_size // 6) | |
| col_need_px = [0 for _ in range(max(1, spec.n_cols))] | |
| delta_pm_scale = max(0.60, min(1.10, float(delta_pm_scale))) | |
| pm_size_est = max(8, int(round(font_size * delta_pm_scale))) | |
| kerning_est = max(1, pm_size_est // 12) | |
| gap_pm_est = max(2, pm_size_est // 6) | |
| if fpath and Path(fpath).exists(): | |
| try: | |
| font_pm_est = ImageFont.truetype(fpath, pm_size_est) | |
| except Exception: | |
| font_pm_est = font | |
| else: | |
| font_pm_est = font | |
| for c in spec.cells: | |
| if c.col_span != 1: | |
| continue | |
| col_idx = int(c.col) | |
| if not (0 <= col_idx < len(col_need_px)): | |
| continue | |
| txt = str(c.text or "") | |
| if not txt: | |
| continue | |
| if c.kind == "data" and "±" in txt: | |
| try: | |
| main_text, pm_text = txt.split("±", 1) | |
| main_text = main_text.strip() | |
| pm_text = "±" + pm_text.strip() | |
| tb_main = _measure.textbbox((0, 0), main_text, font=font) | |
| main_w = tb_main[2] - tb_main[0] | |
| tb_sym = _measure.textbbox((0, 0), "±", font=font_pm_est) | |
| tb_dig = _measure.textbbox((0, 0), pm_text[1:], font=font_pm_est) | |
| sym_w = tb_sym[2] - tb_sym[0] | |
| dig_w = tb_dig[2] - tb_dig[0] | |
| text_w = main_w + gap_pm_est + (sym_w + dig_w - kerning_est) | |
| except Exception: | |
| tb = _measure.textbbox((0, 0), txt, font=font) | |
| text_w = tb[2] - tb[0] | |
| else: | |
| font_obj = font_check if ("✓" in txt or "✗" in txt or c.extra.get("is_flag")) else font | |
| tb = _measure.textbbox((0, 0), txt, font=font_obj) | |
| text_w = tb[2] - tb[0] | |
| extra_pad = pad_est * 2 | |
| if c.kind in ("header", "section"): | |
| extra_pad += max(2, font_size // 8) | |
| col_need_px[col_idx] = max(col_need_px[col_idx], int(text_w + extra_pad)) | |
| col_floor_px: List[int] = [] | |
| for ci in range(spec.n_cols): | |
| if ci < spec.left_cols: | |
| if spec.left_cols == 2: | |
| floor = int(font_size * (4.8 if ci == 0 else 7.2)) | |
| else: | |
| floor = int(font_size * 6.5) | |
| else: | |
| floor = int(font_size * 4.0) | |
| if spec.delta_col is not None and ci == spec.delta_col: | |
| delta_floor_mul = 1.28 if delta_pm_scale >= 0.98 else 1.12 | |
| floor = int(round(floor * delta_floor_mul)) | |
| col_floor_px.append(max(36, floor)) | |
| natural_table_w = sum(max(col_need_px[i], col_floor_px[i]) for i in range(spec.n_cols)) | |
| if data_col_count <= 3: | |
| min_fill_ratio = 0.70 | |
| elif data_col_count <= 5: | |
| min_fill_ratio = 0.76 | |
| elif data_col_count <= 8: | |
| min_fill_ratio = 0.84 | |
| elif data_col_count <= 12: | |
| min_fill_ratio = 0.91 | |
| else: | |
| min_fill_ratio = 0.96 | |
| target_table_w = int(round(natural_table_w * 1.06)) # Leave room to avoid over-compression. | |
| table_w = min(avail_w, max(int(round(avail_w * min_fill_ratio)), target_table_w)) | |
| table_w = max(1, table_w) | |
| table_left = left + max(0, (avail_w - table_w) // 2) | |
| left_w = [int(table_w * r) for r in left_ratios] | |
| data_w = max(1, table_w - sum(left_w)) | |
| weights = [1.0 for _ in range(data_col_count)] | |
| if spec.delta_col is not None: | |
| idx = spec.delta_col - spec.left_cols | |
| if 0 <= idx < len(weights): | |
| pad = max(2, font_size // 6) | |
| pm_size = max(8, int(round(font_size * delta_pm_scale))) | |
| gap_pm = max(2, pm_size // 6) | |
| kerning = max(1, pm_size // 12) | |
| font_pm = ImageFont.truetype(fpath, pm_size) if fpath else font | |
| max_w = 0 | |
| for c in spec.cells: | |
| if c.col != spec.delta_col: | |
| continue | |
| txt = c.text or "" | |
| if c.kind == "data" and "±" in txt: | |
| main_text, pm_text = txt.split("±", 1) | |
| main_text = main_text.strip() | |
| pm_text = "±" + pm_text.strip() | |
| tb_main = _measure.textbbox((0, 0), main_text, font=font) | |
| main_w = tb_main[2] - tb_main[0] | |
| tb_sym = _measure.textbbox((0, 0), "±", font=font_pm) | |
| tb_dig = _measure.textbbox((0, 0), pm_text[1:], font=font_pm) | |
| sym_w = tb_sym[2] - tb_sym[0] | |
| dig_w = tb_dig[2] - tb_dig[0] | |
| pm_w = sym_w + dig_w - kerning | |
| w = main_w + gap_pm + pm_w + pad * 2 | |
| else: | |
| tb = _measure.textbbox((0, 0), txt, font=font) | |
| w = (tb[2] - tb[0]) + pad * 2 | |
| if w > max_w: | |
| max_w = w | |
| base_col_w = data_w / data_col_count if data_col_count > 0 else data_w | |
| need_weight = max_w / max(1.0, base_col_w) | |
| delta_fullsize = delta_pm_scale >= 0.98 | |
| if data_col_count <= 4: | |
| soft_cap = 1.55 if delta_fullsize else 1.35 | |
| soft_floor = 1.18 if delta_fullsize else 1.08 | |
| elif data_col_count <= 8: | |
| soft_cap = 1.72 if delta_fullsize else 1.50 | |
| soft_floor = 1.22 if delta_fullsize else 1.10 | |
| else: | |
| soft_cap = 1.88 if delta_fullsize else 1.65 | |
| soft_floor = 1.24 if delta_fullsize else 1.12 | |
| widened = max(soft_floor, need_weight) | |
| weights[idx] = min(soft_cap, max(1.0, widened)) | |
| total_w = sum(weights) | |
| col_edges = [table_left] | |
| for w in left_w: | |
| col_edges.append(col_edges[-1] + w) | |
| for i in range(data_col_count): | |
| w = int(round(data_w * (weights[i] / total_w))) | |
| col_edges.append(col_edges[-1] + w) | |
| col_edges[-1] = table_left + table_w | |
| section_header_rows = {c.row for c in spec.cells if c.kind == "section"} | |
| hidden_header_metric_row: Optional[int] = None | |
| if section_header_rows and spec.header_rows >= 2: | |
| hidden_header_metric_row = spec.header_rows - 1 | |
| weights = [] | |
| for r in range(spec.n_rows): | |
| if hidden_header_metric_row is not None and r == hidden_header_metric_row: | |
| weights.append(0.0) | |
| elif r < spec.header_rows: | |
| weights.append(1.2) | |
| else: | |
| weights.append(1.0) | |
| total_w = sum(weights) | |
| row_edges = [top] | |
| for w in weights: | |
| row_edges.append(int(round(row_edges[-1] + avail_h * (w / total_w)))) | |
| row_edges[-1] = top + avail_h | |
| img = Image.new("RGB", (canvas_width, canvas_height), (255, 255, 255)) | |
| draw = ImageDraw.Draw(img) | |
| def bbox_for(cell: PTCell) -> Tuple[int, int, int, int]: | |
| x1 = col_edges[cell.col] | |
| x2 = col_edges[cell.col + cell.col_span] | |
| y1 = row_edges[cell.row] | |
| y2 = row_edges[cell.row + cell.row_span] | |
| return (x1, y1, x2, y2) | |
| def fit_text_truncate(text: str, max_w: int) -> str: | |
| if max_w <= 0: | |
| return "" | |
| tb = draw.textbbox((0, 0), text, font=font) | |
| tw = tb[2] - tb[0] | |
| if tw <= max_w: | |
| return text | |
| lo, hi = 0, len(text) | |
| best = "" | |
| while lo <= hi: | |
| mid = (lo + hi) // 2 | |
| cand = text[:mid] | |
| w = draw.textbbox((0, 0), cand, font=font)[2] | |
| if w <= max_w: | |
| best = cand | |
| lo = mid + 1 | |
| else: | |
| hi = mid - 1 | |
| return best | |
| underline_width = max(1, font_size // 12) | |
| bold_offsets = [(0, 0), (1, 0), (0, 1)] if font_size >= 18 else [(0, 0), (1, 0)] | |
| def draw_text_marked( | |
| xy: Tuple[int, int], | |
| text: str, | |
| *, | |
| font_obj: ImageFont.FreeTypeFont | ImageFont.ImageFont, | |
| fill: Tuple[int, int, int], | |
| bold: bool, | |
| ) -> None: | |
| if not bold: | |
| draw.text(xy, text, font=font_obj, fill=fill) | |
| return | |
| x, y = xy | |
| for dx, dy in bold_offsets: | |
| draw.text((x + dx, y + dy), text, font=font_obj, fill=fill) | |
| shade_rows = {c.row for c in spec.cells if c.extra.get("shade_row")} | |
| for r in shade_rows: | |
| y1 = row_edges[r] | |
| y2 = row_edges[r + 1] | |
| draw.rectangle((col_edges[0], y1, col_edges[-1], y2), fill=(242, 242, 242)) | |
| for cell in spec.cells: | |
| bbox = bbox_for(cell) | |
| cell.bbox = bbox | |
| x1, y1, x2, y2 = bbox | |
| if x2 <= x1 or y2 <= y1: | |
| continue | |
| pad = max(2, font_size // 6) | |
| if cell.extra.get("highlight") == "true": | |
| try: | |
| color = _hex_to_rgb(cell.extra.get("highlight_color", "#FFD2E6")) | |
| draw.rectangle(bbox, fill=color) | |
| except Exception: | |
| pass | |
| align = "center" | |
| if cell.kind == "group": | |
| align = "center" | |
| if cell.kind == "item": | |
| align = "center" | |
| if cell.kind == "data": | |
| align = number_align | |
| text = cell.text | |
| base, cite = _split_citation(text) | |
| main_color = (0, 0, 0) | |
| cite_color = (30, 102, 204) | |
| if cell.kind == "data" and cell.extra.get("text_color") == "true": | |
| try: | |
| main_color = _hex_to_rgb(str(cell.extra.get("text_color_hex") or "#000000")) | |
| except Exception: | |
| main_color = (0, 0, 0) | |
| if cell.kind == "data": | |
| pad = max(2, font_size // 6) | |
| gap = max(3, font_size // 5) # Gap between arrow and number, scaled by font size. | |
| arrow = cell.extra.get("arrow") | |
| base_arrow = max(6, int(round(font_size * float(arrow_scale)))) if arrow in ("up", "down") else 0 | |
| max_text_w = (x2 - x1) - 2 * pad - (base_arrow + (gap if base_arrow > 0 else 0)) | |
| max_text_w = max(10, max_text_w) | |
| text = cell.text | |
| delta_mode = bool(cell.extra.get("delta_col")) and "±" in text | |
| if delta_mode: | |
| main_text, pm_text = text.split("±", 1) | |
| main_text = main_text.strip() | |
| pm_text = "±" + pm_text.strip() | |
| measure_text = main_text | |
| else: | |
| main_text, pm_text = "", "" | |
| measure_text = text | |
| tb = draw.textbbox((0, 0), measure_text, font=font) | |
| tw = tb[2] - tb[0] | |
| th = draw.textbbox((0, 0), "Ag", font=font)[3] | |
| s = 1.0 | |
| if tw > max_text_w: | |
| s = max(0.60, max_text_w / max(1, tw)) # Do not shrink below 60%. | |
| if s < 0.999 and fpath and Path(fpath).exists(): | |
| font2 = ImageFont.truetype(fpath, max(8, int(round(font_size * s)))) | |
| else: | |
| font2 = font | |
| if delta_mode: | |
| tb_main = draw.textbbox((0, 0), main_text, font=font2) | |
| tw2 = tb_main[2] - tb_main[0] | |
| th2 = draw.textbbox((0, 0), "Ag", font=font2)[3] | |
| pm_size = max(8, int(round(font_size * s * delta_pm_scale))) | |
| font_pm = ImageFont.truetype(fpath, pm_size) if fpath else font2 | |
| pm_symbol = "±" | |
| pm_digits = pm_text[1:] if pm_text.startswith("±") else pm_text | |
| tb_sym = draw.textbbox((0, 0), pm_symbol, font=font_pm) | |
| tb_dig = draw.textbbox((0, 0), pm_digits, font=font_pm) | |
| sym_w = tb_sym[2] - tb_sym[0] | |
| dig_w = tb_dig[2] - tb_dig[0] | |
| pm_h = max(tb_sym[3] - tb_sym[1], tb_dig[3] - tb_dig[1]) | |
| kerning = max(1, pm_size // 12) | |
| pm_w = sym_w + dig_w - kerning | |
| gap_pm = max(2, pm_size // 6) | |
| max_text_w2 = max_text_w - (pm_w + gap_pm) | |
| if max_text_w2 > 0 and tw > max_text_w2: | |
| s = max(0.60, max_text_w2 / max(1, tw)) | |
| if s < 0.999 and fpath and Path(fpath).exists(): | |
| font2 = ImageFont.truetype(fpath, max(8, int(round(font_size * s)))) | |
| else: | |
| font2 = font | |
| tb_main = draw.textbbox((0, 0), main_text, font=font2) | |
| tw2 = tb_main[2] - tb_main[0] | |
| th2 = draw.textbbox((0, 0), "Ag", font=font2)[3] | |
| pm_size = max(8, int(round(font_size * s * delta_pm_scale))) | |
| font_pm = ImageFont.truetype(fpath, pm_size) if fpath else font2 | |
| tb_sym = draw.textbbox((0, 0), pm_symbol, font=font_pm) | |
| tb_dig = draw.textbbox((0, 0), pm_digits, font=font_pm) | |
| sym_w = tb_sym[2] - tb_sym[0] | |
| dig_w = tb_dig[2] - tb_dig[0] | |
| pm_h = max(tb_sym[3] - tb_sym[1], tb_dig[3] - tb_dig[1]) | |
| kerning = max(1, pm_size // 12) | |
| pm_w = sym_w + dig_w - kerning | |
| gap_pm = max(2, pm_size // 6) | |
| else: | |
| tb2 = draw.textbbox((0, 0), text, font=font2) | |
| tw2 = tb2[2] - tb2[0] | |
| th2 = draw.textbbox((0, 0), "Ag", font=font2)[3] | |
| usable_right = x2 - pad - (base_arrow + (gap if base_arrow > 0 else 0)) | |
| if delta_mode: | |
| usable_right -= (pm_w + gap_pm) | |
| usable_left = x1 + pad | |
| if number_align == "left": | |
| tx = usable_left | |
| elif number_align == "right": | |
| tx = usable_right - tw2 | |
| else: | |
| tx = usable_left + (usable_right - usable_left - tw2) // 2 | |
| ty = y1 + (y2 - y1 - th2) // 2 | |
| if delta_mode: | |
| gap_pm = max(2, pm_size // 6) | |
| pm_x = tx + tw2 + gap_pm | |
| pm_y = ty + th2 - pm_h - max(1, pm_size // 3) | |
| pm_y = max(y1 + pad, pm_y) | |
| if pm_x + pm_w > (x2 - pad): | |
| shift = (pm_x + pm_w) - (x2 - pad) | |
| tx = max(x1 + pad, tx - shift) | |
| pm_x = tx + tw2 + gap_pm | |
| is_bold = cell.extra.get("bold") == "true" | |
| draw_text_marked((tx, ty), main_text, font_obj=font2, fill=main_color, bold=is_bold) | |
| draw_text_marked((pm_x, pm_y), pm_symbol, font_obj=font_pm, fill=main_color, bold=is_bold) | |
| draw_text_marked((pm_x + sym_w - kerning, pm_y), pm_digits, font_obj=font_pm, fill=main_color, bold=is_bold) | |
| else: | |
| draw_text_marked( | |
| (tx, ty), | |
| text, | |
| font_obj=font2, | |
| fill=main_color, | |
| bold=(cell.extra.get("bold") == "true"), | |
| ) | |
| if cell.extra.get("underline") == "true": | |
| underline_y = ty + th2 + max(2, int(round(font_size * s * 0.10))) | |
| draw.line((tx, underline_y, tx + tw2, underline_y), fill=(0, 0, 0), width=underline_width) | |
| if arrow in ("up", "down"): | |
| size = max(5, int(round(base_arrow * s))) | |
| half = size // 2 | |
| ax = tx + tw2 + gap | |
| ax = min(ax, x2 - pad - size) | |
| cy = (y1 + y2) // 2 | |
| head_h = max(4, int(round(size * 0.60))) | |
| shaft_len = max(4, int(round(size * 1.00))) | |
| thickness = max(1, int(round(2 * s))) | |
| if arrow == "up": | |
| tip = (ax + half, cy - shaft_len // 2 - head_h) | |
| base_y = tip[1] + head_h | |
| draw.polygon([tip, (ax, base_y), (ax + size, base_y)], fill=main_color) | |
| draw.line((ax + half, base_y, ax + half, base_y + shaft_len), fill=main_color, width=thickness) | |
| else: | |
| tip = (ax + half, cy + shaft_len // 2 + head_h) | |
| base_y = tip[1] - head_h | |
| draw.polygon([tip, (ax, base_y), (ax + size, base_y)], fill=main_color) | |
| draw.line((ax + half, base_y - shaft_len, ax + half, base_y), fill=main_color, width=thickness) | |
| continue | |
| text_font = font_check if ("✓" in text or "✗" in text or cell.extra.get("is_flag")) else font | |
| max_text_w = (x2 - x1) - 2 * pad | |
| max_text_w = max(10, max_text_w) | |
| if cite: | |
| base_fit = fit_text_truncate(base, max_text_w) | |
| tb1 = draw.textbbox((0, 0), base_fit, font=font) | |
| tb2 = draw.textbbox((0, 0), cite, font=font) | |
| tw = (tb1[2] - tb1[0]) + 4 + (tb2[2] - tb2[0]) | |
| if tw > max_text_w: | |
| base_fit = fit_text_truncate(base, max_text_w - (tb2[2] - tb2[0]) - 4) | |
| tb1 = draw.textbbox((0, 0), base_fit, font=font) | |
| tw = (tb1[2] - tb1[0]) + 4 + (tb2[2] - tb2[0]) | |
| if tw > max_text_w: | |
| cite = "" | |
| base = base_fit | |
| if cite: | |
| tb1 = draw.textbbox((0, 0), base, font=font) | |
| tb2 = draw.textbbox((0, 0), cite, font=font) | |
| tw = (tb1[2] - tb1[0]) + 4 + (tb2[2] - tb2[0]) | |
| else: | |
| text_fit = fit_text_truncate(text, max_text_w) | |
| tb = draw.textbbox((0, 0), text_fit, font=text_font) | |
| tw = tb[2] - tb[0] | |
| text = text_fit | |
| th = draw.textbbox((0, 0), "Ag", font=text_font)[3] | |
| if align == "left": | |
| tx = x1 + pad | |
| elif align == "right": | |
| tx = x2 - pad - tw | |
| else: | |
| tx = x1 + (x2 - x1 - tw) // 2 | |
| ty = y1 + (y2 - y1 - th) // 2 | |
| if cite: | |
| draw_text_marked( | |
| (tx, ty), | |
| base, | |
| font_obj=font, | |
| fill=main_color, | |
| bold=(cell.extra.get("bold") == "true"), | |
| ) | |
| tb1 = draw.textbbox((0, 0), base, font=font) | |
| bx = tx + (tb1[2] - tb1[0]) + 4 | |
| draw_text_marked( | |
| (bx, ty), | |
| cite, | |
| font_obj=font, | |
| fill=cite_color, | |
| bold=(cell.extra.get("bold") == "true"), | |
| ) | |
| else: | |
| draw_text_marked( | |
| (tx, ty), | |
| text, | |
| font_obj=text_font, | |
| fill=main_color, | |
| bold=(cell.extra.get("bold") == "true"), | |
| ) | |
| def _draw_hline(y: int, x1: int, x2: int, w: int = 1, color: Tuple[int, int, int] = (50, 50, 50)) -> None: | |
| draw.rectangle((x1, y, x2, y + w - 1), fill=color) | |
| def _draw_vline(x: int, y1: int, y2: int, w: int = 1, color: Tuple[int, int, int] = (50, 50, 50)) -> None: | |
| draw.rectangle((x, y1, x + w - 1, y2), fill=color) | |
| if line_style == "grid": | |
| for y in row_edges: | |
| _draw_hline(y, col_edges[0], col_edges[-1], 1) | |
| for i, x in enumerate(col_edges): | |
| if i == 0 or i == len(col_edges) - 1: | |
| continue | |
| _draw_vline(x, row_edges[0], row_edges[-1], 1) | |
| elif line_style == "sparse-grid": | |
| top_y = row_edges[0] | |
| header_y = row_edges[spec.top_levels] | |
| bottom_y = row_edges[-1] | |
| left_x = col_edges[0] | |
| right_x = col_edges[-1] | |
| _draw_hline(top_y, left_x, right_x, 1) | |
| _draw_hline(bottom_y, left_x, right_x, 1) | |
| _draw_hline(header_y, left_x, right_x, 1) | |
| for i in range(1, spec.left_cols + 1): | |
| x = col_edges[i] | |
| _draw_vline(x, top_y, bottom_y, 1, (60, 60, 60)) | |
| if block_sep and spec.n_cols > spec.left_cols: | |
| data_start = spec.left_cols | |
| last_block = None | |
| for i, colinfo in enumerate(spec.data_cols): | |
| if colinfo["block"] != last_block: | |
| x = col_edges[data_start + i] | |
| _draw_vline(x, top_y, bottom_y, 1, (80, 80, 80)) | |
| last_block = colinfo["block"] | |
| elif line_style == "three-line": | |
| top_y = row_edges[0] | |
| header_y = row_edges[spec.header_rows] | |
| bottom_y = row_edges[-1] | |
| _draw_hline(top_y, col_edges[0], col_edges[-1], 2, (30, 30, 30)) | |
| _draw_hline(header_y, col_edges[0], col_edges[-1], 2, (30, 30, 30)) | |
| _draw_hline(bottom_y, col_edges[0], col_edges[-1], 2, (30, 30, 30)) | |
| if block_sep and spec.n_cols > spec.left_cols: | |
| data_start = spec.left_cols | |
| last_block = None | |
| for i, colinfo in enumerate(spec.data_cols): | |
| if colinfo["block"] != last_block: | |
| x = col_edges[data_start + i] | |
| _draw_vline(x, top_y, bottom_y, 1, (80, 80, 80)) | |
| last_block = colinfo["block"] | |
| if line_style != "none" and section_header_rows: | |
| left_x = col_edges[0] | |
| right_x = col_edges[-1] | |
| for r in sorted(section_header_rows): | |
| y_top = row_edges[r] | |
| y_bottom = row_edges[r + 1] | |
| if y_bottom <= y_top: | |
| continue | |
| _draw_hline(y_top, left_x, right_x, 1, (55, 55, 55)) | |
| _draw_hline(y_bottom, left_x, right_x, 1, (55, 55, 55)) | |
| if crop_to_table: | |
| pad = max(0, int(crop_pad)) | |
| tx1 = max(0, col_edges[0] - pad) | |
| ty1 = max(0, row_edges[0] - pad) | |
| tx2 = min(img.width, col_edges[-1] + pad + 1) | |
| ty2 = min(img.height, row_edges[-1] + pad + 1) | |
| if tx2 > tx1 and ty2 > ty1: | |
| img = img.crop((tx1, ty1, tx2, ty2)) | |
| for c in spec.cells: | |
| if c.bbox is None: | |
| continue | |
| x1, y1, x2, y2 = c.bbox | |
| c.bbox = (x1 - tx1, y1 - ty1, x2 - tx1, y2 - ty1) | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| img.save(str(out_path)) | |
| def _spec_layout_is_readable( | |
| spec: TableSpec, | |
| *, | |
| canvas_width: int, | |
| canvas_height: int, | |
| margins: Tuple[int, int, int, int], | |
| font_path: Optional[str], | |
| font_size: int, | |
| arrow_scale: float, | |
| ) -> bool: | |
| """Heuristic readability guard: reject layouts that are too dense for the canvas/font. | |
| Goal: prevent visibly cramped tables where row heights are too small or numeric text | |
| would need excessive shrinking (which can cause overlap / illegibility). | |
| """ | |
| left, top, right, bottom = margins | |
| avail_w = int(canvas_width) - left - right | |
| avail_h = int(canvas_height) - top - bottom | |
| if avail_w <= 0 or avail_h <= 0: | |
| return False | |
| if spec.n_rows <= 0 or spec.n_cols <= 0: | |
| return False | |
| # Approximate row heights (same rule as render_table). | |
| row_weights = [1.2 if r < spec.header_rows else 1.0 for r in range(spec.n_rows)] | |
| total_row_w = sum(row_weights) or 1.0 | |
| row_edges = [top] | |
| for w in row_weights: | |
| row_edges.append(int(round(row_edges[-1] + avail_h * (w / total_row_w)))) | |
| row_edges[-1] = top + avail_h | |
| row_heights = [max(0, row_edges[i + 1] - row_edges[i]) for i in range(spec.n_rows)] | |
| if not row_heights: | |
| return False | |
| # Measure text height with actual font. | |
| fpath = font_path or _auto_font_path() | |
| if fpath and Path(fpath).exists(): | |
| font_obj = ImageFont.truetype(fpath, font_size) | |
| else: | |
| font_obj = ImageFont.load_default() | |
| measure = ImageDraw.Draw(Image.new("RGB", (10, 10))) | |
| text_h = measure.textbbox((0, 0), "Ag", font=font_obj)[3] | |
| min_row_needed = text_h + max(2, font_size // 8) | |
| if min(row_heights) < min_row_needed: | |
| return False | |
| # Approximate data-column widths (same base logic as render_table, simplified). | |
| if spec.left_cols == 2: | |
| left_ratios = [0.14, 0.22] | |
| else: | |
| left_ratios = [0.22] | |
| left_w = [int(avail_w * r) for r in left_ratios] | |
| data_w = max(1, avail_w - sum(left_w)) | |
| data_col_count = max(1, (spec.n_cols - spec.left_cols)) | |
| col_weights = [1.0 for _ in range(data_col_count)] | |
| if spec.delta_col is not None: | |
| idx = spec.delta_col - spec.left_cols | |
| if 0 <= idx < len(col_weights): | |
| # Delta column is widened in render_table; keep a conservative bump here too. | |
| col_weights[idx] = max(col_weights[idx], 1.85) | |
| total_col_w = sum(col_weights) or 1.0 | |
| data_col_widths = [int(round(data_w * (w / total_col_w))) for w in col_weights] | |
| if data_col_widths: | |
| # Fix rounding drift to preserve total width. | |
| data_col_widths[-1] += (data_w - sum(data_col_widths)) | |
| min_data_col_w = min(data_col_widths) if data_col_widths else data_w | |
| # Estimate whether a typical numeric cell can fit without over-shrinking. | |
| pad = max(2, font_size // 6) | |
| gap = max(3, font_size // 5) | |
| base_arrow = max(6, int(round(font_size * float(arrow_scale)))) | |
| sample_num = "88.88" | |
| sample_w_bbox = measure.textbbox((0, 0), sample_num, font=font_obj) | |
| sample_num_w = max(1, sample_w_bbox[2] - sample_w_bbox[0]) | |
| max_text_space = min_data_col_w - 2 * pad - (base_arrow + gap) | |
| # Require at least ~75% scale for a typical number; lower than this tends to look cramped. | |
| if max_text_space < int(round(sample_num_w * 0.75)): | |
| return False | |
| return True | |
| # ========================= | |
| # ========================= | |
| _QA_PLACEHOLDER_RE = re.compile(r"\{[A-Z0-9_]+\}") | |
| _DG_TOKEN_RE = re.compile(r"\bDG\b") | |
| _DG_DEF_CANON = "The numeric part of the table includes numeric cells only; exclude all headers/section headers and left header columns." | |
| _DG_DEF_PLAIN = ( | |
| "Row/col indices refer to the numeric part of the table only; exclude all headers/section headers and left header columns." | |
| ) | |
| def _load_question_library(path: Optional[str]) -> Optional[Dict[str, Any]]: | |
| if not path: | |
| return None | |
| p = Path(path) | |
| if not p.exists(): | |
| return None | |
| try: | |
| data = json.loads(p.read_text(encoding="utf-8")) | |
| except Exception: | |
| return None | |
| index: Dict[str, Dict[str, Any]] = {} | |
| for t in data.get("tasks", []): | |
| name = t.get("task_name") | |
| if name: | |
| index[name] = t | |
| for alias in t.get("aliases_old") or []: | |
| index[str(alias)] = t | |
| return {"data": data, "index": index} | |
| def _qa_task_entry(qa_lib: Optional[Dict[str, Any]], task_id: str) -> Optional[Dict[str, Any]]: | |
| if not qa_lib: | |
| return None | |
| return qa_lib.get("index", {}).get(task_id) | |
| def _qa_attach_task_metadata(item: Dict[str, Any], qa_lib: Optional[Dict[str, Any]]) -> Dict[str, Any]: | |
| """Attach canonical template/category metadata from question.json (if available).""" | |
| task_id = str(item.get("task_id") or "") | |
| task_entry = _qa_task_entry(qa_lib, task_id) | |
| if not task_entry: | |
| return item | |
| if "qa_task_name" not in item and task_entry.get("task_name"): | |
| item["qa_task_name"] = task_entry.get("task_name") | |
| if "qa_category" not in item and task_entry.get("category"): | |
| item["qa_category"] = task_entry.get("category") | |
| if "qa_category_id" not in item and task_entry.get("category_id") is not None: | |
| item["qa_category_id"] = task_entry.get("category_id") | |
| return item | |
| def _qa_requirements_ok( | |
| task_entry: Optional[Dict[str, Any]], | |
| facts: Dict[str, bool], | |
| extra: Optional[Dict[str, Any]] = None, | |
| ) -> bool: | |
| if not task_entry: | |
| return True | |
| reqs = task_entry.get("requirements") or [] | |
| if not reqs: | |
| return True | |
| extra = extra or {} | |
| for r in reqs: | |
| if r == "has_highlight" and not facts.get("has_highlight"): | |
| return False | |
| if r == "has_underline" and not facts.get("has_underline"): | |
| return False | |
| if r == "has_bold" and not facts.get("has_bold"): | |
| return False | |
| if r == "has_text_color" and not facts.get("has_text_color"): | |
| return False | |
| if r == "has_highlight_or_underline" and not facts.get("has_highlight_or_underline"): | |
| return False | |
| if r == "has_styled_marker" and not facts.get("has_styled_marker"): | |
| return False | |
| if r == "has_delta_col" and not facts.get("has_delta_col"): | |
| return False | |
| if r == "has_group" and not facts.get("has_group"): | |
| return False | |
| if r == "has_missing" and not facts.get("has_missing"): | |
| return False | |
| if r == "has_metric_arrow" and not facts.get("has_metric_arrow"): | |
| return False | |
| if r == "palette_list" and not facts.get("palette_list"): | |
| return False | |
| if r == "unique_anchor_value" and not extra.get("unique_anchor_value", False): | |
| return False | |
| if r == "anchor_is_highlighted" and not extra.get("anchor_is_highlighted", False): | |
| return False | |
| if r == "anchor_is_styled" and not extra.get("anchor_is_styled", False): | |
| return False | |
| if r == "avoid_ties_in_row" and not extra.get("avoid_ties_in_row", False): | |
| return False | |
| if r == "avoid_ties_in_col" and not extra.get("avoid_ties_in_col", False): | |
| return False | |
| if r == "unique_compare" and not extra.get("unique_compare", False): | |
| return False | |
| if r == "k_le_num_values" and not extra.get("k_le_num_values", False): | |
| return False | |
| return True | |
| def _qa_render_template( | |
| template: str, | |
| slots: Dict[str, Any], | |
| rules: Optional[Dict[str, str]] = None, | |
| ) -> str: | |
| text = template | |
| merged: Dict[str, Any] = {} | |
| if rules: | |
| merged.update(rules) | |
| merged.update(slots) | |
| for k, v in merged.items(): | |
| text = text.replace("{" + str(k) + "}", str(v)) | |
| # Use plain definition rather than the canonical form when no abbreviation precedes it | |
| if _DG_DEF_CANON in text: | |
| prefix = text.split(_DG_DEF_CANON, 1)[0] | |
| if not _DG_TOKEN_RE.search(prefix): | |
| text = text.replace(_DG_DEF_CANON, _DG_DEF_PLAIN) | |
| text = _QA_PLACEHOLDER_RE.sub("", text) | |
| text = " ".join(text.split()) | |
| return text | |
| def generate_qa( | |
| spec: TableSpec, | |
| rng: random.Random, | |
| *, | |
| include_cell_lookup: bool, | |
| cell_lookup_samples: int, | |
| include_position: bool, | |
| position_samples: int, | |
| include_col_extremes: bool, | |
| col_extremes_k: int, | |
| include_row_extremes: bool, | |
| row_extremes_k: int, | |
| include_col_argmax_item: bool, | |
| include_col_argmax_coord: bool, | |
| include_topk: bool, | |
| topk_k: int, | |
| topk_cols: int, | |
| include_kth: bool, | |
| kth_k: int, | |
| include_compare_rows: bool, | |
| include_compare_cols: bool, | |
| compare_samples: int, | |
| include_col_best: bool, | |
| include_group_col_best: bool, | |
| include_highlight_neighbor: bool, | |
| highlight_neighbor_samples: int, | |
| include_neighbors_idx: bool, | |
| include_neighbors_noidx: bool, | |
| neighbor_samples: int, | |
| include_color_values: bool, | |
| palette_id: str, | |
| palette_colors: List[str], | |
| palette_names: Optional[Dict[str, str]], | |
| include_same_color: bool, | |
| same_color_samples: int, | |
| include_same_color_noidx: bool, | |
| same_color_noidx_samples: int, | |
| include_text_color_values: bool, | |
| include_underline_values: bool, | |
| include_underline_per_col: bool, | |
| include_underline_yesno_idx: bool, | |
| include_underline_yesno_noidx: bool, | |
| underline_yesno_samples: int, | |
| include_bold_values: bool, | |
| include_bold_per_col: bool, | |
| include_bold_yesno_idx: bool, | |
| include_bold_yesno_noidx: bool, | |
| bold_yesno_samples: int, | |
| include_color_yesno_idx: bool, | |
| include_color_yesno_noidx: bool, | |
| color_yesno_samples: int, | |
| include_missing_list: bool, | |
| include_missing_check: bool, | |
| missing_samples: int, | |
| include_count_highlight: bool, | |
| include_count_underline: bool, | |
| include_count_bold: bool, | |
| include_filter_threshold: bool, | |
| include_filter_highlight_threshold: bool, | |
| filter_samples: int, | |
| include_agg_mean_group: bool, | |
| include_delta_positive_list: bool, | |
| include_argmax_overall: bool, | |
| include_multi_hop_style_agg: bool, | |
| include_multi_hop_exclude_agg: bool, | |
| multi_hop_samples: int, | |
| include_counterfactual: bool, | |
| include_delta_values: bool, | |
| include_delta_best_row: bool, | |
| delta_samples: int, | |
| qa_lib: Optional[Dict[str, Any]] = None, | |
| ) -> List[Dict]: | |
| out: List[Dict] = [] | |
| data_cells = [c for c in spec.cells if c.kind == "data"] | |
| all_data_cells = list(data_cells) | |
| by_row: Dict[int, List[PTCell]] = {} | |
| by_col: Dict[int, List[PTCell]] = {} | |
| for c in data_cells: | |
| by_row.setdefault(c.row, []).append(c) | |
| by_col.setdefault(c.col, []).append(c) | |
| def is_numeric_cell(c: PTCell) -> bool: | |
| return c.value is not None and c.text not in ("—", "N/A") | |
| data_rows_sorted = sorted({c.row for c in data_cells}) | |
| row_idx_map = {r: i + 1 for i, r in enumerate(data_rows_sorted)} | |
| row_item_map: Dict[int, str] = {} | |
| row_group_map: Dict[int, str] = {} | |
| for c in spec.cells: | |
| if c.kind == "item": | |
| row_item_map[c.row] = c.text | |
| if c.kind == "group": | |
| for rr in range(c.row, c.row + max(1, c.row_span)): | |
| row_group_map[rr] = c.text | |
| group_col_name = "Group" | |
| if spec.left_cols >= 2: | |
| header_cands = [c for c in spec.cells if c.kind == "header" and c.col == 0] | |
| if header_cands: | |
| header_cands = sorted(header_cands, key=lambda x: (x.row, x.col)) | |
| group_col_name = str(header_cands[0].text or "Group") | |
| def group_value_for_question(group_name: str) -> str: | |
| raw = str(group_name or "").strip() | |
| prefix = str(group_col_name or "").strip() | |
| if not raw: | |
| return raw | |
| if prefix: | |
| raw_low = raw.lower() | |
| prefix_low = prefix.lower() | |
| if raw_low == prefix_low: | |
| return raw | |
| pref_sp = prefix + " " | |
| if raw_low.startswith(pref_sp.lower()): | |
| tail = raw[len(pref_sp):].strip() | |
| if tail: | |
| return tail | |
| return raw | |
| missing_tokens = {"N/A", "—", "-", "–"} | |
| has_missing = any( | |
| c.kind == "data" and isinstance(c.text, str) and c.text.strip() in missing_tokens | |
| for c in spec.cells | |
| ) | |
| has_metric_arrow = any( | |
| ("↑" in str(ci.get("metric", ""))) or ("↓" in str(ci.get("metric", ""))) | |
| for ci in spec.data_cols | |
| ) | |
| has_highlight = any(c.extra.get("highlight") == "true" for c in spec.cells if c.kind == "data") | |
| has_underline = any(c.extra.get("underline") == "true" for c in spec.cells if c.kind == "data") | |
| has_bold = any(c.extra.get("bold") == "true" for c in spec.cells if c.kind == "data") | |
| has_text_color = any(c.extra.get("text_color") == "true" for c in spec.cells if c.kind == "data") | |
| has_group = bool(row_group_map) | |
| has_styled_marker = has_highlight or has_underline or has_bold or has_text_color | |
| facts = { | |
| "has_highlight": has_highlight, | |
| "has_underline": has_underline, | |
| "has_bold": has_bold, | |
| "has_text_color": has_text_color, | |
| "has_highlight_or_underline": has_styled_marker, | |
| "has_styled_marker": has_styled_marker, | |
| "has_delta_col": spec.delta_col is not None, | |
| "palette_list": bool(palette_colors), | |
| "has_group": has_group, | |
| "has_missing": has_missing, | |
| "has_metric_arrow": has_metric_arrow, | |
| } | |
| def _ordinal(n: int) -> str: | |
| n_abs = abs(int(n)) | |
| if 10 <= (n_abs % 100) <= 20: | |
| suffix = "th" | |
| else: | |
| suffix = {1: "st", 2: "nd", 3: "rd"}.get(n_abs % 10, "th") | |
| return f"{n}{suffix}" | |
| def _normalize_question_surface(task_id: str, text: str) -> str: | |
| t = str(text or "") | |
| if not t: | |
| return t | |
| t = t.replace("{{", "{").replace("}}", "}") | |
| t = re.sub(r"\b(\d+)-th\b", lambda m: _ordinal(int(m.group(1))), t) | |
| pair_obj = '{"item":"...","value":"..."}' | |
| t = t.replace('Return JSON {"item":...,"value":...}.', f'Return JSON {pair_obj}.') | |
| t = t.replace("Return {item,value}.", f"Return JSON {pair_obj}.") | |
| t = t.replace("Output {item,value}.", f"Return JSON {pair_obj}.") | |
| t = t.replace("as {item,value}.", f"as JSON {pair_obj}.") | |
| t = t.replace("JSON array of pairs", f'JSON array of {pair_obj} objects') | |
| t = t.replace("JSON array of {item,value}", f'JSON array of {pair_obj} objects') | |
| t = t.replace( | |
| "Return JSON with highlighted/color/hex.", | |
| 'Return JSON {"highlighted":true/false,"color":<color_name or null>,"hex":<hex or null>}.', | |
| ) | |
| t = t.replace( | |
| "Return JSON highlighted/color/hex.", | |
| 'Return JSON {"highlighted":true/false,"color":<color_name or null>,"hex":<hex or null>}.', | |
| ) | |
| t = t.replace( | |
| "Use ↑/↓ (↑ better, ↓ better if smaller).", | |
| "The arrow in the metric name indicates optimization direction: ↑ means higher is better, ↓ means lower is better.", | |
| ) | |
| t = t.replace( | |
| "Take the highlighted numbers highlighted (any color)", | |
| "Take all highlighted numbers (any color)", | |
| ) | |
| t = re.sub( | |
| r"row label\s+in\s+the\s+Item\s+column", | |
| "main row label in the left header", | |
| t, | |
| flags=re.IGNORECASE, | |
| ) | |
| t = re.sub( | |
| r"best-performing item\s*\(row label\)", | |
| "best-performing item (main row label in the left header)", | |
| t, | |
| flags=re.IGNORECASE, | |
| ) | |
| if task_id == "P_NEI_VAL" and "appears exactly once in the numeric part of the table" not in t: | |
| t += " The target value appears exactly once in the numeric part of the table." | |
| if task_id in {"P_COLOR_YN_VAL", "P_BOLD_YN_VAL", "P_UNDERLINE_YN_VAL"} and "appears exactly once in the numeric data grid" not in t: | |
| t += " The value appears exactly once in the numeric data grid." | |
| return " ".join(t.split()) | |
| def build_question(task_id: str, slots: Dict[str, Any], fallback: str) -> str: | |
| entry = _qa_task_entry(qa_lib, task_id) | |
| if not entry: | |
| return _normalize_question_surface(task_id, fallback) | |
| templates = entry.get("question_templates") or [] | |
| if not templates: | |
| return _normalize_question_surface(task_id, fallback) | |
| template = rng.choice(templates) | |
| rules = entry.get("rules") or {} | |
| q = _qa_render_template(template, slots, rules) | |
| return _normalize_question_surface(task_id, q or fallback) | |
| def _balanced_binary_sample( | |
| positives: List[PTCell], | |
| negatives: List[PTCell], | |
| k: int, | |
| *, | |
| strict: bool = False, | |
| ) -> List[PTCell]: | |
| """Sample binary-labeled items with balanced positive/negative coverage. | |
| When ``strict=True`` and both classes exist, prefer an exact 1:1 split (may | |
| return fewer than ``k`` items). If one side is absent, fall back to the | |
| available side. | |
| """ | |
| k = max(0, int(k)) | |
| if k <= 0: | |
| return [] | |
| total = len(positives) + len(negatives) | |
| if total <= 0: | |
| return [] | |
| n = min(k, total) | |
| if not positives: | |
| return rng.sample(negatives, k=min(n, len(negatives))) | |
| if not negatives: | |
| return rng.sample(positives, k=min(n, len(positives))) | |
| if strict: | |
| n = min(n, 2 * min(len(positives), len(negatives))) | |
| if n <= 0: | |
| return [] | |
| if n % 2 == 1: | |
| n -= 1 | |
| if n <= 0: | |
| return [] | |
| take_pos = n // 2 | |
| take_neg = n // 2 | |
| picked: List[PTCell] = [] | |
| picked.extend(rng.sample(positives, k=take_pos)) | |
| picked.extend(rng.sample(negatives, k=take_neg)) | |
| rng.shuffle(picked) | |
| return picked | |
| target_pos = n // 2 + (1 if (n % 2 == 1 and rng.random() < 0.5) else 0) | |
| target_neg = n - target_pos | |
| take_pos = min(len(positives), target_pos) | |
| take_neg = min(len(negatives), target_neg) | |
| remain = n - take_pos - take_neg | |
| if remain > 0: | |
| extra_pos = max(0, len(positives) - take_pos) | |
| add_pos = min(remain, extra_pos) | |
| take_pos += add_pos | |
| remain -= add_pos | |
| if remain > 0: | |
| extra_neg = max(0, len(negatives) - take_neg) | |
| add_neg = min(remain, extra_neg) | |
| take_neg += add_neg | |
| remain -= add_neg | |
| picked: List[PTCell] = [] | |
| if take_pos > 0: | |
| picked.extend(rng.sample(positives, k=take_pos)) | |
| if take_neg > 0: | |
| picked.extend(rng.sample(negatives, k=take_neg)) | |
| rng.shuffle(picked) | |
| return picked | |
| def data_col_idx(col: int) -> int: | |
| return col - spec.left_cols + 1 | |
| def data_row_idx(row: int) -> int: | |
| return row_idx_map.get(row, row - spec.data_row_start + 1) | |
| def col_name_by_index(col_idx: int) -> str: | |
| if 0 <= col_idx < len(spec.data_cols): | |
| colinfo = spec.data_cols[col_idx] | |
| name = str(colinfo.get("metric", f"Col-{col_idx+1}")) | |
| if spec.top_levels >= 2: | |
| block = str(colinfo.get("block", "")).strip() | |
| mid = str(colinfo.get("mid", "")).strip() | |
| if spec.top_levels == 2 and block: | |
| return f"{name} (block {block})" | |
| if spec.top_levels >= 3: | |
| if block and mid: | |
| return f"{name} (group {block}/{mid})" | |
| if block: | |
| return f"{name} (group {block})" | |
| return name | |
| return f"Col-{col_idx+1}" | |
| def _metric_text_by_index(col_idx: int) -> str: | |
| if 0 <= col_idx < len(spec.data_cols): | |
| return str(spec.data_cols[col_idx].get("metric", "")) | |
| return "" | |
| def _col_name_by_index_no_arrows(col_idx: int) -> str: | |
| """Question-facing column name with arrow glyphs removed (for arrow-aware tasks).""" | |
| name = col_name_by_index(col_idx) | |
| return re.sub(r"[↑↓▲▼△▽↗↘⇧⇩↟↡]", "", name) | |
| def _has_arrow_in_cols(*col_indices: int) -> bool: | |
| for ci in col_indices: | |
| metric_text = _metric_text_by_index(ci) | |
| if ("↑" in metric_text) or ("↓" in metric_text): | |
| return True | |
| return False | |
| def _arrow_rule_for_cols(*col_indices: int) -> str: | |
| for ci in col_indices: | |
| metric_text = _metric_text_by_index(ci) | |
| if ("↑" in metric_text) or ("↓" in metric_text): | |
| return "Treat ↑/↓ in the metric name as direction annotations only; compare raw numeric values (do not interpret them as better/worse)." | |
| return "" | |
| def sample_cols(k: int) -> List[int]: | |
| cols = list(range(len(spec.data_cols))) | |
| if k > 0 and len(cols) > k: | |
| return rng.sample(cols, k=k) | |
| return cols | |
| if include_position: | |
| numeric_cells = [c for c in data_cells if is_numeric_cell(c)] | |
| if position_samples > 0 and len(numeric_cells) > position_samples: | |
| picked = rng.sample(numeric_cells, k=position_samples) | |
| else: | |
| picked = list(numeric_cells) | |
| for c in sorted(picked, key=lambda x: (x.row, x.col)): | |
| row_idx = data_row_idx(c.row) | |
| col_idx = data_col_idx(c.col) | |
| fallback = ( | |
| f"What is the number at row {row_idx}, column {col_idx}? " | |
| "Row/column indices refer to the data grid only (exclude header rows and any section header rows; " | |
| "columns exclude left header columns). " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx} | |
| q = build_question("P_POS", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_POS", | |
| "question": q, | |
| "answer": c.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_cell_lookup: | |
| numeric_cells = [c for c in data_cells if is_numeric_cell(c)] | |
| k = max(0, int(cell_lookup_samples)) | |
| if numeric_cells and k > 0: | |
| for c in rng.sample(numeric_cells, k=min(k, len(numeric_cells))): | |
| row_name = row_item_map.get(c.row) | |
| col_idx = c.col - spec.left_cols | |
| col_name = col_name_by_index(col_idx) | |
| if not row_name: | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "cell_lookup"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"For item {row_name}, what is the value in column {col_name}? " | |
| "Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"ROW_NAME": row_name, "COL_NAME": col_name} | |
| q = build_question("cell_lookup", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "cell_lookup", | |
| "question": q, | |
| "answer": c.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_col_extremes: | |
| col_indices = sample_cols(col_extremes_k) | |
| for col_idx in col_indices: | |
| if _has_arrow_in_cols(col_idx): | |
| continue | |
| colinfo = spec.data_cols[col_idx] | |
| col = spec.left_cols + col_idx | |
| vals = [c for c in by_col.get(col, []) if is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| vmax = max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| vmin = min(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| max_val = vmax.value | |
| min_val = vmin.value | |
| unique_max = sum(1 for v in vals if v.value == max_val) == 1 | |
| unique_min = sum(1 for v in vals if v.value == min_val) == 1 | |
| if spec.top_levels == 3: | |
| fallback_max = ( | |
| f"What is the maximum value in column {colinfo['metric']} " | |
| f"(group {colinfo['block']} / {colinfo.get('mid','')})? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| fallback_min = ( | |
| f"What is the minimum value in column {colinfo['metric']} " | |
| f"(group {colinfo['block']} / {colinfo.get('mid','')})? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| elif spec.top_levels == 2: | |
| fallback_max = ( | |
| f"What is the maximum value in column {colinfo['metric']} (block {colinfo['block']})? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| fallback_min = ( | |
| f"What is the minimum value in column {colinfo['metric']} (block {colinfo['block']})? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| else: | |
| fallback_max = f"What is the maximum value in column {colinfo['metric']}? Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| fallback_min = f"What is the minimum value in column {colinfo['metric']}? Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| slots = {"COL_NAME": colinfo["metric"], "ARROW_RULE": _arrow_rule_for_cols(col_idx)} | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_COL_MAX"), facts, {"avoid_ties_in_col": unique_max}): | |
| qmax = build_question("P_COL_MAX", slots, fallback_max) | |
| out.append( | |
| { | |
| "task_id": "P_COL_MAX", | |
| "question": qmax, | |
| "answer": vmax.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_COL_MIN"), facts, {"avoid_ties_in_col": unique_min}): | |
| qmin = build_question("P_COL_MIN", slots, fallback_min) | |
| out.append( | |
| { | |
| "task_id": "P_COL_MIN", | |
| "question": qmin, | |
| "answer": vmin.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_col_argmax_item or include_col_argmax_coord: | |
| col_indices = sample_cols(col_extremes_k) | |
| for col_idx in col_indices: | |
| if _has_arrow_in_cols(col_idx): | |
| continue | |
| colinfo = spec.data_cols[col_idx] | |
| col = spec.left_cols + col_idx | |
| vals = [c for c in by_col.get(col, []) if is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| vmax = max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| max_val = vmax.value | |
| unique_max = sum(1 for v in vals if v.value == max_val) == 1 | |
| row_name = row_item_map.get(vmax.row) | |
| if not row_name: | |
| continue | |
| col_name = col_name_by_index(col_idx) | |
| if include_col_argmax_item and _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "col_argmax_item"), facts, {"avoid_ties_in_col": unique_max} | |
| ): | |
| fallback = ( | |
| f"In column {col_name}, which item has the maximum value? " | |
| "Return JSON {\"item\":...,\"value\":...}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": col_name, "ARROW_RULE": _arrow_rule_for_cols(col_idx)} | |
| q = build_question("col_argmax_item", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "col_argmax_item", | |
| "question": q, | |
| "answer": {"item": row_name, "value": vmax.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": vmax.row, "col": vmax.col}, | |
| } | |
| ) | |
| if include_col_argmax_coord and _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "col_argmax_coord"), facts, {"avoid_ties_in_col": unique_max} | |
| ): | |
| row_idx = data_row_idx(vmax.row) | |
| col_idx2 = data_col_idx(vmax.col) | |
| fallback = ( | |
| f"Find the location (row,col) and value of the maximum cell in column {col_name}. " | |
| "Output JSON {\"row\":<int>,\"col\":<int>,\"value\":<string>}. " | |
| "Row/col refer to the data grid only (exclude headers/section headers; left header columns excluded). " | |
| "Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": col_name, "ARROW_RULE": _arrow_rule_for_cols(col_idx)} | |
| q = build_question("col_argmax_coord", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "col_argmax_coord", | |
| "question": q, | |
| "answer": {"row": row_idx, "col": col_idx2, "value": vmax.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["row", "col", "value"]}, | |
| "meta": {"row": vmax.row, "col": vmax.col}, | |
| } | |
| ) | |
| # 2.6) Top-K / K-th | |
| if include_topk or include_kth: | |
| col_indices = sample_cols(topk_cols) | |
| for col_idx in col_indices: | |
| if _has_arrow_in_cols(col_idx): | |
| continue | |
| col = spec.left_cols + col_idx | |
| col_name = col_name_by_index(col_idx) | |
| vals = [c for c in by_col.get(col, []) if is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| uniq = len({c.value for c in vals}) == len(vals) | |
| if include_topk and _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "topk_by_metric"), facts, {"avoid_ties_in_col": uniq, "k_le_num_values": len(vals) >= max(1, int(topk_k))} | |
| ): | |
| k = max(1, int(topk_k)) | |
| if len(vals) >= k: | |
| vals_sorted = sorted(vals, key=lambda x: x.value, reverse=True) # type: ignore[arg-type] | |
| top_vals = vals_sorted[:k] | |
| pairs = [] | |
| for c in top_vals: | |
| item = row_item_map.get(c.row) | |
| if not item: | |
| continue | |
| pairs.append({"item": item, "value": c.text}) | |
| if pairs: | |
| fallback = ( | |
| f"List the top-{k} items by column {col_name}. " | |
| "Return a JSON array of {item,value}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": col_name, "K": k, "ARROW_RULE": _arrow_rule_for_cols(col_idx)} | |
| q = build_question("topk_by_metric", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "topk_by_metric", | |
| "question": q, | |
| "answer": pairs, | |
| "answer_type": "list", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_kth and _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "kth_rank_by_metric"), facts, {"avoid_ties_in_col": uniq, "k_le_num_values": len(vals) >= max(1, int(kth_k))} | |
| ): | |
| k = max(1, int(kth_k)) | |
| if len(vals) >= k: | |
| vals_sorted = sorted(vals, key=lambda x: x.value, reverse=True) # type: ignore[arg-type] | |
| c = vals_sorted[k - 1] | |
| item = row_item_map.get(c.row) | |
| if item: | |
| fallback = ( | |
| f"Who ranks {k}-th in column {col_name}? " | |
| "Return JSON {\"item\":...,\"value\":...}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": col_name, "K": k, "ARROW_RULE": _arrow_rule_for_cols(col_idx)} | |
| q = build_question("kth_rank_by_metric", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "kth_rank_by_metric", | |
| "question": q, | |
| "answer": {"item": item, "value": c.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_row_extremes: | |
| rows = list(by_row.keys()) | |
| if row_extremes_k > 0 and len(rows) > row_extremes_k: | |
| rows = rng.sample(rows, k=row_extremes_k) | |
| for row in rows: | |
| vals = by_row.get(row, []) | |
| vals = [c for c in vals if is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| vmax = max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| vmin = min(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| max_val = vmax.value | |
| min_val = vmin.value | |
| unique_max = sum(1 for v in vals if v.value == max_val) == 1 | |
| unique_min = sum(1 for v in vals if v.value == min_val) == 1 | |
| item_cell = next((c for c in spec.cells if c.kind == "item" and c.row == row), None) | |
| item_name = item_cell.text if item_cell else f"row {row}" | |
| fallback_max = ( | |
| f"For item {item_name}, what is the maximum value across all metrics? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| fallback_min = ( | |
| f"For item {item_name}, what is the minimum value across all metrics? Exclude N/A and —. " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"ROW_NAME": item_name} | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_ROW_MAX"), facts, {"avoid_ties_in_row": unique_max}): | |
| qmax = build_question("P_ROW_MAX", slots, fallback_max) | |
| out.append( | |
| { | |
| "task_id": "P_ROW_MAX", | |
| "question": qmax, | |
| "answer": vmax.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": row}, | |
| } | |
| ) | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_ROW_MIN"), facts, {"avoid_ties_in_row": unique_min}): | |
| qmin = build_question("P_ROW_MIN", slots, fallback_min) | |
| out.append( | |
| { | |
| "task_id": "P_ROW_MIN", | |
| "question": qmin, | |
| "answer": vmin.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": row}, | |
| } | |
| ) | |
| if include_compare_rows or include_compare_cols: | |
| numeric_cells = [c for c in data_cells if is_numeric_cell(c)] | |
| if numeric_cells: | |
| rows = sorted({c.row for c in numeric_cells}) | |
| cols = list(range(len(spec.data_cols))) | |
| k = max(0, int(compare_samples)) | |
| if include_compare_rows and k > 0: | |
| for _ in range(k): | |
| if len(rows) < 2 or not cols: | |
| break | |
| r1, r2 = rng.sample(rows, 2) | |
| col_idx = rng.choice(cols) | |
| col = spec.left_cols + col_idx | |
| c1 = next((c for c in by_row.get(r1, []) if c.col == col and is_numeric_cell(c)), None) | |
| c2 = next((c for c in by_row.get(r2, []) if c.col == col and is_numeric_cell(c)), None) | |
| if not c1 or not c2: | |
| continue | |
| if c1.value == c2.value: | |
| continue | |
| row_a = row_item_map.get(r1) | |
| row_b = row_item_map.get(r2) | |
| if not row_a or not row_b: | |
| continue | |
| winner = c1 if (c1.value or 0) > (c2.value or 0) else c2 | |
| winner_name = row_item_map.get(winner.row) | |
| if not winner_name: | |
| continue | |
| col_name = col_name_by_index(col_idx) | |
| if _has_arrow_in_cols(col_idx): | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "compare_two_systems_one_metric"), facts, {"unique_compare": True}): | |
| continue | |
| fallback = ( | |
| f"Compare {row_a} vs {row_b} on {col_name}. Which one is larger? " | |
| "Return JSON {\"item\":...,\"value\":...}. Exclude N/A and —." | |
| ) | |
| slots = { | |
| "ROW_NAME_A": row_a, | |
| "ROW_NAME_B": row_b, | |
| "COL_NAME": col_name, | |
| "ARROW_RULE": _arrow_rule_for_cols(col_idx), | |
| } | |
| q = build_question("compare_two_systems_one_metric", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "compare_two_systems_one_metric", | |
| "question": q, | |
| "answer": {"item": winner_name, "value": winner.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": winner.row, "col": winner.col}, | |
| } | |
| ) | |
| if include_compare_cols and k > 0: | |
| for _ in range(k): | |
| if len(rows) < 1 or len(cols) < 2: | |
| break | |
| r = rng.choice(rows) | |
| col_idx_a, col_idx_b = rng.sample(cols, 2) | |
| col_a = spec.left_cols + col_idx_a | |
| col_b = spec.left_cols + col_idx_b | |
| c1 = next((c for c in by_row.get(r, []) if c.col == col_a and is_numeric_cell(c)), None) | |
| c2 = next((c for c in by_row.get(r, []) if c.col == col_b and is_numeric_cell(c)), None) | |
| if not c1 or not c2: | |
| continue | |
| if c1.value == c2.value: | |
| continue | |
| row_name = row_item_map.get(r) | |
| if not row_name: | |
| continue | |
| col_name_a = col_name_by_index(col_idx_a) | |
| col_name_b = col_name_by_index(col_idx_b) | |
| if _has_arrow_in_cols(col_idx_a, col_idx_b): | |
| continue | |
| winner = c1 if (c1.value or 0) > (c2.value or 0) else c2 | |
| winner_col = col_name_a if winner is c1 else col_name_b | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "compare_two_metrics_one_system"), facts, {"unique_compare": True}): | |
| continue | |
| fallback = ( | |
| f"For {row_name}, compare {col_name_a} and {col_name_b}. " | |
| "Which metric value is larger? Return JSON {\"item\":<metric_name>,\"value\":<string>}. " | |
| "Exclude N/A and —." | |
| ) | |
| slots = { | |
| "ROW_NAME": row_name, | |
| "COL_NAME_A": col_name_a, | |
| "COL_NAME_B": col_name_b, | |
| "ARROW_RULE": _arrow_rule_for_cols(col_idx_a, col_idx_b), | |
| } | |
| q = build_question("compare_two_metrics_one_system", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "compare_two_metrics_one_system", | |
| "question": q, | |
| "answer": {"item": winner_col, "value": winner.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": r, "col": winner.col}, | |
| } | |
| ) | |
| if include_col_best: | |
| col_indices = sample_cols(col_extremes_k) | |
| for col_idx in col_indices: | |
| col = spec.left_cols + col_idx | |
| vals = [c for c in by_col.get(col, []) if is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| metric = col_name_by_index(col_idx) | |
| metric_q = _col_name_by_index_no_arrows(col_idx) | |
| if "↓" in metric: | |
| best = min(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| direction = "↓" | |
| else: | |
| best = max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| direction = "↑" | |
| item = row_item_map.get(best.row) | |
| if not item: | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "col_best_system_by_arrow"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"For column {metric_q}, which item is the best? " | |
| "Return JSON {\"item\":...,\"value\":...}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": metric_q, "DIR": direction} | |
| q = build_question("col_best_system_by_arrow", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "col_best_system_by_arrow", | |
| "question": q, | |
| "answer": {"item": item, "value": best.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": best.row, "col": best.col}, | |
| } | |
| ) | |
| if include_group_col_best and row_group_map: | |
| groups = sorted(set(row_group_map.values())) | |
| col_indices = sample_cols(col_extremes_k) | |
| for _ in range(max(1, min(len(groups), len(col_indices)))): | |
| group_name = rng.choice(groups) | |
| col_idx = rng.choice(col_indices) if col_indices else 0 | |
| col = spec.left_cols + col_idx | |
| metric = col_name_by_index(col_idx) | |
| metric_q = _col_name_by_index_no_arrows(col_idx) | |
| group_rows = [r for r, g in row_group_map.items() if g == group_name] | |
| vals = [c for c in data_cells if c.row in group_rows and c.col == col and is_numeric_cell(c)] | |
| if not vals: | |
| continue | |
| if "↓" in metric: | |
| best = min(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| else: | |
| best = max(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| item = row_item_map.get(best.row) | |
| if not item: | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "group_col_best"), facts, {}): | |
| continue | |
| group_value = group_value_for_question(group_name) | |
| fallback = ( | |
| f'Inside "{group_name}", which item is best on {metric_q}? ' | |
| "Return JSON {\"item\":...,\"value\":...}. Exclude N/A and —." | |
| ) | |
| slots = { | |
| "GROUP_NAME": group_name, | |
| "GROUP_COL_NAME": group_col_name, | |
| "GROUP_VALUE": group_value, | |
| "COL_NAME": metric_q, | |
| } | |
| q = build_question("group_col_best", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "group_col_best", | |
| "question": q, | |
| "answer": {"item": item, "value": best.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["item", "value"]}, | |
| "meta": {"row": best.row, "col": best.col, "group": group_name, "group_col_name": group_col_name, "group_value": group_value}, | |
| } | |
| ) | |
| if include_neighbors_idx or include_neighbors_noidx: | |
| cell_map: Dict[Tuple[int, int], PTCell] = {(c.row, c.col): c for c in spec.cells} | |
| def neighbor_value(row: int, col: int) -> Optional[str]: | |
| c = cell_map.get((row, col)) | |
| if not c or c.kind != "data": | |
| return None | |
| if c.text in ("N/A", "—"): | |
| return c.text | |
| if c.value is None: | |
| return None | |
| return c.text | |
| def has_full_neighbors(c: PTCell) -> bool: | |
| return all( | |
| neighbor_value(c.row + dr, c.col + dc) is not None | |
| for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)] | |
| ) | |
| highlighted = [c for c in data_cells if c.extra.get("highlight") == "true" and c.value is not None and has_full_neighbors(c)] | |
| non_highlighted = [c for c in data_cells if c.extra.get("highlight") != "true" and c.value is not None and has_full_neighbors(c)] | |
| value_count: Dict[str, int] = {} | |
| for c in data_cells: | |
| value_count[c.text] = value_count.get(c.text, 0) + 1 | |
| def add_neighbor_q_idx(c: PTCell) -> None: | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| col_idx = c.col - spec.left_cols + 1 | |
| fallback = ( | |
| f"At (r={row_idx},c={col_idx}) in the numeric part of the table, return the target and its four neighbors " | |
| "(up, down, left, right) as JSON " | |
| "{\"target\":\"12.34\",\"up\":\"..\",\"down\":\"..\",\"left\":\"..\",\"right\":\"..\"}. " | |
| "The numeric part of the table includes numeric/data cells only (no headers). " | |
| "If a neighbor cell contains N/A or —, return that token string." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx} | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_NEI_IDX"), facts, {}): | |
| return | |
| q = build_question("P_NEI_IDX", slots, fallback) | |
| ans = { | |
| "target": c.text, | |
| "up": neighbor_value(c.row - 1, c.col), | |
| "down": neighbor_value(c.row + 1, c.col), | |
| "left": neighbor_value(c.row, c.col - 1), | |
| "right": neighbor_value(c.row, c.col + 1), | |
| } | |
| out.append( | |
| { | |
| "task_id": "P_NEI_IDX", | |
| "question": q, | |
| "answer": ans, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["target", "up", "down", "left", "right"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| def add_neighbor_q_noidx(c: PTCell) -> None: | |
| fallback = ( | |
| f"At the cell with value {c.text}, return the target and its four neighbors " | |
| "(up, down, left, right) as JSON " | |
| "{\"target\":\"12.34\",\"up\":\"..\",\"down\":\"..\",\"left\":\"..\",\"right\":\"..\"}. " | |
| "The numeric part of the table includes numeric/data cells only (no headers). " | |
| "If a neighbor cell contains N/A or —, return that token string." | |
| ) | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_NEI_VAL"), | |
| facts, | |
| {"unique_anchor_value": True}, | |
| ): | |
| return | |
| slots = {"ANCHOR_VAL": c.text} | |
| q = build_question("P_NEI_VAL", slots, fallback) | |
| ans = { | |
| "target": c.text, | |
| "up": neighbor_value(c.row - 1, c.col), | |
| "down": neighbor_value(c.row + 1, c.col), | |
| "left": neighbor_value(c.row, c.col - 1), | |
| "right": neighbor_value(c.row, c.col + 1), | |
| } | |
| out.append( | |
| { | |
| "task_id": "P_NEI_VAL", | |
| "question": q, | |
| "answer": ans, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["target", "up", "down", "left", "right"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| k = max(0, int(neighbor_samples)) | |
| if include_neighbors_idx and k > 0: | |
| pool = highlighted + non_highlighted | |
| if pool: | |
| for c in rng.sample(pool, k=min(k, len(pool))): | |
| add_neighbor_q_idx(c) | |
| if include_neighbors_noidx and k > 0: | |
| pool_noidx = [c for c in highlighted + non_highlighted if value_count.get(c.text, 0) == 1] | |
| if pool_noidx: | |
| for c in rng.sample(pool_noidx, k=min(k, len(pool_noidx))): | |
| add_neighbor_q_noidx(c) | |
| if include_highlight_neighbor: | |
| cell_map: Dict[Tuple[int, int], PTCell] = {(c.row, c.col): c for c in spec.cells} | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| text_color_hexes = sorted( | |
| { | |
| str(c.extra.get("text_color_hex") or "").upper() | |
| for c in all_data_cells | |
| if c.extra.get("text_color") == "true" and str(c.extra.get("text_color_hex") or "").strip() | |
| } | |
| ) | |
| text_name_map = _build_palette_color_names(text_color_hexes) if text_color_hexes else {} | |
| styled_cells = [ | |
| c | |
| for c in all_data_cells | |
| if c.extra.get("highlight") == "true" | |
| or c.extra.get("underline") == "true" | |
| or c.extra.get("bold") == "true" | |
| or c.extra.get("text_color") == "true" | |
| ] | |
| dirs = [("left", (0, -1)), ("right", (0, 1)), ("up", (-1, 0)), ("down", (1, 0))] | |
| k = max(0, int(highlight_neighbor_samples)) | |
| if k > 0 and styled_cells: | |
| for c in rng.sample(styled_cells, k=min(k, len(styled_cells))): | |
| rng.shuffle(dirs) | |
| chosen = None | |
| for dname, (dr, dc) in dirs: | |
| nb = cell_map.get((c.row + dr, c.col + dc)) | |
| if not nb or nb.kind != "data": | |
| continue | |
| if not is_numeric_cell(nb): | |
| continue | |
| chosen = (dname, nb) | |
| break | |
| if not chosen: | |
| continue | |
| dname, nb = chosen | |
| style_candidates: List[Tuple[str, List[PTCell]]] = [] | |
| if c.extra.get("underline") == "true": | |
| matched = [x for x in all_data_cells if x.extra.get("underline") == "true"] | |
| style_candidates.append(("underlined", matched)) | |
| if c.extra.get("bold") == "true": | |
| matched = [x for x in all_data_cells if x.extra.get("bold") == "true"] | |
| style_candidates.append(("boldfaced", matched)) | |
| if c.extra.get("highlight") == "true": | |
| color_hex = (c.extra.get("highlight_color") or "").upper() | |
| matched = [ | |
| x | |
| for x in all_data_cells | |
| if x.extra.get("highlight") == "true" | |
| and (x.extra.get("highlight_color") or "").upper() == color_hex | |
| ] | |
| color_name = name_map.get(color_hex, "color") | |
| if color_hex: | |
| style_candidates.append((f"highlighted in {color_name} (hex {color_hex})", matched)) | |
| else: | |
| style_candidates.append(("highlighted", matched)) | |
| if c.extra.get("text_color") == "true": | |
| t_hex = (c.extra.get("text_color_hex") or "").upper() | |
| matched = [ | |
| x | |
| for x in all_data_cells | |
| if x.extra.get("text_color") == "true" | |
| and (x.extra.get("text_color_hex") or "").upper() == t_hex | |
| ] | |
| t_name = str(c.extra.get("text_color_name") or text_name_map.get(t_hex, "color")) | |
| if t_hex: | |
| style_candidates.append((f"text-colored in {t_name} (hex {t_hex})", matched)) | |
| else: | |
| style_candidates.append(("text-colored", matched)) | |
| style_desc_candidates: List[Tuple[str, str]] = [] | |
| for base_desc, matched in style_candidates: | |
| if not matched: | |
| continue | |
| if len(matched) == 1 and matched[0] is c: | |
| style_desc_candidates.append((base_desc, "")) | |
| continue | |
| same_val = [x for x in matched if x.text == c.text] | |
| if len(same_val) == 1: | |
| style_desc_candidates.append((base_desc, f" with value {c.text}")) | |
| if not style_desc_candidates: | |
| continue | |
| style_desc, anchor_clause = rng.choice(style_desc_candidates) | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "highlight_neighbor"), | |
| facts, | |
| {"anchor_is_styled": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"Locate the {style_desc} number and return the number immediately to its {dname}. " | |
| "Neighbor answer is guaranteed to be a numeric value (not N/A/—). " | |
| "Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"DIR": dname, "STYLE_DESC": style_desc, "ANCHOR_CLAUSE": anchor_clause} | |
| q = build_question("highlight_neighbor", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "highlight_neighbor", | |
| "question": q, | |
| "answer": nb.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_color_values: | |
| color_map: Dict[str, List[str]] = {} | |
| for c in data_cells: | |
| if c.extra.get("highlight") == "true": | |
| color = (c.extra.get("highlight_color") or "").upper() | |
| if not color: | |
| continue | |
| color_map.setdefault(color, []).append(c.text) | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| for color_hex, vals in color_map.items(): | |
| color_name = name_map.get(color_hex, "color") | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_COLOR"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"List numbers highlighted in {color_name} (hex {color_hex}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"COLOR_NAME": color_name, "COLOR_HEX": color_hex} | |
| q = build_question("P_COLOR", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_COLOR", | |
| "question": q, | |
| "answer": vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": { | |
| "color": color_hex, | |
| "color_name": color_name, | |
| "palette_id": palette_id, | |
| }, | |
| } | |
| ) | |
| if include_same_color: | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| highlighted = [c for c in data_cells if c.extra.get("highlight") == "true" and c.value is not None] | |
| k = max(0, int(same_color_samples)) | |
| if k > 0 and highlighted: | |
| for c in rng.sample(highlighted, k=min(k, len(highlighted))): | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| col_idx = c.col - spec.left_cols + 1 | |
| color_hex = (c.extra.get("highlight_color") or "").upper() | |
| color_name = name_map.get(color_hex, "color") | |
| same_vals = [ | |
| x.text | |
| for x in data_cells | |
| if x.extra.get("highlight") == "true" | |
| and (x.extra.get("highlight_color") or "").upper() == color_hex | |
| ] | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_SAME_COLOR"), | |
| facts, | |
| {"anchor_is_highlighted": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"For the number at row {row_idx}, column {col_idx} (value {c.text}), " | |
| f"list all numbers highlighted with the same color ({color_name}, hex {color_hex}). " | |
| "Row/column indices refer to the data grid only (exclude header rows and any section header rows; " | |
| "columns exclude left header columns). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx, "COLOR_NAME": color_name, "COLOR_HEX": color_hex} | |
| q = build_question("P_SAME_COLOR", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_SAME_COLOR", | |
| "question": q, | |
| "answer": same_vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": { | |
| "row": c.row, | |
| "col": c.col, | |
| "color": color_hex, | |
| "color_name": color_name, | |
| }, | |
| } | |
| ) | |
| if include_text_color_values: | |
| text_color_map: Dict[str, List[str]] = {} | |
| for c in data_cells: | |
| if c.extra.get("text_color") == "true": | |
| color_hex = (c.extra.get("text_color_hex") or "").upper() | |
| if not color_hex: | |
| continue | |
| text_color_map.setdefault(color_hex, []).append(c.text) | |
| if text_color_map: | |
| text_color_hexes = sorted(text_color_map.keys()) | |
| text_name_map = _build_palette_color_names(text_color_hexes) | |
| for color_hex, vals in text_color_map.items(): | |
| if not vals: | |
| continue | |
| color_name = text_name_map.get(color_hex, "color") | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_TEXT_COLOR"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"List numbers whose text is colored in {color_name} (hex {color_hex}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"COLOR_NAME": color_name, "COLOR_HEX": color_hex} | |
| q = build_question("P_TEXT_COLOR", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_TEXT_COLOR", | |
| "question": q, | |
| "answer": vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"color": color_hex, "color_name": color_name, "marker_type": "text_color"}, | |
| } | |
| ) | |
| if include_same_color_noidx: | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| highlighted = [c for c in data_cells if c.extra.get("highlight") == "true" and c.value is not None] | |
| value_count = {} | |
| for c in highlighted: | |
| value_count[c.text] = value_count.get(c.text, 0) + 1 | |
| pool = [c for c in highlighted if value_count.get(c.text, 0) == 1] | |
| k = max(0, int(same_color_noidx_samples)) | |
| if k > 0 and pool: | |
| for c in rng.sample(pool, k=min(k, len(pool))): | |
| color_hex = (c.extra.get("highlight_color") or "").upper() | |
| color_name = name_map.get(color_hex, "color") | |
| same_vals = [ | |
| x.text | |
| for x in data_cells | |
| if x.extra.get("highlight") == "true" | |
| and (x.extra.get("highlight_color") or "").upper() == color_hex | |
| ] | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_SAME_COLOR_VAL"), | |
| facts, | |
| {"unique_anchor_value": True, "anchor_is_highlighted": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"For the number with value {c.text}, list all numbers highlighted with the same color " | |
| f"({color_name}, hex {color_hex}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"ANCHOR_VAL": c.text, "COLOR_NAME": color_name, "COLOR_HEX": color_hex} | |
| q = build_question("P_SAME_COLOR_VAL", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_SAME_COLOR_VAL", | |
| "question": q, | |
| "answer": same_vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"color": color_hex, "color_name": color_name}, | |
| } | |
| ) | |
| underlined_cells = [c for c in data_cells if c.extra.get("underline") == "true"] | |
| if include_underline_values and underlined_cells: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_UNDERLINE"), facts, {}): | |
| underlined = [c.text for c in underlined_cells] | |
| fallback = ( | |
| "List all underlined numbers. Output only a JSON array of strings. " | |
| "Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| q = build_question("P_UNDERLINE", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_UNDERLINE", | |
| "question": q, | |
| "answer": underlined, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {}, | |
| } | |
| ) | |
| bold_cells = [c for c in data_cells if c.extra.get("bold") == "true"] | |
| if include_bold_values and bold_cells: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_BOLD"), facts, {}): | |
| bold_vals = [c.text for c in bold_cells] | |
| fallback = ( | |
| "List all bold numbers. Output only a JSON array of strings. " | |
| "Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| q = build_question("P_BOLD", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_BOLD", | |
| "question": q, | |
| "answer": bold_vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_underline_per_col and underlined_cells: | |
| by_col_under: Dict[int, List[str]] = {} | |
| seen_underline_col_q: set[str] = set() | |
| for c in underlined_cells: | |
| by_col_under.setdefault(c.col, []).append(c.text) | |
| for col_idx, colinfo in enumerate(spec.data_cols): | |
| col = spec.left_cols + col_idx | |
| vals = by_col_under.get(col, []) | |
| if not vals: | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_UNDERLINE_COL"), facts, {}): | |
| continue | |
| if spec.top_levels == 3: | |
| fallback = ( | |
| f"List all underlined numbers in column {colinfo['metric']} " | |
| f"(group {colinfo['block']} / {colinfo.get('mid','')}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| elif spec.top_levels == 2: | |
| fallback = ( | |
| f"List all underlined numbers in column {colinfo['metric']} (block {colinfo['block']}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| else: | |
| fallback = ( | |
| f"List all underlined numbers in column {colinfo['metric']}. " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"COL_NAME": col_name_by_index(col_idx)} | |
| q = build_question("P_UNDERLINE_COL", slots, fallback) | |
| if q in seen_underline_col_q: | |
| continue | |
| seen_underline_col_q.add(q) | |
| out.append( | |
| { | |
| "task_id": "P_UNDERLINE_COL", | |
| "question": q, | |
| "answer": vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_bold_per_col and bold_cells: | |
| by_col_bold: Dict[int, List[str]] = {} | |
| seen_bold_col_q: set[str] = set() | |
| for c in bold_cells: | |
| by_col_bold.setdefault(c.col, []).append(c.text) | |
| for col_idx, colinfo in enumerate(spec.data_cols): | |
| col = spec.left_cols + col_idx | |
| vals = by_col_bold.get(col, []) | |
| if not vals: | |
| continue | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_BOLD_COL"), facts, {}): | |
| continue | |
| if spec.top_levels == 3: | |
| fallback = ( | |
| f"List all bold numbers in column {colinfo['metric']} " | |
| f"(group {colinfo['block']} / {colinfo.get('mid','')}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| elif spec.top_levels == 2: | |
| fallback = ( | |
| f"List all bold numbers in column {colinfo['metric']} (block {colinfo['block']}). " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| else: | |
| fallback = ( | |
| f"List all bold numbers in column {colinfo['metric']}. " | |
| "Output only a JSON array of strings. Example: [\"12.34\",\"56.78\"]." | |
| ) | |
| slots = {"COL_NAME": col_name_by_index(col_idx)} | |
| q = build_question("P_BOLD_COL", slots, fallback) | |
| if q in seen_bold_col_q: | |
| continue | |
| seen_bold_col_q.add(q) | |
| out.append( | |
| { | |
| "task_id": "P_BOLD_COL", | |
| "question": q, | |
| "answer": vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_count_highlight and has_highlight: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "count_highlighted_cells"), facts, {}): | |
| count_hl = sum(1 for c in all_data_cells if c.extra.get("highlight") == "true") | |
| fallback = 'How many highlighted cells are in the table? Output only the count as a string. Example: "7".' | |
| q = build_question("count_highlighted_cells", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "count_highlighted_cells", | |
| "question": q, | |
| "answer": str(count_hl), | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_count_underline and has_underline: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "count_underlined_cells"), facts, {}): | |
| count_ul = sum(1 for c in all_data_cells if c.extra.get("underline") == "true") | |
| fallback = 'How many underlined numbers are in the table? Output only the count as a string. Example: "5".' | |
| q = build_question("count_underlined_cells", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "count_underlined_cells", | |
| "question": q, | |
| "answer": str(count_ul), | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_count_bold and has_bold: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "count_bold_cells"), facts, {}): | |
| count_b = sum(1 for c in all_data_cells if c.extra.get("bold") == "true") | |
| fallback = 'How many bold numbers are in the table? Output only the count as a string. Example: "4".' | |
| q = build_question("count_bold_cells", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "count_bold_cells", | |
| "question": q, | |
| "answer": str(count_b), | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_missing_list and has_missing: | |
| by_col_missing: Dict[int, List[str]] = {} | |
| for c in data_cells: | |
| if isinstance(c.text, str) and c.text.strip() in missing_tokens: | |
| name = row_item_map.get(c.row) | |
| if not name: | |
| continue | |
| by_col_missing.setdefault(c.col, []).append(name) | |
| if by_col_missing and _qa_requirements_ok(_qa_task_entry(qa_lib, "missing_list_in_column"), facts, {}): | |
| cols = list(by_col_missing.keys()) | |
| if missing_samples > 0 and len(cols) > missing_samples: | |
| cols = rng.sample(cols, k=missing_samples) | |
| for col in cols: | |
| col_idx = col - spec.left_cols | |
| col_name = col_name_by_index(col_idx) | |
| rows = by_col_missing.get(col, []) | |
| if not rows: | |
| continue | |
| fallback = ( | |
| f"In {col_name}, which rows have missing values (N/A or —)? " | |
| "Return a JSON array of row names. Example: [\"System-A\",\"System-B\"]." | |
| ) | |
| slots = {"COL_NAME": col_name} | |
| q = build_question("missing_list_in_column", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "missing_list_in_column", | |
| "question": q, | |
| "answer": rows, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_missing_check and has_missing: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "missing_check_cell"), facts, {}): | |
| pool = [c for c in data_cells if c.kind == "data"] | |
| k = max(0, int(missing_samples)) | |
| if pool and k > 0: | |
| pool_missing = [ | |
| c for c in pool | |
| if isinstance(c.text, str) and c.text.strip() in missing_tokens | |
| ] | |
| pool_not_missing = [ | |
| c for c in pool | |
| if not (isinstance(c.text, str) and c.text.strip() in missing_tokens) | |
| ] | |
| for c in _balanced_binary_sample(pool_missing, pool_not_missing, k, strict=True): | |
| row_name = row_item_map.get(c.row) | |
| col_name = col_name_by_index(c.col - spec.left_cols) | |
| if not row_name: | |
| continue | |
| is_missing = isinstance(c.text, str) and c.text.strip() in missing_tokens | |
| fallback = ( | |
| f"Is the cell ({row_name}, {col_name}) missing (N/A or —)? " | |
| "Answer JSON {\"missing\":true/false}." | |
| ) | |
| slots = {"ROW_NAME": row_name, "COL_NAME": col_name} | |
| q = build_question("missing_check_cell", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "missing_check_cell", | |
| "question": q, | |
| "answer": {"missing": bool(is_missing)}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["missing"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_filter_threshold: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "filter_values_by_threshold"), facts, {}): | |
| cols = sample_cols(filter_samples if filter_samples > 0 else 1) | |
| for col_idx in cols: | |
| col = spec.left_cols + col_idx | |
| col_name = col_name_by_index(col_idx) | |
| vals = [c for c in by_col.get(col, []) if is_numeric_cell(c)] | |
| if len(vals) < 2: | |
| continue | |
| vals_sorted = sorted(vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| pivot = vals_sorted[len(vals_sorted) // 2] | |
| op = rng.choice([">", ">=", "<", "<="]) | |
| thr = float(pivot.value or 0.0) | |
| if op == ">": | |
| matched = [c for c in vals if (c.value or 0) > thr] | |
| elif op == ">=": | |
| matched = [c for c in vals if (c.value or 0) >= thr] | |
| elif op == "<": | |
| matched = [c for c in vals if (c.value or 0) < thr] | |
| else: | |
| matched = [c for c in vals if (c.value or 0) <= thr] | |
| if not matched: | |
| continue | |
| pairs = [] | |
| for c in matched: | |
| item = row_item_map.get(c.row) | |
| if not item: | |
| continue | |
| pairs.append({"item": item, "value": c.text}) | |
| if not pairs: | |
| continue | |
| fallback = ( | |
| f"In column {col_name}, list all items with value {op} {thr:.2f}. " | |
| "Return JSON array of {item,value}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": col_name, "OP": op, "THRESH": f"{thr:.2f}"} | |
| q = build_question("filter_values_by_threshold", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "filter_values_by_threshold", | |
| "question": q, | |
| "answer": pairs, | |
| "answer_type": "list", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": col}, | |
| } | |
| ) | |
| if include_filter_highlight_threshold and has_highlight: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "filter_highlighted_values_by_threshold"), facts, {}): | |
| hl_vals = [c for c in all_data_cells if c.extra.get("highlight") == "true" and is_numeric_cell(c)] | |
| if len(hl_vals) >= 2: | |
| vals_sorted = sorted(hl_vals, key=lambda x: x.value) # type: ignore[arg-type] | |
| pivot = vals_sorted[len(vals_sorted) // 2] | |
| op = rng.choice([">", ">=", "<", "<="]) | |
| thr = float(pivot.value or 0.0) | |
| if op == ">": | |
| matched = [c.text for c in hl_vals if (c.value or 0) > thr] | |
| elif op == ">=": | |
| matched = [c.text for c in hl_vals if (c.value or 0) >= thr] | |
| elif op == "<": | |
| matched = [c.text for c in hl_vals if (c.value or 0) < thr] | |
| else: | |
| matched = [c.text for c in hl_vals if (c.value or 0) <= thr] | |
| if matched: | |
| fallback = ( | |
| f"Among highlighted cells, list the values that are {op} {thr:.2f}. " | |
| "Output JSON array of strings." | |
| ) | |
| slots = {"OP": op, "THRESH": f"{thr:.2f}", "COLOR_DESC": "(any color)"} | |
| q = build_question("filter_highlighted_values_by_threshold", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "filter_highlighted_values_by_threshold", | |
| "question": q, | |
| "answer": matched, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_agg_mean_group and has_group: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "aggregate_mean_metric_in_group"), facts, {}): | |
| groups = sorted(set(row_group_map.values())) | |
| if groups: | |
| group_name = rng.choice(groups) | |
| col_indices = sample_cols(1) | |
| if col_indices: | |
| col_idx = col_indices[0] | |
| col = spec.left_cols + col_idx | |
| col_name = col_name_by_index(col_idx) | |
| rows = [r for r, g in row_group_map.items() if g == group_name] | |
| vals = [c for c in data_cells if c.row in rows and c.col == col and is_numeric_cell(c)] | |
| if vals: | |
| mean = sum(c.value for c in vals if c.value is not None) / len(vals) | |
| group_value = group_value_for_question(group_name) | |
| fallback = ( | |
| f'Within "{group_name}", what is the mean value of column {col_name}? ' | |
| "Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = { | |
| "GROUP_NAME": group_name, | |
| "GROUP_COL_NAME": group_col_name, | |
| "GROUP_VALUE": group_value, | |
| "COL_NAME": col_name, | |
| } | |
| q = build_question("aggregate_mean_metric_in_group", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "aggregate_mean_metric_in_group", | |
| "question": q, | |
| "answer": f"{mean:.2f}", | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"group": group_name, "group_col_name": group_col_name, "group_value": group_value, "col": col}, | |
| } | |
| ) | |
| if include_color_yesno_idx or include_color_yesno_noidx: | |
| palette_upper = [c.upper() for c in palette_colors] | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| color_list = [f"{name_map.get(h, 'color')}({h})" for h in palette_upper] | |
| color_list_str = ", ".join(color_list) | |
| highlighted = [c for c in data_cells if c.extra.get("highlight") == "true" and c.value is not None] | |
| non_highlighted = [c for c in data_cells if c.extra.get("highlight") != "true" and c.value is not None] | |
| pool = highlighted + non_highlighted | |
| k = max(0, int(color_yesno_samples)) | |
| value_count: Dict[str, int] = {} | |
| for c in pool: | |
| value_count[c.text] = value_count.get(c.text, 0) + 1 | |
| if include_color_yesno_idx and k > 0 and pool: | |
| for c in _balanced_binary_sample(highlighted, non_highlighted, k, strict=True): | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| col_idx = c.col - spec.left_cols + 1 | |
| is_hl = c.extra.get("highlight") == "true" | |
| color_hex = (c.extra.get("highlight_color") or "").upper() | |
| color_name = name_map.get(color_hex, "color") if is_hl else None | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_COLOR_YN_IDX"), | |
| facts, | |
| {"unique_anchor_value": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"In this table, some numbers are highlighted using the following colors: {color_list_str}. " | |
| f"Is the number at (r={row_idx},c={col_idx}) highlighted? " | |
| "Answer in JSON: {\"highlighted\":true/false,\"color\":<color_name or null>,\"hex\":<hex or null>}. " | |
| "Example: {\"highlighted\":true,\"color\":\"light_blue\",\"hex\":\"#CFE0FF\"}." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx, "PALETTE_LIST": color_list_str} | |
| q = build_question("P_COLOR_YN_IDX", slots, fallback) | |
| ans = { | |
| "highlighted": bool(is_hl), | |
| "color": color_name if is_hl else None, | |
| "hex": color_hex if is_hl else None, | |
| } | |
| out.append( | |
| { | |
| "task_id": "P_COLOR_YN_IDX", | |
| "question": q, | |
| "answer": ans, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["highlighted", "color", "hex"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_color_yesno_noidx and k > 0: | |
| pool_noidx = [c for c in pool if value_count.get(c.text, 0) == 1] | |
| if pool_noidx: | |
| pool_noidx_hl = [c for c in pool_noidx if c.extra.get("highlight") == "true"] | |
| pool_noidx_non_hl = [c for c in pool_noidx if c.extra.get("highlight") != "true"] | |
| for c in _balanced_binary_sample(pool_noidx_hl, pool_noidx_non_hl, k, strict=True): | |
| is_hl = c.extra.get("highlight") == "true" | |
| color_hex = (c.extra.get("highlight_color") or "").upper() | |
| color_name = name_map.get(color_hex, "color") if is_hl else None | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_COLOR_YN_VAL"), | |
| facts, | |
| {"unique_anchor_value": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"In this table, some numbers are highlighted using the following colors: {color_list_str}. " | |
| f"Is the number with value {c.text} highlighted? " | |
| "Answer in JSON: {\"highlighted\":true/false,\"color\":<color_name or null>,\"hex\":<hex or null>}. " | |
| "Example: {\"highlighted\":true,\"color\":\"light_blue\",\"hex\":\"#CFE0FF\"}." | |
| ) | |
| slots = {"ANCHOR_VAL": c.text, "PALETTE_LIST": color_list_str} | |
| q = build_question("P_COLOR_YN_VAL", slots, fallback) | |
| ans = { | |
| "highlighted": bool(is_hl), | |
| "color": color_name if is_hl else None, | |
| "hex": color_hex if is_hl else None, | |
| } | |
| out.append( | |
| { | |
| "task_id": "P_COLOR_YN_VAL", | |
| "question": q, | |
| "answer": ans, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["highlighted", "color", "hex"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_underline_yesno_idx or include_underline_yesno_noidx: | |
| underline_pos = [c for c in data_cells if c.extra.get("underline") == "true" and c.value is not None] | |
| underline_neg = [c for c in data_cells if c.extra.get("underline") != "true" and c.value is not None] | |
| pool = underline_pos + underline_neg | |
| k_underline = max(0, int(underline_yesno_samples)) | |
| value_count_underline: Dict[str, int] = {} | |
| for c in pool: | |
| value_count_underline[c.text] = value_count_underline.get(c.text, 0) + 1 | |
| if include_underline_yesno_idx and k_underline > 0 and pool: | |
| for c in _balanced_binary_sample(underline_pos, underline_neg, k_underline, strict=True): | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| col_idx = c.col - spec.left_cols + 1 | |
| is_underlined = c.extra.get("underline") == "true" | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_UNDERLINE_YN_IDX"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"Is the number at (r={row_idx},c={col_idx}) in the numeric part of the table underlined? " | |
| "Answer JSON {\"underlined\":true/false}. " | |
| "The numeric part of the table includes numeric cells only; exclude all headers/section headers and left header columns. " | |
| "Example: {\"underlined\":true}." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx} | |
| q = build_question("P_UNDERLINE_YN_IDX", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_UNDERLINE_YN_IDX", | |
| "question": q, | |
| "answer": {"underlined": bool(is_underlined)}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["underlined"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_underline_yesno_noidx and k_underline > 0: | |
| pool_noidx = [c for c in pool if value_count_underline.get(c.text, 0) == 1] | |
| if pool_noidx: | |
| pool_noidx_pos = [c for c in pool_noidx if c.extra.get("underline") == "true"] | |
| pool_noidx_neg = [c for c in pool_noidx if c.extra.get("underline") != "true"] | |
| for c in _balanced_binary_sample(pool_noidx_pos, pool_noidx_neg, k_underline, strict=True): | |
| is_underlined = c.extra.get("underline") == "true" | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_UNDERLINE_YN_VAL"), | |
| facts, | |
| {"unique_anchor_value": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"Is the number with value {c.text} underlined? " | |
| "Answer JSON {\"underlined\":true/false}. Example: {\"underlined\":false}." | |
| ) | |
| slots = {"ANCHOR_VAL": c.text} | |
| q = build_question("P_UNDERLINE_YN_VAL", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_UNDERLINE_YN_VAL", | |
| "question": q, | |
| "answer": {"underlined": bool(is_underlined)}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["underlined"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_bold_yesno_idx or include_bold_yesno_noidx: | |
| bold_cells = [c for c in data_cells if c.extra.get("bold") == "true" and c.value is not None] | |
| non_bold_cells = [c for c in data_cells if c.extra.get("bold") != "true" and c.value is not None] | |
| pool = bold_cells + non_bold_cells | |
| k_bold = max(0, int(bold_yesno_samples)) | |
| value_count_bold: Dict[str, int] = {} | |
| for c in pool: | |
| value_count_bold[c.text] = value_count_bold.get(c.text, 0) + 1 | |
| if include_bold_yesno_idx and k_bold > 0 and pool: | |
| for c in _balanced_binary_sample(bold_cells, non_bold_cells, k_bold, strict=True): | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| col_idx = c.col - spec.left_cols + 1 | |
| is_bold = c.extra.get("bold") == "true" | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_BOLD_YN_IDX"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"Is the number at (r={row_idx},c={col_idx}) in the numeric part of the table boldfaced? " | |
| "Answer JSON {\"bold\":true/false}. " | |
| "The numeric part of the table includes numeric cells only; exclude all headers/section headers and left header columns. " | |
| "Example: {\"bold\":true}." | |
| ) | |
| slots = {"R": row_idx, "C": col_idx} | |
| q = build_question("P_BOLD_YN_IDX", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_BOLD_YN_IDX", | |
| "question": q, | |
| "answer": {"bold": bool(is_bold)}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["bold"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_bold_yesno_noidx and k_bold > 0: | |
| pool_noidx = [c for c in pool if value_count_bold.get(c.text, 0) == 1] | |
| if pool_noidx: | |
| pool_noidx_bold = [c for c in pool_noidx if c.extra.get("bold") == "true"] | |
| pool_noidx_non_bold = [c for c in pool_noidx if c.extra.get("bold") != "true"] | |
| for c in _balanced_binary_sample(pool_noidx_bold, pool_noidx_non_bold, k_bold, strict=True): | |
| is_bold = c.extra.get("bold") == "true" | |
| if not _qa_requirements_ok( | |
| _qa_task_entry(qa_lib, "P_BOLD_YN_VAL"), | |
| facts, | |
| {"unique_anchor_value": True}, | |
| ): | |
| continue | |
| fallback = ( | |
| f"Is the number with value {c.text} boldfaced? " | |
| "Answer JSON {\"bold\":true/false}. Example: {\"bold\":false}." | |
| ) | |
| slots = {"ANCHOR_VAL": c.text} | |
| q = build_question("P_BOLD_YN_VAL", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_BOLD_YN_VAL", | |
| "question": q, | |
| "answer": {"bold": bool(is_bold)}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["bold"]}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if spec.delta_col is not None: | |
| delta_idx = spec.delta_col - spec.left_cols | |
| if 0 <= delta_idx < len(spec.data_cols): | |
| delta_name = spec.data_cols[delta_idx].get("metric", "Δ") | |
| else: | |
| delta_name = "Δ" | |
| delta_cells = [c for c in all_data_cells if c.col == spec.delta_col and c.extra.get("delta_col")] | |
| if include_delta_values and delta_cells: | |
| vals = [c.text for c in delta_cells] | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_DELTA_COL"), facts, {}): | |
| fallback = ( | |
| f"List all values in the delta column {delta_name}. " | |
| "Output only a JSON array of strings. Example: [\"+1.70 ± 0.29\",\"-0.34 ± 0.24\"]." | |
| ) | |
| slots = {"COL_NAME": delta_name} | |
| q = build_question("P_DELTA_COL", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_DELTA_COL", | |
| "question": q, | |
| "answer": vals, | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": spec.delta_col}, | |
| } | |
| ) | |
| if include_delta_best_row and delta_cells: | |
| delta_vals = {c.row: float(c.extra.get("delta_base", -1e9)) for c in delta_cells} | |
| best_row = max(delta_vals, key=lambda r: delta_vals[r]) | |
| best_val = delta_vals[best_row] | |
| unique_best = sum(1 for v in delta_vals.values() if v == best_val) == 1 | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "P_DELTA_BEST_ROW"), facts, {"avoid_ties_in_col": unique_best}): | |
| row_idx = row_idx_map.get(best_row, best_row - spec.data_row_start + 1) | |
| fallback = ( | |
| f"Which row has the maximum delta in column {delta_name}? " | |
| "Return the data-row index as a string. Example: \"4\"." | |
| ) | |
| slots = {"COL_NAME": delta_name} | |
| q = build_question("P_DELTA_BEST_ROW", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_DELTA_BEST_ROW", | |
| "question": q, | |
| "answer": str(row_idx), | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": best_row}, | |
| } | |
| ) | |
| # Row-wise delta value lookup is part of the delta-value family; only emit | |
| # it when delta-value questions are explicitly enabled. | |
| if include_delta_values and delta_samples > 0 and delta_cells: | |
| for c in rng.sample(delta_cells, k=min(delta_samples, len(delta_cells))): | |
| row_idx = row_idx_map.get(c.row, c.row - spec.data_row_start + 1) | |
| if not _qa_requirements_ok(_qa_task_entry(qa_lib, "P_DELTA_VAL"), facts, {}): | |
| continue | |
| fallback = ( | |
| f"For the delta column {delta_name}, what is the value at row {row_idx}? " | |
| "Output the full string. Example: \"+1.70 ± 0.29\"." | |
| ) | |
| slots = {"COL_NAME": delta_name, "R": row_idx} | |
| q = build_question("P_DELTA_VAL", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "P_DELTA_VAL", | |
| "question": q, | |
| "answer": c.text, | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {"row": c.row, "col": c.col}, | |
| } | |
| ) | |
| if include_delta_positive_list and spec.delta_col is not None: | |
| delta_cells = [c for c in all_data_cells if c.col == spec.delta_col and c.extra.get("delta_col")] | |
| if delta_cells and _qa_requirements_ok(_qa_task_entry(qa_lib, "delta_gain_positive_list"), facts, {}): | |
| pairs = [] | |
| for c in delta_cells: | |
| base = float(c.extra.get("delta_base", 0.0)) | |
| if base <= 0: | |
| continue | |
| item = row_item_map.get(c.row) | |
| if not item: | |
| continue | |
| pairs.append({"item": item, "value": c.text}) | |
| if pairs: | |
| delta_name = None | |
| delta_idx = spec.delta_col - spec.left_cols | |
| if 0 <= delta_idx < len(spec.data_cols): | |
| delta_name = spec.data_cols[delta_idx].get("metric", "Δ") | |
| delta_name = delta_name or "Δ" | |
| fallback = ( | |
| f"In column {delta_name}, list all items whose value is positive (> 0). " | |
| "Return JSON array of {item,value}. Exclude N/A and —." | |
| ) | |
| slots = {"COL_NAME": delta_name} | |
| q = build_question("delta_gain_positive_list", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "delta_gain_positive_list", | |
| "question": q, | |
| "answer": pairs, | |
| "answer_type": "list", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"col": spec.delta_col}, | |
| } | |
| ) | |
| if include_argmax_overall: | |
| if facts.get("has_metric_arrow"): | |
| pass | |
| elif _qa_requirements_ok(_qa_task_entry(qa_lib, "argmax_overall_coord"), facts, {}): | |
| vals = [c for c in data_cells if is_numeric_cell(c)] | |
| if vals: | |
| max_val = max(c.value for c in vals if c.value is not None) | |
| cands = [c for c in vals if c.value == max_val] | |
| # reading order tie-break: row then col | |
| best = sorted(cands, key=lambda x: (x.row, x.col))[0] | |
| row_idx = data_row_idx(best.row) | |
| col_idx = data_col_idx(best.col) | |
| fallback = ( | |
| "Find the single largest numeric cell in the entire data grid. " | |
| "Return JSON {\"row\":<int>,\"col\":<int>,\"value\":<string>}. " | |
| "Row/col refer to data grid only (exclude headers/section headers; exclude left header columns). " | |
| "Exclude N/A and —." | |
| ) | |
| q = build_question("argmax_overall_coord", {}, fallback) | |
| out.append( | |
| { | |
| "task_id": "argmax_overall_coord", | |
| "question": q, | |
| "answer": {"row": row_idx, "col": col_idx, "value": best.text}, | |
| "answer_type": "record", | |
| "scoring": {"type": "record_multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_object", "keys": ["row", "col", "value"]}, | |
| "meta": {"row": best.row, "col": best.col}, | |
| } | |
| ) | |
| if include_multi_hop_style_agg and facts.get("has_highlight_or_underline"): | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "multi_hop_style_then_aggregate"), facts, {}): | |
| k = max(1, int(multi_hop_samples)) | |
| for _ in range(k): | |
| style_modes: List[str] = [] | |
| if has_highlight: | |
| style_modes.append("highlight") | |
| if has_underline: | |
| style_modes.append("underline") | |
| if has_bold: | |
| style_modes.append("bold") | |
| if has_text_color: | |
| style_modes.append("text_color") | |
| if not style_modes: | |
| continue | |
| chosen_style = rng.choice(style_modes) | |
| if chosen_style == "underline": | |
| style_desc = "underlined" | |
| chosen = [c for c in all_data_cells if c.extra.get("underline") == "true" and is_numeric_cell(c)] | |
| elif chosen_style == "bold": | |
| style_desc = "boldfaced" | |
| chosen = [c for c in all_data_cells if c.extra.get("bold") == "true" and is_numeric_cell(c)] | |
| elif chosen_style == "text_color": | |
| style_desc = "text-colored" | |
| chosen = [c for c in all_data_cells if c.extra.get("text_color") == "true" and is_numeric_cell(c)] | |
| else: | |
| style_desc = "highlighted (any color)" | |
| chosen = [c for c in all_data_cells if c.extra.get("highlight") == "true" and is_numeric_cell(c)] | |
| if chosen: | |
| op = rng.choice(["sum", "mean", "max", "min"]) | |
| vals = [c.value for c in chosen if c.value is not None] | |
| if vals: | |
| if op == "sum": | |
| agg = sum(vals) | |
| elif op == "mean": | |
| agg = sum(vals) / len(vals) | |
| elif op == "max": | |
| agg = max(vals) | |
| else: | |
| agg = min(vals) | |
| fallback = ( | |
| f"Among {style_desc} numbers, compute the {op}. " | |
| "Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"STYLE_DESC": style_desc, "AGG_OP": op} | |
| q = build_question("multi_hop_style_then_aggregate", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "multi_hop_style_then_aggregate", | |
| "question": q, | |
| "answer": f"{agg:.2f}", | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_multi_hop_exclude_agg and facts.get("has_highlight_or_underline"): | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "multi_hop_exclude_style_then_aggregate"), facts, {}): | |
| k = max(1, int(multi_hop_samples)) | |
| for _ in range(k): | |
| style_modes: List[str] = [] | |
| if has_highlight: | |
| style_modes.append("highlight") | |
| if has_underline: | |
| style_modes.append("underline") | |
| if has_bold: | |
| style_modes.append("bold") | |
| if has_text_color: | |
| style_modes.append("text_color") | |
| if not style_modes: | |
| continue | |
| chosen_style = rng.choice(style_modes) | |
| if chosen_style == "underline": | |
| style_desc = "underlined" | |
| remain = [c for c in all_data_cells if c.extra.get("underline") != "true" and is_numeric_cell(c)] | |
| elif chosen_style == "bold": | |
| style_desc = "boldfaced" | |
| remain = [c for c in all_data_cells if c.extra.get("bold") != "true" and is_numeric_cell(c)] | |
| elif chosen_style == "text_color": | |
| style_desc = "text-colored" | |
| remain = [c for c in all_data_cells if c.extra.get("text_color") != "true" and is_numeric_cell(c)] | |
| else: | |
| style_desc = "highlighted (any color)" | |
| remain = [c for c in all_data_cells if c.extra.get("highlight") != "true" and is_numeric_cell(c)] | |
| if remain: | |
| op = rng.choice(["sum", "mean", "max", "min"]) | |
| vals = [c.value for c in remain if c.value is not None] | |
| if vals: | |
| if op == "sum": | |
| agg = sum(vals) | |
| elif op == "mean": | |
| agg = sum(vals) / len(vals) | |
| elif op == "max": | |
| agg = max(vals) | |
| else: | |
| agg = min(vals) | |
| fallback = ( | |
| f"Ignoring {style_desc} cells, compute the {op} over the rest in the whole table. " | |
| "Exclude N/A and —. Output only the number as a string. Example: \"12.34\"." | |
| ) | |
| slots = {"STYLE_DESC": style_desc, "AGG_OP": op, "SCOPE_DESC": "in the whole table"} | |
| q = build_question("multi_hop_exclude_style_then_aggregate", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "multi_hop_exclude_style_then_aggregate", | |
| "question": q, | |
| "answer": f"{agg:.2f}", | |
| "answer_type": "string", | |
| "scoring": {"type": "exact"}, | |
| "expected_format": {"type": "string"}, | |
| "meta": {}, | |
| } | |
| ) | |
| if include_counterfactual: | |
| if _qa_requirements_ok(_qa_task_entry(qa_lib, "counterfactual_style_absent"), facts, {}): | |
| name_map = _build_palette_color_names(palette_colors, explicit=palette_names) | |
| used = {str(c.extra.get("highlight_color") or "").upper() for c in all_data_cells if c.extra.get("highlight") == "true"} | |
| palette_upper = [c.upper() for c in palette_colors] | |
| candidates = [h for h in palette_upper if h not in used] | |
| if not candidates and palette_upper: | |
| candidates = [] | |
| if candidates: | |
| color_hex = rng.choice(candidates) | |
| color_name = name_map.get(color_hex, "color") | |
| style_desc = f"{color_name} highlight" | |
| fallback = ( | |
| f"List all numbers highlighted in {color_name} (hex {color_hex}). " | |
| "If none, output an empty JSON array []." | |
| ) | |
| slots = {"COLOR_NAME": color_name, "COLOR_HEX": color_hex, "STYLE_DESC": style_desc} | |
| q = build_question("counterfactual_style_absent", slots, fallback) | |
| out.append( | |
| { | |
| "task_id": "counterfactual_style_absent", | |
| "question": q, | |
| "answer": [], | |
| "answer_type": "list", | |
| "scoring": {"type": "multiset_exact", "penalty_extra": True}, | |
| "expected_format": {"type": "json_array", "order": "any"}, | |
| "meta": {"color": color_hex, "color_name": color_name}, | |
| } | |
| ) | |
| if qa_lib: | |
| out = [_qa_attach_task_metadata(item, qa_lib) for item in out] | |
| return out | |
| def _write_clean_qa(in_path: Path, out_path: Path) -> None: | |
| keep_order = [ | |
| "qid", | |
| "image_path", | |
| "image_id", | |
| "task_id", | |
| "qa_task_name", | |
| "qa_category", | |
| "qa_category_id", | |
| "table_shape_profile", | |
| "question", | |
| "answer", | |
| ] | |
| if not in_path.exists(): | |
| return | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| with in_path.open("r", encoding="utf-8") as fin, out_path.open("w", encoding="utf-8") as fout: | |
| for line in fin: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| rec = json.loads(line) | |
| except Exception: | |
| continue | |
| out = {k: rec.get(k) for k in keep_order if k in rec} | |
| fout.write(json.dumps(out, ensure_ascii=False) + "\n") | |
| # ========================= | |
| # ========================= | |
| def main() -> int: | |
| p = argparse.ArgumentParser(description="Generate paper-style result tables (PNG + JSON).") | |
| p.add_argument("--out-dir", default="out_paper") | |
| p.add_argument("--count", type=int, default=5) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--canvas-width", type=int, default=1400) | |
| p.add_argument("--canvas-height", type=int, default=800) | |
| p.add_argument("--margins", default="40,40,40,40", help="left,top,right,bottom") | |
| p.add_argument("--crop-to-table", dest="crop_to_table", action="store_true", default=True, help="Crop output image to table bbox with padding.") | |
| p.add_argument("--no-crop-to-table", dest="crop_to_table", action="store_false", help="Keep full canvas (no post-render crop).") | |
| p.add_argument("--crop-pad", type=int, default=12, help="Padding (pixels) when cropping to table bbox.") | |
| p.add_argument("--font-path", default=None) | |
| p.add_argument("--font-size", type=int, default=24) | |
| p.add_argument("--line-style", choices=["none", "grid", "three-line", "sparse-grid"], default="three-line") | |
| p.add_argument("--block-sep", action="store_true", help="Draw vertical separators between blocks.") | |
| p.add_argument("--number-align", choices=["left", "center", "right"], default="center") | |
| p.add_argument("--arrow-offset-x", type=int, default=0, help="Arrow x offset (pixels).") | |
| p.add_argument("--arrow-offset-y", type=int, default=0, help="Arrow y offset (pixels).") | |
| p.add_argument("--arrow-scale", type=float, default=0.38, help="Arrow size scale vs font size.") | |
| p.add_argument("--delta-pm-scale", type=float, default=1.00, help="Relative font scale for ±std text in delta column (default 1.0, same as main digits).") | |
| p.add_argument("--group-count", type=int, default=3) | |
| p.add_argument("--min-items", type=int, default=3) | |
| p.add_argument("--max-items", type=int, default=5) | |
| p.add_argument("--block-count", type=int, default=3) | |
| p.add_argument("--min-metrics", type=int, default=2) | |
| p.add_argument("--max-metrics", type=int, default=3) | |
| p.add_argument("--mid-groups-min", type=int, default=1, help="Min mid-groups per top group when top-levels=3.") | |
| p.add_argument("--mid-groups-max", type=int, default=2, help="Max mid-groups per top group when top-levels=3.") | |
| p.add_argument("--section-count", type=int, default=0, help="Insert mid-table section header rows.") | |
| p.add_argument("--unique-numbers", action="store_true", help="Ensure all numeric cells are unique.") | |
| p.add_argument("--top-levels", choices=["1", "2", "3", "random"], default="random", help="Top header levels (1/2/3/random).") | |
| p.add_argument("--left-levels", choices=["1", "2", "random"], default="random", help="Left header levels (1/2/random).") | |
| p.add_argument( | |
| "--table-shape-mode", | |
| choices=["fixed", "mixed"], | |
| default="fixed", | |
| help="fixed = use one structural regime; mixed = per-image sample compact/wide/tall/dense_header profiles.", | |
| ) | |
| p.add_argument( | |
| "--table-shape-profile-probs", | |
| default="1,1,1,1", | |
| help="Weights for mixed shape profiles: compact,wide,tall,dense_header.", | |
| ) | |
| p.add_argument("--merge-group-prob", type=float, default=0.7) | |
| p.add_argument("--citation-prob", type=float, default=0.3) | |
| p.add_argument("--missing-prob", type=float, default=0.05) | |
| p.add_argument("--dec-min", type=int, default=2) | |
| p.add_argument("--dec-max", type=int, default=2) | |
| p.add_argument("--highlight", action="store_true", help="Enable soft-color highlights.") | |
| p.add_argument("--highlight-mode", choices=["single", "multi", "random"], default="random") | |
| p.add_argument("--highlight-rate", type=float, default=0.12, help="Highlight ratio for data cells.") | |
| p.add_argument("--highlight-count", type=int, default=0, help="Fixed highlight count (overrides rate if >0).") | |
| p.add_argument( | |
| "--highlight-colors", | |
| default="#FFD2E6,#E1FFE1,#FFFAD2,#FFB3B3", | |
| help="Comma-separated soft colors (<=4 recommended).", | |
| ) | |
| p.add_argument( | |
| "--highlight-palettes", | |
| default=None, | |
| help="Multiple palettes separated by ';'. Each palette is comma-separated colors.", | |
| ) | |
| p.add_argument( | |
| "--highlight-palettes-file", | |
| default=None, | |
| help="JSON file with palettes (e.g. palette_preview/index.json).", | |
| ) | |
| p.add_argument("--highlight-use-all-colors", action="store_true", help="Ensure all colors appear in one image.") | |
| p.add_argument("--underline-rate", type=float, default=0.0, help="Underline ratio for data cells.") | |
| p.add_argument("--underline-best-per-col", action="store_true", help="Underline best value in each column.") | |
| p.add_argument("--underline-second-per-col", action="store_true", help="Underline second-best value in each column.") | |
| p.add_argument("--underline-wrong-per-col", action="store_true", help="Underline a non-best value in each column.") | |
| p.add_argument("--underline-image-prob", type=float, default=1.0, help="Probability to apply underlines per image.") | |
| p.add_argument("--bold-rate", type=float, default=0.0, help="Bold ratio for data cells.") | |
| p.add_argument("--bold-best-per-col", action="store_true", help="Bold best value in each column.") | |
| p.add_argument("--bold-wrong-per-col", action="store_true", help="Bold a non-best value in each column.") | |
| p.add_argument("--bold-image-prob", type=float, default=1.0, help="Probability to apply bold per image.") | |
| p.add_argument("--text-color-delta-sign", action="store_true", help="Color delta-column text by sign (pos/neg).") | |
| p.add_argument("--text-color-best-per-col", action="store_true", help="Color best value text in each numeric column.") | |
| p.add_argument("--text-color-image-prob", type=float, default=0.0, help="Probability to apply text color per image.") | |
| p.add_argument("--text-color-pos-hex", default="#2E7D32", help="Text color for positive delta values.") | |
| p.add_argument("--text-color-neg-hex", default="#C62828", help="Text color for negative delta values.") | |
| p.add_argument("--text-color-best-hex", default="#1565C0", help="Text color for best-per-column values.") | |
| p.add_argument( | |
| "--marker-combo-mode", | |
| choices=["independent", "three-way"], | |
| default="independent", | |
| help="How to mix underline/bold across images. three-way forces underline_only/bold_only/both (no none).", | |
| ) | |
| p.add_argument( | |
| "--marker-combo-probs", | |
| default="1,1,6", | |
| help="Weights for three-way marker combo mode: underline_only,bold_only,both.", | |
| ) | |
| p.add_argument( | |
| "--marker-role-policy", | |
| choices=["manual", "paper"], | |
| default="manual", | |
| help="In three-way mode, paper = underline-only=>underline-best, bold-only=>bold-best, both=>bold-best+underline-second.", | |
| ) | |
| p.add_argument( | |
| "--underline-image-prob-overall", | |
| type=float, | |
| default=0.4, | |
| help="Target overall underline ratio (0~1). If set and auto-abc enabled, A-group will be 0 and B/C will be scaled.", | |
| ) | |
| p.add_argument( | |
| "--bold-image-prob-overall", | |
| type=float, | |
| default=-1.0, | |
| help="Target overall bold ratio (0~1). If set and auto-abc enabled, A-group will be 0 and B/C will be scaled.", | |
| ) | |
| p.add_argument("--arrow-rate", type=float, default=0.0, help="Arrow ratio for data cells.") | |
| p.add_argument("--arrow-up-ratio", type=float, default=0.5, help="Fraction of arrows that are up.") | |
| p.add_argument("--data-arrows", action="store_true", help="Enable arrows on data cells (disabled by default).") | |
| p.add_argument("--metric-arrow-prob", type=float, default=0.6, help="Probability to append ↑/↓ to metric names.") | |
| p.add_argument("--config-rows", action="store_true", help="Place a Δ column inside the table (no extra ✓/✗ rows).") | |
| p.add_argument( | |
| "--config-rows-prob", | |
| type=float, | |
| default=0.2, | |
| help="Probability to enable the Δ column per image (only if --config-rows is set).", | |
| ) | |
| p.add_argument( | |
| "--config-flag-pool", | |
| default=None, | |
| help="Comma-separated pool for the two config flag names.", | |
| ) | |
| p.add_argument("--config-shade-best-row", action="store_true", help="Shade the best Δ row lightly.") | |
| p.add_argument("--highlight-strategy", choices=["random", "by_column_rank", "by_column_wrong"], default="random") | |
| p.add_argument("--highlight-rank-k", type=int, default=0, help="Top-K per column when using by_column_rank.") | |
| p.add_argument("--qa-position", action="store_true", help="Ask all position questions.") | |
| p.add_argument("--qa-position-samples", type=int, default=5, help="Samples of P_POS per image (0=all).") | |
| p.add_argument("--qa-cell-lookup", action="store_true", help="Ask row+col name lookup questions.") | |
| p.add_argument("--qa-cell-lookup-samples", type=int, default=5, help="Samples of row+col lookup per image.") | |
| p.add_argument("--qa-col-extremes", action="store_true", help="Ask max/min per column.") | |
| p.add_argument("--qa-col-extremes-k", type=int, default=5, help="Max number of columns for max/min questions (0=all).") | |
| p.add_argument("--qa-row-extremes", action="store_true", help="Ask max/min per row.") | |
| p.add_argument("--qa-row-extremes-k", type=int, default=5, help="Max number of rows for max/min questions (0=all).") | |
| p.add_argument("--qa-col-argmax-item", action="store_true", help="Ask argmax item per column.") | |
| p.add_argument("--qa-col-argmax-coord", action="store_true", help="Ask argmax coord per column.") | |
| p.add_argument("--qa-topk", action="store_true", help="Ask top-k per column.") | |
| p.add_argument("--qa-topk-k", type=int, default=3, help="K for top-k.") | |
| p.add_argument("--qa-topk-cols", type=int, default=3, help="Number of columns for top-k.") | |
| p.add_argument("--qa-kth", action="store_true", help="Ask k-th per column.") | |
| p.add_argument("--qa-kth-k", type=int, default=2, help="K for k-th.") | |
| p.add_argument("--qa-compare-rows", action="store_true", help="Compare two rows on one metric.") | |
| p.add_argument("--qa-compare-cols", action="store_true", help="Compare two metrics within one row.") | |
| p.add_argument("--qa-compare-samples", type=int, default=3, help="Number of compare questions per image.") | |
| p.add_argument("--qa-col-best", action="store_true", help="Ask best item per column using arrow direction.") | |
| p.add_argument("--qa-group-col-best", action="store_true", help="Ask best item per group in a column.") | |
| p.add_argument("--qa-highlight-neighbor", action="store_true", help="Neighbor of highlighted/underlined/bold cell.") | |
| p.add_argument("--qa-highlight-neighbor-samples", type=int, default=3, help="Samples for highlight-neighbor.") | |
| p.add_argument("--qa-neighbors-idx", action="store_true", help="Neighbor questions with (row,col).") | |
| p.add_argument("--qa-neighbors-noidx", action="store_true", help="Neighbor questions by value only (unique values).") | |
| p.add_argument("--qa-neighbor-samples", type=int, default=5, help="Number of neighbor samples per variant per image.") | |
| p.add_argument("--qa-color-values", action="store_true", help="Ask for values by highlight color.") | |
| p.add_argument("--qa-same-color", action="store_true", help="Ask for values sharing the same highlight color.") | |
| p.add_argument("--qa-same-color-samples", type=int, default=5, help="Number of same-color questions per image.") | |
| p.add_argument("--qa-same-color-noidx", action="store_true", help="Same-color questions without (row,col).") | |
| p.add_argument("--qa-same-color-noidx-samples", type=int, default=5, help="Number of same-color (no idx) questions per image.") | |
| p.add_argument("--qa-text-color-values", action="store_true", help="Ask for values by text color (e.g., red text).") | |
| p.add_argument("--qa-underline", action="store_true", help="Ask for all underlined numbers.") | |
| p.add_argument("--qa-underline-per-col", action="store_true", help="Ask for underlined numbers per column.") | |
| p.add_argument("--qa-underline-yesno-idx", action="store_true", help="Underline yes/no questions with (row,col).") | |
| p.add_argument("--qa-underline-yesno-noidx", action="store_true", help="Underline yes/no questions by value only (unique values).") | |
| p.add_argument("--qa-underline-yesno-samples", type=int, default=5, help="Number of underline yes/no questions per variant per image.") | |
| p.add_argument("--qa-bold", action="store_true", help="Ask for all bold numbers.") | |
| p.add_argument("--qa-bold-per-col", action="store_true", help="Ask for bold numbers per column.") | |
| p.add_argument("--qa-bold-yesno-idx", action="store_true", help="Bold yes/no questions with (row,col).") | |
| p.add_argument("--qa-bold-yesno-noidx", action="store_true", help="Bold yes/no questions by value only (unique values).") | |
| p.add_argument("--qa-bold-yesno-samples", type=int, default=5, help="Number of bold yes/no questions per variant per image.") | |
| p.add_argument("--qa-color-yesno-idx", action="store_true", help="Color yes/no questions with (row,col).") | |
| p.add_argument("--qa-color-yesno-noidx", action="store_true", help="Color yes/no questions by value only (unique values).") | |
| p.add_argument("--qa-color-yesno-samples", type=int, default=5, help="Number of color yes/no questions per variant per image.") | |
| p.add_argument("--qa-missing-list", action="store_true", help="Ask missing list per column.") | |
| p.add_argument("--qa-missing-check", action="store_true", help="Ask missing check for a cell.") | |
| p.add_argument("--qa-missing-samples", type=int, default=3, help="Samples for missing check/list.") | |
| p.add_argument("--qa-count-highlight", action="store_true", help="Count highlighted cells.") | |
| p.add_argument("--qa-count-underline", action="store_true", help="Count underlined cells.") | |
| p.add_argument("--qa-count-bold", action="store_true", help="Count bold cells.") | |
| p.add_argument("--qa-filter-threshold", action="store_true", help="Filter values by threshold.") | |
| p.add_argument("--qa-filter-highlight-threshold", action="store_true", help="Filter highlighted values by threshold.") | |
| p.add_argument("--qa-filter-samples", type=int, default=3, help="Samples for threshold filter.") | |
| p.add_argument("--qa-agg-mean-group", action="store_true", help="Mean in group for one column.") | |
| p.add_argument("--qa-delta-positive-list", action="store_true", help="List positive delta rows.") | |
| p.add_argument("--qa-argmax-overall", action="store_true", help="Argmax over whole table.") | |
| p.add_argument("--qa-multi-hop-style-agg", action="store_true", help="Aggregate over styled cells.") | |
| p.add_argument("--qa-multi-hop-exclude-agg", action="store_true", help="Aggregate over non-styled cells.") | |
| p.add_argument("--qa-multi-hop-samples", type=int, default=2, help="Samples for multi-hop aggregation.") | |
| p.add_argument("--qa-counterfactual", action="store_true", help="Ask empty-result style questions.") | |
| # Congruency mode | |
| p.add_argument( | |
| "--congruency-mode", | |
| choices=["none", "congruent", "neutral", "incongruent", "mix"], | |
| default="none", | |
| help="Congruent: style markers align with max; Neutral: no style; Incongruent: style markers point to non-max.", | |
| ) | |
| p.add_argument("--qa-delta-col", action="store_true", help="Ask for all values in the delta column.") | |
| p.add_argument("--qa-delta-best-row", action="store_true", help="Ask for row with maximum delta.") | |
| p.add_argument("--qa-delta-samples", type=int, default=3, help="Number of delta value questions per image.") | |
| p.add_argument("--qa-template-json", default="question.json", help="Question template library JSON (optional).") | |
| p.add_argument("--probe-six", action="store_true", help="Generate 6 variants per base table.") | |
| p.add_argument("--probe-seven", action="store_true", help="Generate 7 unique style-counterfactual variants per base table.") | |
| p.add_argument("--task-name", default="HighlightBench", help="Task set name to store in JSON.") | |
| p.add_argument("--auto-abc", action="store_true", help="Auto switch A/B/C highlight behavior by palette id.") | |
| p.add_argument( | |
| "--gt-format", | |
| choices=["jsonl", "json", "both"], | |
| default="json", | |
| help="GT output format: jsonl (default), json, or both.", | |
| ) | |
| args = p.parse_args() | |
| rng = random.Random(args.seed) | |
| marker_combo_weights = [1.0, 1.0, 1.0] | |
| marker_combo_schedule: List[str] = [] | |
| if str(args.marker_combo_mode) == "three-way": | |
| try: | |
| marker_combo_weights = [float(x.strip()) for x in str(args.marker_combo_probs).split(",")] | |
| except Exception as e: | |
| raise SystemExit(f"--marker-combo-probs parse error: {e}") | |
| if len(marker_combo_weights) != 3: | |
| raise SystemExit("--marker-combo-probs must be 3 comma-separated numbers: underline_only,bold_only,both") | |
| if any(w < 0 for w in marker_combo_weights): | |
| raise SystemExit("--marker-combo-probs cannot contain negative values") | |
| if sum(marker_combo_weights) <= 0: | |
| raise SystemExit("--marker-combo-probs must have positive total weight") | |
| combo_names = ["underline_only", "bold_only", "both"] | |
| n_imgs = max(0, int(args.count)) | |
| guaranteed = [name for name, w in zip(combo_names, marker_combo_weights) if w > 0] | |
| if n_imgs > 0: | |
| if n_imgs >= len(guaranteed): | |
| marker_combo_schedule.extend(guaranteed) | |
| remain = n_imgs - len(guaranteed) | |
| else: | |
| ranked = sorted(zip(combo_names, marker_combo_weights), key=lambda x: x[1], reverse=True) | |
| marker_combo_schedule.extend([name for name, w in ranked[:n_imgs] if w > 0]) | |
| remain = 0 | |
| for _ in range(remain): | |
| marker_combo_schedule.append( | |
| rng.choices(combo_names, weights=marker_combo_weights, k=1)[0] | |
| ) | |
| rng.shuffle(marker_combo_schedule) | |
| shape_profile_names = ["compact", "wide", "tall", "dense_header"] | |
| shape_profile_weights = [1.0, 1.0, 1.0, 1.0] | |
| if str(args.table_shape_mode) == "mixed": | |
| try: | |
| shape_profile_weights = [float(x.strip()) for x in str(args.table_shape_profile_probs).split(",")] | |
| except Exception as e: | |
| raise SystemExit(f"--table-shape-profile-probs parse error: {e}") | |
| if len(shape_profile_weights) != 4: | |
| raise SystemExit("--table-shape-profile-probs must be 4 comma-separated numbers: compact,wide,tall,dense_header") | |
| if any(w < 0 for w in shape_profile_weights): | |
| raise SystemExit("--table-shape-profile-probs cannot contain negative values") | |
| if sum(shape_profile_weights) <= 0: | |
| raise SystemExit("--table-shape-profile-probs must have positive total weight") | |
| def _sample_table_shape_cfg() -> Dict[str, Any]: | |
| if args.top_levels == "random": | |
| top_levels_local = rng.choice([1, 2]) | |
| else: | |
| top_levels_local = int(args.top_levels) | |
| if args.left_levels == "random": | |
| left_levels_local = rng.choice([1, 2]) | |
| else: | |
| left_levels_local = int(args.left_levels) | |
| cfg: Dict[str, Any] = { | |
| "profile": "fixed", | |
| "group_count": int(args.group_count), | |
| "min_items": int(args.min_items), | |
| "max_items": int(args.max_items), | |
| "block_count": int(args.block_count), | |
| "min_metrics": int(args.min_metrics), | |
| "max_metrics": int(args.max_metrics), | |
| "mid_group_min": int(args.mid_groups_min), | |
| "mid_group_max": int(args.mid_groups_max), | |
| "section_count": int(args.section_count), | |
| "top_levels": int(top_levels_local), | |
| "left_levels": int(left_levels_local), | |
| } | |
| if str(args.table_shape_mode) != "mixed": | |
| return cfg | |
| profile = rng.choices(shape_profile_names, weights=shape_profile_weights, k=1)[0] | |
| cfg["profile"] = profile | |
| if args.top_levels == "random": | |
| if profile == "dense_header": | |
| cfg["top_levels"] = 2 | |
| elif profile == "wide": | |
| cfg["top_levels"] = rng.choice([1, 2, 2]) | |
| elif profile == "tall": | |
| cfg["top_levels"] = rng.choice([1, 2]) | |
| else: # compact | |
| cfg["top_levels"] = rng.choice([1, 2]) | |
| if args.left_levels == "random": | |
| if profile == "dense_header": | |
| cfg["left_levels"] = 2 | |
| elif profile == "tall": | |
| cfg["left_levels"] = rng.choice([1, 2, 2]) | |
| else: | |
| cfg["left_levels"] = rng.choice([1, 2]) | |
| if profile == "compact": | |
| cfg["group_count"] = _clamp_int(cfg["group_count"] - rng.choice([0, 1]), lo=1) | |
| cfg["block_count"] = _clamp_int(cfg["block_count"] - rng.choice([0, 1]), lo=1) | |
| cfg["min_items"] = _clamp_int(cfg["min_items"] - rng.choice([0, 1]), lo=2) | |
| cfg["max_items"] = _clamp_int(cfg["max_items"] - rng.choice([0, 1]), lo=cfg["min_items"]) | |
| cfg["min_metrics"] = _clamp_int(cfg["min_metrics"] - rng.choice([0, 1]), lo=1) | |
| cfg["max_metrics"] = _clamp_int(cfg["max_metrics"] - rng.choice([0, 1]), lo=cfg["min_metrics"]) | |
| cfg["mid_group_min"] = _clamp_int(cfg["mid_group_min"], lo=1) | |
| cfg["mid_group_max"] = _clamp_int(min(cfg["mid_group_max"], cfg["mid_group_min"] + 1), lo=cfg["mid_group_min"]) | |
| cfg["section_count"] = max(0, min(cfg["section_count"], 1)) | |
| elif profile == "wide": | |
| cfg["group_count"] = _clamp_int(cfg["group_count"] - rng.choice([0, 1]), lo=1) | |
| cfg["min_items"] = _clamp_int(cfg["min_items"] - rng.choice([0, 1]), lo=2) | |
| cfg["max_items"] = _clamp_int(cfg["max_items"], lo=cfg["min_items"]) | |
| cfg["block_count"] = _clamp_int(cfg["block_count"] + rng.choice([1, 1, 2]), lo=1) | |
| cfg["min_metrics"] = _clamp_int(cfg["min_metrics"] + rng.choice([0, 1]), lo=1) | |
| cfg["max_metrics"] = _clamp_int(cfg["max_metrics"] + rng.choice([1, 1, 2]), lo=cfg["min_metrics"]) | |
| if cfg["top_levels"] == 3: | |
| cfg["mid_group_min"] = _clamp_int(cfg["mid_group_min"] + rng.choice([0, 1]), lo=1) | |
| cfg["mid_group_max"] = _clamp_int(cfg["mid_group_max"] + rng.choice([1, 1, 2]), lo=cfg["mid_group_min"]) | |
| cfg["section_count"] = max(0, cfg["section_count"]) | |
| elif profile == "tall": | |
| cfg["group_count"] = _clamp_int(cfg["group_count"] + rng.choice([1, 1, 2]), lo=1) | |
| cfg["min_items"] = _clamp_int(cfg["min_items"] + rng.choice([0, 1]), lo=2) | |
| cfg["max_items"] = _clamp_int(cfg["max_items"] + rng.choice([1, 1, 2]), lo=cfg["min_items"]) | |
| cfg["block_count"] = _clamp_int(cfg["block_count"] - rng.choice([0, 1]), lo=1) | |
| cfg["min_metrics"] = _clamp_int(cfg["min_metrics"] - rng.choice([0, 1]), lo=1) | |
| cfg["max_metrics"] = _clamp_int(cfg["max_metrics"] - rng.choice([0, 1]), lo=cfg["min_metrics"]) | |
| cfg["section_count"] = max(cfg["section_count"], rng.choice([0, 1])) | |
| if cfg["top_levels"] == 3: | |
| cfg["mid_group_min"] = _clamp_int(cfg["mid_group_min"], lo=1) | |
| cfg["mid_group_max"] = _clamp_int(min(cfg["mid_group_max"], cfg["mid_group_min"] + 1), lo=cfg["mid_group_min"]) | |
| elif profile == "dense_header": | |
| cfg["group_count"] = _clamp_int(cfg["group_count"], lo=1) | |
| cfg["min_items"] = _clamp_int(cfg["min_items"] - rng.choice([0, 1]), lo=2) | |
| cfg["max_items"] = _clamp_int(cfg["max_items"], lo=cfg["min_items"]) | |
| cfg["block_count"] = _clamp_int(cfg["block_count"] + rng.choice([0, 1]), lo=1) | |
| cfg["min_metrics"] = _clamp_int(min(cfg["min_metrics"], 2), lo=1) | |
| cfg["max_metrics"] = _clamp_int(min(cfg["max_metrics"] + 1, max(2, cfg["max_metrics"])), lo=cfg["min_metrics"]) | |
| cfg["top_levels"] = 2 if args.top_levels == "random" else cfg["top_levels"] | |
| cfg["left_levels"] = 2 if args.left_levels == "random" else cfg["left_levels"] | |
| cfg["mid_group_min"] = _clamp_int(max(cfg["mid_group_min"], 1), lo=1) | |
| cfg["mid_group_max"] = _clamp_int(max(cfg["mid_group_max"], cfg["mid_group_min"] + 1), lo=cfg["mid_group_min"]) | |
| cfg["section_count"] = max(cfg["section_count"], rng.choice([1, 1, 2])) | |
| cfg["group_count"] = _clamp_int(cfg["group_count"], lo=1) | |
| cfg["block_count"] = _clamp_int(cfg["block_count"], lo=1) | |
| cfg["min_items"] = _clamp_int(cfg["min_items"], lo=1) | |
| cfg["max_items"] = _clamp_int(cfg["max_items"], lo=cfg["min_items"]) | |
| cfg["min_metrics"] = _clamp_int(cfg["min_metrics"], lo=1) | |
| cfg["max_metrics"] = _clamp_int(cfg["max_metrics"], lo=cfg["min_metrics"]) | |
| cfg["mid_group_min"] = _clamp_int(cfg["mid_group_min"], lo=1) | |
| cfg["mid_group_max"] = _clamp_int(cfg["mid_group_max"], lo=cfg["mid_group_min"]) | |
| cfg["section_count"] = max(0, min(3, int(cfg["section_count"]))) | |
| cfg["top_levels"] = _clamp_int(int(cfg["top_levels"]), lo=1, hi=(2 if args.top_levels == "random" else 3)) | |
| cfg["left_levels"] = _clamp_int(int(cfg["left_levels"]), lo=1, hi=2) | |
| return cfg | |
| qa_lib = _load_question_library(args.qa_template_json) | |
| cfg_info = build_config_info( | |
| vars(args), | |
| exclude={"out_dir", "count", "seed", "qa_template_json"}, | |
| ) | |
| out_dir = Path(args.out_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| (out_dir / "images").mkdir(parents=True, exist_ok=True) | |
| (out_dir / "ann").mkdir(parents=True, exist_ok=True) | |
| m = [int(x) for x in args.margins.split(",")] | |
| if len(m) != 4: | |
| raise SystemExit("--margins must be 4 comma-separated ints") | |
| margins = (m[0], m[1], m[2], m[3]) | |
| def _build_spec_with_readability_retries( | |
| initial_shape_cfg: Dict[str, Any], | |
| builder_fn, | |
| *, | |
| max_retries: int = 24, | |
| ) -> Tuple[TableSpec, Dict[str, Any]]: | |
| """Build a table spec and retry when the layout is too dense for the canvas/font.""" | |
| shape_cfg_local = dict(initial_shape_cfg) | |
| last_spec: Optional[TableSpec] = None | |
| for _attempt in range(max(1, int(max_retries))): | |
| spec_try = builder_fn(shape_cfg_local) | |
| last_spec = spec_try | |
| if _spec_layout_is_readable( | |
| spec_try, | |
| canvas_width=int(args.canvas_width), | |
| canvas_height=int(args.canvas_height), | |
| margins=margins, | |
| font_path=args.font_path, | |
| font_size=int(args.font_size), | |
| arrow_scale=float(args.arrow_scale), | |
| ): | |
| return spec_try, shape_cfg_local | |
| if str(args.table_shape_mode) == "mixed": | |
| shape_cfg_local = _sample_table_shape_cfg() | |
| raise SystemExit( | |
| "Failed to generate a readable table layout after multiple retries. " | |
| "Try increasing canvas size, reducing table density (groups/blocks/metrics), or lowering font size." | |
| ) | |
| gt_path = out_dir / "gt.jsonl" | |
| gt_json_path = out_dir / "gt.json" | |
| qa_full_path = out_dir / "qa_full.jsonl" | |
| qa_path = out_dir / "qa.jsonl" | |
| qid_counter = 1 | |
| gt_records: List[Dict] = [] | |
| write_jsonl = args.gt_format in ("jsonl", "both") | |
| write_json = args.gt_format in ("json", "both") | |
| fgt = gt_path.open("w", encoding="utf-8") if write_jsonl else None | |
| try: | |
| with qa_full_path.open("w", encoding="utf-8") as fqa: | |
| palettes = None | |
| if args.highlight_palettes: | |
| palettes = [] | |
| for i, pal in enumerate(_parse_palettes(args.highlight_palettes)): | |
| palettes.append({"id": f"custom_{i}", "palette": pal, "names": None}) | |
| if args.highlight_palettes_file: | |
| try: | |
| data = json.loads(Path(args.highlight_palettes_file).read_text(encoding="utf-8")) | |
| file_pals = [] | |
| for k, v in data.items(): | |
| if isinstance(v, dict) and "palette" in v: | |
| file_pals.append({"id": str(k), "palette": v["palette"], "names": v.get("names")}) | |
| elif isinstance(v, list): | |
| file_pals.append({"id": str(k), "palette": v, "names": None}) | |
| if file_pals: | |
| palettes = (palettes or []) + file_pals | |
| except Exception: | |
| pass | |
| # probe-seven: build A-color pool for per-image single-color highlighting | |
| probe_a_color_entries: List[Dict[str, str]] = [] | |
| if args.probe_seven: | |
| def _append_probe_color(hex_color: Any, name: Any = None) -> None: | |
| h = str(hex_color or "").strip().upper() | |
| if not h: | |
| return | |
| if not h.startswith("#"): | |
| h = "#" + h | |
| if len(h) != 7: | |
| return | |
| probe_a_color_entries.append({"hex": h, "name": str(name or "")}) | |
| # Prefer loaded palettes (if present), filter A-group | |
| if palettes: | |
| for p in palettes: | |
| if _palette_group_from_id(str(p.get("id", ""))) != "A": | |
| continue | |
| pal = p.get("palette") or [] | |
| names = p.get("names") if isinstance(p.get("names"), dict) else {} | |
| for hx in pal: | |
| n = None | |
| if isinstance(names, dict): | |
| hxs = str(hx) | |
| n = names.get(hxs) or names.get(hxs.upper()) or names.get(hxs.lower()) | |
| _append_probe_color(hx, n) | |
| # Fallback to canonical palette file in repo | |
| if not probe_a_color_entries: | |
| pf = Path("highlight/palette_preview/index.json") | |
| if pf.exists(): | |
| try: | |
| pdata = json.loads(pf.read_text(encoding="utf-8")) | |
| for pid, pv in pdata.items(): | |
| if _palette_group_from_id(str(pid)) != "A": | |
| continue | |
| if not isinstance(pv, dict): | |
| continue | |
| pal = pv.get("palette") or [] | |
| names = pv.get("names") if isinstance(pv.get("names"), dict) else {} | |
| for hx in pal: | |
| hxs = str(hx) | |
| n = names.get(hxs) or names.get(hxs.upper()) or names.get(hxs.lower()) | |
| _append_probe_color(hx, n) | |
| except Exception: | |
| pass | |
| # Last-resort: small A-like fallback pool | |
| if not probe_a_color_entries: | |
| fallback = [ | |
| ("#D3FAEE", "light_teal"), | |
| ("#83EDC4", "mid_teal"), | |
| ("#22D28E", "dark_teal"), | |
| ("#FEF4B8", "light_yellow"), | |
| ("#F7DA67", "mid_yellow"), | |
| ("#EFBC23", "dark_yellow"), | |
| ("#FFD1E7", "light_pink"), | |
| ("#FC88BC", "mid_pink"), | |
| ("#F74B98", "dark_pink"), | |
| ] | |
| for hx, n in fallback: | |
| _append_probe_color(hx, n) | |
| for i in range(1, args.count + 1): | |
| shape_cfg = _sample_table_shape_cfg() | |
| top_levels = int(shape_cfg["top_levels"]) | |
| left_levels = int(shape_cfg["left_levels"]) | |
| shape_profile = str(shape_cfg.get("profile", "fixed")) | |
| use_config_rows = bool(args.config_rows) and (rng.random() < float(args.config_rows_prob)) | |
| highlight_colors = _parse_palette(args.highlight_colors) | |
| palette_id = "default" | |
| palette_names: Optional[Dict[str, str]] = None | |
| if palettes: | |
| if use_config_rows: | |
| candidates = [p for p in palettes if _palette_group_from_id(p.get("id", "")) in ("B", "C")] | |
| picked = rng.choice(candidates) if candidates else rng.choice(palettes) | |
| elif args.probe_six or args.probe_seven: | |
| candidates = [p for p in palettes if _palette_group_from_id(p.get("id", "")) == "A"] | |
| picked = rng.choice(candidates) if candidates else rng.choice(palettes) | |
| else: | |
| picked = rng.choice(palettes) | |
| highlight_colors = picked["palette"] | |
| palette_id = picked["id"] | |
| palette_names = picked.get("names") | |
| palette_group = _palette_group_from_id(palette_id) | |
| palette_group_id = {"A": 1, "B": 2, "C": 3}.get(palette_group, 0) | |
| effective_highlight_strategy = str(args.highlight_strategy) | |
| effective_highlight_mode = str(args.highlight_mode) | |
| effective_use_all = bool(args.highlight_use_all_colors) | |
| if args.auto_abc: | |
| if palette_group == "A": | |
| effective_highlight_strategy = "by_column_rank" | |
| effective_use_all = True | |
| elif palette_group in ("B", "C"): | |
| effective_highlight_strategy = "random" | |
| effective_highlight_mode = "multi" | |
| underline_overall = float(args.underline_image_prob_overall) | |
| if underline_overall >= 0.0: | |
| if args.auto_abc: | |
| if palettes: | |
| total = len(palettes) | |
| count_a = sum(1 for p in palettes if _palette_group_from_id(p.get("id", "")) == "A") | |
| p_a = (count_a / total) if total > 0 else 0.0 | |
| else: | |
| p_a = 0.0 | |
| if palette_group == "A": | |
| apply_underline = False | |
| else: | |
| denom = max(1e-6, (1.0 - p_a)) | |
| prob_bc = min(1.0, underline_overall / denom) | |
| apply_underline = rng.random() < prob_bc | |
| else: | |
| apply_underline = rng.random() < underline_overall | |
| else: | |
| if args.auto_abc and palette_group == "A": | |
| apply_underline = False | |
| else: | |
| apply_underline = rng.random() < float(args.underline_image_prob) | |
| bold_overall = float(args.bold_image_prob_overall) | |
| if bold_overall >= 0.0: | |
| if args.auto_abc: | |
| if palettes: | |
| total = len(palettes) | |
| count_a = sum(1 for p in palettes if _palette_group_from_id(p.get("id", "")) == "A") | |
| p_a = (count_a / total) if total > 0 else 0.0 | |
| else: | |
| p_a = 0.0 | |
| if palette_group == "A": | |
| apply_bold = False | |
| else: | |
| denom = max(1e-6, (1.0 - p_a)) | |
| prob_bc = min(1.0, bold_overall / denom) | |
| apply_bold = rng.random() < prob_bc | |
| else: | |
| apply_bold = rng.random() < bold_overall | |
| else: | |
| if args.auto_abc and palette_group == "A": | |
| apply_bold = False | |
| else: | |
| apply_bold = rng.random() < float(args.bold_image_prob) | |
| apply_text_color = rng.random() < float(args.text_color_image_prob) | |
| marker_combo_pick = "independent" | |
| if str(args.marker_combo_mode) == "three-way": | |
| if marker_combo_schedule and (i - 1) < len(marker_combo_schedule): | |
| combo = marker_combo_schedule[i - 1] | |
| else: | |
| combo = rng.choices( | |
| ["underline_only", "bold_only", "both"], | |
| weights=marker_combo_weights, | |
| k=1, | |
| )[0] | |
| marker_combo_pick = str(combo) | |
| apply_underline = combo in ("underline_only", "both") | |
| apply_bold = combo in ("bold_only", "both") | |
| effective_text_color_delta_sign = bool(args.text_color_delta_sign) | |
| effective_text_color_best_per_col = bool(args.text_color_best_per_col) | |
| if args.auto_abc and palette_group == "A": | |
| effective_text_color_best_per_col = False | |
| if args.probe_six or args.probe_seven: | |
| def _build_probe_base_spec(shape_cfg_try: Dict[str, Any]) -> TableSpec: | |
| return build_paper_table( | |
| rng, | |
| group_count=int(shape_cfg_try["group_count"]), | |
| min_items=int(shape_cfg_try["min_items"]), | |
| max_items=int(shape_cfg_try["max_items"]), | |
| block_count=int(shape_cfg_try["block_count"]), | |
| min_metrics=int(shape_cfg_try["min_metrics"]), | |
| max_metrics=int(shape_cfg_try["max_metrics"]), | |
| mid_group_min=int(shape_cfg_try["mid_group_min"]), | |
| mid_group_max=int(shape_cfg_try["mid_group_max"]), | |
| section_count=int(shape_cfg_try["section_count"]), | |
| unique_numbers=bool(args.unique_numbers), | |
| top_levels=int(shape_cfg_try["top_levels"]), | |
| left_levels=int(shape_cfg_try["left_levels"]), | |
| merge_group_prob=args.merge_group_prob, | |
| citation_prob=args.citation_prob, | |
| missing_prob=args.missing_prob, | |
| dec_min=args.dec_min, | |
| dec_max=args.dec_max, | |
| highlight=False, | |
| highlight_mode="single", | |
| highlight_rate=0.0, | |
| highlight_count=0, | |
| highlight_colors=highlight_colors, | |
| highlight_use_all_colors=True, | |
| highlight_strategy="random", | |
| highlight_rank_k=int(args.highlight_rank_k), | |
| underline_rate=0.0, | |
| underline_best_per_col=False, | |
| underline_second_per_col=False, | |
| underline_wrong_per_col=False, | |
| bold_rate=0.0, | |
| bold_best_per_col=False, | |
| bold_wrong_per_col=False, | |
| text_color_delta_sign=False, | |
| text_color_best_per_col=False, | |
| text_color_pos_hex=str(args.text_color_pos_hex), | |
| text_color_neg_hex=str(args.text_color_neg_hex), | |
| text_color_best_hex=str(args.text_color_best_hex), | |
| arrow_rate=float(args.arrow_rate), | |
| arrow_up_ratio=float(args.arrow_up_ratio), | |
| data_arrows=bool(args.data_arrows), | |
| metric_arrow_prob=float(args.metric_arrow_prob), | |
| config_rows=bool(use_config_rows), | |
| config_flag_pool=( | |
| [x.strip() for x in str(args.config_flag_pool).split(",") if x.strip()] | |
| if args.config_flag_pool | |
| else list(CONFIG_FLAG_POOL) | |
| ), | |
| config_shade_best_row=bool(args.config_shade_best_row), | |
| ) | |
| base_spec, shape_cfg = _build_spec_with_readability_retries(shape_cfg, _build_probe_base_spec) | |
| top_levels = int(shape_cfg["top_levels"]) | |
| left_levels = int(shape_cfg["left_levels"]) | |
| shape_profile = str(shape_cfg.get("profile", "fixed")) | |
| probe_single_hl_hex = str(rng.choice(highlight_colors)).upper() if highlight_colors else "#E6F2FF" | |
| probe_single_hl_name = "" | |
| probe_palette_id = palette_id | |
| probe_palette_colors = list(highlight_colors) | |
| probe_palette_names = palette_names | |
| if args.probe_seven and probe_a_color_entries: | |
| picked_probe_color = rng.choice(probe_a_color_entries) | |
| probe_single_hl_hex = str(picked_probe_color.get("hex") or probe_single_hl_hex).upper() | |
| probe_single_hl_name = str(picked_probe_color.get("name") or "").strip() | |
| probe_palette_id = f"A_single_{probe_single_hl_hex.lstrip('#')}" | |
| probe_palette_colors = [probe_single_hl_hex] | |
| probe_palette_names = {probe_single_hl_hex: probe_single_hl_name} if probe_single_hl_name else None | |
| if args.probe_seven: | |
| variants = [ | |
| ("none", "neutral"), | |
| ("highlight", "congruent"), | |
| ("highlight", "incongruent"), | |
| ("underline", "congruent"), | |
| ("underline", "incongruent"), | |
| ("bold", "congruent"), | |
| ("bold", "incongruent"), | |
| ] | |
| else: | |
| variants = [ | |
| ("highlight", "congruent"), | |
| ("highlight", "neutral"), | |
| ("highlight", "incongruent"), | |
| ("underline", "congruent"), | |
| ("underline", "neutral"), | |
| ("underline", "incongruent"), | |
| ] | |
| for style_var, congruency in variants: | |
| spec = copy.deepcopy(base_spec) | |
| _clear_style_marks(spec.cells) | |
| if style_var == "highlight": | |
| if congruency == "congruent": | |
| _apply_highlight_best_per_col( | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| color_hex=probe_single_hl_hex, | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| elif congruency == "incongruent": | |
| _apply_highlight_by_column_wrong( | |
| rng, | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| colors=[probe_single_hl_hex], | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| # Exp1 probe setting: use a single A-palette color per image for all highlighted cells. | |
| if args.probe_seven: | |
| hl_cells = [c for c in spec.cells if c.extra.get("highlight") == "true"] | |
| if not hl_cells: | |
| data_cells = [c for c in spec.cells if c.kind == "data" and c.value is not None] | |
| if data_cells: | |
| picked = rng.choice(data_cells) | |
| picked.extra["highlight"] = "true" | |
| hl_cells = [picked] | |
| if hl_cells: | |
| for c in hl_cells: | |
| c.extra["highlight"] = "true" | |
| c.extra["highlight_color"] = probe_single_hl_hex | |
| c.extra.pop("highlight_color_name", None) | |
| elif style_var == "underline": | |
| if congruency == "congruent": | |
| _apply_underline_best_per_col( | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| elif congruency == "incongruent": | |
| _apply_underline_wrong_per_col( | |
| rng, | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| elif style_var == "bold": | |
| if congruency == "congruent": | |
| _apply_bold_best_per_col( | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| elif congruency == "incongruent": | |
| _apply_bold_wrong_per_col( | |
| rng, | |
| spec.cells, | |
| left_cols=spec.left_cols, | |
| data_cols_len=len(spec.data_cols), | |
| col_metrics=[str(ci.get("metric", "")) for ci in spec.data_cols], | |
| ) | |
| if style_var == "highlight" and congruency != "neutral": | |
| name_map = _build_palette_color_names(probe_palette_colors, explicit=probe_palette_names) | |
| for c in spec.cells: | |
| if c.extra.get("highlight") == "true": | |
| hex_color = (c.extra.get("highlight_color") or "").upper() | |
| if hex_color: | |
| c.extra["highlight_color_name"] = name_map.get(hex_color, "") | |
| if style_var == "none": | |
| code = "N" | |
| else: | |
| style_code = {"highlight": "H", "underline": "U", "bold": "B"}[style_var] | |
| cong_code = { | |
| "congruent": "C", | |
| "neutral": "N", | |
| "incongruent": "I", | |
| }[congruency] | |
| code = style_code + cong_code | |
| image_id = f"img_{i:05d}_{code}.png" | |
| image_path = out_dir / "images" / image_id | |
| render_table( | |
| spec, | |
| out_path=image_path, | |
| canvas_width=args.canvas_width, | |
| canvas_height=args.canvas_height, | |
| margins=margins, | |
| font_path=args.font_path, | |
| font_size=args.font_size, | |
| line_style=args.line_style, | |
| block_sep=args.block_sep, | |
| number_align=args.number_align, | |
| arrow_offset=(int(args.arrow_offset_x), int(args.arrow_offset_y)), | |
| arrow_scale=float(args.arrow_scale), | |
| delta_pm_scale=float(args.delta_pm_scale), | |
| crop_to_table=bool(args.crop_to_table), | |
| crop_pad=int(args.crop_pad), | |
| ) | |
| # GT | |
| gt_cells = [] | |
| for c in spec.cells: | |
| x1, y1, x2, y2 = c.bbox or (0, 0, 0, 0) | |
| gt_cells.append( | |
| { | |
| "row": c.row, | |
| "col": c.col, | |
| "row_span": c.row_span, | |
| "col_span": c.col_span, | |
| "text": c.text, | |
| "value": c.value, | |
| "bbox": [x1, y1, x2, y2], | |
| "kind": c.kind, | |
| "extra": c.extra, | |
| } | |
| ) | |
| gt = { | |
| "image_id": image_id, | |
| "n_rows": spec.n_rows, | |
| "n_cols": spec.n_cols, | |
| "header_rows": spec.header_rows, | |
| "top_levels": spec.top_levels, | |
| "left_levels": spec.left_levels, | |
| "left_cols": spec.left_cols, | |
| "highlight_palette": probe_palette_colors, | |
| "highlight_palette_id": probe_palette_id, | |
| "highlight_palette_group": "A", | |
| "highlight_palette_group_id": 1, | |
| "task_name": args.task_name, | |
| "task_variant": style_var, | |
| "task_variant_id": 0, | |
| "table_shape_profile": shape_profile, | |
| "cells": gt_cells, | |
| "config_id": cfg_info["config_id"], | |
| "config_code": cfg_info["config_code"], | |
| "config_json": cfg_info["config_json"], | |
| "probe_style": style_var, | |
| "probe_congruency": congruency, | |
| "probe_family": ("style_counterfactual_v2" if args.probe_seven else "style_counterfactual_v1"), | |
| } | |
| if write_jsonl and fgt: | |
| fgt.write(json.dumps(gt, ensure_ascii=False) + "\n") | |
| if write_json: | |
| gt_records.append(gt) | |
| # QA | |
| qa_items = generate_qa( | |
| spec, | |
| rng, | |
| include_cell_lookup=bool(args.qa_cell_lookup), | |
| cell_lookup_samples=int(args.qa_cell_lookup_samples), | |
| include_position=bool(args.qa_position), | |
| position_samples=int(args.qa_position_samples), | |
| include_col_extremes=bool(args.qa_col_extremes), | |
| col_extremes_k=int(args.qa_col_extremes_k), | |
| include_row_extremes=bool(args.qa_row_extremes), | |
| row_extremes_k=int(args.qa_row_extremes_k), | |
| include_col_argmax_item=bool(args.qa_col_argmax_item), | |
| include_col_argmax_coord=bool(args.qa_col_argmax_coord), | |
| include_topk=bool(args.qa_topk), | |
| topk_k=int(args.qa_topk_k), | |
| topk_cols=int(args.qa_topk_cols), | |
| include_kth=bool(args.qa_kth), | |
| kth_k=int(args.qa_kth_k), | |
| include_compare_rows=bool(args.qa_compare_rows), | |
| include_compare_cols=bool(args.qa_compare_cols), | |
| compare_samples=int(args.qa_compare_samples), | |
| include_col_best=bool(args.qa_col_best), | |
| include_group_col_best=bool(args.qa_group_col_best), | |
| include_highlight_neighbor=bool(args.qa_highlight_neighbor), | |
| highlight_neighbor_samples=int(args.qa_highlight_neighbor_samples), | |
| include_neighbors_idx=bool(args.qa_neighbors_idx), | |
| include_neighbors_noidx=bool(args.qa_neighbors_noidx), | |
| neighbor_samples=int(args.qa_neighbor_samples), | |
| include_color_values=bool(args.qa_color_values), | |
| palette_id=probe_palette_id, | |
| palette_colors=probe_palette_colors, | |
| palette_names=probe_palette_names, | |
| include_same_color=bool(args.qa_same_color), | |
| same_color_samples=int(args.qa_same_color_samples), | |
| include_same_color_noidx=bool(args.qa_same_color_noidx), | |
| same_color_noidx_samples=int(args.qa_same_color_noidx_samples), | |
| include_text_color_values=bool(args.qa_text_color_values), | |
| include_underline_values=bool(args.qa_underline), | |
| include_underline_per_col=bool(args.qa_underline_per_col), | |
| include_underline_yesno_idx=bool(args.qa_underline_yesno_idx), | |
| include_underline_yesno_noidx=bool(args.qa_underline_yesno_noidx), | |
| underline_yesno_samples=int(args.qa_underline_yesno_samples), | |
| include_bold_values=bool(args.qa_bold), | |
| include_bold_per_col=bool(args.qa_bold_per_col), | |
| include_bold_yesno_idx=bool(args.qa_bold_yesno_idx), | |
| include_bold_yesno_noidx=bool(args.qa_bold_yesno_noidx), | |
| bold_yesno_samples=int(args.qa_bold_yesno_samples), | |
| include_color_yesno_idx=bool(args.qa_color_yesno_idx), | |
| include_color_yesno_noidx=bool(args.qa_color_yesno_noidx), | |
| color_yesno_samples=int(args.qa_color_yesno_samples), | |
| include_missing_list=bool(args.qa_missing_list), | |
| include_missing_check=bool(args.qa_missing_check), | |
| missing_samples=int(args.qa_missing_samples), | |
| include_count_highlight=bool(args.qa_count_highlight), | |
| include_count_underline=bool(args.qa_count_underline), | |
| include_count_bold=bool(args.qa_count_bold), | |
| include_filter_threshold=bool(args.qa_filter_threshold), | |
| include_filter_highlight_threshold=bool(args.qa_filter_highlight_threshold), | |
| filter_samples=int(args.qa_filter_samples), | |
| include_agg_mean_group=bool(args.qa_agg_mean_group), | |
| include_delta_positive_list=bool(args.qa_delta_positive_list), | |
| include_argmax_overall=bool(args.qa_argmax_overall), | |
| include_multi_hop_style_agg=bool(args.qa_multi_hop_style_agg), | |
| include_multi_hop_exclude_agg=bool(args.qa_multi_hop_exclude_agg), | |
| multi_hop_samples=int(args.qa_multi_hop_samples), | |
| include_counterfactual=bool(args.qa_counterfactual), | |
| include_delta_values=bool(args.qa_delta_col), | |
| include_delta_best_row=bool(args.qa_delta_best_row), | |
| delta_samples=int(args.qa_delta_samples), | |
| qa_lib=qa_lib, | |
| ) | |
| for item in qa_items: | |
| item_out = { | |
| "image_id": image_id, | |
| "image_path": f"images/{image_id}", | |
| "qid": f"q{qid_counter:06d}", | |
| "task_id": item["task_id"], | |
| "qa_task_name": item.get("qa_task_name"), | |
| "qa_category": item.get("qa_category"), | |
| "qa_category_id": item.get("qa_category_id"), | |
| "table_shape_profile": shape_profile, | |
| "question": item["question"], | |
| "answer": item["answer"], | |
| "answer_type": item.get("answer_type", "string"), | |
| "scoring": item.get("scoring", {"type": "exact"}), | |
| "expected_format": item.get("expected_format", {"type": "string"}), | |
| "meta": item.get("meta", {}), | |
| "task_name": args.task_name, | |
| "task_variant": style_var, | |
| "task_variant_id": 0, | |
| "highlight_palette_id": probe_palette_id, | |
| "config_id": cfg_info["config_id"], | |
| "config_code": cfg_info["config_code"], | |
| "probe_style": style_var, | |
| "probe_congruency": congruency, | |
| "probe_family": ("style_counterfactual_v2" if args.probe_seven else "style_counterfactual_v1"), | |
| } | |
| fqa.write(json.dumps(item_out, ensure_ascii=False) + "\n") | |
| qid_counter += 1 | |
| # per-image ann | |
| ann = {"image_id": image_id, "image_path": f"images/{image_id}", "gt": gt, "qa": qa_items} | |
| (out_dir / "ann" / f"{Path(image_id).stem}.json").write_text( | |
| json.dumps(ann, ensure_ascii=False, indent=2), | |
| encoding="utf-8", | |
| ) | |
| continue | |
| congruency = str(args.congruency_mode) | |
| if congruency == "mix": | |
| congruency = rng.choice(["congruent", "neutral", "incongruent"]) | |
| effective_highlight = bool(args.highlight) | |
| underline_best = bool(args.underline_best_per_col) | |
| underline_second = bool(args.underline_second_per_col) | |
| underline_wrong = bool(args.underline_wrong_per_col) | |
| bold_best = bool(args.bold_best_per_col) | |
| bold_wrong = bool(args.bold_wrong_per_col) | |
| if str(args.marker_combo_mode) == "three-way" and str(args.marker_role_policy) == "paper": | |
| if marker_combo_pick == "underline_only": | |
| underline_best = True | |
| underline_second = False | |
| underline_wrong = False | |
| bold_best = False | |
| bold_wrong = False | |
| elif marker_combo_pick == "bold_only": | |
| underline_best = False | |
| underline_second = False | |
| underline_wrong = False | |
| bold_best = True | |
| bold_wrong = False | |
| elif marker_combo_pick == "both": | |
| underline_best = False | |
| underline_second = True | |
| underline_wrong = False | |
| bold_best = True | |
| bold_wrong = False | |
| if congruency != "none": | |
| if congruency == "neutral": | |
| effective_highlight = False | |
| apply_underline = False | |
| underline_best = False | |
| underline_second = False | |
| underline_wrong = False | |
| apply_bold = False | |
| bold_best = False | |
| bold_wrong = False | |
| elif congruency == "congruent": | |
| effective_highlight = True | |
| effective_highlight_strategy = "by_column_rank" | |
| if float(args.underline_image_prob) > 0: | |
| apply_underline = True | |
| underline_best = True | |
| underline_second = False | |
| underline_wrong = False | |
| if float(args.bold_image_prob) > 0: | |
| apply_bold = True | |
| bold_best = True | |
| bold_wrong = False | |
| elif congruency == "incongruent": | |
| effective_highlight = True | |
| effective_highlight_strategy = "by_column_wrong" | |
| if float(args.underline_image_prob) > 0: | |
| apply_underline = True | |
| underline_best = False | |
| underline_second = False | |
| underline_wrong = True | |
| if float(args.bold_image_prob) > 0: | |
| apply_bold = True | |
| bold_best = False | |
| bold_wrong = True | |
| if not apply_bold: | |
| bold_best = False | |
| bold_wrong = False | |
| if not apply_underline: | |
| underline_best = False | |
| underline_second = False | |
| underline_wrong = False | |
| def _build_main_spec(shape_cfg_try: Dict[str, Any]) -> TableSpec: | |
| return build_paper_table( | |
| rng, | |
| group_count=int(shape_cfg_try["group_count"]), | |
| min_items=int(shape_cfg_try["min_items"]), | |
| max_items=int(shape_cfg_try["max_items"]), | |
| block_count=int(shape_cfg_try["block_count"]), | |
| min_metrics=int(shape_cfg_try["min_metrics"]), | |
| max_metrics=int(shape_cfg_try["max_metrics"]), | |
| mid_group_min=int(shape_cfg_try["mid_group_min"]), | |
| mid_group_max=int(shape_cfg_try["mid_group_max"]), | |
| section_count=int(shape_cfg_try["section_count"]), | |
| unique_numbers=bool(args.unique_numbers), | |
| top_levels=int(shape_cfg_try["top_levels"]), | |
| left_levels=int(shape_cfg_try["left_levels"]), | |
| merge_group_prob=args.merge_group_prob, | |
| citation_prob=args.citation_prob, | |
| missing_prob=args.missing_prob, | |
| dec_min=args.dec_min, | |
| dec_max=args.dec_max, | |
| highlight=bool(effective_highlight), | |
| highlight_mode=effective_highlight_mode, | |
| highlight_rate=float(args.highlight_rate), | |
| highlight_count=int(args.highlight_count), | |
| highlight_colors=highlight_colors, | |
| highlight_use_all_colors=effective_use_all, | |
| highlight_strategy=effective_highlight_strategy, | |
| highlight_rank_k=int(args.highlight_rank_k), | |
| underline_rate=float(args.underline_rate) if apply_underline else 0.0, | |
| underline_best_per_col=bool(underline_best) if apply_underline else False, | |
| underline_second_per_col=bool(underline_second) if apply_underline else False, | |
| underline_wrong_per_col=bool(underline_wrong) if apply_underline else False, | |
| bold_rate=float(args.bold_rate) if apply_bold else 0.0, | |
| bold_best_per_col=bool(bold_best) if apply_bold else False, | |
| bold_wrong_per_col=bool(bold_wrong) if apply_bold else False, | |
| text_color_delta_sign=effective_text_color_delta_sign if apply_text_color else False, | |
| text_color_best_per_col=effective_text_color_best_per_col if apply_text_color else False, | |
| text_color_pos_hex=str(args.text_color_pos_hex), | |
| text_color_neg_hex=str(args.text_color_neg_hex), | |
| text_color_best_hex=str(args.text_color_best_hex), | |
| arrow_rate=float(args.arrow_rate), | |
| arrow_up_ratio=float(args.arrow_up_ratio), | |
| data_arrows=bool(args.data_arrows), | |
| metric_arrow_prob=float(args.metric_arrow_prob), | |
| config_rows=bool(use_config_rows), | |
| config_flag_pool=( | |
| [x.strip() for x in str(args.config_flag_pool).split(",") if x.strip()] | |
| if args.config_flag_pool | |
| else list(CONFIG_FLAG_POOL) | |
| ), | |
| config_shade_best_row=bool(args.config_shade_best_row), | |
| ) | |
| spec, shape_cfg = _build_spec_with_readability_retries(shape_cfg, _build_main_spec) | |
| top_levels = int(shape_cfg["top_levels"]) | |
| left_levels = int(shape_cfg["left_levels"]) | |
| shape_profile = str(shape_cfg.get("profile", "fixed")) | |
| if args.highlight: | |
| name_map = _build_palette_color_names(highlight_colors, explicit=palette_names) | |
| for c in spec.cells: | |
| if c.extra.get("highlight") == "true": | |
| hex_color = (c.extra.get("highlight_color") or "").upper() | |
| if hex_color: | |
| c.extra["highlight_color_name"] = name_map.get(hex_color, "") | |
| image_id = f"img_{i:05d}.png" | |
| image_path = out_dir / "images" / image_id | |
| render_table( | |
| spec, | |
| out_path=image_path, | |
| canvas_width=args.canvas_width, | |
| canvas_height=args.canvas_height, | |
| margins=margins, | |
| font_path=args.font_path, | |
| font_size=args.font_size, | |
| line_style=args.line_style, | |
| block_sep=args.block_sep, | |
| number_align=args.number_align, | |
| arrow_offset=(int(args.arrow_offset_x), int(args.arrow_offset_y)), | |
| arrow_scale=float(args.arrow_scale), | |
| delta_pm_scale=float(args.delta_pm_scale), | |
| crop_to_table=bool(args.crop_to_table), | |
| crop_pad=int(args.crop_pad), | |
| ) | |
| # GT | |
| gt_cells = [] | |
| for c in spec.cells: | |
| x1, y1, x2, y2 = c.bbox or (0, 0, 0, 0) | |
| gt_cells.append( | |
| { | |
| "row": c.row, | |
| "col": c.col, | |
| "row_span": c.row_span, | |
| "col_span": c.col_span, | |
| "text": c.text, | |
| "value": c.value, | |
| "bbox": [x1, y1, x2, y2], | |
| "kind": c.kind, | |
| "extra": c.extra, | |
| } | |
| ) | |
| gt = { | |
| "image_id": image_id, | |
| "n_rows": spec.n_rows, | |
| "n_cols": spec.n_cols, | |
| "header_rows": spec.header_rows, | |
| "top_levels": spec.top_levels, | |
| "left_levels": spec.left_levels, | |
| "left_cols": spec.left_cols, | |
| "highlight_palette": highlight_colors, | |
| "highlight_palette_id": palette_id, | |
| "highlight_palette_group": palette_group, | |
| "highlight_palette_group_id": palette_group_id, | |
| "congruency": congruency, | |
| "task_name": args.task_name, | |
| "task_variant": palette_group, | |
| "task_variant_id": palette_group_id, | |
| "table_shape_profile": shape_profile, | |
| "cells": gt_cells, | |
| "config_id": cfg_info["config_id"], | |
| "config_code": cfg_info["config_code"], | |
| "config_json": cfg_info["config_json"], | |
| } | |
| if write_jsonl and fgt: | |
| fgt.write(json.dumps(gt, ensure_ascii=False) + "\n") | |
| if write_json: | |
| gt_records.append(gt) | |
| # QA | |
| qa_items = generate_qa( | |
| spec, | |
| rng, | |
| include_cell_lookup=bool(args.qa_cell_lookup), | |
| cell_lookup_samples=int(args.qa_cell_lookup_samples), | |
| include_position=bool(args.qa_position), | |
| position_samples=int(args.qa_position_samples), | |
| include_col_extremes=bool(args.qa_col_extremes), | |
| col_extremes_k=int(args.qa_col_extremes_k), | |
| include_row_extremes=bool(args.qa_row_extremes), | |
| row_extremes_k=int(args.qa_row_extremes_k), | |
| include_col_argmax_item=bool(args.qa_col_argmax_item), | |
| include_col_argmax_coord=bool(args.qa_col_argmax_coord), | |
| include_topk=bool(args.qa_topk), | |
| topk_k=int(args.qa_topk_k), | |
| topk_cols=int(args.qa_topk_cols), | |
| include_kth=bool(args.qa_kth), | |
| kth_k=int(args.qa_kth_k), | |
| include_compare_rows=bool(args.qa_compare_rows), | |
| include_compare_cols=bool(args.qa_compare_cols), | |
| compare_samples=int(args.qa_compare_samples), | |
| include_col_best=bool(args.qa_col_best), | |
| include_group_col_best=bool(args.qa_group_col_best), | |
| include_highlight_neighbor=bool(args.qa_highlight_neighbor), | |
| highlight_neighbor_samples=int(args.qa_highlight_neighbor_samples), | |
| include_neighbors_idx=bool(args.qa_neighbors_idx), | |
| include_neighbors_noidx=bool(args.qa_neighbors_noidx), | |
| neighbor_samples=int(args.qa_neighbor_samples), | |
| include_color_values=bool(args.qa_color_values), | |
| palette_id=palette_id, | |
| palette_colors=highlight_colors, | |
| palette_names=palette_names, | |
| include_same_color=bool(args.qa_same_color), | |
| same_color_samples=int(args.qa_same_color_samples), | |
| include_same_color_noidx=bool(args.qa_same_color_noidx), | |
| same_color_noidx_samples=int(args.qa_same_color_noidx_samples), | |
| include_text_color_values=bool(args.qa_text_color_values), | |
| include_underline_values=bool(args.qa_underline), | |
| include_underline_per_col=bool(args.qa_underline_per_col), | |
| include_underline_yesno_idx=bool(args.qa_underline_yesno_idx), | |
| include_underline_yesno_noidx=bool(args.qa_underline_yesno_noidx), | |
| underline_yesno_samples=int(args.qa_underline_yesno_samples), | |
| include_bold_values=bool(args.qa_bold), | |
| include_bold_per_col=bool(args.qa_bold_per_col), | |
| include_bold_yesno_idx=bool(args.qa_bold_yesno_idx), | |
| include_bold_yesno_noidx=bool(args.qa_bold_yesno_noidx), | |
| bold_yesno_samples=int(args.qa_bold_yesno_samples), | |
| include_color_yesno_idx=bool(args.qa_color_yesno_idx), | |
| include_color_yesno_noidx=bool(args.qa_color_yesno_noidx), | |
| color_yesno_samples=int(args.qa_color_yesno_samples), | |
| include_missing_list=bool(args.qa_missing_list), | |
| include_missing_check=bool(args.qa_missing_check), | |
| missing_samples=int(args.qa_missing_samples), | |
| include_count_highlight=bool(args.qa_count_highlight), | |
| include_count_underline=bool(args.qa_count_underline), | |
| include_count_bold=bool(args.qa_count_bold), | |
| include_filter_threshold=bool(args.qa_filter_threshold), | |
| include_filter_highlight_threshold=bool(args.qa_filter_highlight_threshold), | |
| filter_samples=int(args.qa_filter_samples), | |
| include_agg_mean_group=bool(args.qa_agg_mean_group), | |
| include_delta_positive_list=bool(args.qa_delta_positive_list), | |
| include_argmax_overall=bool(args.qa_argmax_overall), | |
| include_multi_hop_style_agg=bool(args.qa_multi_hop_style_agg), | |
| include_multi_hop_exclude_agg=bool(args.qa_multi_hop_exclude_agg), | |
| multi_hop_samples=int(args.qa_multi_hop_samples), | |
| include_counterfactual=bool(args.qa_counterfactual), | |
| include_delta_values=bool(args.qa_delta_col), | |
| include_delta_best_row=bool(args.qa_delta_best_row), | |
| delta_samples=int(args.qa_delta_samples), | |
| qa_lib=qa_lib, | |
| ) | |
| for item in qa_items: | |
| item_out = { | |
| "image_id": image_id, | |
| "image_path": f"images/{image_id}", | |
| "qid": f"q{qid_counter:06d}", | |
| "task_id": item["task_id"], | |
| "qa_task_name": item.get("qa_task_name"), | |
| "qa_category": item.get("qa_category"), | |
| "qa_category_id": item.get("qa_category_id"), | |
| "table_shape_profile": shape_profile, | |
| "question": item["question"], | |
| "answer": item["answer"], | |
| "answer_type": item.get("answer_type", "string"), | |
| "scoring": item.get("scoring", {"type": "exact"}), | |
| "expected_format": item.get("expected_format", {"type": "string"}), | |
| "meta": item.get("meta", {}), | |
| "task_name": args.task_name, | |
| "task_variant": palette_group, | |
| "task_variant_id": palette_group_id, | |
| "highlight_palette_id": palette_id, | |
| "congruency": congruency, | |
| "config_id": cfg_info["config_id"], | |
| "config_code": cfg_info["config_code"], | |
| } | |
| fqa.write(json.dumps(item_out, ensure_ascii=False) + "\n") | |
| qid_counter += 1 | |
| # per-image ann | |
| ann = { | |
| "image_id": image_id, | |
| "image_path": f"images/{image_id}", | |
| "gt": gt, | |
| "qa": qa_items, | |
| } | |
| (out_dir / "ann" / f"{Path(image_id).stem}.json").write_text( | |
| json.dumps(ann, ensure_ascii=False, indent=2), | |
| encoding="utf-8", | |
| ) | |
| if write_json: | |
| gt_json_path.write_text(json.dumps(gt_records, ensure_ascii=False, indent=2), encoding="utf-8") | |
| finally: | |
| if fgt: | |
| fgt.close() | |
| _write_clean_qa(qa_full_path, qa_path) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |