Spaces:
Sleeping
Sleeping
Update google_sheet_Legend.py
Browse files- google_sheet_Legend.py +231 -46
google_sheet_Legend.py
CHANGED
|
@@ -17,8 +17,13 @@ from google.oauth2 import service_account
|
|
| 17 |
from googleapiclient.discovery import build
|
| 18 |
import pygsheets
|
| 19 |
import tsadropboxretrieval
|
|
|
|
| 20 |
import fitz
|
| 21 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
def authorizeLegend():
|
|
@@ -33,9 +38,13 @@ def authorizeLegend():
|
|
| 33 |
gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
|
| 34 |
return spreadsheet_service,drive_service,gc
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
spreadsheet_service,drive_service,gc=authorizeLegend()
|
| 37 |
-
|
| 38 |
-
|
| 39 |
def create_new_sheet(path):
|
| 40 |
spreadsheet_details = {
|
| 41 |
'properties': {
|
|
@@ -51,9 +60,11 @@ def create_new_sheet(path):
|
|
| 51 |
drive_service.permissions().create(fileId=spreadsheetId, body=permission1, supportsAllDrives=True).execute()
|
| 52 |
return spreadsheetId
|
| 53 |
|
| 54 |
-
|
| 55 |
def update_sheet(spreadsheetId, SimilarAreaDictionary, pdfpath):
|
| 56 |
ws = gc.open_by_key(spreadsheetId)
|
|
|
|
|
|
|
| 57 |
worksheet = ws.worksheet(0)
|
| 58 |
worksheet.title = 'Legend and data created'
|
| 59 |
worksheet.clear()
|
|
@@ -252,15 +263,19 @@ def update_sheet(spreadsheetId, SimilarAreaDictionary, pdfpath):
|
|
| 252 |
model_cell.color = (213 / 255, 219 / 255, 255 / 255)
|
| 253 |
pygsheets.DataRange('A2', 'K2', worksheet=worksheet).apply_format(model_cell)
|
| 254 |
|
| 255 |
-
|
| 256 |
def legendGoogleSheets(SimilarAreaDictionary, path, pdfpath, spreadsheetId=0):
|
| 257 |
titles = gc.spreadsheet_titles()
|
| 258 |
if path in titles:
|
| 259 |
ws = gc.open(path)
|
|
|
|
|
|
|
| 260 |
spreadsheetId = ws.id
|
| 261 |
else:
|
| 262 |
spreadsheetId = create_new_sheet(path)
|
| 263 |
ws=gc.open_by_key(spreadsheetId)
|
|
|
|
|
|
|
| 264 |
update_sheet(spreadsheetId, SimilarAreaDictionary, pdfpath)
|
| 265 |
spreadsheet_url = f"https://docs.google.com/spreadsheets/d/{spreadsheetId}"
|
| 266 |
drive_service.permissions().update(transferOwnership=True, fileId=spreadsheetId, permissionId='11OfoB4Z6wOVII8mYmbnCbbqTQs7rYA65')
|
|
@@ -268,9 +283,8 @@ def legendGoogleSheets(SimilarAreaDictionary, path, pdfpath, spreadsheetId=0):
|
|
| 268 |
namepathArr = [path, spreadsheetId, ws.get_developer_metadata('path')[0].value]
|
| 269 |
return gc, spreadsheet_service, spreadsheetId, spreadsheet_url, namepathArr
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
def mapnametoLegend(McTName):
|
| 274 |
|
| 275 |
sectionKey = McTName.pop()
|
| 276 |
key=sectionKey[0]
|
|
@@ -280,37 +294,38 @@ def mapnametoLegend(McTName):
|
|
| 280 |
spreadsheet_key =str(key) # Please set the Spreadsheet ID.
|
| 281 |
|
| 282 |
ws = gc.open_by_key(spreadsheet_key)
|
|
|
|
| 283 |
# guessednamesfinal=getguessnames(gc,ws)
|
| 284 |
sheetnames=[]
|
| 285 |
unit=''
|
| 286 |
# ws.add_worksheet("Summary") # Please set the new sheet name.
|
| 287 |
for i in ws._sheet_list:
|
| 288 |
-
print(i)
|
| 289 |
sheetnames.append(i.title)
|
| 290 |
-
print(i.index)
|
| 291 |
if 'XML Export Summary' in sheetnames:
|
| 292 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 293 |
else:
|
| 294 |
ws.add_worksheet("XML Export Summary") # Please set the new sheet name.
|
|
|
|
| 295 |
worksheetw = ws.worksheet(0) #legend
|
| 296 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 297 |
summaryId= ws[1].id
|
| 298 |
-
|
| 299 |
-
print('summaryyyID2',worksheetS.id)
|
| 300 |
worksheetS.clear()
|
| 301 |
|
| 302 |
countnames=0
|
| 303 |
row0=['MC_T Name','Qty','Unit']
|
| 304 |
worksheetS.update_row(1,row0)
|
| 305 |
|
| 306 |
-
|
| 307 |
for i in range(len(McTName)):
|
| 308 |
allgbnames=''
|
| 309 |
item=''
|
| 310 |
-
|
| 311 |
|
| 312 |
# firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
|
| 313 |
-
print('kkk' ,McTName[i][2])
|
| 314 |
if McTName[i][2].startswith('Area'):
|
| 315 |
if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
|
| 316 |
rowvalue=5# column 5
|
|
@@ -333,7 +348,6 @@ def mapnametoLegend(McTName):
|
|
| 333 |
ar=0
|
| 334 |
unit='Nr'
|
| 335 |
|
| 336 |
-
print('mcct',McTName[i][1])
|
| 337 |
if isinstance(McTName[i][1], list):
|
| 338 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 339 |
|
|
@@ -341,9 +355,10 @@ def mapnametoLegend(McTName):
|
|
| 341 |
if m:
|
| 342 |
if m.startswith('text1'):
|
| 343 |
name=m.removeprefix('text1')
|
| 344 |
-
|
|
|
|
| 345 |
indices = [o for o, x in enumerate(guessednames) if x == name]
|
| 346 |
-
print(indices)
|
| 347 |
for j in range(len(indices)):
|
| 348 |
# print('kjjjj',roww[j])
|
| 349 |
ar+=float(worksheetw.cell((indices[j]+1 ,rowvalue)).value)
|
|
@@ -352,7 +367,7 @@ def mapnametoLegend(McTName):
|
|
| 352 |
item+=m
|
| 353 |
else:
|
| 354 |
item+=m + ' ,'
|
| 355 |
-
print(item)
|
| 356 |
if section.startswith('3.2') or section.startswith('3.3'):
|
| 357 |
n= McTName[i][0] + ' ( '+ allgbnames[:-2]+ ' ) '
|
| 358 |
else:
|
|
@@ -363,19 +378,25 @@ def mapnametoLegend(McTName):
|
|
| 363 |
allgbnames+= name
|
| 364 |
|
| 365 |
roww=worksheetw.find(name)
|
| 366 |
-
print(roww)
|
| 367 |
for j in range(len(roww)):
|
| 368 |
-
print('kjjjj',roww[j])
|
| 369 |
ar+=float(worksheetw.cell((roww[j].row ,rowvalue)).value)
|
| 370 |
n= McTName[i][0] + ' ( '+ allgbnames + ' ) '
|
| 371 |
|
| 372 |
rowi=[str(n),ar,unit]
|
|
|
|
|
|
|
|
|
|
| 373 |
worksheetS.update_row(i+2,rowi)
|
| 374 |
# worksheetS.adjust_column_width(start=1,end=4)
|
| 375 |
worksheetS.adjust_column_width(start=1,end=1, pixel_size=350)
|
| 376 |
worksheetS.adjust_column_width(start=2,end=2, pixel_size=100)
|
| 377 |
worksheetS.adjust_column_width(start=3,end=3)
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
xx=(worksheetS.cell( ( len(McTName) +1 ,3)) ).address.label
|
| 380 |
model_cell1 =worksheetS.cell('A2')
|
| 381 |
model_cell1.set_horizontal_alignment( pygsheets.custom_types.HorizontalAlignment.LEFT )
|
|
@@ -461,18 +482,84 @@ def mapnametoLegend(McTName):
|
|
| 461 |
|
| 462 |
# print(x,xarea)
|
| 463 |
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
guessednamesfinal=[]
|
| 466 |
-
|
| 467 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 468 |
-
print(guessednames
|
| 469 |
-
for
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
|
|
|
|
|
|
|
|
|
| 473 |
return guessednamesfinal
|
| 474 |
|
| 475 |
-
|
| 476 |
def is_color_within_tolerance(color1, color2, tolerance):
|
| 477 |
# Ensure both colors are tuples of integers
|
| 478 |
color1 = tuple(map(int, color1))
|
|
@@ -480,12 +567,14 @@ def is_color_within_tolerance(color1, color2, tolerance):
|
|
| 480 |
|
| 481 |
return all(abs(c1 - c2) <= tolerance for c1, c2 in zip(color1, color2))
|
| 482 |
|
|
|
|
| 483 |
def deletefromlegend(deletedrows, SimilarAreaDictionarycopy, section, areaPermArr=[]):
|
| 484 |
items = []
|
| 485 |
-
print('deletefromlegend',deletedrows)
|
| 486 |
idx = 0
|
| 487 |
if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
|
| 488 |
areaPermArr = ast.literal_eval(areaPermArr)
|
|
|
|
| 489 |
myDict = eval(SimilarAreaDictionarycopy)
|
| 490 |
SimilarAreaDictionarycopy = pd.DataFrame(myDict)
|
| 491 |
strings = deletedrows['content']
|
|
@@ -512,22 +601,19 @@ def deletefromlegend(deletedrows, SimilarAreaDictionarycopy, section, areaPermAr
|
|
| 512 |
|
| 513 |
# print('eee',existing_color,color)
|
| 514 |
if is_color_within_tolerance(existing_color, color, tolerance):
|
| 515 |
-
print(f'Color {color} found close to {existing_color} at index {idx}')
|
| 516 |
found = True
|
| 517 |
-
# print(strings[j])
|
| 518 |
matchA = re.search(r"Area=(\d+\.\d+)", strings[j])
|
| 519 |
matchP = re.search(r"Perimeter=(\d+\.\d+)", strings[j])
|
| 520 |
matchL = re.search(r"Length=(\d+\.\d+)", strings[j])
|
| 521 |
-
|
| 522 |
-
print('matchingcontentAA ',float(matchA.group(1)),int(idx))
|
| 523 |
-
if matchP:
|
| 524 |
-
print('matchingcontentPP ',float(matchP.group(1)),int(idx))
|
| 525 |
comment = SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Comments')]
|
| 526 |
occ = SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Occurences')]
|
| 527 |
|
| 528 |
# Only subtract area if the area value is found
|
| 529 |
if matchA:
|
| 530 |
-
print(' SimilarAreaDictionaryArea', float(matchA.group(1)), SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')])
|
| 531 |
SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')] =SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')] - float(matchA.group(1))
|
| 532 |
# Update area occurrences
|
| 533 |
if pd.notna(comment) and 'Area' in str(comment):
|
|
@@ -583,14 +669,13 @@ def deletefromlegend(deletedrows, SimilarAreaDictionarycopy, section, areaPermAr
|
|
| 583 |
|
| 584 |
if not found:
|
| 585 |
print(f'Color {color} not found within tolerance')
|
| 586 |
-
print('indicies_toDelete',indicies_toDelete)
|
| 587 |
|
| 588 |
SimilarAreaDictionarycopy.drop(index=indicies_toDelete, axis=0, inplace=True)
|
| 589 |
-
print('SimilarAreaDictionarycopy',SimilarAreaDictionarycopy)
|
| 590 |
return SimilarAreaDictionarycopy
|
| 591 |
|
| 592 |
-
|
| 593 |
-
|
| 594 |
def DoorsLegend(Dictionary,spreadsheetId,worksheet):
|
| 595 |
top_header_format = [
|
| 596 |
{'mergeCells': { # legend and data created
|
|
@@ -683,11 +768,12 @@ def DoorsLegend(Dictionary,spreadsheetId,worksheet):
|
|
| 683 |
model_cell.set_horizontal_alignment(pygsheets.custom_types.HorizontalAlignment.CENTER)
|
| 684 |
model_cell.color = (213 / 255, 219 / 255, 255 / 255)
|
| 685 |
pygsheets.DataRange('A2', 'B2', worksheet=worksheet).apply_format(model_cell)
|
|
|
|
| 686 |
|
| 687 |
def delete3_2(deletedrows,dictionary):
|
| 688 |
|
| 689 |
items=[]
|
| 690 |
-
print('dletefromlegend3.2')
|
| 691 |
idx=0
|
| 692 |
myDict=eval(dictionary)
|
| 693 |
df_doors=pd.DataFrame(myDict)
|
|
@@ -720,8 +806,7 @@ def delete3_2(deletedrows,dictionary):
|
|
| 720 |
df_doors = df_doors[['Type', 'Quantity']]
|
| 721 |
return df_doors
|
| 722 |
|
| 723 |
-
|
| 724 |
-
|
| 725 |
|
| 726 |
def deletemarkups(list1, dbPath, path):
|
| 727 |
'''list1 : original markup pdf
|
|
@@ -765,7 +850,7 @@ def deletemarkups(list1, dbPath, path):
|
|
| 765 |
# Find the deleted rows by checking the difference between original and current annotations
|
| 766 |
deletedrows = pd.concat([list1, list2]).drop_duplicates(keep=False)
|
| 767 |
|
| 768 |
-
print(deletedrows, len(deletedrows))
|
| 769 |
flag = 0
|
| 770 |
if len(deletedrows) != 0:
|
| 771 |
flag = 1
|
|
@@ -775,4 +860,104 @@ def deletemarkups(list1, dbPath, path):
|
|
| 775 |
else:
|
| 776 |
flag = 0
|
| 777 |
|
| 778 |
-
return deletedrows
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
from googleapiclient.discovery import build
|
| 18 |
import pygsheets
|
| 19 |
import tsadropboxretrieval
|
| 20 |
+
import requests
|
| 21 |
import fitz
|
| 22 |
import numpy as np
|
| 23 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 24 |
+
from io import BytesIO
|
| 25 |
+
from PyPDF2.generic import NameObject, DictionaryObject, FloatObject, TextStringObject
|
| 26 |
+
import dropbox
|
| 27 |
|
| 28 |
|
| 29 |
def authorizeLegend():
|
|
|
|
| 38 |
gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
|
| 39 |
return spreadsheet_service,drive_service,gc
|
| 40 |
|
| 41 |
+
#########################
|
| 42 |
+
global gc
|
| 43 |
+
global pdfpath0
|
| 44 |
+
global pdftitle
|
| 45 |
+
global worksheetw
|
| 46 |
spreadsheet_service,drive_service,gc=authorizeLegend()
|
| 47 |
+
#########################
|
|
|
|
| 48 |
def create_new_sheet(path):
|
| 49 |
spreadsheet_details = {
|
| 50 |
'properties': {
|
|
|
|
| 60 |
drive_service.permissions().create(fileId=spreadsheetId, body=permission1, supportsAllDrives=True).execute()
|
| 61 |
return spreadsheetId
|
| 62 |
|
| 63 |
+
#########################
|
| 64 |
def update_sheet(spreadsheetId, SimilarAreaDictionary, pdfpath):
|
| 65 |
ws = gc.open_by_key(spreadsheetId)
|
| 66 |
+
global pdfpath0
|
| 67 |
+
pdfpath0=pdfpath
|
| 68 |
worksheet = ws.worksheet(0)
|
| 69 |
worksheet.title = 'Legend and data created'
|
| 70 |
worksheet.clear()
|
|
|
|
| 263 |
model_cell.color = (213 / 255, 219 / 255, 255 / 255)
|
| 264 |
pygsheets.DataRange('A2', 'K2', worksheet=worksheet).apply_format(model_cell)
|
| 265 |
|
| 266 |
+
#########################
|
| 267 |
def legendGoogleSheets(SimilarAreaDictionary, path, pdfpath, spreadsheetId=0):
|
| 268 |
titles = gc.spreadsheet_titles()
|
| 269 |
if path in titles:
|
| 270 |
ws = gc.open(path)
|
| 271 |
+
global pdftitle
|
| 272 |
+
pdftitle=path
|
| 273 |
spreadsheetId = ws.id
|
| 274 |
else:
|
| 275 |
spreadsheetId = create_new_sheet(path)
|
| 276 |
ws=gc.open_by_key(spreadsheetId)
|
| 277 |
+
global worksheetw
|
| 278 |
+
worksheetw = ws.worksheet(0) #legend
|
| 279 |
update_sheet(spreadsheetId, SimilarAreaDictionary, pdfpath)
|
| 280 |
spreadsheet_url = f"https://docs.google.com/spreadsheets/d/{spreadsheetId}"
|
| 281 |
drive_service.permissions().update(transferOwnership=True, fileId=spreadsheetId, permissionId='11OfoB4Z6wOVII8mYmbnCbbqTQs7rYA65')
|
|
|
|
| 283 |
namepathArr = [path, spreadsheetId, ws.get_developer_metadata('path')[0].value]
|
| 284 |
return gc, spreadsheet_service, spreadsheetId, spreadsheet_url, namepathArr
|
| 285 |
|
| 286 |
+
#########################
|
| 287 |
+
def mapnametoLegend(McTName,colorsused,pdflink):
|
|
|
|
| 288 |
|
| 289 |
sectionKey = McTName.pop()
|
| 290 |
key=sectionKey[0]
|
|
|
|
| 294 |
spreadsheet_key =str(key) # Please set the Spreadsheet ID.
|
| 295 |
|
| 296 |
ws = gc.open_by_key(spreadsheet_key)
|
| 297 |
+
|
| 298 |
# guessednamesfinal=getguessnames(gc,ws)
|
| 299 |
sheetnames=[]
|
| 300 |
unit=''
|
| 301 |
# ws.add_worksheet("Summary") # Please set the new sheet name.
|
| 302 |
for i in ws._sheet_list:
|
| 303 |
+
# print(i)
|
| 304 |
sheetnames.append(i.title)
|
| 305 |
+
# print(i.index)
|
| 306 |
if 'XML Export Summary' in sheetnames:
|
| 307 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 308 |
else:
|
| 309 |
ws.add_worksheet("XML Export Summary") # Please set the new sheet name.
|
| 310 |
+
global worksheetw
|
| 311 |
worksheetw = ws.worksheet(0) #legend
|
| 312 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 313 |
summaryId= ws[1].id
|
| 314 |
+
|
|
|
|
| 315 |
worksheetS.clear()
|
| 316 |
|
| 317 |
countnames=0
|
| 318 |
row0=['MC_T Name','Qty','Unit']
|
| 319 |
worksheetS.update_row(1,row0)
|
| 320 |
|
| 321 |
+
allrows=[]
|
| 322 |
for i in range(len(McTName)):
|
| 323 |
allgbnames=''
|
| 324 |
item=''
|
| 325 |
+
|
| 326 |
|
| 327 |
# firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
|
| 328 |
+
# print('kkk' ,McTName[i][2])
|
| 329 |
if McTName[i][2].startswith('Area'):
|
| 330 |
if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
|
| 331 |
rowvalue=5# column 5
|
|
|
|
| 348 |
ar=0
|
| 349 |
unit='Nr'
|
| 350 |
|
|
|
|
| 351 |
if isinstance(McTName[i][1], list):
|
| 352 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 353 |
|
|
|
|
| 355 |
if m:
|
| 356 |
if m.startswith('text1'):
|
| 357 |
name=m.removeprefix('text1')
|
| 358 |
+
|
| 359 |
+
allgbnames+= name +' + '
|
| 360 |
indices = [o for o, x in enumerate(guessednames) if x == name]
|
| 361 |
+
# print(indices)
|
| 362 |
for j in range(len(indices)):
|
| 363 |
# print('kjjjj',roww[j])
|
| 364 |
ar+=float(worksheetw.cell((indices[j]+1 ,rowvalue)).value)
|
|
|
|
| 367 |
item+=m
|
| 368 |
else:
|
| 369 |
item+=m + ' ,'
|
| 370 |
+
# print(item)
|
| 371 |
if section.startswith('3.2') or section.startswith('3.3'):
|
| 372 |
n= McTName[i][0] + ' ( '+ allgbnames[:-2]+ ' ) '
|
| 373 |
else:
|
|
|
|
| 378 |
allgbnames+= name
|
| 379 |
|
| 380 |
roww=worksheetw.find(name)
|
|
|
|
| 381 |
for j in range(len(roww)):
|
| 382 |
+
# print('kjjjj',roww[j])
|
| 383 |
ar+=float(worksheetw.cell((roww[j].row ,rowvalue)).value)
|
| 384 |
n= McTName[i][0] + ' ( '+ allgbnames + ' ) '
|
| 385 |
|
| 386 |
rowi=[str(n),ar,unit]
|
| 387 |
+
|
| 388 |
+
allrows.append([rowi[0],unit])
|
| 389 |
+
|
| 390 |
worksheetS.update_row(i+2,rowi)
|
| 391 |
# worksheetS.adjust_column_width(start=1,end=4)
|
| 392 |
worksheetS.adjust_column_width(start=1,end=1, pixel_size=350)
|
| 393 |
worksheetS.adjust_column_width(start=2,end=2, pixel_size=100)
|
| 394 |
worksheetS.adjust_column_width(start=3,end=3)
|
| 395 |
+
guessednamesfinal=getguessnames(worksheetw,colorsused) #gb,color
|
| 396 |
+
mctname_guessedNames=label_MC_Tname(allrows) #mctname, gb1
|
| 397 |
+
mappedMct_colors=mctname_colors(guessednamesfinal,mctname_guessedNames) #mctname,gb1
|
| 398 |
+
adjustannotations(pdflink, mappedMct_colors)
|
| 399 |
+
|
| 400 |
xx=(worksheetS.cell( ( len(McTName) +1 ,3)) ).address.label
|
| 401 |
model_cell1 =worksheetS.cell('A2')
|
| 402 |
model_cell1.set_horizontal_alignment( pygsheets.custom_types.HorizontalAlignment.LEFT )
|
|
|
|
| 482 |
|
| 483 |
# print(x,xarea)
|
| 484 |
|
| 485 |
+
#########################
|
| 486 |
+
def label_MC_Tname(mctname_names):
|
| 487 |
+
# print('mctname_names',mctname_names)
|
| 488 |
+
mctname_guessedNames=[]
|
| 489 |
+
# unit=mctname_names[1]
|
| 490 |
+
for row in mctname_names:
|
| 491 |
+
text=row[0]
|
| 492 |
+
unit=row[1]
|
| 493 |
+
# print(text,unit)
|
| 494 |
+
text_before_parenthesis = text.split('(')[0].strip()
|
| 495 |
+
# Step 2: Extract text inside the parentheses
|
| 496 |
+
inside_parentheses = re.search(r'\((.*?)\)', text)
|
| 497 |
+
if inside_parentheses:
|
| 498 |
+
inside_parentheses = inside_parentheses.group(1).strip()
|
| 499 |
+
if '+' in inside_parentheses:
|
| 500 |
+
# Split the content by '+', and strip any leading/trailing spaces
|
| 501 |
+
parts = [part.strip() for part in inside_parentheses.split('+')]
|
| 502 |
+
else:
|
| 503 |
+
# If no '+', just put the whole content as a single part
|
| 504 |
+
parts = [inside_parentheses]
|
| 505 |
+
mctname_guessedNames.append([text_before_parenthesis,parts , unit])
|
| 506 |
+
# print('mctname_guessedNames',mctname_guessedNames)
|
| 507 |
+
return mctname_guessedNames
|
| 508 |
+
|
| 509 |
+
#########################
|
| 510 |
+
def mctname_colors(color_dict, mctname_gb):
|
| 511 |
+
|
| 512 |
+
# print('color_dict', color_dict)
|
| 513 |
+
# print('mctname_gb', mctname_gb)
|
| 514 |
+
|
| 515 |
+
# Convert the color_dict array into a dictionary with trimmed keys for easier lookup
|
| 516 |
+
color_dict_map = {color[0].strip(): color[1] for color in color_dict}
|
| 517 |
+
# print('color_dict_map', color_dict_map)
|
| 518 |
+
|
| 519 |
+
# Result list to store the final output
|
| 520 |
+
result = []
|
| 521 |
+
|
| 522 |
+
# Processing the items
|
| 523 |
+
for item in mctname_gb:
|
| 524 |
+
name = item[0]
|
| 525 |
+
colors = item[1]
|
| 526 |
+
unit=item[2]
|
| 527 |
+
# print(name,colors)
|
| 528 |
+
# Get RGB values for the corresponding colors
|
| 529 |
+
color_values = []
|
| 530 |
+
for color in colors:
|
| 531 |
+
trimmed_color = color.strip() # Trim any leading/trailing spaces
|
| 532 |
+
if trimmed_color in color_dict_map:
|
| 533 |
+
color_values.append(color_dict_map[trimmed_color])
|
| 534 |
+
else:
|
| 535 |
+
# Handle missing references (e.g., append None or a default color)
|
| 536 |
+
color_values.append(None) # Or append a default color like (0, 0, 0)
|
| 537 |
+
|
| 538 |
+
# Join the name with the corresponding RGB colors
|
| 539 |
+
result.append([name, color_values,unit])
|
| 540 |
+
|
| 541 |
+
# Print the result
|
| 542 |
+
# print('result', result)
|
| 543 |
+
return result
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
#########################
|
| 548 |
+
def getguessnames(worksheetw,colorsused):
|
| 549 |
guessednamesfinal=[]
|
| 550 |
+
# print('colorsused',colorsused)
|
| 551 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 552 |
+
# print(guessednames)
|
| 553 |
+
for i in range(len(guessednames[3:])):
|
| 554 |
+
item = guessednames[3:][i] # Name from the guessednames list
|
| 555 |
+
|
| 556 |
+
colorforitem = colorsused[i] # Get the corresponding color for the current item
|
| 557 |
+
if item not in guessednamesfinal:
|
| 558 |
+
guessednamesfinal.append([item, colorforitem])
|
| 559 |
+
# print('guessednamesfinal', guessednamesfinal)
|
| 560 |
return guessednamesfinal
|
| 561 |
|
| 562 |
+
#########################
|
| 563 |
def is_color_within_tolerance(color1, color2, tolerance):
|
| 564 |
# Ensure both colors are tuples of integers
|
| 565 |
color1 = tuple(map(int, color1))
|
|
|
|
| 567 |
|
| 568 |
return all(abs(c1 - c2) <= tolerance for c1, c2 in zip(color1, color2))
|
| 569 |
|
| 570 |
+
#########################
|
| 571 |
def deletefromlegend(deletedrows, SimilarAreaDictionarycopy, section, areaPermArr=[]):
|
| 572 |
items = []
|
| 573 |
+
# print('deletefromlegend',deletedrows)
|
| 574 |
idx = 0
|
| 575 |
if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
|
| 576 |
areaPermArr = ast.literal_eval(areaPermArr)
|
| 577 |
+
print(areaPermArr)
|
| 578 |
myDict = eval(SimilarAreaDictionarycopy)
|
| 579 |
SimilarAreaDictionarycopy = pd.DataFrame(myDict)
|
| 580 |
strings = deletedrows['content']
|
|
|
|
| 601 |
|
| 602 |
# print('eee',existing_color,color)
|
| 603 |
if is_color_within_tolerance(existing_color, color, tolerance):
|
| 604 |
+
# print(f'Color {color} found close to {existing_color} at index {idx}')
|
| 605 |
found = True
|
| 606 |
+
# print('strings',strings[j])
|
| 607 |
matchA = re.search(r"Area=(\d+\.\d+)", strings[j])
|
| 608 |
matchP = re.search(r"Perimeter=(\d+\.\d+)", strings[j])
|
| 609 |
matchL = re.search(r"Length=(\d+\.\d+)", strings[j])
|
| 610 |
+
|
|
|
|
|
|
|
|
|
|
| 611 |
comment = SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Comments')]
|
| 612 |
occ = SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Occurences')]
|
| 613 |
|
| 614 |
# Only subtract area if the area value is found
|
| 615 |
if matchA:
|
| 616 |
+
# print(' SimilarAreaDictionaryArea', float(matchA.group(1)), SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')])
|
| 617 |
SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')] =SimilarAreaDictionarycopy.iloc[int(idx), SimilarAreaDictionarycopy.columns.get_loc('Total Area')] - float(matchA.group(1))
|
| 618 |
# Update area occurrences
|
| 619 |
if pd.notna(comment) and 'Area' in str(comment):
|
|
|
|
| 669 |
|
| 670 |
if not found:
|
| 671 |
print(f'Color {color} not found within tolerance')
|
| 672 |
+
# print('indicies_toDelete',indicies_toDelete)
|
| 673 |
|
| 674 |
SimilarAreaDictionarycopy.drop(index=indicies_toDelete, axis=0, inplace=True)
|
| 675 |
+
# print('SimilarAreaDictionarycopy',SimilarAreaDictionarycopy)
|
| 676 |
return SimilarAreaDictionarycopy
|
| 677 |
|
| 678 |
+
#########################
|
|
|
|
| 679 |
def DoorsLegend(Dictionary,spreadsheetId,worksheet):
|
| 680 |
top_header_format = [
|
| 681 |
{'mergeCells': { # legend and data created
|
|
|
|
| 768 |
model_cell.set_horizontal_alignment(pygsheets.custom_types.HorizontalAlignment.CENTER)
|
| 769 |
model_cell.color = (213 / 255, 219 / 255, 255 / 255)
|
| 770 |
pygsheets.DataRange('A2', 'B2', worksheet=worksheet).apply_format(model_cell)
|
| 771 |
+
#########################
|
| 772 |
|
| 773 |
def delete3_2(deletedrows,dictionary):
|
| 774 |
|
| 775 |
items=[]
|
| 776 |
+
# print('dletefromlegend3.2')
|
| 777 |
idx=0
|
| 778 |
myDict=eval(dictionary)
|
| 779 |
df_doors=pd.DataFrame(myDict)
|
|
|
|
| 806 |
df_doors = df_doors[['Type', 'Quantity']]
|
| 807 |
return df_doors
|
| 808 |
|
| 809 |
+
#########################
|
|
|
|
| 810 |
|
| 811 |
def deletemarkups(list1, dbPath, path):
|
| 812 |
'''list1 : original markup pdf
|
|
|
|
| 850 |
# Find the deleted rows by checking the difference between original and current annotations
|
| 851 |
deletedrows = pd.concat([list1, list2]).drop_duplicates(keep=False)
|
| 852 |
|
| 853 |
+
# print(deletedrows, len(deletedrows))
|
| 854 |
flag = 0
|
| 855 |
if len(deletedrows) != 0:
|
| 856 |
flag = 1
|
|
|
|
| 860 |
else:
|
| 861 |
flag = 0
|
| 862 |
|
| 863 |
+
return deletedrows
|
| 864 |
+
|
| 865 |
+
############################
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def adjustannotations(pdflink, color_items):
|
| 869 |
+
# Load the input PDF
|
| 870 |
+
pdf_content = None
|
| 871 |
+
if pdflink and ('http' in pdflink or 'dropbox' in pdflink):
|
| 872 |
+
# Modify Dropbox link for direct download
|
| 873 |
+
# print('pdffff',pdflink)
|
| 874 |
+
if 'dl=0' in pdflink:
|
| 875 |
+
pdflink = pdflink.replace('dl=0', 'dl=1')
|
| 876 |
+
|
| 877 |
+
# Download the PDF content from the shareable link
|
| 878 |
+
response = requests.get(pdflink)
|
| 879 |
+
pdf_bytes_io = BytesIO(response.content) # Store the content in memory
|
| 880 |
+
# pdf_bytes_io = BytesIO(OutputPdfStage1)
|
| 881 |
+
reader = PdfReader(pdf_bytes_io)
|
| 882 |
+
writer = PdfWriter()
|
| 883 |
+
|
| 884 |
+
# Append all pages to the writer
|
| 885 |
+
writer.append_pages_from_reader(reader)
|
| 886 |
+
|
| 887 |
+
# Add metadata (optional)
|
| 888 |
+
metadata = reader.metadata
|
| 889 |
+
writer.add_metadata(metadata)
|
| 890 |
+
|
| 891 |
+
# Convert color_items array to a more accessible structure (a dictionary of colors)
|
| 892 |
+
color_dict = {}
|
| 893 |
+
for item in color_items:
|
| 894 |
+
label = item[0]
|
| 895 |
+
colors = item[1]
|
| 896 |
+
unit = item[2]
|
| 897 |
+
# print('UNIT', unit)
|
| 898 |
+
for color in colors:
|
| 899 |
+
color_dict[tuple(color)] = (label, unit) # Map RGB color to a tuple (label, unit)
|
| 900 |
+
|
| 901 |
+
# print(color_dict)
|
| 902 |
+
|
| 903 |
+
# Iterate over pages to check annotations and update label
|
| 904 |
+
for page_index, page in enumerate(writer.pages):
|
| 905 |
+
if "/Annots" in page:
|
| 906 |
+
annotations = page["/Annots"]
|
| 907 |
+
for annot_index, annot in enumerate(annotations):
|
| 908 |
+
obj = annot.get_object()
|
| 909 |
+
|
| 910 |
+
# Only proceed if the annotation has a color and is a valid markup (e.g., Polygon)
|
| 911 |
+
if "/C" in obj:
|
| 912 |
+
color = tuple(obj["/C"]) # Extract the RGB color (list of 3 values)
|
| 913 |
+
color = (int(round(color[0] * 255, 1)), int(round(color[1] * 255, 1)), int(round(color[2] * 255, 1)))
|
| 914 |
+
|
| 915 |
+
# If the color matches any item in color_dict, update the label
|
| 916 |
+
if color in color_dict:
|
| 917 |
+
label, unit = color_dict[color] # Retrieve both label and unit
|
| 918 |
+
# print(unit)
|
| 919 |
+
# Update annotation label (e.g., /Contents or /Subj)
|
| 920 |
+
if "/Contents" in obj:
|
| 921 |
+
if unit == 'm2' and "sq m" in obj["/Contents"]:
|
| 922 |
+
obj.update({
|
| 923 |
+
NameObject("/Label"): TextStringObject(f"{label}")
|
| 924 |
+
})
|
| 925 |
+
elif unit == 'm' and "m" in obj["/Contents"] and "sq" not in obj["/Contents"]: # Ensure it's not an area
|
| 926 |
+
obj.update({
|
| 927 |
+
NameObject("/Label"): TextStringObject(f"{label}")
|
| 928 |
+
})
|
| 929 |
+
# print(f"Updated Annotation: {obj}")
|
| 930 |
+
|
| 931 |
+
# Save the modified PDF
|
| 932 |
+
output_pdf_io = BytesIO()
|
| 933 |
+
writer.write(output_pdf_io)
|
| 934 |
+
output_pdf_io.seek(0)
|
| 935 |
+
|
| 936 |
+
# Save the content to a file (avoid using the same name for the variable and file object)
|
| 937 |
+
OutputPdfStage2=output_pdf_io.read()
|
| 938 |
+
doc2 =fitz.open('pdf',OutputPdfStage2)
|
| 939 |
+
dbPath='/TSA JOBS/ADR Test'+pdfpath0+'Measured Plan/'+pdftitle
|
| 940 |
+
# dburl=tsadropboxretrieval.uploadanyFile(doc=doc2,pdfname=pdftitle ,path=dbPath)
|
| 941 |
+
# print('omarpdf',dburl)
|
| 942 |
+
print("Annotations updated and saved")
|
| 943 |
+
dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
|
| 944 |
+
try:
|
| 945 |
+
# Upload the new file and overwrite the existing one
|
| 946 |
+
dbxTeam.files_upload(doc2.write() ,dbPath, mode=dropbox.files.WriteMode('overwrite'))
|
| 947 |
+
# dbxTeam.files_upload(f.read(), dropbox_file_path, mode=dropbox.files.WriteMode('overwrite'))
|
| 948 |
+
print(f"File replaced successfully at")
|
| 949 |
+
except dropbox.exceptions.ApiError as e:
|
| 950 |
+
print(f"Error replacing the file: {e}")
|
| 951 |
+
# return dburl
|
| 952 |
+
|
| 953 |
+
def getallguessednames():
|
| 954 |
+
guessednamesfinal = []
|
| 955 |
+
# Retrieve column data from the worksheet
|
| 956 |
+
global worksheetw
|
| 957 |
+
guessednames = worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 958 |
+
# Skip the first three entries and filter out empty/whitespace strings
|
| 959 |
+
for item in guessednames[3:]:
|
| 960 |
+
if item.strip() and item not in guessednamesfinal: # Remove surrounding whitespace and check for uniqueness
|
| 961 |
+
guessednamesfinal.append(item)
|
| 962 |
+
print('guessednamesfinal:', guessednamesfinal)
|
| 963 |
+
return guessednamesfinal
|