VicGerardoPR commited on
Commit
b5cd87f
verified
1 Parent(s): 89df01d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -21
app.py CHANGED
@@ -49,17 +49,17 @@ def parse_text_file(filepath):
49
  def parse_html_file(filepath):
50
  """
51
  Parseo para archivos HTML (por ejemplo, de Wikipedia).
52
- Extrae el t铆tulo desde la etiqueta <title> y las coordenadas desde el bloque "wgCoordinates".
53
- Si la coordenada es '-' se asigna None.
54
  """
55
  with open(filepath, 'r', encoding='utf-8') as f:
56
  content = f.read()
57
 
58
- # Extraer el t铆tulo usando BeautifulSoup
59
  soup = BeautifulSoup(content, "html.parser")
60
  title = soup.title.string.strip() if soup.title else os.path.splitext(os.path.basename(filepath))[0]
61
 
62
- # Buscar las coordenadas en el contenido HTML (ej. en el bloque "wgCoordinates")
63
  coord_match = re.search(r'"wgCoordinates":\s*{\s*"lat":\s*([0-9\.-]+),\s*"lon":\s*([0-9\.-]+)', content)
64
  if coord_match:
65
  lat_str = coord_match.group(1)
@@ -75,11 +75,24 @@ def parse_html_file(filepath):
75
  else:
76
  lat, lon = None, None
77
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  return {
79
  "name": title,
80
  "lat": lat,
81
  "lon": lon,
82
- "content": content
 
83
  }
84
 
85
  def load_data_from_directory(directory, parser_func):
@@ -106,7 +119,7 @@ news_dir = os.path.join("data", "news")
106
  landmarks = load_data_from_directory(landmarks_dir, parse_text_file)
107
  news_data = load_data_from_directory(news_dir, parse_text_file)
108
 
109
- # Para municipalities, se usa el parseo de HTML
110
  municipalities = load_data_from_directory(municipalities_dir, parse_html_file)
111
 
112
  # =============================================================================
@@ -126,12 +139,15 @@ for landmark in landmarks:
126
  icon=folium.Icon(color='blue', icon='info-sign')
127
  ).add_to(m)
128
 
129
- # Agregar marcadores para Municipios
130
  for municipality in municipalities:
131
  if municipality["lat"] is not None and municipality["lon"] is not None:
 
 
 
132
  folium.Marker(
133
  location=[municipality["lat"], municipality["lon"]],
134
- popup=folium.Popup(f"<b>{municipality['name']}</b><br>{municipality['content'][:200]}...", max_width=300),
135
  icon=folium.Icon(color='green', icon='home')
136
  ).add_to(m)
137
 
@@ -162,18 +178,19 @@ if st.button("Enviar consulta"):
162
  if user_input:
163
  # Configura tu clave API de OpenAI (def铆nela en st.secrets)
164
  openai.api_key = st.secrets["OPENAI_API_KEY"]
165
- try:
166
- response = openai.ChatCompletion.create(
167
- model="gpt-3.5-turbo",
168
- messages=[
169
- {"role": "system", "content": "Eres un asistente experto en recomendaciones tur铆sticas y culturales de Puerto Rico. Ayudas a los usuarios a descubrir lugares de inter茅s y actividades en la isla."},
170
- {"role": "user", "content": user_input}
171
- ]
172
- )
173
- answer = response.choices[0].message.content.strip()
174
- st.markdown("**Respuesta:**")
175
- st.write(answer)
176
- except Exception as e:
177
- st.error(f"Error al conectarse con la API de OpenAI: {e}")
 
178
  else:
179
  st.warning("Por favor, ingresa una consulta.")
 
49
  def parse_html_file(filepath):
50
  """
51
  Parseo para archivos HTML (por ejemplo, de Wikipedia).
52
+ Extrae el t铆tulo, las coordenadas desde el bloque "wgCoordinates" y, si es posible,
53
+ la secci贸n hist贸rica (buscando un encabezado que contenga "History" o "Historia").
54
  """
55
  with open(filepath, 'r', encoding='utf-8') as f:
56
  content = f.read()
57
 
58
+ # Parsear con BeautifulSoup
59
  soup = BeautifulSoup(content, "html.parser")
60
  title = soup.title.string.strip() if soup.title else os.path.splitext(os.path.basename(filepath))[0]
61
 
62
+ # Extraer coordenadas (pueden venir en el bloque "wgCoordinates")
63
  coord_match = re.search(r'"wgCoordinates":\s*{\s*"lat":\s*([0-9\.-]+),\s*"lon":\s*([0-9\.-]+)', content)
64
  if coord_match:
65
  lat_str = coord_match.group(1)
 
75
  else:
76
  lat, lon = None, None
77
 
78
+ # Intentar extraer datos hist贸ricos: se busca un encabezado que contenga "History" o "Historia"
79
+ history = ""
80
+ history_header = soup.find(lambda tag: tag.name in ["h2", "h3"] and ("History" in tag.get_text() or "Historia" in tag.get_text()))
81
+ if history_header:
82
+ history_parts = []
83
+ # Recorrer los hermanos hasta llegar a otro encabezado del mismo nivel (o superior)
84
+ for sibling in history_header.find_next_siblings():
85
+ if sibling.name and sibling.name.startswith("h"):
86
+ break
87
+ history_parts.append(sibling.get_text(strip=True))
88
+ history = "\n".join(history_parts)
89
+
90
  return {
91
  "name": title,
92
  "lat": lat,
93
  "lon": lon,
94
+ "content": content,
95
+ "history": history
96
  }
97
 
98
  def load_data_from_directory(directory, parser_func):
 
119
  landmarks = load_data_from_directory(landmarks_dir, parse_text_file)
120
  news_data = load_data_from_directory(news_dir, parse_text_file)
121
 
122
+ # Para municipalities, se usa el parseo de HTML (que ahora incluye datos hist贸ricos)
123
  municipalities = load_data_from_directory(municipalities_dir, parse_html_file)
124
 
125
  # =============================================================================
 
139
  icon=folium.Icon(color='blue', icon='info-sign')
140
  ).add_to(m)
141
 
142
+ # Agregar marcadores para Municipios, incluyendo datos hist贸ricos si est谩n disponibles
143
  for municipality in municipalities:
144
  if municipality["lat"] is not None and municipality["lon"] is not None:
145
+ history_text = municipality.get("history", "")
146
+ history_excerpt = history_text[:300] + "..." if len(history_text) > 300 else history_text
147
+ popup_content = f"<b>{municipality['name']}</b><br><b>Historia:</b><br>{history_excerpt}"
148
  folium.Marker(
149
  location=[municipality["lat"], municipality["lon"]],
150
+ popup=folium.Popup(popup_content, max_width=300),
151
  icon=folium.Icon(color='green', icon='home')
152
  ).add_to(m)
153
 
 
178
  if user_input:
179
  # Configura tu clave API de OpenAI (def铆nela en st.secrets)
180
  openai.api_key = st.secrets["OPENAI_API_KEY"]
181
+ with st.spinner("Consultando a OpenAI..."):
182
+ try:
183
+ response = openai.ChatCompletion.create(
184
+ model="gpt-3.5-turbo",
185
+ messages=[
186
+ {"role": "system", "content": "Eres un asistente experto en recomendaciones tur铆sticas y culturales de Puerto Rico. Ayudas a los usuarios a descubrir lugares de inter茅s y actividades en la isla."},
187
+ {"role": "user", "content": user_input}
188
+ ]
189
+ )
190
+ answer = response.choices[0].message.content.strip()
191
+ st.markdown("**Respuesta:**")
192
+ st.write(answer)
193
+ except Exception as e:
194
+ st.error(f"Error al conectarse con la API de OpenAI: {e}")
195
  else:
196
  st.warning("Por favor, ingresa una consulta.")