alvarogalan17 commited on
Commit
a4e3df2
·
verified ·
1 Parent(s): a6eb432

subida buiena

Browse files
Files changed (32) hide show
  1. .gitattributes +1 -0
  2. app2/app1/__pycache__/altura_techo_estimator.cpython-310.pyc +0 -0
  3. app2/app1/__pycache__/altura_techo_estimator.cpython-312.pyc +0 -0
  4. app2/app1/__pycache__/detectar_aire_acondicionado.cpython-310.pyc +0 -0
  5. app2/app1/__pycache__/detectar_aire_acondicionado.cpython-312.pyc +0 -0
  6. app2/app1/__pycache__/feature_engineering.cpython-310.pyc +0 -0
  7. app2/app1/__pycache__/feature_engineering.cpython-312.pyc +0 -0
  8. app2/app1/__pycache__/input_handler.cpython-310.pyc +0 -0
  9. app2/app1/__pycache__/input_handler.cpython-312.pyc +0 -0
  10. app2/app1/__pycache__/predictor.cpython-310.pyc +0 -0
  11. app2/app1/__pycache__/predictor.cpython-312.pyc +0 -0
  12. app2/app1/__pycache__/preprocessing.cpython-310.pyc +0 -0
  13. app2/app1/__pycache__/preprocessing.cpython-312.pyc +0 -0
  14. app2/app1/__pycache__/reformado_classifier.cpython-310.pyc +0 -0
  15. app2/app1/__pycache__/reformado_classifier.cpython-312.pyc +0 -0
  16. app2/app1/altura_techo_estimator.py +441 -0
  17. app2/app1/app.py +235 -0
  18. app2/app1/cabecera.png +3 -0
  19. app2/app1/detectar_aire_acondicionado.py +155 -0
  20. app2/app1/feature_engineering.py +36 -0
  21. app2/app1/input_handler.py +69 -0
  22. app2/app1/logs.log +0 -0
  23. app2/app1/modelos/datos_imagenes_con_predicciones_y_aire.csv +0 -0
  24. app2/app1/modelos/efficientnet_reformado.pth +3 -0
  25. app2/app1/modelos/modelo_arganzuela.pkl +3 -0
  26. app2/app1/modelos/modelo_centro.pkl +3 -0
  27. app2/app1/modelos/modelo_chamberi.pkl +3 -0
  28. app2/app1/modelos/modelo_retiro.pkl +3 -0
  29. app2/app1/predictor.py +64 -0
  30. app2/app1/preprocessing.py +44 -0
  31. app2/app1/reformado_classifier.py +161 -0
  32. app2/app1/requirements.txt +11 -0
.gitattributes CHANGED
@@ -34,3 +34,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  app[[:space:]](2)[[:space:]](1)/app[[:space:]](2)/cabecera.png filter=lfs diff=lfs merge=lfs -text
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  app[[:space:]](2)[[:space:]](1)/app[[:space:]](2)/cabecera.png filter=lfs diff=lfs merge=lfs -text
37
+ app2/app1/cabecera.png filter=lfs diff=lfs merge=lfs -text
app2/app1/__pycache__/altura_techo_estimator.cpython-310.pyc ADDED
Binary file (9.59 kB). View file
 
app2/app1/__pycache__/altura_techo_estimator.cpython-312.pyc ADDED
Binary file (12.3 kB). View file
 
app2/app1/__pycache__/detectar_aire_acondicionado.cpython-310.pyc ADDED
Binary file (3.53 kB). View file
 
app2/app1/__pycache__/detectar_aire_acondicionado.cpython-312.pyc ADDED
Binary file (3.07 kB). View file
 
app2/app1/__pycache__/feature_engineering.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
app2/app1/__pycache__/feature_engineering.cpython-312.pyc ADDED
Binary file (1.68 kB). View file
 
app2/app1/__pycache__/input_handler.cpython-310.pyc ADDED
Binary file (2.44 kB). View file
 
app2/app1/__pycache__/input_handler.cpython-312.pyc ADDED
Binary file (2.98 kB). View file
 
app2/app1/__pycache__/predictor.cpython-310.pyc ADDED
Binary file (1.85 kB). View file
 
app2/app1/__pycache__/predictor.cpython-312.pyc ADDED
Binary file (2.75 kB). View file
 
app2/app1/__pycache__/preprocessing.cpython-310.pyc ADDED
Binary file (1.27 kB). View file
 
app2/app1/__pycache__/preprocessing.cpython-312.pyc ADDED
Binary file (1.61 kB). View file
 
app2/app1/__pycache__/reformado_classifier.cpython-310.pyc ADDED
Binary file (3.87 kB). View file
 
app2/app1/__pycache__/reformado_classifier.cpython-312.pyc ADDED
Binary file (3.76 kB). View file
 
app2/app1/altura_techo_estimator.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ class SimpleCeilingHeightEstimator:
4
+ def __init__(self):
5
+ # Rangos típicos de altura de techo en Madrid
6
+ self.height_ranges = {
7
+ 'low': (2.3, 2.6), # Pisos modernos/reformados
8
+ 'medium': (2.6, 3.0), # Estándar
9
+ 'high': (3.0, 3.8), # Edificios clásicos con techos altos
10
+ 'very_high': (3.8, 4.5) # Edificios señoriales
11
+ }
12
+
13
+ def analyze_image_characteristics(self, image):
14
+ """Analiza características visuales básicas de la imagen"""
15
+ height, width, _ = image.shape
16
+
17
+ # Convertir a escala de grises para análisis
18
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
19
+
20
+ # 1. RATIO DE ASPECTO DE LA IMAGEN
21
+ aspect_ratio = height / width
22
+
23
+ # 2. DETECTAR LÍNEAS VERTICALES PROMINENTES (esquinas, marcos)
24
+ edges = cv2.Canny(gray, 50, 150, apertureSize=3)
25
+ lines = cv2.HoughLines(edges, 1, np.pi/180, threshold=int(height*0.3))
26
+
27
+ vertical_lines = 0
28
+ if lines is not None:
29
+ for line in lines:
30
+ _, theta = line[0]
31
+ # Contar líneas verticales
32
+ if abs(theta) < 0.3 or abs(theta - np.pi) < 0.3:
33
+ vertical_lines += 1
34
+
35
+ # 3. ANALIZAR DISTRIBUCIÓN DE INTENSIDAD VERTICAL
36
+ # Dividir imagen en franjas horizontales
37
+ strip_height = height // 10
38
+ brightness_profile = []
39
+
40
+ for i in range(10):
41
+ start_y = i * strip_height
42
+ end_y = min((i + 1) * strip_height, height)
43
+ strip = gray[start_y:end_y, :]
44
+ avg_brightness = np.mean(strip)
45
+ brightness_profile.append(avg_brightness)
46
+
47
+ # 4. DETECTAR CARACTERÍSTICAS ARQUITECTÓNICAS
48
+ # Buscar patrones que indiquen techos altos vs bajos
49
+
50
+ # Variación de brillo en la parte superior (posible techo decorativo)
51
+ upper_variation = np.std(brightness_profile[:3])
52
+
53
+ # Contraste general de la imagen
54
+ overall_contrast = np.std(gray)
55
+
56
+ # Presencia de elementos en la parte superior de la imagen
57
+ upper_third = gray[:height//3, :]
58
+ upper_edges = cv2.Canny(upper_third, 50, 150)
59
+ upper_edge_density = np.sum(upper_edges > 0) / upper_third.size
60
+
61
+ return {
62
+ 'aspect_ratio': aspect_ratio,
63
+ 'vertical_lines': vertical_lines,
64
+ 'brightness_profile': brightness_profile,
65
+ 'upper_variation': upper_variation,
66
+ 'overall_contrast': overall_contrast,
67
+ 'upper_edge_density': upper_edge_density,
68
+ 'image_height': height,
69
+ 'image_width': width
70
+ }
71
+
72
+ def classify_ceiling_type(self, characteristics):
73
+ """Clasifica el tipo de techo basándose en características visuales"""
74
+
75
+ # Inicializar puntuaciones para cada tipo
76
+ scores = {
77
+ 'low': 0,
78
+ 'medium': 0,
79
+ 'high': 0,
80
+ 'very_high': 0
81
+ }
82
+
83
+ # FACTOR 1: Ratio de aspecto de la imagen
84
+ aspect_ratio = characteristics['aspect_ratio']
85
+ if aspect_ratio < 0.6: # Imagen muy ancha = vista panorámica = techo bajo
86
+ scores['low'] += 2
87
+ scores['medium'] += 1
88
+ elif aspect_ratio < 0.8: # Imagen moderadamente ancha
89
+ scores['medium'] += 2
90
+ scores['low'] += 1
91
+ elif aspect_ratio < 1.2: # Imagen cuadrada
92
+ scores['medium'] += 2
93
+ scores['high'] += 1
94
+ else: # Imagen alta = posible techo alto
95
+ scores['high'] += 2
96
+ scores['very_high'] += 1
97
+ if aspect_ratio > 1.5:
98
+ scores['very_high'] += 1
99
+
100
+ # FACTOR 2: Líneas verticales (elementos arquitectónicos)
101
+ vertical_lines = characteristics['vertical_lines']
102
+ if vertical_lines > 8: # Muchas líneas = arquitectura compleja = techo alto
103
+ scores['high'] += 2
104
+ scores['very_high'] += 1
105
+ elif vertical_lines > 4:
106
+ scores['medium'] += 1
107
+ scores['high'] += 1
108
+ else:
109
+ scores['low'] += 1
110
+ scores['medium'] += 1
111
+
112
+ # FACTOR 3: Variación en la parte superior (molduras, decoración)
113
+ upper_variation = characteristics['upper_variation']
114
+ if upper_variation > 30: # Mucha variación = decoración = techo alto
115
+ scores['high'] += 2
116
+ scores['very_high'] += 1
117
+ elif upper_variation > 15:
118
+ scores['medium'] += 1
119
+ scores['high'] += 1
120
+ else:
121
+ scores['low'] += 1
122
+ scores['medium'] += 1
123
+
124
+ # FACTOR 4: Densidad de bordes en parte superior
125
+ upper_edge_density = characteristics['upper_edge_density']
126
+ if upper_edge_density > 0.1: # Muchos detalles arriba = techo decorado
127
+ scores['high'] += 1
128
+ scores['very_high'] += 1
129
+ elif upper_edge_density > 0.05:
130
+ scores['medium'] += 1
131
+ else:
132
+ scores['low'] += 1
133
+
134
+ # FACTOR 5: Contraste general
135
+ overall_contrast = characteristics['overall_contrast']
136
+ if overall_contrast > 60: # Alto contraste = espacios amplios = techos altos
137
+ scores['high'] += 1
138
+ scores['very_high'] += 1
139
+ elif overall_contrast > 40:
140
+ scores['medium'] += 1
141
+ else:
142
+ scores['low'] += 1
143
+
144
+ # Encontrar la categoría con mayor puntuación
145
+ best_category = max(scores.keys(), key=lambda k: scores[k])
146
+ confidence = scores[best_category] / sum(scores.values())
147
+
148
+ return best_category, confidence, scores
149
+
150
+ def estimate_height_from_category(self, category, confidence):
151
+ """Convierte la categoría en una altura específica"""
152
+ range_min, range_max = self.height_ranges[category]
153
+
154
+ # Usar un valor dentro del rango, ajustado por confianza
155
+ if confidence > 0.7:
156
+ # Alta confianza: usar valor medio del rango
157
+ height = (range_min + range_max) / 2
158
+ elif confidence > 0.5:
159
+ # Confianza media: tender hacia el centro general (2.7m)
160
+ height = (range_min + range_max) / 2
161
+ height = height * 0.7 + 2.7 * 0.3 # Mezclar con valor conservador
162
+ else:
163
+ # Baja confianza: usar valor conservador
164
+ height = 2.7
165
+
166
+ # Añadir pequeña variación aleatoria para evitar valores idénticos
167
+ height += np.random.normal(0, 0.05) # ±5cm de variación
168
+
169
+ return max(2.2, min(4.5, height)) # Limitar entre 2.2 y 4.5m
170
+
171
+ def analyze_single_image(self, image_path):
172
+ """Analiza una sola imagen"""
173
+ try:
174
+ # Cargar imagen
175
+ if isinstance(image_path, str):
176
+ image = cv2.imread(image_path)
177
+ if image is None:
178
+ raise ValueError(f"No se pudo cargar la imagen: {image_path}")
179
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
180
+ else:
181
+ image = image_path
182
+
183
+ # Analizar características
184
+ characteristics = self.analyze_image_characteristics(image)
185
+
186
+ # Clasificar tipo de techo
187
+ category, confidence, scores = self.classify_ceiling_type(characteristics)
188
+
189
+ # Estimar altura
190
+ estimated_height = self.estimate_height_from_category(category, confidence)
191
+
192
+ return {
193
+ 'estimated_height': round(estimated_height, 2),
194
+ 'category': category,
195
+ 'confidence': round(confidence, 2),
196
+ 'scores': scores,
197
+ 'characteristics': characteristics
198
+ }
199
+
200
+ except Exception as e:
201
+ print(f"Error analizando imagen {image_path}: {e}")
202
+ return {
203
+ 'estimated_height': 2.7, # Valor por defecto
204
+ 'category': 'medium',
205
+ 'confidence': 0.2,
206
+ 'error': str(e)
207
+ }
208
+
209
+ def analyze_property_images(self, image_folder, property_id):
210
+ """Analiza todas las imágenes de una propiedad"""
211
+ try:
212
+ # Buscar imágenes de la propiedad
213
+ all_files = os.listdir(image_folder)
214
+ property_files = [f for f in all_files if f.startswith(f'foto_{property_id}_') and f.lower().endswith('.webp')]
215
+
216
+ if not property_files:
217
+ return {
218
+ 'property_id': property_id,
219
+ 'estimated_height': 2.7,
220
+ 'confidence': 0.2,
221
+ 'images_analyzed': 0,
222
+ 'method': 'no_images_found'
223
+ }
224
+
225
+ # Analizar cada imagen
226
+ results = []
227
+ for filename in property_files:
228
+ image_path = os.path.join(image_folder, filename)
229
+ result = self.analyze_single_image(image_path)
230
+ result['filename'] = filename
231
+ results.append(result)
232
+
233
+ # Combinar resultados
234
+ valid_results = [r for r in results if 'error' not in r]
235
+
236
+ if not valid_results:
237
+ return {
238
+ 'property_id': property_id,
239
+ 'estimated_height': 2.7,
240
+ 'confidence': 0.2,
241
+ 'images_analyzed': len(results),
242
+ 'method': 'all_errors'
243
+ }
244
+
245
+ # Calcular estadísticas
246
+ heights = [r['estimated_height'] for r in valid_results]
247
+ confidences = [r['confidence'] for r in valid_results]
248
+ categories = [r['category'] for r in valid_results]
249
+
250
+ # Altura final: mediana (más robusta que media)
251
+ final_height = np.median(heights)
252
+
253
+ # Confianza final: promedio ponderado
254
+ final_confidence = np.mean(confidences)
255
+
256
+ # Ajustar confianza según consistencia
257
+ height_std = np.std(heights)
258
+ if height_std < 0.2: # Muy consistente
259
+ final_confidence = min(0.9, final_confidence + 0.2)
260
+ elif height_std < 0.4: # Razonablemente consistente
261
+ final_confidence = final_confidence
262
+ else: # Inconsistente
263
+ final_confidence = max(0.3, final_confidence - 0.2)
264
+
265
+ # Categoría más común
266
+ most_common_category = max(set(categories), key=categories.count)
267
+
268
+ return {
269
+ 'property_id': property_id,
270
+ 'estimated_height': round(final_height, 2),
271
+ 'confidence': round(final_confidence, 2),
272
+ 'images_analyzed': len(valid_results),
273
+ 'height_std': round(height_std, 2),
274
+ 'most_common_category': most_common_category,
275
+ 'method': 'multi_image_median',
276
+ 'individual_results': results
277
+ }
278
+
279
+ except Exception as e:
280
+ print(f"Error procesando propiedad {property_id}: {e}")
281
+ return {
282
+ 'property_id': property_id,
283
+ 'estimated_height': 2.7,
284
+ 'confidence': 0.2,
285
+ 'images_analyzed': 0,
286
+ 'method': 'error',
287
+ 'error': str(e)
288
+ }
289
+
290
+ import numpy as np
291
+ import cv2
292
+ from PIL import Image
293
+ from collections import Counter
294
+
295
+ def bytes_to_image(bytes_img):
296
+ # Convierte bytes a array numpy para OpenCV
297
+ nparr = np.frombuffer(bytes_img, np.uint8)
298
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # BGR
299
+ if img is not None:
300
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convertir a RGB
301
+ return img
302
+
303
+ def estimate_ceiling_height(image_list):
304
+ logs = []
305
+ def log(msg):
306
+ logs.append(msg)
307
+
308
+ #log("Iniciando estimación de altura de techo...")
309
+ st.markdown(
310
+ f"""
311
+ <div style="
312
+ font-family: Sans, serif;
313
+ font-size: 13px;
314
+ color: #0a2640;
315
+ text-align: center;
316
+ border: 2px solid #bbb;
317
+ padding: 5px 8px;
318
+ border-radius: 3px;
319
+ max-width: 450px;
320
+ margin: 10px 0;
321
+ margin-left: auto;
322
+ margin-right: auto;
323
+ ">
324
+ Iniciando estimación de altura de techo...
325
+ </div>
326
+ """,
327
+ unsafe_allow_html=True
328
+ )
329
+
330
+ if not image_list:
331
+ #log("⚠️ No hay imágenes para analizar. Retornando valor por defecto 2.7")
332
+ st.markdown(
333
+ f"""
334
+ <div style="
335
+ font-family: Sans, serif;
336
+ font-size: 13px;
337
+ color: #0a2640;
338
+ text-align: center;
339
+ border: 2px solid #bbb;
340
+ padding: 5px 8px;
341
+ border-radius: 3px;
342
+ max-width: 450px;
343
+ margin: 10px 0;
344
+ margin-left: auto;
345
+ margin-right: auto;
346
+ ">
347
+ ⚠️ No hay imágenes para analizar. Retornando valor por defecto 2.7
348
+ </div>
349
+ """,
350
+ unsafe_allow_html=True
351
+ )
352
+ return 2.7, logs
353
+
354
+ #log(f" Número de imágenes recibidas: {len(image_list)}")
355
+
356
+ estimator = SimpleCeilingHeightEstimator()
357
+ results = []
358
+
359
+ for i, img_bytes in enumerate(image_list):
360
+ #st.write(f"Procesando imagen {i}")
361
+ img = bytes_to_image(img_bytes)
362
+ if img is None:
363
+ #st.write(f"⚠️ Imagen {i} no pudo ser decodificada. Se ignora.")
364
+ st.markdown(
365
+ f"""
366
+ <div style="
367
+ font-family: Sans, serif;
368
+ font-size: 13px;
369
+ color: #0a2640;
370
+ text-align: center;
371
+ border: 2px solid #bbb;
372
+ padding: 5px 8px;
373
+ border-radius: 3px;
374
+ max-width: 450px;
375
+ margin: 10px 0;
376
+ margin-left: auto;
377
+ margin-right: auto;
378
+ ">
379
+ ⚠️ Imagen {i} no pudo ser decodificada. Se ignora
380
+ </div>
381
+ """,
382
+ unsafe_allow_html=True
383
+ )
384
+
385
+ continue
386
+ result = estimator.analyze_single_image(img)
387
+ #st.write(f"Resultado imagen {i}: {result}")
388
+ st.markdown(
389
+ f"""
390
+ <div style="
391
+ font-family: Sans, serif;
392
+ font-size: 13px;
393
+ color: #0a2640;
394
+ text-align: center;
395
+ border: 2px solid #bbb;
396
+ padding: 5px 8px;
397
+ border-radius: 3px;
398
+ max-width: 450px;
399
+ margin: 10px 0;
400
+ margin-left: auto;
401
+ margin-right: auto;
402
+ ">
403
+ Resultado imagen {i}: {result}
404
+ </div>
405
+ """,
406
+ unsafe_allow_html=True
407
+ )
408
+
409
+ results.append(result)
410
+ heights = [r['estimated_height'] for r in results if 'error' not in r]
411
+ #st.write(f"Alturas obtenidas: {heights}")
412
+ if not heights:
413
+ #st.write("⚠️ No se obtuvieron alturas válidas, devolviendo valor por defecto 2.7")
414
+ final_height = 2.7
415
+ else:
416
+ final_height = np.median(heights)
417
+ st.markdown(
418
+ f"""
419
+ <div style="
420
+ font-family: Sans, serif;
421
+ font-size: 13px;
422
+ color: #0a2640;
423
+ text-align: center;
424
+ border: 2px solid #bbb;
425
+ padding: 5px 8px;
426
+ border-radius: 3px;
427
+ max-width: 450px;
428
+ margin: 10px 0;
429
+ margin-left: auto;
430
+ margin-right: auto;
431
+ ">
432
+ Altura final (mediana): {final_height}
433
+ </div>
434
+ """,
435
+ unsafe_allow_html=True
436
+ )
437
+
438
+
439
+
440
+ return final_height, logs
441
+
app2/app1/app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import joblib
3
+ import traceback
4
+ from input_handler import get_user_inputs
5
+ from feature_engineering import add_features
6
+ from preprocessing import preprocess_input
7
+ from predictor import predecir_precio
8
+ import io
9
+ import streamlit as st
10
+ from PIL import Image
11
+
12
+ # --- Estilos CSS ---
13
+ st.markdown("""
14
+ <style>
15
+ .precio-box {
16
+ background-color: #0a2640;
17
+ color: white;
18
+ padding: 25px 30px;
19
+ border-radius: 10px;
20
+ margin-top: 30px;
21
+ font-size: 22px;
22
+ font-weight: 600;
23
+ text-align: center;
24
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
25
+ border: 1px solid #09314f;
26
+ cursor: default;
27
+ user-select: none;
28
+ }
29
+ div.stButton > button {
30
+ background-color: #0a2640;
31
+ color: white;
32
+ padding: 15px 40px;
33
+ font-size: 20px;
34
+ border-radius: 10px;
35
+ border: none;
36
+ width: 300px;
37
+ cursor: pointer;
38
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
39
+ transition: background-color 0.3s ease;
40
+ display: block;
41
+ margin-left: auto;
42
+ margin-right: auto;
43
+ margin-top: 30px;
44
+ margin-bottom: 10px;
45
+ }
46
+ div.stButton > button:hover {
47
+ background-color: #09314f;
48
+ }
49
+ .small-slogan {
50
+ font-size: 14px;
51
+ font-weight: normal;
52
+ color: #555;
53
+ text-align: center;
54
+ font-family: Arial, sans-serif;
55
+ margin-top: 10px;
56
+ }
57
+ .footer {
58
+ font-size:14px;
59
+ color: #888;
60
+ padding: 20px 0;
61
+ font-family: Arial, sans-serif;
62
+ }
63
+ .footer div {
64
+ display: flex;
65
+ justify-content: space-around;
66
+ flex-wrap: wrap;
67
+ }
68
+ .footer div > div {
69
+ min-width:150px;
70
+ margin-bottom: 15px;
71
+ }
72
+ .footer-bottom {
73
+ text-align:center;
74
+ margin-top: 15px;
75
+ color: #aaa;
76
+ }
77
+ .footer-fixed {
78
+ position: fixed;
79
+ left: 0;
80
+ bottom: 0;
81
+ width: 100%;
82
+ background-color: #f1f1f1;
83
+ color: #555;
84
+ text-align: center;
85
+ padding: 10px;
86
+ font-size: 14px;
87
+ }
88
+ </style>
89
+ """, unsafe_allow_html=True)
90
+
91
+ st.set_page_config(page_title="ZulometrIA Predictor", page_icon="🏡")
92
+
93
+ if 'show_predictor' not in st.session_state:
94
+ st.session_state.show_predictor = False
95
+
96
+ if not st.session_state.show_predictor:
97
+ image = Image.open("cabecera.png")
98
+ st.image(image, use_container_width=True)
99
+ st.markdown('<div class="small-slogan">Conecta datos e imágenes de tu inmueble y deja que nuestra IA entrenada con visión por computador y modelos predictivos haga su magia. Te ofrecemos una estimación ajustada, basada en evidencia y análisis real.</div>', unsafe_allow_html=True)
100
+ if st.button("Prueba nuestro predictor"):
101
+ st.session_state.show_predictor = True
102
+
103
+ else:
104
+ # --- 1. Entrada del usuario ---
105
+ image = Image.open("cabecera.png")
106
+ st.image(image, use_container_width=True)
107
+ user_input = get_user_inputs()
108
+
109
+ if user_input:
110
+ try:
111
+
112
+ neighborhood = user_input["neighborhood"]
113
+ images = user_input.get("images", [])
114
+
115
+ # Convertir UploadedFile a bytes para el modelo
116
+ image_bytes_list = [img.getvalue() for img in images] if images else []
117
+ st.markdown(
118
+ f"""
119
+ <div style="
120
+ background-color: #0a2640; /* azul marino */
121
+ color: white;
122
+ padding: 8px 12px;
123
+ border-radius: 6px;
124
+ margin-top: 10px;
125
+ font-size: 14px;
126
+ font-weight: 600;
127
+ text-align: center;
128
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
129
+ border: 1px solid #09314f;
130
+ max-width: 300px;
131
+ margin-left: auto;
132
+ margin-right: auto;
133
+ ">
134
+ Datos recibidos - {len(image_bytes_list)} imágenes cargadas
135
+ </div>
136
+ """,
137
+ unsafe_allow_html=True
138
+ )
139
+
140
+ #st.write(f" Nº de imágenes cargadas: {len(image_bytes_list)}")
141
+
142
+ # Crear copia sin imágenes para pasar a add_features
143
+ user_input_clean = user_input.copy()
144
+ user_input_clean.pop("images", None)
145
+
146
+ data_with_features = add_features(user_input_clean, neighborhood, image_list=image_bytes_list)
147
+
148
+ # Mostrar sin columna images (que no existe ya)
149
+ #st.write(data_with_features)
150
+
151
+ # --- 3. Preprocesamiento general ---
152
+ #st.write(" Preprocesando datos...")
153
+ processed_data = preprocess_input(data_with_features)
154
+
155
+ #st.success(" Preprocesamiento completado")
156
+ processed_data['property_type'] = processed_data['property_type'].astype('category')
157
+ processed_data['neighborhood'] = processed_data['neighborhood'].astype('category')
158
+
159
+ #st.write(" Realizando predicción...")
160
+ precio_estimado = predecir_precio(processed_data, neighborhood)
161
+ st.markdown(
162
+ f"<div class='precio-box'>Precio estimado: {precio_estimado:,.0f} €</div>",
163
+ unsafe_allow_html=True
164
+ )
165
+ st.markdown("---")
166
+ st.markdown("### ¿Desea guardar sus datos?")
167
+
168
+ # Crear DataFrame con el precio estimado
169
+ data_guardar = processed_data.copy()
170
+ data_guardar["precio_estimado"] = precio_estimado
171
+
172
+ # Convertir el DataFrame a un archivo CSV en memoria
173
+ csv_buffer = io.StringIO()
174
+ data_guardar.to_csv(csv_buffer, index=False)
175
+ csv_bytes = csv_buffer.getvalue().encode('utf-8')
176
+
177
+ # Botón de descarga
178
+ st.download_button(
179
+ label=" Descargar CSV",
180
+ data=csv_bytes,
181
+ file_name="prediccion_zulometrIA.csv",
182
+ mime="text/csv",
183
+ key="download_csv"
184
+ )
185
+ except Exception as e:
186
+ st.error("❌ Ocurrió un error en la ejecución:")
187
+ st.code(traceback.format_exc())
188
+
189
+ st.markdown("---") # línea separadora
190
+ footer = """
191
+ <div style="font-size:14px; color: #888; padding: 20px 0; font-family: Arial, sans-serif;">
192
+ <div style="display: flex; justify-content: space-around; flex-wrap: wrap;">
193
+ <div style="min-width:150px; margin-bottom: 15px;">
194
+ <strong>Sobre Nosotros</strong><br>
195
+ Somos una empresa dedicada a brindar soluciones inteligentes para el sector inmobiliario.<br>
196
+ Nuestra misión es facilitar la toma de decisiones con tecnología de punta.
197
+ </div>
198
+ <div style="min-width:150px; margin-bottom: 15px;">
199
+ <strong>Servicios</strong><br>
200
+ - Predicción de precios<br>
201
+ - Análisis de mercado<br>
202
+ - Consultoría personalizada
203
+ </div>
204
+ <div style="min-width:150px; margin-bottom: 15px;">
205
+ <strong>Soporte</strong><br>
206
+ <a href="mailto:soporte@ejemplo.com" style="color: #555; text-decoration:none;">soporte@ejemplo.com</a><br>
207
+ Tel: +34 900 123 456<br>
208
+ FAQ | Chat en línea
209
+ </div>
210
+ <div style="min-width:150px; margin-bottom: 15px;">
211
+ <strong>Legal</strong><br>
212
+ <a href="#" style="color: #555; text-decoration:none;">Política de Privacidad</a><br>
213
+ <a href="#" style="color: #555; text-decoration:none;">Términos de Servicio</a>
214
+ </div>
215
+ </div>
216
+ <div style="text-align:center; margin-top: 15px; color: #aaa;">
217
+ © 2025 ZulometrIA solutions. Todos los derechos reservados.
218
+ </div>
219
+ </div>
220
+ """
221
+
222
+ st.markdown(footer, unsafe_allow_html=True)
223
+
224
+
225
+
226
+ footer_fixed = """
227
+ <div class="footer-fixed">
228
+ ZulometrIA puede cometer errores. Considera verificar la información con tu especulador de confianza |
229
+ <a href="https://linkedin.com/in/laura-andrés-cepas-69a36a275" target="_blank">LinkedIn</a> |
230
+ <a href="https://github.com/tuusuario" target="_blank">GitHub</a>
231
+ </div>
232
+ """
233
+
234
+ st.markdown(footer_fixed, unsafe_allow_html=True)
235
+
app2/app1/cabecera.png ADDED

Git LFS Details

  • SHA256: 6d8420c0dc3116ed6c4d621cffe15521134907966404e5b327ab1ad7bbe73b58
  • Pointer size: 131 Bytes
  • Size of remote file: 426 kB
app2/app1/detectar_aire_acondicionado.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from roboflow import Roboflow
4
+ from inference_sdk import InferenceHTTPClient
5
+ def detectar_aire_acondicionado_en_imagenes(image_list, st=None):
6
+ """
7
+ Detecta aire acondicionado en una lista de imágenes.
8
+ Devuelve 1 si detecta aire acondicionado en al menos 2 imágenes, 0 en caso contrario.
9
+
10
+ Parámetros:
11
+ - image_list: lista de imágenes, cada una puede ser ruta (str) o bytes
12
+ - st: streamlit para logs (opcional)
13
+
14
+ Retorna:
15
+ - int: 1 o 0
16
+ """
17
+
18
+ def log(msg):
19
+ if st:
20
+ st.write(msg)
21
+ else:
22
+ print(msg)
23
+
24
+ CLIENT = InferenceHTTPClient(
25
+ api_url="https://serverless.roboflow.com",
26
+ api_key="EYfHRlA9fPiyTkjW6pKs"
27
+ )
28
+
29
+ detecciones_positivas = 0
30
+ st.markdown(
31
+ f"""
32
+ <div style="
33
+ font-family: Sans, serif;
34
+ font-size: 13px;
35
+ color: #0a2640;
36
+ text-align: center;
37
+ border: 2px solid #bbb;
38
+ padding: 5px 8px;
39
+ border-radius: 3px;
40
+ max-width: 450px;
41
+ margin: 10px 0;
42
+ margin-left: auto;
43
+ margin-right: auto;
44
+ ">
45
+ Añadiendo características visuales: detección aire acondicionado
46
+ </div>
47
+ """,
48
+ unsafe_allow_html=True
49
+ )
50
+ #log(" Añadiendo características visuales: detección aire acondicionado.")
51
+ if not image_list:
52
+ #log(" No se recibieron imágenes para detectar aire acondicionado.")
53
+ st.markdown(
54
+ f"""
55
+ <div style="
56
+ font-family: Sans, serif;
57
+ font-size: 13px;
58
+ color: #0a2640;
59
+ text-align: center;
60
+ border: 2px solid #bbb;
61
+ padding: 5px 8px;
62
+ border-radius: 3px;
63
+ max-width: 450px;
64
+ margin: 10px 0;
65
+ margin-left: auto;
66
+ margin-right: auto;
67
+ ">
68
+ No se recibieron imágenes para detectar aire acondicionado
69
+ </div>
70
+ """,
71
+ unsafe_allow_html=True
72
+ )
73
+ #log(" Añadiendo características visuales: detección aire acondicionado.")
74
+ return 0
75
+
76
+ for i, img in enumerate(image_list):
77
+ try:
78
+ # img puede ser bytes o path (string)
79
+ if isinstance(img, bytes):
80
+ import tempfile
81
+ with tempfile.NamedTemporaryFile(suffix=".webp") as tmp:
82
+ tmp.write(img)
83
+ tmp.flush()
84
+ resultado = CLIENT.infer(tmp.name, model_id="test3-qzutu/3")
85
+ else:
86
+ resultado = CLIENT.infer(img, model_id="test3-qzutu/3")
87
+
88
+ if resultado and resultado.get("predictions"):
89
+ detectado = False
90
+ for prediction in resultado["predictions"]:
91
+ if prediction.get("class") == 'Air conditioning 1':
92
+ detecciones_positivas += 1
93
+ detectado = True
94
+ #log(f"✅ Aire acondicionado detectado en imagen {i}")
95
+ break
96
+ if not detectado:
97
+ log("")
98
+ #log(f"❌ No se detectó aire acondicionado en imagen {i}")
99
+ else:
100
+ log("")
101
+ #log(f"❌ No se detectaron predicciones en imagen {i}")
102
+
103
+ if detecciones_positivas >= 2:
104
+ #log(f" Aire acondicionado confirmado en al menos 2 imágenes. Parando detección.")
105
+ break
106
+
107
+ except Exception as e:
108
+ #log(f"⚠️ Error procesando imagen {i}: {str(e)}")
109
+ st.markdown(
110
+ f"""
111
+ <div style="
112
+ font-family: Sans, serif;
113
+ font-size: 13px;
114
+ color: #0a2640;
115
+ text-align: center;
116
+ border: 2px solid #bbb;
117
+ padding: 5px 8px;
118
+ border-radius: 3px;
119
+ max-width: 450px;
120
+ margin: 10px 0;
121
+ margin-left: auto;
122
+ margin-right: auto;
123
+ ">
124
+ ⚠️ Error procesando imagen {i}: {str(e)}
125
+ </div>
126
+ """,
127
+ unsafe_allow_html=True
128
+ )
129
+
130
+ if detecciones_positivas < 2:
131
+ #log(f" Aire acondicionado detectado en {detecciones_positivas} imágenes, no alcanza el umbral de 2.")
132
+ st.markdown(
133
+ f"""
134
+ <div style="
135
+ font-family: Sans, serif;
136
+ font-size: 13px;
137
+ color: #0a2640;
138
+ text-align: center;
139
+ border: 2px solid #bbb;
140
+ padding: 5px 8px;
141
+ border-radius: 3px;
142
+ max-width: 450px;
143
+ margin: 10px 0;
144
+ margin-left: auto;
145
+ margin-right: auto;
146
+ ">
147
+ Aire acondicionado detectado en {detecciones_positivas} imágenes, no alcanza el umbral de 2.
148
+ </div>
149
+ """,
150
+ unsafe_allow_html=True
151
+ )
152
+
153
+
154
+ return 1 if detecciones_positivas >= 2 else 0
155
+
app2/app1/feature_engineering.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+ from PIL import Image
4
+ import pandas as pd
5
+ from collections import Counter
6
+ import os
7
+ import streamlit as st
8
+ import io
9
+ from altura_techo_estimator import estimate_ceiling_height
10
+ from reformado_classifier import estimate_reformado_from_images, load_reformado_model
11
+ from detectar_aire_acondicionado import detectar_aire_acondicionado_en_imagenes
12
+
13
+ def add_features(data_dict, neighborhood, image_list=None):
14
+ import pandas as pd
15
+
16
+ df = pd.DataFrame([data_dict])
17
+ device = "cuda" if torch.cuda.is_available() else "cpu"
18
+
19
+ if neighborhood in ["chamberi", "arganzuela"]:
20
+ model = load_reformado_model(device=device)
21
+ reformado = estimate_reformado_from_images(image_list or [], model, device=device)
22
+ df["reformado_bin"] = reformado
23
+
24
+
25
+ if neighborhood == "retiro":
26
+ altura_estim, logs = estimate_ceiling_height(image_list)
27
+ for msg in logs:
28
+ st.write(msg)
29
+ df["altura_techo"] = altura_estim
30
+
31
+ if neighborhood == "centro":
32
+ aire = detectar_aire_acondicionado_en_imagenes(image_list, st=st)
33
+ df["aire_acondicionado_bin"] = aire
34
+
35
+
36
+ return df
app2/app1/input_handler.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def get_user_inputs():
4
+ with st.form("formulario_prediccion"):
5
+ st.subheader("Introduce los detalles de la propiedad")
6
+
7
+ address = st.text_input("Dirección")
8
+ agency_name = st.text_input("Agencia")
9
+ bathroom_count = st.number_input("Baños", min_value=0)
10
+ bedroom_count = st.number_input("Dormitorios", min_value=0)
11
+ energy_certificate = st.selectbox("Certificado energético", ["A", "B", "C", "D", "E", "F", "G"])
12
+ floor = st.number_input("Piso", step=1)
13
+ latitude = st.number_input("Latitud", format="%.6f")
14
+ longitude = st.number_input("Longitud", format="%.6f")
15
+ lot_size = st.number_input("Tamaño del terreno (m2)", min_value=0)
16
+ property_description = st.text_area("Descripción de la propiedad")
17
+ property_id = st.text_input("ID de la propiedad")
18
+ property_title = st.text_input("Título del anuncio")
19
+ property_type = st.selectbox("Tipo de propiedad", ["flat", "Chalet"])
20
+ neighborhood = st.selectbox("Barrio", ["chamberi", "centro", "arganzuela", "retiro"])
21
+ exterior = st.checkbox("¿Es exterior?", value=False)
22
+ ascensor = st.checkbox("¿Tiene ascensor?", value=False)
23
+
24
+ uploaded_images = st.file_uploader(
25
+ "Imágenes de la propiedad (puedes subir varias)",
26
+ type=["webp"],
27
+ accept_multiple_files=True
28
+ )
29
+
30
+ #submit = st.form_submit_button("Predecir")
31
+ submit, disclaimer_col = st.columns([1, 4])
32
+
33
+ with submit:
34
+ submit_button = st.form_submit_button("Predecir")
35
+
36
+ with disclaimer_col:
37
+ st.markdown(
38
+ """
39
+ <div style="font-size:12px; color:#555; margin-top: 3px;">
40
+ Al utilizar esta herramienta, aceptas que los datos proporcionados serán procesados mediante técnicas de Inteligencia Artificial
41
+ con fines de análisis y predicción. Consulta nuestra <a href="#" style="color:#0a2640; text-decoration:underline;">política de privacidad</a>.
42
+ </div>
43
+ """,
44
+ unsafe_allow_html=True
45
+ )
46
+
47
+
48
+ if submit:
49
+ return {
50
+ "address": address,
51
+ "agency_name": agency_name,
52
+ "bathroom_count": bathroom_count,
53
+ "bedroom_count": bedroom_count,
54
+ "energy_certificate": energy_certificate,
55
+ "floor": floor,
56
+ "latitude": latitude,
57
+ "longitude": longitude,
58
+ "lot_size": lot_size,
59
+ "property_description": property_description,
60
+ "property_id": property_id,
61
+ "property_title": property_title,
62
+ "property_type": property_type,
63
+ "neighborhood": neighborhood,
64
+ "images": uploaded_images,
65
+ "exterior": int(exterior),
66
+ "ascensor": int(ascensor),
67
+ }
68
+
69
+ return None
app2/app1/logs.log ADDED
The diff for this file is too large to render. See raw diff
 
app2/app1/modelos/datos_imagenes_con_predicciones_y_aire.csv ADDED
The diff for this file is too large to render. See raw diff
 
app2/app1/modelos/efficientnet_reformado.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf65ecc378c2f2ee355d169d0bd3e3f752393667f8d2eb18318fd042e9681856
3
+ size 16344182
app2/app1/modelos/modelo_arganzuela.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60ada71fed519362bc13d9ad183b5a238a6de712c4ccb2bd64e30195dd288d18
3
+ size 1421
app2/app1/modelos/modelo_centro.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f81304652afe13947f8d236a0f4e3008fc89cebedc3a4082a2ff80494ce6103
3
+ size 4063617
app2/app1/modelos/modelo_chamberi.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8655b18f1ef1047d69ae5bf989bffe10ab27020e373c9e24038536f5d777667
3
+ size 3470625
app2/app1/modelos/modelo_retiro.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8525911367bb4cf473fac80580781bc72121c67d0c38ba89512f33dee7a031e
3
+ size 1726065
app2/app1/predictor.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from pycaret.regression import load_model, predict_model, setup, finalize_model
3
+
4
+ # Cache para no cargar y preparar setup cada vez
5
+ _model_cache = {}
6
+
7
+ def load_and_finalize_model(neighborhood: str):
8
+ global _model_cache
9
+
10
+ if neighborhood in _model_cache:
11
+ return _model_cache[neighborhood]
12
+
13
+ # Carga dataset completo para recrear el setup
14
+ df = pd.read_csv('modelos/datos_imagenes_con_predicciones_y_aire.csv')
15
+
16
+ energy_certificate_order = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
17
+ energy_certificate_mapping = {cert: i for i, cert in enumerate(energy_certificate_order)}
18
+ df['energy_certificate_encoded'] = df['energy_certificate'].str.lower().map(energy_certificate_mapping)
19
+
20
+ features = [
21
+ 'bathroom_count', 'bedroom_count', 'floor',
22
+ 'latitude', 'longitude', 'lot_size',
23
+ 'property_type', 'neighborhood', 'exterior', 'ascensor',
24
+ 'reformado_bin', 'energy_certificate_encoded'
25
+ ]
26
+
27
+ df_training = df[features + ['property_price']].copy()
28
+
29
+ # Categóricas iguales que en el entrenamiento
30
+ df_training['property_type'] = df_training['property_type'].astype('category')
31
+ df_training['neighborhood'] = df_training['neighborhood'].astype('category')
32
+
33
+ # Setup con parámetros iguales que usaste en jupyter
34
+ s = setup(data=df_training, target='property_price', session_id=123, verbose=False)
35
+
36
+ # Carga modelo
37
+ normalized_neighborhood = neighborhood.strip().replace(" ", "_").lower()
38
+ model_path = f"modelos/modelo_{normalized_neighborhood}"
39
+
40
+ modelo = load_model(model_path)
41
+
42
+ # Finaliza el modelo para evitar errores al predecir
43
+ modelo_finalizado = finalize_model(modelo)
44
+
45
+ _model_cache[neighborhood] = modelo_finalizado
46
+
47
+ return modelo_finalizado
48
+
49
+ def predecir_precio(df_preprocesado: pd.DataFrame, neighborhood: str) -> float:
50
+ if df_preprocesado.shape[0] != 1:
51
+ raise ValueError("El DataFrame debe contener exactamente una fila")
52
+
53
+ modelo = load_and_finalize_model(neighborhood)
54
+
55
+ # En tu preprocesamiento debes asegurarte que df_preprocesado tiene:
56
+ # 'property_type' y 'neighborhood' como categorías
57
+ df_preprocesado['property_type'] = df_preprocesado['property_type'].astype('category')
58
+ df_preprocesado['neighborhood'] = df_preprocesado['neighborhood'].astype('category')
59
+
60
+ # Predict con el DataFrame tal cual, sin filtrar columnas
61
+ pred = predict_model(modelo, data=df_preprocesado)
62
+
63
+ return float(pred['prediction_label'].iloc[0])
64
+
app2/app1/preprocessing.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ def preprocess_input(df_raw: pd.DataFrame) -> pd.DataFrame:
4
+ """
5
+ Preprocesa una fila de entrada para predicción con un modelo de PyCaret.
6
+ NO realiza transformaciones avanzadas (OneHot, escalado...), solo lo mínimo necesario.
7
+
8
+ Args:
9
+ df_raw (pd.DataFrame): Una fila de datos crudos
10
+
11
+ Returns:
12
+ pd.DataFrame: Fila lista para `predict_model()`
13
+ """
14
+ # Mapear certificado energético si es necesario
15
+ energy_certificate_order = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
16
+ energy_certificate_mapping = {cert: i for i, cert in enumerate(energy_certificate_order)}
17
+
18
+ df = df_raw.copy()
19
+
20
+ # Asegurar que la columna existe y mapear si hace falta
21
+ if 'energy_certificate' in df.columns:
22
+ df['energy_certificate_encoded'] = df['energy_certificate'].str.lower().map(energy_certificate_mapping)
23
+
24
+ # Definir las features usadas para entrenar
25
+ features = [
26
+ 'bathroom_count', 'bedroom_count', 'floor',
27
+ 'latitude', 'longitude', 'lot_size',
28
+ 'property_type', 'neighborhood', 'exterior', 'ascensor',
29
+ 'reformado_bin', 'energy_certificate_encoded'
30
+ ]
31
+
32
+ # Añadir columnas faltantes como NaN o 0 por defecto
33
+ for col in features:
34
+ if col not in df.columns:
35
+ if col == 'reformado_bin':
36
+ df[col] = 0 # valor por defecto para variable binaria
37
+ else:
38
+ df[col] = pd.NA # o np.nan
39
+
40
+ # Reordenar las columnas según el orden original
41
+ df = df[features]
42
+
43
+ return df
44
+
app2/app1/reformado_classifier.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision import transforms, models
4
+ from PIL import Image
5
+ import numpy as np
6
+ import io # ← IMPORTANTE
7
+ import streamlit as st # si estás usando Streamlit
8
+
9
+ # ----------- Cargar modelo EfficientNet entrenado con torchvision -----------
10
+ def load_reformado_model(path="modelos/efficientnet_reformado.pth", device="cpu"):
11
+ #st.write(" Cargando modelo de reformado...")
12
+
13
+ # Cargar arquitectura desde torchvision
14
+ model = models.efficientnet_b0(pretrained=False)
15
+ model.classifier[1] = nn.Linear(model.classifier[1].in_features, 2) # salida 2 clases
16
+
17
+ model.load_state_dict(torch.load(path, map_location=device))
18
+ model.to(device)
19
+ model.eval()
20
+
21
+ #st.write(" Añadiendo características visuales: reformado/no reformado.")
22
+ st.markdown(
23
+ f"""
24
+ <div style="
25
+ font-family: Sans, serif;
26
+ font-size: 13px;
27
+ color: #0a2640;
28
+ text-align: center;
29
+ border: 2px solid #bbb;
30
+ padding: 5px 8px;
31
+ border-radius: 3px;
32
+ max-width: 450px;
33
+ margin: 10px 0;
34
+ margin-left: auto;
35
+ margin-right: auto;
36
+ ">
37
+ Añadiendo características visuales: reformado/no reformado
38
+ </div>
39
+ """,
40
+ unsafe_allow_html=True
41
+ )
42
+ return model
43
+
44
+ # ----------- Realizar predicciones sobre imágenes -----------
45
+ def estimate_reformado_from_images(image_list, model, device="cpu"):
46
+ #st.write(f" Número de imágenes recibidas: {len(image_list)}")
47
+
48
+ transform = transforms.Compose([
49
+ transforms.Resize((224, 224)),
50
+ transforms.ToTensor(),
51
+ transforms.Normalize(mean=[0.5]*3, std=[0.5]*3) # Usa la normalización usada en el entrenamiento
52
+ ])
53
+
54
+ preds = []
55
+
56
+ for i, img_bytes in enumerate(image_list):
57
+ st.write(f" Procesando imagen {i}")
58
+ try:
59
+ img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
60
+ except Exception as e:
61
+ #st.write(f"⚠️ Imagen {i} no válida: {e}")
62
+ st.markdown(
63
+ f"""
64
+ <div style="
65
+ font-family: Sans, serif;
66
+ font-size: 13px;
67
+ text-align: center;
68
+ color: #0a2640;
69
+ border: 2px solid #bbb;
70
+ padding: 5px 8px;
71
+ margin-left: auto;
72
+ margin-right: auto;
73
+ border-radius: 3px;
74
+ max-width: 400px;
75
+ margin: 10px 0;
76
+ ">
77
+ ⚠️ Imagen {i} no válida: {e}
78
+ </div>
79
+ """,
80
+ unsafe_allow_html=True
81
+ )
82
+ continue
83
+
84
+ input_tensor = transform(img).unsqueeze(0).to(device)
85
+ with torch.no_grad():
86
+ output = model(input_tensor)
87
+ prob = torch.softmax(output, dim=1)[0, 1].item() # probabilidad de clase 1
88
+ pred_class = int(prob > 0.5)
89
+ st.write(f"✅ Imagen {i} → prob: {prob:.2f} → clase: {pred_class}")
90
+ st.markdown(
91
+ f"""
92
+ <div style="
93
+ font-family: Sans, serif;
94
+ font-size: 13px;
95
+ text-align: center;
96
+ color: #0a2640;
97
+ border: 2px solid #bbb;
98
+ padding: 5px 8px;
99
+ margin-left: auto;
100
+ margin-right: auto;
101
+ border-radius: 3px;
102
+ max-width: 400px;
103
+ margin: 10px 0;
104
+ ">
105
+ Imagen {i} → prob: {prob:.2f} → clase: {pred_class}
106
+ </div>
107
+ """,
108
+ unsafe_allow_html=True
109
+ )
110
+ preds.append(pred_class)
111
+
112
+ if not preds:
113
+ #st.write("⚠️ No se pudieron predecir clases. Valor por defecto: 0 (no reformado)")
114
+ st.markdown(
115
+ f"""
116
+ <div style="
117
+ font-family: Sans, serif;
118
+ font-size: 13px;
119
+ color: #0a2640;
120
+ text-align: center;
121
+ border: 2px solid #bbb;
122
+ padding: 5px 8px;
123
+ border-radius: 3px;
124
+ max-width: 450px;
125
+ margin: 10px 0;
126
+ margin-left: auto;
127
+ margin-right: auto;
128
+ ">
129
+ ⚠️ No se pudieron predecir clases. Valor por defecto: 0 (no reformado)
130
+ </div>
131
+ """,
132
+ unsafe_allow_html=True
133
+ )
134
+ return 0
135
+
136
+ #st.write(f" Predicciones: {preds}")
137
+ majority = int(np.round(np.mean(preds))) # mayoría simple
138
+ #st.write(f" Clase mayoritaria final: {majority}")
139
+ st.markdown(
140
+ f"""
141
+ <div style="
142
+ font-family: Sans, serif;
143
+ font-size: 13px;
144
+ color: #0a2640;
145
+ text-align: center;
146
+ border: 2px solid #bbb;
147
+ padding: 5px 8px;
148
+ border-radius: 3px;
149
+ max-width: 450px;
150
+ margin: 10px 0;
151
+ margin-left: auto;
152
+ margin-right: auto;
153
+ ">
154
+ Clase mayoritaria final: {majority}
155
+ </div>
156
+ """,
157
+ unsafe_allow_html=True
158
+ )
159
+
160
+ return majority
161
+
app2/app1/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ torch
5
+ torchvision
6
+ Pillow
7
+ pycaret
8
+ joblib
9
+ roboflow
10
+ inference-sdk
11
+