hvac_fable / python_files /analyze_blueprint_v2.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
60.8 kB
""" analyze_blueprint.py β€” HVAC Blueprint Analyzer Usage: python analyze_blueprint.py <pdf> [--dpi 300] [--out-dir ./output] [--psm 11] [--min-conf 40] [--step schedule|classify|ocr-one] [--tile] Run with --step <name> to stop and confirm after each phase. """ from __future__ import annotations import argparse import itertools import logging import re import sys from io import BytesIO from pathlib import Path from typing import NamedTuple import base64 import csv import io import os import cv2 import fitz import numpy as np import pdfplumber import pytesseract from PIL import Image, ImageDraw, ImageFont # ── Load .env from project root ────────────────────────────────────────────── try: from dotenv import load_dotenv load_dotenv(Path(__file__).parent.parent / ".env") except ImportError: pass # python-dotenv not installed β€” use system env vars # ── Windows Tesseract path ──────────────────────────────────────────────────── _TESS_WIN = r"C:\Program Files\Tesseract-OCR\tesseract.exe" if Path(_TESS_WIN).exists(): pytesseract.pytesseract.tesseract_cmd = _TESS_WIN # ── Inject sibling package ──────────────────────────────────────────────────── sys.path.insert(0, str(Path(__file__).parent)) from hvac_pipeline.extract_schedule_robust import ( RowParse, extract_from_pdf_tables, extract_from_pdf_text, normalize_tag as _normalize_tag_schedule, ) # ── Regex patterns (inlined from read_mechanical_plansvs1.4.py) ─────────────── _TAG_STRICT = re.compile(r"\bAC[-\s]?[A-U]\b", re.IGNORECASE) _TAG_LOOSE = re.compile(r"\bA\s*C\s*[-]?\s*([A-U])\b", re.IGNORECASE) _INT_PAT = re.compile(r"\b\d{1,2}\b") _FLOOR_PAT = re.compile(r"(LEVEL|FLOOR|ROOF|BASEMENT)\s*(\d+)?", re.IGNORECASE) # ── Annotation color palette ────────────────────────────────────────────────── _PALETTE = [ (220, 50, 50), (50, 150, 220), (50, 200, 100), (220, 150, 50), (150, 50, 220), (50, 200, 200), (220, 220, 50), (200, 100, 150), (100, 200, 50), (50, 100, 200), (200, 50, 150), (100, 150, 50), ] # ── Data types ──────────────────────────────────────────────────────────────── class TagHit(NamedTuple): tag: str x: int y: int w: int h: int conf: float fuzzy: bool FloorResults = dict[str, dict[str, list[TagHit]]] # ───────────────────────────────────────────────────────────────────────────── # Helpers inlined from read_mechanical_plansvs1.4.py # ───────────────────────────────────────────────────────────────────────────── def _extract_explicit_title(text: str) -> str | None: if not text: return None lines = [ln.strip() for ln in text.split("\n")] for i, line in enumerate(lines): if re.search(r"DRAWING\s*TITLE", line, re.IGNORECASE): remainder = re.sub(r"DRAWING\s*TITLE\s*[:\-]?\s*", "", line, flags=re.IGNORECASE) if remainder: return remainder.strip() for nxt in lines[i + 1 : i + 6]: if nxt: return nxt.strip() return None _TITLE_KEYWORDS = re.compile( r"\b(MECHANICAL|HVAC|AIR\s+RISER|RISER|DIAGRAM|PLAN|SCHEDULE|DETAIL|SECTION|BULKHEAD|CELLAR|ROOF)\b", re.IGNORECASE, ) def _extract_heuristic_title(text: str, max_lines: int = 20) -> str | None: """ Drawing titles are almost entirely uppercase (>60% ratio). Scans up to max_lines lines; None = search entire text. When scanning the full OCR output, returns the HIGHEST-ratio matching line (not the first), so diagram labels ('BULKHEAD') lose to the actual title ('MECHANICAL AIR RISERS' at 0.90). Also requires at least one title keyword and no junk characters. """ if not text: return None lines = [ln.strip() for ln in text.split("\n") if ln.strip()] search = lines if max_lines is None else lines[:max_lines] candidates: list[tuple[float, str]] = [] for line in search: # Strip non-ASCII junk chars (common OCR artifacts) before evaluating clean = re.sub(r"[^\x00-\x7F]+", " ", line).strip() clean = re.sub(r"\s{2,}", " ", clean) if len(clean) < 8 or len(clean) > 120: continue upper_ratio = sum(c.isupper() for c in clean) / max(len(clean), 1) if upper_ratio > 0.6 and _TITLE_KEYWORDS.search(clean): line = clean # use the cleaned version # Strongly prefer lines that start with MECHANICAL bonus = 0.2 if line.upper().startswith("MECHANICAL") else 0.0 candidates.append((upper_ratio + bonus, line)) if not candidates: return None # Return highest-scoring line, stripped of leading punctuation/symbols best = max(candidates, key=lambda x: x[0])[1] return re.sub(r"^[^A-Z]+", "", best).strip() def _ocr_page_title(pdf_path: Path, page_0idx: int) -> str | None: """Render page at 150 DPI and search ALL OCR lines for the drawing title.""" doc = fitz.open(pdf_path) pix = doc.load_page(page_0idx).get_pixmap(matrix=fitz.Matrix(150/72, 150/72), alpha=False) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) ocr_txt = pytesseract.image_to_string(img, config="--oem 3 --psm 6") # Try explicit DRAWING TITLE label first title = _extract_explicit_title(ocr_txt) if title and _TITLE_KEYWORDS.search(title): return title # Full-page scan picking the highest-ratio matching line return _extract_heuristic_title(ocr_txt, max_lines=None) _JUNK_TITLE = re.compile(r"^(DOB\s*[#:\-]|N/A|TBD|NONE|\-+|\s*)$", re.IGNORECASE) def _is_valid_title(title: str | None) -> bool: """Return False for placeholder/form-field titles that aren't real drawing titles.""" if not title: return False if _JUNK_TITLE.match(title.strip()): return False return bool(_TITLE_KEYWORDS.search(title)) def _extract_page_title(text: str) -> str | None: title = _extract_explicit_title(text) or _extract_heuristic_title(text) return title if _is_valid_title(title) else None def _classify_page_context(title: str | None, text: str) -> str: t = (title or "").upper() x = text.upper() blob = f"{t}\n{x}" if "INDOOR UNIT SCHEDULE" in blob or "SCHEDULE" in t: return "schedule" # Details, DOB forms, and riser diagrams are not floor plans if "DETAIL" in t or "SECTION" in t or "RISER" in t or "DIAGRAM" in t: return "detail" if "NOTE" in t and "PLAN" not in t: return "notes" if "PLAN" in t or "FLOOR" in t or "LEVEL" in t or "ROOF" in t or "CELLAR" in t or "BULKHEAD" in t: return "plan" return "other" def _normalize_tag(raw: str) -> str | None: """Return 'AC-X' form or None.""" raw = re.sub(r"[^A-Z0-9\-]", "", raw.upper()) m = _TAG_STRICT.search(raw) if m: tag = m.group(0).upper().replace(" ", "-") if "-" not in tag: tag = f"AC-{tag[-1]}" return tag if re.match(r"^AC-[A-U]$", tag) else None return None def _parse_schedule_lines_robust(lines: list[str], page_num: int) -> list[dict]: rows: list[dict] = [] seen: set = set() for line in lines: upper = line.upper() tag = None m = _TAG_STRICT.search(upper) if m: tag = _normalize_tag(m.group(0)) if tag is None: m2 = _TAG_LOOSE.search(upper) if m2: tag = f"AC-{m2.group(1).upper()}" if tag is None: m3 = re.search(r"\bAC[-\s]?([A-U])\w*\b", upper) if m3: tag = f"AC-{m3.group(1).upper()}" if not tag: continue nums = [int(v) for v in _INT_PAT.findall(line)] qty = next((n for n in nums if 0 <= n <= 50), None) if "CEILING" in upper and "DUCT" in upper: utype = "Ceiling Concealed Ducted Unit" elif "WALL" in upper and "MOUNT" in upper: utype = "Wall Mounted" else: utype = "" key = (tag, str(qty), utype) if key in seen: continue seen.add(key) rows.append({"page_num": page_num, "tag": tag, "qty_required": qty, "unit_type": utype}) return rows # ───────────────────────────────────────────────────────────────────────────── # Step 1 β€” Schedule extraction # ───────────────────────────────────────────────────────────────────────────── # ───────────────────────────────────────────────────────────────────────────── # Gemini vision fallback for schedule extraction # ───────────────────────────────────────────────────────────────────────────── def _extract_schedule_via_gemini(pil_img: Image.Image) -> list[RowParse]: """ Send the schedule page image to Gemini and ask it to return the INDOOR UNIT SCHEDULE table as CSV. Returns [] if API key not set. """ api_key = os.environ.get("GEMINI_API_KEY", "") if not api_key: print(" [INFO] GEMINI_API_KEY not set β€” skipping vision fallback.") print(" Set it with: $env:GEMINI_API_KEY = 'your-key-here'") return [] try: from google import genai as google_genai from google.genai import types as genai_types except ImportError: print(" [INFO] google-genai not installed β€” run: pip install google-genai") return [] client = google_genai.Client(api_key=api_key) buf = io.BytesIO() pil_img.save(buf, format="PNG") img_bytes = buf.getvalue() prompt = ( "Look at this HVAC mechanical blueprint page. " "Find the table titled 'INDOOR UNIT SCHEDULE' or 'VARIABLE REFRIGERANT VOLUME – INDOOR UNIT SCHEDULE'. " "Extract every row from that table only (not the outdoor unit schedule or any other table). " "Return the data as CSV with exactly these columns: tag,qty,unit_type\n" "Rules:\n" "- tag must be in the form AC-A through AC-U\n" "- qty must be an integer (the QUANTITY column value)\n" "- unit_type should be the TYPE column value (e.g. CEILING CONCEALED DUCTED UNIT, WALL MOUNTED)\n" "- Include all rows, even those with qty=0\n" "- Output ONLY the CSV rows, no headers, no explanations." ) response = client.models.generate_content( model="gemini-2.5-flash", contents=[ prompt, genai_types.Part.from_bytes(data=img_bytes, mime_type="image/png"), ], config=genai_types.GenerateContentConfig(max_output_tokens=2048, temperature=0.0), ) rows: list[RowParse] = [] for line in response.text.strip().splitlines(): line = line.strip().strip(",") if not line: continue parts = [p.strip() for p in line.split(",")] if len(parts) < 2: continue tag = _normalize_tag(parts[0]) if not tag: continue try: qty = int(parts[1]) except ValueError: qty = None utype = parts[2] if len(parts) > 2 else "" rows.append(RowParse( tag=tag, qty_required=qty, unit_type=utype, confidence=0.95, source="gemini_vision", raw_text=line, )) return rows _INDOOR_HEADER = re.compile(r"INDOOR\s+UNIT\s+SCHEDULE", re.IGNORECASE) _OTHER_SCHEDULE = re.compile(r"(OUTDOOR|CONDENSING|EQUIPMENT|ELECTRICAL)\s+(UNIT\s+)?SCHEDULE", re.IGNORECASE) def _extract_indoor_unit_section(lines: list[str]) -> list[str]: """ Return only the lines that belong to the INDOOR UNIT SCHEDULE table. Starts at the header line and stops when another schedule header appears or when a line that looks like end-of-table notes begins. If no header is found, return all lines (best-effort). """ start = None for i, line in enumerate(lines): if _INDOOR_HEADER.search(line): start = i break if start is None: return lines # header not found β€” return everything, parser will filter result = [] for line in lines[start:]: # Stop at a different schedule section if result and _OTHER_SCHEDULE.search(line): break # Stop at indoor unit notes block if result and re.match(r"INDOOR\s+UNIT\s+NOTES", line, re.IGNORECASE): break result.append(line) return result def _schedule_cache_path(pdf_path: Path, out_dir: Path) -> Path: return out_dir / f"{pdf_path.stem}_schedule_cache.json" def _load_schedule_cache(cache_path: Path) -> dict[str, dict] | None: if not cache_path.exists(): return None import json data = json.loads(cache_path.read_text(encoding="utf-8")) print(f" Loaded schedule from cache: {cache_path}") print(f" (Delete that file or use --refresh-schedule to re-extract)") return data def _save_schedule_cache(schedule: dict[str, dict], cache_path: Path) -> None: import json cache_path.write_text(json.dumps(schedule, indent=2), encoding="utf-8") print(f" Schedule cached to: {cache_path}") def extract_schedule(pdf_path: Path, dpi: int, schedule_page: int | None = None, out_dir: Path | None = None, refresh: bool = False) -> dict[str, dict]: """ Returns {tag: {"unit_type": str, "qty": int|None}} for all found tags. Tries three tiers: pdf tables β†’ pdf text β†’ OCR β†’ Gemini vision. Results are cached to <out_dir>/<pdf_stem>_schedule_cache.json so the API is only called once. Use --refresh-schedule to force re-extraction. """ # ── Cache check ─────────────────────────────────────────────────────────── if out_dir is not None: cache_path = _schedule_cache_path(pdf_path, out_dir) if not refresh: cached = _load_schedule_cache(cache_path) if cached is not None: return cached schedule_pages: list[int] = [] if schedule_page is not None: schedule_pages = [schedule_page] print(f" Using specified schedule page: {schedule_page}") else: # Search only first 15 + last 15 pages (schedules are rarely in the middle) with pdfplumber.open(pdf_path) as pdf: total = len(pdf.pages) candidates_idx = sorted(set( list(range(1, min(16, total + 1))) + list(range(max(1, total - 14), total + 1)) )) print(f" Scanning {len(candidates_idx)} pages (of {total} total) for schedule…") for i in candidates_idx: print(f" page {i}/{total}…", end="\r", flush=True) txt = pdf.pages[i - 1].extract_text() or "" title = _extract_page_title(txt) ptype = _classify_page_context(title, txt) if ptype == "schedule": schedule_pages.append(i) print() # clear the \r line if not schedule_pages: print(" [WARNING] No schedule page found in first/last 15 pages.") print(" Tip: run with --schedule-page N to specify the exact page number.") return {} candidates: list[RowParse] = [] for pnum in schedule_pages: logging.info(f" Trying schedule on page {pnum}…") t1 = extract_from_pdf_tables(pdf_path, pnum) t2 = extract_from_pdf_text(pdf_path, pnum) candidates.extend(t1) candidates.extend(t2) # Tier 3: OCR fallback when native text yields nothing if not t1 and not t2: logging.info(f" Native extraction empty β€” falling back to OCR on page {pnum}") # 250 DPI β€” frombytes() bypasses PIL bomb check so large sheets are fine ocr_dpi = 250 doc = fitz.open(pdf_path) page_obj = doc.load_page(pnum - 1) mat = fitz.Matrix(ocr_dpi / 72.0, ocr_dpi / 72.0) pix = page_obj.get_pixmap(matrix=mat, alpha=False) pil_img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) # Convert to grayscale β€” NO adaptive threshold for schedules. # Blueprint tables are already high-contrast; thresholding destroys # thin characters and causes "AC-A" to read as "sk" / "face". np_img = np.array(pil_img) gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY) ocr_img = Image.fromarray(gray) # PSM 4 = single column variable-size text (best for table rows) # PSM 6 = uniform block (backup) raw_lines: list[str] = [] for psm in (4, 6): txt = pytesseract.image_to_string(ocr_img, config=f"--oem 3 --psm {psm}") raw_lines.extend(ln.strip() for ln in txt.splitlines() if ln.strip()) # Filter to the INDOOR UNIT SCHEDULE section only. # Find the header line then stop at the next all-caps schedule header. lines = _extract_indoor_unit_section(raw_lines) logging.info(f" OCR produced {len(raw_lines)} lines; {len(lines)} in indoor unit section") print(f"\n --- Indoor unit section lines ({len(lines)}) ---") for ln in lines: print(f" {repr(ln)}") print(f" --- end ---\n") for row in _parse_schedule_lines_robust(lines, pnum): candidates.append( RowParse( tag=row["tag"], qty_required=row["qty_required"], unit_type=row["unit_type"], confidence=0.6, source="ocr_fallback", raw_text="", ) ) # Count unique tags found so far from this page ocr_tag_count = len({c.tag for c in candidates}) if ocr_tag_count < 5: print(f" OCR found only {ocr_tag_count} tag(s) β€” trying Gemini vision fallback…") vision_rows = _extract_schedule_via_gemini(pil_img) if vision_rows: print(f" Gemini returned {len(vision_rows)} rows.") candidates.extend(vision_rows) # Deduplicate: keep highest-confidence parse per tag by_tag: dict[str, RowParse] = {} for row in candidates: if row.tag not in by_tag or row.confidence > by_tag[row.tag].confidence: by_tag[row.tag] = row result = { tag: {"unit_type": row.unit_type, "qty": row.qty_required} for tag, row in by_tag.items() if row.qty_required is not None or row.unit_type } # Save to cache so Gemini is never called again for this PDF if out_dir is not None and result: _save_schedule_cache(result, _schedule_cache_path(pdf_path, out_dir)) return result # ───────────────────────────────────────────────────────────────────────────── # Step 2 β€” Page classification # ───────────────────────────────────────────────────────────────────────────── def _floor_name_from_title(title: str | None) -> str | None: """ Extract a human-readable floor label from a page title. 'MECHANICAL 4TH FLOOR PLAN' -> '4th Floor' 'MECHANICAL TYPICAL 4TH THRU 5TH FLOOR PLAN' -> 'Typical 4th-5th Floor' 'MECHANICAL ROOF PLAN' -> 'Roof' 'MECHANICAL CELLAR PLAN' -> 'Cellar' 'MECHANICAL BULKHEAD PLAN' -> 'Bulkhead' """ if not title: return None t = title.upper() t = re.sub(r"^MECHANICAL\s*", "", t).strip() t = re.sub(r"\s*FLOOR\s*PLAN\s*$", "", t).strip() t = re.sub(r"\s*PLAN\s*$", "", t).strip() if not t: return None # Normalize ordinals: 1ST -> 1st, 2ND -> 2nd, etc. t = re.sub(r"\b(\d+)(ST|ND|RD|TH)\b", lambda m: m.group(1) + m.group(2).lower(), t) t = re.sub(r"\s+THRU\s+", "-", t) return t.title() def classify_pages(pdf_path: Path) -> list[dict]: """ Returns list of {page_num, page_type, floor_name, title} for every page. """ manifest = [] with pdfplumber.open(pdf_path) as pdf: total = len(pdf.pages) for i, page in enumerate(pdf.pages, start=1): print(f" classifying page {i}/{total}…", end="\r", flush=True) txt = page.extract_text() or "" title = _extract_page_title(txt) # If pdfplumber found no usable drawing title (common on flattened pages # where only the title block vectors are readable), fall back to OCR and # search the entire page image for the drawing title. if title is None: title = _ocr_page_title(pdf_path, i - 1) ptype = _classify_page_context(title, txt) floor_name = _floor_name_from_title(title) if not floor_name: m = _FLOOR_PAT.search(txt) floor_name = m.group(0).title() if m else f"Page {i}" if i == total: print() # clear the \r line manifest.append({ "page_num": i, "page_type": ptype, "floor_name": floor_name, "title": title or "(no title)", }) return manifest # ───────────────────────────────────────────────────────────────────────────── # Step 3 β€” Gemini vision floor detection + YOLO label export # ───────────────────────────────────────────────────────────────────────────── # All 21 possible tag classes in order β€” used for YOLO class IDs _ALL_TAGS = [f"AC-{chr(65+i)}" for i in range(21)] _TAG_TO_CLASS = {tag: i for i, tag in enumerate(_ALL_TAGS)} _DATASET_ROOT = Path(__file__).parent.parent / "dataset" def _detection_cache_path(out_dir: Path, page_num: int, floor_name: str) -> Path: safe = re.sub(r"[^\w]", "_", floor_name) return out_dir / f"floor_{page_num:03d}_{safe}_detections.json" def _scale_image_for_api(img: Image.Image, max_px: int = 2048) -> tuple[Image.Image, float]: """Scale down to max_px on the longest side. Returns (scaled_img, scale_factor).""" w, h = img.size longest = max(w, h) if longest <= max_px: return img, 1.0 factor = max_px / longest new_w, new_h = int(w * factor), int(h * factor) return img.resize((new_w, new_h), Image.LANCZOS), factor def _make_tiles(img: Image.Image, tile_size: int = 3000, overlap: int = 300, skip_right_frac: float = 0.15) -> list[tuple[int, int, Image.Image]]: """ Divide image into overlapping tiles, skipping the right title-block margin. Returns list of (x0, y0, tile_img). """ W, H = img.size max_x = int(W * (1.0 - skip_right_frac)) # exclude title block step = tile_size - overlap tiles = [] y = 0 while y < H: x = 0 while x < max_x: x1 = min(x + tile_size, W) y1 = min(y + tile_size, H) tile = img.crop((x, y, x1, y1)) tiles.append((x, y, tile)) if x1 >= max_x: break x += step if y + tile_size >= H: break y += step return tiles def _gemini_call_tile( client, genai_types, tile: Image.Image, x0: int, y0: int, img_w: int, img_h: int, known_tags: list[str], page_num: int, max_px: int = 2048, ) -> list[TagHit]: """Send one tile to Gemini and return TagHits in full-image pixel coordinates.""" tile_w, tile_h = tile.size scaled, _ = _scale_image_for_api(tile, max_px) buf = io.BytesIO() scaled.save(buf, format="PNG") tag_list = ", ".join(sorted(known_tags)) if known_tags else "(no tags provided)" prompt = ( "You are analyzing a SECTION (tile) of a mechanical HVAC floor plan blueprint.\n\n" "Your job: find HVAC indoor unit symbols labeled with one of the equipment-schedule tags\n" "listed at the bottom of this prompt. The exact tag format varies per project β€” match\n" "the tag text EXACTLY as it appears in the schedule list (could be 'AC-D', 'FC-1',\n" "'IDU-A', etc.).\n\n" "A valid indoor unit symbol has ALL THREE of these properties:\n\n" "1. SHAPE β€” a rectangular box symbol. Aspect ratio and size vary by unit type:\n" " * Ceiling-concealed-ducted units: longer/wider rectangles\n" " * Wall-mounted units: smaller rectangles, often near a wall\n" " * Cassette units: square-ish\n" " The rectangle usually has INTERNAL DETAIL: parallel hatching lines (representing\n" " coil fins), fan symbols, or coil patterns β€” NOT an empty box.\n\n" "2. CONNECTIONS β€” visible ductwork rectangles (labeled with duct sizes like '12X6',\n" " '16X8') or refrigerant piping lines enter and exit the unit symbol.\n\n" "3. LABEL β€” an explicit text tag printed adjacent to the unit (above, below, beside,\n" " or rotated 90Β°). The label must MATCH EXACTLY one of the schedule tags listed\n" " below (full tag text, including any prefix).\n\n" "REJECT β€” these are NOT indoor units:\n" "* Symbols where the label is just a single letter inside a circle (e.g. 'D 4B',\n" " 'F 2A', 'TX 8B') β€” those are diffuser/drain/transfer designators\n" "* Ductwork sizing labels (numbers like '16X8'), 'VD', 'SG-N', 'EG-N', 'RG-N',\n" " 'CD-N', 'FD', 'BC-N', 'CAR', 'COD', 'PL-N', 'LD-N', 'EUN-N'\n" "* Schedule tables, legends, title blocks, notes\n" "* Thermostat symbols (small circles with 'T')\n" "* A bare rectangle without internal detail, without a matching label, or without piping\n\n" f"SCHEDULE TAGS for this blueprint:\n{tag_list}\n\n" "Return ONLY valid JSON, no markdown:\n" '{"detections": [{"tag": "<exact tag from list>", "ymin": N, "xmin": N, "ymax": N, "xmax": N}, ...]}\n\n' "The bounding box should enclose BOTH the unit rectangle AND its text label.\n" "Coordinates are integers 0-1000 normalized to THIS TILE's size.\n" 'Return {"detections": []} if no valid units in this tile.' ) try: response = client.models.generate_content( model="gemini-2.5-flash", contents=[prompt, genai_types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png")], config=genai_types.GenerateContentConfig(max_output_tokens=4096, temperature=0.0), ) raw = response.text.strip() raw = re.sub(r"^```[a-z]*\n?", "", raw, flags=re.MULTILINE) raw = re.sub(r"```$", "", raw.strip()) except Exception as e: logging.warning(f" Tile ({x0},{y0}) Gemini error: {e}") return [] import json as _json try: dets = _json.loads(raw).get("detections", []) except _json.JSONDecodeError: dets = [] hits = [] for det in dets: tag = _normalize_tag(det.get("tag", "")) if not tag or (known_tags and tag not in known_tags): continue # Convert 0-1000 normalized tile coords β†’ full-image pixels xn, yn = det["xmin"] / 1000, det["ymin"] / 1000 xn2, yn2 = det["xmax"] / 1000, det["ymax"] / 1000 x = x0 + int(xn * tile_w) y = y0 + int(yn * tile_h) w = max(int((xn2 - xn) * tile_w), 20) h = max(int((yn2 - yn) * tile_h), 20) hits.append(TagHit(tag=tag, x=x, y=y, w=w, h=h, conf=0.9, fuzzy=False)) return hits def gemini_detect_floor_page( pdf_path: Path, page_0idx: int, dpi: int, known_tags: set[str], out_dir: Path, page_num: int, floor_name: str, save_yolo: bool = True, tile_size: int = 3000, ) -> tuple[Image.Image, list[TagHit]]: """ Render the floor plan at DPI, tile it, send each tile to Gemini to detect unit tags, merge and deduplicate, cache results, and optionally save YOLO labels. Returns (full-res color_img, list[TagHit]). """ import json cache_path = _detection_cache_path(out_dir, page_num, floor_name) # ── Render full-res image (needed for annotation regardless of cache) ───── color_img = _render_page(pdf_path, page_0idx, dpi) img_w, img_h = color_img.size # ── Load from cache if available ────────────────────────────────────────── if cache_path.exists(): data = json.loads(cache_path.read_text(encoding="utf-8")) hits = [TagHit(**d) for d in data["hits"]] print(f"cached ({len(hits)} detections)") return color_img, hits # ── Call Gemini ─────────────────────────────────────────────────────────── api_key = os.environ.get("GEMINI_API_KEY", "") if not api_key: print("no GEMINI_API_KEY β€” skipping") return color_img, [] try: from google import genai as google_genai from google.genai import types as genai_types except ImportError: print("google-genai not installed β€” run: pip install google-genai") return color_img, [] client = google_genai.Client(api_key=api_key) # ── Tile the image and query each tile ──────────────────────────────────── tiles = _make_tiles(color_img, tile_size=tile_size, overlap=tile_size // 10) all_hits: list[TagHit] = [] known_list = sorted(known_tags) if known_tags else [] for idx, (x0, y0, tile_img) in enumerate(tiles): print(f" tile {idx+1}/{len(tiles)} ({x0},{y0})…", end=" ", flush=True) tile_hits = _gemini_call_tile( client, genai_types, tile_img, x0, y0, img_w, img_h, known_list, page_num, ) print(f"{len(tile_hits)} hit(s)") all_hits.extend(tile_hits) # ── Deduplicate across tiles (IOU > 0.3 same tag β†’ keep one) ───────────── hits = _deduplicate_hits(all_hits, iou_threshold=0.3) # ── Verify each hit + refine its box (drops false positives) ───────────── if hits: print(f" verifying {len(hits)} hit(s)…", end=" ", flush=True) verified = [] rejected = 0 for h in hits: r = _refine_hit_box(client, genai_types, color_img, h) if r is None: rejected += 1 else: verified.append(r) hits = verified print(f"{len(hits)} kept, {rejected} rejected") # ── Cache results ───────────────────────────────────────────────────────── cache_path.write_text( json.dumps({"hits": [h._asdict() for h in hits], "img_w": img_w, "img_h": img_h}, indent=2), encoding="utf-8", ) # ── Save YOLO labels ────────────────────────────────────────────────────── if save_yolo and hits: _save_yolo_labels(pdf_path, page_num, color_img, hits, img_w, img_h) return color_img, hits def _save_yolo_labels( pdf_path: Path, page_num: int, color_img: Image.Image, hits: list[TagHit], img_w: int, img_h: int, ) -> None: """ Save image + YOLO label file into dataset/images/train and dataset/labels/train. Also updates dataset.yaml to list all 21 tag classes. """ import json stem = f"{pdf_path.stem}_p{page_num:03d}" split = "train" # new Gemini labels go to train by default img_dir = _DATASET_ROOT / "images" / split lbl_dir = _DATASET_ROOT / "labels" / split img_dir.mkdir(parents=True, exist_ok=True) lbl_dir.mkdir(parents=True, exist_ok=True) # Save image as JPG (matching existing dataset convention) img_path = img_dir / f"{stem}.jpg" color_img.save(img_path, format="JPEG", quality=92) # Write YOLO label file: class_id x_center y_center width height (all 0-1) label_lines = [] for hit in hits: cls = _TAG_TO_CLASS.get(hit.tag, 0) xc = (hit.x + hit.w / 2) / img_w yc = (hit.y + hit.h / 2) / img_h w_n = hit.w / img_w h_n = hit.h / img_h label_lines.append(f"{cls} {xc:.6f} {yc:.6f} {w_n:.6f} {h_n:.6f}") lbl_path = lbl_dir / f"{stem}.txt" lbl_path.write_text("\n".join(label_lines), encoding="utf-8") # Update dataset.yaml to use multi-class names yaml_path = _DATASET_ROOT / "dataset.yaml" names_block = "\n".join(f" {i}: {tag}" for i, tag in enumerate(_ALL_TAGS)) yaml_path.write_text( f"path: {_DATASET_ROOT}\ntrain: images/train\nval: images/val\nnames:\n{names_block}\n", encoding="utf-8", ) logging.debug(f" YOLO labels saved: {lbl_path} ({len(hits)} boxes)") # ───────────────────────────────────────────────────────────────────────────── # Step 3b β€” High-DPI OCR per floor page (kept as fallback) # ───────────────────────────────────────────────────────────────────────────── def _refine_hit_box( client, genai_types, color_img: Image.Image, hit: TagHit, search_radius: int = 900, ) -> TagHit | None: """ Re-query Gemini on a small crop centered on hit to VERIFY the unit actually exists there and get tighter bounds. Returns None if the unit can't be verified (false positive from the initial pass). """ W, H = color_img.size cx = hit.x + hit.w // 2 cy = hit.y + hit.h // 2 x0 = max(0, cx - search_radius) y0 = max(0, cy - search_radius) x1 = min(W, cx + search_radius) y1 = min(H, cy + search_radius) crop = color_img.crop((x0, y0, x1, y1)) crop_w, crop_h = crop.size buf = io.BytesIO() crop.save(buf, format="PNG") prompt = ( "This is a zoomed-in section of an HVAC mechanical blueprint.\n\n" f"VERIFY: is there an HVAC indoor unit labeled exactly '{hit.tag}' (matching this\n" "exact text from the equipment schedule) visible in this image?\n\n" "A VALID match requires ALL of:\n" " - A rectangular unit body (size/shape varies by unit type β€” ducted units are\n" " longer rectangles, wall-mounted are smaller, cassettes are square-ish).\n" " Internal detail is typical: parallel hatching, fan symbols, or coil patterns.\n" " - Ductwork or refrigerant piping connecting to the rectangle.\n" f" - The exact text label '{hit.tag}' printed adjacent to that rectangle\n" " (label may be rotated 90Β°).\n\n" "REJECT (return verified=false) if:\n" f" - The text '{hit.tag}' is not visible anywhere in this image\n" f" - The text '{hit.tag}' is visible but there's no rectangular unit body next to it\n" " - The only nearby symbol is a circle with a single letter (e.g. 'D 4B') β€” not a unit\n" " - The only nearby labels are ductwork-related (16X8, VD, SG-N, EG-N, RG-N, CD-N,\n" " FD, CAR, COD, PL-N, LD-N, BC-N)\n\n" "If verified: return tight bounds covering BOTH the unit rectangle AND its label.\n" "If NOT verified: return all zeros.\n\n" "Return ONLY JSON:\n" '{"verified": true_or_false, "ymin": N, "xmin": N, "ymax": N, "xmax": N}\n\n' "Coordinates 0-1000 normalized to this crop's size." ) try: response = client.models.generate_content( model="gemini-2.5-flash", contents=[prompt, genai_types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png")], config=genai_types.GenerateContentConfig(max_output_tokens=512, temperature=0.0), ) raw = response.text.strip() raw = re.sub(r"```[a-zA-Z]*\n?", "", raw) raw = raw.replace("```", "").strip() # Parse verified flag verified = None m_verified = re.search(r'verified"?\s*[:=]\s*(true|false)', raw, re.IGNORECASE) if m_verified: verified = m_verified.group(1).lower() == "true" # Parse coords (any order) coords = {} for key in ("ymin", "xmin", "ymax", "xmax"): m = re.search(rf'{key}"?\s*[:=]\s*(\d+)', raw) if m: coords[key] = int(m.group(1)) # Verification logic if verified is False: # Explicitly rejected by Gemini return None if not coords or len(coords) != 4: # Couldn't parse β€” keep original (conservative) return hit # All-zero box also means rejection if all(v == 0 for v in coords.values()): return None if coords["xmax"] <= coords["xmin"] or coords["ymax"] <= coords["ymin"]: return hit xn, yn = coords["xmin"] / 1000, coords["ymin"] / 1000 xn2, yn2 = coords["xmax"] / 1000, coords["ymax"] / 1000 new_x = x0 + int(xn * crop_w) new_y = y0 + int(yn * crop_h) new_w = max(int((xn2 - xn) * crop_w), 20) new_h = max(int((yn2 - yn) * crop_h), 20) return TagHit(tag=hit.tag, x=new_x, y=new_y, w=new_w, h=new_h, conf=hit.conf, fuzzy=hit.fuzzy) except Exception as e: logging.warning(f" Verify error for {hit.tag} at ({hit.x},{hit.y}): {e}") return hit def _iou(a: TagHit, b: TagHit) -> float: ax1, ay1, ax2, ay2 = a.x, a.y, a.x + a.w, a.y + a.h bx1, by1, bx2, by2 = b.x, b.y, b.x + b.w, b.y + b.h ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) inter = max(0, ix2 - ix1) * max(0, iy2 - iy1) if inter == 0: return 0.0 union = (a.w * a.h) + (b.w * b.h) - inter return inter / union if union > 0 else 0.0 def _deduplicate_hits(hits: list[TagHit], iou_threshold: float = 0.5) -> list[TagHit]: kept: list[TagHit] = [] for hit in sorted(hits, key=lambda h: -h.conf): if any(h.tag == hit.tag and _iou(h, hit) > iou_threshold for h in kept): continue kept.append(hit) return kept def _render_page(pdf_path: Path, page_0idx: int, dpi: int) -> Image.Image: doc = fitz.open(pdf_path) page = doc.load_page(page_0idx) mat = fitz.Matrix(dpi / 72.0, dpi / 72.0) pix = page.get_pixmap(matrix=mat, alpha=False) # Disable PIL decompression-bomb check β€” blueprint sheets are legitimately huge Image.MAX_IMAGE_PIXELS = None return Image.frombytes("RGB", [pix.width, pix.height], pix.samples) def _ocr_image(pil_img: Image.Image, psm: int, min_conf: float) -> "pd.DataFrame": # type: ignore[name-defined] import pandas as pd # local import keeps top-level clean if pandas missing gray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2GRAY) thresh = cv2.adaptiveThreshold( gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2 ) data = pytesseract.image_to_data( Image.fromarray(thresh), output_type=pytesseract.Output.DATAFRAME, config=f"--oem 3 --psm {psm}", ) data = data[(data["text"].notna()) & (data["conf"] >= min_conf)].copy() data["text"] = data["text"].str.strip() data = data[data["text"] != ""].reset_index(drop=True) return data def _extract_hits_from_data(data, known_tags: set[str], psm_used: int) -> list[TagHit]: import pandas as pd hits: list[TagHit] = [] # ── Single-token pass ────────────────────────────────────────────────── _SINGLE = re.compile(r"^AC[-\s]?[A-U]$", re.IGNORECASE) for _, row in data.iterrows(): raw = str(row["text"]).strip() if _SINGLE.match(raw): tag = _normalize_tag(raw) if tag and (not known_tags or tag in known_tags): hits.append(TagHit(tag, int(row["left"]), int(row["top"]), int(row["width"]), int(row["height"]), float(row["conf"]), False)) # ── Multi-token merge (handles "AC -A", "AC" + "A" split) ───────────── sort_cols = [c for c in ("block_num", "par_num", "line_num", "word_num") if c in data.columns] if sort_cols and len(data) > 1: ds = data.sort_values(sort_cols).reset_index(drop=True) for i in range(len(ds) - 1): w1 = str(ds.iloc[i]["text"]).upper() w2 = str(ds.iloc[i + 1]["text"]).upper() merged = re.sub(r"[\s\-]", "", w1 + w2) m = re.match(r"^AC([A-U])$", merged) if not m: continue tag = f"AC-{m.group(1)}" if known_tags and tag not in known_tags: continue r1, r2 = ds.iloc[i], ds.iloc[i + 1] x = int(r1["left"]) y = int(min(r1["top"], r2["top"])) w = int(r2["left"] + r2["width"] - r1["left"]) h = int(max(r1["top"] + r1["height"], r2["top"] + r2["height"]) - y) conf = float((r1["conf"] + r2["conf"]) / 2) hits.append(TagHit(tag, x, y, max(w, 10), max(h, 10), conf, False)) # ── Fuzzy pass (high-conf tokens only) ──────────────────────────────── _FUZZY = re.compile(r"^AC([A-U])$", re.IGNORECASE) for _, row in data[data["conf"] > 70].iterrows(): raw = re.sub(r"[^A-Z0-9]", "", str(row["text"]).upper()) m = _FUZZY.match(raw) if m: tag = f"AC-{m.group(1)}" if known_tags and tag not in known_tags: continue hits.append(TagHit(tag, int(row["left"]), int(row["top"]), int(row["width"]), int(row["height"]), float(row["conf"]), True)) return hits def ocr_floor_page( pdf_path: Path, page_0idx: int, dpi: int, psm: int, min_conf: float, known_tags: set[str], ) -> tuple[Image.Image, list[TagHit]]: """Render page at DPI and OCR-detect unit tags. Returns (color_img, hits).""" color_img = _render_page(pdf_path, page_0idx, dpi) data = _ocr_image(color_img, psm, min_conf) hits = _extract_hits_from_data(data, known_tags, psm) # PSM fallback if sparse results if len(hits) < 3 and psm != 12: logging.debug(f" Page {page_0idx+1}: only {len(hits)} hits with psm {psm}, retrying with psm 12") data2 = _ocr_image(color_img, 12, min_conf) hits.extend(_extract_hits_from_data(data2, known_tags, 12)) return color_img, _deduplicate_hits(hits) # ───────────────────────────────────────────────────────────────────────────── # Step 5 β€” Annotate and save image # ───────────────────────────────────────────────────────────────────────────── def _build_color_map(tags: list[str]) -> dict[str, tuple]: palette = itertools.cycle(_PALETTE) return {tag: next(palette) for tag in sorted(tags)} def annotate_and_save( floor_name: str, page_idx: int, color_img: Image.Image, hits: list[TagHit], out_dir: Path, tag_colors: dict[str, tuple], ) -> Path: img = color_img.copy() draw = ImageDraw.Draw(img) try: font = ImageFont.truetype("arial.ttf", 22) except (OSError, IOError): font = ImageFont.load_default() for hit in hits: color = (220, 220, 50) if hit.fuzzy else tag_colors.get(hit.tag, (220, 50, 50)) # Bounding box draw.rectangle( [hit.x, hit.y, hit.x + hit.w, hit.y + hit.h], outline=color, width=3, ) # Label background + text above the box label = hit.tag lx, ly = hit.x, max(0, hit.y - 20) tw = len(label) * 10 draw.rectangle([lx, ly, lx + tw, ly + 18], fill=color) draw.text((lx + 2, ly + 1), label, fill=(255, 255, 255), font=font) safe = re.sub(r"[^\w]", "_", floor_name) out_path = out_dir / f"floor_{page_idx:03d}_{safe}_annotated.png" img.save(out_path, format="PNG") return out_path # ───────────────────────────────────────────────────────────────────────────── # Step 4 β€” Console summary table # ───────────────────────────────────────────────────────────────────────────── def print_summary_table(floor_results: FloorResults, schedule_tags: dict[str, dict]) -> None: all_tags = sorted( set(schedule_tags.keys()) | {tag for floor in floor_results.values() for tag in floor} ) floors = list(floor_results.keys()) col_w = max((len(t) for t in all_tags), default=4) + 2 lbl_w = max([6, 10] + [len(f) for f in floors]) + 2 header = f"{'Floor':<{lbl_w}}" + "".join(f"{t:>{col_w}}" for t in all_tags) + f"{'Total':>{col_w}}" sep = "─" * len(header) print() print(header) print(sep) detected_totals: dict[str, int] = {t: 0 for t in all_tags} for floor in floors: row_counts = {t: len(floor_results[floor].get(t, [])) for t in all_tags} total = sum(row_counts.values()) for t in all_tags: detected_totals[t] += row_counts[t] row = f"{floor:<{lbl_w}}" + "".join(f"{row_counts[t]:>{col_w}}" for t in all_tags) + f"{total:>{col_w}}" print(row) print(sep) # Schedule row sched_row = f"{'Schedule':<{lbl_w}}" sched_total = 0 for t in all_tags: qty = schedule_tags.get(t, {}).get("qty") or 0 sched_row += f"{qty:>{col_w}}" sched_total += int(qty) print(sched_row + f"{sched_total:>{col_w}}") # Detected totals row det_total = sum(detected_totals.values()) det_row = f"{'Detected':<{lbl_w}}" + "".join(f"{detected_totals[t]:>{col_w}}" for t in all_tags) + f"{det_total:>{col_w}}" print(det_row) print() # Reconciliation warnings for t in all_tags: sched_qty = int(schedule_tags.get(t, {}).get("qty") or 0) det_qty = detected_totals[t] if sched_qty > 0 and det_qty > sched_qty + 1: print(f"[WARNING] Detected > Schedule for {t} ({det_qty} detected vs {sched_qty} scheduled)") elif sched_qty > 0 and det_qty == 0: print(f"[WARNING] {t} appears in schedule (qty {sched_qty}) but was not detected on any floor") # ───────────────────────────────────────────────────────────────────────────── # Interactive checkpoint helper # ───────────────────────────────────────────────────────────────────────────── _auto_yes = False # set to True via --yes flag def _confirm(prompt: str = "Continue? [y/n]: ") -> bool: if _auto_yes: print(prompt + "y (auto)") return True try: answer = input(prompt).strip().lower() return answer in ("y", "yes", "") except (EOFError, KeyboardInterrupt): print() return False # ───────────────────────────────────────────────────────────────────────────── # CLI entry point # ───────────────────────────────────────────────────────────────────────────── def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="HVAC Blueprint Analyzer") p.add_argument("pdf", type=Path, help="Path to the blueprint PDF") p.add_argument("--dpi", type=int, default=300, help="Render DPI (default 300)") p.add_argument("--out-dir", type=Path, default=Path("output"), help="Output directory for annotated images") p.add_argument("--psm", type=int, default=11, help="Tesseract PSM mode (default 11)") p.add_argument("--min-conf", type=float, default=40.0, help="Minimum OCR confidence (default 40)") p.add_argument( "--step", choices=["schedule", "classify", "ocr-one"], default=None, help="Stop after this phase for interactive confirmation", ) p.add_argument("--tile", action="store_true", help="Use tiled OCR for very large pages") p.add_argument("--schedule-page", type=int, default=None, help="1-based page number of the equipment schedule (skips auto-detection)") p.add_argument("--refresh-schedule", action="store_true", help="Ignore cached schedule and re-extract (calls Gemini again)") p.add_argument("--no-yolo", action="store_true", help="Skip saving YOLO training labels to dataset/") p.add_argument("--yes", "-y", action="store_true", help="Auto-confirm all checkpoints (non-interactive run)") p.add_argument("--floor", type=str, default=None, help="Process only one floor (matches floor name, case-insensitive), e.g. '4Th' or 'Roof'") p.add_argument("--page", type=int, default=None, help="Process only one plan page number (1-based)") return p.parse_args() def main() -> None: global _auto_yes # Force UTF-8 stdout/stderr on Windows so non-ASCII chars don't crash piped runs try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") sys.stderr.reconfigure(encoding="utf-8", errors="replace") except Exception: pass args = parse_args() _auto_yes = args.yes logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") if not args.pdf.exists(): logging.error(f"PDF not found: {args.pdf}") sys.exit(1) args.out_dir.mkdir(parents=True, exist_ok=True) # ── Checkpoint 1: Schedule extraction ──────────────────────────────────── print(f"\n{'='*60}") print(f" CHECKPOINT 1 β€” Extracting equipment schedule") print(f"{'='*60}") print(f" PDF : {args.pdf}") print() schedule_tags = extract_schedule(args.pdf, args.dpi, args.schedule_page, out_dir=args.out_dir, refresh=args.refresh_schedule) if schedule_tags: print(f" Found {len(schedule_tags)} unit tag(s):\n") for tag, info in sorted(schedule_tags.items()): qty_str = str(info["qty"]) if info["qty"] is not None else "?" utype = info["unit_type"] or "(type unknown)" print(f" {tag:6s} qty={qty_str:>3} {utype}") else: print(" [WARNING] No unit tags found in schedule β€” tags will be inferred from OCR.") if args.step == "schedule": print() if not _confirm(" Results look correct? Continue to page classification? [y/n]: "): print(" Stopped at schedule step.") return # ── Checkpoint 2: Page classification ──────────────────────────────────── print(f"\n{'='*60}") print(f" CHECKPOINT 2 β€” Classifying pages") print(f"{'='*60}\n") page_manifest = classify_pages(args.pdf) plan_pages = [p for p in page_manifest if p["page_type"] == "plan"] if args.page is not None: plan_pages = [p for p in plan_pages if p["page_num"] == args.page] if args.floor: floor_q = args.floor.strip().lower() plan_pages = [p for p in plan_pages if floor_q in p["floor_name"].lower()] for entry in page_manifest: skip = " (skipped)" if entry["page_type"] != "plan" else "" print(f" Page {entry['page_num']:>3}: {entry['page_type']:<10} {entry['floor_name']:<20} [{entry['title']}]{skip}") print(f"\n {len(plan_pages)} plan page(s) will be processed, {len(page_manifest) - len(plan_pages)} skipped.") # Save manifest so you have a permanent page β†’ floor record import csv manifest_path = args.out_dir / "pages_manifest.csv" with open(manifest_path, "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["page_num", "page_type", "floor_name", "title"]) writer.writeheader() writer.writerows(page_manifest) print(f" Page manifest saved: {manifest_path}") if not plan_pages: logging.error("No plan pages found. Cannot continue.") sys.exit(1) if args.step in ("schedule", "classify"): print() if not _confirm(" Floor list correct? Continue to OCR? [y/n]: "): print(" Stopped at classify step.") return # ── Checkpoint 3: OCR + annotate ───────────────────────────────────────── # Only consider tags with non-zero scheduled quantity (drops false-positive tags) known_tags = {t for t, info in schedule_tags.items() if (info.get("qty") or 0) > 0} if not known_tags: known_tags = set(schedule_tags.keys()) # fallback: schedule has no qty info skipped_zero = sorted(set(schedule_tags.keys()) - known_tags) if skipped_zero: print(f" Skipping detection for {len(skipped_zero)} qty=0 tag(s): {', '.join(skipped_zero)}") all_tags = list(sorted(known_tags)) if known_tags else [f"AC-{chr(65+i)}" for i in range(21)] tag_colors = _build_color_map(all_tags) floor_results: FloorResults = {} pages_to_process = plan_pages[:1] if args.step == "ocr-one" else plan_pages print(f"\n{'='*60}") print(f" CHECKPOINT 3 β€” OCR{' (first floor only)' if args.step == 'ocr-one' else ''}") print(f"{'='*60}\n") for entry in pages_to_process: page_0 = entry["page_num"] - 1 floor_name = entry["floor_name"] print(f" Processing page {entry['page_num']} ({floor_name}) at {args.dpi} DPI…", end=" ", flush=True) floor_out_dir = args.out_dir / re.sub(r"[^\w]", "_", floor_name) floor_out_dir.mkdir(parents=True, exist_ok=True) try: color_img, hits = gemini_detect_floor_page( args.pdf, page_0, args.dpi, known_tags, floor_out_dir, entry["page_num"], floor_name, save_yolo=not args.no_yolo, tile_size=3000, ) except Exception as exc: print(f"FAILED β€” {exc}") logging.warning(f"Page {entry['page_num']} detection failed: {exc} β€” skipping") continue # Accumulate into floor_results (multiple sheets may share a floor name) floor_results.setdefault(floor_name, {}) for hit in hits: floor_results[floor_name].setdefault(hit.tag, []).append(hit) # Annotate and save out_path = annotate_and_save( floor_name, entry["page_num"], color_img, hits, floor_out_dir, tag_colors ) tag_summary = ", ".join( f"{t}Γ—{len(floor_results[floor_name][t])}" for t in sorted(floor_results[floor_name]) ) print(f"done -> {tag_summary or 'no tags found'}") print(f" Annotated image: {out_path}") if args.step == "ocr-one": print() if not _confirm(" Open the annotated image and verify boxes. Continue with all floors? [y/n]: "): print(" Stopped at ocr-one step.") return # Continue with remaining floors print(f"\n Continuing with remaining {len(plan_pages) - 1} floor(s)…\n") for entry in plan_pages[1:]: page_0 = entry["page_num"] - 1 floor_name = entry["floor_name"] print(f" Processing page {entry['page_num']} ({floor_name}) at {args.dpi} DPI…", end=" ", flush=True) floor_out_dir = args.out_dir / re.sub(r"[^\w]", "_", floor_name) floor_out_dir.mkdir(parents=True, exist_ok=True) try: color_img, hits = gemini_detect_floor_page( args.pdf, page_0, args.dpi, known_tags, floor_out_dir, entry["page_num"], floor_name, save_yolo=not args.no_yolo, tile_size=3000, ) except Exception as exc: print(f"FAILED β€” {exc}") continue floor_results.setdefault(floor_name, {}) for hit in hits: floor_results[floor_name].setdefault(hit.tag, []).append(hit) out_path = annotate_and_save( floor_name, entry["page_num"], color_img, hits, floor_out_dir, tag_colors ) tag_summary = ", ".join( f"{t}Γ—{len(floor_results[floor_name][t])}" for t in sorted(floor_results[floor_name]) ) print(f"done -> {tag_summary or 'no tags found'}") print(f" Annotated image: {out_path}") # ── Checkpoint 4: Summary table ─────────────────────────────────────────── print(f"\n{'='*60}") print(f" CHECKPOINT 4 β€” Summary") print(f"{'='*60}") print_summary_table(floor_results, schedule_tags) print(f" Annotated images saved to: {args.out_dir.resolve()}") if __name__ == "__main__": main()
"""
analyze_blueprint.py β€” HVAC Blueprint Analyzer
Usage:
python analyze_blueprint.py <pdf> [--dpi 300] [--out-dir ./output]
[--psm 11] [--min-conf 40]
[--step schedule|classify|ocr-one]
[--tile]
Run with --step <name> to stop and confirm after each phase.
"""
from __future__ import annotations
import argparse
import itertools
import logging
import re
import sys
from io import BytesIO
from pathlib import Path
from typing import NamedTuple
import base64
import csv
import io
import os
import cv2
import fitz
import numpy as np
import pdfplumber
import pytesseract
from PIL import Image, ImageDraw, ImageFont
# ── Load .env from project root ──────────────────────────────────────────────
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent.parent / ".env")
except ImportError:
pass # python-dotenv not installed β€” use system env vars
# ── Windows Tesseract path ────────────────────────────────────────────────────
_TESS_WIN = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
if Path(_TESS_WIN).exists():
pytesseract.pytesseract.tesseract_cmd = _TESS_WIN
# ── Inject sibling package ────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent))
from hvac_pipeline.extract_schedule_robust import (
RowParse,
extract_from_pdf_tables,
extract_from_pdf_text,
normalize_tag as _normalize_tag_schedule,
)
# ── Regex patterns (inlined from read_mechanical_plansvs1.4.py) ───────────────
_TAG_STRICT = re.compile(r"\bAC[-\s]?[A-U]\b", re.IGNORECASE)
_TAG_LOOSE = re.compile(r"\bA\s*C\s*[-]?\s*([A-U])\b", re.IGNORECASE)
_INT_PAT = re.compile(r"\b\d{1,2}\b")
_FLOOR_PAT = re.compile(r"(LEVEL|FLOOR|ROOF|BASEMENT)\s*(\d+)?", re.IGNORECASE)
# ── Annotation color palette ──────────────────────────────────────────────────
_PALETTE = [
(220, 50, 50),
(50, 150, 220),
(50, 200, 100),
(220, 150, 50),
(150, 50, 220),
(50, 200, 200),
(220, 220, 50),
(200, 100, 150),
(100, 200, 50),
(50, 100, 200),
(200, 50, 150),
(100, 150, 50),
]
# ── Data types ────────────────────────────────────────────────────────────────
class TagHit(NamedTuple):
tag: str
x: int
y: int
w: int
h: int
conf: float
fuzzy: bool
FloorResults = dict[str, dict[str, list[TagHit]]]
# ─────────────────────────────────────────────────────────────────────────────
# Helpers inlined from read_mechanical_plansvs1.4.py
# ─────────────────────────────────────────────────────────────────────────────
def _extract_explicit_title(text: str) -> str | None:
if not text:
return None
lines = [ln.strip() for ln in text.split("\n")]