hvac_fable / python_files /read_mechanical_plansvs1.3.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
6.15 kB
from __future__ import annotations
import argparse
import re
from pathlib import Path
import fitz
import pandas as pd
import pdfplumber
import pytesseract
DRAWING_TITLE_PATTERN = re.compile(r"DRAWING\s*TITLE\s*[:\-]?\s*(.*)", re.IGNORECASE)
TAG_PATTERN = re.compile(r"\bAC[-\s]?[A-U]\b", re.IGNORECASE)
INT_PATTERN = re.compile(r"\b\d{1,2}\b")
def extract_explicit_title(text: str) -> str | None:
if not text:
return None
lines = [l.strip() for l 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 next_line in lines[i + 1 : i + 6]:
if next_line:
return next_line.strip()
return None
def extract_mechanical_title_heuristic(text: str) -> str | None:
if not text:
return None
lines = [l.strip() for l in text.split("\n") if l.strip()]
bottom_lines = lines[int(len(lines) * 0.7) :]
keywords = ["MECHANICAL", "HVAC", "AIR", "RISER", "DIAGRAM", "PLAN", "SCHEDULE", "DETAIL", "SECTION"]
for line in bottom_lines:
upper = line.upper()
if 8 < len(line) < 120 and any(k in upper for k in keywords):
return line.strip()
return None
def extract_page_title(text: str) -> tuple[str | None, str]:
title = extract_explicit_title(text)
if title:
return title, "explicit"
title = extract_mechanical_title_heuristic(text)
if title:
return title, "heuristic"
return None, "missing"
def classify_page_context(title: str | None, text: str) -> str:
t = (title or "").upper()
x = text.upper()
blob = f"{t}\n{x}"
if "INDOOR UNIT SCHEDULE" in blob or "SCHEDULE" in t:
return "schedule"
if "PLAN" in blob or "FLOOR" in blob or "LEVEL" in blob:
return "plan"
if "DETAIL" in blob or "SECTION" in blob or "RISER" in blob:
return "detail"
if "NOTE" in blob:
return "notes"
return "other"
def normalize_tag(raw: str) -> str:
t = raw.upper().replace(" ", "-")
if "-" not in t and len(t) == 3 and t.startswith("AC"):
t = f"AC-{t[-1]}"
return t
def parse_schedule_lines(lines: list[str], page_num: int) -> list[dict]:
rows: list[dict] = []
for line in lines:
m = TAG_PATTERN.search(line)
if not m:
continue
tag = normalize_tag(m.group(0))
nums = [int(v) for v in INT_PATTERN.findall(line)]
qty = ""
for n in nums:
if 0 <= n <= 50:
qty = n
break
u = line.upper()
if "CEILING" in u and "DUCT" in u:
unit_type = "Ceiling Concealed Ducted Unit"
elif "WALL" in u and "MOUNT" in u:
unit_type = "Wall Mounted"
else:
unit_type = ""
rows.append(
{
"page_num": page_num,
"tag": tag,
"qty_required": qty,
"unit_type": unit_type,
"source_line": line.strip(),
}
)
return rows
def ocr_page_from_pdf(pdf_path: Path, page_num_1based: int, dpi: int) -> str:
doc = fitz.open(pdf_path)
page = doc.load_page(page_num_1based - 1)
mat = fitz.Matrix(dpi / 72.0, dpi / 72.0)
pix = page.get_pixmap(matrix=mat, alpha=False)
text = pytesseract.image_to_string(pix.tobytes("png"), config="--oem 3 --psm 6")
return text.strip()
def scan_pdf(pdf_path: Path, out_prefix: str | None, dpi: int) -> tuple[Path, Path]:
pages_out = []
schedule_rows = []
with pdfplumber.open(pdf_path) as pdf:
total_pages = len(pdf.pages)
for page_num, page in enumerate(pdf.pages, start=1):
raw_text = page.extract_text() or ""
text_source = "pdf_text"
if len(raw_text.strip()) < 80:
raw_text = ocr_page_from_pdf(pdf_path, page_num, dpi=dpi)
text_source = "ocr"
title, title_source = extract_page_title(raw_text)
context = classify_page_context(title, raw_text)
pages_out.append(
{
"page_num": page_num,
"total_pages": total_pages,
"text_source": text_source,
"page_title": title or "",
"title_source": title_source,
"page_context": context,
"raw_text": raw_text,
}
)
if context == "schedule" or "INDOOR UNIT SCHEDULE" in raw_text.upper():
lines = [ln for ln in raw_text.splitlines() if ln.strip()]
schedule_rows.extend(parse_schedule_lines(lines, page_num))
pages_df = pd.DataFrame(pages_out)
sched_df = pd.DataFrame(schedule_rows).drop_duplicates(subset=["tag"], keep="first")
base_name = out_prefix or pdf_path.stem
out_dir = pdf_path.parent
pages_csv = out_dir / f"{base_name}_pages_context.csv"
schedule_csv = out_dir / f"{base_name}_schedule_detected.csv"
pages_df.drop(columns=["raw_text"]).to_csv(pages_csv, index=False)
sched_df.to_csv(schedule_csv, index=False)
return pages_csv, schedule_csv
def main() -> None:
parser = argparse.ArgumentParser(description="Scan mechanical blueprint PDF: OCR fallback, title/context labels, schedule extraction.")
parser.add_argument("--pdf", type=Path, required=True, help="Input blueprint PDF path.")
parser.add_argument("--dpi", type=int, default=300, help="OCR render DPI for low-text pages.")
parser.add_argument("--out-prefix", type=str, default=None, help="Output filename prefix.")
args = parser.parse_args()
if not args.pdf.exists():
raise FileNotFoundError(f"PDF not found: {args.pdf}")
pages_csv, schedule_csv = scan_pdf(args.pdf, args.out_prefix, args.dpi)
print(f"Wrote page context file: {pages_csv}")
print(f"Wrote schedule extraction file: {schedule_csv}")
if __name__ == "__main__":
main()