agerhund commited on
Commit
36f4290
·
verified ·
1 Parent(s): a74d240

Upload 7 files

Browse files
Files changed (7) hide show
  1. README.md +76 -19
  2. app.py +404 -0
  3. generate_cache.py +22 -0
  4. logic.py +1470 -0
  5. packages.txt +1 -0
  6. requirements.txt +14 -2
  7. vectores_cache.pkl +3 -0
README.md CHANGED
@@ -1,19 +1,76 @@
1
- ---
2
- title: DesignIA
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Streamlit template space
12
- ---
13
-
14
- # Welcome to Streamlit!
15
-
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
17
-
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DesignIA - Recomendador de Muebles Inteligente
2
+
3
+ DesignIA es una aplicación inteligente que te ayuda a diseñar tu salón ideal. A partir de una imagen panorámica (360°) de tu habitación vacía, la aplicación detecta automáticamente la geometría del espacio (paredes, puertas, ventanas) y te sugiere una distribución óptima de muebles, recomendándote productos reales de IKEA que se ajustan a tu estilo y presupuesto.
4
+
5
+ ## Características
6
+
7
+ * **Escaneo de Habitación 3D**: Utiliza **HorizonNet** para detectar la estructura de la habitación a partir de una sola imagen panorámica.
8
+ * **Diseño Automático**: Algoritmos de optimización espacial para colocar muebles respetando zonas de paso y distancias de visualización (TV-Sofá).
9
+ * **Recomendación Estilística**: Un modelo basado en **BERT** analiza el estilo de los muebles para sugerir combinaciones coherentes.
10
+ * **Visualización Interactiva**: Visualiza tu futuro salón en 3D directamente en el navegador.
11
+ * **Presupuesto Ajustable**: Define cuánto quieres gastar y la IA buscará la mejor combinación calidad/precio.
12
+
13
+ ## Requisitos Previos
14
+
15
+ Debido al uso de modelos de Inteligencia Artificial avanzados, este proyecto requiere descargar archivos de gran tamaño.
16
+
17
+ 1. **Python 3.8+**
18
+ 2. **Git LFS (Large File Storage)**: Imprescindible para descargar los modelos de IA.
19
+ * Instalación: [https://git-lfs.com/](https://git-lfs.com/)
20
+ * O ejecuta: `git lfs install`
21
+
22
+ ## Instalación
23
+
24
+ 1. **Clonar el repositorio**
25
+ Asegúrate de tener Git LFS instalado antes de clonar.
26
+ ```bash
27
+ git lfs install
28
+ git clone https://github.com/agerhund/DesignIA.git
29
+ cd DesignIA
30
+ ```
31
+ *Nota: La descarga puede tardar unos minutos debido a los modelos (~1.7 GB).*
32
+
33
+ 2. **Crear un entorno virtual (Recomendado)**
34
+ ```bash
35
+ python -m venv venv
36
+ # En Windows:
37
+ venv\Scripts\activate
38
+ # En Mac/Linux:
39
+ source venv/bin/activate
40
+ ```
41
+
42
+ 3. **Instalar dependencias**
43
+ ```bash
44
+ pip install -r requirements.txt
45
+ ```
46
+
47
+ ## Ejecución
48
+
49
+ Para iniciar la aplicación web localmente:
50
+
51
+ ```bash
52
+ streamlit run app.py
53
+ ```
54
+
55
+ La aplicación se abrirá automáticamente en tu navegador (usualmente en `http://localhost:8501`).
56
+
57
+ ## Notas sobre el Rendimiento
58
+
59
+ * **Memoria RAM**: Se recomienda disponer de al menos **8 GB de RAM**, ya que los modelos de visión y lenguaje se cargan en memoria.
60
+ * **GPU**: Si dispones de una GPU NVIDIA (CUDA) o un Mac con chip M-series (MPS), la aplicación intentará usarla para acelerar la detección. De lo contrario, funcionará en CPU (más lento).
61
+ * **Streamlit Cloud**: Es posible que esta aplicación **no funcione** en la capa gratuita de Streamlit Cloud debido a las limitaciones de memoria y almacenamiento (los modelos exceden el límite habitual). Se recomienda ejecutar en local o en un servidor con mayores recursos.
62
+
63
+ ## Estructura del Proyecto
64
+
65
+ * `app.py`: Punto de entrada de la aplicación Streamlit.
66
+ * `logic.py`: Lógica principal (IA, geometría, recomendación).
67
+ * `models/`: Contiene los pesos de los modelos (HorizonNet y BERT Encoder).
68
+ * `data/`: Base de datos de muebles (CSV).
69
+ * `horizonnet/`: Código fuente del modelo de visión computacional.
70
+
71
+ ## Autor
72
+
73
+ **Andrés Gerlotti Slusnys**
74
+ Máster de Data Science, Business Analytics y Big Data
75
+ Universidad Complutense de Madrid
76
+ © 2025
app.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from PIL import Image
5
+ import os
6
+
7
+ # Importar la lógica principal del proyecto
8
+ import logic
9
+
10
+ # --- CONFIGURACIÓN INICIAL DE LA PÁGINA ---
11
+ st.set_page_config(page_title="DesignIA - Recomendador de Muebles inteligente", layout="wide")
12
+
13
+ # --- CARGAR ESTILOS CSS ---
14
+ def cargar_estilo():
15
+ """Define y aplica estilos CSS para la UI de Streamlit."""
16
+ st.markdown("""
17
+ <style>
18
+ /* Ocultar elementos de sistema de Streamlit */
19
+ #MainMenu {visibility: hidden;}
20
+ footer {visibility: hidden;}
21
+ header {visibility: hidden;}
22
+
23
+ /* Estilo de Botones (Azul IKEA) */
24
+ div.stButton > button:first-child {
25
+ background-color: #0051ba;
26
+ color: white;
27
+ border-radius: 8px;
28
+ font-weight: bold;
29
+ border: none;
30
+ padding: 0.5rem 1rem;
31
+ }
32
+ div.stButton > button:first-child:hover {
33
+ background-color: #003e8f;
34
+ border: none;
35
+ }
36
+
37
+ /* Estilo de las Tarjetas de Producto */
38
+ .product-card {
39
+ background-color: white;
40
+ padding: 15px;
41
+ border-radius: 10px;
42
+ box-shadow: 0 2px 5px rgba(0,0,0,0.05);
43
+ margin-bottom: 15px;
44
+ border: 1px solid #eee;
45
+ color: black !important; /* Forzar texto negro dentro de la tarjeta blanca */
46
+ }
47
+ </style>
48
+ """, unsafe_allow_html=True)
49
+
50
+ cargar_estilo()
51
+
52
+ # --- CONSTANTES Y RUTAS DE RECURSOS ---
53
+ # Rutas relativas para despliegue
54
+ csv_path = "data/furniture_data.csv"
55
+ model_path = "models/bert_style_encoder.pth"
56
+ horizon_path = "models/horizonnet_model.pth"
57
+ cache_path = "vectores_cache.pkl" # Se generará en el directorio de trabajo
58
+
59
+ # --- SIDEBAR: INFORMACIÓN DEL PROYECTO ---
60
+ with st.sidebar:
61
+ st.title("DesignIA - Asistente de Diseño")
62
+ st.markdown("---")
63
+ st.markdown("**Trabajo de fin de Máster**")
64
+ st.caption("Máster de Data Science, Business Analytics y Big Data")
65
+ st.caption("Universidad Complutense de Madrid")
66
+ st.markdown("---")
67
+ st.markdown("Desarrollado por **Andrés Gerlotti Slusnys**")
68
+ st.markdown("© 2025")
69
+
70
+ # Indicador de estado para debugging
71
+ with st.expander("Estado del Sistema", expanded=False):
72
+ st.success("Motor Gráfico: Activo")
73
+ st.success("Modelo NLP: Cargado")
74
+ if os.path.exists(horizon_path):
75
+ st.success("HorizonNet: Conectado")
76
+ else:
77
+ st.error("HorizonNet: No encontrado")
78
+
79
+ # Sección de Ejemplos
80
+ st.markdown("---")
81
+ st.subheader("📸 Imágenes de Ejemplo")
82
+ st.caption("Descarga estas imágenes para probar la app:")
83
+
84
+ examples_dir = os.path.join(os.path.dirname(__file__), "examples")
85
+ if os.path.exists(examples_dir):
86
+ example_files = [f for f in os.listdir(examples_dir) if f.endswith(('.jpg', '.png'))]
87
+ example_files.sort()
88
+
89
+ selected_example = st.selectbox("Selecciona un ejemplo:", example_files)
90
+
91
+ if selected_example:
92
+ file_path = os.path.join(examples_dir, selected_example)
93
+ with open(file_path, "rb") as file:
94
+ btn = st.download_button(
95
+ label="⬇️ Descargar Imagen",
96
+ data=file,
97
+ file_name=selected_example,
98
+ mime="image/jpeg"
99
+ )
100
+
101
+ # Mostrar miniatura
102
+ st.image(file_path, caption="Vista previa", use_container_width=True)
103
+ else:
104
+ st.info("No hay ejemplos disponibles.")
105
+
106
+ # --- INICIALIZACIÓN DEL ESTADO DE SESIÓN ---
107
+ if 'stage' not in st.session_state: st.session_state.stage = 0
108
+ if 'room_data' not in st.session_state: st.session_state.room_data = None
109
+ if 'muebles_df' not in st.session_state: st.session_state.muebles_df = None
110
+ if 'data_manager' not in st.session_state: st.session_state.data_manager = None
111
+
112
+ # --- 1. CARGA DE DATOS Y MODELOS (Cacheado) ---
113
+ @st.cache_resource
114
+ def init_backend(csv, cache, model):
115
+ """Inicializa DataManager y carga/genera el DataFrame de muebles."""
116
+ dm = logic.DataManager(csv, cache, model)
117
+ df = dm.cargar_datos()
118
+ return dm, df
119
+
120
+ try:
121
+ if st.session_state.data_manager is None:
122
+ with st.spinner("Cargando base de datos de muebles y modelos IA..."):
123
+ dm, df = init_backend(csv_path, cache_path, model_path)
124
+ st.session_state.data_manager = dm
125
+ st.session_state.muebles_df = df
126
+ st.sidebar.success(f"Base de datos cargada: {len(st.session_state.muebles_df)} items")
127
+ except Exception as e:
128
+ st.error(f"Error cargando datos: {e}")
129
+ st.stop()
130
+
131
+ # --- INTERFAZ PRINCIPAL ---
132
+ st.title("Recomendador de Muebles Inteligente")
133
+ st.markdown("Sube una panorámica, detecta el espacio y obtén el diseño ideal según tu presupuesto.")
134
+
135
+ # --- PASO 1: CARGA DE IMAGEN Y DETECCIÓN ---
136
+ st.header("1. Escaneo de Habitación")
137
+ uploaded_file = st.file_uploader("Sube tu imagen panorámica (360)", type=['jpg', 'png', 'jpeg'])
138
+
139
+ if uploaded_file is not None:
140
+ image = Image.open(uploaded_file)
141
+ st.image(image, caption='Imagen subida', use_container_width=True)
142
+
143
+ if st.button("Analizar la habitación"):
144
+ with st.spinner("Detectando la geometría..."):
145
+ # Guardar temporalmente la imagen para que la librería pueda leerla
146
+ with open("temp_pano.jpg", "wb") as f:
147
+ f.write(uploaded_file.getbuffer())
148
+
149
+ # Instanciar y ejecutar el detector de layout (HorizonNet)
150
+ try:
151
+ detector = logic.RoomLayoutDetector(horizon_path)
152
+ room_data = detector.detect_layout("temp_pano.jpg")
153
+
154
+ # Validación de datos y manejo de fallos
155
+ if room_data is None or not isinstance(room_data, dict) or 'width' not in room_data:
156
+ st.error("**Detección fallida.** El modelo de Computer Vision no pudo extraer las dimensiones ni los obstáculos. Asegúrate de que el modelo HorizonNet está configurado y funcionando correctamente.")
157
+ st.session_state.room_data = None
158
+ st.session_state.stage = 0
159
+ else:
160
+ st.session_state.room_data = room_data
161
+ st.session_state.stage = 1
162
+ st.success("Análisis completado")
163
+
164
+ # Mostrar resultado de la detección de HorizonNet
165
+ st.header("Resultado del análisis visual")
166
+ annotated_image = logic.dibujar_layout_sobre_imagen("temp_pano.jpg", room_data)
167
+ st.image(annotated_image, caption='Análisis de HorizonNet (Vértices, Puertas y Ventanas)', use_container_width=True)
168
+
169
+ except Exception as e:
170
+ st.error(f"Error en detección: {e}. Revisa la configuración del modelo HorizonNet.")
171
+ st.session_state.stage = 0
172
+
173
+ # --- PASO 2: VERIFICACIÓN Y EDICIÓN DE GEOMETRÍA/OBSTÁCULOS ---
174
+ if st.session_state.stage >= 1 and st.session_state.room_data:
175
+ st.header("2. Verificación de Geometría")
176
+
177
+ # Mostrar dimensiones detectadas
178
+ w_m = st.session_state.room_data.get('width', 0.0)
179
+ l_m = st.session_state.room_data.get('length', 0.0)
180
+
181
+ col1, col2 = st.columns(2)
182
+ with col1:
183
+ st.metric("Ancho (m)", f"{w_m:.2f}")
184
+ with col2:
185
+ st.metric("Largo (m)", f"{l_m:.2f}")
186
+
187
+ # Mostrar el diagrama de planta
188
+ st.subheader("Planta de la habitación")
189
+ floor_plan_fig = logic.generar_diagrama_planta(st.session_state.room_data)
190
+ st.pyplot(floor_plan_fig)
191
+
192
+ # Formulario para añadir puertas y ventanas manualmente
193
+ st.subheader("Añadir puertas y ventanas manualmente")
194
+
195
+ polygon_points = st.session_state.room_data.get('polygon_points', [])
196
+ num_walls = len(polygon_points) if polygon_points is not None else 0
197
+
198
+ if num_walls > 0:
199
+ col_a, col_b, col_c, col_d = st.columns(4)
200
+
201
+ with col_a:
202
+ wall_options = [f"Pared {i+1}" for i in range(num_walls)]
203
+ selected_wall = st.selectbox("Seleccionar Pared", wall_options, key="wall_select")
204
+ wall_idx = int(selected_wall.split()[1]) - 1
205
+
206
+ with col_b:
207
+ obstacle_type = st.radio("Tipo", ["Puerta", "Ventana"], key="obs_type")
208
+
209
+ with col_c:
210
+ # Posición normalizada [0.0, 1.0]
211
+ position_pct = st.number_input("Posición (%)", min_value=0.0, max_value=100.0, value=50.0, step=5.0, key="obs_pos")
212
+
213
+ with col_d:
214
+ width_m = st.number_input("Ancho (m)", min_value=0.1, max_value=5.0, value=0.9, step=0.1, key="obs_width")
215
+
216
+ if st.button("Añadir elemento"):
217
+ # Los datos de centro están normalizados
218
+ new_obstacle = {
219
+ 'center': [position_pct / 100.0, wall_idx / max(1, num_walls)],
220
+ 'width': width_m
221
+ }
222
+
223
+ if obstacle_type == "Puerta":
224
+ st.session_state.room_data['doors'].append(new_obstacle)
225
+ else:
226
+ st.session_state.room_data['windows'].append(new_obstacle)
227
+
228
+ st.success(f"{obstacle_type} añadida a {selected_wall}")
229
+ st.rerun()
230
+ else:
231
+ st.warning("No se detectaron paredes en el polígono.")
232
+
233
+ # Editor de datos para modificar obstáculos detectados/añadidos
234
+ st.subheader("Editar elementos (puertas y ventanas)")
235
+ st.info("Ajusta las coordenadas de los obstáculos. Los valores X/Y están normalizados [0.0, 1.0].")
236
+
237
+ # Preparar datos para st.data_editor
238
+ doors_data = []
239
+ for i, d in enumerate(st.session_state.room_data.get('doors', [])):
240
+ center_y = d['center'][1] if len(d['center']) > 1 else 0
241
+ doors_data.append({"ID": f"P{i}", "Tipo": "Puerta", "Centro X (Norm.)": d['center'][0], "Centro Y (Norm.)": center_y, "Ancho (m)": d['width']})
242
+
243
+ windows_data = []
244
+ for i, w in enumerate(st.session_state.room_data.get('windows', [])):
245
+ center_y = w['center'][1] if len(w['center']) > 1 else 0
246
+ windows_data.append({"ID": f"V{i}", "Tipo": "Ventana", "Centro X (Norm.)": w['center'][0], "Centro Y (Norm.)": center_y, "Ancho (m)": w['width']})
247
+
248
+ all_obstacles = doors_data + windows_data
249
+ df_obs = pd.DataFrame(all_obstacles)
250
+
251
+ col_config = {
252
+ "Centro X (Norm.)": st.column_config.NumberColumn("Centro X (Norm.)", help="Posición horizontal normalizada [0.0, 1.0]", format="%.2f"),
253
+ "Centro Y (Norm.)": st.column_config.NumberColumn("Centro Y (Norm.)", help="Posición vertical normalizada [0.0, 1.0]", format="%.2f"),
254
+ "Ancho (m)": st.column_config.NumberColumn("Ancho (m)", help="Ancho del obstáculo en metros", format="%.2f"),
255
+ }
256
+
257
+ edited_df = st.data_editor(df_obs, num_rows="dynamic", use_container_width=True, column_config=col_config)
258
+
259
+ if st.button("Confirmar geometría"):
260
+ # Reconstruir el diccionario room_data a partir del DataFrame editado
261
+ new_doors = []
262
+ new_windows = []
263
+ for index, row in edited_df.iterrows():
264
+ obj = {'center': [row['Centro X (Norm.)'], row['Centro Y (Norm.)']], 'width': row['Ancho (m)']}
265
+ if row['Tipo'] == 'Puerta': new_doors.append(obj)
266
+ else: new_windows.append(obj)
267
+
268
+ st.session_state.room_data['doors'] = new_doors
269
+ st.session_state.room_data['windows'] = new_windows
270
+ st.session_state.stage = 2
271
+ st.rerun()
272
+
273
+ # --- PASO 3: PRESUPUESTO Y GENERACIÓN DE LAYOUT/RECOMENDACIÓN ---
274
+ if st.session_state.stage >= 2:
275
+ st.header("3. Presupuesto y generación")
276
+
277
+ presupuesto = st.number_input("Presupuesto Máximo (€)", min_value=100.0, value=1000.0, step=100.0)
278
+
279
+ if st.button("Generar diseño"):
280
+ # Convertir dimensiones de m a cm para el LayoutEngine
281
+ w_cm = st.session_state.room_data.get('width', 0.0) * 100
282
+ l_cm = st.session_state.room_data.get('length', 0.0) * 100
283
+
284
+ if w_cm < 200 or l_cm < 200:
285
+ st.error("Las dimensiones de la habitación son demasiado pequeñas (mínimo 2x2m) o no fueron capturadas correctamente.")
286
+ else:
287
+ with st.spinner("Calculando distribución óptima y seleccionando muebles..."):
288
+ # 1. Inicializar motores
289
+ layout_engine = logic.LayoutEngine(st.session_state.data_manager.dimensiones_promedio)
290
+ recommender = logic.Recommender(st.session_state.muebles_df)
291
+
292
+ # 2. Sugerir el pack de muebles base
293
+ pack_sugerido = layout_engine.sugerir_pack(w_cm, l_cm)
294
+
295
+ # 3. Convertir obstáculos a polígonos para el motor
296
+ obs_layout = layout_engine.convertir_obstaculos(
297
+ st.session_state.room_data,
298
+ w_cm, l_cm,
299
+ polygon_points=st.session_state.room_data.get('polygon_points')
300
+ )
301
+
302
+ # 4. Generar el Layout
303
+ layout_plan, constraints, log_msgs = layout_engine.generar_layout(
304
+ w_cm, l_cm,
305
+ pack_sugerido,
306
+ obs_layout,
307
+ polygon_points=st.session_state.room_data.get('polygon_points')
308
+ )
309
+
310
+ # Mostrar Log de Generación
311
+ with st.expander("📝 Detalles de la Generación del Layout", expanded=False):
312
+ for msg in log_msgs:
313
+ if "✅" in msg: st.success(msg)
314
+ elif "❌" in msg: st.error(msg)
315
+ elif "⚠️" in msg: st.warning(msg)
316
+ else: st.text(msg)
317
+
318
+ if not layout_plan:
319
+ st.error("No se pudo generar una distribución válida para este espacio (demasiado pequeño o muchos obstáculos).")
320
+ else:
321
+ # 5. Recomendar productos (Knapsack para optimización de precio/estilo)
322
+ # Las 'constraints' se definen por los muebles que el layout PUDO colocar
323
+ best_combo = recommender.buscar_combinacion(constraints, presupuesto, top_n=1)
324
+
325
+ if not best_combo:
326
+ st.error("No se encontraron muebles que se ajusten al presupuesto y restricciones.")
327
+ else:
328
+ st.session_state.result_layout = layout_plan
329
+ st.session_state.result_items = best_combo[0]['items']
330
+ st.session_state.result_total = best_combo[0]['precio_total']
331
+ st.session_state.result_score = best_combo[0]['score']
332
+ st.session_state.stage = 3
333
+
334
+ # --- PASO 4: RESULTADOS Y VISUALIZACIÓN FINAL ---
335
+ if st.session_state.stage == 3:
336
+ st.divider()
337
+ st.header("Tu salón ideal")
338
+
339
+ # --- VISUALIZACIÓN 3D Interactiva (Plotly) ---
340
+ st.subheader("Visualización 3D Interactiva")
341
+
342
+ # Generar la figura 3D
343
+ fig_plotly = logic.generar_figura_3d_plotly(
344
+ st.session_state.result_layout,
345
+ st.session_state.room_data,
346
+ st.session_state.result_items
347
+ )
348
+
349
+ # Renderizar la figura de Plotly
350
+ st.plotly_chart(fig_plotly, use_container_width=True, theme="streamlit")
351
+
352
+ st.info("💡 Usa el ratón: Clic izquierdo para rotar, rueda para zoom.")
353
+
354
+ st.divider()
355
+
356
+ # --- LISTA DE COMPRA ---
357
+ st.subheader("Lista de Compra")
358
+
359
+ # Totales y Score de Diseño
360
+ c_tot1, c_tot2 = st.columns([2, 1])
361
+ with c_tot1:
362
+ st.markdown("### Total Estimado")
363
+ st.caption(f"Score de Diseño (Estilo + Puntuación Base): {st.session_state.result_score:.2f}/1.0")
364
+ with c_tot2:
365
+ st.markdown(f"### {st.session_state.result_total:.2f}€")
366
+
367
+ st.markdown("---")
368
+
369
+ # Listado de productos
370
+ for item in st.session_state.result_items:
371
+ with st.container():
372
+ c_img, c_info, c_price, c_link = st.columns([1, 2, 1, 1])
373
+
374
+ url = f"https://www.ikea.com/es/es/p/{item.get('Enlace_producto', '')}-{item.get('ID', '')}"
375
+ img_src = item.get('Imagen_principal', '')
376
+ nombre = item['Nombre']
377
+ tipo = item['Tipo_mueble']
378
+ precio = float(item['Precio'])
379
+
380
+ with c_img:
381
+ if img_src:
382
+ st.image(img_src, width=150)
383
+ else:
384
+ st.text("Sin imagen")
385
+
386
+ with c_info:
387
+ st.subheader(nombre)
388
+ st.caption(tipo)
389
+ st.text(item.get('Descripcion', '')[:100] + '...')
390
+
391
+ with c_price:
392
+ st.markdown(f"### {precio:.2f} €")
393
+
394
+ with c_link:
395
+ st.link_button("Ver en IKEA", url)
396
+
397
+ st.divider()
398
+
399
+ if st.button("Reiniciar"):
400
+ for key in ['room_data', 'result_layout', 'result_items', 'result_total', 'result_score']:
401
+ if key in st.session_state:
402
+ del st.session_state[key]
403
+ st.session_state.stage = 0
404
+ st.rerun()
generate_cache.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import logic
4
+
5
+ # Configurar rutas
6
+ base_dir = os.path.dirname(__file__)
7
+ csv_path = os.path.join(base_dir, "data", "furniture_data.csv")
8
+ model_path = os.path.join(base_dir, "models", "bert_style_encoder.pth")
9
+ cache_path = os.path.join(base_dir, "vectores_cache.pkl")
10
+
11
+ print("Iniciando generación de caché...")
12
+ print(f"CSV: {csv_path}")
13
+ print(f"Modelo: {model_path}")
14
+
15
+ # Inicializar DataManager
16
+ dm = logic.DataManager(csv_path, cache_path, model_path)
17
+
18
+ # Esto forzará la generación y guardado del pickle
19
+ df = dm.cargar_datos()
20
+
21
+ print(f"Caché generado exitosamente en: {cache_path}")
22
+ print(f"Total items: {len(df)}")
logic.py ADDED
@@ -0,0 +1,1470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import os
4
+ import itertools
5
+ import pickle
6
+ import torch
7
+ import torch.nn as nn
8
+ from transformers import BertModel, BertTokenizer
9
+ from sklearn.metrics.pairwise import cosine_similarity
10
+ import matplotlib.pyplot as plt
11
+ from shapely.geometry import Polygon, LineString, Point
12
+ from tqdm import tqdm
13
+ import sys
14
+ from PIL import Image, ImageDraw
15
+ import plotly.graph_objects as go
16
+ import pywavefront
17
+
18
+ # --- CONFIGURACIÓN DE RUTAS EXTERNAS ---
19
+ # En despliegue, HorizonNet está en un subdirectorio local
20
+ HORIZON_NET_PATH = os.path.join(os.path.dirname(__file__), 'horizonnet')
21
+ MODEL_DIR = os.path.join(os.path.dirname(__file__), 'modelos_3D')
22
+
23
+ if HORIZON_NET_PATH not in sys.path:
24
+ sys.path.append(HORIZON_NET_PATH)
25
+
26
+ try:
27
+ # Importar desde el paquete local horizonnet
28
+ from horizonnet.model import HorizonNet
29
+ from horizonnet.inference import inference
30
+ from horizonnet.misc import utils
31
+ except ImportError as e:
32
+ print(f"Error al importar HorizonNet desde {HORIZON_NET_PATH}")
33
+ print(f"Detalle: {e}")
34
+ # Definición de clase MOCK para evitar un crash de la aplicación
35
+ class RoomLayoutDetector:
36
+ def __init__(self, model_path):
37
+ print("RoomLayoutDetector en modo MOCK (Error de importación)")
38
+ def detect_layout(self, img_path): return None
39
+
40
+ # ==========================================
41
+ # CLASE DE DETECCIÓN DE LAYOUT (HorizonNet)
42
+ # ==========================================
43
+ class RoomLayoutDetector:
44
+ """
45
+ Clase para la detección de geometría de habitación (floor/ceiling boundaries)
46
+ y corners a partir de una imagen panorámica 360 usando HorizonNet.
47
+ """
48
+ def __init__(self, model_path):
49
+ # Utiliza MPS (Metal Performance Shaders) si está disponible en M4
50
+ self.device = torch.device('cpu')
51
+ if torch.backends.mps.is_available():
52
+ self.device = torch.device('mps')
53
+
54
+ print(f"Cargando modelo desde: {model_path} en {self.device}")
55
+ try:
56
+ self.net = utils.load_trained_model(HorizonNet, model_path).to(self.device)
57
+ self.net.eval()
58
+ except Exception as e:
59
+ print(f"Error cargando modelo: {e}")
60
+ self.net = None
61
+
62
+ def detect_layout(self, img_path):
63
+ """Ejecuta la inferencia de HorizonNet y escala los resultados a metros."""
64
+ if self.net is None: return None
65
+
66
+ # 1. Preprocesar imagen
67
+ try:
68
+ img_pil = Image.open(img_path)
69
+ if img_pil.size != (1024, 512):
70
+ img_pil = img_pil.resize((1024, 512), Image.BICUBIC)
71
+ img_ori = np.array(img_pil)[..., :3].transpose([2, 0, 1]).copy()
72
+ x = torch.FloatTensor([img_ori / 255])
73
+
74
+ # 2. Inferencia
75
+ with torch.no_grad():
76
+ cor_id, z0, z1, vis_out = inference(
77
+ net=self.net, x=x, device=self.device,
78
+ flip=False, rotate=[], visualize=False,
79
+ force_cuboid=False, force_raw=False,
80
+ min_v=None, r=0.05
81
+ )
82
+
83
+ # 3. Procesar resultados: Obtener polígono del suelo
84
+ uv = [[float(u), float(v)] for u, v in cor_id]
85
+ floor_points = self._uv_to_floor_polygon(uv, z0, z1)
86
+
87
+ # 4. Calcular dimensiones y escalar a metros
88
+ min_x, min_y = floor_points.min(axis=0)
89
+ max_x, max_y = floor_points.max(axis=0)
90
+ ancho_bbox = max_x - min_x
91
+ largo_bbox = max_y - min_y
92
+ altura_unidades = abs(z1 - z0)
93
+
94
+ # Factor de escala: Se asume altura de cámara de 1.6m (z0)
95
+ ALTURA_CAMARA = 1.6
96
+ factor_escala = ALTURA_CAMARA / z0
97
+
98
+ ancho_m = ancho_bbox * factor_escala
99
+ largo_m = largo_bbox * factor_escala
100
+ altura_m = altura_unidades * factor_escala
101
+
102
+ # Escalar puntos para visualización 3D y normalizar para 2D (planta)
103
+ floor_points_scaled = floor_points * factor_escala
104
+ # Para la planta 2D, normalizamos para que empiece en (0,0) y esté en metros
105
+ floor_points_norm = (floor_points_scaled - [floor_points_scaled[:,0].min(), floor_points_scaled[:,1].min()])
106
+
107
+ # Obtener datos raw para la visualización de la detección
108
+ x_tensor = x.to(self.device)
109
+ y_bon_, y_cor_ = self.net(x_tensor)
110
+ y_bon_ = y_bon_.cpu().detach().numpy()[0]
111
+ y_cor_ = torch.sigmoid(y_cor_).cpu().detach().numpy()[0, 0]
112
+
113
+ return {
114
+ 'width': ancho_m,
115
+ 'length': largo_m,
116
+ 'height': altura_m,
117
+ 'doors': [], 'windows': [], # Estos deberían ser inferidos en tu versión completa
118
+ 'y_bon': y_bon_, 'y_cor': y_cor_,
119
+ 'polygon_points': floor_points_norm.tolist(),
120
+ 'polygon_points_raw': floor_points_scaled.tolist(),
121
+ 'factor_escala': factor_escala
122
+ }
123
+
124
+ except Exception as e:
125
+ print(f"Error en inferencia: {e}")
126
+ import traceback
127
+ traceback.print_exc()
128
+ return None
129
+
130
+ def _uv_to_floor_polygon(self, uv, z0, z1):
131
+ """Convierte los puntos uv (coordenadas de la imagen) en coordenadas (x,y) del plano del suelo."""
132
+ floor_points = []
133
+ for i in range(0, len(uv), 2):
134
+ u = uv[i][0]
135
+ v_floor = uv[i+1][1]
136
+ lon = (u - 0.5) * 2 * np.pi
137
+ lat = (0.5 - v_floor) * np.pi
138
+ # Fórmula de proyección esférica
139
+ r = abs(z0 / np.tan(lat)) if np.tan(lat) != 0 else 0
140
+ x = r * np.cos(lon)
141
+ y = r * np.sin(lon)
142
+ floor_points.append([x, y])
143
+ return np.array(floor_points)
144
+
145
+ # ==========================================
146
+ # 1. MODELO DE ESTILO (Encoder basado en BERT)
147
+ # ==========================================
148
+ class StyleEncoder(nn.Module):
149
+ """
150
+ Encoder de estilo basado en BERT para generar un vector de embedding
151
+ a partir de la descripción de un mueble.
152
+ """
153
+ def __init__(self, n_dims=128):
154
+ super(StyleEncoder, self).__init__()
155
+ self.bert = BertModel.from_pretrained('bert-base-multilingual-cased')
156
+ self.fc = nn.Linear(self.bert.config.hidden_size, n_dims)
157
+
158
+ def forward(self, input_ids, attention_mask):
159
+ bert_output = self.bert(input_ids=input_ids, attention_mask=attention_mask)
160
+ pooler_output = bert_output[1] # Vector [CLS]
161
+ vector_estilo = self.fc(pooler_output)
162
+ return vector_estilo
163
+
164
+ # ==========================================
165
+ # 2. GESTOR DE DATOS Y CARGA
166
+ # ==========================================
167
+ class DataManager:
168
+ """Gestiona la carga de la base de datos, la vectorización y el cacheo."""
169
+ def __init__(self, csv_path, vectors_cache_path, bert_model_path):
170
+ self.csv_path = csv_path
171
+ self.cache_path = vectors_cache_path
172
+ self.bert_model_path = bert_model_path
173
+ self.df_muebles = None
174
+ self.dimensiones_promedio = {}
175
+
176
+ # Tipos de muebles relevantes para el layout del salón
177
+ self.muebles_a_usar = [
178
+ 'Sofás', 'Sillones', 'Muebles de salón',
179
+ 'Mesas bajas de salón, de centro y auxiliares',
180
+ 'Estanterías y librerías'
181
+ ]
182
+
183
+ def cargar_datos(self):
184
+ """Carga los vectores desde caché o los genera usando el StyleEncoder."""
185
+ if os.path.exists(self.cache_path):
186
+ print(f"Cargando caché de: {self.cache_path}")
187
+ with open(self.cache_path, 'rb') as f:
188
+ self.df_muebles = pickle.load(f)
189
+ else:
190
+ print("Generando vectores (esto puede tardar)...")
191
+ self._generar_vectores()
192
+
193
+ # Filtrar sofás excesivamente grandes (> 300cm) que rompen el layout en habitaciones normales
194
+ if self.df_muebles is not None:
195
+ self.df_muebles = self.df_muebles[~((self.df_muebles['Tipo_mueble'] == 'Sofás') & (self.df_muebles['Ancho'] > 300))]
196
+
197
+ # Pre-procesar columnas de dimensiones para asegurar que son numéricas y válidas
198
+ if self.df_muebles is not None:
199
+ cols_dim = ['Ancho', 'Largo', 'Altura']
200
+ for col in cols_dim:
201
+ self.df_muebles[col] = pd.to_numeric(self.df_muebles[col], errors='coerce')
202
+ self.df_muebles.loc[self.df_muebles[col] <= 0, col] = np.nan
203
+
204
+ # Calcular dimensiones promedio por categoría
205
+ if self.df_muebles is not None:
206
+ avg_df = self.df_muebles.groupby('Tipo_mueble')[['Ancho', 'Largo']].mean()
207
+ self.dimensiones_promedio = avg_df.to_dict('index')
208
+
209
+ # Normalizar claves a minúsculas para evitar errores de key y aplicar lógica de negocio
210
+ processed_dims = {}
211
+ for k, v in self.dimensiones_promedio.items():
212
+ ancho = round(v.get('Ancho', 100.0), 1)
213
+ largo = round(v.get('Largo', 50.0), 1)
214
+
215
+ # Correcciones de lógica de negocio o datos faltantes (en cm)
216
+ if k == 'Sofás':
217
+ if largo < 50: largo = 90.0
218
+ if k == 'Sillones':
219
+ if largo < 40: largo = ancho if ancho >= 40 else 70.0
220
+
221
+ processed_dims[k] = {'ancho': ancho, 'largo': largo}
222
+ self.dimensiones_promedio = processed_dims
223
+
224
+ # Imputar valores faltantes o inválidos en el DataFrame con los promedios calculados
225
+ if self.df_muebles is not None:
226
+ for tipo, dims in self.dimensiones_promedio.items():
227
+ mask_tipo = self.df_muebles['Tipo_mueble'] == tipo
228
+
229
+ # Imputar Ancho
230
+ mask_invalid_w = mask_tipo & (self.df_muebles['Ancho'].isna())
231
+ if mask_invalid_w.any():
232
+ self.df_muebles.loc[mask_invalid_w, 'Ancho'] = dims['ancho']
233
+
234
+ # Imputar Largo
235
+ mask_invalid_l = mask_tipo & (self.df_muebles['Largo'].isna() | (self.df_muebles['Largo'] <= 0))
236
+ if mask_invalid_l.any():
237
+ self.df_muebles.loc[mask_invalid_l, 'Largo'] = dims['largo']
238
+
239
+ # Imputar Altura (opcional, pero bueno para consistencia)
240
+ # mask_invalid_h = mask_tipo & (self.df_muebles['Altura'].isna() | (self.df_muebles['Altura'] <= 0))
241
+ # if mask_invalid_h.any():
242
+ # self.df_muebles.loc[mask_invalid_h, 'Altura'] = 60 # Valor por defecto seguro
243
+
244
+ return self.df_muebles
245
+
246
+ def _generar_vectores(self, n_dims=128):
247
+ """Procesa el CSV y genera el vector de estilo para cada mueble."""
248
+ if not os.path.exists(self.csv_path):
249
+ raise FileNotFoundError(f"No se encuentra el CSV en {self.csv_path}")
250
+
251
+ df = pd.read_csv(self.csv_path)
252
+ df_filtrado = df[df['Tipo_mueble'].isin(self.muebles_a_usar)].copy()
253
+
254
+ # Carga modelo BERT
255
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
256
+ model = StyleEncoder(n_dims=n_dims).to(device)
257
+
258
+ if os.path.exists(self.bert_model_path):
259
+ model.load_state_dict(torch.load(self.bert_model_path, map_location=device))
260
+ else:
261
+ print("ADVERTENCIA: No se encontraron pesos del modelo BERT, usando aleatorios.")
262
+
263
+ tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')
264
+ model.eval()
265
+
266
+ df_filtrado['text_data'] = df_filtrado['Nombre'].fillna('') + ' ' + df_filtrado['Descripcion'].fillna('')
267
+ generated_vectors = []
268
+
269
+ with torch.no_grad():
270
+ for text in tqdm(df_filtrado['text_data'], desc="Vectorizando"):
271
+ tokens = tokenizer(text, padding='max_length', truncation=True, max_length=64, return_tensors='pt')
272
+ input_ids = tokens['input_ids'].to(device)
273
+ attention_mask = tokens['attention_mask'].to(device)
274
+ vector = model(input_ids, attention_mask)
275
+ generated_vectors.append(vector.cpu().detach().numpy().flatten())
276
+
277
+ df_filtrado['vector_estilo'] = generated_vectors
278
+ df_filtrado['vector_estilo'] = df_filtrado['vector_estilo'].apply(lambda x: np.array(x))
279
+
280
+ self.df_muebles = df_filtrado
281
+ # Guardar caché
282
+ try:
283
+ with open(self.cache_path, 'wb') as f:
284
+ pickle.dump(self.df_muebles, f)
285
+ except Exception as e:
286
+ print(f"Advertencia: No se pudo guardar la caché de vectores: {e}")
287
+
288
+
289
+ def _calcular_dimensiones_promedio(self):
290
+ """Calcula el ancho y largo promedio por Tipo_mueble."""
291
+ if self.df_muebles is None: return
292
+
293
+ cols = ['Ancho', 'Largo', 'Altura']
294
+ for col in cols:
295
+ self.df_muebles[col] = pd.to_numeric(self.df_muebles[col], errors='coerce')
296
+ # Reemplazar valores <= 0 con NaN para no afectar el promedio
297
+ self.df_muebles.loc[self.df_muebles[col] <= 0, col] = np.nan
298
+
299
+ avg_df = self.df_muebles.groupby('Tipo_mueble')[cols].mean()
300
+
301
+ self.dimensiones_promedio = {}
302
+ for tipo, row in avg_df.iterrows():
303
+ self.dimensiones_promedio[tipo] = {
304
+ 'nombre': tipo,
305
+ 'ancho': round(row['Ancho'], 1) if not pd.isna(row['Ancho']) else 100.0,
306
+ 'largo': round(row['Largo'], 1) if not pd.isna(row['Largo']) else 50.0
307
+ }
308
+
309
+ # Correcciones de lógica de negocio o datos faltantes (en cm)
310
+ if 'Sofás' in self.dimensiones_promedio:
311
+ if self.dimensiones_promedio['Sofás']['largo'] < 50: self.dimensiones_promedio['Sofás']['largo'] = 90.0
312
+ if 'Sillones' in self.dimensiones_promedio:
313
+ if self.dimensiones_promedio['Sillones']['largo'] < 40:
314
+ self.dimensiones_promedio['Sillones']['largo'] = self.dimensiones_promedio['Sillones']['ancho'] if self.dimensiones_promedio['Sillones']['ancho'] >= 40 else 70.0
315
+
316
+ # ==========================================
317
+ # 3. MOTOR DE LAYOUT (Lógica Espacial y de Colocación)
318
+ # ==========================================
319
+ class LayoutEngine:
320
+ """Implementa la lógica de colocación de muebles, restricciones espaciales y colisiones."""
321
+ def __init__(self, dimensiones_promedio):
322
+ self.dim_promedio = dimensiones_promedio
323
+ self.config = {
324
+ 'pasillo_minimo': 90, # cm
325
+ 'margen_pared': 10, # cm
326
+ 'margen_obstaculo': 20, # cm
327
+ 'distancia_tv_sofa': 280 # cm (distancia ideal)
328
+ }
329
+
330
+ def sugerir_pack(self, ancho_cm, largo_cm):
331
+ """Sugiere un conjunto de muebles base según el área de la habitación."""
332
+ area = (ancho_cm * largo_cm) / 10000.0
333
+ # Definición de tipos de mueble base
334
+ pack = [{'tipo': 'Muebles de salón'}, {'tipo': 'Mesas bajas de salón, de centro y auxiliares'}, {'tipo': 'Sofás'}]
335
+ # Añadir complejidad según el tamaño de la sala
336
+ if area > 16.0: pack.insert(0, {'tipo': 'Sillones'})
337
+ if area > 22.0: pack.insert(0, {'tipo': 'Estanterías y librerías'})
338
+ return pack
339
+
340
+ def convertir_obstaculos(self, obstaculos_dict, ancho_hab, largo_hab, polygon_points):
341
+ """Convierte los obstáculos detectados (puertas/ventanas) en polígonos Shapely con margen de seguridad."""
342
+ obs_polys = []
343
+ num_walls = len(polygon_points)
344
+
345
+ todos_obs = []
346
+ for d in obstaculos_dict.get('doors', []): d['type'] = 'door'; todos_obs.append(d)
347
+ for w in obstaculos_dict.get('windows', []): w['type'] = 'window'; todos_obs.append(w)
348
+
349
+ for obs in todos_obs:
350
+ # Lógica para mapear la posición normalizada (0-1) a un polígono en CM
351
+ w_idx = int(round(obs['center'][1] * num_walls)) % num_walls
352
+ p1 = np.array(polygon_points[w_idx]) * 100
353
+ p2 = np.array(polygon_points[(w_idx + 1) % num_walls]) * 100
354
+
355
+ vec_pared = p2 - p1
356
+ len_pared = np.linalg.norm(vec_pared)
357
+ unit_pared = vec_pared / len_pared
358
+
359
+ # Centro del obstáculo a lo largo de la pared
360
+ center_pt = p1 + vec_pared * obs['center'][0]
361
+ width = obs['width'] * 100
362
+ depth = 250 if obs['type'] == 'door' else 30 # Profundidad de la zona de exclusión (250cm = ~1.25m dentro de la habitación)
363
+
364
+ # Vector normal a la pared
365
+ normal = np.array([-unit_pared[1], unit_pared[0]])
366
+
367
+ # Definir las esquinas del polígono de exclusión (con margen)
368
+ c1 = center_pt - unit_pared * (width/2) - normal * (depth/2)
369
+ c2 = center_pt + unit_pared * (width/2) - normal * (depth/2)
370
+ c3 = center_pt + unit_pared * (width/2) + normal * (depth/2)
371
+ c4 = center_pt - unit_pared * (width/2) + normal * (depth/2)
372
+
373
+ poly = Polygon([c1, c2, c3, c4])
374
+ obs_polys.append({'poly': poly, 'tipo': obs['type']})
375
+
376
+ return obs_polys
377
+
378
+ def _get_poly_from_rect(self, x, y, w, l, angle_rad):
379
+ """Genera un Polygon de Shapely rotado a partir del centro (x, y), dimensiones (w, l) y ángulo."""
380
+ cx, cy = x, y
381
+ dx = w / 2
382
+ dy = l / 2
383
+
384
+ corners = [
385
+ (dx, dy), (-dx, dy), (-dx, -dy), (dx, -dy)
386
+ ]
387
+
388
+ new_corners = []
389
+ c_cos = np.cos(angle_rad)
390
+ c_sin = np.sin(angle_rad)
391
+
392
+ for px, py in corners:
393
+ nx = px * c_cos - py * c_sin + cx
394
+ ny = px * c_sin + py * c_cos + cy
395
+ new_corners.append((nx, ny))
396
+
397
+ return Polygon(new_corners)
398
+
399
+ def _check_collision(self, candidate_poly, room_poly, placed_items, obstacles):
400
+ """Verifica si el polígono candidato colisiona con la pared, ítems colocados u obstáculos."""
401
+ # 1. Dentro de la habitación (con margen de pared)
402
+ buffered_room = room_poly.buffer(-self.config['margen_pared'])
403
+ if not buffered_room.contains(candidate_poly):
404
+ # print(f"DEBUG: Colisión con PARED. Poly fuera del buffer.")
405
+ # print(f" Room Buffer Bounds: {buffered_room.bounds}")
406
+ # print(f" Candidate Bounds: {candidate_poly.bounds}")
407
+ return False
408
+
409
+ # 2. Colisión con items ya colocados
410
+ for item in placed_items:
411
+ # Usar un buffer de 10cm para asegurar un pequeño espacio entre muebles
412
+ if candidate_poly.buffer(10).intersects(item['poly']):
413
+ # print(f"DEBUG: Colisión con ITEM {item['tipo']}.")
414
+ return False
415
+
416
+ # 3. Colisión con obstáculos (con margen)
417
+ for obs in obstacles:
418
+ if candidate_poly.intersects(obs['poly']):
419
+ # print(f"DEBUG: Colisión con OBSTÁCULO {obs['tipo']}.")
420
+ return False
421
+
422
+ return True
423
+
424
+ def _scan_wall(self, p1, p2, item_dim, room_poly, placed, obstacles, align_dist=None, align_target=None):
425
+ """Barre una pared específica buscando la primera ubicación válida para un mueble."""
426
+ vec = p2 - p1
427
+ wall_len = np.linalg.norm(vec)
428
+ unit_vec = vec / wall_len
429
+
430
+ normal = np.array([-unit_vec[1], unit_vec[0]])
431
+
432
+ # Verificar que la normal apunta al interior de la habitación
433
+ centroid = np.array(room_poly.centroid.coords[0])
434
+ mid_wall = (p1 + p2) / 2
435
+ if np.dot(centroid - mid_wall, normal) < 0:
436
+ normal = -normal
437
+
438
+ w_item = item_dim['ancho']
439
+ l_item = item_dim['largo']
440
+ angle = np.arctan2(unit_vec[1], unit_vec[0])
441
+
442
+ # Distancia del centro del mueble a la pared (para pegar a la pared)
443
+ dist_from_wall = self.config['margen_pared'] + l_item/2
444
+ if align_dist: dist_from_wall = align_dist
445
+
446
+ step = 20 # cm
447
+ margin_side = self.config['margen_pared'] + w_item/2
448
+
449
+ range_start = margin_side
450
+ range_end = wall_len - margin_side
451
+
452
+ if range_end < range_start: return []
453
+
454
+ candidates = list(np.arange(range_start, range_end, step))
455
+ # Asegurar que el centro de la pared está en los candidatos
456
+ mid_dist = wall_len / 2
457
+ if range_start <= mid_dist <= range_end:
458
+ candidates.append(mid_dist)
459
+ # Ordenar para probar primero el centro? No necesariamente, pero ayuda.
460
+ candidates = sorted(list(set(candidates)))
461
+
462
+ if align_target is not None:
463
+ # Lógica para alinear con un objeto existente
464
+ v_target = np.array([align_target['x'], align_target['y']]) - p1
465
+ proj_dist = np.dot(v_target, unit_vec)
466
+ candidates = [proj_dist]
467
+
468
+ valid_candidates = []
469
+ for dist_along in candidates:
470
+ center = p1 + unit_vec * dist_along + normal * dist_from_wall
471
+ cand_poly = self._get_poly_from_rect(center[0], center[1], w_item, l_item, angle)
472
+
473
+ if self._check_collision(cand_poly, room_poly, placed, obstacles):
474
+ valid_candidates.append({
475
+ 'x': center[0], 'y': center[1],
476
+ 'ancho': w_item, 'largo': l_item,
477
+ 'angle': angle,
478
+ 'tipo': item_dim['nombre'],
479
+ 'poly': cand_poly
480
+ })
481
+ return valid_candidates
482
+
483
+ def generar_layout(self, ancho_hab, largo_hab, pack_sugerido, obs_layout, polygon_points=None):
484
+ """Genera el layout buscando una configuración TV-Sofá válida y añadiendo la mesa de centro."""
485
+ # setup básico
486
+ layout = []
487
+ constraints = []
488
+ log = []
489
+ final_layout_objs = []
490
+
491
+ if not polygon_points:
492
+ # Usar un rectángulo simple si no hay polígono
493
+ polygon_points = [[0,0], [ancho_hab/100, 0], [ancho_hab/100, largo_hab/100], [0, largo_hab/100]]
494
+
495
+ poly_pts_cm = np.array(polygon_points) * 100
496
+ room_poly = Polygon(poly_pts_cm)
497
+ num_walls = len(poly_pts_cm)
498
+
499
+ # Dimensiones promedio de los dos muebles clave
500
+ d_tv = self.dim_promedio.get('Muebles de salón', {'ancho': 120, 'largo': 40})
501
+ d_tv['nombre'] = 'Muebles de salón'
502
+ d_sofa = self.dim_promedio.get('Sofás', {'ancho': 200, 'largo': 90})
503
+ d_sofa['nombre'] = 'Sofás'
504
+
505
+ # Estrategia de reintento con tamaños reducidos
506
+ attempt_configs = [
507
+ {'scale': 1.0, 'desc': 'Standard'},
508
+ {'scale': 0.8, 'desc': 'Compact'}
509
+ ]
510
+
511
+ best_overall_score = -1
512
+ best_overall_layout = []
513
+
514
+ for config in attempt_configs:
515
+ scale = config['scale']
516
+ # Aplicar escala a las dimensiones temporales para este intento
517
+ current_d_tv = d_tv.copy()
518
+ current_d_tv['ancho'] *= scale
519
+ current_d_tv['largo'] *= scale
520
+
521
+ current_d_sofa = d_sofa.copy()
522
+ current_d_sofa['ancho'] *= scale
523
+ current_d_sofa['largo'] *= scale
524
+
525
+ log.append(f"🔄 Intentando generación con modo {config['desc']} (Escala {scale})")
526
+
527
+ best_score = -1
528
+ best_layout = []
529
+
530
+ # Iterar sobre todas las paredes para encontrar la mejor ubicación para el binomio TV-Sofá
531
+ for i in range(num_walls):
532
+ p1 = poly_pts_cm[i]
533
+ p2 = poly_pts_cm[(i+1)%num_walls]
534
+
535
+ # 1. Intentar poner Mueble de Salón (TV) en la pared
536
+ # Ahora devuelve una lista de candidatos
537
+ tv_candidates = self._scan_wall(p1, p2, current_d_tv, room_poly, [], obs_layout)
538
+
539
+ for tv_pos in tv_candidates:
540
+ current_layout = [tv_pos]
541
+
542
+ # Calcular la normal del TV
543
+ vec_pared = p2 - p1
544
+ unit_vec_pared = vec_pared / np.linalg.norm(vec_pared)
545
+ normal_base = np.array([-unit_vec_pared[1], unit_vec_pared[0]])
546
+
547
+ centroid = np.array(room_poly.centroid.coords[0])
548
+ mid_wall = (p1 + p2) / 2
549
+
550
+ # Asegurar que la normal apunta al centro (adentro)
551
+ if np.linalg.norm((mid_wall + normal_base) - centroid) > np.linalg.norm((mid_wall - normal_base) - centroid):
552
+ tv_normal = -normal_base
553
+ else:
554
+ tv_normal = normal_base
555
+
556
+ # 2. Calcular dónde estaría el sofá y proyectar un rayo
557
+ tv_center_pt = Point(tv_pos['x'], tv_pos['y'])
558
+ ray_end_np = np.array([tv_pos['x'], tv_pos['y']]) + tv_normal * max(ancho_hab, largo_hab) * 100
559
+ ray = LineString([tv_center_pt, (ray_end_np[0], ray_end_np[1])])
560
+
561
+ intersection = ray.intersection(room_poly.boundary)
562
+
563
+ distancia_pared_opuesta = 9999
564
+
565
+ if not intersection.is_empty:
566
+ if intersection.geom_type == 'Point':
567
+ d = tv_center_pt.distance(intersection)
568
+ if d > 50: distancia_pared_opuesta = d
569
+ elif intersection.geom_type == 'MultiPoint':
570
+ for pt in intersection.geoms:
571
+ d = tv_center_pt.distance(pt)
572
+ if d > 50 and d < distancia_pared_opuesta:
573
+ distancia_pared_opuesta = d
574
+
575
+ dist_ideal = self.config['distancia_tv_sofa']
576
+ fondo_sofa = current_d_sofa['largo']
577
+
578
+ # Calcular el espacio libre entre la parte trasera del sofá y la pared
579
+ espacio_detras = distancia_pared_opuesta - (tv_pos['largo']/2 + dist_ideal + fondo_sofa/2)
580
+
581
+ dist_sofa_desde_tv = dist_ideal
582
+
583
+ if distancia_pared_opuesta < (tv_pos['largo']/2 + dist_ideal + fondo_sofa + self.config['margen_pared']):
584
+ # Si la habitación es demasiado pequeña, pega el sofá a la pared trasera
585
+ # Corrección: No restar tv_pos['largo']/2 porque la distancia es desde el centro de la TV
586
+ dist_sofa_desde_tv = distancia_pared_opuesta - fondo_sofa/2 - self.config['margen_pared']
587
+ log_msg = f"✅ Sofá ajustado a pared (Espacio insuficiente para ideal)"
588
+ elif espacio_detras < 100: # Aumentado a 100cm. Si sobra menos de 1m, pégalo atrás.
589
+ # Corrección: Añadir 5cm extra de margen para asegurar que el polígono esté DENTRO del buffer de la habitación
590
+ dist_sofa_desde_tv = distancia_pared_opuesta - fondo_sofa/2 - self.config['margen_pared'] - 5.0
591
+ log_msg = f"✅ Sofá ajustado a pared (Evitar espacio muerto de {espacio_detras:.0f}cm)"
592
+ else:
593
+ # Posicionamiento ideal frente a TV
594
+ dist_sofa_desde_tv = dist_ideal + tv_pos['largo']/2 + fondo_sofa/2
595
+ log_msg = "✅ Sofá en isla"
596
+
597
+
598
+ # Intentar colocar el sofá con "nudge" (empujoncitos) SOLO frontal para mantener alineación
599
+ sofa_placed = False
600
+ # Nudge frontal: 0 a 30cm
601
+ for nudge in [0, 5, 10, 15, 20, 25, 30]:
602
+ current_dist = dist_sofa_desde_tv - nudge
603
+
604
+ sofa_center_np = np.array([tv_pos['x'], tv_pos['y']]) + tv_normal * current_dist
605
+ sofa_poly = self._get_poly_from_rect(sofa_center_np[0], sofa_center_np[1], current_d_sofa['ancho'], current_d_sofa['largo'], tv_pos['angle'])
606
+
607
+ sofa_cand = {
608
+ 'x': sofa_center_np[0], 'y': sofa_center_np[1],
609
+ 'ancho': current_d_sofa['ancho'], 'largo': current_d_sofa['largo'],
610
+ 'angle': tv_pos['angle'], 'tipo': 'Sofás', 'poly': sofa_poly
611
+ }
612
+
613
+ if self._check_collision(sofa_poly, room_poly, [tv_pos], obs_layout):
614
+ current_layout.append(sofa_cand)
615
+ score = 100 - nudge
616
+ if score > best_score:
617
+ best_score = score
618
+ best_layout = current_layout
619
+ log.append(f"{log_msg} (Nudge={nudge}cm)")
620
+ sofa_placed = True
621
+ break
622
+
623
+ if sofa_placed:
624
+ break # Romper el loop de TV candidates si ya encontramos un layout válido
625
+ else:
626
+ log.append(f"❌ Sofá colisiona tras intentos. DistBase={dist_sofa_desde_tv:.1f}")
627
+ # print(f"DEBUG: Fallo Sofá. Dist={dist_sofa_desde_tv:.1f}. Wall={i}")
628
+
629
+ if best_layout:
630
+ best_overall_layout = best_layout
631
+ best_overall_score = best_score
632
+ break # Si encontramos un layout válido con esta escala, nos quedamos con él
633
+
634
+ best_layout = best_overall_layout # Restaurar para el resto del código
635
+
636
+ if best_layout:
637
+ # 2. Convertir layout a formato final y generar restricciones
638
+ for item in best_layout:
639
+ final_layout_objs.append({
640
+ 'x': item['x'], 'y': item['y'],
641
+ 'ancho': item['ancho'], 'largo': item['largo'],
642
+ 'angle': item['angle'], 'tipo': item['tipo']
643
+ })
644
+ # Definir la restricción dimensional
645
+ constraints.append({'tipo': item['tipo'], 'max_ancho': item['ancho']*1.2, 'max_largo': item['largo']*1.2})
646
+
647
+ # 3. Colocación condicional de Mesa de Centro
648
+ tv = best_layout[0]
649
+ sofa = best_layout[1]
650
+
651
+ # Calcular la distancia libre entre TV y Sofá
652
+ dist_centros = np.linalg.norm(np.array([tv['x'], tv['y']]) - np.array([sofa['x'], sofa['y']]))
653
+ depth_tv = tv['largo']
654
+ depth_sofa = sofa['largo']
655
+
656
+ espacio_libre = dist_centros - (depth_tv / 2) - (depth_sofa / 2)
657
+
658
+ profundidad_mesa = self.dim_promedio.get('Mesas bajas de salón, de centro y auxiliares', {'largo': 60})['largo']
659
+ pasillo_minimo = 60 # cm para circular alrededor
660
+
661
+ if espacio_libre >= (profundidad_mesa + pasillo_minimo):
662
+ mid_x = (tv['x'] + sofa['x']) / 2
663
+ mid_y = (tv['y'] + sofa['y']) / 2
664
+
665
+ final_layout_objs.append({
666
+ 'x': mid_x, 'y': mid_y,
667
+ 'ancho': 100, 'largo': profundidad_mesa, # Usamos ancho y largo genérico
668
+ 'angle': tv['angle'],
669
+ 'tipo': 'Mesas bajas de salón, de centro y auxiliares'
670
+ })
671
+ constraints.append({'tipo': 'Mesas bajas de salón, de centro y auxiliares'})
672
+ else:
673
+ log.append(f"⚠️ Mesa de centro omitida: Espacio libre ({espacio_libre:.0f}cm) insuficiente para mesa + paso.")
674
+
675
+ else:
676
+ log.append("No se encontró distribución válida TV-Sofá. Distribución fallida.")
677
+
678
+ return final_layout_objs, constraints, log
679
+
680
+ # ==========================================
681
+ # 4. MOTOR DE RECOMENDACIÓN (Knapsack/Estilo)
682
+ # ==========================================
683
+ class Recommender:
684
+ """Implementa el algoritmo de selección de productos para maximizar el Score/Coherencia dentro del presupuesto."""
685
+ def __init__(self, df_data):
686
+ self.df = df_data
687
+
688
+ def _coherencia(self, vectores):
689
+ """Calcula la coherencia de estilo promedio (Similitud Coseno) entre los vectores de estilo de los muebles."""
690
+ if len(vectores) < 2: return 1.0
691
+ mat = cosine_similarity(np.array(vectores))
692
+ # Promedio de la similitud entre todos los pares (triángulo superior)
693
+ indices = np.triu_indices_from(mat, k=1)
694
+ return float(np.mean(mat[indices])) if indices[0].size > 0 else 1.0
695
+
696
+ def buscar_combinacion(self, constraints, presupuesto, top_n=1):
697
+ """
698
+ Algoritmo Knapsack de fuerza bruta optimizada.
699
+ Busca la mejor combinación de productos que cumpla restricciones dimensionales y presupuestarias,
700
+ maximizando el score total (Score Base + Coherencia de Estilo).
701
+ """
702
+ listas_candidatos = []
703
+
704
+ for const in constraints:
705
+ tipo = const['tipo']
706
+ max_w = const.get('max_ancho', 9999)
707
+ max_l = const.get('max_largo', 9999)
708
+
709
+ # Filtro dimensional
710
+ pool = self.df[self.df['Tipo_mueble'] == tipo]
711
+ # Permite rotación (Ancho <= Max_W y Largo <= Max_L) o (Ancho <= Max_L y Largo <= Max_W)
712
+ fits = pool[((pool['Ancho'] <= max_w) & (pool['Largo'] <= max_l)) |
713
+ ((pool['Ancho'] <= max_l) & (pool['Largo'] <= max_w))]
714
+
715
+ if fits.empty: fits = pool # Si no hay que cumplen, toma la lista completa
716
+
717
+ # ESTRATEGIA HÍBRIDA:
718
+ # Seleccionar los top 5 por Score (Calidad) Y los top 5 más baratos (Presupuesto)
719
+ # para asegurar que tenemos opciones viables si el presupuesto es bajo.
720
+
721
+ top_score = fits.sort_values('Score', ascending=False).head(5)
722
+ top_cheap = fits.sort_values('Precio', ascending=True).head(5)
723
+ top_expensive = fits.sort_values('Precio', ascending=False).head(5)
724
+
725
+ # Combinar y eliminar duplicados (usando ID para evitar error con numpy arrays)
726
+ candidates_df = pd.concat([top_score, top_cheap, top_expensive]).drop_duplicates(subset='ID')
727
+
728
+ candidatos = candidates_df.to_dict('records')
729
+ listas_candidatos.append(candidatos)
730
+
731
+ if not listas_candidatos: return []
732
+
733
+ validas = []
734
+ for combo in itertools.product(*listas_candidatos):
735
+ precio = sum(x['Precio'] for x in combo)
736
+ if precio <= presupuesto:
737
+ score_base = np.mean([x['Score'] for x in combo])
738
+ vectores = [x['vector_estilo'] for x in combo]
739
+ coherencia = self._coherencia(vectores)
740
+
741
+ # Score Final:
742
+ # 40% Score Base (Calidad/Popularidad)
743
+ # 40% Coherencia (Estilo)
744
+ # 20% Aprovechamiento de Presupuesto (Reward por usar el presupuesto disponible)
745
+ budget_utilization = precio / presupuesto
746
+
747
+ final_score = 0.4 * score_base + 0.4 * coherencia + 0.2 * budget_utilization
748
+
749
+ validas.append({
750
+ 'items': combo,
751
+ 'precio_total': precio,
752
+ 'score': final_score
753
+ })
754
+
755
+ validas.sort(key=lambda x: x['score'], reverse=True)
756
+ return validas[:top_n]
757
+
758
+ # ==========================================
759
+ # 5. VISUALIZADORES (PLANTAS 2D y 3D con OBJs)
760
+ # ==========================================
761
+
762
+ def get_segment_properties(p1, p2):
763
+ """Calcula longitud, punto central y ángulo de un segmento 2D."""
764
+ p1 = np.array(p1)
765
+ p2 = np.array(p2)
766
+
767
+ dx = p2[0] - p1[0]
768
+ dy = p2[1] - p1[1]
769
+ length = np.sqrt(dx**2 + dy**2)
770
+ midpoint_x = (p1[0] + p2[0]) / 2
771
+ midpoint_y = (p1[1] + p2[1]) / 2
772
+ angle = np.arctan2(dy, dx)
773
+ return length, midpoint_x, midpoint_y, angle
774
+
775
+
776
+ def read_kenney_obj(obj_path):
777
+ """
778
+ Lee archivos OBJ simples (como los de Kenney) extrayendo solo vértices (v) y caras (f).
779
+ Retorna (vertices_list, faces_list).
780
+ """
781
+ vertices = []
782
+ faces = []
783
+
784
+ # --- DEBUG: Comprobar lectura de archivo ---
785
+ print(f"\n--- DEBUG: Leyendo manualmente: {obj_path} ---")
786
+ v_count = 0
787
+ f_count = 0
788
+
789
+ try:
790
+ # Nota: El error podría ser la codificación. Usamos 'utf-8' o 'latin-1'
791
+ with open(obj_path, 'r', encoding='latin-1') as f:
792
+ for line in f:
793
+ parts = line.strip().split()
794
+ if not parts:
795
+ continue
796
+
797
+ prefix = parts[0]
798
+
799
+ if prefix == 'v':
800
+ # Vértices: 'v x y z'
801
+ try:
802
+ vertices.append([float(parts[1]), float(parts[2]), float(parts[3])])
803
+ v_count += 1
804
+ except ValueError:
805
+ print(f"DEBUG: Vértice inválido en {obj_name}: {line.strip()}")
806
+
807
+ elif prefix == 'f':
808
+ # Caras: 'f v/vt/vn v/vt/vn v/vt/vn ...'
809
+ try:
810
+ face_indices = []
811
+ for part in parts[1:]:
812
+ v_index = int(part.split('/')[0])
813
+ face_indices.append(v_index - 1)
814
+ faces.append(face_indices)
815
+ f_count += 1
816
+ except ValueError:
817
+ print(f"DEBUG: Cara inválida en {obj_name}: {line.strip()}")
818
+
819
+ except FileNotFoundError:
820
+ print(f"DEBUG: Archivo no encontrado en la ruta de {obj_path}")
821
+ return [], []
822
+ except Exception as e:
823
+ print(f"DEBUG: Error inesperado de E/S: {e}")
824
+ return [], []
825
+
826
+ # --- DEBUG: Reporte final de la lectura ---
827
+ print(f"DEBUG RESULTADO: Vértices leídos (v): {v_count}")
828
+ print(f"DEBUG RESULTADO: Caras leídas (f): {f_count}")
829
+ print(f"---------------------------------------------")
830
+
831
+ return vertices, faces
832
+
833
+
834
+ def load_and_transform_mesh(obj_name, w, l, h, cx, cy, angle, base_z=0, rotation_offset=0):
835
+ """
836
+ Carga un modelo .obj usando el parser manual, lo escala de forma NO UNIFORME
837
+ para encajar en (w, l, h), y lo rota/traslada a la posición.
838
+ """
839
+ obj_path = os.path.join(MODEL_DIR, obj_name)
840
+
841
+ if not os.path.exists(obj_path):
842
+ print(f"!!! ERROR MODELO 3D: '{obj_name}' no encontrado en {MODEL_DIR}")
843
+ return None, None, None, None, None, None
844
+
845
+ # --- 1. CARGA USANDO PARSER MANUAL ---
846
+ vertices, faces_indices_list = read_kenney_obj(obj_path)
847
+
848
+ if not vertices:
849
+ print(f"!!! ERROR MODELO 3D: Modelo '{obj_name}' sin datos 3D después del parseo.")
850
+ return None, None, None, None, None, None
851
+
852
+ vertices_np = np.array(vertices, dtype=np.float32).reshape(-1, 3)
853
+
854
+ # --- 2. PREPARAR CARAS PARA PLOTLY ---
855
+ i_faces, j_faces, k_faces = [], [], []
856
+
857
+ for face in faces_indices_list:
858
+ if len(face) == 3:
859
+ i_faces.append(face[0])
860
+ j_faces.append(face[1])
861
+ k_faces.append(face[2])
862
+ elif len(face) == 4:
863
+ i_faces.extend([face[0], face[0]])
864
+ j_faces.extend([face[1], face[2]])
865
+ k_faces.extend([face[2], face[3]])
866
+
867
+ if not i_faces:
868
+ print(f"!!! ERROR MODELO 3D: Modelo '{obj_name}' sin caras válidas para Plotly.")
869
+ return None, None, None, None, None, None
870
+
871
+ # --- 3. TRANSFORMAR VÉRTICES (ESCALADO NO UNIFORME) ---
872
+
873
+ # 3.0. CORRECCIÓN CRÍTICA DE ORIENTACIÓN (Rotación 90° sobre X)
874
+ # Rota el modelo de Kenney (que suele tener Y=Arriba, Z=Profundidad) a
875
+ # la convención de tu sistema (Z=Arriba, Y=Profundidad).
876
+
877
+ # Matriz de rotación 90° sobre eje X (Rotar Y a Z, Z a -Y)
878
+ R_X = np.array([
879
+ [1, 0, 0],
880
+ [0, 0, -1],
881
+ [0, 1, 0]
882
+ ])
883
+ vertices_np = vertices_np @ R_X.T # Aplicamos la rotación BASE
884
+
885
+ # 3.1. Encontrar el Bounding Box (para escalado) - ¡Usando los vértices rotados!
886
+ min_x, max_x = vertices_np[:, 0].min(), vertices_np[:, 0].max()
887
+ min_y, max_y = vertices_np[:, 1].min(), vertices_np[:, 1].max()
888
+ min_z, max_z = vertices_np[:, 2].min(), vertices_np[:, 2].max()
889
+
890
+ bbox_w = max_x - min_x
891
+ bbox_l = max_y - min_y
892
+ bbox_h = max_z - min_z
893
+
894
+ # 3.2. Calcular Factor de Escala NO UNIFORME
895
+ # Evitar división por cero
896
+ scale_x = w / bbox_w if bbox_w > 0 else 1.0
897
+ scale_y = l / bbox_l if bbox_l > 0 else 1.0
898
+ scale_z = h / bbox_h if bbox_h > 0 else 1.0
899
+
900
+ # 3.3. Trasladar al origen (centrar en XY y base en Z=0)
901
+ center_x_base = (min_x + max_x) / 2
902
+ center_y_base = (min_y + max_y) / 2
903
+
904
+ # Trasladar el centro y mover la base al plano Z=0
905
+ transformed_v = vertices_np - np.array([center_x_base, center_y_base, min_z])
906
+
907
+ # 3.4. Aplicar Escala No Uniforme
908
+ transformed_v[:, 0] *= scale_x
909
+ transformed_v[:, 1] *= scale_y
910
+ transformed_v[:, 2] *= scale_z
911
+
912
+ # --- 4. APLICAR ROTACIÓN Y TRASLACIÓN FINAL ---
913
+
914
+ # Aplicar Rotación del Layout (en el eje Z) + Offset
915
+ final_angle = angle + rotation_offset
916
+ c_cos = np.cos(final_angle)
917
+ c_sin = np.sin(final_angle)
918
+ rot_matrix = np.array([[c_cos, -c_sin], [c_sin, c_cos]])
919
+ transformed_v[:, :2] = transformed_v[:, :2] @ rot_matrix.T
920
+
921
+ # Aplicar Traslación Final
922
+ transformed_v[:, 0] += cx
923
+ transformed_v[:, 1] += cy
924
+ transformed_v[:, 2] += base_z
925
+
926
+ x_coords, y_coords, z_coords = transformed_v[:, 0], transformed_v[:, 1], transformed_v[:, 2]
927
+
928
+ return x_coords, y_coords, z_coords, i_faces, j_faces, k_faces
929
+
930
+ def dibujar_layout_sobre_imagen(img_path, room_data):
931
+ """
932
+ Dibuja las predicciones de HorizonNet (líneas de floor/ceiling y corners)
933
+ sobre la imagen panorámica para visualización de la detección.
934
+ """
935
+ try:
936
+ # Cargar imagen y redimensionar a 1024x512
937
+ img = Image.open(img_path).convert("RGB")
938
+ img = img.resize((1024, 512), Image.LANCZOS)
939
+ img_array = np.array(img)
940
+
941
+ # Verificar que tenemos los datos raw del modelo
942
+ if 'y_bon' not in room_data or 'y_cor' not in room_data:
943
+ draw = ImageDraw.Draw(img)
944
+ draw.text((10, 10), "Sin datos de visualización raw", fill=(255, 0, 0))
945
+ return img
946
+
947
+ y_bon = room_data['y_bon'] # [2, 1024] en radianes
948
+ y_cor = room_data['y_cor'] # [1024] probabilidades [0,1]
949
+
950
+ # Convertir boundary de radianes a píxeles
951
+ y_bon_pix = ((y_bon / np.pi + 0.5) * 512).round().astype(int)
952
+ y_bon_pix[0] = np.clip(y_bon_pix[0], 0, 511) # ceiling
953
+ y_bon_pix[1] = np.clip(y_bon_pix[1], 0, 511) # floor
954
+
955
+ # Crear visualización
956
+ img_vis = (img_array * 0.5).astype(np.uint8) # Oscurecer imagen un poco
957
+
958
+ # Dibujar las líneas de ceiling y floor (verde)
959
+ for x in range(1024):
960
+ img_vis[y_bon_pix[0][x], x] = [0, 255, 0] # Verde para ceiling
961
+ img_vis[y_bon_pix[1][x], x] = [0, 255, 0] # Verde para floor
962
+
963
+ # Dibujar probabilidades de corner como barra en la parte superior
964
+ cor_height = 30
965
+ gt_cor = np.zeros((cor_height, 1024, 3), np.uint8)
966
+ gt_cor[:] = (y_cor[None, :, None] * 255).astype(np.uint8) # Escala de grises
967
+
968
+ separator = np.ones((3, 1024, 3), np.uint8) * 255
969
+
970
+ # Concatenar: corner heatmap + separador + imagen con boundaries
971
+ final_vis = np.concatenate([gt_cor, separator, img_vis], axis=0)
972
+
973
+ return Image.fromarray(final_vis)
974
+
975
+ except Exception as e:
976
+ print(f"Error al dibujar layout: {e}")
977
+ import traceback
978
+ traceback.print_exc()
979
+ # En caso de error, devuelve la imagen original
980
+ return Image.open(img_path).convert("RGB")
981
+
982
+
983
+ def generar_figura_3d_plotly(layout_plan, room_data, items_recomendados, altura_pared=250):
984
+ """
985
+ Genera visualización 3D interactiva, usando modelos .OBJ para estructura y muebles.
986
+ Si un OBJ no carga, el elemento es OMITIDO.
987
+ """
988
+ if not layout_plan:
989
+ return go.Figure()
990
+
991
+ # --- Mapeo y Constantes ---
992
+ WALL_COLOR = '#bdbdbd'
993
+ CORNER_COLOR = '#6d6d6d'
994
+ DOOR_COLOR = '#8d6e63'
995
+ WINDOW_COLOR = '#d4e6f1'
996
+ WALL_H = altura_pared
997
+ WALL_DEPTH_CM = 10 # Profundidad de la pared a renderizar en 3D
998
+
999
+ MODEL_MAP = {
1000
+ 'Sofás': 'loungeSofa.obj',
1001
+ 'Sillones': 'loungeChair.obj',
1002
+ 'Mesas bajas de salón, de centro y auxiliares': 'tableCoffee.obj',
1003
+ 'Muebles de salón': 'cabinetTelevision.obj',
1004
+ 'Estanterías y librerías': 'bookcaseOpen.obj'
1005
+ }
1006
+
1007
+ OBSTACLE_MAP = {
1008
+ # w y l representan las dimensiones del OBJ
1009
+ 'door': {'obj': 'wallDoorway.obj', 'color': DOOR_COLOR, 'height': 200, 'v_offset': 0, 'w': WALL_DEPTH_CM, 'l': 0},
1010
+ 'window': {'obj': 'wallWindow.obj', 'color': WINDOW_COLOR, 'height': 120, 'v_offset': 100, 'w': WALL_DEPTH_CM, 'l': 0}
1011
+ }
1012
+
1013
+ pool_items = {}
1014
+ if items_recomendados:
1015
+ for it in items_recomendados:
1016
+ pool_items.setdefault(it['Tipo_mueble'], []).append(it)
1017
+
1018
+ colores = {
1019
+ 'Sofás': '#7f8c8d', 'Muebles de salón': '#95a5a6',
1020
+ 'Mesas bajas de salón, de centro y auxiliares': '#d6bfa9',
1021
+ 'Sillones': '#5d6d7e', 'Estanterías y librerías': '#ecf0f1'
1022
+ }
1023
+
1024
+ polygon_points = room_data.get('polygon_points', [])
1025
+ poly_pts_cm = np.array(polygon_points) * 100
1026
+ data = []
1027
+
1028
+ # --- FASE 1: DIBUJAR ESTRUCTURA DE LA HABITACIÓN (PAREDES Y OBSTÁCULOS) ---
1029
+ if len(poly_pts_cm) > 1:
1030
+ num_walls = len(poly_pts_cm)
1031
+ all_obstacles = room_data.get('doors', []) + room_data.get('windows', [])
1032
+
1033
+ for i in range(num_walls):
1034
+ p1 = poly_pts_cm[i]
1035
+ p2 = poly_pts_cm[(i+1) % num_walls]
1036
+
1037
+ length, cx_seg, cy_seg, angle = get_segment_properties(p1, p2)
1038
+
1039
+ # Identificar obstáculos en esta pared (índice i) y ordenarlos
1040
+ wall_obstacles = []
1041
+ for obs in all_obstacles:
1042
+ # Nota: obs['center'][1] es el índice normalizado de pared (0 a 1)
1043
+ wall_idx_obs = int(round(obs['center'][1] * num_walls)) % num_walls
1044
+ if wall_idx_obs == i:
1045
+ obs['type'] = 'door' if 'doors' in room_data and obs in room_data['doors'] else 'window'
1046
+ wall_obstacles.append(obs)
1047
+ wall_obstacles.sort(key=lambda x: x['center'][0]) # Ordenar por posición a lo largo de la pared
1048
+
1049
+ # Definir segmentos de pared a dibujar
1050
+ segments_to_draw = []
1051
+ current_start_pct = 0.0
1052
+
1053
+ for obs in wall_obstacles:
1054
+ center_pct = obs['center'][0]
1055
+ width_m = obs['width']
1056
+ width_pct = (width_m * 100) / length
1057
+
1058
+ obs_start_pct = max(0.0, center_pct - width_pct / 2)
1059
+ obs_end_pct = min(1.0, center_pct + width_pct / 2)
1060
+
1061
+ # Segmento de pared antes del obstáculo (pared vacía)
1062
+ if obs_start_pct > current_start_pct:
1063
+ segments_to_draw.append({'type': 'wall', 'start': current_start_pct, 'end': obs_start_pct})
1064
+
1065
+ # Segmento de obstáculo
1066
+ segments_to_draw.append({'type': obs['type'], 'start': obs_start_pct, 'end': obs_end_pct, 'w': width_m * 100})
1067
+
1068
+ current_start_pct = obs_end_pct
1069
+
1070
+ # Segmento de pared final (pared vacía)
1071
+ if current_start_pct < 1.0:
1072
+ segments_to_draw.append({'type': 'wall', 'start': current_start_pct, 'end': 1.0})
1073
+
1074
+ # --- DIBUJAR LOS SEGMENTOS CON OBJS ---
1075
+
1076
+ for seg in segments_to_draw:
1077
+ seg_start_cm = seg['start'] * length
1078
+ seg_end_cm = seg['end'] * length
1079
+ seg_len = seg_end_cm - seg_start_cm
1080
+
1081
+ if seg_len < 1: continue
1082
+
1083
+ # Recalcular centro y ángulo para el subsegmento
1084
+ seg_mid_x = p1[0] + (seg['start'] + seg['end']) / 2 * (p2[0] - p1[0])
1085
+ seg_mid_y = p1[1] + (seg['start'] + seg['end']) / 2 * (p2[1] - p1[1])
1086
+
1087
+ # Configuración del modelo
1088
+ if seg['type'] == 'wall':
1089
+ obj_file = 'wall.obj'
1090
+ color = WALL_COLOR
1091
+ h_val = WALL_H
1092
+ z_base = 0
1093
+ w_seg = seg_len # El largo del segmento es el ANCHO (X) del OBJ
1094
+ l_seg = WALL_DEPTH_CM # La profundidad de la pared es el LARGO (Y) del OBJ
1095
+ else:
1096
+ obs_data = OBSTACLE_MAP[seg['type']]
1097
+ obj_file = obs_data['obj']
1098
+ color = obs_data['color']
1099
+ h_val = obs_data['height']
1100
+ z_base = obs_data['v_offset']
1101
+ w_seg = seg_len
1102
+ l_seg = WALL_DEPTH_CM
1103
+
1104
+ # Cargar y transformar el OBJ
1105
+
1106
+ # Lista de elementos a dibujar en este segmento (puede ser múltiple para ventanas/puertas)
1107
+ sub_elements = []
1108
+
1109
+ if seg['type'] == 'wall':
1110
+ sub_elements.append({
1111
+ 'obj': 'wall.obj', 'color': WALL_COLOR,
1112
+ 'h': WALL_H, 'z': 0,
1113
+ 'w': seg_len, 'l': WALL_DEPTH_CM,
1114
+ 'name': 'Pared'
1115
+ })
1116
+ else:
1117
+ obs_data = OBSTACLE_MAP[seg['type']]
1118
+
1119
+ # 1. El Obstáculo en sí
1120
+ sub_elements.append({
1121
+ 'obj': obs_data['obj'], 'color': obs_data['color'],
1122
+ 'h': obs_data['height'], 'z': obs_data['v_offset'],
1123
+ 'w': seg_len, 'l': WALL_DEPTH_CM,
1124
+ 'name': seg['type'].title()
1125
+ })
1126
+
1127
+ # 2. Relleno SUPERIOR (Dintel) - Si hay espacio hasta el techo
1128
+ top_gap = WALL_H - (obs_data['v_offset'] + obs_data['height'])
1129
+ if top_gap > 1:
1130
+ sub_elements.append({
1131
+ 'obj': 'wall.obj', 'color': WALL_COLOR,
1132
+ 'h': top_gap, 'z': obs_data['v_offset'] + obs_data['height'],
1133
+ 'w': seg_len, 'l': WALL_DEPTH_CM,
1134
+ 'name': 'Muro Superior'
1135
+ })
1136
+
1137
+ # 3. Relleno INFERIOR (Antepecho) - Si el obstáculo no empieza en el suelo
1138
+ bottom_gap = obs_data['v_offset']
1139
+ if bottom_gap > 1:
1140
+ sub_elements.append({
1141
+ 'obj': 'wall.obj', 'color': WALL_COLOR,
1142
+ 'h': bottom_gap, 'z': 0,
1143
+ 'w': seg_len, 'l': WALL_DEPTH_CM,
1144
+ 'name': 'Muro Inferior'
1145
+ })
1146
+
1147
+ # Renderizar todos los sub-elementos del segmento
1148
+ for el in sub_elements:
1149
+ x_seg, y_seg, z_seg, i_seg, j_seg, k_seg = load_and_transform_mesh(
1150
+ el['obj'], w=el['w'], l=el['l'], h=el['h'],
1151
+ cx=seg_mid_x, cy=seg_mid_y, angle=angle, base_z=el['z']
1152
+ )
1153
+
1154
+ if x_seg is not None:
1155
+ data.append(go.Mesh3d(
1156
+ x=x_seg, y=y_seg, z=z_seg, i=i_seg, j=j_seg, k=k_seg,
1157
+ color=el['color'], opacity=1.0, flatshading=True,
1158
+ name=f'{el["name"]} P{i}', showlegend=(seg['type']!='wall' and el['name'] == seg['type'].title())
1159
+ ))
1160
+ else:
1161
+ print(f"!!! FALLO DE CARGA: Omisión de {el['name']} en pared {i}.")
1162
+
1163
+ # 5. ESQUINA (wallCorner.obj) - Se dibuja en el vértice P1
1164
+ if i == 0 or True: # Dibujar esquina en cada vértice para cerrar bien
1165
+ # Nota: Dibujamos esquina en P1 (inicio del segmento)
1166
+ x_c, y_c, z_c, i_c, j_c, k_c = load_and_transform_mesh(
1167
+ 'wallCorner.obj', w=WALL_DEPTH_CM, l=WALL_DEPTH_CM, h=WALL_H,
1168
+ cx=p1[0], cy=p1[1], angle=angle
1169
+ )
1170
+
1171
+ if x_c is not None:
1172
+ data.append(go.Mesh3d(
1173
+ x=x_c, y=y_c, z=z_c, i=i_c, j=i_c, k=i_c,
1174
+ color=CORNER_COLOR, opacity=1.0, flatshading=True,
1175
+ name=f'Esquina {i}', showlegend=False
1176
+ ))
1177
+
1178
+
1179
+ # --- FASE 2: DIBUJAR SUELO ---
1180
+ # Usar un fill poly simple. Convertir a (X, Y, Z) para Plotly
1181
+ x_floor = poly_pts_cm[:, 0]
1182
+ y_floor = poly_pts_cm[:, 1]
1183
+ z_floor = np.zeros_like(x_floor)
1184
+
1185
+ # Crear caras del suelo (convexhull)
1186
+ from scipy.spatial import ConvexHull
1187
+ try:
1188
+ hull = ConvexHull(np.array([x_floor, y_floor]).T)
1189
+ i_f, j_f, k_f = hull.simplices.T
1190
+ except: # Fails if points are collinear or too few
1191
+ i_f, j_f, k_f = [], [], []
1192
+
1193
+ suelo_trace = go.Mesh3d(
1194
+ x=x_floor, y=y_floor, z=z_floor,
1195
+ i=i_f, j=j_f, k=k_f,
1196
+ color='#fafafa', opacity=1, name='Suelo', hoverinfo='skip'
1197
+ )
1198
+ data.append(suelo_trace)
1199
+
1200
+ # --- FASE 3: DIBUJAR MUEBLES (OBJ o OMISIÓN) ---
1201
+ for mueble in layout_plan:
1202
+ tipo = mueble['tipo']
1203
+ obj_file = MODEL_MAP.get(tipo)
1204
+ # Buscar la info real del mueble seleccionado
1205
+ info_real = pool_items.get(tipo, [{}])[0] if tipo in pool_items else {}
1206
+
1207
+ nombre_display = info_real.get('Nombre', tipo)
1208
+ precio = info_real.get('Precio', '?')
1209
+ desc = info_real.get('Descripcion', '')[:60]
1210
+
1211
+ hover_text = (
1212
+ f"<b>TIPO:</b> {tipo}<br>"
1213
+ f"<b>MODELO:</b> {nombre_display}<br>"
1214
+ f"<b>PRECIO:</b> {precio}€<br>"
1215
+ f"<i>{desc}...</i>"
1216
+ )
1217
+
1218
+ try:
1219
+ h_val = float(info_real.get('Altura', 60))
1220
+ if np.isnan(h_val) or h_val <= 0: h_val = 60
1221
+ except: h_val = 60
1222
+
1223
+ w_m = mueble['ancho']
1224
+ l_m = mueble['largo']
1225
+
1226
+ # Rotación extra para sofás (suelen venir mirando hacia atrás)
1227
+ rot_offset = np.pi if tipo == 'Sofás' else 0
1228
+
1229
+ # Lógica específica para detectar Sofás en L (Chaise Longue / Rinconera)
1230
+ if tipo == 'Sofás':
1231
+ keywords_l_shape = ['chaise', 'esquina', 'rincon', 'l-shaped', 'modular', 'l shape']
1232
+ text_to_search = (nombre_display + " " + desc).lower()
1233
+ if any(k in text_to_search for k in keywords_l_shape):
1234
+ obj_file = 'loungeDesignSofaCorner.obj'
1235
+ # Ajuste de rotación específico para este modelo si es necesario (a veces los modelos de esquina tienen otra orientación)
1236
+ # Por ahora mantenemos la rotación de sofá estándar (pi) o ajustamos si el usuario reporta algo raro.
1237
+ # rot_offset = np.pi
1238
+
1239
+ if obj_file:
1240
+ x_m, y_m, z_m, i_m, j_m, k_m = load_and_transform_mesh(
1241
+ obj_file, w=w_m, l=l_m, h=h_val,
1242
+ cx=mueble['x'], cy=mueble['y'], angle=mueble['angle'],
1243
+ rotation_offset=rot_offset
1244
+ )
1245
+
1246
+ if x_m is not None:
1247
+ traces = [go.Mesh3d(
1248
+ x=x_m, y=y_m, z=z_m, i=i_m, j=j_m, k=k_m,
1249
+ color=colores.get(tipo, '#95a5a6'), opacity=1.0, flatshading=True,
1250
+ name=nombre_display, hoverinfo='text', text=hover_text,
1251
+ lighting=dict(ambient=0.6, diffuse=0.8), showlegend=True
1252
+ )]
1253
+ data.extend(traces)
1254
+ else:
1255
+ # Fallo de carga: OMITIR
1256
+ print(f"!!! FALLO DE CARGA/RENDERIZADO: {tipo} ({nombre_display}). Modelo OBJ no usado.")
1257
+ continue
1258
+ else:
1259
+ # Omisión si no hay OBJ mapeado
1260
+ print(f"!!! OMISIÓN: No hay OBJ mapeado para el tipo: {tipo}. Saltando renderizado.")
1261
+ continue
1262
+
1263
+ # --- CONFIGURACIÓN FINAL ---
1264
+ max_dim = np.max(poly_pts_cm, axis=0) if poly_pts_cm.size > 0 else [500, 500]
1265
+
1266
+ layout = go.Layout(
1267
+ title="Diseño 3D (Interactúa con el ratón)",
1268
+ showlegend=True,
1269
+ scene=dict(
1270
+ xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False),
1271
+ aspectmode='data', # Usar 'data' para que los ejes sean proporcionales a los valores reales
1272
+ aspectratio=None,
1273
+ bgcolor='white',
1274
+ camera=dict(eye=dict(x=2.0, y=2.0, z=2.0)) # Zoom out inicial
1275
+ ),
1276
+ margin=dict(r=0, l=0, b=0, t=30),
1277
+ height=600
1278
+ )
1279
+
1280
+ return go.Figure(data=data, layout=layout)
1281
+
1282
+
1283
+ def generar_diagrama_planta(room_data):
1284
+ """Genera un diagrama de planta 2D de la habitación con paredes, puertas y ventanas."""
1285
+ try:
1286
+ # --- 1. CONFIGURACIÓN DE ESTILO ---
1287
+ COLORS = {
1288
+ 'bg': '#1C4E80', # Azul oscuro de fondo
1289
+ 'line': '#ffffff', # Blanco para líneas
1290
+ 'hole': '#1C4E80', # Mismo color que el fondo para "borrar" la pared
1291
+ 'grid': '#ffffff',
1292
+ 'text': '#ffffff'
1293
+ }
1294
+
1295
+ WALL_WIDTH = 6
1296
+ HOLE_WIDTH = 8
1297
+ ELEM_WIDTH = 1.5
1298
+
1299
+ fig, ax = plt.subplots(figsize=(12, 8))
1300
+ fig.patch.set_facecolor(COLORS['bg'])
1301
+ ax.set_facecolor(COLORS['bg'])
1302
+
1303
+ polygon_points = room_data.get('polygon_points', None)
1304
+ if polygon_points is None or len(polygon_points) < 3:
1305
+ ax.text(0.5, 0.5, "ERROR: Polígono de habitación inválido", color=COLORS['text'], ha='center')
1306
+ return fig
1307
+
1308
+ polygon_m = np.array(polygon_points)
1309
+ centroid = np.mean(polygon_m, axis=0)
1310
+
1311
+ # A. Forzar proporción real (1 metro visual = 1 metro dato)
1312
+ ax.set_aspect('equal', adjustable='box')
1313
+
1314
+ # B. Calcular límites enteros para asegurar que el grid cae en el metro exacto
1315
+ min_x, min_y = np.min(polygon_m, axis=0)
1316
+ max_x, max_y = np.max(polygon_m, axis=0)
1317
+
1318
+ # Márgenes de 1 metro extra alrededor
1319
+ start_x = np.floor(min_x - 1)
1320
+ end_x = np.ceil(max_x + 1)
1321
+ start_y = np.floor(min_y - 1)
1322
+ end_y = np.ceil(max_y + 1)
1323
+
1324
+ ax.set_xlim(start_x, end_x)
1325
+ ax.set_ylim(start_y, end_y)
1326
+
1327
+ # C. Definir ticks explícitamente cada 1.0 unidades (1 metro)
1328
+ xticks = np.arange(start_x, end_x + 1, 1.0)
1329
+ yticks = np.arange(start_y, end_y + 1, 1.0)
1330
+
1331
+ ax.set_xticks(xticks)
1332
+ ax.set_yticks(yticks)
1333
+
1334
+ # Grid muy sutil
1335
+ ax.grid(True, color=COLORS['grid'], linestyle=':', linewidth=0.5, alpha=0.2)
1336
+ ax.set_xticklabels([]); ax.set_yticklabels([])
1337
+ ax.tick_params(length=0)
1338
+
1339
+ # --- Helper: Datos de Muro (Necesario aquí para Doors/Windows) ---
1340
+ num_walls = len(polygon_m)
1341
+ def get_wall_data(idx, pct):
1342
+ idx = idx % num_walls
1343
+ p1, p2 = polygon_m[idx], polygon_m[(idx + 1) % num_walls]
1344
+ vec = p2 - p1
1345
+ L_wall = np.linalg.norm(vec)
1346
+ if L_wall == 0: return None
1347
+ unit = vec / L_wall
1348
+ center_on_wall = p1 + vec * (pct / 100.0)
1349
+
1350
+ # Vector normal hacia adentro
1351
+ n1 = np.array([-unit[1], unit[0]])
1352
+ # Comprobar si n1 apunta hacia el centroide
1353
+ if np.linalg.norm((center_on_wall + n1) - centroid) > np.linalg.norm((center_on_wall - n1) - centroid):
1354
+ normal_in = -n1
1355
+ else:
1356
+ normal_in = n1
1357
+ return center_on_wall, unit, normal_in
1358
+
1359
+ # --- 3. DIBUJAR PAREDES ---
1360
+ polygon_closed = np.vstack([polygon_m, polygon_m[0]])
1361
+
1362
+ # Relleno muy sutil del suelo
1363
+ ax.fill(polygon_closed[:, 0], polygon_closed[:, 1], color=COLORS['line'], alpha=0.05, zorder=1)
1364
+
1365
+ # EL MURO GRUESO
1366
+ ax.plot(polygon_closed[:, 0], polygon_closed[:, 1],
1367
+ color=COLORS['line'], linewidth=WALL_WIDTH, zorder=2, solid_capstyle='round')
1368
+
1369
+
1370
+ # --- 4. PUERTAS (Hueco + Hoja + Arco) ---
1371
+ for d in room_data.get('doors', []):
1372
+ # Obtener índice de pared y posición porcentual a lo largo de esa pared
1373
+ wall_idx = int(round(d['center'][1] * num_walls)) % num_walls
1374
+ pos_pct = d['center'][0] * 100 # a cm
1375
+
1376
+ info = get_wall_data(wall_idx, pos_pct)
1377
+ if not info: continue
1378
+ center, unit, normal_in = info
1379
+ w = d['width'] # ancho de la puerta en metros
1380
+
1381
+ # A. HUECO (Borrar muro)
1382
+ h_s = center - unit * (w/2)
1383
+ h_e = center + unit * (w/2)
1384
+ ax.plot([h_s[0], h_e[0]], [h_s[1], h_e[1]],
1385
+ color=COLORS['hole'], linewidth=HOLE_WIDTH, zorder=5)
1386
+
1387
+ # B. HOJA
1388
+ hinge = h_s
1389
+ tip = hinge + normal_in * w
1390
+ ax.plot([hinge[0], tip[0]], [hinge[1], tip[1]],
1391
+ color=COLORS['line'], linewidth=ELEM_WIDTH, zorder=6)
1392
+
1393
+ # C. ARCO (Interpolado)
1394
+ arc_pts = []
1395
+ start_angle = np.arctan2(unit[1], unit[0])
1396
+
1397
+ # Crear la rotación desde el vector 'unit' al vector 'normal_in'
1398
+ for t in np.linspace(0, 1, 15):
1399
+ angle_interp = t * (np.pi/2)
1400
+ # Aplicar rotación al vector 'unit'
1401
+ v_rot = unit * np.cos(angle_interp) + normal_in * np.sin(angle_interp)
1402
+ pt = hinge + v_rot * w
1403
+ arc_pts.append(pt)
1404
+ arc_pts = np.array(arc_pts)
1405
+ ax.plot(arc_pts[:, 0], arc_pts[:, 1],
1406
+ color=COLORS['line'], linestyle=':', linewidth=1, zorder=6)
1407
+
1408
+ # --- 5. VENTANAS (Hueco + Rectángulo vacío) ---
1409
+ for w_obj in room_data.get('windows', []):
1410
+ wall_idx = int(round(w_obj['center'][1] * num_walls)) % num_walls
1411
+ pos_pct = w_obj['center'][0] * 100
1412
+
1413
+ info = get_wall_data(wall_idx, pos_pct)
1414
+ if not info: continue
1415
+ center, unit, normal_in = info
1416
+ w = w_obj['width'] # ancho de la ventana en metros
1417
+
1418
+ # A. HUECO (Borrar muro grueso)
1419
+ h_s = center - unit * (w/2); h_e = center + unit * (w/2)
1420
+ ax.plot([h_s[0], h_e[0]], [h_s[1], h_e[1]],
1421
+ color=COLORS['hole'], linewidth=HOLE_WIDTH, zorder=5)
1422
+
1423
+ # B. MARCO RECTANGULAR (Sin relleno)
1424
+ frame_depth = 0.1 # 10 cm de profundidad de marco (en metros)
1425
+
1426
+ # 4 Esquinas del rectángulo
1427
+ c1 = h_s - normal_in * (frame_depth/2)
1428
+ c2 = h_e - normal_in * (frame_depth/2)
1429
+ c3 = h_e + normal_in * (frame_depth/2)
1430
+ c4 = h_s + normal_in * (frame_depth/2)
1431
+
1432
+ # Dibujar perímetro (c1->c2->c3->c4->c1)
1433
+ rect_x = [c1[0], c2[0], c3[0], c4[0], c1[0]]
1434
+ rect_y = [c1[1], c2[1], c3[1], c4[1], c1[1]]
1435
+
1436
+ ax.plot(rect_x, rect_y, color=COLORS['line'], linewidth=ELEM_WIDTH, zorder=6)
1437
+
1438
+ # --- 6. ETIQUETAS Y LEYENDA ---
1439
+ legend_items = []
1440
+ for i in range(num_walls):
1441
+ p1, p2 = polygon_m[i], polygon_m[(i + 1) % num_walls]
1442
+ mid = (p1 + p2) / 2
1443
+
1444
+ # Vector hacia afuera para etiqueta
1445
+ vec_out = mid - centroid
1446
+ vec_out = vec_out / np.linalg.norm(vec_out)
1447
+ text_pos = mid + vec_out * 0.5 # 50cm afuera para no tocar el muro grueso
1448
+
1449
+ L = np.linalg.norm(p2 - p1)
1450
+ legend_items.append(f"P{i+1}: {L:.2f} m")
1451
+
1452
+ ax.text(text_pos[0], text_pos[1], f"P{i+1}", color=COLORS['bg'], fontsize=8, fontweight='bold',
1453
+ ha='center', va='center', zorder=10,
1454
+ bbox=dict(boxstyle='circle,pad=0.2', fc='white', ec='none'))
1455
+
1456
+ plt.subplots_adjust(right=0.70)
1457
+
1458
+ info_text = "HABITACIÓN\n(Grid 1x1m)\n\n" + "\n".join(legend_items)
1459
+
1460
+ fig.text(0.72, 0.5, info_text, fontsize=10, color=COLORS['text'],
1461
+ fontfamily='monospace', va='center',
1462
+ bbox=dict(boxstyle='square,pad=1', fc=COLORS['hole'], ec=COLORS['line']))
1463
+
1464
+ return fig
1465
+
1466
+ except Exception as e:
1467
+ print(f"Error planta: {e}")
1468
+ import traceback
1469
+ traceback.print_exc()
1470
+ return plt.figure()
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ libgl1
requirements.txt CHANGED
@@ -1,3 +1,15 @@
1
- altair
2
  pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
  pandas
3
+ numpy
4
+ Pillow
5
+ torch
6
+ torchvision
7
+ transformers
8
+ scikit-learn
9
+ matplotlib
10
+ shapely
11
+ tqdm
12
+ plotly
13
+ pywavefront
14
+ scipy
15
+ opencv-python-headless
vectores_cache.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ead8295d791f946f9ddb61bcfdcbe1b1a447c1307dfffd1eefb1d80dda0f20b0
3
+ size 1090945