adriansanz commited on
Commit
679771a
·
verified ·
1 Parent(s): 0db294f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -51
app.py CHANGED
@@ -147,60 +147,77 @@ def chat(user_input, chat_history, current_step, user_context):
147
  siguiente_pregunta = preguntar_al_usuario(preguntas[current_step][1])
148
  chat_history.append(("assistant", siguiente_pregunta))
149
  else:
150
- resultado = predict_disponibilidad(user_context)
151
- if "error" in resultado:
152
- chat_history.append(("assistant", resultado["error"] + " Reiniciando conversación..."))
153
- user_context = {
154
- "ubicacion": None,
155
- "month": None,
156
- "day": None,
157
- "hour": None,
158
- "target_pct": None,
159
- "temperature": None,
160
- "lluvia": None
161
- }
162
- current_step = 0
163
- chat_history.append(("assistant", preguntar_al_usuario(preguntas[0][1])))
164
- return chat_history, current_step, user_context
165
  else:
166
- clima = resultado["candidatas"][0]
167
-
168
- # Resumen del contexto
169
- resumen_contexto = (
170
- f"🗓️ Día: {user_context['day']:02d}/{user_context['month']:02d}/2025\n"
171
- f"🕒 Hora: {user_context['hour']:02d}:00h\n"
172
- f"📍 Ubicación: {user_context['ubicacion']}\n"
173
- f"🎯 Porcentaje mínimo deseado de bicis: {int(user_context['target_pct'] * 100)}%"
174
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- # Mensaje principal
177
- msg = (
178
- f"📈 Predicción meteorológica:\n"
179
- f"🌡️ Temperatura aprox.: {clima['temperature']}°C\n"
180
- f"☔ Precipitación aprox.: {clima['precip']} mm\n\n"
181
- f"{resumen_contexto}\n\n"
182
- f"🚲 Estaciones ordenadas por disponibilidad:\n"
 
 
 
 
 
 
183
  )
184
- for r in resultado["candidatas"]:
185
- emoji = "✅" if r["pred_pct"] >= resultado["target_pct"] else "⚠️"
186
- msg += (
187
- f"{emoji} '{r['address']}' (ID {r['station_id']}): "
188
- f"{round(r['pred_pct']*100)}% disponibilidad\n"
189
- )
190
- chat_history.append(("assistant", msg.strip()))
191
-
192
- # Generar resumen final con el LLM
193
- resumen_llm = client.chat.completions.create(
194
- messages=[
195
- {"role": "system", "content": "Eres un asistente experto en movilidad urbana. Resume de forma clara y amigable si el usuario podrá encontrar bicis disponibles, y en qué estaciones, según los datos que se te dan."},
196
- {"role": "user", "content": f"Aquí tienes el resultado del sistema:\n{msg.strip()}"}
197
- ],
198
- model="llama-3.3-70b-versatile",
199
- temperature=0.5,
200
- max_completion_tokens=256
201
- ).choices[0].message.content.strip()
202
-
203
- chat_history.append(("assistant", resumen_llm))
 
 
 
 
 
 
 
 
204
 
205
 
206
  return chat_history, current_step, user_context
 
147
  siguiente_pregunta = preguntar_al_usuario(preguntas[current_step][1])
148
  chat_history.append(("assistant", siguiente_pregunta))
149
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  else:
151
+ resultado = predict_disponibilidad(user_context)
152
+ if "error" in resultado:
153
+ chat_history.append(("assistant", resultado["error"] + " Reiniciando conversación..."))
154
+ user_context = {
155
+ "ubicacion": None,
156
+ "month": None,
157
+ "day": None,
158
+ "hour": None,
159
+ "target_pct": None,
160
+ "temperature": None,
161
+ "lluvia": None
162
+ }
163
+ current_step = 0
164
+ chat_history.append(("assistant", preguntar_al_usuario(preguntas[0][1])))
165
+ return chat_history, current_step, user_context
166
+ else:
167
+ clima = resultado["candidatas"][0]
168
+
169
+ # 🧾 Resumen del contexto
170
+ fecha_str = f"{user_context['day']:02d}/{user_context['month']:02d}/2025"
171
+ hora_str = f"{user_context['hour']:02d}:00h"
172
+ resumen_contexto = (
173
+ f"📍 *Ubicación*: {user_context['ubicacion']}\n"
174
+ f"🗓️ *Día*: {fecha_str}\n"
175
+ f"🕒 *Hora*: {hora_str}\n"
176
+ f"🎯 *Porcentaje mínimo deseado de bicis*: {int(user_context['target_pct'] * 100)}%"
177
+ )
178
 
179
+ # 📈 Predicción meteorológica
180
+ resumen_meteo = (
181
+ f"🌡️ *Temperatura esperada*: {clima['temperature']}°C\n"
182
+ f" *Precipitación esperada*: {clima['precip']} mm"
183
+ )
184
+
185
+ # 🚲 Disponibilidad de estaciones
186
+ msg_estaciones = "🚲 *Estaciones más cercanas ordenadas por disponibilidad:*\n"
187
+ for r in resultado["candidatas"]:
188
+ emoji = "✅" if r["pred_pct"] >= resultado["target_pct"] else "⚠️"
189
+ msg_estaciones += (
190
+ f"{emoji} '{r['address']}' (ID {r['station_id']}): "
191
+ f"{round(r['pred_pct']*100)}% disponibilidad\n"
192
  )
193
+
194
+ # Construir mensaje completo
195
+ mensaje_final = f"{resumen_contexto}\n\n{resumen_meteo}\n\n{msg_estaciones}"
196
+ chat_history.append(("assistant", mensaje_final.strip()))
197
+
198
+ # 🧠 Resumen generado por LLM
199
+ # 🧠 Resumen generado por LLM
200
+ resumen_llm = client.chat.completions.create(
201
+ messages=[
202
+ {
203
+ "role": "system",
204
+ "content": (
205
+ "Eres un asistente experto en movilidad urbana. Resume al usuario de forma clara y amigable "
206
+ "si podrá encontrar bicis disponibles, indicando las mejores estaciones según los datos meteorológicos "
207
+ "y el porcentaje mínimo requerido."
208
+ )
209
+ },
210
+ {"role": "user", "content": mensaje_final.strip()}
211
+ ],
212
+ model="llama-3.3-70b-versatile",
213
+ temperature=0.5,
214
+ max_completion_tokens=256
215
+ ).choices[0].message.content.strip()
216
+
217
+ # Añadir texto fijo al final del resumen
218
+ resumen_llm += "\n\nSi quieres hacer otra consulta, dime una nueva ubicación o escribe 'reiniciar'."
219
+
220
+ chat_history.append(("assistant", resumen_llm))
221
 
222
 
223
  return chat_history, current_step, user_context