File size: 10,360 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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