""" analyze_blueprint.py — HVAC Blueprint Analyzer Usage: python analyze_blueprint.py [--dpi 300] [--out-dir ./output] [--psm 11] [--min-conf 40] [--step schedule|classify|ocr-one] [--tile] Run with --step 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) ─────────────── # Matches standard single-letter tags (AC-A … AC-U) plus extended formats: # multi-letter : AC-LV, AC-R # letter+number : AC-C-1, AC-C-11 # number+number : AC-1-1, AC-1-14, AC-2-2 _TAG_STRICT = re.compile( r"\bAC" r"[-\s]?" r"(?:" r"[A-Z]{1,3}(?:[-]\d{1,2})?" # AC-A, AC-LV, AC-C-1, AC-C-11 r"|" r"\d{1,2}(?:[-]\d{1,2})?" # AC-1, AC-1-1, AC-1-14 r")\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) # ── Schedule model-number / company extraction ──────────────────────────────── _MODEL_NUMBER_PAT = re.compile( r"\b(" r"(?:FX|RX|RZ)[A-Z]{1,3}Q?\d{2,3}[A-Z]{2,8}" # Daikin VRV/VRF (FXAQ, FXSQ, RXTQ …) r"|MSZ[-\s]?[A-Z]{2,4}[-\s]?\d{2,3}[A-Z]*" # Mitsubishi MSZ wall-mount r"|(?:SEZ|MFZ|MLZ|PEFY|PKFY|PLFY|PMFY|PCFY)[-\s]?[A-Z0-9]{3,12}" # Mitsubishi others r")\b", re.IGNORECASE, ) _COMPANY_PAT = re.compile(r"\b(DAIKIN|DAIK|MITSUBISHI|MITS)\b", 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 _SCHEDULE_TITLE_PAT = re.compile( r"\b(" r"INDOOR\s+UNITS?|" r"INDOOR\s+FAN\s+COILS?|" r"FAN\s+COIL\s+UNITS?|" r"VR[FV]\s+INDOOR|" r"EQUIPMENT\s+SCHEDULE|" r"UNIT\s+SCHEDULE|" r"MECHANICAL\s+SCHEDULE|" r"MECHANICAL\s+EQUIPMENT|" r"HEAT\s+PUMP\s+SCHEDULE|" r"SPLIT\s+SYSTEM\s+SCHEDULE" r")\b", re.IGNORECASE, ) _SCHEDULE_BODY_PAT = re.compile( r"\b(" r"INDOOR\s+UNITS?|" r"INDOOR\s+UNIT\s+SCHEDULE|" r"VARIABLE\s+REFRIGERANT\s+VOLUME|" r"VR[FV]\s+INDOOR|" r"FAN\s+COIL\s+UNITS?|" r"HEAT\s+PUMP\s+SCHEDULE|" r"SPLIT\s+SYSTEM\s+SCHEDULE" r")\b", re.IGNORECASE, ) _TITLE_KEYWORDS = re.compile( r"\b(MECHANICAL|HVAC|AIR\s+RISER|RISER|DIAGRAM|PLAN|SCHEDULE|DETAIL|" r"SECTION|BULKHEAD|CELLAR|ROOF|EQUIPMENT|INDOOR\s+UNITS?)\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 if _SCHEDULE_TITLE_PAT.search(line): bonus += 0.4 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() # Strong schedule signal: the literal word SCHEDULE next to an equipment word. # Requiring "…SCHEDULE" avoids false-positives on DETAIL/SECTION pages that merely # mention "INDOOR UNITS" (e.g. Dean St p15 "24 MIN. TO INDOOR UNITS"). The char # classes absorb the most common OCR misreads of these words. _SCHEDULE_STRONG = re.compile( r"\b(" r"E[OQ]UIPMENT|UNIT|INDOOR\s*UNIT|MECHANICAL|HEAT\s*PUMP|FAN\s*COIL|" r"CONDENSING\s*UNIT|OUTDOOR\s*UNIT|VR[FV]" r")\s+SCH[EO]D[UV][IL][EO]\b", re.IGNORECASE, ) # Schedule signal acceptable IN A TITLE (title block / sheet title) — broader than # _SCHEDULE_STRONG because a title saying "INDOOR UNITS" (without the word # SCHEDULE) is still the indoor-unit schedule. NOT safe to run over body text, # where "INDOOR UNIT(S)" shows up in notes ("…for each INDOOR UNIT"). _SCHEDULE_TITLE_KEYWORDS = re.compile( r"\b(SCH[EO]D[UV][IL][EO]|INDOOR\s+UNITS?|INDOOR\s+FAN\s+COILS?|" r"FAN\s+COIL\s+UNITS?|VR[FV]\s+INDOOR)\b", re.IGNORECASE, ) def _ocr_page_fulltext(pdf_path: Path, page_0idx: int, dpi: int = 220) -> str: """OCR the whole page (multi-PSM) and return the combined text. Higher DPI than the old 150 (small title text reads far better at 220), and PSM 4 (columnar) + PSM 6 (block) together recover titles one mode misses. """ doc = fitz.open(pdf_path) pix = doc.load_page(page_0idx).get_pixmap( matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) gray = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2GRAY) g = Image.fromarray(gray) parts = [] for psm in (6, 4): try: parts.append(pytesseract.image_to_string(g, config=f"--oem 3 --psm {psm}")) except Exception: pass return "\n".join(parts) def _title_from_ocr_text(ocr_txt: str) -> str | None: """Pick the drawing title out of already-OCR'd page text.""" title = _extract_explicit_title(ocr_txt) if title and _TITLE_KEYWORDS.search(title): return title return _extract_heuristic_title(ocr_txt, max_lines=None) def _ocr_page_title(pdf_path: Path, page_0idx: int) -> str | None: """Render the page, OCR it, and return the drawing title (or None).""" return _title_from_ocr_text(_ocr_page_fulltext(pdf_path, page_0idx)) # Sub-labels that live in the title block but are NOT the drawing title. _TITLE_BLOCK_EXCLUDE = re.compile( r"\b(SITE\s+PLAN|PLAN\s+NOTES?|KEY\s+PLAN|GENERAL\s+NOTES?|" r"NORTH|SCALE|DRAWN|CHECKED)\b", re.IGNORECASE) # A note / spec / callout line — never the drawing title. Catches things like # "1. PROVIDE ONE 7-DAY PROGRAMMABLE THERMOSTAT FOR EACH INDOOR UNIT" that would # otherwise score as a schedule title because they contain "INDOOR UNIT". _NOTE_LINE = re.compile( r"^\s*\d+\s*[.\)]" # numbered note ("1.", "2)") r"|\b(PROVIDE|INSTALL|SHALL|THERMOSTAT|PURGE|MINIMUM|REFER\s+TO|" r"CONSTRUCTION|SLEEVE|CONTROL\s+PANEL|TYPICAL\s+OF|EACH\s+INDOOR)\b", re.IGNORECASE) def _ocr_titleblock_text(pdf_path: Path, page_0idx: int, dpi: int = 220) -> str: """OCR the title-block strips (right edge + bottom) and return their text. These strips hold the sheet title; kept separate from the page body so the title scorer can give title-block lines a small boost.""" doc = fitz.open(pdf_path) pix = doc.load_page(page_0idx).get_pixmap( matrix=fitz.Matrix(dpi / 72, dpi / 72), alpha=False) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) W, H = img.size out = [] for (x0, y0, x1, y1) in [(int(0.70 * W), 0, W, H), (0, int(0.80 * H), W, H)]: gray = cv2.cvtColor(np.array(img.crop((x0, y0, x1, y1))), cv2.COLOR_RGB2GRAY) g = Image.fromarray(gray) for psm in (6, 4): try: out.append(pytesseract.image_to_string(g, config=f"--oem 3 --psm {psm}")) except Exception: pass return "\n".join(out) def _best_ocr_title(full_text: str, tb_text: str = "") -> str | None: """Pick the drawing title from OCR'd text (whole page + title block). Scores every title-ish line and PREFERS a 'standard' drawing title — one that starts with MECHANICAL, ends with a sheet-type word (PLAN/SCHEDULE/RISERS/…), or carries an ordinal floor. This beats both note paragraphs (Dean St) and stray floor-key legends in the title block (355 'CELLAR FLOOR'), without caring where on the sheet the title sits. """ scored: dict[str, int] = {} def consider(line: str, in_tb: bool): s = re.sub(r"[^\x00-\x7F]+", " ", line) s = re.sub(r"\s{2,}", " ", s).strip() # Titles are short; note/spec lines are long sentences. 55 keeps the # longest real titles ("…TYPICAL 13TH THRU 14TH FLOOR PLAN" ≈ 44). if not (6 <= len(s) <= 55) or _TITLE_BLOCK_EXCLUDE.search(s) \ or _NOTE_LINE.search(s): return if sum(c.isupper() for c in s) / max(len(s), 1) < 0.5: return su = s.upper() if not (_TITLE_KEYWORDS.search(su) or _SCHEDULE_TITLE_KEYWORDS.search(su)): return sc = 1 std = _is_standard_title(s) if std: sc += 6 # a real sheet title beats notes & floor-keys if _SCHEDULE_TITLE_KEYWORDS.search(su): sc += 4 if std and _FLOOR_DESIG_PAT.search(su): sc += 2 # prefer the floor-specific standard title if in_tb: sc += 1 scored[s] = scored.get(s, 0) + sc for ln in (full_text or "").splitlines(): consider(ln, False) for ln in (tb_text or "").splitlines(): consider(ln, True) if not scored: return None return max(scored.items(), key=lambda kv: kv[1])[0] _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 or "").upper() # Schedule: require the literal word SCHEDULE in the title (every real # schedule sheet's title block says "...SCHEDULE"). The old rule also fired # on a bare "INDOOR UNIT(S)", which wrongly tagged plan sheets whose notes # say "...for each INDOOR UNIT" as schedules. # Schedule when the TITLE says SCHEDULE or INDOOR UNIT(S)/FAN COIL — title # text is safe to match broadly (notes live in the body, not the title). if _SCHEDULE_TITLE_KEYWORDS.search(t): return "schedule" # Cover/index/title sheet — generic, no specific floor. Exact-match guard so # a real " MECHANICAL PLAN" is never swallowed. if (any(k in t for k in ("COVER", "INDEX", "TITLE SHEET")) or t.strip() in ("MECHANICAL PLANS", "MECHANICAL PLAN", "MECHANICAL")): return "other" if "SPECIFICATION" in t or ("NOTE" in t and "PLAN" not in t): return "notes" # A floor-PLAN title (has both FLOOR and PLAN) wins over a stray SECTION / # DETAIL callout that the title block may also contain. if "FLOOR" in t and "PLAN" in t: return "plan" # 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 ("PLAN" in t or "FLOOR" in t or "LEVEL" in t or "ROOF" in t or "CELLAR" in t or "BULKHEAD" in t or "PENTHOUSE" in t or "MEZZANINE" in t): return "plan" # Image-only schedule whose title block didn't OCR a usable title — fall # back to a STRONG body signal (word SCHEDULE beside an equipment word). # Only when there's no title at all, so a specs/notes sheet that merely # references a schedule isn't itself called a schedule. if not t and _SCHEDULE_STRONG.search(x): return "schedule" return "other" def _normalize_tag(raw: str) -> str | None: """Return normalized tag form or None. Accepted output formats: AC-A … AC-U (single letter) AC-LV (multi-letter special tags) AC-C-1 (letter + dash + number, e.g. AC-C-1 … AC-C-11) AC-1-1 (digit + dash + digit, e.g. AC-1-1 … AC-1-14) """ # Uppercase, collapse whitespace → dashes, strip anything that isn't # alphanumeric or dash, collapse double-dashes, trim leading/trailing dashes. cleaned = raw.upper().strip() cleaned = re.sub(r"\s+", "-", cleaned) cleaned = re.sub(r"[^A-Z0-9\-]", "", cleaned) cleaned = re.sub(r"-{2,}", "-", cleaned).strip("-") # Extract the "rest" after the AC prefix if cleaned.startswith("AC-"): rest = cleaned[3:] elif cleaned.startswith("AC") and len(cleaned) > 2: rest = cleaned[2:] else: return None # Validate: 1–3 uppercase letters (optionally followed by -NN) # OR 1–2 digits (optionally followed by -NN) if (re.match(r"^[A-Z]{1,3}(?:-\d{1,2})?$", rest) or re.match(r"^\d{1,2}(?:-\d{1,2})?$", rest)): return f"AC-{rest}" 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 # Model number: search after the tag position so we don't grab # model-like strings that precede the tag in garbled OCR lines. tag_end = (m or m2 or m3).end() if (m or m2 or m3) else 0 model_match = _MODEL_NUMBER_PAT.search(line, tag_end) model_number = model_match.group(1).upper() if model_match else "" # Company from manufacturer keyword anywhere in the line company_match = _COMPANY_PAT.search(upper) company_raw = company_match.group(1).upper() if company_match else "" if company_raw in ("DAIKIN", "DAIK"): company = "Daikin" elif company_raw in ("MITSUBISHI", "MITS"): company = "Mitsubishi" else: company = "" # Qty: first 1-2 digit integer that follows the model number (avoids # picking up capacity numbers like 12,000 or voltage like 208). search_start = model_match.end() if model_match else tag_end nums = [int(v) for v in _INT_PAT.findall(line[search_start:])] qty = next((n for n in nums if 1 <= n <= 50), None) if qty is None: # Fallback: scan the whole line nums_all = [int(v) for v in _INT_PAT.findall(line)] qty = next((n for n in nums_all if 1 <= 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), model_number) if key in seen: continue seen.add(key) rows.append({ "page_num": page_num, "tag": tag, "qty_required": qty, "unit_type": utype, "model_number": model_number, "company": company, }) 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. It contains MULTIPLE tables: an outdoor " "unit schedule, an indoor unit schedule, fan schedules, and possibly others — all on the " "same page.\n\n" "YOUR TASK: Extract ONLY rows from the INDOOR UNIT SCHEDULE table (also labelled " "'VARIABLE REFRIGERANT VOLUME – INDOOR UNIT SCHEDULE' or similar).\n\n" "IMPORTANT: The indoor unit schedule may be split into several sub-sections on this page " "(for example: apartment units, commercial/building units, corridor units). " "Extract every row from EVERY sub-section of the indoor unit schedule.\n\n" "Return the data as CSV with exactly these 5 columns: tag,qty,unit_type,model_number,company\n\n" "Rules:\n" "- tag must exactly reproduce the tag shown in the schedule. Accepted formats:\n" " Single letter : AC-A, AC-B … AC-U\n" " Multi-letter : AC-LV, AC-R\n" " Letter+number : AC-C-1, AC-C-2 … AC-C-11\n" " Number+number : AC-1-1, AC-1-2 … AC-1-14 or AC-2-1, AC-2-2\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 UNIT); leave blank if not shown\n" "- model_number should be the manufacturer part/model number " "(e.g. FXSQ48TAVJU, FXAQ09PVJU, MSZ-FX12NA); leave blank if not shown\n" "- company should be the manufacturer/brand name (e.g. Daikin, Mitsubishi); leave blank " "if not shown\n" "- Do NOT include commas inside any field value\n" "- Do NOT extract rows from the outdoor unit schedule, fan schedule, exhaust fan " "schedule, or any other non-indoor-unit table\n" "- Include ALL rows from all sub-sections of the indoor unit schedule, even qty=0 rows\n" "- Output ONLY the CSV rows — no header row, no explanations, no markdown." ) try: 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=4096, temperature=0.0), ) except Exception as e: print(f" [WARNING] Gemini schedule call failed ({e}) — continuing with OCR results only.") print(" Check GEMINI_API_KEY in .env (get a key at https://aistudio.google.com/apikey)") return [] rows: list[RowParse] = [] for line in response.text.strip().splitlines(): line = line.strip().strip(",") if not line: continue # Split on first 4 commas so remaining fields don't overflow into model_number/company parts = [p.strip() for p in line.split(",", 4)] 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 "" model_number = parts[3] if len(parts) > 3 else "" company = parts[4] if len(parts) > 4 else "" rows.append(RowParse( tag=tag, qty_required=qty, unit_type=utype, confidence=0.95, source="gemini_vision", raw_text=line, model_number=model_number, company=company, )) return rows _INDOOR_HEADER = re.compile( r"\b(" r"INDOOR\s+UNIT\s+SCHEDULE|" r"INDOOR\s+UNITS?|" r"INDOOR\s+FAN\s+COILS?|" r"FAN\s+COIL\s+UNITS?|" r"VR[FV]\s+INDOOR" r")\b", 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, region: tuple[float, float, float, float] | None = None) -> 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 /_schedule_cache.json so the API is only called once. Use --refresh-schedule to force re-extraction. region: optional (x0, y0, x1, y1) as 0-1 fractions of the page. When given (with schedule_page), only that rectangle is read — the user has drawn a box around the schedule table in the GUI. Forces a fresh extract (skips cache). """ if region is not None: refresh = True # a hand-drawn region always re-extracts # ── 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…") # Phase 1 (sequential, cheap): native text extraction + classify. # pdfplumber isn't thread-safe to share across threads, and text # extraction is fast, so do it in one pass and note which pages still # need an OCR title check (the slow part). need_ocr: list[int] = [] page_txt: dict[int, str] = {} for i in candidates_idx: print(f" page {i}/{total}…", end="\r", flush=True) txt = pdf.pages[i - 1].extract_text() or "" page_txt[i] = txt title = _extract_page_title(txt) ptype = _classify_page_context(title, txt) if ptype == "schedule": schedule_pages.append(i) continue needs_ocr_schedule_hint = ( not title or len(txt.strip()) < 500 or bool(_SCHEDULE_BODY_PAT.search(txt)) ) if needs_ocr_schedule_hint: need_ocr.append(i) print() # clear the \r line # Phase 2 (parallel): OCR the page titles. Tesseract runs as a # subprocess (releases the GIL) and each call opens its own PDF # handle, so several pages OCR at once — same result, far less wait. if need_ocr: workers = max(1, int(os.environ.get("HVAC_TILE_WORKERS", "4"))) print(f" OCR-checking {len(need_ocr)} page title(s) " f"({workers} at a time)…", flush=True) from concurrent.futures import ThreadPoolExecutor def _ocr_check(i): # Image-only schedule sheets have no native text. Two signals: # (a) the STRONG word "SCHEDULE" beside an equipment word # anywhere on the page (e.g. Dean St p16 "EQUIPMENT # SCHEDULE"), and # (b) the TITLE BLOCK saying SCHEDULE / INDOOR UNIT(S) — this # catches a schedule titled "INDOOR UNITS" with no # "SCHEDULE" word, WITHOUT tripping on DETAIL/SECTION # pages whose BODY says "INDOOR UNITS" (p15), since we # only read the title block here, not the notes. try: full = _ocr_page_fulltext(pdf_path, i - 1) except Exception: return i, False if _SCHEDULE_STRONG.search(full): return i, True tb = _ocr_titleblock_text(pdf_path, i - 1) title = _best_ocr_title(full, tb) or "" return i, bool(_SCHEDULE_TITLE_KEYWORDS.search(title)) with ThreadPoolExecutor(max_workers=workers) as ex: for i, is_sched in ex.map(_ocr_check, need_ocr): if is_sched: schedule_pages.append(i) schedule_pages.sort() 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}…") # ── Hand-drawn region: read ONLY the boxed rectangle ────────────────── # The user pointed at the schedule and drew a box around the table, so # skip the page-wide native tiers and OCR + Gemini-vision just the crop. if region is not None: rx0, ry0, rx1, ry1 = region 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) full = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) W, H = full.size box = (int(rx0 * W), int(ry0 * H), int(rx1 * W), int(ry1 * H)) crop = full.crop(box) print(f" Reading hand-drawn schedule region on page {pnum}: " f"{box} of {W}x{H}px") gray = cv2.cvtColor(np.array(crop), cv2.COLOR_RGB2GRAY) ocr_img = Image.fromarray(gray) raw_lines = [] 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()) lines = _extract_indoor_unit_section(raw_lines) 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="region_ocr", raw_text="", model_number=row.get("model_number", ""), company=row.get("company", ""))) # Gemini vision on the crop — best for an arbitrary boxed table. vision_rows = _extract_schedule_via_gemini(crop) if vision_rows: print(f" Gemini returned {len(vision_rows)} rows from the region.") candidates.extend(vision_rows) continue 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="", model_number=row.get("model_number", ""), company=row.get("company", ""), ) ) # Trigger Gemini if we have few tags OR any tags are missing their type. # OCR text parsing reliably finds tags but rarely extracts model numbers, # so unit_type is usually blank even when tag count is high. ocr_tag_count = len({c.tag for c in candidates}) missing_type = {c.tag for c in candidates if not c.unit_type} if ocr_tag_count < 5 or missing_type: reason = ( f"only {ocr_tag_count} tag(s)" if ocr_tag_count < 5 else f"{len(missing_type)} tag(s) missing unit type" ) print(f" {reason} — 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, "model_number": row.model_number, "company": row.company, } for tag, row in by_tag.items() if row.qty_required is not None or row.unit_type } # Fill in missing unit types via Excel lookup for tag, info in result.items(): if not info["unit_type"] and info.get("model_number"): looked_up = _lookup_unit_type(info.get("company", ""), info["model_number"]) if looked_up: info["unit_type"] = looked_up print(f" Resolved unit type for {tag} via Excel lookup: {looked_up}" f" (model: {info['model_number']})") # 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 # ───────────────────────────────────────────────────────────────────────────── # A floor designation, found ANYWHERE in the title — robust to word order. Handles # both "MECHANICAL 4TH FLOOR PLAN" and "7TH FLOOR MECHANICAL PLAN" (Dean St style), # plus named levels and typical-floor ranges. _FLOOR_DESIG_PAT = re.compile( r"\b(" r"SUB[\s-]?CELLAR|CELLAR|BASEMENT|" r"GROUND(?:\s+FLOOR)?|" r"ROOF|BULKHEAD|PENTHOUSE|MEZZANINE|" r"(?:TYPICAL\s+)?\d{1,2}(?:ST|ND|RD|TH)?" r"(?:\s*(?:THRU|TO|-|&|/)\s*\d{1,2}(?:ST|ND|RD|TH)?)?\s*FLOOR" r")\b", re.IGNORECASE, ) def _floor_name_from_title(title: str | None) -> str | None: """ Pull a human-readable floor label out of a page title, wherever it sits. 'MECHANICAL 4TH FLOOR PLAN' -> '4th Floor' '7TH FLOOR MECHANICAL PLAN' -> '7th Floor' (Dean St order) 'MECHANICAL TYPICAL 4TH THRU 5TH FLOOR PLAN'-> 'Typical 4th-5th Floor' 'MECHANICAL ROOF PLAN' -> 'Roof' 'MECHANICAL CELLAR PLAN' -> 'Cellar' 'BULKHEAD MECHANICAL PLAN' -> 'Bulkhead' Returns None when no floor designation is present (e.g. a cover/index sheet). """ if not title: return None m = _FLOOR_DESIG_PAT.search(title.upper()) if not m: return None desig = m.group(1) desig = re.sub(r"\s*(?:THRU|TO|&|/)\s*", "-", desig) # range -> 4TH-5TH desig = re.sub(r"\s*-\s*", "-", desig) desig = re.sub(r"\s{2,}", " ", desig).strip().title() # title() capitalizes ordinal suffixes ('7Th'); fix them back to '7th' desig = re.sub(r"\b(\d+)(St|Nd|Rd|Th)\b", lambda mm: mm.group(1) + mm.group(2).lower(), desig) return desig # A native title is "strong" (a real sheet title we can trust as-is) when it has # the word PLAN/SCHEDULE or an ordinal floor designation. A note that merely # contains a bare "ROOF"/"CELLAR" (e.g. "ROOF OVER CELLAR PARKING GARAGE BELOW") # is NOT strong, so we fall back to the title block for those. _ORDINAL_FLOOR_PAT = re.compile( r"\b(?:TYPICAL\s+)?\d{1,2}(?:ST|ND|RD|TH)?" r"(?:\s*(?:THRU|TO|-|&|/)\s*\d{1,2}(?:ST|ND|RD|TH)?)?\s*FLOOR\b", re.IGNORECASE, ) # A native title is "standard" — a real drawing title we trust as-is — when it # starts with MECHANICAL, ends with a sheet-type word (PLAN/SCHEDULE/RISERS/ # DETAILS/…), or contains an ordinal floor. A note that merely mentions a floor # word in prose ("ROOF OVER CELLAR PARKING GARAGE BELOW") is NOT standard, so # those pages fall through to the title-block OCR. _SHEET_TYPE_END = re.compile( r"\b(PLANS?|SCHEDULES?|RISERS?|DETAILS?|DIAGRAMS?|SECTIONS?|" r"SPECIFICATIONS?|NOTES?|LEGEND)\s*$", re.IGNORECASE) def _is_standard_title(s: str) -> bool: """A real drawing title — NOT a note/callout that merely ends in 'PLAN'. A bare '…UP ON PLAN' or floor-key 'CELLAR' is not standard; a floor title with PLAN, a MECHANICAL sheet, a schedule, or a detail/riser is.""" u = s.upper().strip() if u.startswith("MECHANICAL"): return True if "MECHANICAL PLAN" in u or "MECHANICAL SCHEDULE" in u: return True if _SCHEDULE_TITLE_KEYWORDS.search(u): return True if re.search(r"\b(RISERS?|DIAGRAMS?|DETAILS?|SECTIONS?)\b", u): return True if _FLOOR_DESIG_PAT.search(u) and "PLAN" in u: # " … PLAN" return True return False def _classify_one_page(pdf_path: Path, i: int, txt: str) -> dict: """Classify a single page. Trusts the native (vector-text) drawing title when it's a standard sheet title — keeping crisp sets like 355 fast and unchanged. Only when the native title is missing or is a prose note (e.g. Dean St p5 "ROOF OVER CELLAR…" on the 2nd-floor plan) does it OCR the TITLE BLOCK strip, which is far cleaner than whole-page OCR (that kept mistaking notes for the title).""" native = _extract_page_title(txt) body = txt if native and _is_standard_title(native): title = native # crisp native title — trust it else: # Missing or prose native title (image-only / flattened sheet): OCR both # the whole page and the title block, then pick the best STANDARD title. full = _ocr_page_fulltext(pdf_path, i - 1) tb = _ocr_titleblock_text(pdf_path, i - 1) title = _best_ocr_title(full, tb) or native body = full # for image-only schedule fallback ptype = _classify_page_context(title, body) # Floor name comes ONLY from the (clean) title — never from a whole-page # scan, which used to pick up a stray "ROOF"/"2ND FLOOR" from a note. floor_name = _floor_name_from_title(title) if not floor_name: m = _FLOOR_PAT.search(txt) floor_name = m.group(0).title().strip() if m else f"Page {i}" return {"page_num": i, "page_type": ptype, "floor_name": floor_name, "title": title or "(no title)"} def classify_pages(pdf_path: Path) -> list[dict]: """ Returns list of {page_num, page_type, floor_name, title} for every page. The per-page OCR fallback (image-only sheets) dominates the cost, so pages are classified concurrently — Tesseract runs as a subprocess and each call opens its own PDF handle. Native text extraction is done first in one pass (pdfplumber isn't thread-safe to share). """ from concurrent.futures import ThreadPoolExecutor with pdfplumber.open(pdf_path) as pdf: total = len(pdf.pages) texts = [(i, pdf.pages[i - 1].extract_text() or "") for i in range(1, total + 1)] workers = max(1, int(os.environ.get("HVAC_TILE_WORKERS", "4"))) print(f" classifying {total} pages ({workers} at a time)…", flush=True) manifest: list[dict] = [] with ThreadPoolExecutor(max_workers=workers) as ex: for entry in ex.map(lambda it: _classify_one_page(pdf_path, it[0], it[1]), texts): manifest.append(entry) manifest.sort(key=lambda e: e["page_num"]) 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" _UNIT_LOOKUP_XLSX = Path(__file__).parent.parent / "Mitsubishi_Daikin_Indoor_HVAC_Units_v1.xlsx" # ── Unit-type Excel lookup ───────────────────────────────────────────────────── _unit_lookup_rows: list[dict] | None = None def _get_unit_lookup_rows(excel_path: Path = _UNIT_LOOKUP_XLSX) -> list[dict]: """Load and cache rows from the All Indoor Units sheet.""" global _unit_lookup_rows if _unit_lookup_rows is not None: return _unit_lookup_rows if not excel_path.exists(): logging.warning(f"Unit lookup Excel not found: {excel_path}") _unit_lookup_rows = [] return _unit_lookup_rows try: import pandas as pd df = pd.read_excel(excel_path, sheet_name="All Indoor Units", header=2) df = df.dropna(subset=[df.columns[0]]) _unit_lookup_rows = df.to_dict("records") except Exception as e: logging.warning(f"Could not load unit lookup Excel: {e}") _unit_lookup_rows = [] return _unit_lookup_rows def _lookup_unit_type(company: str, model_number: str, excel_path: Path = _UNIT_LOOKUP_XLSX) -> str: """ Return unit type by matching brand + model-number prefix against the Excel reference sheet. Tries series-prefix match first, then example-model prefix. Returns empty string when no match is found. """ model_upper = model_number.strip().upper() if not model_upper: return "" company_norm = company.strip().lower() rows = _get_unit_lookup_rows(excel_path) for row in rows: cols = list(row.keys()) brand = str(row.get(cols[0], "")).strip().lower() unit_type = str(row.get(cols[2], "")).strip() series_raw = str(row.get(cols[3], "")).strip() examples_raw = str(row.get(cols[6], "")) if not unit_type or unit_type == "nan": continue # Brand filter — skip only when a company was given and clearly doesn't match if company_norm and company_norm not in brand and brand not in company_norm: continue # Series / Model Family prefix match (handles "FXFQ-PVJU / FXFQ-TVJU") for series in re.split(r"\s*/\s*", series_raw): prefix = series.strip().upper() if prefix and model_upper.startswith(prefix): return unit_type # Fallback: derive prefix from example model numbers (strip trailing digits) for ex in examples_raw.split(","): ex_prefix = re.sub(r"\d+.*$", "", ex.strip().upper()).rstrip("-") if len(ex_prefix) >= 4 and model_upper.startswith(ex_prefix): return unit_type return "" 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 _tile_coords(img_size: tuple[int, int], tile_size: int = 3000, overlap: int = 300, skip_right_frac: float = 0.15) -> list[tuple[int, int, int, int]]: """Tile (x0,y0,x1,y1) rectangles only — no image crops held in memory. Use when iterating many tiles (consensus passes) to avoid OOM.""" W, H = img_size max_x = int(W * (1.0 - skip_right_frac)) step = tile_size - overlap out = [] y = 0 while y < H: x = 0 while x < max_x: x1 = min(x + tile_size, W) y1 = min(y + tile_size, H) out.append((x, y, x1, y1)) if x1 >= max_x: break x += step if y + tile_size >= H: break y += step return out 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 _detection_prompt_inclusive(tag_list: str) -> str: """Recall-first prompt: be inclusive, let the verify step handle precision.""" return ( "You are analyzing a SECTION (tile) of a mechanical HVAC floor plan.\n\n" "Find EVERY HVAC indoor unit in this tile. Your goal is to MISS NOTHING. " "A separate verification step removes false positives afterward, so when " "in doubt, INCLUDE it.\n\n" "Report a detection if EITHER of these is true:\n" " (a) one of the schedule tags below appears as a printed label (it may be " "small, faint, or rotated 90°) — even if the unit symbol is partly cut off " "at the tile edge; OR\n" " (b) you see a box/rectangle symbol with internal hatching, coil lines, or " "an X pattern that looks like an indoor unit, with a nearby short label.\n\n" "Only DON'T report: schedule tables, title blocks, and pure text-note blocks. " "Everything else that might be a unit — INCLUDE it.\n\n" f"SCHEDULE TAGS for this blueprint:\n{tag_list}\n\n" "For each detection give the tag that best matches the label (your closest " "guess if unsure — the tag is re-checked later).\n" "Return ONLY JSON, no markdown:\n" '{"detections": [{"tag": "", "ymin": N, "xmin": N, "ymax": N, "xmax": N}, ...]}\n' "Box encloses the unit symbol AND its label. Coordinates are integers 0-1000 " 'normalized to THIS TILE. Return {"detections": []} only if there is truly ' "nothing unit-like here." ) def _detection_prompt(tag_list: str, inclusive: bool = False) -> str: if inclusive: return _detection_prompt_inclusive(tag_list) return ( "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": "", "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.' ) def _parse_tile_detections(raw: str, x0: int, y0: int, tile_w: int, tile_h: int, known_tags: list[str], coord_w: float = 1000, coord_h: float = 1000) -> list[TagHit]: """Parse a model's {"detections":[{tag,xmin,ymin,xmax,ymax}]} into full-image pixel TagHits. coord_w/coord_h are the model's coordinate space: 1000 for Gemini (normalized 0-1000), or the sent image's pixel size for Qwen (which returns absolute pixels). Shared by every detector backend.""" import json as _json raw = re.sub(r"^```[a-z]*\n?", "", raw.strip(), flags=re.MULTILINE) raw = re.sub(r"```$", "", raw.strip()) m = re.search(r"\{.*\}", raw, re.DOTALL) # tolerate prose around JSON if m: raw = m.group(0) try: dets = _json.loads(raw).get("detections", []) except _json.JSONDecodeError: return [] hits = [] for det in dets: tag = _normalize_tag(det.get("tag", "")) if not tag or (known_tags and tag not in known_tags): continue try: cw, ch = coord_w, coord_h # auto-detect: if any coord exceeds 1000, it's absolute pixels if max(det["xmax"], det["ymax"]) > 1000 and coord_w == 1000: cw = ch = max(det["xmax"], det["ymax"]) xn, yn = det["xmin"] / cw, det["ymin"] / ch xn2, yn2 = det["xmax"] / cw, det["ymax"] / ch except (KeyError, TypeError): continue 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_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, inclusive: bool = False, ) -> 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 = _detection_prompt(tag_list, inclusive) 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() except Exception as e: logging.warning(f" Tile ({x0},{y0}) Gemini error: {e}") return [] return _parse_tile_detections(raw, x0, y0, tile_w, tile_h, known_tags) def _qwen_call_tile( api_key: str, model: str, tile: Image.Image, x0: int, y0: int, img_w: int, img_h: int, known_tags: list[str], page_num: int, max_px: int = 2048, inclusive: bool = False, ) -> list[TagHit]: """Send one tile to a vision model via OpenRouter (Qwen by default) and return TagHits in full-image pixel coordinates. Same prompt/format as Gemini so the rest of the pipeline (snap, verify, cache) is identical.""" import base64, json as _json, urllib.request tile_w, tile_h = tile.size scaled, _ = _scale_image_for_api(tile, max_px) buf = io.BytesIO() scaled.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() tag_list = ", ".join(sorted(known_tags)) if known_tags else "(no tags provided)" body = { "model": model, "messages": [{"role": "user", "content": [ {"type": "text", "text": _detection_prompt(tag_list, inclusive)}, {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}, ]}], "max_tokens": 4096, "temperature": 0, } req = urllib.request.Request( "https://openrouter.ai/api/v1/chat/completions", data=_json.dumps(body).encode(), headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=120) as r: raw = _json.load(r)["choices"][0]["message"]["content"] except Exception as e: logging.warning(f" Tile ({x0},{y0}) Qwen error: {e}") return [] # Qwen returns absolute pixels of the scaled image it received sw, sh = scaled.size return _parse_tile_detections(raw, x0, y0, tile_w, tile_h, known_tags, coord_w=sw, coord_h=sh) 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, refresh: bool = False, consensus: int = 1, render_pdf: Path | None = None, detector: str = "gemini", qwen_model: str = "qwen/qwen2.5-vl-72b-instruct", recall_prompt: bool = False, fp_filter: bool = False, runs: int = 1, workers: int = 0, ) -> 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]). render_pdf: if given, the floor IMAGE is rendered from this PDF instead of pdf_path (e.g. a crisp un-flattened vector PDF for sharper glyphs). It must share pdf_path's page order and size so coordinates stay 1:1. """ 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(render_pdf or pdf_path, page_0idx, dpi) img_w, img_h = color_img.size # ── Load from cache if available ────────────────────────────────────────── if cache_path.exists() and not refresh: 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 # ── Set up the detection model + the verify model (Gemini) ─────────────── # Verify/refine always uses Gemini, so we need its client either way. 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) qwen_key = os.environ.get("OPENROUTER_API_KEY", "") if detector == "qwen" and not qwen_key: print("no OPENROUTER_API_KEY — needed for --detector qwen") return color_img, [] def _call_tile(tile_img, x0, y0): if detector == "qwen": return _qwen_call_tile(qwen_key, qwen_model, tile_img, x0, y0, img_w, img_h, known_list, page_num, inclusive=recall_prompt) return _gemini_call_tile(client, genai_types, tile_img, x0, y0, img_w, img_h, known_list, page_num, inclusive=recall_prompt) # ── Tile the image and query each tile ──────────────────────────────────── # Multi-offset consensus: run several passes whose tile boundaries fall in # DIFFERENT places, then union the hits. A unit split across a tile edge in # one pass sits mid-tile in another, so recall goes up. Extra passes cost # more Gemini calls; the verify step still drops false positives. configs = [(tile_size, tile_size // 10)] # pass 1 (baseline grid) if consensus >= 2: configs.append((tile_size, tile_size // 3)) # shifted edges (moderate overlap) if consensus >= 3: configs.append((int(tile_size * 0.75), tile_size // 5)) # different tile size all_hits: list[TagHit] = [] known_list = sorted(known_tags) if known_tags else [] # Tile calls are network-bound (each waits on an API round-trip), so running # them concurrently cuts wall-clock time dramatically WITHOUT changing the # results — same calls, same hits, just not idle between them. Worker count # is capped low by default to stay under the Gemini free-tier rate limit; # override with the HVAC_TILE_WORKERS env var (e.g. 8 on a paid key). if workers <= 0: workers = int(os.environ.get("HVAC_TILE_WORKERS", "4")) workers = max(1, workers) # --runs N: repeat the whole detection N times and UNION the hits. VLM # detection jitters run-to-run (even at temperature 0), so a unit missed in # one run is caught in another — this beats the stochastic "close same-tag # neighbour" misses that a single run (or tile-offset consensus) can't. for run_i in range(max(1, runs)): if runs > 1: print(f" === detection run {run_i+1}/{runs} ===") for p, (ts, ov) in enumerate(configs, start=1): # coords only — crop each tile just-in-time so we never hold all the # large crops in memory at once (consensus passes can be 50+ tiles). coords = _tile_coords(color_img.size, tile_size=ts, overlap=ov) if len(configs) > 1: print(f" consensus pass {p}/{len(configs)} (tile={ts}, overlap={ov}, " f"{len(coords)} tiles)") def _do_tile(args): # Crop just-in-time inside the worker so we only ever hold # `workers` crops in memory at once, not the whole grid. x0, y0, x1, y1 = args try: return _call_tile(color_img.crop((x0, y0, x1, y1)), x0, y0) except Exception as e: # one bad tile shouldn't abort the floor print(f" tile ({x0},{y0}) error: {e}", flush=True) return [] print(f" querying {len(coords)} tiles ({workers} at a time)…", flush=True) done = 0 from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=workers) as ex: for tile_hits in ex.map(_do_tile, coords): done += 1 if tile_hits: all_hits.extend(tile_hits) if done % 10 == 0 or done == len(coords): print(f" {done}/{len(coords)} tiles, " f"{len(all_hits)} hit(s) so far", flush=True) # ── Deduplicate / union across tiles + passes (IOU > 0.3 same tag) ──────── hits = _deduplicate_hits(all_hits, iou_threshold=0.3) # ── Ground boxes on exact OCR'd tag-text positions ─────────────────────── # Gemini knows WHAT is there but its coordinates are approximate (often off # by 50-300 px). For each hit, OCR a small crop around it (at 0°/90°/270° — # plan labels are often rotated) and snap the box to the exact tag text. print(f" snapping {len(hits)} hit(s) to OCR'd tag text…", end=" ", flush=True) snapped: list[TagHit] = [] unsnapped: list[TagHit] = [] for h in hits: s = _local_ocr_snap(color_img, h) (snapped if s is not None else unsnapped).append(s if s is not None else h) print(f"{len(snapped)} snapped, {len(unsnapped)} unsnapped") # Crash-safety: persist the post-snap result NOW (snapped grounded, unsnapped # marked for review) so a crash in the heavy verify loop doesn't lose the # whole floor. Verify overwrites this at the end. _prelim = snapped + [u._replace(fuzzy=True, conf=0.5) for u in unsnapped] _prelim = _merge_nearby_same_tag(_deduplicate_hits(_prelim, 0.3), max_dist=250) cache_path.write_text( json.dumps({"hits": [h._asdict() for h in _prelim], "img_w": img_w, "img_h": img_h}, indent=2), encoding="utf-8") # ── Verify only the uncertain hits via Gemini crop check ───────────────── # Snapped hits are already grounded (tag text verifiably exists there). import gc verified: list[TagHit] = [] if unsnapped: print(f" verifying {len(unsnapped)} unsnapped hit(s)…", end=" ", flush=True) rejected = 0 recovered = 0 for vi, h in enumerate(unsnapped): if vi % 10 == 9: gc.collect() r = _refine_hit_box(client, genai_types, color_img, h) if r is None: rejected += 1 continue # One wide snap at the refined position. The tight radius already # failed in the main snap loop, so go straight to a 1000px search — # recovers units Gemini boxed onto a nearby feature (500-650 px off) # in a single OCR pass instead of three (cuts Tesseract churn 3x). esc = _local_ocr_snap(color_img, r, radius=1000) if esc is not None: # Recovered: tag text WAS found, just offset. conf=0.75 marks # it for a quick human confirm (not fuzzy/yellow). verified.append(esc._replace(conf=0.75)) recovered += 1 else: # Tag text never found at any radius — Gemini's guess only. # Mark fuzzy → YELLOW → likely hallucination, review it. verified.append(r._replace(fuzzy=True, conf=0.5)) print(f"{len(verified)} kept ({recovered} recovered via wide snap), {rejected} rejected") hits = _deduplicate_hits(snapped + verified, iou_threshold=0.3) hits = _merge_nearby_same_tag(hits, max_dist=250) hits = _remove_overlapping_boxes(hits) # ── Precision pass: drop false positives via Qwen+Claude existence vote ── import gc as _gc _gc.collect() # free detection-run memory before fp-filter (OOM guard) if fp_filter and qwen_key: print(f" fp-filter: verifying {sum(1 for h in hits if _review_status(h)!='confirmed')} " f"uncertain box(es) with Qwen+Claude…", end=" ", flush=True) hits = _fp_filter_hits(hits, color_img, qwen_key, qwen_model) hits = _remove_overlapping_boxes(hits) # ── 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 _clean_blueprint_for_ocr(gray: np.ndarray, cutoff: int = 110, line_len: int = 60) -> np.ndarray: """ Prepare a blueprint crop for OCR: 1. Hard threshold — hatching/fill patterns are drawn in GRAY while tag text is BLACK, so a cutoff erases the hatching that Tesseract otherwise reads as 'NN'/'SS' junk. 2. Morphological line removal — long horizontal/vertical strokes (ductwork, unit outlines) are erased so text enclosed inside unit rectangles isn't swallowed as a 'graphic region'. Measured on the 355 E 86th cellar: tags inside hatched/boxed regions go from undetected to conf 40-75. """ _, bw = cv2.threshold(gray, cutoff, 255, cv2.THRESH_BINARY) inv = 255 - bw # ink = white for morphology horiz = cv2.morphologyEx(inv, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (line_len, 1))) vert = cv2.morphologyEx(inv, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (1, line_len))) return 255 - cv2.subtract(inv, cv2.add(horiz, vert)) def _ocr_tag_boxes(gray_img: Image.Image, known_tags: set[str], min_conf: float = 40.0, psms: tuple[int, ...] = (11, 12)) -> list[TagHit]: """ OCR a (small) grayscale image and return exact pixel boxes for every known-tag text occurrence. Input should already be cleaned via _clean_blueprint_for_ocr (adaptive threshold destroys the thin stroked blueprint font — measured: 2 vs 4 tags found on the same region). """ hits: list[TagHit] = [] for psm in psms: try: data = pytesseract.image_to_data( gray_img, output_type=pytesseract.Output.DATAFRAME, config=f"--oem 3 --psm {psm}", ) except Exception as e: logging.debug(f" OCR pass psm={psm} failed: {e}") continue data = data[(data["text"].notna()) & (data["conf"] >= min_conf)].copy() data["text"] = data["text"].astype(str).str.strip() data = data[data["text"] != ""].reset_index(drop=True) # Single tokens: 'AC-D', 'AC-C-1', 'AC-1-14' … for _, row in data.iterrows(): tag = _normalize_tag(str(row["text"])) if tag and tag in known_tags: hits.append(TagHit(tag, int(row["left"]), int(row["top"]), int(row["width"]), int(row["height"]), float(row["conf"]), False)) # Two-token merges ('AC' + 'D'), only when physically adjacent 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): r1, r2 = ds.iloc[i], ds.iloc[i + 1] tag = _normalize_tag(f"{r1['text']}{r2['text']}") if not tag or tag not in known_tags: continue max_h = max(int(r1["height"]), int(r2["height"])) gap = abs(int(r2["left"]) - (int(r1["left"]) + int(r1["width"]))) v_off = abs(int(r1["top"]) - int(r2["top"])) if gap > 3 * max_h or v_off > max_h: continue # tokens too far apart to be one label bx = int(min(r1["left"], r2["left"])) by = int(min(r1["top"], r2["top"])) bw = int(max(r1["left"] + r1["width"], r2["left"] + r2["width"])) - bx bh = int(max(r1["top"] + r1["height"], r2["top"] + r2["height"])) - by hits.append(TagHit(tag, bx, by, max(bw, 10), max(bh, 10), float((r1["conf"] + r2["conf"]) / 2), False)) return _deduplicate_hits(hits, iou_threshold=0.3) def _local_ocr_snap( color_img: Image.Image, hit: TagHit, radius: int = 600, min_conf: float = 30.0, ) -> TagHit | None: """ Ground a Gemini hit on the exact tag-text position via OCR of a small crop centered on the hit. Tag labels on plans are often rotated 90°, so the crop is OCR'd at 0°, 90° and 270°. min_conf is deliberately low: we only accept text that normalizes to the ONE tag we're looking for, so false positives are unlikely even at low confidence. Returns the hit re-centered on the nearest matching text, or None if the tag text isn't found. """ import math W, H = color_img.size cx, cy = hit.x + hit.w // 2, hit.y + hit.h // 2 x0, y0 = max(0, cx - radius), max(0, cy - radius) x1, y1 = min(W, cx + radius), min(H, cy + radius) crop = color_img.crop((x0, y0, x1, y1)) cw, ch = crop.size gray_np = cv2.cvtColor(np.array(crop), cv2.COLOR_RGB2GRAY) gray = Image.fromarray(_clean_blueprint_for_ocr(gray_np)) best: tuple[float, float, float, int, int] | None = None # (dist, ox, oy, ow, oh) for scale in (1, 2): # 2× upscale rescues small/thin tag text if scale == 1: g_img = gray else: g_np = cv2.resize(np.array(gray), None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC) g_img = Image.fromarray(g_np) for rot in (0, 90, 270): img_r = g_img.rotate(rot, expand=True) if rot else g_img for o in _ocr_tag_boxes(img_r, {hit.tag}, min_conf, psms=(11, 12, 6)): bcx = (o.x + o.w / 2) / scale bcy = (o.y + o.h / 2) / scale ow_s, oh_s = o.w / scale, o.h / scale scw, sch = cw, ch # rotation happened in scaled space; centers already unscaled if rot == 0: ox, oy, ow, oh = bcx, bcy, ow_s, oh_s elif rot == 90: # PIL rotates CCW; inverse-map rotated → original ox, oy, ow, oh = scw - 1 - bcy, bcx, oh_s, ow_s else: # rot == 270 ox, oy, ow, oh = bcy, sch - 1 - bcx, oh_s, ow_s d = math.hypot(ox - (cx - x0), oy - (cy - y0)) if best is None or d < best[0]: best = (d, ox, oy, int(ow), int(oh)) if best is not None: break # found at native scale — skip the slower upscaled pass if best is None: return None _, ox, oy, ow, oh = best # Box centered on the exact text location; keep Gemini's size estimate # (it saw the whole unit symbol) but never smaller than text + padding. bw = max(hit.w, int(ow) + 80) bh = max(hit.h, int(oh) + 80) return TagHit(hit.tag, int(x0 + ox - bw / 2), int(y0 + oy - bh / 2), bw, bh, 0.95, False) 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 _merge_nearby_same_tag(hits: list[TagHit], max_dist: int = 250, min_pair_dist: int = 110) -> list[TagHit]: """ Drop same-tag DUPLICATES while PRESERVING genuinely adjacent same-tag units (e.g. two identical units back-to-back on opposite sides of a wall, serving different apartments — common on residential plans). A nearby same-tag hit is treated as a duplicate (dropped) only when it looks like a re-detection of the SAME unit: • it OVERLAPS a kept hit (same unit boxed twice), OR • it is ungrounded/fuzzy (no tag text of its own) and sits within max_dist of a kept hit (a stray body box near a real, labelled one), OR • it is implausibly close (< min_pair_dist) — closer than two real same-size units can physically sit. Two GROUNDED hits (each OCR-snapped to its OWN printed tag) that do NOT overlap and are >= min_pair_dist apart are kept as distinct units. This is what recovers the missed back-to-back twin without re-introducing duplicates elsewhere: a doubly-detected single unit still overlaps (or one copy is ungrounded) and is still dropped. """ import math kept: list[TagHit] = [] # Prefer non-fuzzy (OCR-grounded) hits, then higher confidence for hit in sorted(hits, key=lambda h: (h.fuzzy, -h.conf)): hcx, hcy = hit.x + hit.w / 2, hit.y + hit.h / 2 dup = False for k in kept: if k.tag != hit.tag: continue d = math.hypot(hcx - (k.x + k.w / 2), hcy - (k.y + k.h / 2)) if d >= max_dist: continue if _overlap_frac(hit, k) > 0.15: dup = True; break # same unit boxed twice if d < min_pair_dist: dup = True; break # too close to be two real units if hit.fuzzy or k.fuzzy: dup = True; break # ungrounded body near a real one # else: two grounded, non-overlapping, >= min_pair_dist apart → # two distinct printed tags → keep both (back-to-back units) if not dup: kept.append(hit) return kept def _overlap_frac(a: TagHit, b: TagHit) -> float: """Intersection area as a fraction of the SMALLER box. Unlike IOU this isn't diluted by the union, so it flags partial overlaps (a box mostly covering a smaller one) that IOU misses.""" ix1, iy1 = max(a.x, b.x), max(a.y, b.y) ix2, iy2 = min(a.x + a.w, b.x + b.w), min(a.y + a.h, b.y + b.h) inter = max(0, ix2 - ix1) * max(0, iy2 - iy1) if inter == 0: return 0.0 return inter / max(1, min(a.w * a.h, b.w * b.h)) def _qwen_verify_refine(api_key: str, model: str, color_img: Image.Image, hit: TagHit, radius: int = 500, max_px: int = 1400): """Ask Qwen (conservative + tight grounding) to confirm a unit and tighten its box. Returns: a refined TagHit (present, box tightened) or None (Qwen says it's not a real unit → drop the false positive).""" import base64, json as _json, urllib.request W, H = color_img.size cx, cy = hit.x + hit.w // 2, hit.y + hit.h // 2 x0, y0 = max(0, cx - radius), max(0, cy - radius) x1, y1 = min(W, cx + radius), min(H, cy + radius) crop = color_img.crop((x0, y0, x1, y1)) cw, ch = crop.size scaled, _ = _scale_image_for_api(crop, max_px) sw, sh = scaled.size buf = io.BytesIO(); scaled.save(buf, format="PNG") b64 = base64.b64encode(buf.getvalue()).decode() prompt = ( "This is a zoomed crop of a mechanical HVAC floor plan.\n" f"Is there a REAL HVAC indoor unit here whose printed tag is exactly '{hit.tag}'? " "A real unit is a rectangle/box symbol (usually with internal hatching or " f"coil lines) with '{hit.tag}' printed next to it (label may be rotated 90°). " "Ductwork, diffusers (a letter in a circle like 'D 4B'), duct-size labels " "(e.g. 12X6), grilles (SG/RG/EG), and plain text are NOT units.\n" "If YES, give the TIGHT bounding box around the unit symbol AND its label.\n" 'Return ONLY JSON: {"present": true or false, "xmin":N,"ymin":N,"xmax":N,"ymax":N}\n' "Coordinates in pixels of THIS image. If not present, return {\"present\": false}." ) body = {"model": model, "messages": [{"role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}]}], "max_tokens": 200, "temperature": 0} req = urllib.request.Request( "https://openrouter.ai/api/v1/chat/completions", data=_json.dumps(body).encode(), headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=90) as r: raw = _json.load(r)["choices"][0]["message"]["content"] m = re.search(r"\{.*\}", raw, re.DOTALL) data = _json.loads(m.group(0)) if m else {} except Exception as e: logging.warning(f" Qwen verify error for {hit.tag}: {e}") return hit # network error → keep original (conservative) if not data.get("present", False): return None # Qwen says not a real unit → drop try: xmin, ymin, xmax, ymax = data["xmin"], data["ymin"], data["xmax"], data["ymax"] cmax = max(xmax, ymax) denom = cmax if cmax > 1000 else 1000 # absolute px vs 0-1000 # map back through the scale used for the API image fx, fy = cw / sw, ch / sh nx = x0 + int(xmin / denom * sw * fx) ny = y0 + int(ymin / denom * sh * fy) nw = max(20, int((xmax - xmin) / denom * sw * fx)) nh = max(20, int((ymax - ymin) / denom * sh * fy)) # Cap relocation: a big jump means Qwen latched onto a DIFFERENT unit in # the crop, not a tighter box for this one. Confirm presence but keep the # original position when the move exceeds ~250px. import math as _m if _m.hypot((nx + nw / 2) - (hit.x + hit.w / 2), (ny + nh / 2) - (hit.y + hit.h / 2)) > 250: return hit._replace(conf=0.9, fuzzy=False) return TagHit(hit.tag, nx, ny, nw, nh, 0.9, False) except (KeyError, TypeError, ZeroDivisionError): return hit def _fp_filter_hits(hits: list[TagHit], color_img: Image.Image, qwen_key: str, qwen_model: str = "qwen/qwen2.5-vl-72b-instruct", claude_model: str = "anthropic/claude-sonnet-4.6") -> list[TagHit]: """Precision pass: drop false positives WITHOUT hurting recall. Trusts the grounded (snapped) boxes; for each UNCERTAIN box asks Qwen "is this a unit?", and when Qwen says no, tiebreaks with Claude — dropping only when BOTH conservative models agree it's not a unit. Real units one model fumbles get rescued by the other; Gemini is excluded (it made the detection → biased).""" import gc kept, dropped = [], 0 for vi, h in enumerate(hits): if vi % 8 == 7: gc.collect() if _review_status(h) == "confirmed": kept.append(h) continue q = _qwen_verify_refine(qwen_key, qwen_model, color_img, h) if q is not None: kept.append(q._replace(conf=0.9, fuzzy=False)) continue c = _qwen_verify_refine(qwen_key, claude_model, color_img, h) if c is None: dropped += 1 # Qwen AND Claude agree: not a unit else: kept.append(c._replace(conf=0.9, fuzzy=False)) # Claude rescued it if dropped: print(f" fp-filter: dropped {dropped} false positive(s) " f"(Qwen+Claude agreement)") return kept def _remove_overlapping_boxes(hits: list[TagHit], same_tag_frac: float = 0.15, cross_tag_frac: float = 0.4) -> list[TagHit]: """Non-max suppression on overlapping boxes — keep the higher-quality one (grounded over fuzzy, then higher confidence). Tag-aware: SAME-tag boxes that overlap even a little are almost certainly the same unit detected twice (low threshold); DIFFERENT-tag boxes need a big overlap before we assume a duplicate (so genuinely adjacent distinct units aren't merged).""" kept: list[TagHit] = [] for hit in sorted(hits, key=lambda h: (h.fuzzy, -h.conf)): drop = False for k in kept: thr = same_tag_frac if k.tag == hit.tag else cross_tag_frac if _overlap_frac(hit, k) > thr: drop = True break if not drop: kept.append(hit) return kept 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 _review_status(hit: TagHit) -> str: """Map a hit's confidence/fuzzy flag to a review status label.""" if hit.fuzzy or hit.conf < 0.7: return "review" # yellow — likely hallucination, confirm or delete if hit.conf < 0.9: return "recovered" # orange — found offset via wide snap, quick confirm return "confirmed" # green — OCR-grounded, trust it _STATUS_COLOR = { "confirmed": None, # use tag color "recovered": (255, 140, 0), # orange "review": (230, 220, 40), # yellow } 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) idfont = ImageFont.truetype("arialbd.ttf", 30) except (OSError, IOError): font = ImageFont.load_default() idfont = font for i, hit in enumerate(hits, start=1): status = _review_status(hit) color = _STATUS_COLOR[status] or 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 = f"#{i} {hit.tag}" lx, ly = hit.x, max(0, hit.y - 34) tw = len(label) * 16 draw.rectangle([lx, ly, lx + tw, ly + 32], fill=color) draw.text((lx + 3, ly + 1), label, fill=(255, 255, 255), font=idfont) 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 def write_review_csv( floor_name: str, page_idx: int, hits: list[TagHit], out_dir: Path, ) -> Path: """ Emit a per-floor review sheet. Box #ids match the annotated image. You edit the `action` column: keep (or blank) — accept the box as-is delete — remove it (false positive / hallucination) AC-X — relabel to a different tag Then run: analyze_blueprint.py --apply-review The `status` column is pre-filled so you can focus on non-'confirmed' rows. """ safe = re.sub(r"[^\w]", "_", floor_name) path = out_dir / f"floor_{page_idx:03d}_{safe}_review.csv" with open(path, "w", newline="", encoding="utf-8") as f: w = csv.writer(f) w.writerow(["id", "tag", "status", "action", "x", "y", "w", "h", "page_num", "floor_name"]) for i, h in enumerate(hits, start=1): w.writerow([i, h.tag, _review_status(h), "", h.x, h.y, h.w, h.h, page_idx, floor_name]) return 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, len("Schedule"), len("Detected"), *(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("--schedule-region", type=str, default=None, help="Read ONLY this rectangle of --schedule-page as the schedule, " "as 0-1 fractions 'x0,y0,x1,y1' (set by the GUI's " "'Manually select schedule' tool). Forces a fresh extract.") p.add_argument("--page", type=int, default=None, help="Process ONLY this 1-based PDF page (must be a plan page). " "Use for one-floor-at-a-time runs: detect this floor, review " "it, then move to the next.") p.add_argument("--pages", type=str, default=None, help="Process a RANGE/list of 1-based plan pages in order, e.g. " "'4-24' or '4,6,8' or '4-9,22'. Each floor's outputs are written " "as it finishes, so you can review early floors while later ones " "are still detecting.") p.add_argument("--refresh-schedule", action="store_true", help="Ignore cached schedule and re-extract (calls Gemini again)") p.add_argument("--refresh-detections", action="store_true", help="Ignore cached floor detections and re-detect (calls Gemini again)") p.add_argument("--consensus", type=int, default=1, choices=[1, 2, 3], help="Multi-offset tile consensus passes (2-3) to raise recall on " "units that fall on tile boundaries. Costs N× the Gemini calls.") p.add_argument("--tile-size", type=int, default=3000, help="Tile size in px (default 3000). Smaller (e.g. 1800) = finer " "spatial resolution so small/faint units stay larger to the " "model — better recall on tiny units, more tiles/cost.") p.add_argument("--render-pdf", type=Path, default=None, help="Render floor images from this (crisp/un-flattened) PDF " "instead of the main PDF. Must share page order + size.") p.add_argument("--detector", choices=["gemini", "qwen"], default="gemini", help="Which vision model finds the units (verify always uses " "Gemini). Qwen runs via OpenRouter.") p.add_argument("--qwen-model", default="qwen/qwen2.5-vl-72b-instruct", help="OpenRouter model id for --detector qwen") p.add_argument("--recall-prompt", action="store_true", help="Use the inclusive recall-first detection prompt (be " "inclusive; the verify step removes false positives)") p.add_argument("--fp-filter", action="store_true", help="Precision pass: drop false positives via a Qwen+Claude " "existence vote on uncertain boxes (needs OPENROUTER_API_KEY)") p.add_argument("--all-tags", action="store_true", help="Search EVERY schedule tag incl. qty=0 (schedule counts are " "unreliable; fp-filter + reconcile_schedule.py handle precision)") p.add_argument("--runs", type=int, default=1, help="Run the whole detection N times and UNION the hits. Beats " "run-to-run VLM jitter (stochastic close same-tag misses). " "Costs N× the detection calls.") 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("--reclassify", action="store_true", help="Rebuild pages_manifest.csv instead of reusing the cached one") p.add_argument("--classify-only", action="store_true", help="Extract schedule + classify pages + write pages_manifest.csv, " "then stop (no detection). Used by the GUI to list floors.") p.add_argument("--apply-review", action="store_true", help="Ingest edited floor_*_review.csv files in --out-dir: apply " "keep/delete/relabel actions, rewrite detection caches + YOLO " "labels, and append corrections to corrections_log.csv") return p.parse_args() # ───────────────────────────────────────────────────────────────────────────── # Human-in-the-loop review ingestion (--apply-review) # ───────────────────────────────────────────────────────────────────────────── def apply_review(out_dir: Path, pdf_path: Path, dpi: int, save_yolo: bool = True) -> None: """ Read every floor_*_review.csv in out_dir, apply the human-entered `action` column, and rewrite that floor's detection cache, annotated image, and YOLO labels. Every change is appended to out_dir/corrections_log.csv — the evidence trail of what the detector got wrong, for later tuning / YOLO data. action column values (case-insensitive): ''/keep accept the box as-is (status promoted to confirmed) delete/no/x drop the box (false positive) AC-X relabel to that tag (and keep) """ import json review_files = sorted(out_dir.glob("floor_*_review.csv")) if not review_files: print(f" No floor_*_review.csv files found in {out_dir}.") return log_path = out_dir / "corrections_log.csv" new_log = not log_path.exists() log_f = open(log_path, "a", newline="", encoding="utf-8") log_w = csv.writer(log_f) if new_log: log_w.writerow(["page_num", "floor_name", "id", "tag", "old_status", "action", "result", "x", "y", "w", "h"]) grand_kept = grand_deleted = grand_relabeled = grand_added = 0 for rf in review_files: rows = list(csv.DictReader(open(rf, encoding="utf-8"))) if not rows: continue page_num = int(rows[0]["page_num"]) floor_name = rows[0]["floor_name"] kept: list[TagHit] = [] n_del = n_relabel = n_added = 0 for r in rows: action = (r.get("action") or "").strip().lower() tag = r["tag"] old_status = r.get("status", "") if old_status == "added": n_added += 1 hit = TagHit(tag, int(r["x"]), int(r["y"]), int(r["w"]), int(r["h"]), 0.99, False) # human-confirmed → top confidence, not fuzzy if action in ("delete", "del", "no", "x", "remove"): n_del += 1 log_w.writerow([page_num, floor_name, r["id"], tag, old_status, action, "deleted", r["x"], r["y"], r["w"], r["h"]]) continue result = "kept" new_tag = _normalize_tag(action) if action else None if new_tag and new_tag != tag: hit = hit._replace(tag=new_tag) n_relabel += 1 result = f"relabeled {tag}->{new_tag}" kept.append(hit) # Only log rows the human actually touched or that weren't confirmed if action or old_status != "confirmed": log_w.writerow([page_num, floor_name, r["id"], hit.tag, old_status, action or "keep", result, hit.x, hit.y, hit.w, hit.h]) grand_kept += len(kept) grand_deleted += n_del grand_relabeled += n_relabel grand_added += n_added # Rewrite detection cache for this floor color_img = _render_page(pdf_path, page_num - 1, dpi) img_w, img_h = color_img.size cache_path = _detection_cache_path(out_dir, page_num, floor_name) cache_path.write_text( json.dumps({"hits": [h._asdict() for h in kept], "img_w": img_w, "img_h": img_h}, indent=2), encoding="utf-8", ) # Redraw annotated image (all green now — human-confirmed) tag_colors = _build_color_map(sorted({h.tag for h in kept}) or ["AC-A"]) annotate_and_save(floor_name, page_num, color_img, kept, out_dir, tag_colors) if save_yolo and kept: _save_yolo_labels(pdf_path, page_num, color_img, kept, img_w, img_h) print(f" {rf.name}: {len(kept)} kept ({n_added} added), " f"{n_del} deleted, {n_relabel} relabeled") log_f.close() print(f"\n Totals: {grand_kept} kept ({grand_added} of them newly added by you), " f"{grand_deleted} deleted, {grand_relabeled} relabeled " f"across {len(review_files)} floor(s).") print(f" Corrections logged to: {log_path}") print(f" Detection caches + YOLO labels updated with your corrections.") 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) # ── Apply-review mode: ingest human corrections, then exit ──────────────── if args.apply_review: print(f"\n{'='*60}") print(f" APPLY REVIEW — ingesting corrections from {args.out_dir}") print(f"{'='*60}\n") apply_review(args.out_dir, args.pdf, args.dpi, save_yolo=not args.no_yolo) return # ── Checkpoint 1: Schedule extraction ──────────────────────────────────── print(f"\n{'='*60}") print(f" CHECKPOINT 1 — Extracting equipment schedule") print(f"{'='*60}") print(f" PDF : {args.pdf}") print() _region = None if args.schedule_region: try: _region = tuple(float(v) for v in args.schedule_region.split(",")) assert len(_region) == 4 except Exception: print(f" [WARNING] bad --schedule-region '{args.schedule_region}' — ignoring") _region = None schedule_tags = extract_schedule(args.pdf, args.dpi, args.schedule_page, out_dir=args.out_dir, refresh=args.refresh_schedule, region=_region) 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)" model_str = info.get("model_number") or "" company_str = info.get("company") or "" extra = "" if company_str or model_str: extra = f" [{' '.join(filter(None, [company_str, model_str]))}]" print(f" {tag:6s} qty={qty_str:>3} {utype}{extra}") 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") import csv manifest_path = args.out_dir / "pages_manifest.csv" # Reuse a cached manifest from a prior run of this blueprint (classification # is slow — it OCRs every page title — and never changes for a given PDF). if manifest_path.exists() and not args.reclassify: with open(manifest_path, newline="", encoding="utf-8") as f: page_manifest = [ {"page_num": int(r["page_num"]), "page_type": r["page_type"], "floor_name": r["floor_name"], "title": r["title"]} for r in csv.DictReader(f) ] print(f" Loaded cached page manifest: {manifest_path}") print(f" (use --reclassify to rebuild it)") else: page_manifest = classify_pages(args.pdf) 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}") plan_pages = [p for p in page_manifest if p["page_type"] == "plan"] 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.") if args.classify_only: print(f" --classify-only: {len(plan_pages)} plan page(s) listed. Stopping.") return if not plan_pages: logging.error("No plan pages found. Cannot continue.") sys.exit(1) # ── --page / --pages: restrict to specific plan pages ──────────────────── selected: list[int] | None = None if args.page is not None: selected = [args.page] elif args.pages: selected = [] for part in args.pages.split(","): part = part.strip() if "-" in part: lo, hi = part.split("-", 1) selected.extend(range(int(lo), int(hi) + 1)) elif part: selected.append(int(part)) if selected is not None: plan_by_num = {p["page_num"]: p for p in plan_pages} bad = [n for n in selected if n not in plan_by_num] if bad: plan_nums = ", ".join(str(p["page_num"]) for p in plan_pages) logging.error(f"Page(s) {bad} are not plan pages. Plan pages are: {plan_nums}") sys.exit(1) # preserve requested order, de-duplicated seen: set[int] = set() plan_pages = [plan_by_num[n] for n in selected if not (n in seen or seen.add(n))] names = ", ".join(f"{p['page_num']}={p['floor_name']}" for p in plan_pages) print(f"\n Processing {len(plan_pages)} selected floor(s): {names}") 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 ───────────────────────────────────────── # By default consider only tags with non-zero scheduled quantity (drops # false-positive tags). --all-tags searches EVERY schedule tag — the schedule # counts are unreliable (e.g. AC-B listed qty 0 but real units exist), so the # fp-filter handles precision and the schedule-reconcile step flags conflicts. if args.all_tags: known_tags = set(schedule_tags.keys()) print(f" --all-tags: searching all {len(known_tags)} schedule tag(s), " f"including qty=0 (fp-filter + reconcile handle precision)") else: 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()) 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) try: color_img, hits = gemini_detect_floor_page( args.pdf, page_0, args.dpi, known_tags, args.out_dir, entry["page_num"], floor_name, save_yolo=not args.no_yolo, tile_size=args.tile_size, refresh=args.refresh_detections, consensus=args.consensus, render_pdf=args.render_pdf, detector=args.detector, qwen_model=args.qwen_model, recall_prompt=args.recall_prompt, fp_filter=args.fp_filter, runs=args.runs, ) 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, args.out_dir, tag_colors ) review_path = write_review_csv( floor_name, entry["page_num"], hits, args.out_dir ) tag_summary = ", ".join( f"{t}×{len(floor_results[floor_name][t])}" for t in sorted(floor_results[floor_name]) ) n_review = sum(1 for h in hits if _review_status(h) != "confirmed") print(f"done -> {tag_summary or 'no tags found'}") print(f" Annotated image: {out_path}") print(f" Review sheet: {review_path}" f" ({n_review} box(es) need review)" if n_review else f" Review sheet: {review_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) try: color_img, hits = gemini_detect_floor_page( args.pdf, page_0, args.dpi, known_tags, args.out_dir, entry["page_num"], floor_name, save_yolo=not args.no_yolo, tile_size=args.tile_size, refresh=args.refresh_detections, consensus=args.consensus, render_pdf=args.render_pdf, detector=args.detector, qwen_model=args.qwen_model, recall_prompt=args.recall_prompt, fp_filter=args.fp_filter, runs=args.runs, ) 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, args.out_dir, tag_colors ) write_review_csv(floor_name, entry["page_num"], hits, args.out_dir) 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()