File size: 6,153 Bytes
dac3297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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()