hvac_fable / python_files /read_mechanical_plansvs1.4.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
9.55 kB
from __future__ import annotations
import argparse
import re
from io import BytesIO
from pathlib import Path
import fitz
import pandas as pd
import pdfplumber
import pytesseract
from PIL import Image
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")
TAG_LOOSE_PATTERN = re.compile(r"\bA\s*C\s*[-]?\s*([A-U])\b", re.IGNORECASE)
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 ocr_schedule_lines_from_pdf(pdf_path: Path, page_num_1based: int, dpi: int) -> list[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)
pil_img = Image.open(BytesIO(pix.tobytes("png")))
lines = []
for psm in (6, 11, 12):
txt = pytesseract.image_to_string(pil_img, config=f"--oem 3 --psm {psm}")
lines.extend([ln.strip() for ln in txt.splitlines() if ln.strip()])
return lines
def parse_schedule_lines_robust(lines: list[str], page_num: int) -> list[dict]:
rows: list[dict] = []
seen = set()
for line in lines:
upper = line.upper()
tag = None
m_strict = TAG_PATTERN.search(upper)
if m_strict:
tag = normalize_tag(m_strict.group(0))
else:
m_loose = TAG_LOOSE_PATTERN.search(upper)
if m_loose:
tag = f"AC-{m_loose.group(1).upper()}"
else:
# OCR variants like ACCO / ACDO / AC-E|
m_var = re.search(r"\bAC[-\s]?([A-U])\w*\b", upper)
if m_var:
tag = f"AC-{m_var.group(1).upper()}"
if not tag:
continue
nums = [int(v) for v in INT_PATTERN.findall(line)]
qty = ""
for n in nums:
if 0 <= n <= 50:
qty = n
break
if "CEILING" in upper and "DUCT" in upper:
unit_type = "Ceiling Concealed Ducted Unit"
elif "WALL" in upper and "MOUNT" in upper:
unit_type = "Wall Mounted"
else:
unit_type = ""
key = (tag, str(qty), unit_type)
if key in seen:
continue
seen.add(key)
rows.append(
{
"page_num": page_num,
"tag": tag,
"qty_required": qty,
"unit_type": unit_type,
"source_line": line.strip(),
}
)
# prefer rows with qty/unit_type when duplicate tags appear
if not rows:
return rows
df = pd.DataFrame(rows)
df["score"] = df["qty_required"].apply(lambda x: 1 if str(x) != "" else 0) + df["unit_type"].apply(lambda x: 1 if x else 0)
df = df.sort_values(["tag", "score"], ascending=[True, False]).drop_duplicates(subset=["tag"], keep="first")
return df.drop(columns=["score"]).to_dict(orient="records")
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()]
strict_rows = parse_schedule_lines(lines, page_num)
schedule_rows.extend(strict_rows)
# OCR assist pass for schedule pages (especially flattened PDFs)
ocr_lines = ocr_schedule_lines_from_pdf(pdf_path, page_num, dpi=max(dpi, 350))
robust_rows = parse_schedule_lines_robust(ocr_lines, page_num)
schedule_rows.extend(robust_rows)
pages_df = pd.DataFrame(pages_out)
sched_columns = ["page_num", "tag", "qty_required", "unit_type", "source_line"]
if schedule_rows:
sched_df = pd.DataFrame(schedule_rows)
sched_df["score"] = sched_df["qty_required"].apply(lambda x: 1 if str(x) != "" else 0) + sched_df["unit_type"].apply(lambda x: 1 if x else 0)
sched_df = sched_df.sort_values(["tag", "score"], ascending=[True, False]).drop_duplicates(subset=["tag"], keep="first")
sched_df = sched_df.drop(columns=["score"])
else:
sched_df = pd.DataFrame(columns=sched_columns)
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()