Rachel7's picture
Deploy af82b43: HVAC Blueprint Analyzer (T3 live deployment)
45a6327 verified
Raw History Blame Contribute Delete
2.91 kB
import json
import tempfile
from pathlib import Path
from typing import Any
import fitz
from analyzer.markup import render_markup
SCORE_DPI = 300
class PdfError(Exception):
pass
def inspect_pdf(path: Path) -> list[dict[str, Any]]:
try:
with fitz.open(path) as document:
if not document.is_pdf or document.page_count < 1:
raise PdfError("Uploaded file is not a PDF")
pages = []
for index, page in enumerate(document):
rect = page.rect
pages.append({
"num": index + 1,
"floor_guess": None,
"width_px": round(rect.width * SCORE_DPI / 72),
"height_px": round(rect.height * SCORE_DPI / 72),
})
return pages
except PdfError:
raise
except Exception as exc:
raise PdfError("Uploaded file is not a valid PDF") from exc
def render_page(source_pdf: Path, cache_dir: Path, page_number: int, dpi: int) -> Path:
output = cache_dir / f"page_{page_number}_{dpi}.png"
if output.is_file():
return output
try:
with fitz.open(source_pdf) as document:
if page_number < 1 or page_number > document.page_count:
raise PdfError("Page not found")
page = document[page_number - 1]
pixmap = page.get_pixmap(matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False)
png = pixmap.tobytes("png")
except PdfError:
raise
except Exception as exc:
raise PdfError("Could not render page") from exc
cache_dir.mkdir(parents=True, exist_ok=True)
temporary = output.with_suffix(".png.tmp")
temporary.write_bytes(png)
temporary.replace(output)
return output
def render_reviewed_markup(
raw_result: dict[str, Any],
detections: list[dict[str, Any]],
categories: list[str] | None,
dpi: int,
) -> bytes:
merged = dict(raw_result)
merged["detections"] = [
{
"tag": detection["tag"],
"category": detection["category"],
"confidence": detection["confidence"],
"notes": detection["notes"],
"x": detection["x"],
"y": detection["y"],
"w": detection["w"],
"h": detection["h"],
}
for detection in detections
if detection["action"] == "keep"
]
with tempfile.TemporaryDirectory() as directory:
run_path = Path(directory) / "run.json"
output_path = Path(directory) / "markup.png"
with run_path.open("w", encoding="utf-8") as handle:
json.dump(merged, handle, ensure_ascii=False)
render_markup(str(run_path), str(output_path), categories=categories, dpi=dpi)
return output_path.read_bytes()