Marthee commited on
Commit
732f5e4
·
verified ·
1 Parent(s): 1d0efbd

Upload deploying_3_3.py

Browse files
Files changed (1) hide show
  1. deploying_3_3.py +641 -0
deploying_3_3.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Deploying 3.3
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1HEw0DdXhDcxtJN1pjs7bCnlhr-wXX3-m
8
+ """
9
+
10
+ # pip install pymupdf
11
+
12
+ # pip install ezdxf
13
+
14
+ from math import sqrt
15
+
16
+ def distance(v1, v2):
17
+ """Calculate the Euclidean distance between two points."""
18
+ return sqrt((v1[0] - v2[0])**2 + (v1[1] - v2[1])**2)
19
+
20
+ def normalize_vertices(vertices):
21
+ """Convert all vertices to tuples and sort them."""
22
+ return sorted([tuple(vertex) for vertex in vertices])
23
+
24
+ def vertices_are_close(vertices1, vertices2, threshold=0.01):
25
+ """Check if all vertices in two sets are within a certain distance threshold."""
26
+ vertices1 = normalize_vertices(vertices1)
27
+ vertices2 = normalize_vertices(vertices2)
28
+
29
+ if len(vertices1) != len(vertices2):
30
+ return False
31
+
32
+ for v1, v2 in zip(vertices1, vertices2):
33
+ if distance(v1, v2) > threshold:
34
+ return False
35
+ return True
36
+
37
+ def vertices_exist(hatched_areas, vertices, threshold=0.01):
38
+ """Check if a set of vertices exists in hatched_areas within a given threshold."""
39
+ for area in hatched_areas:
40
+ existing_vertices = area[0]
41
+ if vertices_are_close(existing_vertices, vertices, threshold):
42
+ return True
43
+ return False
44
+
45
+ from ctypes import sizeof
46
+ # -*- coding: utf-8 -*-wj
47
+ """Version to be deployed of 3.2 Calculating area/perimeter
48
+
49
+ Automatically generated by Colab.
50
+
51
+ Original file is located at
52
+ https://colab.research.google.com/drive/1XPeCoTBgWSNBYZ3aMKBteP4YG3w4bORs
53
+ """
54
+
55
+ # pip install ezdxf[draw]
56
+
57
+ # pip install --upgrade ezdxf
58
+
59
+ # pip install pymupdf #==1.22.5
60
+
61
+ # pip install PyPDF2
62
+
63
+ # pip install ezdxf scipy
64
+
65
+ """## Imports"""
66
+
67
+ import numpy as np
68
+ import cv2
69
+ from matplotlib import pyplot as plt
70
+ import math
71
+ from PIL import Image , ImageDraw, ImageFont , ImageColor
72
+ import fitz
73
+ import ezdxf as ez
74
+ import sys
75
+ from ezdxf import units
76
+ # from google.colab.patches import cv2_imshow
77
+ from ezdxf.math import OCS, Matrix44, Vec3
78
+ import ezdxf
79
+ import matplotlib.pyplot as plt
80
+ from matplotlib.patches import Polygon
81
+ from shapely.geometry import Polygon as ShapelyPolygon
82
+ from ezdxf.math import Vec2
83
+ import random
84
+ import pandas as pd
85
+ # import google_sheet_Legend
86
+ import tsadropboxretrieval
87
+ from ezdxf import bbox
88
+ from math import sin, cos, radians
89
+ import google_sheet_Legend
90
+
91
+ """## Notes"""
92
+
93
+ #new approach to get width and height of dxf plan
94
+ '''
95
+ This portion is used to convert vertices read from dxf to pixels in order to accurately locate shapes in the image and pdf
96
+ ratio :
97
+ MeasuredMetric* PixelValue/ DxfMetric = MeasuredPixel
98
+ PixelValue: get from pixel conversion code , second number in the bracker represents the perimeter
99
+ DxfMetric: measured perimeter from foxit
100
+
101
+ divide pixelvalue by dxfmetric, will give u a ratio , this is ur dxfratio
102
+
103
+
104
+ '''
105
+
106
+
107
+ """PDF to image"""
108
+
109
+ def pdftoimg(datadoc):
110
+ doc = fitz.open('pdf',datadoc)
111
+ page=doc[0]
112
+ pix = page.get_pixmap() # render page to an image
113
+ pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
114
+ img=np.array(pl)
115
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
116
+ return img
117
+
118
+
119
+ # Standard ISO paper sizes in inches
120
+ ISO_SIZES_INCHES = {
121
+ "A0": (33.11, 46.81),
122
+ "A1": (23.39, 33.11),
123
+ "A2": (16.54, 23.39),
124
+ "A3": (11.69, 16.54),
125
+ "A4": (8.27, 11.69),
126
+ "A5": (5.83, 8.27),
127
+ "A6": (4.13, 5.83),
128
+ "A7": (2.91, 4.13),
129
+ "A8": (2.05, 2.91),
130
+ "A9": (1.46, 2.05),
131
+ "A10": (1.02, 1.46)
132
+ }
133
+
134
+ def get_paper_size_in_inches(width, height):
135
+ """Find the closest matching paper size in inches."""
136
+ for size, (w, h) in ISO_SIZES_INCHES.items():
137
+ if (abs(w - width) < 0.1 and abs(h - height) < 0.1) or (abs(w - height) < 0.1 and abs(h - width) < 0.1):
138
+ return size
139
+ return "Unknown Size"
140
+
141
+ def analyze_pdf(datadoc):
142
+ # Open the PDF file
143
+ pdf_document = fitz.open('pdf',datadoc)
144
+
145
+ # Iterate through pages and print their sizes
146
+ for page_number in range(len(pdf_document)):
147
+ page = pdf_document[page_number]
148
+ rect = page.rect
149
+ width_points, height_points = rect.width, rect.height
150
+
151
+ # Convert points to inches
152
+ width_inches, height_inches = width_points / 72, height_points / 72
153
+
154
+ paper_size = get_paper_size_in_inches(width_inches, height_inches)
155
+
156
+ print(f"Page {page_number + 1}: {width_inches:.2f} x {height_inches:.2f} inches ({paper_size})")
157
+
158
+ pdf_document.close()
159
+ return width_inches , height_inches , paper_size
160
+
161
+
162
+ def get_dxfSize(dxfpath):
163
+
164
+ doc = ezdxf.readfile(dxfpath)
165
+ msp = doc.modelspace()
166
+ # Create a cache for bounding box calculations
167
+ # Get the overall bounding box for all entities in the modelspace
168
+ cache = bbox.Cache()
169
+ overall_bbox = bbox.extents(msp, cache=cache)
170
+ print("Overall Bounding Box:", overall_bbox)
171
+ print(overall_bbox.extmin[0]+overall_bbox.extmax[0], overall_bbox.extmin[1]+overall_bbox.extmax[1])
172
+
173
+ return overall_bbox.extmin[0]+overall_bbox.extmax[0], overall_bbox.extmin[1]+overall_bbox.extmax[1]
174
+
175
+
176
+
177
+ def switch_case(argument):
178
+ switcher = {
179
+ "A0": 1.27,
180
+ "A1": 2.54,
181
+ "A2": 5.08,
182
+ "A3": 10.16,
183
+ "A4": 20.32,
184
+ "A5": 40.64,
185
+ "A6": 81.28,
186
+ "A7": 162.56,
187
+ "A8": 325.12,
188
+ "A9": 650.24,
189
+ "A10": 1300.48
190
+ }
191
+ # Get the value from the dictionary; if not found, return a default value
192
+ print("Final Ratio=",switcher.get(argument, 1))
193
+ return switcher.get(argument, 1)
194
+
195
+
196
+
197
+
198
+ def RetriveRatio(datadoc,dxfpath):
199
+
200
+ width,height,paper_size = analyze_pdf (datadoc)
201
+
202
+ if(width > height ):
203
+ bigger=width
204
+ else:
205
+ bigger=height
206
+
207
+ width_dxf,height_dxf = get_dxfSize(dxfpath)
208
+
209
+ if(width_dxf > height_dxf ):
210
+ bigger_dxf=width_dxf
211
+ else:
212
+ bigger_dxf=height_dxf
213
+
214
+ if(0.2 < bigger_dxf/bigger < 1.2):
215
+ print("bigger_dxf/bigger",bigger/bigger_dxf)
216
+ argument = paper_size
217
+ FinalRatio=switch_case(argument)
218
+ else:
219
+ FinalRatio=1
220
+ return FinalRatio
221
+
222
+
223
+ """Flips image
224
+ DXF origin is at the bottom left while img origin is top left
225
+ """
226
+
227
+ def flip(img):
228
+ height, width = img.shape[:2]
229
+
230
+ # Define the rotation angle (clockwise)
231
+ angle = 180
232
+
233
+ # Calculate the rotation matrix
234
+ rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), angle, 1)
235
+
236
+ # Rotate the image
237
+ rotated_image = cv2.warpAffine(img, rotation_matrix, (width, height))
238
+ flipped_horizontal = cv2.flip(rotated_image, 1)
239
+ return flipped_horizontal
240
+
241
+ """### Hatched areas"""
242
+ def get_hatched_areas(filename,FinalRatio):
243
+ doc = ezdxf.readfile(filename)
244
+ doc.header['$MEASUREMENT'] = 1
245
+ msp = doc.modelspace()
246
+ trial=0
247
+ hatched_areas = []
248
+ threshold=0.01
249
+ for entity in msp:
250
+ if entity.dxftype() == 'HATCH':
251
+ # print(f"Processing HATCH entity: {entity}")
252
+ for path in entity.paths:
253
+ vertices = [] # Reset vertices for each path
254
+
255
+ if str(path.type) == 'BoundaryPathType.POLYLINE':
256
+ # Handle POLYLINE type HATCH
257
+ vertices = [(vertex[0] * FinalRatio, vertex[1] * FinalRatio) for vertex in path.vertices]
258
+
259
+ if len(vertices) > 3:
260
+ poly = ShapelyPolygon(vertices)
261
+ minx, miny, maxx, maxy = poly.bounds
262
+ width = maxx - minx
263
+ height = maxy - miny
264
+
265
+ if poly.area > 0 and (height > 0.3 or width > 0.3):
266
+ area1 = round(poly.area, 3)
267
+ perimeter = round(poly.length, 3)
268
+
269
+ # Append POLYLINE if vertices don't already exist
270
+ if not vertices_exist(hatched_areas, vertices, threshold):
271
+ # print(f"Appending POLYLINE with area: {area1} and perimeter: {perimeter}")
272
+ hatched_areas.append([vertices, area1, perimeter])
273
+
274
+ elif str(path.type) == 'BoundaryPathType.EDGE':
275
+ # Handle EDGE type HATCH
276
+ vert = []
277
+ for edge in path.edges:
278
+ x, y = edge.start
279
+ x1, y1 = edge.end
280
+ vert.append((x * FinalRatio, y * FinalRatio))
281
+ vert.append((x1 * FinalRatio, y1 * FinalRatio))
282
+
283
+ poly = ShapelyPolygon(vert)
284
+ minx, miny, maxx, maxy = poly.bounds
285
+ width = maxx - minx
286
+ height = maxy - miny
287
+
288
+ if poly.area > 0 and (height > 0.3 or width > 0.3):
289
+ area1 = round(poly.area, 3)
290
+ perimeter = round(poly.length, 3)
291
+
292
+ # Append EDGE if vertices don't already exist
293
+ if not vertices_exist(hatched_areas, vert, threshold):
294
+ # print(f"Appending EDGE with area: {area1} and perimeter: {perimeter}")
295
+ hatched_areas.append([vert, area1, perimeter])
296
+
297
+ else:
298
+ print(f"Unhandled path type: {path.type}")
299
+
300
+ elif entity.dxftype() == 'SOLID':
301
+ vertices = [entity.dxf.vtx0 * (FinalRatio), entity.dxf.vtx1* (FinalRatio), entity.dxf.vtx2* (FinalRatio), entity.dxf.vtx3* (FinalRatio)]
302
+ poly = ShapelyPolygon(vertices)
303
+ minx, miny, maxx, maxy = poly.bounds
304
+
305
+ # Calculate the width and height of the bounding box
306
+ width = maxx - minx
307
+ height = maxy - miny
308
+
309
+ if (poly.area > 0 and (height > 0.3 or width > 0.3)):
310
+ if not vertices_exist(hatched_areas, vertices, threshold):#if not vertices_exist(hatched_areas, vertices):
311
+ hatched_areas.append([vertices,poly.area,poly.length])
312
+
313
+
314
+
315
+ elif entity.dxftype() == 'LWPOLYLINE':
316
+ vertices = []
317
+ lwpolyline = entity
318
+ points = lwpolyline.get_points()
319
+ flag = 0
320
+
321
+ # Collect vertices and apply the FinalRatio
322
+ for i in range(len(points)):
323
+ vertices.append([points[i][0] * FinalRatio, points[i][1] * FinalRatio])
324
+
325
+ # # Ensure there are more than 3 vertices
326
+ if len(vertices) > 3:
327
+ # Check if the polyline is closed
328
+ if vertices[0][0] == vertices[-1][0] or vertices[0][1] == vertices[-1][1]:
329
+ poly = ShapelyPolygon(vertices)
330
+ minx, miny, maxx, maxy = poly.bounds
331
+
332
+ # Calculate width and height of the bounding box
333
+ width = maxx - minx
334
+ height = maxy - miny
335
+
336
+ # Check area and size constraints
337
+ if poly.area > 0 and (height > 0.3 or width > 0.3):
338
+ area1 = round(poly.area, 3)
339
+ perimeter = round(poly.length, 3)
340
+
341
+ # for i in range(len(hatched_areas)):
342
+ # if area1 == hatched_areas[i][1]:
343
+ # flag = 1
344
+ # if flag == 0:
345
+ if not vertices_exist(hatched_areas, vertices, threshold):#if not vertices_exist(hatched_areas, vertices):
346
+ hatched_areas.append([vertices, area1, perimeter])
347
+
348
+
349
+
350
+ elif entity.dxftype() == 'POLYLINE':
351
+
352
+ # print("In POLYLINE")
353
+
354
+ flag=0
355
+ vertices = [(v.dxf.location.x * (FinalRatio), v.dxf.location.y * (FinalRatio)) for v in entity.vertices]
356
+ # print('Vertices:', vertices)
357
+
358
+ if(len(vertices)>3):
359
+
360
+ if(vertices[0][0] == vertices[len(vertices)-1][0] or vertices[0][1] == vertices[len(vertices)-1][1]):
361
+
362
+ poly=ShapelyPolygon(vertices)
363
+ minx, miny, maxx, maxy = poly.bounds
364
+
365
+ # Calculate the width and height of the bounding box
366
+ width = maxx - minx
367
+ height = maxy - miny
368
+
369
+ if (poly.area > 0 and (height > 0.3 or width > 0.3)):
370
+ area1 = round(poly.area,3)
371
+ perimeter = round (poly.length,3)
372
+ for i in range(len(hatched_areas)):
373
+ if(area1 == hatched_areas[i][1]):
374
+ flag=1
375
+ if(flag==0):
376
+ hatched_areas.append([vertices,area1,perimeter])
377
+
378
+ elif entity.dxftype() == 'SPLINE':
379
+ spline_entity = entity
380
+ vertices = []
381
+ control_points = spline_entity.control_points
382
+ if(len(control_points)>3):
383
+ for i in range(len(control_points)):
384
+ vertices.append([control_points[i][0]* (FinalRatio),control_points[i][1]* (FinalRatio)])
385
+ poly=ShapelyPolygon(vertices)
386
+
387
+ minx, miny, maxx, maxy = poly.bounds
388
+
389
+ # Calculate the width and height of the bounding box
390
+ width = maxx - minx
391
+ height = maxy - miny
392
+
393
+
394
+ if (poly.area > 0 and (height > 0.3 or width > 0.3)):
395
+ area1 = round(poly.area,3)
396
+ perimeter = round (poly.length,3)
397
+ if not vertices_exist(hatched_areas, vertices):
398
+ hatched_areas.append([vertices,area1,perimeter])
399
+
400
+ sorted_data = sorted(hatched_areas, key=lambda x: x[1])
401
+ return sorted_data
402
+
403
+ """### Rotate polygon"""
404
+
405
+
406
+
407
+ def rotate_point(point, angle,pdfrotation,width,height, center_point=(0, 0)):
408
+ """Rotates a point around center_point(origin by default)
409
+ Angle is in degrees.
410
+ Rotation is counter-clockwise
411
+ """
412
+ angle_rad = radians(angle % 360)
413
+ # Shift the point so that center_point becomes the origin
414
+ new_point = (point[0] - center_point[0], point[1] - center_point[1])
415
+ new_point = (new_point[0] * cos(angle_rad) - new_point[1] * sin(angle_rad),
416
+ new_point[0] * sin(angle_rad) + new_point[1] * cos(angle_rad))
417
+ # Reverse the shifting we have done
418
+ if pdfrotation!=0:
419
+
420
+ new_point = (new_point[0]+width + center_point[0], new_point[1] + center_point[1]) #pdfsize[2] is the same as +width
421
+ else:
422
+
423
+ new_point = (new_point[0] + center_point[0], new_point[1]+ height + center_point[1]) # pdfsize[3] is the same as +height
424
+ # new_point = (new_point[0] + center_point[0], new_point[1] + center_point[1])
425
+ return new_point
426
+
427
+
428
+ def rotate_polygon(polygon, angle, pdfrotation,width,height,center_point=(0, 0)):
429
+ """Rotates the given polygon which consists of corners represented as (x,y)
430
+ around center_point (origin by default)
431
+ Rotation is counter-clockwise
432
+ Angle is in degrees
433
+ """
434
+ rotated_polygon = []
435
+ for corner in polygon:
436
+ rotated_corner = rotate_point(corner, angle,pdfrotation,width,height, center_point)
437
+ rotated_polygon.append(rotated_corner)
438
+ return rotated_polygon
439
+
440
+ #create a dataframe containing color , count(how many times is this object found in the plan), area of 1 of these shapes, total area
441
+ #perimeter, totat perimeter, length, total length
442
+ #import pandas as pd
443
+ #SimilarAreaDictionary= pd.DataFrame(columns=['Guess','Color','Occurences','Area','Total Area','Perimeter','Total Perimeter','Length','Total Length','R','G','B'])
444
+ #loop 3la hatched areas and count the occurences of each shape w create a table bl hagat di
445
+
446
+ def generate_color_array(length):
447
+ colorRanges = []
448
+ while len(colorRanges) < length:
449
+ # Generate random RGB values
450
+ r = random.randint(0, 255)
451
+ g = random.randint(0, 255)
452
+ b = random.randint(0, 255)
453
+ # Ensure no duplicate colors
454
+ if (r, g, b) not in colorRanges:
455
+ colorRanges.append((r, g, b))
456
+ return colorRanges
457
+
458
+
459
+
460
+
461
+
462
+ def Create_DF(dxfpath,datadoc):
463
+
464
+ FinalRatio= RetriveRatio(datadoc,dxfpath)
465
+
466
+ hatched_areas = get_hatched_areas(dxfpath,FinalRatio)
467
+ # print('hatched_areas',hatched_areas)
468
+ # hatched_areas=remove_duplicate_shapes(new_hatched_areas)
469
+
470
+ # SimilarAreaDictionary= pd.DataFrame(columns=['Area', 'Total Area', 'Perimeter', 'Total Perimeter', 'Occurences', 'Color'])
471
+ SimilarAreaDictionary= pd.DataFrame(columns=['Guess','Color','Occurences','Area','Total Area','Perimeter','Total Perimeter','Length','Total Length','Texts','Comments'])
472
+
473
+ colorRanges2=generate_color_array(30000)
474
+ colorRanges = [[255, 0, 0], [0, 0, 255], [0, 255, 255], [0, 64, 0], [255, 204, 0], [255, 128, 64], [255, 0, 128], [255, 128, 192], [128, 128, 255], [128, 64, 0],[0, 255, 0],[0, 200, 0],[255, 128, 255], [128, 0, 255], [0, 128, 192], [128, 0, 128],[128, 0, 0], [0, 128, 255], [149, 1, 70], [255, 182, 128], [222, 48, 71], [240, 0, 112], [255, 0, 255], [192, 46, 65], [0, 0, 128],[0, 128, 64],[255, 255, 0], [128, 0, 80], [255, 255, 128], [90, 255, 140],[255, 200, 20],[91, 16, 51], [90, 105, 138], [114, 10, 138], [36, 82, 78], [225, 105, 190], [108, 150, 170], [11, 35, 75], [42, 176, 170], [255, 176, 170], [209, 151, 15],[81, 27, 85], [226, 106, 122], [67, 119, 149], [159, 179, 140], [159, 179, 30],[255, 85, 198], [255, 27, 85], [188, 158, 8],[140, 188, 120], [59, 61, 52], [65, 81, 21], [212, 255, 174], [15, 164, 90],[41, 217, 245], [213, 23, 182], [11, 85, 169], [78, 153, 239], [0, 66, 141],[64, 98, 232], [140, 112, 255], [57, 33, 154], [194, 117, 252], [116, 92, 135], [74, 43, 98], [188, 13, 123], [129, 58, 91], [255, 128, 100], [171, 122, 145], [255, 98, 98], [222, 48, 77]]
475
+ colorUsed=[]
476
+ TotalArea=0
477
+ TotalPerimeter=0
478
+ for i in range(len(hatched_areas)):
479
+ area = hatched_areas[i][1] # area
480
+ perimeter = hatched_areas[i][2] # perimeter
481
+ if(i < len(colorRanges)):
482
+ color = colorRanges[i]
483
+ colorUsed.append(color)
484
+ else:
485
+ color = colorRanges2[i]
486
+ colorUsed.append(color)
487
+ TotalArea = area
488
+ TotalPerimeter = perimeter
489
+ tol=2
490
+ condition1 = (SimilarAreaDictionary['Area'] >= area - tol) & (SimilarAreaDictionary['Area'] <= area +tol)
491
+ condition2 = (SimilarAreaDictionary['Perimeter'] >= perimeter -tol) & (SimilarAreaDictionary['Perimeter'] <= perimeter +tol)
492
+ combined_condition = condition1 & condition2
493
+
494
+ if any(combined_condition):
495
+ index = np.where(combined_condition)[0][0]
496
+ SimilarAreaDictionary.at[index, 'Occurences'] += 1
497
+ SimilarAreaDictionary.at[index, 'Total Area'] = SimilarAreaDictionary.at[index, 'Area'] * SimilarAreaDictionary.at[index, 'Occurences']
498
+ SimilarAreaDictionary.at[index, 'Total Perimeter'] = SimilarAreaDictionary.at[index, 'Perimeter'] * SimilarAreaDictionary.at[index, 'Occurences']
499
+ else:
500
+ TotalArea=area
501
+ TotalPerimeter=perimeter
502
+ new_data = {'Area': area, 'Total Area': TotalArea ,'Perimeter': perimeter, 'Total Perimeter': TotalPerimeter, 'Occurences': 1, 'Color':color,'Comments':''} #add color here and read color to insert in
503
+ SimilarAreaDictionary = pd.concat([SimilarAreaDictionary, pd.DataFrame([new_data])], ignore_index=True)
504
+
505
+ # print(SimilarAreaDictionary)
506
+ return SimilarAreaDictionary
507
+ """### Draw on Image and PDF"""
508
+
509
+ def mainFunctionDrawImgPdf(datadoc,dxfpath, dxfratio,pdfpath=0,pdfname=0):
510
+ FinalRatio= RetriveRatio(datadoc,dxfpath)
511
+
512
+ hatched_areas = get_hatched_areas(dxfpath,FinalRatio)
513
+ # hatched_areas=remove_duplicate_shapes(new_hatched_areas)
514
+
515
+ img=pdftoimg(datadoc)
516
+ flipped_horizontal=flip(img)
517
+ allcnts = []
518
+ imgg = flipped_horizontal
519
+ # imgtransparent1=imgg.copy()
520
+ doc = fitz.open('pdf',datadoc)
521
+ page2 = doc[0]
522
+ rotationOld=page2.rotation
523
+ derotationMatrix=page2.derotation_matrix
524
+ pix=page2.get_pixmap()
525
+ width=abs(page2.mediabox[2])+abs(page2.mediabox[0])
526
+ height=abs(page2.mediabox[3])+abs(page2.mediabox[1])
527
+ print('mediabox', width , height)
528
+ if page2.rotation!=0:
529
+
530
+ rotationangle = page2.rotation
531
+ page2.set_rotation(0)
532
+ ratio = pix.width/ img.shape[0]
533
+ else:
534
+ ratio = pix.width/ img.shape[1]
535
+ rotationangle = 270
536
+
537
+ allshapes=[]
538
+ # Iterate through each polygon in metric units
539
+ NewColors = []
540
+ SimilarAreaDictionary=Create_DF(dxfpath,datadoc)
541
+ i=0
542
+
543
+
544
+ for polygon in hatched_areas:
545
+ cntPoints = []
546
+ cntPoints1 = []
547
+ shapee = []
548
+ # Convert each vertex from metric to pixel coordinates
549
+ for vertex in polygon[0]:
550
+ x = (vertex[0]) *dxfratio
551
+ y = (vertex[1]) *dxfratio
552
+ if rotationangle==0:
553
+ if y<0:
554
+ y=y*-1
555
+ cntPoints.append([int(x), int(y)])
556
+ cntPoints1.append([x, y])
557
+
558
+ for poi in np.array(cntPoints1):
559
+ x1, y1 = poi
560
+ p1 = fitz.Point(x1,y1)
561
+ # p1 = fitz.Point(x1,y1)
562
+ p1=p1*derotationMatrix
563
+ shapee.append([p1[0],p1[1]])
564
+
565
+ shapee=np.flip(shapee,1)
566
+ shapee=rotate_polygon(shapee,rotationangle,rotationOld,width,height)
567
+ tol=2
568
+ condition1 = (SimilarAreaDictionary['Area'] >= polygon[1] - tol) & (SimilarAreaDictionary['Area'] <= polygon[1] +tol)
569
+ condition2 = (SimilarAreaDictionary['Perimeter'] >= polygon[2] -tol) & (SimilarAreaDictionary['Perimeter'] <= polygon[2] +tol)
570
+ combined_condition = condition1 & condition2
571
+
572
+ if any(combined_condition):
573
+
574
+ index = np.where(combined_condition)[0][0]
575
+ # print(SimilarAreaDictionary.at[index, 'Color'])
576
+ NewColors=SimilarAreaDictionary.at[index, 'Color']
577
+ else:
578
+ NewColors=SimilarAreaDictionary.at[i, 'Color']
579
+
580
+ # cv2.drawContours(imgg, [np.array(cntPoints)], -1, (NewColors), thickness=2)
581
+ cv2.drawContours(imgg, [np.array(cntPoints)], -1, ([NewColors[2],NewColors[1],NewColors[0]]), thickness=-1)
582
+ annot11 = page2.add_polygon_annot( points=shapee) # 'Polygon'
583
+ annot11.set_border(width=0.2)
584
+ annot11.set_colors(stroke=(int(NewColors[0])/255,int(NewColors[1])/255,int(NewColors[2])/255), fill= (int(NewColors[0])/255,int(NewColors[1])/255,int(NewColors[2])/255) )
585
+ annot11.set_info(content='Area='+str(polygon[1])+' m^2',subject='ADR Team')
586
+ annot11.set_opacity(0.8)
587
+ # annot.set_line_ends(fitz.PDF_ANNOT_LE_DIAMOND, fitz.PDF_ANNOT_LE_CIRCLE)
588
+ annot11.update()
589
+
590
+
591
+
592
+ annot12 = page2.add_polygon_annot( points=shapee) # 'Polygon'
593
+ annot12.set_border(width=0.2)
594
+ annot12.set_colors(stroke=(int(NewColors[0])/255,int(NewColors[1])/255,int(NewColors[2])/255))
595
+ annot12.set_info(content='Perimeter='+str(polygon[2])+' m',subject='ADR Team')
596
+ annot12.set_opacity(0.8)
597
+ # annot.set_line_ends(fitz.PDF_ANNOT_LE_DIAMOND, fitz.PDF_ANNOT_LE_CIRCLE)
598
+ annot12.update()
599
+ i += 1
600
+ alpha = 0.8 # Transparency factor.
601
+
602
+ page2.set_rotation(rotationOld)
603
+ Correct_img=flip(imgg)
604
+
605
+ image_new1 = cv2.addWeighted(Correct_img, alpha, img, 1 - alpha, 0)
606
+ SimilarAreaDictionary = SimilarAreaDictionary.fillna(' ')
607
+ gc,spreadsheet_service,spreadsheetId, spreadsheet_url , namepathArr=google_sheet_Legend.legendGoogleSheets(SimilarAreaDictionary , pdfname,pdfpath)
608
+ # dbxTeam=tsadropboxretrieval.ADR_Access_DropboxTeam('user')
609
+ # md, res =dbxTeam.files_download(path= pdfpath+pdfname)
610
+ # data = res.content
611
+ # doc=fitz.open("pdf", data)
612
+ # list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
613
+ list1=pd.DataFrame(columns=['content', 'id', 'subject','color'])
614
+
615
+ for page in doc:
616
+ # Iterate through annotations on the page
617
+ for annot in page.annots():
618
+ # Get the color of the annotation
619
+ annot_color = annot.colors
620
+ if annot_color is not None:
621
+ # annot_color is a dictionary with 'stroke' and 'fill' keys
622
+ stroke_color = annot_color.get('stroke') # Border color
623
+ fill_color = annot_color.get('fill') # Fill color
624
+ if fill_color:
625
+ v='fill'
626
+ # print('fill')
627
+ if stroke_color:
628
+ v='stroke'
629
+ x,y,z=int(annot_color.get(v)[0]*255),int(annot_color.get(v)[1]*255),int(annot_color.get(v)[2]*255)
630
+ list1.loc[len(list1)] =[annot.info['content'],annot.info['id'],annot.info['subject'],[x,y,z]]
631
+ return doc,image_new1, SimilarAreaDictionary ,spreadsheetId, spreadsheet_url , namepathArr , list1,hatched_areas
632
+
633
+ # doc.save('Testing(2.7).pdf')
634
+ # return doc,image_new1#, SimilarAreaDictionary ,spreadsheetId, spreadsheet_url , namepathArr , list1,hatched_areas
635
+
636
+ # datadoc='/content/3.3 - Ceiling finishes - Example 1 - Sheet 1.pdf' #pdf path here
637
+ # dxfpath='/content/3.3 - Ceiling finishes - Example 1 - Sheet 1.dxf'#dxfpath here
638
+ # dxfratio=28.3464527867108
639
+ # doc,image_new1=mainFunctionDrawImgPdf(datadoc,dxfpath, dxfratio)
640
+ # cv2_imshow(image_new1)
641
+