Marthee commited on
Commit
c56393f
·
1 Parent(s): 8f67e2c

Delete pilecaps_adr.py

Browse files
Files changed (1) hide show
  1. pilecaps_adr.py +0 -1525
pilecaps_adr.py DELETED
@@ -1,1525 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """Copy of XOR- ROI from plan-PileCaps-ADR.ipynb
3
-
4
- Automatically generated by Colaboratory.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/16RHtRae7VU_fqHMAjOUL4ET5slEFo3pf
8
- """
9
-
10
- # pip install pdf-annotate
11
-
12
- # pip install pdf-annotate
13
-
14
- #pip install pdf2image
15
-
16
- #!pip install -q gradio
17
-
18
- #pip install pygsheets
19
-
20
- # !apt-get install poppler-utils
21
-
22
- import numpy as np
23
- import cv2
24
- #from google.colab.patches import cv2_imshow
25
- from matplotlib import pyplot as plt
26
- #from pdf2image import convert_from_path
27
-
28
- import math
29
-
30
- import pandas as pd
31
- import random
32
- # import imutils
33
- # from imutils import contours
34
- import colorsys
35
- from PIL import Image , ImageDraw, ImageFont , ImageColor
36
- import numpy as np
37
- #import gradio as gr
38
-
39
- # from __future__ import print_function
40
- from googleapiclient.discovery import build
41
- from google.oauth2 import service_account
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()
52
- imgGry1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
53
- kernel=np.ones((3,3),np.uint8)
54
- er1=cv2.erode(imgGry1,kernel, iterations=2)
55
-
56
- er1=cv2.dilate(er1,kernel, iterations=1)
57
- gray_blurred = cv2.blur(er1, (3,3 ))
58
- # Apply Hough transform on the blurred image.
59
- # min distance between circles, Upper threshold for the internal Canny edge detector.
60
- detected_circles = cv2.HoughCircles( gray_blurred, cv2.HOUGH_GRADIENT, 1, 50, param1= 550,
61
- param2 =21, minRadius = 20, maxRadius = 40) #18 param2
62
-
63
- # Draw circles that are detected.
64
- if detected_circles is not None:
65
- # Convert the circle parameters a, b and r to integers.
66
- detected_circles = np.uint16(np.around(detected_circles))
67
- detected_circles = np.round(detected_circles[0, :]).astype("int")
68
- #DRAW CIRCLES
69
- for (x, y, r) in detected_circles:
70
- cv2.circle(im, (x, y), r, (255, 255, 255), 5)
71
- im=cv2.medianBlur(im,1)
72
- print('circles')
73
- # cv2_imshow(im)
74
- return im
75
-
76
- def detectSmallCircles(img ):
77
- #Remove tiny TOC points that interfere with shapes
78
- im=img.copy()
79
- imgGry1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
80
- kernel=np.ones((3,3),np.uint8)
81
- er1=cv2.erode(imgGry1,kernel, iterations=1)
82
- # Apply Hough transform on the blurred image.
83
- # min distance between circles, Upper threshold for the internal Canny edge detector.
84
- detected_circles = cv2.HoughCircles( imgGry1, cv2.HOUGH_GRADIENT, 1, 60, param1 =550,
85
- param2 =13, minRadius = 1, maxRadius = 10) #18 param2
86
-
87
- # Draw circles that are detected.
88
- if detected_circles is not None:
89
- # Convert the circle parameters a, b and r to integers.
90
- detected_circles = np.uint16(np.around(detected_circles))
91
- detected_circles = np.round(detected_circles[0, :]).astype("int")
92
- #DRAW CIRCLES
93
- for (x, y, r) in detected_circles:
94
- cv2.circle(im, (x, y), r+1, (255, 255, 255), -1)
95
- # cv2_imshow(im)
96
- return im
97
- # c=detectCircles(img)
98
-
99
- def DashedPreprocessing(imgOriginal,imgnoSmall):
100
- h,w=imgOriginal.shape[0:2]
101
- #remove the gray contours from the plan
102
- imgBW=cv2.threshold(imgnoSmall, 180, 255, cv2.THRESH_BINARY)[1]
103
-
104
- im_copy=imgBW.copy()
105
- im_copy1=im_copy
106
- kernel1 = np.ones((3,5),np.uint8)
107
- kernel2 = np.ones((9,9),np.uint8)
108
- kernel3= np.ones((3,3),np.uint8)
109
- imgGray=cv2.cvtColor(imgBW,cv2.COLOR_BGR2GRAY)
110
- imgBW1=cv2.threshold(imgGray, 200, 255, cv2.THRESH_BINARY_INV)[1]
111
-
112
- img1=cv2.erode(imgBW1, kernel1, iterations=1)
113
- img2=cv2.dilate(img1, kernel2, iterations=3)
114
- img3 = cv2.bitwise_and(imgBW1,img2)
115
- img3= cv2.bitwise_not(img3)
116
- img4 = cv2.bitwise_and(imgBW1,imgBW1,mask=img3)
117
- img4=cv2.blur(img4,(7,7))
118
- if h > w :
119
- max = h
120
- min = w
121
- else:
122
- max = w
123
- min = h
124
- return img4, imgBW, max,min
125
-
126
- def removeDashedLines(img4, imgBW ,max,min):
127
-
128
- imgLines= cv2.HoughLinesP(img4,1,np.pi/310,30,minLineLength=(max-min)//1.8,maxLineGap = 120) #was w-h , gap=150 0.99
129
- #1 120
130
-
131
- for i in range(len(imgLines)):
132
- for x1,y1,x2,y2 in imgLines[i]:
133
- cv2.line(imgBW,(x1,y1),(x2,y2),(0,255,0),2)
134
-
135
- im_copy=imgBW.copy()
136
- green=im_copy[:,:,1]
137
- # cv2_imshow(im_copy)
138
- return green
139
-
140
- def removeSmallDashes(imgOriginal,green):
141
- smalldashes=green.copy()
142
- smalldashes=cv2.bitwise_not(smalldashes)
143
-
144
- kernel3= np.ones((3,3),np.uint8)
145
-
146
- img1=cv2.dilate(smalldashes, kernel3, iterations=2)
147
- img2=cv2.erode(img1, kernel3, iterations=2)
148
-
149
- smalldashes=cv2.medianBlur(img2,5)
150
- smalldashes=cv2.medianBlur(smalldashes,7)
151
- # cv2_imshow(smalldashes)
152
- smalldashesOut=green.copy()
153
- smalldashesOut=cv2.cvtColor(smalldashesOut,cv2.COLOR_GRAY2BGR)
154
- imgLines= cv2.HoughLinesP(smalldashes,1,np.pi/150,27,minLineLength=10,maxLineGap = 70) #was w-h , gap=150
155
-
156
- imgCopy=imgOriginal.copy()
157
- for i in range(len(imgLines)):
158
- for x1,y1,x2,y2 in imgLines[i]:
159
- cv2.line(smalldashesOut,(x1,y1),(x2,y2),(0,255,0),2)
160
-
161
-
162
- smalldashesOut=smalldashesOut[:,:,1]
163
- # cv2_imshow(smalldashesOut)
164
- for i in range(len(imgLines)):
165
- for x1,y1,x2,y2 in imgLines[i]:
166
- cv2.line(imgCopy,(x1,y1),(x2,y2),(0,255,0),6)
167
-
168
- imgCopy=imgCopy[:,:,1]
169
- # cv2_imshow(imgCopy)
170
- return imgCopy,smalldashesOut
171
-
172
- def euclidian_distance(point1, point2):
173
- return sum([(point1[x] - point2[x]) ** 2 for x in range(len(point1))]) ** 0.5
174
-
175
- def removeDashedLinesSmall(img4, imgBW ,max,min):
176
-
177
- imgBW=cv2.cvtColor(imgBW,cv2.COLOR_GRAY2BGR)
178
-
179
- imgLines= cv2.HoughLinesP(img4,1,np.pi/100,20,minLineLength=(max-min)//2.2,maxLineGap = 70) #2.1
180
-
181
- for i in range(len(imgLines)):
182
- for x1,y1,x2,y2 in imgLines[i]:
183
- dist=euclidian_distance((x1,y1), (x2,y2))
184
- # if dist > 1300 and dist <1450:
185
- if dist >= (max-min)//2.1 and dist < (max-min)//1.9: #1.4
186
- cv2.line(imgBW,(x1,y1),(x2,y2),(0,255,0),3)
187
-
188
- im_copy=imgBW.copy()
189
- green=im_copy[:,:,1]
190
- # cv2_imshow(im_copy)
191
- return green
192
-
193
- def ConnectBeamLines(smalldashesOut):
194
- green1=cv2.bitwise_not(smalldashesOut)
195
- green2=smalldashesOut.copy()
196
- green2=cv2.cvtColor(green2,cv2.COLOR_GRAY2BGR)
197
- imgLines= cv2.HoughLinesP(green1,0.05,np.pi/250,10,minLineLength=25,maxLineGap = 20) #was w-h , gap=150 #50
198
- for i in range(len(imgLines)):
199
- for x1,y1,x2,y2 in imgLines[i]:
200
- cv2.line(green2,(x1,y1),(x2,y2),(0,0,0),1)
201
-
202
- imgLines= cv2.HoughLinesP(green1,0.3,np.pi/360,10,minLineLength=25,maxLineGap = 20) #try 180
203
-
204
-
205
- for i in range(len(imgLines)):
206
- for x1,y1,x2,y2 in imgLines[i]:
207
- cv2.line(green2,(x1,y1),(x2,y2),(0,0,0),1)
208
- # cv2_imshow(green2)
209
- return green2
210
-
211
- def allpreSteps(imgOriginal):
212
- noCircles=detectCircles(imgOriginal)
213
- imgnoSmall=detectSmallCircles(noCircles )
214
- img4,imgBW,max,min=DashedPreprocessing(imgOriginal,imgnoSmall)
215
- green=removeDashedLines(img4,imgBW,max,min)
216
- imgCopy,smalldashesOut=removeSmallDashes(imgOriginal,green)
217
- noSmallDashes=removeDashedLinesSmall(img4, smalldashesOut ,max,min)
218
- green2=ConnectBeamLines(noSmallDashes)
219
- # cv2_imshow(green2)
220
- return green2
221
-
222
- def ChangeBrightness(img,k):
223
- imgdarker = 255 * (img/255)**k # k>1 darker , k <1 lighter
224
- # cv2_imshow(imgdarker)
225
- imgdarker = imgdarker.astype('uint8')
226
- return imgdarker
227
-
228
- def preprocessold(img,number):
229
-
230
- # imcopy=detectCircles(img)
231
- blurG = cv2.GaussianBlur(ChangeBrightness(img,6),(3,3),0)
232
-
233
- imgGry = cv2.cvtColor(blurG, cv2.COLOR_BGR2GRAY)
234
-
235
- kernel=np.ones((3,3),np.uint8)
236
-
237
- er1=cv2.dilate(imgGry,kernel, iterations=2) #thinning
238
-
239
- er2=cv2.erode(er1,kernel, iterations=3) #thicken
240
- er3=cv2.dilate(er2,kernel, iterations=4)
241
-
242
- if number == 0:
243
- ret3, thresh = cv2.threshold(er3, 200, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
244
- else:
245
- ret3, thresh = cv2.threshold(er3, 220, 255, cv2.THRESH_BINARY_INV) #`140 - 141
246
- # cv2_imshow(thresh)
247
- return thresh
248
- # preprocessold(img,0)
249
-
250
- def preprocess(imgOriginal,number,green2):
251
- #first preprocessing ( old method - black img with white shapes)
252
- img1=preprocessold(imgOriginal,number)
253
- imgGry0 = cv2.cvtColor(imgOriginal , cv2.COLOR_BGR2GRAY)
254
-
255
- kernel=np.ones((3,3),np.uint8)
256
-
257
- anding=cv2.bitwise_and(green2,green2,mask=img1)
258
- anding = cv2.cvtColor(anding , cv2.COLOR_BGR2GRAY)
259
-
260
- return anding
261
-
262
- """# ROI (levels)
263
- ## Detect regions with specific color and mask them
264
- """
265
-
266
- def hexRGB(color):
267
- color=color.lstrip('#')
268
-
269
- color= tuple(int(color[i:i+2], 16) for i in (0, 2, 4)) #hex to rgb
270
- color=np.array(color) #rgb to bgr
271
- return color
272
- def DetectColor(img,color=0):
273
-
274
- imgCopy=img.copy()
275
- imgCopy=cv2.cvtColor(imgCopy,cv2.COLOR_BGR2HSV)
276
- tol=5 #tolerance
277
- # color=hexRGB(color)
278
- h,s,v = cv2.cvtColor(np.uint8([[[color[2],color[1],color[0]]]]),cv2.COLOR_BGR2HSV)[0][0]
279
-
280
- lower =np.array( [h- tol, 100, 100 ], dtype='uint8')
281
- upper = np.array( [h + tol, 255, 255],dtype='uint8')
282
-
283
- mask = cv2.inRange(imgCopy, lower , upper)
284
-
285
- detectedColors = cv2.bitwise_and(imgCopy,imgCopy, mask= mask) # Bitwise-AND mask and original image
286
-
287
- kernel=np.ones((3,3),np.uint8)
288
- mask=cv2.dilate(mask,kernel, iterations=5)
289
- mask=cv2.erode(mask,kernel, iterations=4)
290
-
291
- detectedColors=cv2.dilate(detectedColors,kernel, iterations=5)
292
- detectedColors=cv2.erode(detectedColors,kernel, iterations=4)
293
-
294
- detectedColors=cv2.cvtColor(detectedColors,cv2.COLOR_HSV2BGR)
295
- detectedColors=cv2.medianBlur(detectedColors,7)
296
- # cv2_imshow(detectedColors)
297
-
298
- return mask, detectedColors, color
299
-
300
-
301
- def detectAllColors(img,finalColorArray):
302
- for i in range(len(finalColorArray)):
303
- detectedColors= DetectColor(img,finalColorArray[i])[1]
304
- if i == 0:
305
- allcolorsImg=cv2.bitwise_or(detectedColors,detectedColors)
306
- else:
307
- allcolorsImg=cv2.bitwise_or(allcolorsImg,detectedColors)
308
- allcolorsImg= cv2.medianBlur(allcolorsImg,7)
309
-
310
- return allcolorsImg
311
-
312
- def colorOrder(img,finalColorArray):
313
- newimg=img.copy()
314
- arraycolor=[]
315
- allcolorsImg= detectAllColors(img,finalColorArray)
316
- allcolorsImgG= cv2.cvtColor(allcolorsImg, cv2.COLOR_BGR2GRAY)
317
-
318
- ColoredContour, Coloredhierarchy = cv2.findContours(allcolorsImgG, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
319
- Coloredhierarchy=Coloredhierarchy[0]
320
- for cnt in ColoredContour :
321
- Blackmask = np.zeros(img.shape[:2], dtype="uint8")
322
- cv2.drawContours(Blackmask,[cnt],0,(255,255,255),20)
323
- coloredand=cv2.bitwise_and(allcolorsImg,allcolorsImg,mask=Blackmask)
324
-
325
- for colors in finalColorArray:
326
- getColor=DetectColor(coloredand,colors)[1]
327
-
328
- pil_image=Image.fromarray(getColor)
329
- extrema = pil_image.convert("L").getextrema()
330
- if extrema != (0, 0): # if image is not black --> has a colored mask within
331
- arraycolor.append(colors)
332
- break
333
-
334
- res = []
335
- [res.append(x) for x in arraycolor if x not in res]
336
-
337
- return res
338
-
339
- def getinnerColor(BlackmaskDetected,img,detectedColors,finalColorArray,num1,num2,flag,eachcolor):
340
-
341
- countBlackMasks=0
342
- xored=detectedColors
343
-
344
- invertedmask=detectedColors
345
-
346
- imgc=img.copy()
347
- imgNewCopy=img.copy()
348
- Blackmask = np.zeros(img.shape[:2], dtype="uint8")
349
- for eachcolor in finalColorArray:
350
- masked=DetectColor(detectedColors,eachcolor)[0]
351
- pil_image=Image.fromarray(masked)
352
- extrema = pil_image.convert("L").getextrema()
353
- if extrema != (0, 0): # if image is not black --> has a colored mask within
354
- cc=detectedColors.copy()
355
- # cc1=detectedColorsB.copy()
356
- ColoredContour, Coloredhierarchy = cv2.findContours(masked, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
357
-
358
- for cnt in ColoredContour:
359
-
360
- area1 = cv2.contourArea(cnt)
361
- if (area1 > 1000 ):
362
-
363
- x, y , width, height = cv2.boundingRect(cnt)
364
- # cv2.rectangle(cc, (x,y ), (x+width, y+height), (255,255,255), -1)
365
- # cv2.rectangle(Blackmask, (x,y ), (x+width, y+height), 255, -1)
366
- #to get rid of the edge of the inner reectangles
367
- cv2.drawContours(cc,[cnt],0,(255,255,255), 3)
368
- cv2.drawContours(Blackmask,[cnt] ,0, (255,255,255), 3)
369
-
370
- cv2.drawContours(cc,[cnt],0,(255,255,255), -1) # (x-5,y-5 ), (x+width, y+height),
371
- cv2.drawContours(Blackmask,[cnt] ,0, (255,255,255), -1) #,(x,y ), (x+width, y+height)
372
-
373
- cv2.drawContours(BlackmaskDetected,[cnt] ,0, (0,0,0), -1) #,(x,y ), (x+width, y+height)
374
-
375
- invertedmask = cv2.bitwise_and(imgc,imgc, mask= Blackmask)
376
- xored=cc
377
- # masked b abyad
378
- detectedColors=xored
379
-
380
- else: #black mask , no other levels are found # to check law count == number of colors in array yb2a no more levels and break
381
- countBlackMasks+=1
382
-
383
- return xored,invertedmask , BlackmaskDetected
384
-
385
- def allLevelsofColor(BlackmaskDetected,img,levelonly, invertedmask,color,finalColorArray):
386
-
387
- # cc=levelonly.copy()
388
- firstLevel=levelonly
389
- firstLevel1=levelonly
390
- print('in')
391
- Blackmask = np.zeros(img.shape[:2], dtype="uint8")
392
-
393
- masked,maskedColor,rgbcolor=DetectColor(invertedmask,color)
394
- # color=hexRGB(color)
395
- color=[color[0],color[1],color[2]]
396
-
397
- rgbcolor=[rgbcolor[0],rgbcolor[1],rgbcolor[2]]
398
- print(rgbcolor,color)
399
- pil_image=Image.fromarray(masked)
400
- extrema = pil_image.convert("L").getextrema()
401
- if extrema != (0, 0): # if image is not black --> has a colored mask within
402
-
403
- if rgbcolor==color: #found level tany gowa b nfs el lon
404
- print('kkkkkkkk')
405
- ColoredContour, Coloredhierarchy = cv2.findContours(masked, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
406
- Coloredhierarchy=Coloredhierarchy[0]
407
- for component in zip(ColoredContour,Coloredhierarchy):
408
- cnt=component[0]
409
- hier=component[1]
410
- area1 = cv2.contourArea(cnt)
411
- if (area1 > 1000 ):
412
- if hier[3]> -1:
413
- cv2.drawContours(Blackmask,[cnt],0,(255,255,255), -1)
414
- cv2.drawContours(Blackmask,[cnt],0,(0,0,0), 20)
415
- cv2.drawContours(BlackmaskDetected,[cnt],0,(255,255,255), -1)
416
-
417
- firstLevel=cv2.bitwise_and(invertedmask,invertedmask,mask=Blackmask)
418
- ####remove black pixels and let them be all white
419
- # get (i, j) positions of all RGB pixels that are black (i.e. [0, 0, 0])
420
- black_pixels = np.where(
421
- (firstLevel[:, :, 0] == 0) &
422
- (firstLevel[:, :, 1] == 0) &
423
- (firstLevel[:, :, 2] == 0)
424
- )
425
-
426
- # set those pixels to white
427
- firstLevel[black_pixels] = [255, 255, 255]
428
- firstLevel1=cv2.bitwise_and(levelonly,firstLevel)
429
- # cv2_imshow(firstLevel1)
430
-
431
- # cv2_imshow(firstLevel1)
432
- for othercolor in finalColorArray:
433
- # othercolor2=hexRGB(othercolor)
434
- othercolor2=[othercolor[0],othercolor[1],othercolor[2]]
435
- print(othercolor2,color)
436
- if othercolor2!=color:
437
- print('anothre')
438
- masked0=DetectColor(firstLevel,othercolor)[0]
439
- pil_image0=Image.fromarray(masked0)
440
- extrema0 = pil_image0.convert("L").getextrema()
441
- if extrema != (0, 0): # if image is not black --> has a colored mask within
442
- ColoredContour0, Coloredhierarchy0 = cv2.findContours(masked0, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
443
- for cnt in ColoredContour0:
444
- area1 = cv2.contourArea(cnt)
445
- if (area1 > 1000 ):
446
- cv2.drawContours(firstLevel1,[cnt],0,(255,255,255), -1)
447
- cv2.drawContours(firstLevel1,[cnt],0,(255,255,255), 10)
448
- cv2.drawContours(BlackmaskDetected,[cnt],0,(0,0,0), -1)
449
- # cv2.drawContours(Blackmask,[cnt],0,(255,255,255), -1)
450
- # cv2.drawContours(Blackmask,[cnt],0,(255,255,255), 10)
451
- # cv2_imshow(firstLevel1)
452
- # cv2_imshow(Blackmask)
453
- return firstLevel1, BlackmaskDetected
454
-
455
- def getColoredContour(mask,img,finalColorArray,num1,num2,flag,eachcolor):
456
- print('uuuuuuuuummmmmmmmmmmmm')
457
-
458
- ColoredContour, Coloredhierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
459
- Coloredhierarchy=Coloredhierarchy[0]
460
-
461
- imgc= img.copy()
462
-
463
- detectedColors=np.zeros(img.shape[:2], dtype="uint8")
464
- Blackmask = np.zeros(img.shape[:2], dtype="uint8")
465
-
466
- for component in zip( ColoredContour, Coloredhierarchy):
467
- cnt=component[0]
468
- hier=component[1]
469
- area1 = cv2.contourArea(cnt)
470
- if (area1 > 3000 ):
471
- # cv2.drawContours(imgNewCopy, [cnt], 0,(255,255,255), 20) #(x+20,y+20 ), (x+width-20, y+height-20),
472
- if hier[3] >-1:
473
-
474
- x, y , width, height = cv2.boundingRect(cnt)
475
- cv2.drawContours(Blackmask, [cnt], 0,(255,255,255), -1) #(x+20,y+20 ), (x+width-20, y+height-20),
476
- cv2.drawContours(Blackmask, [cnt], 0,(0,0,0), 10) #(x+20,y+20 ), (x+width-20, y+height-20),
477
-
478
- detectedColors = cv2.bitwise_and(imgc,imgc, mask= Blackmask)
479
- pil_image=Image.fromarray(detectedColors)
480
- extrema = pil_image.convert("L").getextrema()
481
- if extrema == (0, 0) :#and extremaB==(0,0): # if image is not black --> has a colored mask within
482
- break
483
-
484
- levelOnly,invertedmask,BlackmaskDetected=getinnerColor(Blackmask,img,detectedColors,finalColorArray,num1,num2,flag,eachcolor) #mask inner levels b abyad
485
- firstLevel1, BlackmaskDetected1= allLevelsofColor(BlackmaskDetected,img,levelOnly, invertedmask,eachcolor,finalColorArray)
486
- # cv2.imshow('kk',firstLevel1)
487
- print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
488
- return firstLevel1,invertedmask, BlackmaskDetected1
489
-
490
- """# contours"""
491
-
492
- def findContoursFullImage(green2,img,number,finalColorArray,num1,num2,flag,color=[0,0,0]):
493
- if number == 0:
494
- thresh=preprocess(img,number,green2)
495
-
496
- contourss, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
497
- return contourss
498
- else:
499
- mask, detectedColors, rgbcolor =DetectColor(img,color)
500
- print(rgbcolor)
501
-
502
- pil_image=Image.fromarray(mask)
503
-
504
- extrema = pil_image.convert("L").getextrema()
505
- if extrema != (0, 0): # if image is not black --> has a colored mask within
506
- coloredregions,invertedmask,BlackmaskDetected1=getColoredContour(mask,img,finalColorArray,num1,num2,flag,color)
507
- thresh=preprocess(coloredregions,number,green2)
508
- x=cv2.bitwise_and(thresh,thresh,mask=BlackmaskDetected1)
509
- contourss, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
510
- return contourss,rgbcolor ,invertedmask
511
-
512
- else:
513
- print('ELSEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE')
514
- thresh=preprocess(img,number,green2)
515
-
516
- contourss, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
517
- hierarchy = hierarchy[0]
518
- return contourss,color ,mask
519
-
520
-
521
-
522
- def StraightenImage(contour,imgArea):
523
- rect = cv2.minAreaRect(contour)
524
-
525
- (center, (width, height), angleR) = cv2.minAreaRect(contour)
526
-
527
- box = cv2.boxPoints(rect)
528
- box = np.int0(box)
529
-
530
- # get width and height of the detected rectangle
531
- width = int(rect[1][0])
532
- height = int(rect[1][1])
533
-
534
- # src_pts = box.astype("float32")
535
- # dst_pts = np.array([[0, height-1],
536
- # [0, 0],
537
- # [width-1, 0],
538
- # [width-1, height-1]], dtype="float32")
539
-
540
- # # the perspective transformation matrix
541
- # M = cv2.getPerspectiveTransform(src_pts, dst_pts)
542
-
543
- # # directly warp the rotated rectangle to get the straightened rectangle
544
-
545
- # warped = cv2.warpPerspective(imgArea, M, (width, height))
546
- ##############
547
- return angleR,width,height
548
-
549
- def getAreasPerimeter(green2,img,number,num1,num2,flag,finalColorArray,color=[0,0,0]):
550
- appended=[]
551
- if number==0:
552
- contourss=findContoursFullImage(green2,img,number,finalColorArray,num1,num2,flag,color)
553
- else:
554
- contourss=findContoursFullImage(green2,img,number,finalColorArray,num1,num2,flag,color)[0]
555
-
556
- for contour in contourss:
557
-
558
- area1 = cv2.contourArea(contour)
559
- perimeter1 = cv2.arcLength(contour, True)
560
- x, y , width, height = cv2.boundingRect(contour)
561
-
562
- angleR,widthR ,heightR= StraightenImage(contour,img)
563
-
564
- if (angleR != 90.0 and angleR != -90.0 and angleR != 0.0 and angleR != -0.0 ): #inclined b ay degree
565
- width=widthR
566
- height=heightR
567
- if (area1 > 4000 ): #check perimeter kman fl condition -- 2800
568
- if num1!=0 and num2!=0:
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:
576
- #perimeter=round(perimeter1*(num1/num2),3)
577
- #appended.append([perimeter,width,height])
578
-
579
- return appended
580
-
581
-
582
- def FillDictionary(green2,SimilarAreaDictionary,img,number,num1,num2,flag,finalColorArray,rgbcolor=[0,0,0],color=[0,0,0]):
583
- #fills dictionary with key areas and number of occurences
584
- print('wttttt')
585
- areas_Perimeters=sorted(getAreasPerimeter(green2,img,number,num1,num2,flag,finalColorArray,color) )
586
-
587
- indices=[]
588
- colorRanges=[[255,153,153],[51,255,51],[201,56,147],[255,0,0],[255,0,255],[0,102,204],[102,0,102],[153,0,76],[200,92,135],[52,161,99],[235,250,24],[40,30,170],[98,149,63],[100,30,179],[200,55,67],[150,80,200],[0,102,102],[250,28,191],[101,27,101],[230,150,76],[3,65,127],[114,39,39],[250,36,100],[180,30,40],[10,250,60],[140,30,253],[114,58,245],[47,255,255],[18,236,206],[225,105,29],[189,65,121],[206,204,48],[126,7,247],[3,168,251]]
589
- print(colorRanges[0])
590
- print(colorRanges[0][0],colorRanges[0][1], colorRanges[0][2])
591
- colorsUsed=[]
592
- for i in range(len(areas_Perimeters)):
593
-
594
- # colorRGB=hexRGB(color)
595
- item1 = areas_Perimeters[i][0]
596
- width1 = areas_Perimeters[i][1]
597
- height1 = areas_Perimeters[i][2]
598
- widthMin= width1-10
599
- widthMax= width1+10
600
- heightMin=height1-10
601
- heightMax= height1+10
602
- areaPerimeterMin= round(item1,1) - 0.3
603
- areaPerimeterMax= round(item1,1) + 0.3
604
- # print (areaMin, areaMax)
605
- if color != [0,0,0]: #colored images
606
-
607
- mydata=[[rgbcolor[0],rgbcolor[1],rgbcolor[2] ],round(item1,1),width1,height1,1, 0,0,0,0,0,0,0]
608
- # mydata=[round(item1,1),width1,height1,0, 1,0,[rgbcolor[0],rgbcolor[1],rgbcolor[2] ],colorRanges[0][2],colorRanges[0][1],colorRanges[0][0]]
609
- # colorRanges.pop(0)
610
- else:
611
- # print('??')
612
-
613
- mydata=[' ', round(item1,1),width1,height1,1, 0,0,0,0,0,0,0]
614
-
615
- # if (( round(item1,1) in SimilarAreaDictionary['Rounded'].values) or (areaMin in SimilarAreaDictionary['Rounded'].values )or (areaMax in SimilarAreaDictionary['Rounded'].values )):
616
-
617
- # myindex= SimilarAreaDictionary.index[( SimilarAreaDictionary['Rounded']== round(item1,1) ) ].tolist()
618
- myindex= SimilarAreaDictionary.index[((SimilarAreaDictionary['Rounded'] >=areaPerimeterMin) &(SimilarAreaDictionary['Rounded']<=areaPerimeterMax) )].tolist()
619
- # for i in myindex:
620
- # SimilarAreaDictionary['Rounded'].loc[i]
621
- if color!= [0,0,0]: #leveled image
622
-
623
- checkifColorExists=0 # to check whether this row was found or not( area and color )
624
- for i in myindex: # loop on indices that were found --> rows containing this area to check its color and add occ.
625
- if SimilarAreaDictionary['Color'].loc[i]==[rgbcolor[0],rgbcolor[1],rgbcolor[2]] and ( SimilarAreaDictionary['Rounded'].loc[i] >= areaPerimeterMin and SimilarAreaDictionary['Rounded'].loc[i] <= areaPerimeterMax) :
626
- 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 ) :
627
- checkifColorExists=1 #found and incremented
628
- SimilarAreaDictionary['Occurences'].loc[i]+=1
629
- if checkifColorExists==0: #couldnt find the color , doesnt exist so add it
630
- SimilarAreaDictionary.loc[len(SimilarAreaDictionary)] =mydata
631
-
632
- else: #full image
633
- # print('here')
634
- #same code bs mgher color
635
- checkifColorExists=0
636
- for i in myindex: #(SimilarAreaDictionary['Rounded'].loc[i] == round(item1,1) ) or
637
- if ( SimilarAreaDictionary['Rounded'].loc[i] <= areaPerimeterMax and SimilarAreaDictionary['Rounded'].loc[i] >= areaPerimeterMin) :
638
- # print(SimilarAreaDictionary['Rounded'].loc[i] ,'in rng if', areaMin,areaMax)
639
- 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 ) :
640
- checkifColorExists=1 #found and incremented
641
- SimilarAreaDictionary['Occurences'].loc[i]+=1
642
- # SimilarAreaDictionary['R'].loc[i] =colorRanges[i][0]
643
- # SimilarAreaDictionary['G'].loc[i] =colorRanges[i][1]
644
- # SimilarAreaDictionary['B'].loc[i] = colorRanges[i][2]
645
-
646
- # colorRanges.pop(0)
647
-
648
- if checkifColorExists==0: #couldnt find the color , doesnt exist so add it
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()
669
- imgArea1= img.copy()
670
- imgPerimeter1=img.copy()
671
- imgtransparent1=img.copy()
672
-
673
- Blackmask = np.zeros(img.shape[:2], dtype="uint8")
674
-
675
- invertedmask=img
676
- allpoints=[]
677
-
678
- if number ==220:
679
- # finalColorArray= colorOrder(img,finalColorArray)
680
- # if flag== 'area':
681
- # SimilarAreaDictionary= pd.DataFrame(columns=['Color','Rounded','Width','Height','Area','Occurences','Total Area' , 'R','G','B']) #
682
- # else:
683
- # SimilarAreaDictionary= pd.DataFrame(columns=['Color','Rounded','Width','Height','Perimeter','Occurences','Total Perimeter' ,'R','G','B'])
684
- SimilarAreaDictionary= pd.DataFrame(columns=['Color','Rounded','Width','Height','Occurences','Area','Total Area','Perimeter','Total Perimeter','R','G','B'])
685
- firstcolor=finalColorArray[0]
686
- # print(lastcolor)
687
- counter=0
688
- maskDone=img.copy()
689
- for eachcolor in finalColorArray:
690
-
691
- print(eachcolor)
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
-
700
- # for component in zip(contourss,hierarchy):
701
- # contour = component[0]
702
- # currentHierarchy = component[1]
703
- for contour in contourss:
704
- shape=[]
705
-
706
- # cv2_imshow(imgStraight)
707
- area1 = cv2.contourArea(contour)
708
- perimeter1 = cv2.arcLength(contour, True)
709
- if (area1 > 4000 ): #check perimeter kman fl condition -- 2800
710
- angleR,widthR ,heightR= StraightenImage(contour,imgArea1)
711
- rect = cv2.minAreaRect(contour)
712
-
713
- (center, (width, height), angleR) = cv2.minAreaRect(contour)
714
-
715
- box = cv2.boxPoints(rect)
716
- box = box.astype('int')
717
- print(box)
718
-
719
- x, y , width, height = cv2.boundingRect(contour)
720
- # cv2.drawContours(imgArea1,contours=[box], contourIdx=0 , color=(0, 0, 255), thickness=10)
721
- approx = cv2.approxPolyDP(contour, 0.005 * perimeter1, True)
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)
732
- print(shape)
733
- if (angleR != 90.0 and angleR != -90.0 and angleR != 0.0 and angleR != -0.0 ): #inclined b ay degree
734
- width=widthR
735
- height=heightR
736
-
737
- widthMin= width-10
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
752
-
753
- # if flag=='area':
754
- areaPerimeterMin= round(areaa,1) - 0.3
755
- areaPerimeterMax= round(areaa,1) + 0.3
756
- # areaPerimeterMin= round(perimeterr,1) - 0.3
757
- # areaPerimeterMax= round(perimeterr,1) + 0.3
758
- masked=SimilarAreaDictionary.loc[SimilarAreaDictionary.index[((SimilarAreaDictionary['Rounded'] >=areaPerimeterMin) &(SimilarAreaDictionary['Rounded']<=areaPerimeterMax) )]]
759
- # masked=SimilarAreaDictionary.loc[SimilarAreaDictionary['Rounded'] ==round(areaa,1)]
760
- # if (round(areaa,1) in masked['Rounded'].values ) :
761
- passed=0
762
- for i, row in masked.iterrows():
763
- if passed ==0:
764
- if SimilarAreaDictionary['Color'].loc[i] == [rgbcolor[0],rgbcolor[1],rgbcolor[2]] and ( SimilarAreaDictionary['Rounded'].loc[i] <= areaPerimeterMax and SimilarAreaDictionary['Rounded'].loc[i] >= areaPerimeterMin) :
765
- 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 ) :
766
- SimilarAreaDictionary['Total Area'].loc[i]+=areaa
767
- SimilarAreaDictionary['Area'].loc[i]=areaa
768
-
769
- SimilarAreaDictionary['Total Perimeter'].loc[i]+=perimeterr
770
- SimilarAreaDictionary['Perimeter'].loc[i]=perimeterr
771
- passed=1
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)
787
-
788
- cv2.putText(imgPerimeter1,'Perimeter'+str(perimeterr), (x+50,y-10) ,cv2.FONT_HERSHEY_SIMPLEX, 0.6, (50, 50, 255), 2)
789
-
790
-
791
- for i,row in SimilarAreaDictionary.iterrows():
792
- # print(row)
793
- if row[5] not in areasinImage: # column of area
794
- SimilarAreaDictionary = SimilarAreaDictionary.drop(SimilarAreaDictionary.loc[SimilarAreaDictionary.index==i].index)
795
-
796
- print(SimilarAreaDictionary)
797
- # display(totaldf)
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=[]
807
- area1 = cv2.contourArea(contour)
808
- perimeter1 = cv2.arcLength(contour, True)
809
- if (area1 >4000 ):
810
- shape=[]
811
- angleR,widthR ,heightR= StraightenImage(contour,imgArea1)
812
- x, y , width, height = cv2.boundingRect(contour)
813
-
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
821
- height=heightR
822
-
823
- widthMin= width-10 #5
824
- widthMax= width+10
825
- heightMin=height-10
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
839
- # if flag=='area':
840
- areaPerimeterMin= round(areaa,1) - 0.3
841
- areaPerimeterMax= round(areaa,1) + 0.3
842
- masked=SimilarAreaDictionary.loc[SimilarAreaDictionary.index[((SimilarAreaDictionary['Rounded'] >=areaPerimeterMin) & (SimilarAreaDictionary['Rounded']<=areaPerimeterMax) )]]
843
- passed=0
844
- # if (round(areaa,1) in masked['Rounded'].values ) :
845
-
846
- for i, row in masked.iterrows():
847
- if passed ==0:
848
- # if SimilarAreaDictionary['Rounded'].loc[i] == round(areaa,1) :
849
- if ( SimilarAreaDictionary['Rounded'].loc[i] <= areaPerimeterMax and SimilarAreaDictionary['Rounded'].loc[i] >= areaPerimeterMin) :
850
- 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 ) :
851
- SimilarAreaDictionary['Total Area'].loc[i]+=areaa
852
- SimilarAreaDictionary['Area'].loc[i]=areaa
853
-
854
- SimilarAreaDictionary['Total Perimeter'].loc[i]+=perimeterr
855
- SimilarAreaDictionary['Perimeter'].loc[i]=perimeterr
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)
873
-
874
-
875
- alpha = 0.4 # Transparency factor.
876
- image_new1 = cv2.addWeighted(imgArea1, alpha, imgtransparent1, 1 - alpha, 0)
877
-
878
- # SimilarAreaDictionary.drop(['Rounded', 'Width','Height','R','G','B'], axis=1, inplace=True)
879
-
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):
1014
- planName= path.split("/")[-1].split('.')
1015
- LegendName='Legend of ' + str(planName[0]) + ' plan'
1016
- return LegendName
1017
-
1018
- def retrieveMCCol(gc):
1019
- ws=gc.open_by_key('1A8VtqLFhe2NXPxIjfAilbxF9xV2eSzZ-yZ9GP8_5jSo')
1020
- worksheet = ws.worksheet(0)
1021
- mcT_Names=worksheet.get_col(1)
1022
- newMcTNames=[]
1023
- for i in mcT_Names:
1024
- if i != '':
1025
- newMcTNames.append(i)
1026
- return newMcTNames
1027
-
1028
-
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='*',
1036
- ranges='A2:A60',includeGridData=True).execute()
1037
- r=list(response['sheets'][0]['data'][0]['rowData'][0]['values'][0])
1038
- print(r)
1039
- if 'dataValidation' in r:
1040
- print('yes')
1041
- colvals= response['sheets'][0]['data'][0]['rowData'][0]['values'][0]['dataValidation']
1042
- colvalsList=list(colvals.items())
1043
- print(colvalsList[0][1])
1044
- lengthVals=len(colvalsList[0][1]['values'])
1045
- for i in range(lengthVals):
1046
- dictVal=(colvalsList[0][1]['values'][i].values())
1047
- # val=[*dictVal]
1048
-
1049
- dropdownValues.append(*dictVal)
1050
- print(dropdownValues)
1051
- worksheet.update_col(index=1, values=dropdownValues)
1052
- return dropdownValues
1053
- def authorizeLegend():
1054
- SCOPES = [
1055
- 'https://www.googleapis.com/auth/spreadsheets',
1056
- 'https://www.googleapis.com/auth/drive'
1057
- ]
1058
- credentials = service_account.Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
1059
- spreadsheet_service = build('sheets', 'v4', credentials=credentials)
1060
- drive_service = build('drive', 'v3', credentials=credentials)
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 = [
1133
-
1134
- {'mergeCells': {
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
-
1206
- print(colorsUsed[i])
1207
- r,g,b=colorsUsed[i]
1208
- body = {
1209
- "requests": [
1210
- {
1211
- "updateCells": {
1212
- "range": {
1213
- "sheetId": sheetId,
1214
- "startRowIndex": i+3,
1215
- # "endRowIndex":4 ,
1216
- "startColumnIndex":1,
1217
-
1218
- # "endColumnIndex": 0
1219
- },
1220
-
1221
- "rows": [
1222
- {
1223
- "values": [
1224
- {
1225
- "userEnteredFormat": {
1226
- "backgroundColor": {
1227
-
1228
- "red": r/255,
1229
- "green": g/255,
1230
- "blue": b/255,
1231
- "alpha": 0.4,
1232
-
1233
- }
1234
-
1235
- }
1236
- }
1237
- ]
1238
- }
1239
- ],
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
-
1332
- def mapnametoLegend(McTName):
1333
- print('aaaaaaaaaaaaaa')
1334
- print(McTName)
1335
- lastelement = McTName.pop()
1336
- print(lastelement[0])
1337
- # McTNameSplit= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[0])
1338
- # namesSplit=x= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[1])
1339
-
1340
- spreadsheet_service,drive_service,gc=authorizeLegend()
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']
1362
- worksheetS.update_row(1,row0)
1363
-
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)
1391
- roww=worksheetw.find(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
-
1412
- # roww=worksheetw.find(allgbnames)
1413
- # for i in range (len(roww)):
1414
- # ar+=float(worksheetw.cell((roww[i].row ,rowvalue)).value)
1415
-
1416
- # print(ar)
1417
- # # xx=str(x.address.label)
1418
-
1419
- # worksheetS.cell((1,1)).value='aaa'
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
- ################################################################