Marthee commited on
Commit
b3213ac
·
1 Parent(s): ef6e2f1

Update pilecaps_adr.py

Browse files
Files changed (1) hide show
  1. pilecaps_adr.py +485 -160
pilecaps_adr.py CHANGED
@@ -42,37 +42,10 @@ from google.oauth2 import service_account
42
  import pygsheets
43
  import re
44
  import pandas
45
- #import openpyxl
46
-
47
- #from google.colab import drive
48
- #drive.mount('/content/drive')
49
-
50
- #pip install pymupdf -q
51
-
52
- #path='/content/drive/MyDrive/Colab Notebooks/Pile caps plans/13886-B3-NO_TEXT.pdf'
53
- # images = convert_from_path(path)
54
- # # images = convert_from_path('/content/drive/MyDrive/Colab Notebooks/pile caps.pdf')
55
-
56
-
57
- # for i in range(len(images)):
58
-
59
- # # Save pages as images in the pdf
60
- # images[i].save('page'+ str(i) +'.jpg', 'JPEG')
61
-
62
- # img = cv2.imread('/content/page0.jpg') #RBG format
63
- # cv2_imshow(img)
64
- # img.shape
65
-
66
- # import fitz
67
-
68
- # doc = fitz.open(path)
69
- # for page in doc:
70
- # pix = page.get_pixmap(dpi=200) # render page to an image
71
- # pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
72
- # img=np.array(pl)
73
- # img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
74
- # # newi=np.array(img1)
75
- # img.shape
76
 
77
  def detectCircles(imgOriginal ):
78
  im=imgOriginal.copy()
@@ -596,7 +569,7 @@ def getAreasPerimeter(green2,img,number,num1,num2,flag,finalColorArray,color=[0,
596
  #if flag=='area':
597
  # addedMargin=area1+perimeter1*2
598
  # areaa=round(addedMargin* (num1/(num2+perimeter1*2) ), 3) # true value of area of any shape/ area px value of same shape
599
- areaa=round(area1*(num1/num2),3)
600
  appended.append([areaa,width,height])
601
 
602
  #else:
@@ -676,28 +649,20 @@ def FillDictionary(green2,SimilarAreaDictionary,img,number,num1,num2,flag,finalC
676
  SimilarAreaDictionary.loc[len(SimilarAreaDictionary)] =mydata
677
  # s= SimilarAreaDictionary
678
  for i in range(len(SimilarAreaDictionary)):
679
- # SimilarAreaDictionary.loc[i, "R"] = colorRanges[i][0]
680
- # SimilarAreaDictionary.loc[i, "G"] = colorRanges[i][1]
681
- # SimilarAreaDictionary.loc[i, "B"] = colorRanges[i][2]
682
  SimilarAreaDictionary['R'].loc[i] =colorRanges[i][0]
683
  SimilarAreaDictionary['G'].loc[i] =colorRanges[i][1]
684
  SimilarAreaDictionary['B'].loc[i] = colorRanges[i][2]
685
  colorsUsed.append(colorRanges[i])
686
- # x='#%02x%02x%02x' % (colorRanges[i])
687
- # xx='#%02x%02x%02x' % ( colorRanges[i][0] , colorRanges[i][1] , colorRanges[i][2] )
688
- # print( xx)
689
- # s=( SimilarAreaDictionary.style.apply('background-color: %s' % ('#%02x%02x%02x' % ( colorRanges[i][0] , colorRanges[i][1] , colorRanges[i][2] )), subset=['Color'] ) )
690
-
691
 
692
 
693
- return SimilarAreaDictionary, colorsUsed
694
- def drawAllContours(img,number,finalColorArray,num1,num2,flag):
695
  green2=allpreSteps(img)
696
- # doc = fitz.open(path)
697
- # page = doc[0]
698
- # page.set_rotation(0)
699
- # pix=page.get_pixmap()
700
- # ratio = pix.width/ img.shape[1]
701
 
702
  areasinImage=[]
703
  totaldf=pd.DataFrame()
@@ -727,8 +692,8 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
727
  if eachcolor==firstcolor: # 3shan a3rf el array of colors et3adet kam mara - to support embedded levels
728
  counter+=1
729
 
730
- contourss,rgbcolor,invertedmask=findContoursFullImage(green2,maskDone,number,finalColorArray,num1,num2,flag,eachcolor)
731
- SimilarAreaDictionary, colorsUsed= FillDictionary(green2,SimilarAreaDictionary,maskDone,number,num1,num2,flag,finalColorArray,rgbcolor,eachcolor)
732
 
733
  a = SimilarAreaDictionary.to_numpy()
734
 
@@ -757,10 +722,10 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
757
  for point in approx:
758
  x1, y1 = point[0]
759
 
760
- #shape.append([int(x1*ratio),int(y1*ratio)])
761
  # shape= np.fliplr(shape)
762
 
763
- cv2.circle(imgArea1, (x1, y1), 4, (0, 255, 0), -1)
764
  allpoints.append(shape)
765
  # print(x,y,width,height)
766
  # print(allpoints)
@@ -773,14 +738,14 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
773
  widthMax= width+10
774
  heightMin=height-10
775
  heightMax= height+10
776
- if num1 !=0 and num2!=0:
777
- widthh=round(width*(num1/num2),3)
778
- heightt=round(height*(num1/num2),3)
779
  # if flag=='area':
780
- areaa=round(area1* (num1/num2 ), 3) # true value of area of any shape/ area px value of same shape
781
 
782
  # elif flag=='perimeter':
783
- perimeterr=round(perimeter1* (num1/num2 ), 3)
784
  else:
785
  areaa=area1
786
  perimeterr=perimeter1
@@ -807,8 +772,15 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
807
  # print(index)
808
  # cv2.drawContours(imgArea1, [contour], 0, (int(rgbcolor[2]), int(rgbcolor[1]), int(rgbcolor[0])), -1)
809
  cv2.drawContours(imgArea1, [contour], 0, ( int(SimilarAreaDictionary['B'].loc[i]), int(SimilarAreaDictionary['G'].loc[i]), int(SimilarAreaDictionary['R'].loc[i])), -1)
810
-
811
- cv2.putText(imgtransparent1,'Area= '+str(areaa) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
 
 
 
 
 
 
 
812
  # cv2.putText(imgtransparent1,'Width= '+str(width) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
813
  # cv2.putText(imgtransparent1,'Length= '+str(height) , (x+50,y-20) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
814
  areasinImage.append(areaa)
@@ -826,9 +798,9 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
826
  #########################
827
  else:
828
 
829
- SimilarAreaDictionary= pd.DataFrame(columns=['Color','Rounded','Width','Height','Perimeter','Occurences','Total Perimeter','Area','Total Area','R','G','B'])
830
- contourss=findContoursFullImage(green2,img,number,finalColorArray,num1,num2,flag)
831
- SimilarAreaDictionary,colorsUsed= FillDictionary(green2,SimilarAreaDictionary,img,number,num1,num2,flag,finalColorArray)
832
  # print('filled')
833
  for contour in contourss:
834
  # shape=[]
@@ -842,7 +814,7 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
842
  approx = cv2.approxPolyDP(contour, 0.005 * perimeter1, True)
843
  for point in approx:
844
  x1, y1 = point[0]
845
- # shape.append([int(x1*ratio),int(y1*ratio)])
846
  allpoints.append(shape)
847
  if (angleR != 90.0 and angleR != -90.0 and angleR != 0.0 and angleR != -0.0 ): #inclined b ay degree
848
  width=widthR
@@ -854,12 +826,13 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
854
  heightMax= height+10
855
 
856
 
857
- if num1 !=0 and num2!=0:
858
  # if flag=='area':
859
- addedMargin=area1+perimeter1*2
860
- areaa=round(addedMargin* (num1/(num2+perimeter1*2) ), 3) # true value of area of any shape/ area px value of same shape
861
  # elif flag=='perimeter':
862
- perimeterr=round(perimeter1* (num1/num2 ), 3)
 
863
  else:
864
  areaa=area1
865
  perimeterr=perimeter1
@@ -883,17 +856,17 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
883
  passed=1
884
  cv2.drawContours(imgArea1, [contour], 0, ( int(SimilarAreaDictionary['B'].loc[i]), int(SimilarAreaDictionary['G'].loc[i]), int(SimilarAreaDictionary['R'].loc[i])), -1)
885
 
886
- # annot = page.add_polygon_annot( points=shape ) # 'Polygon'
887
- # annot.set_border(width=0.3, dashes=[2])
888
- # annot.set_colors( fill=( int(SimilarAreaDictionary['B'].loc[i])/255 , int(SimilarAreaDictionary['G'].loc[i])/255 , int(SimilarAreaDictionary['R'].loc[i])/255 ) )
889
- # # annot.set_colors( fill=(1,0,1) )
890
- # annot.set_opacity(0.5)
891
- # annot.set_info(content='kkk',subject='MEE',title='uuum')
892
- # # annot.set_line_ends(fitz.PDF_ANNOT_LE_DIAMOND, fitz.PDF_ANNOT_LE_CIRCLE)
893
- # annot.update()
894
- #cv2.putText(imgtransparent1,'area= '+str(areaa) + ' m', (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
895
- cv2.putText(imgtransparent1,'Width= '+str(width) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
896
- cv2.putText(imgtransparent1,'Length= '+str(height) , (x+50,y-40) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
897
  cv2.drawContours(imgArea1, [contour], 0, (0, 0, 255),2)
898
  cv2.drawContours(imgPerimeter1, [contour], 0, (0, 0, 255), 4)
899
  cv2.putText(imgPerimeter1,'Perimeter='+str(perimeterr), (x+30,y-30) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
@@ -907,12 +880,134 @@ def drawAllContours(img,number,finalColorArray,num1,num2,flag):
907
  print(SimilarAreaDictionary)
908
 
909
  # annotationsSave
910
- # doc.save('k.pdf', deflate=True)
911
- gc,spreadsheet_service,spreadsheetId, spreadsheet_url=legendGoogleSheets(SimilarAreaDictionary,colorsUsed)
912
- return imgPerimeter1,image_new1,SimilarAreaDictionary, colorsUsed , spreadsheet_url , spreadsheetId
913
-
914
-
915
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916
  #######################################################
917
 
918
  def getTitle(path):
@@ -934,6 +1029,7 @@ def retrieveMCCol(gc):
934
  def getdropdownValues(gc,spreadsheet_service,spreadsheetid):
935
  dropdownValues=[]
936
  ws=gc.open_by_key('1A8VtqLFhe2NXPxIjfAilbxF9xV2eSzZ-yZ9GP8_5jSo') ## spreadsheet containing mc-t names
 
937
  worksheet = ws.worksheet(0)
938
  response = spreadsheet_service.spreadsheets().get(
939
  spreadsheetId=spreadsheetid, fields='*',
@@ -965,47 +1061,72 @@ def authorizeLegend():
965
  gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
966
  return spreadsheet_service,drive_service,gc
967
 
968
- def legendGoogleSheets(SimilarAreaDictionary,colorsUsed):
969
  # authorize uing json file
970
  # SimilarAreaDictionary.drop(['Rounded', 'Width','Height','R','G','B'], axis=1, inplace=True)
971
  spreadsheet_service,drive_service,gc=authorizeLegend()
972
-
 
973
  ########
974
- # legendTitle=getTitle(path)
975
- # titles=gc.spreadsheet_titles()
976
- # # print(titles)
977
- # if legendTitle in titles:
978
- # print('found sheet ')
979
- # else:
980
- # ####### create new sheet
981
- # print('creating new sheeet')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
 
984
-
985
- # LegendName=getTitle(path)
986
- spreadsheet_details = {
987
- 'properties': {
988
- 'title': 'namee'
989
- }
990
- }
991
- sheet = spreadsheet_service.spreadsheets().create(body=spreadsheet_details,
992
- fields='spreadsheetId').execute()
993
-
994
- # spreadsheetId = sheet.get('spreadsheetId')
995
- spreadsheetId='1dGhc1ffsrTxBkgcSYGLU-l1BJk5VFXozMWdYeEikEdo'
996
- # print('Spreadsheet ID: {0}'.format(spreadsheetId))
997
- permission1 = {
998
- 'type': 'anyone',
999
- 'role': 'writer',
1000
- # 'emailAddress': 'marthe.adr@gmail.com'
1001
- }
1002
- drive_service.permissions().create(fileId=spreadsheetId, body=permission1).execute()
1003
  ###################3
1004
  #open sheet
1005
  # spreadsheetId='1dtDi_6-g3jkn6ePVlzM6PM3FE8wIHzyL2Rt4ksH59SE'
1006
- ws=gc.open_by_key(spreadsheetId)
 
1007
  sheetId = '0' # Please set sheet ID.
1008
  worksheet = ws.worksheet(0)
 
 
1009
  second_row_data=['Nr','m2','Total','m','Total']
1010
 
1011
  top_header_format = [
@@ -1014,66 +1135,71 @@ def legendGoogleSheets(SimilarAreaDictionary,colorsUsed):
1014
  'mergeType': 'MERGE_ROWS',
1015
  'range': {
1016
  'sheetId': '0',
1017
- 'startRowIndex': 0,
1018
- 'endRowIndex': 1,
1019
  'startColumnIndex': 3,
1020
  'endColumnIndex':5
1021
 
1022
 
1023
  }
1024
  }},
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
  {'mergeCells': {
1026
  'mergeType': 'MERGE_ROWS',
1027
  'range': {
1028
  'sheetId': '0',
1029
  'startRowIndex': 0,
1030
  'endRowIndex': 1,
1031
- 'startColumnIndex': 5,
1032
  'endColumnIndex':7
1033
  }
1034
 
1035
  }}
1036
- # ,{'mergeCells': {
1037
- # 'mergeType': 'MERGE_ROWS',
1038
- # 'range': {
1039
- # 'sheetId': '0',
1040
- # 'startRowIndex': 0,
1041
- # 'endRowIndex': 1,
1042
- # 'startColumnIndex': 6,
1043
- # 'endColumnIndex':8
1044
-
1045
-
1046
- # }
1047
- # }}
1048
  ]
1049
  spreadsheet_service.spreadsheets().batchUpdate( spreadsheetId=spreadsheetId , body={'requests': top_header_format} ).execute()
1050
-
1051
- worksheet.cell((1,1)).value='Guess'
1052
- worksheet.cell((1,2)).value='Color'
1053
- worksheet.cell((1,3)).value='Count'
1054
- worksheet.cell((1,4)).value='Areas'
1055
- worksheet.cell((1,6)).value='Perimeter'
1056
 
1057
- worksheet.update_row(2,second_row_data,col_offset=2)
1058
 
1059
- worksheet.update_col(3,list(SimilarAreaDictionary['Occurences']),row_offset=2)
1060
- worksheet.update_col(4,list(SimilarAreaDictionary['Area']),row_offset=2)
1061
- worksheet.update_col(5,list(SimilarAreaDictionary['Total Area']),row_offset=2)
1062
- worksheet.update_col(6,list(SimilarAreaDictionary['Perimeter']),row_offset=2)
1063
- worksheet.update_col(7,list(SimilarAreaDictionary['Total Perimeter']),row_offset=2)
1064
 
1065
  rowsLen=len(SimilarAreaDictionary.values.tolist()) #kam row -- last row = rowsLen +1
1066
  lastcell=worksheet.cell((rowsLen+2,1)) #row,col
1067
  lastcellNotation=str(lastcell.address.label)
1068
- worksheet.set_data_validation('A3',lastcellNotation, condition_type='ONE_OF_LIST', condition_values=['Ground Beam','Pile Cap'], showCustomUi=True)
1069
 
1070
  #get lengths of df
1071
  columnsLen=len(SimilarAreaDictionary.columns.values.tolist()) #kam column -- last col = columnsLen+1 3shan base0
1072
  lastUsedCol=columnsLen+1
1073
 
1074
- worksheet.adjust_column_width(start=2,end=8)
1075
-
1076
 
 
 
 
 
1077
  sheetId = '0' # Please set sheet ID.
1078
  for i in range(len(colorsUsed)):
1079
 
@@ -1085,7 +1211,7 @@ def legendGoogleSheets(SimilarAreaDictionary,colorsUsed):
1085
  "updateCells": {
1086
  "range": {
1087
  "sheetId": sheetId,
1088
- "startRowIndex": i+2,
1089
  # "endRowIndex":4 ,
1090
  "startColumnIndex":1,
1091
 
@@ -1102,7 +1228,7 @@ def legendGoogleSheets(SimilarAreaDictionary,colorsUsed):
1102
  "red": r/255,
1103
  "green": g/255,
1104
  "blue": b/255,
1105
- # "alpha": 0.8
1106
 
1107
  }
1108
 
@@ -1114,13 +1240,92 @@ def legendGoogleSheets(SimilarAreaDictionary,colorsUsed):
1114
  "fields": "userEnteredFormat.backgroundColor",
1115
 
1116
  }
 
 
 
1117
  }
1118
  ]
1119
  }
1120
  res = spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=body).execute()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  spreadsheet_url = "https://docs.google.com/spreadsheets/d/%s" % spreadsheetId
1122
  print(spreadsheet_url)
1123
-
1124
  return gc,spreadsheet_service,spreadsheetId ,spreadsheet_url
1125
  #######################
1126
 
@@ -1136,11 +1341,21 @@ def mapnametoLegend(McTName):
1136
  spreadsheet_key =str(lastelement[0]) # Please set the Spreadsheet ID.
1137
 
1138
  ws = gc.open_by_key(spreadsheet_key)
1139
-
1140
- # # ws.add_worksheet("Summary") # Please set the new sheet name.
1141
-
 
 
 
 
 
 
 
 
 
1142
  worksheetw = ws.worksheet(0) #legend
1143
- worksheetS = ws.worksheet_by_title('Summary')
 
1144
  worksheetS.clear()
1145
  countnames=0
1146
  row0=['MC_T Name','Qty','Unit']
@@ -1149,23 +1364,27 @@ def mapnametoLegend(McTName):
1149
  for i in range(len(McTName)):
1150
  allgbnames=''
1151
  item=''
1152
- print(McTName[i][2])
1153
 
1154
- # firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
1155
 
1156
  # print(firstpart) #[ Ground Beams , m2 ]
1157
- if (McTName[i][2]=='area'):
 
1158
  rowvalue=5# column 5
1159
  ar=0
1160
- if (McTName[i][2]=='perimeter'):
 
 
1161
  rowvalue=7# column 7
1162
  ar=0
 
1163
  # # print( worksheet.get_col(5, include_tailing_empty=False) )
1164
 
1165
  for m in McTName[i][1]:
1166
  print(m)
1167
  # if len(McTName[i][1])>2:
1168
- if m.startswith('gb'):
1169
  allgbnames+= m +' +'
1170
 
1171
  print(m)
@@ -1173,11 +1392,20 @@ def mapnametoLegend(McTName):
1173
  print(roww)
1174
  for j in range(len(roww)):
1175
  ar+=float(worksheetw.cell((roww[j].row ,rowvalue)).value)
1176
-
 
 
 
 
 
 
 
 
1177
  else:
1178
- item+=m + ','
 
1179
 
1180
- n= McTName[i][0] + '('+ allgbnames[:-1] +',' + item[:-1] + ')'
1181
  print(n)
1182
 
1183
 
@@ -1192,9 +1420,106 @@ def mapnametoLegend(McTName):
1192
 
1193
  # for count in range(len(name[1])):
1194
  # print(count)
1195
- rowi=[str(n),ar,'m']
1196
  worksheetS.update_row(i+2,rowi)
1197
- worksheetS.adjust_column_width(start=1,end=4)
 
 
 
 
 
 
 
 
1198
 
1199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1200
  # print(x,xarea)
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  import pygsheets
43
  import re
44
  import pandas
45
+ import fitz
46
+ import json
47
+ import db
48
+ import ast
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  def detectCircles(imgOriginal ):
51
  im=imgOriginal.copy()
 
569
  #if flag=='area':
570
  # addedMargin=area1+perimeter1*2
571
  # areaa=round(addedMargin* (num1/(num2+perimeter1*2) ), 3) # true value of area of any shape/ area px value of same shape
572
+ areaa=round(area1*num1,3)
573
  appended.append([areaa,width,height])
574
 
575
  #else:
 
649
  SimilarAreaDictionary.loc[len(SimilarAreaDictionary)] =mydata
650
  # s= SimilarAreaDictionary
651
  for i in range(len(SimilarAreaDictionary)):
 
 
 
652
  SimilarAreaDictionary['R'].loc[i] =colorRanges[i][0]
653
  SimilarAreaDictionary['G'].loc[i] =colorRanges[i][1]
654
  SimilarAreaDictionary['B'].loc[i] = colorRanges[i][2]
655
  colorsUsed.append(colorRanges[i])
 
 
 
 
 
656
 
657
 
658
+ return SimilarAreaDictionary, colorsUsed , areas_Perimeters
659
+ def drawAllContours(img,number,finalColorArray,ratioarea,ratioperim,flag , path,pdfpath):
660
  green2=allpreSteps(img)
661
+ doc = fitz.open('dropbox_plans/1.0/'+path)
662
+ page = doc[0]
663
+ page.set_rotation(0)
664
+ pix=page.get_pixmap()
665
+ ratio = pix.width/ img.shape[1]
666
 
667
  areasinImage=[]
668
  totaldf=pd.DataFrame()
 
692
  if eachcolor==firstcolor: # 3shan a3rf el array of colors et3adet kam mara - to support embedded levels
693
  counter+=1
694
 
695
+ contourss,rgbcolor,invertedmask=findContoursFullImage(green2,maskDone,number,finalColorArray,ratioarea,ratioperim,flag,eachcolor)
696
+ SimilarAreaDictionary, colorsUsed , areas_Perimeters= FillDictionary(green2,SimilarAreaDictionary,maskDone,number,ratioarea,ratioperim,flag,finalColorArray,rgbcolor,eachcolor)
697
 
698
  a = SimilarAreaDictionary.to_numpy()
699
 
 
722
  for point in approx:
723
  x1, y1 = point[0]
724
 
725
+ shape.append([int(x1*ratio),int(y1*ratio)])
726
  # shape= np.fliplr(shape)
727
 
728
+ # cv2.circle(imgArea1, (x1, y1), 4, (0, 255, 0), -1)
729
  allpoints.append(shape)
730
  # print(x,y,width,height)
731
  # print(allpoints)
 
738
  widthMax= width+10
739
  heightMin=height-10
740
  heightMax= height+10
741
+ if ratioarea !=0 and ratioperim!=0:
742
+ widthh=round(width*ratioperim,3)
743
+ heightt=round(height*ratioperim,3)
744
  # if flag=='area':
745
+ areaa=round(area1* ratioarea, 3) # true value of area of any shape/ area px value of same shape
746
 
747
  # elif flag=='perimeter':
748
+ perimeterr=round(perimeter1* ratioperim, 3)
749
  else:
750
  areaa=area1
751
  perimeterr=perimeter1
 
772
  # print(index)
773
  # cv2.drawContours(imgArea1, [contour], 0, (int(rgbcolor[2]), int(rgbcolor[1]), int(rgbcolor[0])), -1)
774
  cv2.drawContours(imgArea1, [contour], 0, ( int(SimilarAreaDictionary['B'].loc[i]), int(SimilarAreaDictionary['G'].loc[i]), int(SimilarAreaDictionary['R'].loc[i])), -1)
775
+ annot = page.add_polygon_annot( points=shape ) # 'Polygon'
776
+ annot.set_border(width=0.3, dashes=[2])
777
+ annot.set_colors( fill=( int(SimilarAreaDictionary['R'].loc[i])/255 , int(SimilarAreaDictionary['G'].loc[i])/255 , int(SimilarAreaDictionary['B'].loc[i])/255 ) )
778
+ # annot.set_colors( fill=(1,0,1) )
779
+ annot.set_opacity(0.5)
780
+ annot.set_info(content='Area='+str(areaa)+' m2' +'\n \nPerimeter='+str(perimeterr)+' m',subject='ADR Team')#,title='uuum')
781
+ # annot.set_line_ends(fitz.PDF_ANNOT_LE_DIAMOND, fitz.PDF_ANNOT_LE_CIRCLE)
782
+ annot.update()
783
+ cv2.putText(imgtransparent1,'Area= '+str(area1) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
784
  # cv2.putText(imgtransparent1,'Width= '+str(width) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
785
  # cv2.putText(imgtransparent1,'Length= '+str(height) , (x+50,y-20) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
786
  areasinImage.append(areaa)
 
798
  #########################
799
  else:
800
 
801
+ SimilarAreaDictionary= pd.DataFrame(columns=['Color','Rounded','Width','Height','Occurences','Area','Total Area','Perimeter','Total Perimeter','R','G','B'])
802
+ contourss=findContoursFullImage(green2,img,number,finalColorArray,ratioarea,ratioperim,flag)
803
+ SimilarAreaDictionary,colorsUsed , areas_Perimeters= FillDictionary(green2,SimilarAreaDictionary,img,number,ratioarea,ratioperim,flag,finalColorArray)
804
  # print('filled')
805
  for contour in contourss:
806
  # shape=[]
 
814
  approx = cv2.approxPolyDP(contour, 0.005 * perimeter1, True)
815
  for point in approx:
816
  x1, y1 = point[0]
817
+ shape.append([int(x1*ratio),int(y1*ratio)])
818
  allpoints.append(shape)
819
  if (angleR != 90.0 and angleR != -90.0 and angleR != 0.0 and angleR != -0.0 ): #inclined b ay degree
820
  width=widthR
 
826
  heightMax= height+10
827
 
828
 
829
+ if ratioarea !=0 and ratioperim!=0:
830
  # if flag=='area':
831
+ # addedMargin=area1+perimeter1*2
832
+ # areaa=round(addedMargin* (num1/(num2+perimeter1*2) ), 3) # true value of area of any shape/ area px value of same shape
833
  # elif flag=='perimeter':
834
+ areaa=round(area1* ratioarea, 3) # true value of area of any shape/ area px value of same shape
835
+ perimeterr=round(perimeter1* ratioperim, 3)
836
  else:
837
  areaa=area1
838
  perimeterr=perimeter1
 
856
  passed=1
857
  cv2.drawContours(imgArea1, [contour], 0, ( int(SimilarAreaDictionary['B'].loc[i]), int(SimilarAreaDictionary['G'].loc[i]), int(SimilarAreaDictionary['R'].loc[i])), -1)
858
 
859
+ annot = page.add_polygon_annot( points=shape ) # 'Polygon'
860
+ annot.set_border(width=0.3, dashes=[2])
861
+ annot.set_colors( fill=( int(SimilarAreaDictionary['R'].loc[i])/255 , int(SimilarAreaDictionary['G'].loc[i])/255 , int(SimilarAreaDictionary['B'].loc[i])/255 ) )
862
+ # annot.set_colors( fill=(1,0,1) )
863
+ annot.set_opacity(0.5)
864
+ annot.set_info(content='Area='+str(areaa)+' m2' +'\n \nPerimeter='+str(perimeterr)+' m',subject='ADR Team')#,title='uuum')
865
+ # annot.set_line_ends(fitz.PDF_ANNOT_LE_DIAMOND, fitz.PDF_ANNOT_LE_CIRCLE)
866
+ annot.update()
867
+ cv2.putText(imgtransparent1,'area= '+str(area1) + ' m', (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
868
+ # cv2.putText(imgtransparent1,'Width= '+str(width) , (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
869
+ # cv2.putText(imgtransparent1,'Length= '+str(height) , (x+50,y-40) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
870
  cv2.drawContours(imgArea1, [contour], 0, (0, 0, 255),2)
871
  cv2.drawContours(imgPerimeter1, [contour], 0, (0, 0, 255), 4)
872
  cv2.putText(imgPerimeter1,'Perimeter='+str(perimeterr), (x+30,y-30) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
 
880
  print(SimilarAreaDictionary)
881
 
882
  # annotationsSave
883
+ # doc.save('k.pdf', deflate=True)
884
+ pdflink= db.dropbox_upload_file(doc=doc,pdfname=path,pdfpath=pdfpath)
885
+ # list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
886
+ # doc1 = fitz.open('k.pdf')
887
+ # for page in doc1:
888
+ # for annot in page.annots():
889
+ # list1.loc[len(list1)] =annot.info
890
+ # print(list1)
891
+ dbx=db.dropbox_connect()
892
+ md, res =dbx.files_download(path= pdfpath+path)
893
+ data = res.content
894
+ doc=fitz.open("pdf", data)
895
+ # list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
896
+ list1=pd.DataFrame(columns=['content', 'id', 'subject'])
897
+ for page in doc:
898
+ for annot in page.annots():
899
+ list1.loc[len(list1)] =annot.info
900
+
901
+ print(list1)
902
+ gc,spreadsheet_service,spreadsheetId, spreadsheet_url=legendGoogleSheets(SimilarAreaDictionary , path,colorsUsed)
903
+ return imgPerimeter1,image_new1,SimilarAreaDictionary, colorsUsed , spreadsheet_url , spreadsheetId , list1 , pdflink , areas_Perimeters
904
+
905
+ ######################################################
906
+
907
+ def deletemarkups(list1, pdfpath , path):
908
+ '''list1 : original markup pdf
909
+ list2 : deleted markup pdf
910
+ deletedrows : deleted markups - difference betw both dfs
911
+
912
+ '''
913
+ myDict1=eval(list1)
914
+ list1=pd.DataFrame(myDict1)
915
+
916
+ areastodelete = []
917
+ perimstodelete=[]
918
+ # list2=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
919
+ # doc = fitz.open('k.pdf')
920
+ # for page in doc:
921
+ # for annot in page.annots():
922
+ # list2.loc[len(list2)] =annot.info
923
+ dbx=db.dropbox_connect()
924
+
925
+ md, res =dbx.files_download(path= pdfpath+path)
926
+ data = res.content
927
+ doc=fitz.open("pdf", data)
928
+ list2=pd.DataFrame(columns=['content', 'id', 'subject'])
929
+ # list2=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
930
+ for page in doc:
931
+ for annot in page.annots():
932
+ list2.loc[len(list2)] =annot.info
933
+ print(list1)
934
+ deletedrows=pd.concat([list1,list2]).drop_duplicates(keep=False)
935
+
936
+ print(deletedrows,len(deletedrows))
937
+ flag=0
938
+ if len(deletedrows)!=0:
939
+ flag=1
940
+ deletedrows=deletedrows[['content', 'id', 'subject']]
941
+ deletedrows = deletedrows.drop(deletedrows.index[deletedrows['content'].str.startswith('Scale')] )#, inplace=True)
942
+ else:
943
+ flag=0
944
+ return deletedrows
945
+ # return SimilarAreaDictionary
946
+ def deletefromlegend(deletedrows,SimilarAreaDictionarycopy, areaPermArr):
947
+ items=[]
948
+
949
+ areaPermArr=ast.literal_eval(areaPermArr)
950
+
951
+ # print(type(areaPermArr))
952
+ myDict=eval(SimilarAreaDictionarycopy)
953
+ # print(type(myDict))
954
+ SimilarAreaDictionarycopy=pd.DataFrame(myDict)
955
+ strings=deletedrows['content']
956
+
957
+ areastodelete = []
958
+ perimstodelete=[]
959
+
960
+
961
+ for item in strings:
962
+ items.append(str(item).split('\n \n'))
963
+
964
+ for i in range(len(items)):
965
+ # areastodelete.append(round(float(re.findall("\d+\.\d+", str(items[i][0]).split()[0])[0]),1) )
966
+ areastodelete.append(float(re.findall("\d+\.\d+", str(items[i][0]).split()[0])[0]))
967
+ perimstodelete.append(float(re.findall("\d+\.\d+", str(items[i][1]).split()[0])[0]) )
968
+
969
+
970
+ for i in range(len(areastodelete)):#item in areastodelete:
971
+ areamin=round(areastodelete[i],1)- 0.3
972
+ areamax=round(areastodelete[i],1)+ 0.3
973
+ perimmin=round(perimstodelete[i],1)- 0.3
974
+ perimmax=round(perimstodelete[i],1)+ 0.3
975
+ for p in range(len(areaPermArr)):
976
+ if areastodelete[i] in areaPermArr[p]:
977
+ area= areaPermArr[p][0]
978
+ width= areaPermArr[p][1]
979
+ height= areaPermArr[p][2]
980
+
981
+ widthMin= width -10
982
+ widthMax= width +10
983
+ heightMin = height-10
984
+ heightMax=height+10
985
+ print(width, widthMin ,height, heightMin)
986
+ found=SimilarAreaDictionarycopy.loc[SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Rounded'] >=areamin) & (SimilarAreaDictionarycopy['Rounded']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) ) & ( ((SimilarAreaDictionarycopy['Width']>=widthMin) & (SimilarAreaDictionarycopy['Width']<=widthMax) & (SimilarAreaDictionarycopy['Height']>=heightMin) & (SimilarAreaDictionarycopy['Height']<=heightMax) ) | ((SimilarAreaDictionarycopy['Width']>=heightMin) & (SimilarAreaDictionarycopy['Width']<=heightMax) & (SimilarAreaDictionarycopy['Height']>=widthMin) & (SimilarAreaDictionarycopy['Height']<=widthMax) )) ]]
987
+
988
+ # if ( SimilarAreaDictionary['Rounded'].loc[i] <= areaPerimeterMax and SimilarAreaDictionary['Rounded'].loc[i] >= areaPerimeterMin) :
989
+ # if (SimilarAreaDictionary['Width'].loc[i] <=widthMax and SimilarAreaDictionary['Width'].loc[i] >= widthMin) and (SimilarAreaDictionary['Height'].loc[i] <= heightMax and SimilarAreaDictionary['Height'].loc[i] >= heightMin ) or (SimilarAreaDictionary['Width'].loc[i] <=heightMax and SimilarAreaDictionary['Width'].loc[i] >= heightMin) and (SimilarAreaDictionary['Height'].loc[i] <= widthMax and SimilarAreaDictionary['Height'].loc[i] >= widthMin ) :
990
+
991
+ print(found.index.values)
992
+ if len(found.index.values ) >0:
993
+ occ=SimilarAreaDictionarycopy.loc[found.index.values[0],'Occurences']
994
+ if occ== 1: #drop row
995
+ print('occ=1')
996
+ # print(SimilarAreaDictionarycopy[(SimilarAreaDictionarycopy['Rounded'] == item ) ].index)
997
+ # SimilarAreaDictionarycopy.drop(SimilarAreaDictionarycopy['Occurences'] == item)
998
+ SimilarAreaDictionarycopy= SimilarAreaDictionarycopy.drop(found.index.values[0])
999
+
1000
+ else: #occ minus 1 , total area - areavalue , total perim - perimvalue
1001
+ print('occ>1')
1002
+ idx=SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Rounded'] >=areamin) & (SimilarAreaDictionarycopy['Rounded']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) ) & ( ((SimilarAreaDictionarycopy['Width']>=widthMin) & (SimilarAreaDictionarycopy['Width']<=widthMax) & (SimilarAreaDictionarycopy['Height']>=heightMin) & (SimilarAreaDictionarycopy['Height']<=heightMax) ) | ((SimilarAreaDictionarycopy['Width']>=heightMin) & (SimilarAreaDictionarycopy['Width']<=heightMax) & (SimilarAreaDictionarycopy['Height']>=widthMin) & (SimilarAreaDictionarycopy['Height']<=widthMax) )) ]
1003
+ # SimilarAreaDictionary.loc[idx]['Total Area']
1004
+ # for j in range(occ):
1005
+ SimilarAreaDictionarycopy.loc[idx,'Total Area'] = SimilarAreaDictionarycopy.loc[idx,'Total Area'] - areastodelete[i]
1006
+ SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] = SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] - perimstodelete[i]
1007
+ SimilarAreaDictionarycopy.loc[idx,'Occurences'] = int(SimilarAreaDictionarycopy.loc[idx,'Occurences']) - 1
1008
+
1009
+ print(SimilarAreaDictionarycopy)
1010
+ return SimilarAreaDictionarycopy
1011
  #######################################################
1012
 
1013
  def getTitle(path):
 
1029
  def getdropdownValues(gc,spreadsheet_service,spreadsheetid):
1030
  dropdownValues=[]
1031
  ws=gc.open_by_key('1A8VtqLFhe2NXPxIjfAilbxF9xV2eSzZ-yZ9GP8_5jSo') ## spreadsheet containing mc-t names
1032
+
1033
  worksheet = ws.worksheet(0)
1034
  response = spreadsheet_service.spreadsheets().get(
1035
  spreadsheetId=spreadsheetid, fields='*',
 
1061
  gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
1062
  return spreadsheet_service,drive_service,gc
1063
 
1064
+ def legendGoogleSheets(SimilarAreaDictionary,path , spreadsheetId=0,colorsUsed=[]):
1065
  # authorize uing json file
1066
  # SimilarAreaDictionary.drop(['Rounded', 'Width','Height','R','G','B'], axis=1, inplace=True)
1067
  spreadsheet_service,drive_service,gc=authorizeLegend()
1068
+
1069
+ print('colorsss ', colorsUsed)
1070
  ########
1071
+ legendTitle='Legend of: ' +path
1072
+ titles=gc.spreadsheet_titles()
1073
+ ids=gc.spreadsheet_ids()
1074
+ print(ids)
1075
+ # # print(titles)
1076
+ if spreadsheetId in ids :
1077
+ print('found sheet ', spreadsheetId)
1078
+ ws=gc.open_by_key(spreadsheetId)
1079
+ colorsUsed=[]
1080
+ for i in range(len(SimilarAreaDictionary)):
1081
+ colorsUsed.append([SimilarAreaDictionary['R'].iloc[i] ,SimilarAreaDictionary['G'].iloc[i] , SimilarAreaDictionary['B'].iloc[i]] )
1082
+
1083
+ if legendTitle in titles:
1084
+ print('found sheet ', legendTitle)
1085
+ ws=gc.open(str(legendTitle))
1086
+ spreadsheetId=ws.id
1087
+ colorsUsed=[]
1088
+ for i in range(len(SimilarAreaDictionary)):
1089
+ colorsUsed.append([SimilarAreaDictionary['R'].iloc[i] ,SimilarAreaDictionary['G'].iloc[i] , SimilarAreaDictionary['B'].iloc[i]] )
1090
+
1091
+ else:
1092
+ # ####### create new sheet
1093
+ print('creating new sheeet')
1094
 
1095
+ spreadsheet_details = {
1096
+ 'properties': {
1097
+ 'title': 'Legend of: ' +path
1098
+ }
1099
+ }
1100
+ sheet = spreadsheet_service.spreadsheets().create(body=spreadsheet_details,
1101
+ fields='spreadsheetId').execute()
1102
+
1103
+ spreadsheetId = sheet.get('spreadsheetId')
1104
+ permission1 = {
1105
+ 'type': 'anyone',
1106
+ 'role': 'writer',
1107
+ # 'emailAddress': 'marthe.adr@gmail.com'
1108
+ }
1109
+ # permission2 = {
1110
+ # 'type': 'user',
1111
+ # 'role': 'writer',
1112
+ # 'emailAddress': 'marthe.adr@gmail.com',
1113
+ # 'pendingOwner': True
1114
 
1115
+
1116
+ # }
1117
+
1118
+
1119
+ drive_service.permissions().create(fileId=spreadsheetId, body=permission1, supportsAllDrives=True ).execute()
1120
+ # print('llliiiistt',drive_service.permissions().list(fileId=spreadsheetId))
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  ###################3
1122
  #open sheet
1123
  # spreadsheetId='1dtDi_6-g3jkn6ePVlzM6PM3FE8wIHzyL2Rt4ksH59SE'
1124
+ ws=gc.open_by_key(spreadsheetId)
1125
+
1126
  sheetId = '0' # Please set sheet ID.
1127
  worksheet = ws.worksheet(0)
1128
+ worksheet.title='Legend and data created'
1129
+ worksheet.clear()
1130
  second_row_data=['Nr','m2','Total','m','Total']
1131
 
1132
  top_header_format = [
 
1135
  'mergeType': 'MERGE_ROWS',
1136
  'range': {
1137
  'sheetId': '0',
1138
+ 'startRowIndex': 1,
1139
+ 'endRowIndex': 2,
1140
  'startColumnIndex': 3,
1141
  'endColumnIndex':5
1142
 
1143
 
1144
  }
1145
  }},
1146
+
1147
+ {'mergeCells': {
1148
+ 'mergeType': 'MERGE_ROWS',
1149
+ 'range': {
1150
+ 'sheetId': '0',
1151
+ 'startRowIndex': 1,
1152
+ 'endRowIndex': 2,
1153
+ 'startColumnIndex': 5,
1154
+ 'endColumnIndex':7
1155
+ }
1156
+
1157
+ }},
1158
+
1159
  {'mergeCells': {
1160
  'mergeType': 'MERGE_ROWS',
1161
  'range': {
1162
  'sheetId': '0',
1163
  'startRowIndex': 0,
1164
  'endRowIndex': 1,
1165
+ 'startColumnIndex': 0,
1166
  'endColumnIndex':7
1167
  }
1168
 
1169
  }}
 
 
 
 
 
 
 
 
 
 
 
 
1170
  ]
1171
  spreadsheet_service.spreadsheets().batchUpdate( spreadsheetId=spreadsheetId , body={'requests': top_header_format} ).execute()
1172
+ worksheet.cell((1,1)).value='Legend and Data Created'
1173
+ worksheet.cell((2,1)).value='Guess'
1174
+ worksheet.cell((2,2)).value='Color'
1175
+ worksheet.cell((2,3)).value='Count'
1176
+ worksheet.cell((2,4)).value='Areas'
1177
+ worksheet.cell((2,6)).value='Perimeter'
1178
 
1179
+ worksheet.update_row(3,second_row_data,col_offset=2)
1180
 
1181
+ worksheet.update_col(3,list(SimilarAreaDictionary['Occurences']),row_offset=3)
1182
+ worksheet.update_col(4,list(SimilarAreaDictionary['Area']),row_offset=3)
1183
+ worksheet.update_col(5,list(SimilarAreaDictionary['Total Area']),row_offset=3)
1184
+ worksheet.update_col(6,list(SimilarAreaDictionary['Perimeter']),row_offset=3)
1185
+ worksheet.update_col(7,list(SimilarAreaDictionary['Total Perimeter']),row_offset=3)
1186
 
1187
  rowsLen=len(SimilarAreaDictionary.values.tolist()) #kam row -- last row = rowsLen +1
1188
  lastcell=worksheet.cell((rowsLen+2,1)) #row,col
1189
  lastcellNotation=str(lastcell.address.label)
1190
+ # worksheet.set_data_validation('A3',lastcellNotation, condition_type='ONE_OF_LIST', condition_values=['Ground Beam','Pile Cap'], showCustomUi=True)
1191
 
1192
  #get lengths of df
1193
  columnsLen=len(SimilarAreaDictionary.columns.values.tolist()) #kam column -- last col = columnsLen+1 3shan base0
1194
  lastUsedCol=columnsLen+1
1195
 
1196
+ worksheet.adjust_column_width(start=2,end=3)
1197
+ worksheet.adjust_column_width(start=4,end=7,pixel_size=60)
1198
 
1199
+ colorsUsed=[]
1200
+ for i in range(len(SimilarAreaDictionary)):
1201
+ colorsUsed.append([SimilarAreaDictionary['R'].iloc[i] ,SimilarAreaDictionary['G'].iloc[i] , SimilarAreaDictionary['B'].iloc[i]] )
1202
+
1203
  sheetId = '0' # Please set sheet ID.
1204
  for i in range(len(colorsUsed)):
1205
 
 
1211
  "updateCells": {
1212
  "range": {
1213
  "sheetId": sheetId,
1214
+ "startRowIndex": i+3,
1215
  # "endRowIndex":4 ,
1216
  "startColumnIndex":1,
1217
 
 
1228
  "red": r/255,
1229
  "green": g/255,
1230
  "blue": b/255,
1231
+ "alpha": 0.4,
1232
 
1233
  }
1234
 
 
1240
  "fields": "userEnteredFormat.backgroundColor",
1241
 
1242
  }
1243
+
1244
+
1245
+
1246
  }
1247
  ]
1248
  }
1249
  res = spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=body).execute()
1250
+ body2={
1251
+ "requests": [
1252
+ {
1253
+ "updateBorders": {
1254
+ "range": {
1255
+ "sheetId": sheetId,
1256
+ "startRowIndex": 0,
1257
+ "endRowIndex": len(SimilarAreaDictionary)+3,
1258
+ "startColumnIndex": 0,
1259
+ "endColumnIndex": 7
1260
+ },
1261
+ "top": {
1262
+ "style": "SOLID",
1263
+ "width": 2,
1264
+ "color": {
1265
+ "red": 0.0,
1266
+ "green":0.0,
1267
+ "blue":0.0
1268
+ },
1269
+ },
1270
+ "bottom": {
1271
+ "style": "SOLID",
1272
+ "width": 2,
1273
+ "color": {
1274
+ "red": 0.0,
1275
+ "green":0.0,
1276
+ "blue":0.0
1277
+ },
1278
+ },
1279
+ "left":{
1280
+ "style": "SOLID",
1281
+ "width":2,
1282
+ "color": {
1283
+ "red": 0.0,
1284
+ "green":0.0,
1285
+ "blue":0.0
1286
+ },
1287
+ },
1288
+ "right":{
1289
+ "style": "SOLID",
1290
+ "width": 2,
1291
+ "color": {
1292
+ "red": 0.0,
1293
+ "green":0.0,
1294
+ "blue":0.0
1295
+ },
1296
+ },
1297
+ "innerHorizontal":{
1298
+ "style": "SOLID",
1299
+ "width":2,
1300
+ "color": {
1301
+ "red": 0.0,
1302
+ "green":0.0,
1303
+ "blue":0.0
1304
+ },
1305
+ },
1306
+ "innerVertical": {
1307
+ "style": "SOLID",
1308
+ "width": 2,
1309
+ "color": {
1310
+ "red": 0.0,
1311
+ "green":0.0,
1312
+ "blue":0.0
1313
+ },
1314
+ },
1315
+ }
1316
+ }
1317
+ ]
1318
+ }
1319
+ spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body=body2).execute()
1320
+
1321
+ model_cell =worksheet.cell('A1')
1322
+ model_cell.set_text_format('bold', True)
1323
+ model_cell.set_horizontal_alignment( pygsheets.custom_types.HorizontalAlignment.CENTER )
1324
+ pygsheets.DataRange('A2','G2', worksheet=worksheet).apply_format(model_cell)
1325
+ model_cell.color = (213/255, 219/255 ,255/255)
1326
  spreadsheet_url = "https://docs.google.com/spreadsheets/d/%s" % spreadsheetId
1327
  print(spreadsheet_url)
1328
+ drive_service.permissions().update(transferOwnership=True , fileId=spreadsheetId,permissionId='11OfoB4Z6wOVII8mYmbnCbbqTQs7rYA65')
1329
  return gc,spreadsheet_service,spreadsheetId ,spreadsheet_url
1330
  #######################
1331
 
 
1341
  spreadsheet_key =str(lastelement[0]) # Please set the Spreadsheet ID.
1342
 
1343
  ws = gc.open_by_key(spreadsheet_key)
1344
+ guessednamesfinal=getguessnames(gc,ws)
1345
+ sheetnames=[]
1346
+ unit=''
1347
+ # ws.add_worksheet("Summary") # Please set the new sheet name.
1348
+ for i in ws._sheet_list:
1349
+ print(i)
1350
+ sheetnames.append(i.title)
1351
+ print(i.index)
1352
+ if 'XML Export Summary' in sheetnames:
1353
+ worksheetS = ws.worksheet_by_title('XML Export Summary')
1354
+ else:
1355
+ ws.add_worksheet("XML Export Summary") # Please set the new sheet name.
1356
  worksheetw = ws.worksheet(0) #legend
1357
+ worksheetS = ws.worksheet_by_title('XML Export Summary')
1358
+ summaryId= ws[1].id
1359
  worksheetS.clear()
1360
  countnames=0
1361
  row0=['MC_T Name','Qty','Unit']
 
1364
  for i in range(len(McTName)):
1365
  allgbnames=''
1366
  item=''
1367
+ print(McTName[i][0])
1368
 
1369
+ firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
1370
 
1371
  # print(firstpart) #[ Ground Beams , m2 ]
1372
+ # if (McTName[i][2]=='area'):
1373
+ if firstpart[1]=='m2':
1374
  rowvalue=5# column 5
1375
  ar=0
1376
+ unit='m2'
1377
+ # if (McTName[i][2]=='perimeter'):
1378
+ if firstpart[1]=='m':
1379
  rowvalue=7# column 7
1380
  ar=0
1381
+ unit='m'
1382
  # # print( worksheet.get_col(5, include_tailing_empty=False) )
1383
 
1384
  for m in McTName[i][1]:
1385
  print(m)
1386
  # if len(McTName[i][1])>2:
1387
+ if m.startswith('g'):
1388
  allgbnames+= m +' +'
1389
 
1390
  print(m)
 
1392
  print(roww)
1393
  for j in range(len(roww)):
1394
  ar+=float(worksheetw.cell((roww[j].row ,rowvalue)).value)
1395
+
1396
+ elif m.startswith('p'):
1397
+ allgbnames+= m +' + '
1398
+
1399
+ print(m)
1400
+ roww=worksheetw.find(m)
1401
+ print(roww)
1402
+ for j in range(len(roww)):
1403
+ ar+=float(worksheetw.cell((roww[j].row ,rowvalue)).value)
1404
  else:
1405
+ item+=m + ' ,'
1406
+ print(item)
1407
 
1408
+ n= McTName[i][0] + ' ( '+ allgbnames[:-2] +' , ' + item[:-1] + ' ) '
1409
  print(n)
1410
 
1411
 
 
1420
 
1421
  # for count in range(len(name[1])):
1422
  # print(count)
1423
+ rowi=[str(n),ar,firstpart[1]]
1424
  worksheetS.update_row(i+2,rowi)
1425
+ # worksheetS.adjust_column_width(start=1,end=4)
1426
+ worksheetS.adjust_column_width(start=1,end=1, pixel_size=350)
1427
+ worksheetS.adjust_column_width(start=2,end=2, pixel_size=100)
1428
+ worksheetS.adjust_column_width(start=3,end=3)
1429
+
1430
+ xx=(worksheetS.cell( ( len(McTName) +1 ,3)) ).address.label
1431
+ model_cell1 =worksheetS.cell('A2')
1432
+ model_cell1.set_horizontal_alignment( pygsheets.custom_types.HorizontalAlignment.LEFT )
1433
+ pygsheets.DataRange('A2', str(xx), worksheet=worksheetS).apply_format(model_cell1)
1434
 
1435
 
1436
+ model_cell =worksheetS.cell('A1')
1437
+ model_cell.set_text_format('bold', True)
1438
+ model_cell.set_horizontal_alignment( pygsheets.custom_types.HorizontalAlignment.CENTER )
1439
+ pygsheets.DataRange('A1','C1', worksheet=worksheetS).apply_format(model_cell)
1440
+
1441
+ body2={
1442
+ "requests": [
1443
+ {
1444
+ "updateBorders": {
1445
+ "range": {
1446
+ "sheetId": str(summaryId),
1447
+ "startRowIndex": 0,
1448
+ "endRowIndex": len(McTName) +1 ,
1449
+ "startColumnIndex": 0,
1450
+ "endColumnIndex": 3
1451
+ },
1452
+ "top": {
1453
+ "style": "SOLID",
1454
+ "width": 2,
1455
+ "color": {
1456
+ "red": 0.0,
1457
+ "green":0.0,
1458
+ "blue":0.0
1459
+ },
1460
+ },
1461
+ "bottom": {
1462
+ "style": "SOLID",
1463
+ "width": 2,
1464
+ "color": {
1465
+ "red": 0.0,
1466
+ "green":0.0,
1467
+ "blue":0.0
1468
+ },
1469
+ },
1470
+ "left":{
1471
+ "style": "SOLID",
1472
+ "width":2,
1473
+ "color": {
1474
+ "red": 0.0,
1475
+ "green":0.0,
1476
+ "blue":0.0
1477
+ },
1478
+ },
1479
+ "right":{
1480
+ "style": "SOLID",
1481
+ "width": 2,
1482
+ "color": {
1483
+ "red": 0.0,
1484
+ "green":0.0,
1485
+ "blue":0.0
1486
+ },
1487
+ },
1488
+ "innerHorizontal":{
1489
+ "style": "SOLID",
1490
+ "width":2,
1491
+ "color": {
1492
+ "red": 0.0,
1493
+ "green":0.0,
1494
+ "blue":0.0
1495
+ },
1496
+ },
1497
+ "innerVertical": {
1498
+ "style": "SOLID",
1499
+ "width": 2,
1500
+ "color": {
1501
+ "red": 0.0,
1502
+ "green":0.0,
1503
+ "blue":0.0
1504
+ },
1505
+ },
1506
+ }
1507
+ }
1508
+ ]
1509
+ }
1510
+ spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_key, body=body2).execute()
1511
+ return summaryId,guessednamesfinal
1512
+
1513
  # print(x,xarea)
1514
+ def getguessnames(gc,ws):
1515
+ guessednamesfinal=[]
1516
+ worksheetw = ws.worksheet(0)
1517
+ guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
1518
+ print(guessednames[2:])
1519
+ for item in guessednames[2:]:
1520
+ if item not in guessednamesfinal:
1521
+ guessednamesfinal.append(item)
1522
+ print(guessednamesfinal)
1523
+ return guessednamesfinal
1524
+
1525
+ ################################################################