AOZ2025 commited on
Commit
ac34dc6
·
verified ·
1 Parent(s): 4ed46b9

Upload 12 files

Browse files
Models/best_tag_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:065f0b156e8c6fd02afe6cc43f7567ed637fd1f3c82dd858df9c594daab51708
3
+ size 3091095
Models/div_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:446e60cf4788c7e5ffcd9bb59c1583b4ee283be6cd19eb85bd616705ce55dd5a
3
+ size 1129942
Models/imputer.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10fb207b1c12eb9df04a8d25e54e13225b20c8b68424af536cf8b8c368fd4076
3
+ size 1183
Models/input_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:412f7b53e10dc593c96fb4278b6186a61a24614aab864664c60679bd320d264f
3
+ size 1014928
Models/label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b21cfd8a5d27715d91c11d300cc84444209b277e3f147e6f34662eb2ecfe02a3
3
+ size 553
Models/ohe_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4216070d03c2d9bf62c071c153d2c5949fa2af6771a24a44c700dadf9663e688
3
+ size 2220
Models/p_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65dbed8de556cdd3e17b7e1dab5f252184fcf3b82b2401a71c348729cb718501
3
+ size 1055004
Models/scaler.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a9fb57a7f3539dfc3eccfcfafabbbe3537f349c3fec3eeec587f9931c63cda5
3
+ size 911
Models/tag_classifier.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fdf72dbbf96e1143b540e317afcaa4dfaa982936851c8cc193d440d5d606cd2
3
+ size 465294
Models/tag_classifier_complete.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41bdc16ad733e069fe67020364cbc13115132331a85dcff476607a680af26067
3
+ size 1039451
predict_tags.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import torch
3
+ import torch.nn as nn
4
+ import joblib
5
+ import numpy as np
6
+ import math
7
+ import pandas as pd
8
+ import os
9
+ import spacy
10
+ import random
11
+ import shutil
12
+ from lxml import etree
13
+ import webbrowser
14
+ from sklearn.preprocessing import LabelEncoder, StandardScaler, OneHotEncoder
15
+ from sklearn.impute import SimpleImputer
16
+
17
+ body_width = None
18
+ num_nodes = None
19
+ num_chars = None
20
+
21
+ # Load the pretrained spaCy model
22
+ nlp = spacy.load("en_core_web_sm")
23
+
24
+ def verb_ratio(text):
25
+ doc = nlp(text)
26
+ if len(doc) > 5:
27
+ return 0
28
+
29
+ verb_count = sum(1 for token in doc if token.pos_ == "VERB" and token.lemma_.lower() not in ["username"])
30
+ total_words = sum(1 for token in doc if token.is_alpha)
31
+
32
+ return verb_count / total_words if total_words > 0 else 0
33
+
34
+ def is_near_gray(r, g, b, threshold=30, min_val=50, max_val=200):
35
+ return (
36
+ min_val <= r <= max_val and
37
+ min_val <= g <= max_val and
38
+ min_val <= b <= max_val and
39
+ abs(r - g) <= threshold and
40
+ abs(g - b) <= threshold and
41
+ abs(r - b) <= threshold
42
+ )
43
+
44
+ def color_difference(color1, color2):
45
+ if not all([color1, color2]):
46
+ return 0
47
+
48
+ r1, g1, b1 = color1
49
+ r2, g2, b2 = color2
50
+
51
+ distance = math.sqrt((r2-r1)**2 + (g2-g1)**2 + (b2-b1)**2)
52
+ max_distance = math.sqrt(3 * 255**2)
53
+ normalized_distance = distance / max_distance
54
+
55
+ return normalized_distance
56
+
57
+ class ImprovedTagClassifier(nn.Module):
58
+ def __init__(self, input_size, output_size, dropout_rate=0.4):
59
+ super(ImprovedTagClassifier, self).__init__()
60
+ self.fc1 = nn.Linear(input_size, 512)
61
+ self.bn1 = nn.BatchNorm1d(512)
62
+ self.fc2 = nn.Linear(512, 256)
63
+ self.bn2 = nn.BatchNorm1d(256)
64
+ self.fc3 = nn.Linear(256, 128)
65
+ self.bn3 = nn.BatchNorm1d(128)
66
+ self.fc4 = nn.Linear(128, output_size)
67
+ self.dropout = nn.Dropout(dropout_rate)
68
+ self.leaky_relu = nn.LeakyReLU(0.1)
69
+ self.skip1_3 = nn.Linear(512, 128)
70
+
71
+ self._initialize_weights()
72
+
73
+ def _initialize_weights(self):
74
+ for m in self.modules():
75
+ if isinstance(m, nn.Linear):
76
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
77
+ if m.bias is not None:
78
+ nn.init.constant_(m.bias, 0)
79
+ elif isinstance(m, nn.BatchNorm1d):
80
+ nn.init.constant_(m.weight, 1)
81
+ nn.init.constant_(m.bias, 0)
82
+
83
+ def forward(self, x):
84
+ x1 = self.fc1(x)
85
+ x1 = self.bn1(x1)
86
+ x1 = self.leaky_relu(x1)
87
+ x1 = self.dropout(x1)
88
+
89
+ x2 = self.fc2(x1)
90
+ x2 = self.bn2(x2)
91
+ x2 = self.leaky_relu(x2)
92
+ x2 = self.dropout(x2)
93
+
94
+ x3 = self.fc3(x2)
95
+ skip_x1 = self.skip1_3(x1)
96
+ x3 = x3 + skip_x1
97
+ x3 = self.bn3(x3)
98
+ x3 = self.leaky_relu(x3)
99
+ x3 = self.dropout(x3)
100
+
101
+ output = self.fc4(x3)
102
+ return output
103
+
104
+ class MultiLevelTagClassifier:
105
+ def __init__(self, device='cuda'):
106
+ self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
107
+ self.models = {}
108
+ self.preprocessors = {}
109
+ self.label_encoders = {}
110
+
111
+ self.tag_hierarchy = {
112
+ 'DIV': ['DIV', 'FOOTER', 'NAVBAR', 'LIST', 'CARD'],
113
+ 'P': ['P', 'LABEL', 'LI', 'TEST'],
114
+ 'INPUT': ['INPUT', 'DROPDOWN']
115
+ }
116
+
117
+ print(f"Using device: {self.device}")
118
+
119
+ def load_models(self, model_dir='../Models'):
120
+ for parent_tag in self.tag_hierarchy.keys():
121
+ model_path = f'{model_dir}/{parent_tag.lower()}_classifier.pth'
122
+ if os.path.exists(model_path):
123
+ print(f"Loading {parent_tag} model from {model_path}")
124
+ checkpoint = torch.load(model_path, map_location=self.device)
125
+
126
+ model = ImprovedTagClassifier(
127
+ checkpoint['input_size'],
128
+ checkpoint['output_size']
129
+ ).to(self.device)
130
+ model.load_state_dict(checkpoint['model_state_dict'])
131
+ model.eval()
132
+
133
+ self.models[parent_tag] = model
134
+ self.preprocessors[parent_tag] = checkpoint['preprocessors']
135
+ self.label_encoders[parent_tag] = checkpoint['preprocessors']['label_encoder']
136
+
137
+ print(f"Loaded {parent_tag} model (Test Accuracy: {checkpoint['test_accuracy']:.4f})")
138
+ else:
139
+ print(f"Model file {model_path} not found!")
140
+
141
+ def predict_hierarchical(self, sample_data, base_prediction):
142
+ if base_prediction not in self.tag_hierarchy:
143
+ return base_prediction, 1.0
144
+
145
+ if base_prediction not in self.models:
146
+ print(f"No sub-classifier found for {base_prediction}")
147
+ return base_prediction, 1.0
148
+
149
+ preprocessors = self.preprocessors[base_prediction]
150
+ sample_df = pd.DataFrame([sample_data])
151
+
152
+ cat_cols = preprocessors['categorical_cols']
153
+ cont_cols = preprocessors['continuous_cols']
154
+
155
+ for col in cat_cols + cont_cols:
156
+ if col not in sample_df.columns:
157
+ sample_df[col] = 'unknown' if col in cat_cols else 0
158
+
159
+ sample_df[cat_cols] = sample_df[cat_cols].astype(str).fillna('unknown')
160
+ X_cat = preprocessors['ohe'].transform(sample_df[cat_cols])
161
+
162
+ X_cont = preprocessors['imputer'].transform(sample_df[cont_cols])
163
+ X_cont = preprocessors['scaler'].transform(X_cont)
164
+
165
+ X_processed = np.concatenate([X_cat, X_cont], axis=1)
166
+ X_tensor = torch.tensor(X_processed, dtype=torch.float32).to(self.device)
167
+
168
+ model = self.models[base_prediction]
169
+ with torch.no_grad():
170
+ outputs = model(X_tensor)
171
+ probabilities = torch.softmax(outputs, dim=1)
172
+ _, predicted = torch.max(outputs, 1)
173
+
174
+ predicted_label = preprocessors['label_encoder'].inverse_transform([predicted.cpu().numpy()[0]])[0]
175
+ confidence = probabilities.max().item()
176
+
177
+ return predicted_label, confidence
178
+
179
+ def load_model_and_encoders():
180
+ label_encoder = joblib.load("Models/label_encoder.pkl")
181
+ ohe = joblib.load("Models/ohe_encoder.pkl")
182
+ imputer = joblib.load("Models/imputer.pkl")
183
+ scaler = joblib.load("Models/scaler.pkl")
184
+
185
+ checkpoint = torch.load("Models/tag_classifier_complete.pth", map_location=torch.device('cpu'))
186
+ model = ImprovedTagClassifier(
187
+ input_size=checkpoint['input_size'],
188
+ output_size=checkpoint['output_size']
189
+ )
190
+ model.load_state_dict(checkpoint['model_state_dict'])
191
+ model.eval()
192
+
193
+ multi_classifier = MultiLevelTagClassifier()
194
+ multi_classifier.load_models()
195
+
196
+ return model, label_encoder, ohe, imputer, scaler, multi_classifier
197
+
198
+ def find_nearest_text_node(node, text_nodes):
199
+ if not text_nodes:
200
+ return 9999999
201
+
202
+ node_data = node.get("node", {})
203
+ x = node_data.get("x", 0) + node_data.get("width", 0) / 2
204
+ y = node_data.get("y", 0) + node_data.get("height", 0) / 2
205
+
206
+ min_distance = float('inf')
207
+ for text_node in text_nodes:
208
+ tx, ty = text_node['x'], text_node['y']
209
+ distance = math.sqrt((x - tx)**2 + (y - ty)**2)
210
+ min_distance = min(min_distance, distance)
211
+
212
+ return min_distance
213
+
214
+ def extract_features(node, sibling_count=0, prev_sibling_tag=None, parent_height=0, parent_bg_color=None, text_nodes=None):
215
+ global body_width
216
+ global num_nodes
217
+ global num_chars
218
+
219
+ node_data = node.get("node", {})
220
+ node_type = str(node_data.get("type", ""))
221
+ text = node_data.get("characters", "")
222
+
223
+ children = node.get("children", [])
224
+ num_direct_children = len(children)
225
+
226
+ child_1_tag = None
227
+ child_2_tag = None
228
+ child_1_percent = 0
229
+ child_2_percent = 0
230
+
231
+ node_width = node_data.get("width", 0)
232
+ node_height = node_data.get("height", 0)
233
+ node_area = node_width * node_height
234
+
235
+ has_placeholder = 0
236
+ is_verb = 0
237
+ if num_direct_children > 0:
238
+ if len(children) >= 1:
239
+ child_1_tag = children[0].get("tag", "")
240
+ child_1_type = children[0].get("node",{}).get("type", "")
241
+ if child_1_type == "TEXT":
242
+ if is_verb == 0:
243
+ is_verb = verb_ratio(children[0].get("node", {}).get("characters", ""))
244
+ placeholder_fills = children[0].get("node", {}).get("fills", [])
245
+ fills = [fill for fill in placeholder_fills if fill and (color := fill.get("color")) and color.get("a", 1) > 0]
246
+ for fill in placeholder_fills:
247
+ if fill.get("type") == "SOLID" and "color" in fill:
248
+ r, g, b = (
249
+ int(fill["color"].get("r", 0) * 255),
250
+ int(fill["color"].get("g", 0) * 255),
251
+ int(fill["color"].get("b", 0) * 255),
252
+ )
253
+ if is_near_gray(r, g, b):
254
+ has_placeholder = 1
255
+ break
256
+ child_1_width = children[0].get("node", {}).get("width", 0)
257
+ child_1_height = children[0].get("node", {}).get("height", 0)
258
+ child_1_area = child_1_width * child_1_height
259
+ child_1_percent = (child_1_area / node_area) if node_area > 0 else 0
260
+
261
+ if len(children) >= 2:
262
+ child_2_tag = children[1].get("tag", "")
263
+ child_2_type = children[1].get("node",{}).get("type", "")
264
+ if child_2_type == "TEXT" and is_verb == 0:
265
+ is_verb = verb_ratio(children[1].get("node", {}).get("characters", ""))
266
+ child_2_width = children[1].get("node", {}).get("width", 0)
267
+ child_2_height = children[1].get("node", {}).get("height", 0)
268
+ child_2_area = child_2_width * child_2_height
269
+ child_2_percent = (child_2_area / node_area) if node_area > 0 else 0
270
+
271
+ def count_all_descendants(node):
272
+ count = 0
273
+ for child in node.get("children", []):
274
+ count += 1
275
+ count += count_all_descendants(child)
276
+ return count
277
+
278
+ def count_chars_to_end(node):
279
+ count = 0
280
+ for child in node.get("children", []):
281
+ node_data = child.get("node", {})
282
+ count += len(node_data.get("characters", ""))
283
+ count += count_chars_to_end(child)
284
+ return count
285
+
286
+ def get_center_of_weight(node):
287
+ parent_node_data = node.get("node", {})
288
+ parent_x_center = parent_node_data.get("x", 0) + parent_node_data.get("width", 0) / 2
289
+
290
+ total_area = 0
291
+ total = 0
292
+ for child in node.get("children", []):
293
+ child_node_data = child.get("node", {})
294
+ x = child_node_data.get("x", 0)
295
+ width = child_node_data.get("width", 0)
296
+ height = child_node_data.get("height", 0)
297
+ child_x_center = x + width / 2
298
+ area = width * height
299
+ total += area * child_x_center
300
+ total_area += area
301
+ weighted_x = total / total_area if total_area else parent_x_center
302
+ diff = abs(parent_x_center - weighted_x) / (parent_node_data.get("width", 0) if parent_node_data.get("width", 0) else 1)
303
+ return diff
304
+
305
+ num_children_to_end = count_all_descendants(node)
306
+ if not num_nodes or num_nodes == 0:
307
+ num_nodes = num_children_to_end
308
+ chars_count_to_end = count_chars_to_end(node)
309
+ if not num_chars or num_chars == 0:
310
+ num_chars = chars_count_to_end
311
+ bg_color = None
312
+
313
+ feature = {
314
+ "type": node_type,
315
+ "width": node_width/(body_width if body_width else 1),
316
+ "height": node_height/(parent_height if parent_height else node_height if node_height else 1),
317
+ "sibling_count": sibling_count,
318
+ "prev_sibling_html_tag": prev_sibling_tag if prev_sibling_tag else "",
319
+ "has_background_color": 0,
320
+ "border_radius": 0,
321
+ "aspect_ratio": node_width / node_height if node_height > 0 else 0,
322
+ "child_1_html_tag": child_1_tag,
323
+ "child_2_html_tag": child_2_tag,
324
+ "child_1_percentage_of_parent": child_1_percent,
325
+ "child_2_percentage_of_parent": child_2_percent,
326
+ "distinct_background": 0,
327
+ "center_of_weight_diff": get_center_of_weight(node),
328
+ "is_verb": is_verb,
329
+ "has_placeholder": has_placeholder
330
+ }
331
+
332
+ fills = node_data.get("fills", [])
333
+ fills = [fill for fill in fills if fill and (color := fill.get("color")) and color.get("a", 1) > 0]
334
+
335
+ for fill in fills:
336
+ if fill.get("type") == "SOLID" and "color" in fill:
337
+ r, g, b = (
338
+ int(fill["color"].get("r", 0) * 255),
339
+ int(fill["color"].get("g", 0) * 255),
340
+ int(fill["color"].get("b", 0) * 255),
341
+ )
342
+ feature["has_background_color"] = 1
343
+ bg_color = (r, g, b)
344
+ if parent_bg_color:
345
+ bg_difference = color_difference(bg_color, parent_bg_color)
346
+ if bg_difference > 0.25:
347
+ feature["distinct_background"] = 1
348
+ break
349
+
350
+ backgrounds = node_data.get("backgrounds", [])
351
+ for bg in backgrounds:
352
+ if bg.get("type") == "SOLID" and "color" in bg:
353
+ r, g, b = (
354
+ int(bg["color"].get("r", 0) * 255),
355
+ int(bg["color"].get("g", 0) * 255),
356
+ int(bg["color"].get("b", 0) * 255),
357
+ )
358
+ feature["has_background_color"] = 1
359
+ a = min(float(bg["color"].get("a", 1)), float(bg.get("opacity", 1)))
360
+ bg_color = (r*a, g*a, b*a)
361
+ if parent_bg_color:
362
+ bg_difference = color_difference(bg_color, parent_bg_color)
363
+ if bg_difference > 0.2:
364
+ feature["distinct_background"] = 1
365
+ break
366
+
367
+ br_top_left = node_data.get("topLeftRadius", 0)
368
+ br_top_right = node_data.get("topRightRadius", 0)
369
+ br_bottom_left = node_data.get("bottomLeftRadius", 0)
370
+ br_bottom_right = node_data.get("bottomRightRadius", 0)
371
+
372
+ if any([br_top_left, br_top_right, br_bottom_left, br_bottom_right]):
373
+ feature["border_radius"] = (br_top_left + br_top_right + br_bottom_left + br_bottom_right) / 4
374
+ if feature["border_radius"] >= 50:
375
+ feature["border_radius"] = 0
376
+
377
+ nearest_text_distance = find_nearest_text_node(node, text_nodes)
378
+ feature["nearest_text_node_dist"] = (nearest_text_distance+0.01) / (math.sqrt((node_width+0.001)* (node_height+0.001)) if math.sqrt((node_width+0.001)*(node_height+0.001)) else 1)
379
+
380
+ return feature
381
+
382
+ def predict_tag(node, sibling_count, prev_sibling_tag, parent_height, parent_bg_color, text_nodes, model, label_encoder, ohe, imputer, scaler, multi_classifier):
383
+ global body_width
384
+
385
+ if text_nodes is None:
386
+ def collect_text_nodes(node):
387
+ text_nodes_list = []
388
+ def has_meaningful_text(node_data):
389
+ return node_data.get('type', '') == "TEXT"
390
+
391
+ node_data = node.get("node", {})
392
+ if has_meaningful_text(node_data):
393
+ text_nodes_list.append({
394
+ 'x': node_data.get("x", 0) + node_data.get("width", 0) / 2,
395
+ 'y': node_data.get("y", 0) + node_data.get("height", 0) / 2
396
+ })
397
+
398
+ for child in node.get("children", []):
399
+ text_nodes_list.extend(collect_text_nodes(child))
400
+
401
+ return text_nodes_list
402
+
403
+ text_nodes = collect_text_nodes(node)
404
+
405
+ node_data = node.get("node", {})
406
+ figma_type = node_data.get("type", "")
407
+ node_height = node_data.get("height", 0)
408
+ if not body_width or (body_width and body_width == 0):
409
+ body_width = node_data.get("width", 0)
410
+
411
+ fills = node_data.get("fills", [])
412
+ fills = [fill for fill in fills if fill and (color := fill.get("color")) and color.get("a", 1) > 0]
413
+ has_background_color = False
414
+ bg_color = None
415
+ for fill in fills:
416
+ if fill.get("type") == "SOLID" and "color" in fill:
417
+ r, g, b = (
418
+ int(fill["color"].get("r", 0) * 255),
419
+ int(fill["color"].get("g", 0) * 255),
420
+ int(fill["color"].get("b", 0) * 255),
421
+ )
422
+ has_background_color = True
423
+ bg_color = (r, g, b)
424
+ break
425
+ backgrounds = node_data.get("backgrounds", [])
426
+ for bg in backgrounds:
427
+ if bg.get("type") == "SOLID" and "color" in bg:
428
+ r, g, b = (
429
+ int(bg["color"].get("r", 0) * 255),
430
+ int(bg["color"].get("g", 0) * 255),
431
+ int(bg["color"].get("b", 0) * 255),
432
+ )
433
+ has_background_color = True
434
+ bg_color = (r, g, b)
435
+ break
436
+
437
+ prev_sib_tag = None
438
+ for i, child in enumerate(node.get("children", [])):
439
+ predict_tag(child, len(node.get("children", []))-1, prev_sib_tag, node_height, bg_color if has_background_color and figma_type != "GROUP" else parent_bg_color, text_nodes, model, label_encoder, ohe, imputer, scaler, multi_classifier)
440
+ prev_sib_tag = child.get("tag", "UNK")
441
+
442
+ if figma_type == "GROUP":
443
+ node["tag"] = "DIV"
444
+ node["base_tag"] = "DIV" # Store base tag
445
+ elif figma_type == "TEXT":
446
+ node["tag"] = "P"
447
+ node["base_tag"] = "P"
448
+ elif figma_type == "SVG":
449
+ node["tag"] = "SVG"
450
+ node["base_tag"] = "SVG"
451
+ elif figma_type == "VECTOR":
452
+ node["tag"] = "ICON"
453
+ node["base_tag"] = "ICON"
454
+ elif figma_type == "LINE":
455
+ node["tag"] = "HR"
456
+ node["base_tag"] = "HR"
457
+ elif (fills := node_data.get("fills", [])) and any(fill.get("type") == "IMAGE" for fill in fills):
458
+ node["tag"] = "SVG"
459
+ node["base_tag"] = "SVG"
460
+ elif node.get("node", {}).get("width", 0) == node.get("node", {}).get("height", 0) and node.get("node", {}).get("width", 0) < 50:
461
+ strokes = node_data.get("strokes", [])
462
+ strokes = [stroke for stroke in strokes if stroke and (color := stroke.get("color")) and color.get("a", 1) > 0]
463
+ fills = node_data.get("fills", [])
464
+ fills = [fill for fill in fills if fill and (color := fill.get("color")) and color.get("a", 1) > 0]
465
+ has_solid_fill = any(fill.get("type") == "SOLID" for fill in fills)
466
+ stroke_color = strokes[0].get("color") if strokes else None
467
+ fill_color = fills[0].get("color") if fills else None
468
+ if not strokes or (stroke_color == fill_color):
469
+ node["tag"] = "LI"
470
+ node["base_tag"] = "LI"
471
+ elif has_solid_fill:
472
+ if node.get("node", {}).get("type", "RECTANGLE") == "RECTANGLE":
473
+ node["tag"] = "CHECKBOX"
474
+ node["base_tag"] = "CHECKBOX"
475
+ elif node.get("node", {}).get("type", "ELLIPSE") == "ELLIPSE":
476
+ node["tag"] = "RADIO"
477
+ node["base_tag"] = "RADIO"
478
+ elif node.get("name", "").startswith("ICON"):
479
+ node["tag"] = "ICON"
480
+ node["base_tag"] = "ICON"
481
+
482
+ if node.get("tag", "").upper() != "UNK":
483
+ return
484
+
485
+ feature = extract_features(
486
+ node,
487
+ sibling_count,
488
+ prev_sibling_tag,
489
+ parent_height,
490
+ parent_bg_color,
491
+ text_nodes
492
+ )
493
+
494
+ categorical_cols = ['type', 'prev_sibling_html_tag', 'child_1_html_tag', 'child_2_html_tag']
495
+ continuous_cols = [col for col in feature.keys() if col not in categorical_cols]
496
+
497
+ cat_data = [[feature[col] for col in categorical_cols]]
498
+ X_cat_df = pd.DataFrame(cat_data, columns=categorical_cols)
499
+ cat_encoded = ohe.transform(X_cat_df)
500
+
501
+ cont_data = [[feature.get(col, 0) for col in continuous_cols]]
502
+ X_df = pd.DataFrame(cont_data, columns=continuous_cols)
503
+ cont_imputed = imputer.transform(X_df)
504
+ cont_scaled = scaler.transform(cont_imputed)
505
+
506
+ X_processed = np.concatenate([cat_encoded, cont_scaled], axis=1)
507
+
508
+ with torch.no_grad():
509
+ X_tensor = torch.tensor(X_processed, dtype=torch.float32)
510
+ outputs = model(X_tensor)
511
+ probabilities = torch.softmax(outputs, dim=1)
512
+ _, predicted = torch.max(outputs, 1)
513
+ base_predicted_tag = label_encoder.inverse_transform(predicted)[0]
514
+ base_confidence = probabilities.max().item()
515
+
516
+ # Store base predicted tag
517
+ node["base_tag"] = base_predicted_tag
518
+
519
+ # Add parent_tag_html for sub-classifiers
520
+ feature['parent_tag_html'] = base_predicted_tag
521
+
522
+ # Hierarchical prediction in order: P, INPUT, DIV
523
+ predicted_tag = base_predicted_tag
524
+ confidence = base_confidence
525
+
526
+ for sub_classifier in ['P', 'INPUT', 'DIV']:
527
+ if base_predicted_tag == sub_classifier:
528
+ predicted_tag, confidence = multi_classifier.predict_hierarchical(feature, base_predicted_tag)
529
+ break
530
+
531
+ X_cat_df["predicted_tag"] = predicted_tag
532
+ X_full_df = pd.concat([X_cat_df, X_df], axis=1)
533
+ X_full_df["predicted_tag"] = predicted_tag
534
+ X_full_df["confidence"] = confidence
535
+ print(f"Predicted tag: {predicted_tag} (Confidence: {confidence:.4f})")
536
+
537
+ X_full_df.to_csv("features_with_prediction.csv", mode='a', index=False)
538
+
539
+ node["tag"] = predicted_tag
540
+
541
+ def post_process_tags(nodes):
542
+ global body_width
543
+
544
+ if not isinstance(nodes, dict):
545
+ raise ValueError("Expected a dict with 'children' key but got a different structure")
546
+
547
+ process_nodes(nodes)
548
+
549
+ return nodes
550
+
551
+ def process_nodes(node):
552
+ if not node or "children" not in node:
553
+ return
554
+
555
+ for child in node["children"]:
556
+ process_nodes(child)
557
+
558
+ children = node.get("children", [])
559
+ for i in range(len(children) - 1):
560
+ if (children[i].get("tag") == "P" and
561
+ children[i+1].get("tag") == "INPUT"):
562
+ children[i]["tag"] = "LABEL"
563
+ children[i]["base_tag"] = "P" # Ensure base_tag reflects original
564
+
565
+ for child in children:
566
+ if (child.get("tag") == "DIV" and
567
+ child.get("node", {}).get("x") == 0.0 and
568
+ child.get("node", {}).get("y") == 0.0 and
569
+ abs(child.get("node", {}).get("width", 0) - body_width) < 5
570
+ and child.get("node", {}).get("height", 0) < body_width / 10):
571
+ child["tag"] = "NAVBAR"
572
+
573
+ # for child in children:
574
+ # if (child.get("tag") == "DIV" and
575
+ # count_list_items(child) >= 2):
576
+ # child["tag"] = "UL"
577
+
578
+ # for child in children:
579
+ # if child.get("tag") == "DIV":
580
+ # form_elements = count_form_elements(child)
581
+ # if form_elements >= 2:
582
+ # child["tag"] = "FORM"
583
+
584
+ def count_form_elements(node):
585
+ count = 0
586
+ if not node or "children" not in node:
587
+ return count
588
+
589
+ for child in node.get("children", []):
590
+ if child.get("tag") == "FORM":
591
+ return 0
592
+ if child.get("tag") in ["INPUT", "BUTTON"]:
593
+ count += 1
594
+
595
+ for child in node.get("children", []):
596
+ count += count_form_elements(child)
597
+
598
+ return count
599
+
600
+ def count_list_items(node):
601
+ if not node or "children" not in node:
602
+ return 0
603
+ count = 0
604
+ for child in node.get("children", []):
605
+ if child.get("tag") == "LI":
606
+ count += 1
607
+ elif child.get("tag") != "UL":
608
+ count += sum(1 for grandchild in child.get("children", []) if grandchild.get("tag") == "LI")
609
+ return count
610
+
611
+ def generate_random_color():
612
+ r = random.randint(0, 255)
613
+ g = random.randint(0, 255)
614
+ b = random.randint(0, 255)
615
+ return f"rgba({r},{g},{b},0.3)"
616
+
617
+ def draw_tags_on_svg_file(data, svg_input_file, svg_output_file=None):
618
+ if svg_output_file is None:
619
+ base, ext = os.path.splitext(svg_input_file)
620
+ svg_output_file = f"{base}_tagged{ext}"
621
+
622
+ shutil.copy2(svg_input_file, svg_output_file)
623
+
624
+ parser = etree.XMLParser(remove_blank_text=True)
625
+ tree = etree.parse(svg_output_file, parser)
626
+ root = tree.getroot()
627
+
628
+ frame_width = root.get('width', str(data.get("node", {}).get("width", "1000"))).replace('px', '')
629
+ frame_height = root.get('height', str(data.get("node", {}).get("height", "1000"))).replace('px', '')
630
+
631
+ style_element = etree.SubElement(root, 'style')
632
+ style_element.text = """
633
+ .tag-box { stroke: #000000; stroke-width: 1; fill-opacity: 0.3; }
634
+ .tag-text { font-family: Arial; font-size: 10px; }
635
+ .tag-label { fill: white; stroke: #000000; stroke-width: 0.5; rx: 3; ry: 3; }
636
+ .changed-tag { fill: #ff0000; fill-opacity: 0.5; stroke: #ff0000; stroke-width: 2; }
637
+ """
638
+
639
+ tag_group = etree.SubElement(root, 'g', id="tag-annotations")
640
+
641
+ tag_colors = {}
642
+
643
+ def draw_element(element, parent_element):
644
+ if not element or "node" not in element:
645
+ return
646
+
647
+ tag = element.get("tag", "UNKNOWN")
648
+ base_tag = element.get("base_tag", tag) # Use tag if base_tag not set
649
+
650
+ if tag not in tag_colors:
651
+ tag_colors[tag] = generate_random_color()
652
+ color = tag_colors[tag]
653
+
654
+ node = element["node"]
655
+ x, y = node.get("x", 0), node.get("y", 0)
656
+ width, height = node.get("width", 50), node.get("height", 50)
657
+
658
+ group = etree.SubElement(parent_element, 'g')
659
+
660
+ # Highlight if tag changed by sub-model
661
+ is_changed = tag != base_tag
662
+ rect_class = "changed-tag" if is_changed else "tag-box"
663
+
664
+ rect = etree.SubElement(group, 'rect', {
665
+ "x": str(x),
666
+ "y": str(y),
667
+ "width": str(width),
668
+ "height": str(height),
669
+ "class": rect_class,
670
+ "fill": color,
671
+ "stroke": "black" if not is_changed else "#ff0000",
672
+ "stroke-width": "1" if not is_changed else "2"
673
+ })
674
+
675
+ label_width = max(80, len(tag) * 7 + (len(f"{base_tag} -> ") if is_changed else 0))
676
+ label_height = 40 if not is_changed else 52 # Extra height for changed tags
677
+
678
+ label_bg = etree.SubElement(group, 'rect', {
679
+ "x": str(x),
680
+ "y": str(y),
681
+ "width": str(label_width),
682
+ "height": str(label_height),
683
+ "rx": "3",
684
+ "ry": "3",
685
+ "fill": "white",
686
+ "fill-opacity": "0.7",
687
+ "stroke": "black",
688
+ "stroke-width": "0.5"
689
+ })
690
+
691
+ # Show base tag if changed
692
+ if is_changed:
693
+ etree.SubElement(group, 'text', {
694
+ "x": str(x + 3),
695
+ "y": str(y + 12),
696
+ "class": "tag-text",
697
+ "fill": "black"
698
+ }).text = f"{base_tag} -> {tag}"
699
+ else:
700
+ etree.SubElement(group, 'text', {
701
+ "x": str(x + 3),
702
+ "y": str(y + 12),
703
+ "class": "tag-text",
704
+ "fill": "black"
705
+ }).text = tag
706
+
707
+ etree.SubElement(group, 'text', {
708
+ "x": str(x + 3),
709
+ "y": str(y + 24),
710
+ "class": "tag-text",
711
+ "fill": "black"
712
+ }).text = f"x:{x:.1f}, y:{y:.1f}"
713
+
714
+ etree.SubElement(group, 'text', {
715
+ "x": str(x + 3),
716
+ "y": str(y + 36),
717
+ "class": "tag-text",
718
+ "fill": "black"
719
+ }).text = f"w:{width:.1f}, h:{height:.1f}"
720
+
721
+ for child in element.get("children", []):
722
+ if child.get("tag") != "P":
723
+ draw_element(child, group)
724
+
725
+ draw_element(data, tag_group)
726
+
727
+ tree.write(svg_output_file, pretty_print=True, encoding='utf-8', xml_declaration=True)
728
+ print(f"SVG visualization created at {svg_output_file}")
729
+
730
+ webbrowser.open(f"file://{os.path.abspath(svg_output_file)}")
731
+
732
+ def process_figma_json(input_file, output_file, svg_file=None):
733
+ model, label_encoder, ohe, imputer, scaler, multi_classifier = load_model_and_encoders()
734
+
735
+ with open(input_file, 'r', encoding='utf-8') as f:
736
+ data = json.load(f)
737
+
738
+ if os.path.exists('features_with_prediction.csv'):
739
+ os.remove('features_with_prediction.csv')
740
+
741
+ predict_tag(data, 0, None, None, None, None, model, label_encoder, ohe, imputer, scaler, multi_classifier)
742
+
743
+ data = post_process_tags(data)
744
+
745
+ if svg_file:
746
+ svg_output = os.path.splitext(svg_file)[0] + "_tagged.svg"
747
+ draw_tags_on_svg_file(data, svg_file, svg_output)
748
+
749
+ with open(output_file, 'w', encoding='utf-8') as f:
750
+ json.dump(data, f, indent=2)
751
+
752
+ print(f"Processed {input_file}. Output saved to {output_file}")
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ flask
2
+ torch
3
+ joblib
4
+ pandas
5
+ numpy
6
+ scikit-learn
7
+ spacy
8
+ lxml