Rachel7's picture
Deploy af82b43: HVAC Blueprint Analyzer (T3 live deployment)
45a6327 verified
Raw History Blame Contribute Delete
2.81 kB
"""PDF page rendering: overview images and native-resolution region crops.
Coordinate systems:
- pt: PDF points (72/inch), the page's native space.
- overview px: pixels of the downscaled full-page image the model sees first.
- score px: 300-DPI full-page pixels (matches ground-truth CSVs).
"""
from dataclasses import dataclass
import fitz
from . import config
# fitz rounds pixmap dimensions up from the transformed clip rect, which can
# overshoot the target by ~1px. Render to a few px under the hard API cap so the
# result is always <= IMAGE_LONG_EDGE.
_RENDER_MARGIN_PX = 8
_RENDER_TARGET = config.IMAGE_LONG_EDGE - _RENDER_MARGIN_PX
@dataclass
class RegionRender:
region_id: str
png: bytes
rect_pt: fitz.Rect # region location on the page
zoom: float # px per pt in this render
width: int
height: int
def local_to_score(self, x: float, y: float, w: float, h: float) -> tuple[float, float, float, float]:
"""Map a bbox in this render's pixels to 300-DPI page pixels."""
s = config.SCORE_DPI / 72.0
return (
(self.rect_pt.x0 + x / self.zoom) * s,
(self.rect_pt.y0 + y / self.zoom) * s,
(w / self.zoom) * s,
(h / self.zoom) * s,
)
class PageRenderer:
def __init__(self, pdf_path: str, page_num: int):
"""page_num is 1-based."""
self.doc = fitz.open(pdf_path)
if not 1 <= page_num <= len(self.doc):
raise ValueError(f"page {page_num} out of range (1-{len(self.doc)})")
self.page = self.doc[page_num - 1]
self.page_num = page_num
self.rect = self.page.rect
self._counter = 0
def render_overview(self) -> RegionRender:
zoom = _RENDER_TARGET / max(self.rect.width, self.rect.height)
pix = self.page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
return RegionRender("overview", pix.tobytes("png"), fitz.Rect(self.rect), zoom, pix.width, pix.height)
def render_region(self, overview: RegionRender, x: float, y: float, w: float, h: float) -> RegionRender | None:
"""Render a region given in overview pixels at the highest useful resolution."""
oz = overview.zoom
rect = fitz.Rect(x / oz, y / oz, (x + w) / oz, (y + h) / oz) & self.rect
if rect.is_empty or rect.width < 1 or rect.height < 1:
return None
zoom = min(
_RENDER_TARGET / rect.width,
_RENDER_TARGET / rect.height,
config.MAX_CROP_DPI / 72.0,
)
pix = self.page.get_pixmap(matrix=fitz.Matrix(zoom, zoom), clip=rect)
self._counter += 1
return RegionRender(f"R{self._counter}", pix.tobytes("png"), rect, zoom, pix.width, pix.height)