Christopher Román Jaimes commited on
Commit
1ef8976
·
1 Parent(s): 518184e

fix: add cleaning post inference.

Browse files
Files changed (1) hide show
  1. app.py +232 -8
app.py CHANGED
@@ -1,14 +1,225 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
2
  from gliner import GLiNER
3
 
 
4
  model = GLiNER.from_pretrained("chris32/gliner_multi_pii_real_state-v2")
5
  model.eval()
6
 
7
- #text = """
8
- #Casa en venta Valle de San Ángel, San Pedro Garza García**Para remodelar o demoler Casa de 1220 m2 de terreno y 1400 m2 de construcciónCasa de 3 niveles-Sala-Comedor-Cocina-Estancia-Preparación para alberca-Cochera para 3 autos techada -4 recamaras -Lavandería"Esta es una de las varias opciones que tenemos para ti. Somos una agencia de bienes raíces especializada en la venta y renta de vivienda residencial, te brindamos un servicio personalizado y de alta calidad. Si necesitas ayuda para comprar o rentar, contáctanos y uno de nuestros asesores te atenderá.
9
- #"""
10
- #for entity in entities:
11
- # print(entity["text"], "=>", entity["label"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def generate_answer(text):
14
  labels = [
@@ -24,10 +235,23 @@ def generate_answer(text):
24
  'NOMBRE_CONDOMINIO',
25
  'AÑO_REMODELACIÓN'
26
  ]
 
27
  entities = model.predict_entities(text, labels, threshold=0.4)
28
- result_dict = entities
29
-
30
- return result_dict
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  # Cambiar a entrada de texto
33
  #text_input = gr.inputs.Textbox(lines=15, label="Input Text")
 
1
+ # Datetime
2
+ import datetime
3
+ # Manipulate
4
+ import os
5
+ import re
6
+ import json
7
+ import numpy as np
8
+ import pandas as pd
9
+ # App
10
  import gradio as gr
11
+ # GLiNER Model
12
  from gliner import GLiNER
13
 
14
+ # Load Model
15
  model = GLiNER.from_pretrained("chris32/gliner_multi_pii_real_state-v2")
16
  model.eval()
17
 
18
+ # Global Variables: For Post Cleaning Inferences
19
+ YEAR_OF_REMODELING_LIMIT = 100
20
+ CURRENT_YEAR = int(datetime.date.today().year)
21
+ SCORE_LIMIT_SIMILARITY_NAMES = 70
22
+
23
+ def format_gliner_predictions(prediction):
24
+ if len(prediction) > 0:
25
+ # Select the Entity value with the Greater Score for each Entity Name
26
+ prediction_df = pd.DataFrame(prediction)\
27
+ .sort_values("score", ascending = False)\
28
+ .drop_duplicates(subset = "label", keep = "first")
29
+
30
+ # Add Columns Label for Text and Probability
31
+ prediction_df["label_text"] = prediction_df["label"].apply(lambda x: f"pred_{x}")
32
+ prediction_df["label_prob"] = prediction_df["label"].apply(lambda x: f"prob_{x}")
33
+
34
+ # Format Predictions
35
+ entities = prediction_df.set_index("label_text")["text"].to_dict()
36
+ entities_probs = prediction_df.set_index("label_prob")["score"].to_dict()
37
+ predictions_formatted = {**entities, **entities_probs}
38
+
39
+ return predictions_formatted
40
+ else:
41
+ return dict()
42
+
43
+ def clean_prediction(row, feature_name, threshols_dict, clean_functions_dict):
44
+ # Prediction and Probability
45
+ prediction = row[f"pred_{feature_name}"]
46
+ prob = row[f"prob_{feature_name}"]
47
+
48
+ # Clean and Return Prediction only if the Threshold is lower.
49
+ if prob > threshols_dict[feature_name]:
50
+ clean_function = clean_functions_dict[feature_name]
51
+ prediction_clean = clean_function(prediction)
52
+ return prediction_clean
53
+ else:
54
+ return None
55
+
56
+ surfaces_words_to_omit = ["ha", "hect", "lts", "litros", "mil"]
57
+ tower_name_key_words_to_keep = ["torr", "towe"]
58
+
59
+ def has_number(string):
60
+ return bool(re.search(r'\d', string))
61
+
62
+ def contains_multiplication(string):
63
+ # Regular expression pattern to match a multiplication operation
64
+ pattern = r'\b([\d,]+(?:\.\d+)?)\s*(?:\w+\s*)*[xX]\s*([\d,]+(?:\.\d+)?)\s*(?:\w+\s*)*\b'
65
+
66
+ # Search for the pattern in the string
67
+ match = re.search(pattern, string)
68
+
69
+ # If a match is found, return True, otherwise False
70
+ if match:
71
+ return True
72
+ else:
73
+ return False
74
+
75
+ def extract_first_number_from_string(text):
76
+ if isinstance(text, str):
77
+ match = re.search(r'\b\d*\.?\d+\b|\d*\.?\d+', text)
78
+ if match:
79
+ start_pos = match.start()
80
+ end_pos = match.end()
81
+ number = int(float(match.group()))
82
+ return number, start_pos, end_pos
83
+ else:
84
+ return None, None, None
85
+ else:
86
+ return None, None, None
87
+
88
+ def get_character(string, index):
89
+ if len(string) > index:
90
+ return string[index]
91
+ else:
92
+ return None
93
+
94
+ def find_valid_comma_separated_number(string):
95
+ # This regular expression matches strings starting with 1 to 3 digits followed by a comma and 3 digits. It ensures no other digits or commas follow or the string ends.
96
+ match = re.match(r'^(\d{1,3},\d{3})(?:[^0-9,]|$)', string)
97
+ if match:
98
+ valid_number = int(match.group(1).replace(",", ""))
99
+ return valid_number
100
+ else:
101
+ return None
102
+
103
+ def extract_surface_from_string(string: str) -> int:
104
+ if isinstance(string, str):
105
+ # 1. Validate if it Contains a Number
106
+ if not(has_number(string)): return None
107
+
108
+ # 2. Validate if it No Contains Multiplication
109
+ if contains_multiplication(string): return None
110
+
111
+ # 3. Validate if it No Contains Words to Omit
112
+ if any([word in string.lower() for word in surfaces_words_to_omit]): return None
113
+
114
+ # 4. Extract First Number
115
+ number, start_pos, end_pos = extract_first_number_from_string(string)
116
+
117
+ # 5. Extract Valid Comma Separated Number
118
+ if isinstance(number, int):
119
+ if get_character(string, end_pos) == ",":
120
+ valid_comma_separated_number = find_valid_comma_separated_number(string[start_pos: -1])
121
+ return valid_comma_separated_number
122
+ else:
123
+ return number
124
+ else:
125
+ return None
126
+ else:
127
+ return None
128
+
129
+ def clean_prediction(row, feature_name, threshols_dict, clean_functions_dict):
130
+ # Prediction and Probability
131
+ prediction = row[f"pred_{feature_name}"]
132
+ prob = row[f"prob_{feature_name}"]
133
+
134
+ # Clean and Return Prediction only if the Threshold is lower.
135
+ if prob > threshols_dict[feature_name]:
136
+ clean_function = clean_functions_dict[feature_name]
137
+ prediction_clean = clean_function(prediction)
138
+ return prediction_clean
139
+ else:
140
+ return None
141
+
142
+ def calculate_metrics(X, feature_name, data_type):
143
+ true_positives = 0
144
+ true_negatives = 0
145
+ false_positives = 0
146
+ false_negatives = 0
147
+ for pred, true in zip(X[f"clean_pred_{feature_name}"], X[f"clean_{feature_name}"]):
148
+ if isinstance(pred, data_type):
149
+ if isinstance(true, data_type):
150
+ if pred == true:
151
+ true_positives += 1
152
+ else:
153
+ false_positives += 1
154
+ else:
155
+ false_positives += 1
156
+ else:
157
+ if isinstance(true, data_type):
158
+ false_negatives += 1
159
+ else:
160
+ true_negatives += 1
161
+
162
+ # Calculate Metrics
163
+ precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) != 0 else np.nan
164
+ recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) != 0 else np.nan
165
+ f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) != 0 else np.nan
166
+ metrics = {
167
+ "precision": precision,
168
+ "recall": recall,
169
+ "f1_score": f1_score,
170
+ }
171
+
172
+ return metrics
173
+
174
+ def extract_remodeling_year_from_string(string):
175
+ if isinstance(string, str):
176
+ # 1. Detect 4-digit year
177
+ match = re.search(r'\b\d{4}\b', string)
178
+ if match:
179
+ year_predicted = int(match.group())
180
+ else:
181
+ # 2. Detect quantity of years followed by "year", "years", "anio", "año", or "an"
182
+ match = re.search(r'(\d+) (year|years|anio|año|an|añ)', string.lower(), re.IGNORECASE)
183
+ if match:
184
+ past_years_predicted = int(match.group(1))
185
+ year_predicted = CURRENT_YEAR - past_years_predicted
186
+ else:
187
+ return None
188
+
189
+ # 3. Detect if it is a valid year
190
+ is_valid_year = (year_predicted <= CURRENT_YEAR) and (YEAR_OF_REMODELING_LIMIT > CURRENT_YEAR - year_predicted)
191
+ return year_predicted if is_valid_year else None
192
+
193
+ return None
194
+
195
+ # Cleaning
196
+ clean_functions_dict = {
197
+ "SUPERFICIE_TERRAZA": extract_surface_from_string,
198
+ "SUPERFICIE_JARDIN": extract_surface_from_string,
199
+ "SUPERFICIE_TERRENO": extract_surface_from_string,
200
+ "SUPERFICIE_HABITABLE": extract_surface_from_string,
201
+ "SUPERFICIE_BALCON": extract_surface_from_string,
202
+ "AÑO_REMODELACIÓN": extract_remodeling_year_from_string,
203
+ "NOMBRE_COMPLETO_ARQUITECTO": lambda x: x,
204
+ 'NOMBRE_CLUB_GOLF': lambda x: x,
205
+ 'NOMBRE_TORRE': lambda x: x,
206
+ 'NOMBRE_CONDOMINIO': lambda x: x,
207
+ 'NOMBRE_DESARROLLO': lambda x: x,
208
+ }
209
+
210
+ threshols_dict = {
211
+ "SUPERFICIE_TERRAZA": 0.9,
212
+ "SUPERFICIE_JARDIN": 0.9,
213
+ "SUPERFICIE_TERRENO": 0.9,
214
+ "SUPERFICIE_HABITABLE": 0.9,
215
+ "SUPERFICIE_BALCON": 0.9,
216
+ "AÑO_REMODELACIÓN": 0.9,
217
+ "NOMBRE_COMPLETO_ARQUITECTO": 0.9,
218
+ 'NOMBRE_CLUB_GOLF': 0.9,
219
+ 'NOMBRE_TORRE': 0.9,
220
+ 'NOMBRE_CONDOMINIO': 0.9,
221
+ 'NOMBRE_DESARROLLO': 0.9,
222
+ }
223
 
224
  def generate_answer(text):
225
  labels = [
 
235
  'NOMBRE_CONDOMINIO',
236
  'AÑO_REMODELACIÓN'
237
  ]
238
+ # Inference
239
  entities = model.predict_entities(text, labels, threshold=0.4)
240
+
241
+ # Format Prediction Entities
242
+ entities_formatted = format_gliner_predictions(entities)
243
+
244
+ # Clean Entities
245
+ entities_names = list({c.replace("pred_", "").replace("prob_", "") for c in list(entities_formatted.keys())})
246
+ entities_cleaned = dict()
247
+ for feature_name in entities_names:
248
+ entity_prediction_cleaned = clean_prediction(entities_formatted, feature_name, threshols_dict, clean_functions_dict)
249
+ if isinstance(entity_prediction_cleaned, str) or isinstance(entity_prediction_cleaned, int):
250
+ entities_cleaned[feature_name] = entity_prediction_cleaned
251
+
252
+ result_json = json.dumps(entities_cleaned, indent = 4, ensure_ascii = False)
253
+
254
+ return result_json
255
 
256
  # Cambiar a entrada de texto
257
  #text_input = gr.inputs.Textbox(lines=15, label="Input Text")