hvac_fable / python_files /read_mechanical_plans.py
Rachel7's picture
Deploy Fable B-test analyzer
dac3297 verified
Raw History Blame Contribute Delete
10.4 kB
from pdf2image import convert_from_path
#read pdf
blueprint_file = 'C:/Users/ruchy/Downloads/2023 02 07-147-35 95th MECHANICAL.pdf'
import pdfplumber
import pandas as pd
import pytesseract
#blueprint_file = r"C:/Users/ruchy/Downloads/355 E 86th St Mechanical 100% CD Set.pdf"
def ocr_page_fast(pdf_path, page_number, dpi=150):
images = convert_from_path(
pdf_path,
first_page=page_number,
last_page=page_number,
dpi=dpi
)
text = pytesseract.image_to_string(
images[0],
config="--psm 6"
)
return text.strip()
def ocr_page_hq(pdf_path, page_number, dpi=300):
images = convert_from_path(
pdf_path,
first_page=page_number,
last_page=page_number,
dpi=dpi
)
return pytesseract.image_to_string(
images[0],
config="--psm 6"
).strip()
rows = []
with pdfplumber.open(blueprint_file) as pdf:
total_pages = len(pdf.pages)
print(total_pages)
for i, page in enumerate(pdf.pages, start=1):
print(i)
text = page.extract_text() or ""
# Normal extraction failed → try FAST OCR
if len(text.strip()) < 50:
print(f"Trying fast OCR on page {i}")
text = ocr_page_fast(blueprint_file, i)
# Fast OCR still junk → try HQ OCR
if len(text) < 50:
print(f"Escalating to HQ OCR on page {i}")
text = ocr_page_hq(blueprint_file, i)
print(text)
rows.append({
"page_num": i,
"raw_text": text
})
df = pd.DataFrame(rows)
df["total_pages"] = total_pages
import re
DRAWING_TITLE_PATTERN = re.compile(
r"DRAWING\s*TITLE\s*[:\-]?\s*(.*)",
re.IGNORECASE
)
def extract_explicit_title(text):
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):
# Case 1: title on same line
remainder = re.sub(r"DRAWING\s*TITLE\s*[:\-]?\s*", "", line, flags=re.IGNORECASE)
if remainder:
return remainder.strip()
# Case 2: title on next non-empty line
for next_line in lines[i + 1 : i + 5]:
if next_line:
return next_line.strip()
return None
def extract_heuristic_title(text):
if not text:
return None
lines = [l.strip() for l in text.split("\n") if l.strip()]
candidates = []
for line in lines[:20]:
if (
len(line) < 80
and sum(c.isupper() for c in line) / max(len(line), 1) > 0.6
):
candidates.append(line)
return candidates[0] if candidates else None
def extract_page_title(text):
# 1️⃣ Explicit "DRAWING TITLE" (highest confidence)
title = extract_explicit_title(text)
if title:
return title, "explicit"
# 2️⃣ Heuristic fallback
title = extract_heuristic_title(text)
if title:
return title, "heuristic"
# 3️⃣ Nothing found
return None, "missing"
titles = []
sources = []
for txt in df["raw_text"]:
title, source = extract_page_title(txt)
titles.append(title)
sources.append(source)
df["page_title"] = titles
df["title_source"] = sources
df["title_found"] = df["page_title"].notna()
########################################333
from google import genai
import json
import os
# set key once (or use env var)
os.environ["GEMINI_API_KEY"] = "AIzaSyDjlIDneBe-e2pdjGKH7OWGTyvp45e-ZjQ"
client = genai.Client()
def build_title_validation_prompt(titles):
titles_text = "\n".join(
[f"{i}. {t}" for i, t in enumerate(titles)]
)
return f"""
You are reviewing drawing titles from a mechanical plan set.
Identify titles that are clearly INVALID.
Rules:
- Invalid titles are placeholders, empty labels, or non-descriptive items
(examples: "DOB :", "", "N/A").
- Do NOT flag real drawing titles.
- Be conservative: only obvious errors.
- Do NOT rewrite titles.
Return JSON ONLY in this format:
{{
"invalid_titles": [
{{
"index": 24,
"title": "DOB :",
"reason": "placeholder title"
}}
]
}}
Titles:
{titles_text}
"""
def find_invalid_titles(titles):
output = []
prompt = build_title_validation_prompt(titles)
response = client.models.generate_content(
model="models/gemini-2.5-flash",
contents=prompt
)
raw = response.text.strip()
try:
return json.loads(raw)
except json.JSONDecodeError:
print("Model returned invalid JSON:")
print(raw)
#return {"invalid_titles": []}
output.append(raw)
#for item in invalid_items:
# idx = item["index"]
# bad_title = item["title"]
# reason = item.get("reason", "")
# Pull raw_text from your dataframe
# raw_text = df.loc[df.index[idx], "raw_text"]
# output.append({
# "index": idx,
# "bad_title": bad_title,
# "reason": reason,
# "raw_text": raw_text
# })
return output
result = find_invalid_titles(titles)
print(result)
#get first thing from result
# If result is a list with the JSON dictionary as the first element
# Suppose result[0] is the string returned by your model
json_str = result[0]
try:
# Sometimes model adds extra text around JSON, so extract curly braces
start = json_str.find("{")
end = json_str.rfind("}") + 1
clean_json_str = json_str[start:end]
json_dict = json.loads(clean_json_str)
except (json.JSONDecodeError, AttributeError):
print("Invalid JSON from model:")
print(json_str)
json_dict = {"invalid_titles": []}
# Now safely access invalid titles
invalid_titles = json_dict.get("invalid_titles", [])
index = []
# Pull raw_text for each invalid title
for item in invalid_titles:
index.append(item["index"])
title = item["title"]
reason = item["reason"]
raw_text = df.loc[index, "raw_text"] # get raw text from DataFrame
print(f"Index: {index}, Title: {title}, Reason: {reason}")
print(f"Raw text (first 500 chars): {raw_text[:500]}...\n")
#now get raw text from df corrosponding to index
# Build dictionary mapping index -> raw_text
invalid_raw_text = {idx: df.loc[idx, "raw_text"] for idx in index}
# Suppose invalid_raw_text is your dictionary: {index -> raw_text}
def fix_invalid_titles(invalid_raw_text):
results = []
for idx, raw_text in invalid_raw_text.items():
# Build a prompt specifically for this page
prompt = f"""
You are reviewing an architectural blueprint page.
The previously extracted title was flagged as incorrect.
Here is the full text of the page:
\"\"\"
{raw_text}
\"\"\"
Please provide the most likely correct drawing title from this page.
Respond only with JSON in the following format:
{{
"index": {idx},
"correct_title": "<the corrected title>"
}}
"""
# Call the model
response = client.models.generate_content(
model="models/gemini-2.5-flash",
contents=prompt
)
# Try to parse the JSON returned by the model
raw = response.text.strip()
try:
start = raw.find("{")
end = raw.rfind("}") + 1
clean_json_str = raw[start:end]
corrected = json.loads(clean_json_str)
corrected["index"] = idx
results.append(corrected)
except json.JSONDecodeError:
print(f"Invalid JSON for index {idx}:")
print(raw)
results.append(raw)
return results
# Run second-pass correction
corrected_titles = fix_invalid_titles(invalid_raw_text)
# Write back corrected titles
for item in corrected_titles:
idx = item["index"] # index in the array
title = item["correct_title"] # corrected title
df.at[idx, "page_title"] = title
#new df only page_num and page_title
new_df = df[["page_num", "page_title"]]
new_df.to_csv("pages.csv", index=False)
def classify_page(title):
if not title:
return "unknown"
t = title.upper()
if "SCHEDULE" in t:
return "schedule"
if "PLAN" in t or "LEVEL" in t or "FLOOR" in t:
return "plan"
if "DETAIL" in t or "SECTION" in t:
return "detail"
if "INDEX" in t or "DRAWING LIST" in t:
return "index"
return "other"
def position_hint(page_num, total_pages):
if page_num > total_pages * 0.7:
return "late"
if page_num < total_pages * 0.3:
return "early"
return "middle"
def refine_classification(row, total_pages):
pos = position_hint(row.page_num, total_pages)
if row.page_type == "unknown":
if pos == "late":
return "schedule_or_detail"
if pos == "early":
return "plan"
return row.page_type
import re
FLOOR_PATTERN = re.compile(
r"(LEVEL|FLOOR|ROOF|BASEMENT)\s*(\d+)?",
re.IGNORECASE
)
def extract_floor(title):
if not title:
return None
match = FLOOR_PATTERN.search(title)
return match.group(0).upper() if match else None
def find_schedule_pages(pdf_path):
schedule_pages = []
with pdfplumber.open(pdf_path) as pdf:
for i, page in enumerate(pdf.pages):
text = page.extract_text() or ""
if "SCHEDULE" in text.upper():
schedule_pages.append(i)
return schedule_pages
def extract_tables(pdf_path, page_num):
with pdfplumber.open(pdf_path) as pdf:
page = pdf.pages[page_num]
tables = page.extract_tables()
return tables
def pdf_to_images(pdf_path, out_dir):
pages = convert_from_path(pdf_path, dpi=300)
paths = []
for i, page in enumerate(pages, 1):
path = f"{out_dir}/page_{i}.png"
page.save(path, "PNG")
paths.append(path)
return paths