Marthee commited on
Commit
5aa9ee2
·
verified ·
1 Parent(s): 56153ad

Update InitialMarkups.py

Browse files
Files changed (1) hide show
  1. InitialMarkups.py +399 -1
InitialMarkups.py CHANGED
@@ -8,7 +8,9 @@ Original file is located at
8
  """
9
  baselink='https://findconsole-initialmarkups.hf.space/view-pdf?'
10
 
11
-
 
 
12
 
13
  from io import BytesIO
14
  import re
@@ -26,6 +28,13 @@ from collections import defaultdict, Counter
26
  import difflib
27
  from fuzzywuzzy import fuzz
28
 
 
 
 
 
 
 
 
29
  def get_regular_font_size_and_color(doc):
30
  font_sizes = []
31
  colors = []
@@ -203,6 +212,7 @@ def extract_headers(doc, toc_pages, most_common_font_size, most_common_color, mo
203
 
204
  # Get the smallest font size among valid ones
205
  smallest_font_size = min(valid_font_sizes) if valid_font_sizes else None
 
206
  return headers, top_3_font_sizes, smallest_font_size, spans
207
 
208
  def is_numbered(text):
@@ -1028,3 +1038,391 @@ def extract_section_under_header(pdf_path):
1028
  docHighlights.save(pdf_bytes)
1029
  print('JSONN',json_output)
1030
  return pdf_bytes.getvalue(), docHighlights , json_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  """
9
  baselink='https://findconsole-initialmarkups.hf.space/view-pdf?'
10
 
11
+ newlink='https://findconsole-initialmarkups.hf.space/view-highlight?'
12
+
13
+
14
 
15
  from io import BytesIO
16
  import re
 
28
  import difflib
29
  from fuzzywuzzy import fuzz
30
 
31
+ def filteredJsons(pdf_path,filteredjsonsfromrawan):
32
+ # for heading in subjects:
33
+ extract_section_under_headerRawan (pdf_path=pdf_path,listofheadingsfromrawan=filteredjsonsfromrawan)
34
+
35
+
36
+
37
+
38
  def get_regular_font_size_and_color(doc):
39
  font_sizes = []
40
  colors = []
 
212
 
213
  # Get the smallest font size among valid ones
214
  smallest_font_size = min(valid_font_sizes) if valid_font_sizes else None
215
+
216
  return headers, top_3_font_sizes, smallest_font_size, spans
217
 
218
  def is_numbered(text):
 
1038
  docHighlights.save(pdf_bytes)
1039
  print('JSONN',json_output)
1040
  return pdf_bytes.getvalue(), docHighlights , json_output
1041
+
1042
+
1043
+
1044
+
1045
+ def extract_section_under_headerRawan(pdf_path,headingjson,pagenum=0,incomingheader=0):
1046
+ top_margin = 70
1047
+ bottom_margin = 50
1048
+ # Optimized URL handling
1049
+ if pdf_path and ('http' in pdf_path or 'dropbox' in pdf_path):
1050
+ pdf_path = pdf_path.replace('dl=0', 'dl=1')
1051
+
1052
+ # Cache frequently used values
1053
+ response = requests.get(pdf_path)
1054
+ pdf_content = BytesIO(response.content)
1055
+ if not pdf_content:
1056
+ raise ValueError("No valid PDF content found.")
1057
+
1058
+ doc = fitz.open(stream=pdf_content, filetype="pdf")
1059
+ docHighlights = fitz.open(stream=pdf_content, filetype="pdf")
1060
+ most_common_font_size, most_common_color, most_common_font = get_regular_font_size_and_color(doc)
1061
+
1062
+ # Precompute regex patterns
1063
+ dot_pattern = re.compile(r'\.{3,}')
1064
+ url_pattern = re.compile(r'https?://\S+|www\.\S+')
1065
+
1066
+ def get_toc_page_numbers(doc, max_pages_to_check=15):
1067
+ toc_pages = []
1068
+ for page_num in range(min(len(doc), max_pages_to_check)):
1069
+ page = doc.load_page(page_num)
1070
+ blocks = page.get_text("dict")["blocks"]
1071
+
1072
+ dot_line_count = 0
1073
+ for block in blocks:
1074
+ for line in block.get("lines", []):
1075
+ line_text = get_spaced_text_from_spans(line["spans"]).strip()
1076
+ if dot_pattern.search(line_text):
1077
+ dot_line_count += 1
1078
+
1079
+ if dot_line_count >= 3:
1080
+ toc_pages.append(page_num)
1081
+
1082
+ return list(range(0, toc_pages[-1] +1)) if toc_pages else toc_pages
1083
+
1084
+ toc_pages = get_toc_page_numbers(doc)
1085
+
1086
+ headers, top_3_font_sizes, smallest_font_size, headersSpans = extract_headers(
1087
+ doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin
1088
+ )
1089
+
1090
+ listofheadingsfromrawan=[]
1091
+ if type(headingjson) == str:
1092
+ listofheadingsfromrawan.append(headingjson)
1093
+ headingjson=[headingjson]
1094
+ else:
1095
+ for item in headingjson:
1096
+ listofheadingsfromrawan.append(normalize_text(item['Subject']))
1097
+ print('hereeeeeeeeeeeeeee0',listofheadingsfromrawan)
1098
+ # Precompute all children headers once
1099
+ allchildrenheaders = listofheadingsfromrawan
1100
+ print('hereeeeeeeeeeeeeee00',allchildrenheaders)
1101
+ allchildrenheaders_set = set(allchildrenheaders) # For faster lookups
1102
+
1103
+ df = pd.DataFrame(columns=["NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2"])
1104
+ data_list_JSON = []
1105
+
1106
+ if len(top_3_font_sizes)==3:
1107
+ mainHeaderFontSize, subHeaderFontSize, subsubheaderFontSize = top_3_font_sizes
1108
+ elif len(top_3_font_sizes)==2:
1109
+ mainHeaderFontSize= top_3_font_sizes[0]
1110
+ subHeaderFontSize= top_3_font_sizes[1]
1111
+ subsubheaderFontSize= top_3_font_sizes[1]
1112
+
1113
+ print("📌 Has TOC:", bool(toc_pages), " | Pages to skip:", toc_pages)
1114
+
1115
+ # Preload all pages to avoid repeated loading
1116
+ # pages = [doc.load_page(page_num) for page_num in range(len(doc)) if page_num not in toc_pages]
1117
+ newjsonList=[]
1118
+ for heading_to_searchDict in headingjson:
1119
+ if type(heading_to_searchDict) == str:
1120
+ heading_to_search = heading_to_searchDict
1121
+ heading_to_searchPageNum = pagenum
1122
+ else:
1123
+ heading_to_search = heading_to_searchDict['Subject']
1124
+ heading_to_searchPageNum = int(heading_to_searchDict['Page'])-1
1125
+ incomingheader = heading_to_searchDict['head above 1']
1126
+
1127
+ print('hereeeeeeeeeeeeeee0',heading_to_searchPageNum)
1128
+ done = False
1129
+ collecting = False
1130
+ collected_lines = []
1131
+ page_highlights = {}
1132
+ current_bbox = {}
1133
+ last_y1s = {}
1134
+ mainHeader = ''
1135
+ subHeader = ''
1136
+ matched_header_line_norm = heading_to_search
1137
+ break_collecting = False
1138
+ heading_norm = normalize_text(heading_to_search)
1139
+
1140
+ for page_num in range(heading_to_searchPageNum,len(doc)):
1141
+ print('hereeeeeeeeeeeeeee1')
1142
+ if page_num in toc_pages:
1143
+ continue
1144
+ if break_collecting:
1145
+ break
1146
+ page=doc[page_num]
1147
+ page_height = page.rect.height
1148
+ blocks = page.get_text("dict")["blocks"]
1149
+
1150
+ for block in blocks:
1151
+ if break_collecting:
1152
+ break
1153
+
1154
+ lines = block.get("lines", [])
1155
+ i = 0
1156
+ while i < len(lines):
1157
+ if break_collecting:
1158
+ break
1159
+
1160
+ spans = lines[i].get("spans", [])
1161
+ if not spans:
1162
+ i += 1
1163
+ continue
1164
+
1165
+ y0 = spans[0]["bbox"][1]
1166
+ y1 = spans[0]["bbox"][3]
1167
+ if y0 < top_margin or y1 > (page_height - bottom_margin):
1168
+ i += 1
1169
+ continue
1170
+
1171
+ line_text = get_spaced_text_from_spans(spans).lower()
1172
+ line_text_norm = normalize_text(line_text)
1173
+
1174
+ # Combine with next line if available
1175
+ if i + 1 < len(lines):
1176
+ next_spans = lines[i + 1].get("spans", [])
1177
+ next_line_text = get_spaced_text_from_spans(next_spans).lower()
1178
+ combined_line_norm = normalize_text(line_text + " " + next_line_text)
1179
+ else:
1180
+ combined_line_norm = line_text_norm
1181
+ # Optimized header matching
1182
+ existsfull = (
1183
+ ( combined_line_norm in allchildrenheaders_set or
1184
+ combined_line_norm in allchildrenheaders ) and heading_to_search in combined_line_norm
1185
+ )
1186
+
1187
+ # New word-based matching
1188
+ current_line_words = set(combined_line_norm.split())
1189
+ heading_words = set(heading_norm.split())
1190
+ all_words_match = current_line_words.issubset(heading_words) and len(current_line_words) > 0
1191
+
1192
+ substring_match = (
1193
+ heading_norm in combined_line_norm or
1194
+ combined_line_norm in heading_norm or
1195
+ all_words_match # Include the new word-based matching
1196
+ )
1197
+
1198
+ if (substring_match and existsfull and not collecting and
1199
+ len(combined_line_norm) > 0 ):#and (headertoContinue1 or headertoContinue2) ):
1200
+
1201
+ # Check header conditions more efficiently
1202
+ header_spans = [
1203
+ span for span in spans
1204
+ if (is_header(span, most_common_font_size, most_common_color, most_common_font)
1205
+ # and span['size'] >= subsubheaderFontSize
1206
+ and span['size'] < mainHeaderFontSize)
1207
+ ]
1208
+ if header_spans:
1209
+ collecting = True
1210
+ matched_header_font_size = max(span["size"] for span in header_spans)
1211
+ print(f"📥 Start collecting after header: {combined_line_norm} (Font size: {matched_header_font_size})")
1212
+
1213
+ collected_lines.append(line_text)
1214
+ valid_spans = [span for span in spans if span.get("bbox")]
1215
+
1216
+ if valid_spans:
1217
+ x0s = [span["bbox"][0] for span in valid_spans]
1218
+ x1s = [span["bbox"][2] for span in valid_spans]
1219
+ y0s = [span["bbox"][1] for span in valid_spans]
1220
+ y1s = [span["bbox"][3] for span in valid_spans]
1221
+
1222
+ header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
1223
+
1224
+ if page_num in current_bbox:
1225
+ cb = current_bbox[page_num]
1226
+ current_bbox[page_num] = [
1227
+ min(cb[0], header_bbox[0]),
1228
+ min(cb[1], header_bbox[1]),
1229
+ max(cb[2], header_bbox[2]),
1230
+ max(cb[3], header_bbox[3])
1231
+ ]
1232
+ else:
1233
+ current_bbox[page_num] = header_bbox
1234
+ last_y1s[page_num] = header_bbox[3]
1235
+ x0, y0, x1, y1 = header_bbox
1236
+
1237
+ zoom = 200
1238
+ left = int(x0)
1239
+ top = int(y0)
1240
+ zoom_str = f"{zoom},{left},{top}"
1241
+ pageNumberFound = page_num + 1
1242
+
1243
+ # Build the query parameters
1244
+ params = {
1245
+ 'pdfLink': pdf_path, # Your PDF link
1246
+ 'keyword': heading_to_search, # Your keyword (could be a string or list)
1247
+ }
1248
+
1249
+ # URL encode each parameter
1250
+ encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}
1251
+
1252
+ # Construct the final encoded link
1253
+ encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])
1254
+
1255
+ # Correctly construct the final URL with page and zoom
1256
+ final_url = f"{newlink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"
1257
+
1258
+ # Get current date and time
1259
+ now = datetime.now()
1260
+
1261
+ # Format the output
1262
+ formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
1263
+ # Optionally, add the URL to a DataFrame
1264
+ new_url= final_url
1265
+ if type(heading_to_searchDict) != str:
1266
+ heading_to_searchDict['NBSLink']=new_url
1267
+ newjsonList.append(heading_to_searchDict)
1268
+ print("Final URL:", final_url)
1269
+ i += 2
1270
+ continue
1271
+ else:
1272
+ if (substring_match and not collecting and
1273
+ len(combined_line_norm) > 0): # and (headertoContinue1 or headertoContinue2) ):
1274
+
1275
+ # Calculate word match percentage
1276
+ word_match_percent = words_match_ratio(heading_norm, combined_line_norm) * 100
1277
+
1278
+ # Check if at least 70% of header words exist in this line
1279
+ meets_word_threshold = word_match_percent >= 100
1280
+
1281
+ # Check header conditions (including word threshold)
1282
+ header_spans = [
1283
+ span for span in spans
1284
+ if (is_header(span, most_common_font_size, most_common_color, most_common_font)
1285
+ # and span['size'] >= subsubheaderFontSize
1286
+ and span['size'] < mainHeaderFontSize)
1287
+ ]
1288
+
1289
+ if header_spans and (meets_word_threshold or same_start_word(heading_to_search, combined_line_norm) ):
1290
+ collecting = True
1291
+ matched_header_font_size = max(span["size"] for span in header_spans)
1292
+ print(f"📥 Start collecting after header: {combined_line_norm} "
1293
+ f"(Font: {matched_header_font_size}, Word match: {word_match_percent:.0f}%)")
1294
+
1295
+ collected_lines.append(line_text)
1296
+ valid_spans = [span for span in spans if span.get("bbox")]
1297
+
1298
+ if valid_spans:
1299
+ x0s = [span["bbox"][0] for span in valid_spans]
1300
+ x1s = [span["bbox"][2] for span in valid_spans]
1301
+ y0s = [span["bbox"][1] for span in valid_spans]
1302
+ y1s = [span["bbox"][3] for span in valid_spans]
1303
+
1304
+ header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
1305
+
1306
+ if page_num in current_bbox:
1307
+ cb = current_bbox[page_num]
1308
+ current_bbox[page_num] = [
1309
+ min(cb[0], header_bbox[0]),
1310
+ min(cb[1], header_bbox[1]),
1311
+ max(cb[2], header_bbox[2]),
1312
+ max(cb[3], header_bbox[3])
1313
+ ]
1314
+ else:
1315
+ current_bbox[page_num] = header_bbox
1316
+
1317
+ last_y1s[page_num] = header_bbox[3]
1318
+ x0, y0, x1, y1 = header_bbox
1319
+ zoom = 200
1320
+ left = int(x0)
1321
+ top = int(y0)
1322
+ zoom_str = f"{zoom},{left},{top}"
1323
+ pageNumberFound = page_num + 1
1324
+
1325
+ # Build the query parameters
1326
+ params = {
1327
+ 'pdfLink': pdf_path, # Your PDF link
1328
+ 'keyword': heading_to_search, # Your keyword (could be a string or list)
1329
+ }
1330
+
1331
+ # URL encode each parameter
1332
+ encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}
1333
+
1334
+ # Construct the final encoded link
1335
+ encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])
1336
+
1337
+ # Correctly construct the final URL with page and zoom
1338
+ final_url = f"{newlink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"
1339
+ new_url= final_url
1340
+ if type(heading_to_searchDict) != str:
1341
+ heading_to_searchDict['NBSLink']=new_url
1342
+ newjsonList.append(heading_to_searchDict)
1343
+ print("Final URL:", final_url)
1344
+ i += 2
1345
+ continue
1346
+ if collecting:
1347
+ norm_line = normalize_text(line_text)
1348
+
1349
+ # Optimized URL check
1350
+ if url_pattern.match(norm_line):
1351
+ line_is_header = False
1352
+ else:
1353
+ line_is_header = any(is_header(span, most_common_font_size, most_common_color, most_common_font) for span in spans)
1354
+
1355
+ if line_is_header:
1356
+ header_font_size = max(span["size"] for span in spans)
1357
+ is_probably_real_header = (
1358
+ header_font_size >= matched_header_font_size and
1359
+ is_header(spans[0], most_common_font_size, most_common_color, most_common_font) and
1360
+ len(line_text.strip()) > 2
1361
+ )
1362
+
1363
+ if (norm_line != matched_header_line_norm and
1364
+ norm_line != heading_norm and
1365
+ is_probably_real_header):
1366
+ if line_text not in heading_norm:
1367
+ print(f"🛑 Stop at header with same or larger font: '{line_text}' ({header_font_size} ≥ {matched_header_font_size})")
1368
+ collecting = False
1369
+ done = True
1370
+ headertoContinue1 = False
1371
+ headertoContinue2=False
1372
+ for page_num, bbox in current_bbox.items():
1373
+ bbox[3] = last_y1s.get(page_num, bbox[3])
1374
+ page_highlights[page_num] = bbox
1375
+
1376
+ if 'installation' in incomingheader or 'execution' in incomingheader or 'miscellaneous items' in incomingheader :
1377
+ stringtowrite='Not to be billed'
1378
+ else:
1379
+ stringtowrite='To be billed'
1380
+ highlight_boxes(docHighlights, page_highlights,stringtowrite)
1381
+
1382
+ break_collecting = True
1383
+ break
1384
+
1385
+ if break_collecting:
1386
+ break
1387
+
1388
+ collected_lines.append(line_text)
1389
+ valid_spans = [span for span in spans if span.get("bbox")]
1390
+ if valid_spans:
1391
+ x0s = [span["bbox"][0] for span in valid_spans]
1392
+ x1s = [span["bbox"][2] for span in valid_spans]
1393
+ y0s = [span["bbox"][1] for span in valid_spans]
1394
+ y1s = [span["bbox"][3] for span in valid_spans]
1395
+
1396
+ line_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
1397
+
1398
+ if page_num in current_bbox:
1399
+ cb = current_bbox[page_num]
1400
+ current_bbox[page_num] = [
1401
+ min(cb[0], line_bbox[0]),
1402
+ min(cb[1], line_bbox[1]),
1403
+ max(cb[2], line_bbox[2]),
1404
+ max(cb[3], line_bbox[3])
1405
+ ]
1406
+ else:
1407
+ current_bbox[page_num] = line_bbox
1408
+
1409
+ last_y1s[page_num] = line_bbox[3]
1410
+ i += 1
1411
+
1412
+ if not done:
1413
+ for page_num, bbox in current_bbox.items():
1414
+ bbox[3] = last_y1s.get(page_num, bbox[3])
1415
+ page_highlights[page_num] = bbox
1416
+ if 'installation' in incomingheader or 'execution' in incomingheader or 'miscellaneous items' in incomingheader :
1417
+ stringtowrite='Not to be billed'
1418
+ else:
1419
+ stringtowrite='To be billed'
1420
+ highlight_boxes(docHighlights, page_highlights,stringtowrite)
1421
+
1422
+ # docHighlights.save("highlighted_output.pdf", garbage=4, deflate=True)
1423
+
1424
+ pdf_bytes = BytesIO()
1425
+ docHighlights.save(pdf_bytes)
1426
+ return pdf_bytes.getvalue(), docHighlights , newjsonList
1427
+
1428
+