Marthee commited on
Commit
49b7e5a
·
verified ·
1 Parent(s): e5c8179

Upload Code_2_7.py

Browse files
Files changed (1) hide show
  1. Code_2_7.py +1622 -0
Code_2_7.py ADDED
@@ -0,0 +1,1622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """2.7 Code to be deployed 21.02.2025
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1RWSQn0GW_KXoHkJLcbYzLAGGyc0tiDWl
8
+ """
9
+
10
+ """## Imports"""
11
+
12
+ import numpy as np
13
+ import cv2
14
+ from matplotlib import pyplot as plt
15
+ import math
16
+ from PIL import Image , ImageDraw, ImageFont , ImageColor
17
+ import fitz
18
+ import ezdxf as ez
19
+ import sys
20
+ from ezdxf import units
21
+ # from google.colab.patches import cv2_imshow
22
+ from ezdxf.math import OCS, Matrix44, Vec3
23
+ import ezdxf
24
+ print(ezdxf.__version__)
25
+ import matplotlib.pyplot as plt
26
+ from matplotlib.patches import Polygon
27
+ from shapely.geometry import Point, Polygon as ShapelyPolygon
28
+ from ezdxf.math import Vec2
29
+ import random
30
+ import pandas as pd
31
+ import google_sheet_Legend
32
+ # import tsadropboxretrieval
33
+ from ezdxf import bbox
34
+ from math import sin, cos, radians
35
+ # from ezdxf.tools import rgb
36
+ from ezdxf.colors import aci2rgb
37
+ # from ezdxf.math import rgb_from_color
38
+ from collections import Counter
39
+
40
+ import xml.etree.ElementTree as ET
41
+ from PyPDF2 import PdfReader, PdfWriter
42
+ from PyPDF2.generic import TextStringObject, NameObject, ArrayObject, FloatObject
43
+ from PyPDF2.generic import NameObject, TextStringObject, DictionaryObject, FloatObject, ArrayObject, NumberObject
44
+
45
+ from typing import NewType
46
+ from ctypes import sizeof
47
+ from io import BytesIO
48
+
49
+
50
+
51
+ def normalize_vertices(vertices):
52
+ """Sort vertices to ensure consistent order."""
53
+ return tuple(sorted(tuple(v) for v in vertices))
54
+
55
+ def areas_are_similar(area1, area2, tolerance=0.2):
56
+ """Check if two areas are within a given tolerance."""
57
+ return abs(area1 - area2) <= tolerance
58
+
59
+
60
+ # -*- coding: utf-8 -*-wj
61
+ """Version to be deployed of 3.2 Calculating area/perimeter
62
+
63
+ Automatically generated by Colab.
64
+
65
+ Original file is located at
66
+ https://colab.research.google.com/drive/1XPeCoTBgWSNBYZ3aMKBteP4YG3w4bORs
67
+ """
68
+
69
+
70
+ """## Notes"""
71
+
72
+ #new approach to get width and height of dxf plan
73
+ '''
74
+ This portion is used to convert vertices read from dxf to pixels in order to accurately locate shapes in the image and pdf
75
+ ratio :
76
+ MeasuredMetric* PixelValue/ DxfMetric = MeasuredPixel
77
+ PixelValue: get from pixel conversion code , second number in the bracker represents the perimeter
78
+ DxfMetric: measured perimeter from foxit
79
+
80
+ divide pixelvalue by dxfmetric, will give u a ratio , this is ur dxfratio
81
+
82
+
83
+ '''
84
+
85
+
86
+ """PDF to image"""
87
+
88
+ def pdftoimg(datadoc):
89
+ doc =fitz.open('pdf',datadoc)
90
+ page=doc[0]
91
+ pix = page.get_pixmap() # render page to an image
92
+ pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
93
+ img=np.array(pl)
94
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
95
+ print("IMAGE")
96
+ # cv2_imshow(img)
97
+ return img,pix
98
+
99
+
100
+ # Standard ISO paper sizes in inches
101
+ ISO_SIZES_INCHES = {
102
+ "A0": (33.11, 46.81),
103
+ "A1": (23.39, 33.11),
104
+ "A2": (16.54, 23.39),
105
+ "A3": (11.69, 16.54),
106
+ "A4": (8.27, 11.69),
107
+ "A5": (5.83, 8.27),
108
+ "A6": (4.13, 5.83),
109
+ "A7": (2.91, 4.13),
110
+ "A8": (2.05, 2.91),
111
+ "A9": (1.46, 2.05),
112
+ "A10": (1.02, 1.46)
113
+ }
114
+
115
+ def get_paper_size_in_inches(width, height):
116
+ """Find the closest matching paper size in inches."""
117
+ for size, (w, h) in ISO_SIZES_INCHES.items():
118
+ if (abs(w - width) < 0.1 and abs(h - height) < 0.1) or (abs(w - height) < 0.1 and abs(h - width) < 0.1):
119
+ return size
120
+ return "Unknown Size"
121
+
122
+ def analyze_pdf(datadoc):
123
+ # Open the PDF file
124
+ pdf_document = fitz.open('pdf',datadoc)
125
+
126
+ # Iterate through pages and print their sizes
127
+ for page_number in range(len(pdf_document)):
128
+ page = pdf_document[page_number]
129
+ rect = page.rect
130
+ width_points, height_points = rect.width, rect.height
131
+
132
+ # Convert points to inches
133
+ width_inches, height_inches = width_points / 72, height_points / 72
134
+
135
+ paper_size = get_paper_size_in_inches(width_inches, height_inches)
136
+
137
+ print(f"Page {page_number + 1}: {width_inches:.2f} x {height_inches:.2f} inches ({paper_size})")
138
+
139
+ pdf_document.close()
140
+ return width_inches , height_inches , paper_size
141
+
142
+
143
+ def get_dxfSize(dxfpath):
144
+
145
+ doc = ezdxf.readfile(dxfpath)
146
+ msp = doc.modelspace()
147
+ # Create a cache for bounding box calculations
148
+ # Get the overall bounding box for all entities in the modelspace
149
+ cache = bbox.Cache()
150
+ overall_bbox = bbox.extents(msp, cache=cache)
151
+ print("Overall Bounding Box:", overall_bbox)
152
+ print(overall_bbox.extmin[0]+overall_bbox.extmax[0], overall_bbox.extmin[1]+overall_bbox.extmax[1])
153
+
154
+ return overall_bbox.extmin[0]+overall_bbox.extmax[0], overall_bbox.extmin[1]+overall_bbox.extmax[1]
155
+
156
+
157
+
158
+ def switch_case(argument):
159
+ switcher = {
160
+ "A0": 1.27,
161
+ "A1": 2.54,
162
+ "A2": 5.08,
163
+ "A3": 10.16,
164
+ "A4": 20.32,
165
+ "A5": 40.64,
166
+ "A6": 81.28,
167
+ "A7": 162.56,
168
+ "A8": 325.12,
169
+ "A9": 650.24,
170
+ "A10": 1300.48
171
+ }
172
+ # Get the value from the dictionary; if not found, return a default value
173
+ print("Final Ratio=",switcher.get(argument, 1))
174
+ return switcher.get(argument, 1)
175
+
176
+
177
+
178
+
179
+ def RetriveRatio(datadoc,dxfpath):
180
+
181
+ width,height,paper_size = analyze_pdf (datadoc)
182
+
183
+ if(width > height ):
184
+ bigger=width
185
+ else:
186
+ bigger=height
187
+
188
+ width_dxf,height_dxf = get_dxfSize(dxfpath)
189
+
190
+ if(width_dxf > height_dxf ):
191
+ bigger_dxf=width_dxf
192
+ else:
193
+ bigger_dxf=height_dxf
194
+
195
+ if(0.2 < bigger_dxf/bigger < 1.2):
196
+ print("bigger_dxf/bigger",bigger/bigger_dxf)
197
+ argument = paper_size
198
+ FinalRatio=switch_case(argument)
199
+ else:
200
+ FinalRatio=1
201
+ return FinalRatio
202
+
203
+
204
+ """Flips image
205
+ DXF origin is at the bottom left while img origin is top left
206
+ """
207
+
208
+ def flip(img):
209
+ height, width = img.shape[:2]
210
+
211
+ # Define the rotation angle (clockwise)
212
+ angle = 180
213
+
214
+ # Calculate the rotation matrix
215
+ rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), angle, 1)
216
+
217
+ # Rotate the image
218
+ rotated_image = cv2.warpAffine(img, rotation_matrix, (width, height))
219
+ flipped_horizontal = cv2.flip(rotated_image, 1)
220
+ return flipped_horizontal
221
+
222
+
223
+
224
+ def aci_to_rgb(aci):
225
+ aci_rgb_map = {
226
+ 0: (0, 0, 0),
227
+ 1: (255, 0, 0),
228
+ 2: (255, 255, 0),
229
+ 3: (0, 255, 0),
230
+ 4: (0, 255, 255),
231
+ 5: (0, 0, 255),
232
+ 6: (255, 0, 255),
233
+ 7: (255, 255, 255),
234
+ 8: (65, 65, 65),
235
+ 9: (128, 128, 128),
236
+ 10: (255, 0, 0),
237
+ 11: (255, 170, 170),
238
+ 12: (189, 0, 0),
239
+ 13: (189, 126, 126),
240
+ 14: (129, 0, 0),
241
+ 15: (129, 86, 86),
242
+ 16: (104, 0, 0),
243
+ 17: (104, 69, 69),
244
+ 18: (79, 0, 0),
245
+ 19: (79, 53, 53),
246
+ 20: (255, 63, 0),
247
+ 21: (255, 191, 170),
248
+ 22: (189, 46, 0),
249
+ 23: (189, 141, 126),
250
+ 24: (129, 31, 0),
251
+ 25: (129, 96, 86),
252
+ 26: (104, 25, 0),
253
+ 27: (104, 78, 69),
254
+ 28: (79, 19, 0),
255
+ 29: (79, 59, 53),
256
+ 30: (255, 127, 0),
257
+ 31: (255, 212, 170),
258
+ 32: (189, 94, 0),
259
+ 33: (189, 157, 126),
260
+ 34: (129, 64, 0),
261
+ 35: (129, 107, 86),
262
+ 36: (104, 52, 0),
263
+ 37: (104, 86, 69),
264
+ 38: (79, 39, 0),
265
+ 39: (79, 66, 53),
266
+ 40: (255, 191, 0),
267
+ 41: (255, 234, 170),
268
+ 42: (189, 141, 0),
269
+ 43: (189, 173, 126),
270
+ 44: (129, 96, 0),
271
+ 45: (129, 118, 86),
272
+ 46: (104, 78, 0),
273
+ 47: (104, 95, 69),
274
+ 48: (79, 59, 0),
275
+ 49: (79, 73, 53),
276
+ 50: (255, 255, 0),
277
+ 51: (255, 255, 170),
278
+ 52: (189, 189, 0),
279
+ 53: (189, 189, 126),
280
+ 54: (129, 129, 0),
281
+ 55: (129, 129, 86),
282
+ 56: (104, 104, 0),
283
+ 57: (104, 104, 69),
284
+ 58: (79, 79, 0),
285
+ 59: (79, 79, 53),
286
+ 60: (191, 255, 0),
287
+ 61: (234, 255, 170),
288
+ 62: (141, 189, 0),
289
+ 63: (173, 189, 126),
290
+ 64: (96, 129, 0),
291
+ 65: (118, 129, 86),
292
+ 66: (78, 104, 0),
293
+ 67: (95, 104, 69),
294
+ 68: (59, 79, 0),
295
+ 69: (73, 79, 53),
296
+ 70: (127, 255, 0),
297
+ 71: (212, 255, 170),
298
+ 72: (94, 189, 0),
299
+ 73: (157, 189, 126),
300
+ 74: (64, 129, 0),
301
+ 75: (107, 129, 86),
302
+ 76: (52, 104, 0),
303
+ 77: (86, 104, 69),
304
+ 78: (39, 79, 0),
305
+ 79: (66, 79, 53),
306
+ 80: (63, 255, 0),
307
+ 81: (191, 255, 170),
308
+ 82: (46, 189, 0),
309
+ 83: (141, 189, 126),
310
+ 84: (31, 129, 0),
311
+ 85: (96, 129, 86),
312
+ 86: (25, 104, 0),
313
+ 87: (78, 104, 69),
314
+ 88: (19, 79, 0),
315
+ 89: (59, 79, 53),
316
+ 90: (0, 255, 0),
317
+ 91: (170, 255, 170),
318
+ 92: (0, 189, 0),
319
+ 93: (126, 189, 126),
320
+ 94: (0, 129, 0),
321
+ 95: (86, 129, 86),
322
+ 96: (0, 104, 0),
323
+ 97: (69, 104, 69),
324
+ 98: (0, 79, 0),
325
+ 99: (53, 79, 53),
326
+ 100: (0, 255, 63),
327
+ 101: (170, 255, 191),
328
+ 102: (0, 189, 46),
329
+ 103: (126, 189, 141),
330
+ 104: (0, 129, 31),
331
+ 105: (86, 129, 96),
332
+ 106: (0, 104, 25),
333
+ 107: (69, 104, 78),
334
+ 108: (0, 79, 19),
335
+ 109: (53, 79, 59),
336
+ 110: (0, 255, 127),
337
+ 111: (170, 255, 212),
338
+ 112: (0, 189, 94),
339
+ 113: (126, 189, 157),
340
+ 114: (0, 129, 64),
341
+ 115: (86, 129, 107),
342
+ 116: (0, 104, 52),
343
+ 117: (69, 104, 86),
344
+ 118: (0, 79, 39),
345
+ 119: (53, 79, 66),
346
+ 120: (0, 255, 191),
347
+ 121: (170, 255, 234),
348
+ 122: (0, 189, 141),
349
+ 123: (126, 189, 173),
350
+ 124: (0, 129, 96),
351
+ 125: (86, 129, 118),
352
+ 126: (0, 104, 78),
353
+ 127: (69, 104, 95),
354
+ 128: (0, 79, 59),
355
+ 129: (53, 79, 73),
356
+ 130: (0, 255, 255),
357
+ 131: (170, 255, 255),
358
+ 132: (0, 189, 189),
359
+ 133: (126, 189, 189),
360
+ 134: (0, 129, 129),
361
+ 135: (86, 129, 129),
362
+ 136: (0, 104, 104),
363
+ 137: (69, 104, 104),
364
+ 138: (0, 79, 79),
365
+ 139: (53, 79, 79),
366
+ 140: (0, 191, 255),
367
+ 141: (170, 234, 255),
368
+ 142: (0, 141, 189),
369
+ 143: (126, 173, 189),
370
+ 144: (0, 96, 129),
371
+ 145: (86, 118, 129),
372
+ 146: (0, 78, 104),
373
+ 147: (69, 95, 104),
374
+ 148: (0, 59, 79),
375
+ 149: (53, 73, 79),
376
+ 150: (0, 127, 255),
377
+ 151: (170, 212, 255),
378
+ 152: (0, 94, 189),
379
+ 153: (126, 157, 189),
380
+ 154: (0, 64, 129),
381
+ 155: (86, 107, 129),
382
+ 156: (0, 52, 104),
383
+ 157: (69, 86, 104),
384
+ 158: (0, 39, 79),
385
+ 159: (53, 66, 79),
386
+ 160: (0, 63, 255),
387
+ 161: (170, 191, 255),
388
+ 162: (0, 46, 189),
389
+ 163: (126, 141, 189),
390
+ 164: (0, 31, 129),
391
+ 165: (86, 96, 129),
392
+ 166: (0, 25, 104),
393
+ 167: (69, 78, 104),
394
+ 168: (0, 19, 79),
395
+ 169: (53, 59, 79),
396
+ 170: (0, 0, 255),
397
+ 171: (170, 170, 255),
398
+ 172: (0, 0, 189),
399
+ 173: (126, 126, 189),
400
+ 174: (0, 0, 129),
401
+ 175: (86, 86, 129),
402
+ 176: (0, 0, 104),
403
+ 177: (69, 69, 104),
404
+ 178: (0, 0, 79),
405
+ 179: (53, 53, 79),
406
+ 180: (63, 0, 255),
407
+ 181: (191, 170, 255),
408
+ 182: (46, 0, 189),
409
+ 183: (141, 126, 189),
410
+ 184: (31, 0, 129),
411
+ 185: (96, 86, 129),
412
+ 186: (25, 0, 104),
413
+ 187: (78, 69, 104),
414
+ 188: (19, 0, 79),
415
+ 189: (59, 53, 79),
416
+ 190: (127, 0, 255),
417
+ 191: (212, 170, 255),
418
+ 192: (94, 0, 189),
419
+ 193: (157, 126, 189),
420
+ 194: (64, 0, 129),
421
+ 195: (107, 86, 129),
422
+ 196: (52, 0, 104),
423
+ 197: (86, 69, 104),
424
+ 198: (39, 0, 79),
425
+ 199: (66, 53, 79),
426
+ 200: (191, 0, 255),
427
+ 201: (234, 170, 255),
428
+ 202: (141, 0, 189),
429
+ 203: (173, 126, 189),
430
+ 204: (96, 0, 129),
431
+ 205: (118, 86, 129),
432
+ 206: (78, 0, 104),
433
+ 207: (95, 69, 104),
434
+ 208: (59, 0, 79),
435
+ 209: (73, 53, 79),
436
+ 210: (255, 0, 255),
437
+ 211: (255, 170, 255),
438
+ 212: (189, 0, 189),
439
+ 213: (189, 126, 189),
440
+ 214: (129, 0, 129),
441
+ 215: (129, 86, 129),
442
+ 216: (104, 0, 104),
443
+ 217: (104, 69, 104),
444
+ 218: (79, 0, 79),
445
+ 219: (79, 53, 79),
446
+ 220: (255, 0, 191),
447
+ 221: (255, 170, 234),
448
+ 222: (189, 0, 141),
449
+ 223: (189, 126, 173),
450
+ 224: (129, 0, 96),
451
+ 225: (129, 86, 118),
452
+ 226: (104, 0, 78),
453
+ 227: (104, 69, 95),
454
+ 228: (79, 0, 59),
455
+ 229: (79, 53, 73),
456
+ 230: (255, 0, 127),
457
+ 231: (255, 170, 212),
458
+ 232: (189, 0, 94),
459
+ 233: (189, 126, 157),
460
+ 234: (129, 0, 64),
461
+ 235: (129, 86, 107),
462
+ 236: (104, 0, 52),
463
+ 237: (104, 69, 86),
464
+ 238: (79, 0, 39),
465
+ 239: (79, 53, 66),
466
+ 240: (255, 0, 63),
467
+ 241: (255, 170, 191),
468
+ 242: (189, 0, 46),
469
+ 243: (189, 126, 141),
470
+ 244: (129, 0, 31),
471
+ 245: (129, 86, 96),
472
+ 246: (104, 0, 25),
473
+ 247: (104, 69, 78),
474
+ 248: (79, 0, 19),
475
+ 249: (79, 53, 59),
476
+ 250: (51, 51, 51),
477
+ 251: (80, 80, 80),
478
+ 252: (105, 105, 105),
479
+ 253: (130, 130, 130),
480
+ 254: (190, 190, 190),
481
+ 255: (255, 255, 255)
482
+ }
483
+
484
+ # Default to white if index is invalid or not found
485
+ return aci_rgb_map.get(aci, (255, 255, 255))
486
+
487
+
488
+ def int_to_rgb(color_int):
489
+ """Convert an integer to an (R, G, B) tuple."""
490
+ r = (color_int >> 16) & 255
491
+ g = (color_int >> 8) & 255
492
+ b = color_int & 255
493
+ return (r, g, b)
494
+
495
+
496
+ def get_hatch_color(entity):
497
+ """Extract hatch color with detailed debugging."""
498
+ if not entity:
499
+ # print("No entity provided for color extraction.")
500
+ return (255, 255, 255)
501
+
502
+ # Check for true color
503
+ if entity.dxf.hasattr('true_color'):
504
+ true_color = entity.dxf.true_color
505
+ rgb_color = int_to_rgb(true_color) # Convert integer to (R, G, B)
506
+ # print(f"True color detected (RGB): {rgb_color}")
507
+ return rgb_color
508
+
509
+ # Check for color index
510
+ color_index = entity.dxf.color
511
+ # print(f"Entity color index: {color_index}")
512
+ if 1 <= color_index <= 255:
513
+ rgb_color = aci_to_rgb(color_index) # Convert ACI to RGB
514
+ # print(f"Converted ACI to RGB: {rgb_color}")
515
+ return rgb_color
516
+
517
+ # Handle ByLayer or ByBlock
518
+ if color_index == 0: # ByLayer
519
+ layer_name = entity.dxf.layer
520
+ layer = entity.doc.layers.get(layer_name)
521
+ # print(f"ByLayer detected for layer '{layer_name}'.")
522
+ if layer:
523
+ layer_color_index = layer.dxf.color
524
+ # print(layer_color_index)
525
+ rgb_color = aci_to_rgb(layer_color_index)
526
+ # print(f"Layer '{layer_name}' color index {layer_color_index} converted to RGB: {rgb_color}")
527
+ return rgb_color
528
+ else:
529
+ # print(f"Layer '{layer_name}' not found. Defaulting to white.")
530
+ return (255, 255, 255)
531
+
532
+ # Default
533
+ # print("Unhandled color case. Defaulting to white.")
534
+ return (255, 255, 255)
535
+
536
+
537
+
538
+ def point_in_rectangle(point, rect_coords):
539
+ x, y = point
540
+ (x1, y1), (x2, y2) = rect_coords
541
+ return x1 <= x <= x2 and y1 <= y <= y2
542
+
543
+ from math import sqrt
544
+
545
+ def euclidean_distance(point1, point2):
546
+ x1, y1 = point1
547
+ x2, y2 = point2
548
+ return sqrt((x2 - x1)**2 + (y2 - y1)**2)
549
+
550
+ def compute_hatch_centroid(hatch):
551
+ x_coords = []
552
+ y_coords = []
553
+ for path in hatch.paths:
554
+ if path.PATH_TYPE == "PolylinePath":
555
+ for vertex in path.vertices:
556
+ x_coords.append(vertex[0])
557
+ y_coords.append(vertex[1])
558
+ elif path.PATH_TYPE == "EdgePath":
559
+ for edge in path.edges:
560
+ if hasattr(edge, "start"):
561
+ x_coords.append(edge.start[0])
562
+ y_coords.append(edge.start[1])
563
+ if hasattr(edge, "end"):
564
+ x_coords.append(edge.end[0])
565
+ y_coords.append(edge.end[1])
566
+ if x_coords and y_coords:
567
+ return (sum(x_coords) / len(x_coords), sum(y_coords) / len(y_coords))
568
+ return None
569
+
570
+ """### Hatched areas"""
571
+ def get_hatched_areas(datadoc,filename,FinalRatio,rotationangle,SearchArray):
572
+
573
+ print("SearchArray = ",SearchArray)
574
+
575
+ doc = ezdxf.readfile(filename)
576
+ doc.header['$MEASUREMENT'] = 1
577
+ msp = doc.modelspace()
578
+ trial=0
579
+ hatched_areas = []
580
+ threshold=0.001
581
+ TextFound = 0
582
+ j=0
583
+ unique_shapes = []
584
+
585
+
586
+ text_with_positions = []
587
+ text_color_mapping = {}
588
+ color_palette = [
589
+ (255, 0, 0), (0, 0, 255), (0, 255, 255), (0, 64, 0), (255, 204, 0),
590
+ (255, 128, 64), (255, 0, 128), (255, 128, 192), (128, 128, 255),
591
+ (128, 64, 0), (0, 255, 0), (0, 200, 0), (255, 128, 255), (128, 0, 255),
592
+ (0, 128, 192), (128, 0, 128), (128, 0, 0), (0, 128, 255), (149, 1, 70),
593
+ (255, 182, 128), (222, 48, 71), (240, 0, 112), (255, 0, 255),
594
+ (192, 46, 65), (0, 0, 128), (0, 128, 64), (255, 255, 0), (128, 0, 80),
595
+ (255, 255, 128), (90, 255, 140), (255, 200, 20), (91, 16, 51),
596
+ (90, 105, 138), (114, 10, 138), (36, 82, 78), (225, 105, 190),
597
+ (108, 150, 170), (11, 35, 75), (42, 176, 170), (255, 176, 170),
598
+ (209, 151, 15), (81, 27, 85), (226, 106, 122), (67, 119, 149),
599
+ (159, 179, 140), (159, 179, 30), (255, 85, 198), (255, 27, 85),
600
+ (188, 158, 8), (140, 188, 120), (59, 61, 52), (65, 81, 21),
601
+ (212, 255, 174), (15, 164, 90), (41, 217, 245), (213, 23, 182),
602
+ (11, 85, 169), (78, 153, 239), (0, 66, 141), (64, 98, 232),
603
+ (140, 112, 255), (57, 33, 154), (194, 117, 252), (116, 92, 135),
604
+ (74, 43, 98), (188, 13, 123), (129, 58, 91), (255, 128, 100),
605
+ (171, 122, 145), (255, 98, 98), (222, 48, 77)
606
+ ]
607
+ import re
608
+
609
+ text_with_positions = []
610
+ # SearchArray=[["","Wall Type","",""],["","","",""]]
611
+
612
+ # print("SearchArray=",len(SearchArray))
613
+ # print("SearchArray=",len(SearchArray[0]))
614
+ # print("SearchArray=",SearchArray[0][0])
615
+
616
+ if(SearchArray):
617
+ for i in range(len(SearchArray)):
618
+
619
+ if (SearchArray[i][1] and SearchArray[i][2] and SearchArray[i][3]):
620
+ for text_entity in doc.modelspace().query('TEXT MTEXT'):
621
+ text = text_entity.text.strip() if hasattr(text_entity, 'text') else ""
622
+ # if (text.startswith("P") and len(text) == 3) or (text.startswith("I") and len(text) == 3): # Filter for "Wall"
623
+ if(text.startswith(SearchArray[i][1]) and len(text)==int(SearchArray[i][3])):
624
+ position = text_entity.dxf.insert # Extract text position
625
+ x, y = position.x, position.y
626
+
627
+ for text_entity in doc.modelspace().query('TEXT MTEXT'):
628
+ NBS = text_entity.text.strip() if hasattr(text_entity, 'text') else ""
629
+ if (NBS.startswith(SearchArray[i][2])):
630
+ positionNBS = text_entity.dxf.insert # Extract text position
631
+ xNBS, yNBS = positionNBS.x, positionNBS.y
632
+
633
+ if(x == xNBS or y == yNBS):
634
+ textNBS=NBS
635
+ break
636
+
637
+ else:
638
+ textNBS = None
639
+
640
+
641
+
642
+ nearest_hatch = None
643
+ min_distance = float('inf') # Initialize with a very large value
644
+ detected_color = (255, 255, 255) # Default to white
645
+
646
+ # Search for the nearest hatch
647
+ for hatch in doc.modelspace().query('HATCH'): # Query only hatches
648
+ if hatch.paths:
649
+ for path in hatch.paths:
650
+ if path.type == 1: # PolylinePath
651
+ vertices = [v[:2] for v in path.vertices]
652
+ # Calculate the centroid of the hatch
653
+ centroid_x = sum(v[0] for v in vertices) / len(vertices)
654
+ centroid_y = sum(v[1] for v in vertices) / len(vertices)
655
+ centroid = (centroid_x, centroid_y)
656
+
657
+ # Calculate the distance between the text and the hatch centroid
658
+ distance = calculate_distance((x, y), centroid)
659
+
660
+ # Update the nearest hatch if a closer one is found
661
+ if distance < min_distance:
662
+ min_distance = distance
663
+ nearest_hatch = hatch
664
+
665
+ # Get the color of this hatch
666
+ current_color = get_hatch_color(hatch)
667
+ if current_color != (255, 255, 255): # Valid color found
668
+ detected_color = current_color
669
+ break # Stop checking further paths for this hatch
670
+
671
+
672
+ # Append the detected result only once
673
+ text_with_positions.append([text, textNBS, (x, y), detected_color])
674
+ print("text_with_positions=",text_with_positions)
675
+
676
+ elif (SearchArray[i][1] and SearchArray[i][3]):
677
+ for text_entity in doc.modelspace().query('TEXT MTEXT'):
678
+ text = text_entity.text.strip() if hasattr(text_entity, 'text') else ""
679
+ # if (text.startswith("P") and len(text) == 3) or (text.startswith("I") and len(text) == 3): # Filter for "Wall"
680
+ if(text.startswith(SearchArray[i][1]) and len(text)==int(SearchArray[i][3])):
681
+ position = text_entity.dxf.insert # Extract text position
682
+ x, y = position.x, position.y
683
+ textNBS = None
684
+ nearest_hatch = None
685
+ min_distance = float('inf') # Initialize with a very large value
686
+ detected_color = (255, 255, 255) # Default to white
687
+
688
+ # Search for the nearest hatch
689
+ for hatch in doc.modelspace().query('HATCH'): # Query only hatches
690
+ if hatch.paths:
691
+ for path in hatch.paths:
692
+ if path.type == 1: # PolylinePath
693
+ vertices = [v[:2] for v in path.vertices]
694
+ # Calculate the centroid of the hatch
695
+ centroid_x = sum(v[0] for v in vertices) / len(vertices)
696
+ centroid_y = sum(v[1] for v in vertices) / len(vertices)
697
+ centroid = (centroid_x, centroid_y)
698
+
699
+ # Calculate the distance between the text and the hatch centroid
700
+ distance = calculate_distance((x, y), centroid)
701
+
702
+ # Update the nearest hatch if a closer one is found
703
+ if distance < min_distance:
704
+ min_distance = distance
705
+ nearest_hatch = hatch
706
+
707
+ # Get the color of this hatch
708
+ current_color = get_hatch_color(hatch)
709
+ if current_color != (255, 255, 255): # Valid color found
710
+ detected_color = current_color
711
+ break # Stop checking further paths for this hatch
712
+
713
+
714
+ # Append the detected result only once
715
+ text_with_positions.append([text, textNBS, (x, y), detected_color])
716
+ print("text_with_positions=",text_with_positions)
717
+
718
+ elif(SearchArray[i][1]):
719
+ for text_entity in doc.modelspace().query('TEXT MTEXT'):
720
+ text = text_entity.text.strip() if hasattr(text_entity, 'text') else ""
721
+ # if (text.startswith("P") and len(text) == 3) or (text.startswith("I") and len(text) == 3): # Filter for "Wall"
722
+ if(text.startswith(SearchArray[i][1])):
723
+ position = text_entity.dxf.insert # Extract text position
724
+ x, y = position.x, position.y
725
+ textNBS = None
726
+ nearest_hatch = None
727
+ min_distance = float('inf') # Initialize with a very large value
728
+ detected_color = (255, 255, 255) # Default to white
729
+
730
+ # Search for the nearest hatch
731
+ for hatch in doc.modelspace().query('HATCH'): # Query only hatches
732
+ if hatch.paths:
733
+ for path in hatch.paths:
734
+ if path.type == 1: # PolylinePath
735
+ vertices = [v[:2] for v in path.vertices]
736
+ # Calculate the centroid of the hatch
737
+ centroid_x = sum(v[0] for v in vertices) / len(vertices)
738
+ centroid_y = sum(v[1] for v in vertices) / len(vertices)
739
+ centroid = (centroid_x, centroid_y)
740
+
741
+ # Calculate the distance between the text and the hatch centroid
742
+ distance = calculate_distance((x, y), centroid)
743
+
744
+ # Update the nearest hatch if a closer one is found
745
+ if distance < min_distance:
746
+ min_distance = distance
747
+ nearest_hatch = hatch
748
+
749
+ # Get the color of this hatch
750
+ current_color = get_hatch_color(hatch)
751
+ if current_color != (255, 255, 255): # Valid color found
752
+ detected_color = current_color
753
+ break # Stop checking further paths for this hatch
754
+
755
+
756
+ # Append the detected result only once
757
+ text_with_positions.append([text, textNBS, (x, y), detected_color])
758
+ print("text_with_positions=",text_with_positions)
759
+
760
+
761
+
762
+
763
+
764
+
765
+
766
+
767
+ grouped = {}
768
+ for entry in text_with_positions:
769
+ key = entry[0]
770
+ grouped.setdefault(key, []).append(entry)
771
+
772
+ # Filter the groups: if any entry in a group has a non-None Text Nbs, keep only one of those
773
+ filtered_results = []
774
+ for key, entries in grouped.items():
775
+ # Find the first entry with a valid textNBS (non-None)
776
+ complete = next((entry for entry in entries if entry[1] is not None), None)
777
+ if complete:
778
+ filtered_results.append(complete)
779
+ else:
780
+ # If none are complete, you can choose to keep just one entry
781
+ filtered_results.append(entries[0])
782
+
783
+ text_with_positions=filtered_results
784
+
785
+ for entity in msp:
786
+ if entity.dxftype() == 'HATCH':
787
+
788
+ cntPoints=[]
789
+ for path in entity.paths:
790
+
791
+ # path_type = path.type
792
+
793
+ # # Resolve the path type to its name
794
+ # path_type_name = BoundaryPathType(path_type).name
795
+ # print(f"Encountered path type: {path_type_name}")
796
+
797
+ vertices = [] # Reset vertices for each path
798
+
799
+ # print(str(path.type))
800
+
801
+ if str(path.type) == 'BoundaryPathType.POLYLINE' or path.type == 1:
802
+ # if path.type == 2: # Polyline path
803
+ # Handle POLYLINE type HATCH
804
+ vertices = [(vertex[0] * FinalRatio, vertex[1] * FinalRatio) for vertex in path.vertices]
805
+ # print("Hatch Vertices = ",vertices)
806
+
807
+ if len(vertices) > 3:
808
+ poly = ShapelyPolygon(vertices)
809
+ minx, miny, maxx, maxy = poly.bounds
810
+ width = maxx - minx
811
+ height = maxy - miny
812
+
813
+
814
+
815
+
816
+ if (poly.area > 0 and (height > 0.2 or width > 0.2)):
817
+
818
+ length = height
819
+ if(width > length):
820
+ length = width
821
+
822
+ area1 = round(poly.area, 3)
823
+ perimeter = round(poly.length, 3)
824
+ # print("Vertices = ",vertices)
825
+ normalized_vertices = normalize_vertices(vertices)
826
+
827
+ rgb_color = get_hatch_color(entity)
828
+ # print("rgb_color = ",rgb_color)
829
+
830
+ # if(rgb_color == (255, 255, 255)):
831
+ # if(len(text_with_positions)>0):
832
+
833
+ # for text, position, color in text_with_positions:
834
+ # text_position = Point(position[0], position[1])
835
+
836
+ # if poly.contains(text_position):
837
+ # rgb_color = color
838
+ # break
839
+
840
+ duplicate_found = False
841
+ for existing_vertices, existing_area in unique_shapes:
842
+ if normalized_vertices == existing_vertices and areas_are_similar(area1, existing_area):
843
+ duplicate_found = True
844
+ break
845
+
846
+ if not duplicate_found:
847
+ # rgb_color = get_hatch_color(entity) # Assuming this function exists
848
+ unique_shapes.append((normalized_vertices, area1))
849
+ hatched_areas.append([vertices, area1, length, rgb_color])
850
+
851
+ elif str(path.type) == 'BoundaryPathType.EDGE' or path.type == 2:
852
+ # elif path.type == 2: # Edge path
853
+ # Handle EDGE type HATCH
854
+ vert = []
855
+ for edge in path.edges:
856
+ x, y = edge.start
857
+ x1, y1 = edge.end
858
+ vert.append((x * FinalRatio, y * FinalRatio))
859
+ vert.append((x1 * FinalRatio, y1 * FinalRatio))
860
+
861
+ poly = ShapelyPolygon(vert)
862
+ minx, miny, maxx, maxy = poly.bounds
863
+ width = maxx - minx
864
+ height = maxy - miny
865
+
866
+ if (poly.area > 0 and (height > 0.2 or width > 0.2)):
867
+
868
+ length = height
869
+ if(width > length):
870
+ length = width
871
+
872
+ area1 = round(poly.area, 3)
873
+ perimeter = round(poly.length, 3)
874
+ normalized_vertices = normalize_vertices(vert)
875
+ rgb_color = get_hatch_color(entity)
876
+ # print("rgb_color = ",rgb_color)
877
+
878
+ # if(rgb_color == (255, 255, 255)):
879
+ # if(len(text_with_positions)>0):
880
+ # for text, position, color in text_with_positions:
881
+ # text_position = Point(position[0], position[1])
882
+
883
+ # if poly.contains(text_position):
884
+ # rgb_color = color
885
+ # break
886
+
887
+
888
+ duplicate_found = False
889
+ for existing_vertices, existing_area in unique_shapes:
890
+ if normalized_vertices == existing_vertices and areas_are_similar(area1, existing_area):
891
+ duplicate_found = True
892
+ break
893
+
894
+ if not duplicate_found:
895
+ # rgb_color = get_hatch_color(entity) # Assuming this function exists
896
+ unique_shapes.append((normalized_vertices, area1))
897
+ hatched_areas.append([vert, area1, length, rgb_color])
898
+
899
+ else:
900
+ print(f"Encountered path type: {path.type}")
901
+
902
+ elif entity.dxftype() == 'SOLID':
903
+
904
+
905
+
906
+ vertices = [entity.dxf.vtx0 * (FinalRatio), entity.dxf.vtx1* (FinalRatio), entity.dxf.vtx2* (FinalRatio), entity.dxf.vtx3* (FinalRatio)]
907
+ poly = ShapelyPolygon(vertices)
908
+ minx, miny, maxx, maxy = poly.bounds
909
+
910
+ # Calculate the width and height of the bounding box
911
+ width = maxx - minx
912
+ height = maxy - miny
913
+
914
+ if (poly.area > 0 and (height > 0 and width > 0)):
915
+ area1 = round(poly.area, 3)
916
+ perimeter = round(poly.length, 3)
917
+ normalized_vertices = normalize_vertices(vertices)
918
+
919
+ duplicate_found = False
920
+ for existing_vertices, existing_area in unique_shapes:
921
+ if normalized_vertices == existing_vertices or areas_are_similar(area1, existing_area):
922
+ duplicate_found = True
923
+ break
924
+
925
+ if not duplicate_found:
926
+ rgb_color = get_hatch_color(entity) # Assuming this function exists
927
+ unique_shapes.append((normalized_vertices, area1))
928
+ hatched_areas.append([vertices, area1, perimeter, rgb_color])
929
+
930
+
931
+
932
+ elif entity.dxftype() == 'LWPOLYLINE':
933
+
934
+ vertices = []
935
+ lwpolyline = entity
936
+ points = lwpolyline.get_points()
937
+ flag = 0
938
+
939
+ # Collect vertices and apply the FinalRatio
940
+ for i in range(len(points)):
941
+ vertices.append([points[i][0] * FinalRatio, points[i][1] * FinalRatio])
942
+
943
+ # # Ensure there are more than 3 vertices
944
+ if len(vertices) > 3:
945
+ # Check if the polyline is closed
946
+ if vertices[0][0] == vertices[-1][0] or vertices[0][1] == vertices[-1][1]:
947
+ poly = ShapelyPolygon(vertices)
948
+ minx, miny, maxx, maxy = poly.bounds
949
+
950
+ # Calculate width and height of the bounding box
951
+ width = maxx - minx
952
+ height = maxy - miny
953
+
954
+ # Check area and size constraints
955
+ if (poly.area > 0 and (height > 0 and width > 0)):
956
+ area1 = round(poly.area, 3)
957
+ perimeter = round(poly.length, 3)
958
+ normalized_vertices = normalize_vertices(vertices)
959
+
960
+ duplicate_found = False
961
+ for existing_vertices, existing_area in unique_shapes:
962
+ if normalized_vertices == existing_vertices or areas_are_similar(area1, existing_area):
963
+ duplicate_found = True
964
+ break
965
+
966
+ if not duplicate_found:
967
+ rgb_color = get_hatch_color(entity) # Assuming this function exists
968
+ unique_shapes.append((normalized_vertices, area1))
969
+ hatched_areas.append([vertices, area1, perimeter, rgb_color])
970
+
971
+
972
+
973
+ elif entity.dxftype() == 'POLYLINE':
974
+
975
+ flag=0
976
+ vertices = [(v.dxf.location.x * (FinalRatio), v.dxf.location.y * (FinalRatio)) for v in entity.vertices]
977
+ # print('Vertices:', vertices)
978
+
979
+ if(len(vertices)>3):
980
+
981
+ if(vertices[0][0] == vertices[len(vertices)-1][0] or vertices[0][1] == vertices[len(vertices)-1][1]):
982
+
983
+ poly=ShapelyPolygon(vertices)
984
+ minx, miny, maxx, maxy = poly.bounds
985
+
986
+ # Calculate the width and height of the bounding box
987
+ width = maxx - minx
988
+ height = maxy - miny
989
+
990
+ if (poly.area > 0 and (height > 0 and width > 0)):
991
+ area1 = round(poly.area,3)
992
+ perimeter = round (poly.length,3)
993
+ normalized_vertices = normalize_vertices(vertices)
994
+
995
+ duplicate_found = False
996
+ for existing_vertices, existing_area in unique_shapes:
997
+ if normalized_vertices == existing_vertices or areas_are_similar(area1, existing_area):
998
+ duplicate_found = True
999
+ break
1000
+
1001
+ if not duplicate_found:
1002
+ rgb_color = get_hatch_color(entity) # Assuming this function exists
1003
+ unique_shapes.append((normalized_vertices, area1))
1004
+ hatched_areas.append([vertices, area1, perimeter, rgb_color])
1005
+
1006
+
1007
+ elif entity.dxftype() == 'SPLINE':
1008
+
1009
+ spline_entity = entity
1010
+ vertices = []
1011
+ control_points = spline_entity.control_points
1012
+ if(len(control_points)>3):
1013
+ for i in range(len(control_points)):
1014
+ vertices.append([control_points[i][0]* (FinalRatio),control_points[i][1]* (FinalRatio)])
1015
+ poly=ShapelyPolygon(vertices)
1016
+
1017
+ minx, miny, maxx, maxy = poly.bounds
1018
+
1019
+ # Calculate the width and height of the bounding box
1020
+ width = maxx - minx
1021
+ height = maxy - miny
1022
+
1023
+
1024
+ if (poly.area > 0 and (height > 0 and width > 0)):
1025
+ area1 = round(poly.area,3)
1026
+ perimeter = round (poly.length,3)
1027
+ normalized_vertices = normalize_vertices(vertices)
1028
+
1029
+ duplicate_found = False
1030
+ for existing_vertices, existing_area in unique_shapes:
1031
+ if normalized_vertices == existing_vertices or areas_are_similar(area1, existing_area):
1032
+ duplicate_found = True
1033
+ break
1034
+
1035
+ if not duplicate_found:
1036
+ rgb_color = get_hatch_color(entity) # Assuming this function exists
1037
+ unique_shapes.append((normalized_vertices, area1))
1038
+ hatched_areas.append([vertices, area1, perimeter, rgb_color])
1039
+
1040
+
1041
+
1042
+ sorted_data = sorted(hatched_areas, key=lambda x: x[1])
1043
+ return sorted_data,text_with_positions
1044
+
1045
+
1046
+ """### Rotate polygon"""
1047
+
1048
+
1049
+
1050
+ def rotate_point(point, angle,pdfrotation,width,height, center_point=(0, 0)):
1051
+ """Rotates a point around center_point(origin by default)
1052
+ Angle is in degrees.
1053
+ Rotation is counter-clockwise
1054
+ """
1055
+ angle_rad = radians(angle % 360)
1056
+ # Shift the point so that center_point becomes the origin
1057
+ new_point = (point[0] - center_point[0], point[1] - center_point[1])
1058
+ new_point = (new_point[0] * cos(angle_rad) - new_point[1] * sin(angle_rad),
1059
+ new_point[0] * sin(angle_rad) + new_point[1] * cos(angle_rad))
1060
+ # Reverse the shifting we have done
1061
+ if pdfrotation!=0:
1062
+
1063
+ new_point = (new_point[0]+width + center_point[0], new_point[1] + center_point[1]) #pdfsize[2] is the same as +width
1064
+ else:
1065
+
1066
+ new_point = (new_point[0] + center_point[0], new_point[1]+ height + center_point[1]) # pdfsize[3] is the same as +height
1067
+ # new_point = (new_point[0] + center_point[0], new_point[1] + center_point[1])
1068
+ return new_point
1069
+
1070
+
1071
+ def rotate_polygon(polygon, angle, pdfrotation,width,height,center_point=(0, 0)):
1072
+ """Rotates the given polygon which consists of corners represented as (x,y)
1073
+ around center_point (origin by default)
1074
+ Rotation is counter-clockwise
1075
+ Angle is in degrees
1076
+ """
1077
+ rotated_polygon = []
1078
+ for corner in polygon:
1079
+ rotated_corner = rotate_point(corner, angle,pdfrotation,width,height, center_point)
1080
+ rotated_polygon.append(rotated_corner)
1081
+ return rotated_polygon
1082
+
1083
+ #create a dataframe containing color , count(how many times is this object found in the plan), area of 1 of these shapes, total area
1084
+ #perimeter, totat perimeter, length, total length
1085
+ #import pandas as pd
1086
+ #SimilarAreaDictionary= pd.DataFrame(columns=['Guess','Color','Occurences','Area','Total Area','Perimeter','Total Perimeter','Length','Total Length','R','G','B'])
1087
+ #loop 3la hatched areas and count the occurences of each shape w create a table bl hagat di
1088
+
1089
+
1090
+
1091
+ def Create_DF(dxfpath,datadoc,hatched_areas):
1092
+
1093
+ FinalRatio= RetriveRatio(datadoc,dxfpath)
1094
+
1095
+ # hatched_areas = get_hatched_areas(datadoc,dxfpath,FinalRatio)
1096
+
1097
+ # hatched_areas=remove_duplicate_shapes(new_hatched_areas)
1098
+
1099
+ # SimilarAreaDictionary= pd.DataFrame(columns=['Area', 'Total Area', 'Perimeter', 'Total Perimeter', 'Occurences', 'Color'])
1100
+ SimilarAreaDictionary= pd.DataFrame(columns=['Guess','Color','Occurences','Area','Total Area','Perimeter','Total Perimeter','Length','Total Length','Texts','Comments'])
1101
+
1102
+ # colorRanges2=generate_color_array(30000)
1103
+ # 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]]
1104
+ # colorUsed=[]
1105
+ TotalArea=0
1106
+ TotalPerimeter=0
1107
+ for shape in hatched_areas:
1108
+ area = shape[1] # area
1109
+ perimeter = shape[2] # perimeter
1110
+ # if(i < len(colorRanges)):
1111
+ # color = colorRanges[i]
1112
+ # colorUsed.append(color)
1113
+ # else:
1114
+ # color = colorRanges2[i]
1115
+ # colorUsed.append(color)
1116
+ TotalArea = area
1117
+ TotalPerimeter = perimeter
1118
+ tol=0
1119
+ condition1 = (SimilarAreaDictionary['Area'] >= area - tol) & (SimilarAreaDictionary['Area'] <= area +tol)
1120
+ condition2 = (SimilarAreaDictionary['Perimeter'] >= perimeter -tol) & (SimilarAreaDictionary['Perimeter'] <= perimeter +tol)
1121
+ combined_condition = condition1 & condition2
1122
+
1123
+ if any(combined_condition):
1124
+ index = np.where(combined_condition)[0][0]
1125
+ SimilarAreaDictionary.at[index, 'Occurences'] += 1
1126
+ SimilarAreaDictionary.at[index, 'Total Area'] = SimilarAreaDictionary.at[index, 'Area'] * SimilarAreaDictionary.at[index, 'Occurences']
1127
+ SimilarAreaDictionary.at[index, 'Total Perimeter'] = SimilarAreaDictionary.at[index, 'Perimeter'] * SimilarAreaDictionary.at[index, 'Occurences']
1128
+ else:
1129
+ TotalArea=area
1130
+ TotalPerimeter=perimeter
1131
+ # print("Shape[3]",shape[3])
1132
+ new_data = {'Area': area, 'Total Area': TotalArea ,'Perimeter': perimeter, 'Total Perimeter': TotalPerimeter, 'Occurences': 1, 'Color':shape[3],'Comments':''} #add color here and read color to insert in
1133
+ SimilarAreaDictionary = pd.concat([SimilarAreaDictionary, pd.DataFrame([new_data])], ignore_index=True)
1134
+
1135
+ # print(SimilarAreaDictionary)
1136
+ return SimilarAreaDictionary
1137
+ """### Draw on Image and PDF"""
1138
+
1139
+ # from sklearn.cluster import KMeans
1140
+
1141
+ def color_distance(color1, color2):
1142
+ print("color1 = ",color1)
1143
+ print("color2 = ",color2)
1144
+ print("abs(color1[0] - color2[0]) = ",abs(color1[0] - color2[0]))
1145
+ print("abs(color1[1] - color2[1]) = ",abs(color1[1] - color2[1]))
1146
+ print("abs(color1[2] - color2[2]) = ",abs(color1[2] - color2[2]))
1147
+ if(abs(color1[0] - color2[0]) < 20 and
1148
+ abs(color1[1] - color2[1]) < 20 and
1149
+ abs(color1[2] - color2[2]) < 20):
1150
+ return 1
1151
+ else:
1152
+ return 100
1153
+ # return np.sqrt(sum((a - b) ** 2 for a, b in zip(color1, color2)))
1154
+
1155
+ # Unify colors within a distance threshold
1156
+ def unify_colors(df, threshold=20):
1157
+ # Convert colors to tuple if they are not already in tuple format
1158
+ df['Color'] = df['Color'].apply(lambda x: tuple(x) if isinstance(x, list) else x)
1159
+
1160
+ # Iterate through the DataFrame and compare each color with the next one
1161
+ for i in range(len(df) - 1): # We don't need to compare the last color with anything
1162
+ current_color = df.at[i, 'Color']
1163
+ next_color = df.at[i + 1, 'Color']
1164
+
1165
+ # If the distance between current color and the next color is smaller than the threshold
1166
+ if color_distance(current_color, next_color) <= threshold:
1167
+ # Make both the same color (unify them to the current color)
1168
+ df.at[i + 1, 'Color'] = current_color # Change the next color to the current color
1169
+
1170
+ return df
1171
+
1172
+ def normalize_color(color):
1173
+ """Convert PDF color (range 0-1) to RGB (range 0-255)."""
1174
+ return tuple(min(max(round(c * 255), 0), 255) for c in color)
1175
+
1176
+
1177
+
1178
+
1179
+ def adjustannotations(OutputPdfStage1,text_with_positions):
1180
+ input_pdf_path = OutputPdfStage1
1181
+ output_pdf_path = "Final-WallsAdjusted.pdf"
1182
+
1183
+ # Load the input PDF
1184
+ pdf_bytes_io = BytesIO(OutputPdfStage1)
1185
+
1186
+ reader = PdfReader(pdf_bytes_io)
1187
+ writer = PdfWriter()
1188
+
1189
+ # Append all pages to the writer
1190
+ writer.append_pages_from_reader(reader)
1191
+
1192
+ # Add metadata (optional)
1193
+ metadata = reader.metadata
1194
+ writer.add_metadata(metadata)
1195
+
1196
+ # x=input_pdf_path
1197
+
1198
+ # # Load the input PDF
1199
+ # reader = PdfReader(input_pdf_path)
1200
+ # writer = PdfWriter()
1201
+
1202
+ # # Append all pages to the writer
1203
+ # writer.append_pages_from_reader(reader)
1204
+
1205
+ # # Add metadata (optional)
1206
+ # metadata = reader.metadata
1207
+ # writer.add_metadata(metadata)
1208
+
1209
+ for page_index, page in enumerate(writer.pages):
1210
+ if "/Annots" in page:
1211
+ annotations = page["/Annots"]
1212
+ for annot_index, annot in enumerate(annotations):
1213
+ obj = annot.get_object()
1214
+
1215
+ # print("obj", obj)
1216
+ # print(obj.get("/IT"))
1217
+
1218
+ if obj.get("/Subtype") == "/Line":
1219
+ # print("AWL ANNOT IF")
1220
+ # Check the /IT value to differentiate annotations
1221
+ # if "/Contents" in obj and "m" in obj["/Contents"]:
1222
+ if "/Subj" in obj and "Perimeter Measurement" in obj["/Subj"]:
1223
+ # print("Tany IF")
1224
+ obj.update({
1225
+ NameObject("/Measure"): DictionaryObject({
1226
+ NameObject("/Type"): NameObject("/Measure"),
1227
+ NameObject("/L"): DictionaryObject({
1228
+ NameObject("/G"): FloatObject(1),
1229
+ NameObject("/U"): TextStringObject("m"), # Unit of measurement for area
1230
+ }),
1231
+
1232
+ }),
1233
+ NameObject("/IT"): NameObject("/LineDimension"), # Use more distinctive name
1234
+ NameObject("/Subj"): TextStringObject("Length Measurement"), # Intent explicitly for Area
1235
+ })
1236
+ # print(obj)
1237
+
1238
+ if obj.get("/Subtype") in ["/Line", "/PolyLine"] and "/C" in obj:
1239
+ # Normalize and match the color
1240
+ annot_color = normalize_color(obj["/C"])
1241
+ matched_entry = next(
1242
+ ((text, NBS) for text,NBS, _, color in text_with_positions if annot_color == color),
1243
+ (None, None)
1244
+ )
1245
+ # print("matched_entry = ",matched_entry)
1246
+ matched_text, matched_nbs = matched_entry
1247
+
1248
+ combined_text = ""
1249
+ if matched_text and matched_nbs:
1250
+ combined_text = f"{matched_text} - {matched_nbs}"
1251
+ elif matched_text:
1252
+ combined_text = matched_text
1253
+ elif matched_nbs:
1254
+ combined_text = matched_nbs
1255
+
1256
+ obj.update({
1257
+ NameObject("/T"): TextStringObject(combined_text), # Custom text for "Comment" column
1258
+ })
1259
+
1260
+
1261
+
1262
+ output_pdf_io = BytesIO()
1263
+ writer.write(output_pdf_io)
1264
+ output_pdf_io.seek(0)
1265
+
1266
+ print(f"Annotations updated and saved to {output_pdf_path}")
1267
+ return output_pdf_io.read()
1268
+ # # Save the modified PDF
1269
+ # with open(output_pdf_path, "wb") as fp:
1270
+ # writer.write(fp)
1271
+
1272
+ # print(f"Annotations updated and saved to {output_pdf_path}")
1273
+ # return output_pdf_path
1274
+
1275
+
1276
+
1277
+
1278
+
1279
+ def calculate_distance(p1, p2):
1280
+ return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
1281
+
1282
+
1283
+
1284
+ def mainFunctionDrawImgPdf(datadoc,dxfpath, dxfratio,SearchArray,pdfpath=0,pdfname=0):
1285
+ OutputPdfStage1='BB Trial.pdf'
1286
+ FinalRatio= RetriveRatio(datadoc,dxfpath)
1287
+
1288
+ # hatched_areas = get_hatched_areas(datadoc,dxfpath,FinalRatio)
1289
+ # hatched_areas=remove_duplicate_shapes(new_hatched_areas)
1290
+
1291
+ img,pix2=pdftoimg(datadoc)
1292
+ flipped_horizontal=flip(img)
1293
+ allcnts = []
1294
+ imgg = flipped_horizontal
1295
+ # imgtransparent1=imgg.copy()
1296
+ doc = fitz.open('pdf',datadoc)
1297
+ page2 = doc[0]
1298
+ rotationOld=page2.rotation
1299
+ derotationMatrix=page2.derotation_matrix
1300
+ # print("Derotation Matrix = ",derotationMatrix)
1301
+ pix=page2.get_pixmap()
1302
+ width=abs(page2.mediabox[2])+abs(page2.mediabox[0])
1303
+ height=abs(page2.mediabox[3])+abs(page2.mediabox[1])
1304
+ print('mediabox', width , height)
1305
+
1306
+
1307
+
1308
+
1309
+
1310
+
1311
+ if page2.rotation!=0:
1312
+
1313
+ rotationangle = page2.rotation
1314
+ page2.set_rotation(0)
1315
+ ratio = pix.width/ img.shape[0]
1316
+ else:
1317
+ ratio = pix.width/ img.shape[1]
1318
+ rotationangle = 270
1319
+
1320
+ hatched_areas,text_with_positions = get_hatched_areas(datadoc,dxfpath,FinalRatio,rotationangle,SearchArray)
1321
+ allshapes=[]
1322
+ # Iterate through each polygon in metric units
1323
+ NewColors = []
1324
+ SimilarAreaDictionary=Create_DF(dxfpath,datadoc,hatched_areas)
1325
+ i=0
1326
+ flagcolor = 0
1327
+ ColorCounter = 0
1328
+ ColorCheck=[]
1329
+ deleterows = []
1330
+
1331
+
1332
+ # def color_distance(color1, color2):
1333
+ # return np.sqrt(sum((a - b) ** 2 for a, b in zip(color1, color2)))
1334
+
1335
+ color_margin = 2 # Define margin threshold
1336
+
1337
+ for polygon in hatched_areas:
1338
+ cntPoints = []
1339
+ cntPoints1 = []
1340
+ shapeePerimeter = []
1341
+ shapeeArea = []
1342
+ Text_Detected = 0
1343
+
1344
+ blackImgShapes = np.zeros(imgg.shape[:2], dtype="uint8")
1345
+ blackImgShapes= cv2.cvtColor(blackImgShapes, cv2.COLOR_GRAY2BGR)
1346
+
1347
+ # Convert each vertex from metric to pixel coordinates
1348
+ for vertex in polygon[0]:
1349
+ x = (vertex[0]) *dxfratio
1350
+ y = (vertex[1]) *dxfratio
1351
+ if rotationangle==0:
1352
+ if y<0:
1353
+ y=y*-1
1354
+ cntPoints.append([int(x), int(y)])
1355
+ cntPoints1.append([x, y])
1356
+
1357
+ cv2.drawContours(blackImgShapes, [np.array(cntPoints)], -1, ([255,255,255]), thickness=-1)
1358
+ x, y, w, h = cv2.boundingRect(np.array(cntPoints))
1359
+ firstpoint = 0
1360
+ for poi in np.array(cntPoints1):
1361
+ if firstpoint == 0:
1362
+ x2, y2 = poi
1363
+ p2 = fitz.Point(x2,y2)
1364
+ # p1 = fitz.Point(x1,y1)
1365
+ p2=p2*derotationMatrix
1366
+ shapeePerimeter.append([p2[0],p2[1]])
1367
+ firstpoint = 1
1368
+ else:
1369
+ x1, y1 = poi
1370
+ p1 = fitz.Point(x1,y1)
1371
+ # p1 = fitz.Point(x1,y1)
1372
+ p1=p1*derotationMatrix
1373
+ # print("P1 = ",p1)
1374
+ shapeePerimeter.append([p1[0],p1[1]])
1375
+
1376
+ shapeePerimeter.append([p2[0],p2[1]])
1377
+ shapeePerimeter=np.flip(shapeePerimeter,1)
1378
+ shapeePerimeter=rotate_polygon(shapeePerimeter,rotationangle,rotationOld,width,height)
1379
+
1380
+ for poi in np.array(cntPoints1):
1381
+ x1, y1 = poi
1382
+ p1 = fitz.Point(x1,y1)
1383
+ # p1 = fitz.Point(x1,y1)
1384
+ p1=p1*derotationMatrix
1385
+ # print("P1 = ",p1)
1386
+ shapeeArea.append([p1[0],p1[1]])
1387
+
1388
+ shapeeArea.append([p2[0],p2[1]])
1389
+ shapeeArea=np.flip(shapeeArea,1)
1390
+ shapeeArea=rotate_polygon(shapeeArea,rotationangle,rotationOld,width,height)
1391
+
1392
+ tol=0
1393
+ condition1 = (SimilarAreaDictionary['Area'] >= polygon[1] - tol) & (SimilarAreaDictionary['Area'] <= polygon[1] +tol)
1394
+ condition2 = (SimilarAreaDictionary['Perimeter'] >= polygon[2] -tol) & (SimilarAreaDictionary['Perimeter'] <= polygon[2] +tol)
1395
+ combined_condition = condition1 & condition2
1396
+ # print("combined_condition = ",combined_condition)
1397
+
1398
+ if any(combined_condition):
1399
+
1400
+ flagcolor = 1
1401
+ index = np.where(combined_condition)[0][0]
1402
+ # print(SimilarAreaDictionary.at[index, 'Color'])
1403
+ NewColors=SimilarAreaDictionary.at[index, 'Color']
1404
+
1405
+ else:
1406
+ flagcolor = 2
1407
+ NewColors=SimilarAreaDictionary.at[i, 'Color']
1408
+ # flagcolor = 2
1409
+
1410
+ # cv2.drawContours(imgg, [np.array(cntPoints)], -1, (NewColors), thickness=2)
1411
+ # print("new color = ",NewColors)
1412
+ # print("New Colors = ",NewColors)
1413
+ # if img is not None or img.shape[0] != 0 or img.shape[1] != 0:
1414
+ if(int(NewColors[0])==255 and int(NewColors[1])==255 and int(NewColors[2])==255):
1415
+
1416
+ WhiteImgFinal = cv2.bitwise_and(blackImgShapes,imgg)
1417
+ # print("length = ",WhiteImgFinal.shape[0])
1418
+ # print("width = ",WhiteImgFinal.shape[1])
1419
+ flipped=flip(WhiteImgFinal)
1420
+ # print("Flipped")
1421
+ # cv2_imshow(flipped)
1422
+
1423
+ imgslice = WhiteImgFinal[y:y+h, x:x+w]
1424
+ # print("length slice = ",imgslice.shape[0])
1425
+ # print("width slice = ",imgslice.shape[1])
1426
+ if(imgslice.shape[0] != 0 and imgslice.shape[1] != 0):
1427
+ flippedSlice=flip(imgslice)
1428
+ # print("Sliced & Flipped")
1429
+ # cv2_imshow(flippedSlice)
1430
+
1431
+ # Convert flippedSlice to PIL for color extraction
1432
+ flippedSlice_pil = Image.fromarray(flippedSlice)
1433
+
1434
+ # Define patch size for color sampling (e.g., 10x10 pixels)
1435
+ patch_size = 100
1436
+ patch_colors = []
1437
+
1438
+ # Loop through patches in the image
1439
+ for i in range(0, flippedSlice_pil.width, patch_size):
1440
+ for j in range(0, flippedSlice_pil.height, patch_size):
1441
+ # Crop a patch from the original image
1442
+ patch = flippedSlice_pil.crop((i, j, i + patch_size, j + patch_size))
1443
+ patch_colors += patch.getcolors(patch_size * patch_size)
1444
+
1445
+ # Calculate the dominant color from all patches
1446
+ max_count = 0
1447
+ dominant_color = None
1448
+ tolerance = 5
1449
+ black_threshold = 30 # Max RGB value for a color to be considered "black"
1450
+ white_threshold = 225 # Min RGB value for a color to be considered "white"
1451
+
1452
+ for count, color in patch_colors:
1453
+ # Exclude colors within the black and white ranges
1454
+ if not (all(c <= black_threshold for c in color) or all(c >= white_threshold for c in color)):
1455
+ # Update if the current color has a higher count than previous max
1456
+ if count > max_count:
1457
+ max_count = count
1458
+ dominant_color = color
1459
+
1460
+ # print("Dominant Color =", dominant_color)
1461
+
1462
+ # Append dominant color to ColorCheck and update NewColors
1463
+ if dominant_color is not None:
1464
+ ColorCheck.append(dominant_color)
1465
+
1466
+ NewColors = None # Initialize NewColors
1467
+
1468
+ for color in ColorCheck:
1469
+ # Check if the current color is within the tolerance
1470
+ # print("color = ",color)
1471
+ # print("dominant_color = ",dominant_color)
1472
+ if (abs(color[0] - dominant_color[0]) < 20 and
1473
+ abs(color[1] - dominant_color[1]) < 20 and
1474
+ abs(color[2] - dominant_color[2]) < 20):
1475
+ NewColors = (color[2], color[1], color[0]) # Set the new color
1476
+ break
1477
+ else:
1478
+ # If no color in ColorCheck meets the tolerance, use the dominant color
1479
+ NewColors = (dominant_color[2], dominant_color[1], dominant_color[0])
1480
+ # break
1481
+
1482
+ # Avoid appending `dominant_color` again unnecessarily
1483
+ if NewColors not in ColorCheck:
1484
+ ColorCheck.append(NewColors)
1485
+
1486
+ if flagcolor == 1:
1487
+ SimilarAreaDictionary.at[index, 'Color'] = NewColors
1488
+ # # print(f"Updated Color at index {index} with {NewColors}.")
1489
+ elif flagcolor == 2:
1490
+ SimilarAreaDictionary.at[i, 'Color'] = NewColors
1491
+ # print("New Colors = ",NewColors)
1492
+ cv2.drawContours(imgg, [np.array(cntPoints)], -1, ([NewColors[2],NewColors[1],NewColors[0]]), thickness=3)
1493
+
1494
+
1495
+
1496
+
1497
+ start_point1 = shapeePerimeter[0]
1498
+ end_point1 = shapeePerimeter[1]
1499
+ start_point2 = shapeePerimeter[0]
1500
+ end_point2 = shapeePerimeter[-2]
1501
+
1502
+ distance1 = calculate_distance(start_point1, end_point1)
1503
+ distance2 = calculate_distance(start_point2, end_point2)
1504
+
1505
+
1506
+
1507
+ # Divide the shapePerimeter into two halves
1508
+ half_index = len(shapeePerimeter) // 2
1509
+ half1 = shapeePerimeter[1:half_index+1]
1510
+ half2 = shapeePerimeter[half_index:]
1511
+
1512
+ # Calculate distances for the halves
1513
+ if len(half1) >= 2:
1514
+ half1_distance = sum(calculate_distance(half1[i], half1[i + 1]) for i in range(len(half1) - 1))
1515
+ else:
1516
+ half1_distance = 0
1517
+
1518
+ if len(half2) >= 2:
1519
+ half2_distance = sum(calculate_distance(half2[i], half2[i + 1]) for i in range(len(half2) - 1))
1520
+ else:
1521
+ half2_distance = 0
1522
+
1523
+ max_distance = max(distance1, distance2, half1_distance)
1524
+
1525
+ if max_distance == distance1:
1526
+ # Draw the line annotation for distance1
1527
+ chosen_start = start_point1
1528
+ chosen_end = end_point1
1529
+ annot12 = page2.add_line_annot(chosen_start, chosen_end)
1530
+ elif max_distance == distance2:
1531
+ # Draw the line annotation for distance2
1532
+ chosen_start = start_point2
1533
+ chosen_end = end_point2
1534
+ annot12 = page2.add_line_annot(chosen_start, chosen_end)
1535
+ elif max_distance == half1_distance:
1536
+ # Draw the polyline annotation for half1
1537
+ annot12 = page2.add_polyline_annot(half1)
1538
+ # else: # max_distance == half2_distance
1539
+ # # Draw the polyline annotation for half2
1540
+ # annot12 = page2.add_polyline_annot(half2)
1541
+
1542
+
1543
+
1544
+ annot12.set_border(width=0.8)
1545
+ annot12.set_colors(stroke=(int(NewColors[0])/255,int(NewColors[1])/255,int(NewColors[2])/255))
1546
+ # annot12.set_info(content=str(polygon[2])+' m',subject='Perimeter Measurement', title="ADR Team")
1547
+ annot12.set_info(subject='Perimeter Measurement',content=str(polygon[2])+' m')
1548
+ annot12.set_opacity(0.8)
1549
+ annot12.update()
1550
+
1551
+
1552
+ i += 1
1553
+ alpha = 0.8 # Transparency factor.
1554
+
1555
+ page2.set_rotation(rotationOld)
1556
+ Correct_img=flip(imgg)
1557
+
1558
+ image_new1 = cv2.addWeighted(Correct_img, alpha, img, 1 - alpha, 0)
1559
+ SimilarAreaDictionary = SimilarAreaDictionary.fillna(' ')
1560
+
1561
+ # Define white color to filter out
1562
+ white_color = (255, 255, 255)
1563
+
1564
+ # Delete rows where 'Guess' equals white_color
1565
+ SimilarAreaDictionary = SimilarAreaDictionary[SimilarAreaDictionary['Color'] != white_color]
1566
+
1567
+ # Reset the index to update row numbering
1568
+ SimilarAreaDictionary.reset_index(drop=True, inplace=True)
1569
+
1570
+
1571
+ grouped_df = SimilarAreaDictionary.groupby('Color').agg({
1572
+ 'Occurences': 'sum', # Sum of occurrences for each color
1573
+ 'Area':'first',
1574
+ 'Total Area': 'sum', # Sum of areas for each color
1575
+ 'Perimeter':'first',
1576
+ 'Total Perimeter': 'sum', # Sum of perimeters for each color
1577
+
1578
+ }).reset_index()
1579
+
1580
+
1581
+ # Apply the unification function
1582
+ # SimilarAreaDictionary = unify_colors(SimilarAreaDictionary)
1583
+
1584
+
1585
+ # print(SimilarAreaDictionary)
1586
+ # print(grouped_df)
1587
+ # doc.save(OutputPdfStage1)
1588
+ # OutputPdfStage2=adjustannotations(OutputPdfStage1,text_with_positions)
1589
+ modified_pdf_data = doc.tobytes()
1590
+ OutputPdfStage2=adjustannotations(modified_pdf_data,text_with_positions)
1591
+ latestimg,pix=pdftoimg(OutputPdfStage2)
1592
+ doc2 =fitz.open('pdf',OutputPdfStage2)
1593
+
1594
+ gc,spreadsheet_service,spreadsheetId, spreadsheet_url , namepathArr=google_sheet_Legend.legendGoogleSheets(grouped_df , pdfname,pdfpath)
1595
+ # dbxTeam=tsadropboxretrieval.ADR_Access_DropboxTeam('user')
1596
+ # md, res =dbxTeam.files_download(path= pdfpath+pdfname)
1597
+ # data = res.content
1598
+ # doc=fitz.open("pdf", data)
1599
+ # list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
1600
+ list1=pd.DataFrame(columns=['content', 'id', 'subject','color'])
1601
+
1602
+ # for page in doc:
1603
+ for page in doc2:
1604
+ # Iterate through annotations on the page
1605
+ for annot in page.annots():
1606
+ # Get the color of the annotation
1607
+ annot_color = annot.colors
1608
+ if annot_color is not None:
1609
+ # annot_color is a dictionary with 'stroke' and 'fill' keys
1610
+ stroke_color = annot_color.get('stroke') # Border color
1611
+ fill_color = annot_color.get('fill') # Fill color
1612
+ if fill_color:
1613
+ v='fill'
1614
+ # print('fill')
1615
+ if stroke_color:
1616
+ v='stroke'
1617
+ x,y,z=int(annot_color.get(v)[0]*255),int(annot_color.get(v)[1]*255),int(annot_color.get(v)[2]*255)
1618
+ list1.loc[len(list1)] =[annot.info['content'],annot.info['id'],annot.info['subject'],[x,y,z]]
1619
+ print('LISTTT',list1)
1620
+ return doc2,latestimg, SimilarAreaDictionary ,spreadsheetId, spreadsheet_url , namepathArr , list1,hatched_areas
1621
+
1622
+