wenjieshu's picture
Add files using upload-large-folder tool
b8ea052 verified
Raw History Blame Contribute Delete
6.82 kB
"""Check-scoped OCR execution helpers for typed PVR tool calls."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Callable
from PIL import Image
def parse_json_list(value: Any) -> list[Any]:
if isinstance(value, list):
return value
try:
parsed = json.loads(str(value or "[]"))
except Exception:
return []
return parsed if isinstance(parsed, list) else []
def rect_from_value(value: Any) -> list[float] | None:
if isinstance(value, dict):
value = value.get("bbox") or value.get("rect") or (
[value.get("x0"), value.get("y0"), value.get("x1"), value.get("y1")]
if {"x0", "y0", "x1", "y1"} <= set(value)
else None
)
if not isinstance(value, (list, tuple)) or len(value) != 4:
return None
try:
return [float(item) for item in value]
except Exception:
return None
def resolve_region_rects(
contract: dict[str, Any],
region_ids: list[str],
image_size: tuple[int, int],
region_overrides: dict[str, Any] | None = None,
) -> tuple[list[dict[str, Any]], list[str]]:
"""Resolve contract geometry first, then typed detector proposals."""
width, height = image_size
zones = contract.get("zones") if isinstance(contract.get("zones"), dict) else {}
planned: dict[str, Any] = {}
for check in contract.get("atomic_checks", []):
params = check.get("params") if isinstance(check, dict) else {}
for region in (params or {}).get("planned_regions", []) or []:
if isinstance(region, dict) and (region.get("region_id") or region.get("id")):
planned[str(region.get("region_id") or region.get("id"))] = region
resolved, unresolved = [], []
for region_id in region_ids:
raw = zones.get(region_id, planned.get(region_id))
rect = rect_from_value(raw)
if rect is None:
rect = rect_from_value((region_overrides or {}).get(region_id))
if rect is None:
unresolved.append(region_id)
continue
if max(abs(value) for value in rect) <= 1.0:
rect = [rect[0] * width, rect[1] * height, rect[2] * width, rect[3] * height]
x0, y0, x1, y1 = rect
rect = [max(0.0, min(width, x0)), max(0.0, min(height, y0)), max(0.0, min(width, x1)), max(0.0, min(height, y1))]
if rect[2] <= rect[0] or rect[3] <= rect[1]:
unresolved.append(region_id)
continue
resolved.append({"region_id": region_id, "bbox_xyxy": rect})
return resolved, unresolved
def ocr_layout_region_ids(contract: dict[str, Any]) -> set[str]:
"""Return regions whose geometry is intentionally discovered by OCR.
These regions cannot be required as an OCR input crop: doing so creates a
circular dependency (OCR needs the label box before OCR may run). A dense
full-frame OCR pass is the objective region proposer for this method.
"""
result: set[str] = set()
for check in contract.get("atomic_checks", []):
params = check.get("params") if isinstance(check, dict) else {}
for region in (params or {}).get("planned_regions", []) or []:
if not isinstance(region, dict) or str(region.get("proposal_method") or "") != "ocr_layout":
continue
region_id = str(region.get("region_id") or region.get("id") or "")
if region_id:
result.add(region_id)
return result
def normalize_rapidocr_result(result: Any, *, dx: float = 0.0, dy: float = 0.0, min_confidence: float = 0.0) -> list[dict[str, Any]]:
raw_items = result[0] if isinstance(result, tuple) else result
rows = []
for raw in raw_items or []:
if not isinstance(raw, (list, tuple)) or len(raw) < 3:
continue
polygon, value, confidence = raw[0], str(raw[1]), float(raw[2])
if confidence < min_confidence:
continue
points = []
for point in polygon or []:
if isinstance(point, (list, tuple)) and len(point) >= 2:
points.append([float(point[0]) + dx, float(point[1]) + dy])
if not points:
continue
xs, ys = [point[0] for point in points], [point[1] for point in points]
rows.append(
{
"text": value,
"confidence": confidence,
"box": points,
"bbox_xyxy": [min(xs), min(ys), max(xs), max(ys)],
}
)
return rows
def execute_ocr_call(
call: dict[str, str],
*,
backend: Callable[[Image.Image], Any],
min_confidence: float = 0.1,
region_overrides: dict[str, Any] | None = None,
) -> dict[str, Any]:
role = call.get("image_role", "pred")
if role not in {"input", "pred"}:
return {"status": "unsupported", "reason": f"unsupported_image_role:{role}", "items": []}
image_path = Path(call.get(role, ""))
if not image_path.is_file():
return {"status": "error", "reason": "image_not_found", "image_path": str(image_path), "items": []}
contract_path = Path(call.get("contract_path", ""))
contract = json.loads(contract_path.read_text(encoding="utf-8")) if contract_path.is_file() else {}
region_ids = [str(item) for item in parse_json_list(call.get("region_ids")) if str(item)]
with Image.open(image_path).convert("RGB") as image:
regions, unresolved = resolve_region_rects(contract, region_ids, image.size, region_overrides)
layout_regions = ocr_layout_region_ids(contract)
unresolved_non_ocr = [region_id for region_id in unresolved if region_id not in layout_regions]
if region_ids and unresolved_non_ocr:
return {
"status": "insufficient",
"reason": "unresolved_ocr_regions",
"region_ids": region_ids,
"unresolved_region_ids": unresolved_non_ocr,
"resolved_regions": regions,
"items": [],
}
scopes = regions or [{"region_id": "full_image", "bbox_xyxy": [0.0, 0.0, float(image.width), float(image.height)]}]
items: list[dict[str, Any]] = []
for scope in scopes:
x0, y0, x1, y1 = scope["bbox_xyxy"]
crop = image.crop((int(round(x0)), int(round(y0)), int(round(x1)), int(round(y1))))
for item in normalize_rapidocr_result(backend(crop), dx=x0, dy=y0, min_confidence=min_confidence):
items.append({**item, "region_id": scope["region_id"]})
return {
"status": "ok" if items else "no_text",
"reason": "ocr_layout_full_frame_scan" if unresolved and not regions else "ocr_completed",
"region_ids": region_ids,
"resolved_regions": scopes,
"items": items,
}