|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import Any, Dict, List, Optional, Tuple |
| 5 | + |
| 6 | + |
| 7 | +@dataclass(frozen=True) |
| 8 | +class HeuristicConfig: |
| 9 | + # Text overflow heuristic |
| 10 | + avg_char_width_em: float = 0.6 # ~0.5-0.6 is typical for Latin fonts |
| 11 | + line_height_em: float = 1.2 |
| 12 | + overflow_warn_ratio: float = 1.0 # >1 means text likely doesn't fit |
| 13 | + overflow_info_ratio: float = 0.9 # >0.9 means tight fit |
| 14 | + |
| 15 | + # Page density heuristic |
| 16 | + objects_per_page_warn: int = 80 |
| 17 | + |
| 18 | + |
| 19 | +def _as_float(v: Any, default: float = 0.0) -> float: |
| 20 | + try: |
| 21 | + return float(v) |
| 22 | + except Exception: |
| 23 | + return float(default) |
| 24 | + |
| 25 | + |
| 26 | +def _as_int(v: Any, default: int = 0) -> int: |
| 27 | + try: |
| 28 | + return int(v) |
| 29 | + except Exception: |
| 30 | + return int(default) |
| 31 | + |
| 32 | + |
| 33 | +def _iter_pages(layout_json: Dict[str, Any]): |
| 34 | + for page in layout_json.get("pages", []) or []: |
| 35 | + if isinstance(page, dict): |
| 36 | + yield page |
| 37 | + |
| 38 | + |
| 39 | +def _iter_objects(page: Dict[str, Any]): |
| 40 | + for obj in page.get("objects", []) or []: |
| 41 | + if isinstance(obj, dict): |
| 42 | + yield obj |
| 43 | + |
| 44 | + |
| 45 | +def estimate_text_overflow_ratio( |
| 46 | + *, |
| 47 | + text: str, |
| 48 | + bbox_w: float, |
| 49 | + bbox_h: float, |
| 50 | + font_size: float, |
| 51 | + cfg: HeuristicConfig, |
| 52 | +) -> Optional[float]: |
| 53 | + """ |
| 54 | + Estimate overflow risk as (needed_height / available_height). |
| 55 | + Returns None if not enough inputs. |
| 56 | + """ |
| 57 | + |
| 58 | + if not text or bbox_w <= 0 or bbox_h <= 0 or font_size <= 0: |
| 59 | + return None |
| 60 | + |
| 61 | + # chars per line (rough) |
| 62 | + char_w = max(0.1, cfg.avg_char_width_em * font_size) |
| 63 | + cpl = max(1.0, bbox_w / char_w) |
| 64 | + |
| 65 | + # count "visual" characters (ignore excessive whitespace) |
| 66 | + compact = " ".join(text.split()) |
| 67 | + n = len(compact) |
| 68 | + if n <= 0: |
| 69 | + return None |
| 70 | + |
| 71 | + # line count (simple) |
| 72 | + lines = max(1.0, (n / cpl)) |
| 73 | + line_h = max(0.1, cfg.line_height_em * font_size) |
| 74 | + needed_h = lines * line_h |
| 75 | + |
| 76 | + return needed_h / bbox_h |
| 77 | + |
| 78 | + |
| 79 | +def run_heuristic_checks( |
| 80 | + layout_json: Dict[str, Any], |
| 81 | + *, |
| 82 | + config: Optional[HeuristicConfig] = None, |
| 83 | +) -> Dict[str, Any]: |
| 84 | + """ |
| 85 | + Warn-only checks: |
| 86 | + - text_overflow_risk: estimates if text likely doesn't fit its bbox |
| 87 | + - page_density: objects-per-page beyond threshold |
| 88 | +
|
| 89 | + Output is designed to be stable/deterministic given identical inputs. |
| 90 | + """ |
| 91 | + |
| 92 | + cfg = config or HeuristicConfig() |
| 93 | + |
| 94 | + warnings: List[Dict[str, Any]] = [] |
| 95 | + infos: List[Dict[str, Any]] = [] |
| 96 | + |
| 97 | + pages_summary: List[Dict[str, Any]] = [] |
| 98 | + for page in _iter_pages(layout_json): |
| 99 | + pn = _as_int(page.get("pageNumber"), 0) |
| 100 | + objs = list(_iter_objects(page)) |
| 101 | + pages_summary.append({"pageNumber": pn, "objectCount": len(objs)}) |
| 102 | + |
| 103 | + if len(objs) >= cfg.objects_per_page_warn: |
| 104 | + warnings.append( |
| 105 | + { |
| 106 | + "id": "page.density", |
| 107 | + "page": pn, |
| 108 | + "message": f"High object count on page {pn}: {len(objs)} objects", |
| 109 | + "objectCount": len(objs), |
| 110 | + } |
| 111 | + ) |
| 112 | + |
| 113 | + for obj in objs: |
| 114 | + if str(obj.get("type") or "") != "text": |
| 115 | + continue |
| 116 | + text = str(obj.get("content") or "") |
| 117 | + bbox = obj.get("bbox") or {} |
| 118 | + ratio = estimate_text_overflow_ratio( |
| 119 | + text=text, |
| 120 | + bbox_w=_as_float(bbox.get("w"), 0.0), |
| 121 | + bbox_h=_as_float(bbox.get("h"), 0.0), |
| 122 | + font_size=_as_float(obj.get("fontSize"), 0.0), |
| 123 | + cfg=cfg, |
| 124 | + ) |
| 125 | + if ratio is None: |
| 126 | + continue |
| 127 | + |
| 128 | + entry = { |
| 129 | + "id": "text.overflow_risk", |
| 130 | + "page": pn, |
| 131 | + "objectId": obj.get("id"), |
| 132 | + "ratio": round(float(ratio), 4), |
| 133 | + "message": "Estimated text overflow risk (needed_height / bbox_height)", |
| 134 | + } |
| 135 | + if ratio > cfg.overflow_warn_ratio: |
| 136 | + warnings.append(entry) |
| 137 | + elif ratio > cfg.overflow_info_ratio: |
| 138 | + infos.append(entry) |
| 139 | + |
| 140 | + return { |
| 141 | + "passed": True, # warn-only module |
| 142 | + "warnings": warnings, |
| 143 | + "infos": infos, |
| 144 | + "summary": { |
| 145 | + "pages": pages_summary, |
| 146 | + "warnCount": len(warnings), |
| 147 | + "infoCount": len(infos), |
| 148 | + "config": { |
| 149 | + "avg_char_width_em": cfg.avg_char_width_em, |
| 150 | + "line_height_em": cfg.line_height_em, |
| 151 | + "overflow_warn_ratio": cfg.overflow_warn_ratio, |
| 152 | + "overflow_info_ratio": cfg.overflow_info_ratio, |
| 153 | + "objects_per_page_warn": cfg.objects_per_page_warn, |
| 154 | + }, |
| 155 | + }, |
| 156 | + } |
| 157 | + |
0 commit comments