Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
634 lines (511 loc) · 24.7 KB
/
Copy pathapp.py
File metadata and controls
634 lines (511 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import streamlit as st
import googlemaps
import pandas as pd
import requests
from bs4 import BeautifulSoup
import re
import concurrent.futures
import time
from urllib.parse import urlparse
import sqlite3
from datetime import datetime
# Configuración de Streamlit
st.set_page_config(page_title="Maps Bot & Scraper", layout="wide", page_icon="📍")
def detect_tech_and_seo(soup, url):
"""Detecta tecnologías y problemas SEO básicos."""
tech_stack = []
has_ssl = "No"
# SSL Check
if url.startswith("https"):
has_ssl = "Si"
# Tech Detection (Básico basado en HTML)
html_str = str(soup).lower()
if "wp-content" in html_str or "wordpress" in html_str:
tech_stack.append("WordPress")
if "wix.com" in html_str or "wix-image" in html_str:
tech_stack.append("Wix")
if "shopify" in html_str:
tech_stack.append("Shopify")
if "squarespace" in html_str:
tech_stack.append("Squarespace")
if "jumpseller" in html_str:
tech_stack.append("Jumpseller")
if "elementor" in html_str:
tech_stack.append("Elementor")
tech_str = ", ".join(tech_stack) if tech_stack else "HTML/Otro"
return tech_str, has_ssl
def generate_sales_pitch(name, rubro, city, website, tech_stack="N/A", has_ssl="N/A"):
"""Genera un script de venta personalizado."""
# 1. Caso: No tiene web
if website == 'N/A' or not website:
return f"""Hola {name}, ¿cómo estás?
Estuve buscando {rubro} en {city} y vi que su negocio aparece en Google Maps, pero noté que no tienen un sitio web oficial.
Hoy en día, el 80% de los clientes buscan en Google antes de ir. Sin web, están perdiendo muchas ventas contra la competencia.
Me dedico a crear páginas web modernas y vendedoras. Me gustaría armarles una propuesta sin compromiso.
¿Les interesa?"""
# 2. Caso: Tiene web, pero sin SSL (No Seguro)
if has_ssl == "No":
return f"""Hola {name}, buscando {rubro} en {city} encontré su web.
Noté algo importante: Su sitio figura como "No Seguro" (sin candado SSL). Google penaliza esto y muestra un aviso de alerta a sus clientes, lo que baja mucho la confianza y las ventas.
Puedo solucionar esto rápidamente y modernizar su sitio. ¿Les gustaría que lo veamos?"""
# 3. Caso: Usa Wix/Integrados (Escalabilidad)
if tech_stack and ("Wix" in tech_stack or "Squarespace" in tech_stack):
return f"""Hola {name}, ¿qué tal? Vi su sitio web de {rubro}.
Veo que usan {tech_stack}. Es una buena plataforma para empezar, pero suele ser lenta y difícil de posicionar bien en Google a largo plazo.
Ayudo a negocios a migrar a plataformas profesionales (sin pagos mensuales fijos a Wix) que cargan rápido y venden más.
¿Hacemos una auditoría rápida de su sitio?"""
# 4. Caso: WordPress/Genérico (Rediseño)
return f"""Hola {name}, ¿qué tal?
Encontré su sitio web buscando {rubro} en {city}.
Estuve analizando su página ({website}) y vi oportunidades para modernizar el diseño y que cargue más rápido en celulares.
Ayudo a negocios como el suyo a renovar su imagen digital.
¿Podría enviarles algunos ejemplos de antes/después?"""
def normalize_url(url):
"""Asegura que la URL tenga esquema http/https."""
if not url.startswith('http'):
return 'http://' + url
return url
def extract_socials_and_contacts(soup):
"""Extrae redes sociales, emails y teléfonos del HTML parseado."""
social_links = {
'Facebook': '',
'Instagram': '',
'LinkedIn': '',
'Twitter': ''
}
emails = set()
whatsapp = []
# Redes Sociales y WhatsApp (Búsqueda en hrefs)
for a in soup.find_all('a', href=True):
href = a['href'].lower()
full_link = a['href'] # Conservar case original para el link visual
# Redes Sociales (Priorizar links que parecen perfiles)
if 'facebook.com' in href and not social_links['Facebook']:
social_links['Facebook'] = full_link
elif 'instagram.com' in href and not social_links['Instagram']:
social_links['Instagram'] = full_link
elif 'linkedin.com' in href and not social_links['LinkedIn']:
social_links['LinkedIn'] = full_link
elif ('twitter.com' in href or 'x.com' in href) and not social_links['Twitter']:
social_links['Twitter'] = full_link
# WhatsApp
if 'wa.me' in href or 'api.whatsapp.com' in href:
# Intentar extraer el número
# Patrones comunes: wa.me/54911..., api.whatsapp.com/send?phone=54911...
number_match = re.search(r'(?:wa\.me\/|phone=)(\d+)', href)
if number_match:
number = number_match.group(1)
# Crear link directo a WhatsApp Web
web_link = f"https://web.whatsapp.com/send?phone={number}"
whatsapp.append(web_link)
else:
whatsapp.append(full_link)
# Emails (Regex en todo el texto)
# Regex robusto que intenta evitar extensiones de imagen comunes
text = soup.get_text()
# Buscamos en el HTML crudo también por si están en atributos 'mailto:'
html_str = str(soup)
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
found_emails = re.findall(email_pattern, html_str)
for email in found_emails:
# Filtrar falsos positivos comunes (imágenes, archivos)
if not re.search(r'\.(png|jpg|jpeg|gif|css|js|woff|ttf)$', email, re.IGNORECASE):
emails.add(email)
return {
'social_links': social_links,
'emails': list(emails),
'whatsapp': list(set(whatsapp)),
'soup': soup # Retornamos soup para análisis posterior
}
def scrape_website(url):
"""
Entra a una web y extrae información.
Retorna un diccionario con los datos encontrados.
"""
if not url:
return {'emails': [], 'socials': [], 'whatsapp': [], 'status': 'No URL'}
target_url = normalize_url(url)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
try:
response = requests.get(target_url, headers=headers, timeout=5)
response.raise_for_status()
# Parsear HTML
soup = BeautifulSoup(response.text, 'lxml')
# Extraer datos
data = extract_socials_and_contacts(soup)
data['status'] = 'Success'
return data
except Exception as e:
return {'emails': [], 'socials': [], 'whatsapp': [], 'status': f'Error: {str(e)}'}
# --- BASE DE DATOS (SQLite) ---
def init_db():
"""Inicializa la base de datos si no existe."""
conn = sqlite3.connect('leads.db')
c = conn.cursor()
# Crear tabla si no existe
# Guardamos todo como TEXT para simplicidad en SQLite
c.execute('''
CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre TEXT,
direccion TEXT,
rating TEXT,
telefono TEXT,
website TEXT,
link_maps TEXT,
emails TEXT,
instagram TEXT,
facebook TEXT,
linkedin TEXT,
twitter TEXT,
whatsapp_link TEXT,
scraping_status TEXT,
lat REAL,
lon REAL,
search_content TEXT,
city TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
tech_stack TEXT,
has_ssl TEXT,
lead_status TEXT
)
''')
# Migración "simple" (Check si existen columnas nuevas, si no, agregarlas)
try:
c.execute("ALTER TABLE leads ADD COLUMN tech_stack TEXT")
except: pass
try:
c.execute("ALTER TABLE leads ADD COLUMN has_ssl TEXT")
except: pass
try:
c.execute("ALTER TABLE leads ADD COLUMN lead_status TEXT")
except: pass
conn.commit()
conn.close()
def update_lead_status(lead_id, new_status):
"""Actualiza el estado de un lead."""
conn = sqlite3.connect('leads.db')
c = conn.cursor()
c.execute("UPDATE leads SET lead_status = ? WHERE id = ?", (new_status, lead_id))
conn.commit()
conn.close()
def save_results(df, search_term, city):
"""Guarda los resultados en la base de datos."""
if df.empty:
return
conn = sqlite3.connect('leads.db')
# Preparamos el DF para que coincida con la tabla sql
df_save = df.copy()
df_save['search_content'] = search_term
df_save['city'] = city
df_save['timestamp'] = datetime.now()
# Renombrar columnas del DF a las de la DB (normalización)
# Mapping: Nombre Columna DF -> Nombre Columna DB
col_mapping = {
'Nombre': 'nombre',
'Dirección': 'direccion',
'Rating': 'rating',
'Teléfono': 'telefono',
'Website': 'website',
'Link Maps': 'link_maps',
'Emails Detectados': 'emails',
'Instagram': 'instagram',
'Facebook': 'facebook',
'LinkedIn': 'linkedin',
'Twitter': 'twitter',
'WhatsApp Link': 'whatsapp_link',
'Scraping Status': 'scraping_status',
'lat': 'lat',
'lon': 'lon',
'tech_stack': 'tech_stack',
'has_ssl': 'has_ssl',
'lead_status': 'lead_status'
}
df_save = df_save.rename(columns=col_mapping)
# Seleccionar solo las columnas que existen en la DB
valid_cols = list(col_mapping.values()) + ['search_content', 'city', 'timestamp']
df_save = df_save[valid_cols]
df_save.to_sql('leads', conn, if_exists='append', index=False)
conn.close()
def load_history():
"""Carga todo el historial."""
conn = sqlite3.connect('leads.db')
try:
df = pd.read_sql_query("SELECT * FROM leads ORDER BY timestamp DESC", conn)
return df
except:
return pd.DataFrame()
finally:
conn.close()
# --- FUNCIONES DE GOOGLE MAPS ---
def search_places(gmaps_client, query, max_results=60):
"""Busca lugares en Google Maps API."""
places = []
page_token = None
while len(places) < max_results:
try:
results = gmaps_client.places(query=query, page_token=page_token)
if 'results' in results:
places.extend(results['results'])
page_token = results.get('next_page_token')
if not page_token:
break
# Google requiere un pequeño delay antes de usar el next_page_token
time.sleep(2)
except Exception as e:
st.error(f"Error en la búsqueda de Google Maps: {e}")
break
return places[:max_results]
def get_place_details_and_enrich(place, gmaps_client, enable_scraping):
"""
Obtiene detalles de un lugar y opcionalmente hace scraping.
Esta función está diseñada para correr en un hilo separado.
"""
place_id = place.get('place_id')
name = place.get('name')
address = place.get('formatted_address')
rating = place.get('rating', 'N/A')
loc = place.get('geometry', {}).get('location', {})
# Datos base
result = {
'Nombre': name,
'Dirección': address,
'Rating': rating,
'Teléfono': 'N/A',
'Website': 'N/A',
'Link Maps': f"https://www.google.com/maps/place/?q=place_id:{place_id}",
'Emails Detectados': '',
'Instagram': '',
'Facebook': '',
'LinkedIn': '',
'Twitter': '',
'WhatsApp Link': '',
'Scraping Status': 'Skipped',
'lat': loc.get('lat'),
'lon': loc.get('lng'),
'tech_stack': 'N/A',
'has_ssl': 'N/A',
'lead_status': 'Nuevo'
}
# 1. Obtener detalles de Google Maps (Teléfono y Website)
try:
details = gmaps_client.place(place_id=place_id, fields=['formatted_phone_number', 'website'])
if 'result' in details:
details_res = details['result']
result['Teléfono'] = details_res.get('formatted_phone_number', 'N/A')
result['Website'] = details_res.get('website', 'N/A')
except Exception as e:
pass # Si falla details, conservamos los N/A.
# 2. Scraping (si está habilitado y hay website)
if enable_scraping and result['Website'] != 'N/A':
scrap_data = scrape_website(result['Website'])
result['Emails Detectados'] = ", ".join(scrap_data['emails'])
# Asignar redes individuales
links = scrap_data.get('social_links', {})
result['Instagram'] = links.get('Instagram', '')
result['Facebook'] = links.get('Facebook', '')
result['LinkedIn'] = links.get('LinkedIn', '')
result['Twitter'] = links.get('Twitter', '')
# Tech Analysis
soup = scrap_data.get('soup')
if soup:
tech, ssl = detect_tech_and_seo(soup, result['Website'])
result['tech_stack'] = tech
result['has_ssl'] = ssl
result['WhatsApp Link'] = ", ".join(scrap_data['whatsapp'])
result['Scraping Status'] = scrap_data['status']
return result
# --- CONFIGURACIÓN INICIAL ---
init_db()
# --- INTERFAZ STREAMLIT ---
st.title("🗺️ Maps Bot & Scraper")
# Sidebar
with st.sidebar:
st.header("Navegación")
mode = st.radio("Modo", ["🔍 Buscador", "🗄️ Historial"])
st.markdown("---")
# === MODO BUSCADOR ===
if mode == "🔍 Buscador":
st.markdown("""
Esta herramienta busca empresas en **Google Maps** y utiliza **Inteligencia Web** para encontrar emails y redes sociales en sus sitios web.
""")
with st.sidebar:
st.header("Configuración de Búsqueda")
api_key = st.text_input("Google Maps API Key", type="password", help="Asegúrate de tener habilitada la 'Places API'.")
st.subheader("Búsqueda")
keyword = st.text_input("Rubro / Keyword", placeholder="Ej: Pizzería, Abogados")
location = st.text_input("Ciudad / Ubicación", placeholder="Ej: Rosario, Buenos Aires")
st.subheader("Opciones")
enable_scraping = st.checkbox("Activar Inteligencia Web (Scraping)", value=True, help="Entrará a los sitios web para buscar emails y redes. Puede demorar más.")
search_btn = st.button("🔍 Buscar Empresas", type="primary")
# Lógica Principal
if search_btn:
if not api_key:
st.warning("⚠️ Por favor ingresa tu Google Maps API Key.")
elif not keyword or not location:
st.warning("⚠️ Por favor ingresa un Rubro y una Ciudad.")
else:
try:
gmaps = googlemaps.Client(key=api_key)
query = f"{keyword} en {location}"
with st.spinner(f"Buscando '{query}' en Google Maps..."):
places_raw = search_places(gmaps, query)
if not places_raw:
st.info("No se encontraron resultados en Google Maps.")
else:
st.success(f"Se encontraron {len(places_raw)} lugares. Comenzando enriquecimiento...")
# Barra de progreso
progress_bar = st.progress(0)
status_text = st.empty()
enriched_results = []
total_places = len(places_raw)
# Ejecución en paralelo con ThreadPoolExecutor
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
# Preparamos las tareas
futures = {executor.submit(get_place_details_and_enrich, place, gmaps, enable_scraping): place for place in places_raw}
for i, future in enumerate(concurrent.futures.as_completed(futures)):
result = future.result()
enriched_results.append(result)
# Actualizar progreso
progress = (i + 1) / total_places
progress_bar.progress(progress)
status_text.text(f"Procesando {i + 1} de {total_places}: {result['Nombre']}")
progress_bar.empty()
status_text.empty()
# Crear DataFrame
df = pd.DataFrame(enriched_results)
# --- GUARDADO AUTOMÁTICO ---
save_results(df, keyword, location)
st.toast("✅ Resultados guardados en el Historial automáticamente.")
# --- DASHBOARD & VISUALIZACIÓN ---
# 1. KPIs
total = len(df)
with_web = len(df[df['Website'] != 'N/A'])
with_email = len(df[df['Emails Detectados'] != ''])
kpi1, kpi2, kpi3 = st.columns(3)
kpi1.metric("Total Encontrados", total)
kpi2.metric("Con Website", f"{with_web} ({round(with_web/total*100)}%)")
kpi3.metric("Con Emails", f"{with_email} ({round(with_email/total*100)}%)")
st.markdown("---")
# 2. Tabs y Filtros
tab1, tab2, tab3 = st.tabs(["📋 Datos", "🗺️ Mapa", "📊 Análisis"])
with tab1:
# Filtros
st.caption("Filtros de Visualización")
col_f1, col_f2 = st.columns(2)
filter_email = col_f1.checkbox("Mostrar solo con Email")
filter_web = col_f2.checkbox("Mostrar solo con Website")
# Dataframe display (Sin lat/lon)
df_display = df.copy()
if filter_email:
df_display = df_display[df_display['Emails Detectados'] != '']
if filter_web:
df_display = df_display[df_display['Website'] != 'N/A']
# Ocultar columnas técnicas para la vista
cols_to_hide = ['lat', 'lon']
df_show = df_display.drop(columns=[c for c in cols_to_hide if c in df_display.columns])
st.dataframe(df_show, use_container_width=True)
# Botón de Descarga (basado en lo filtrado y limpio)
csv = df_show.to_csv(index=False).encode('utf-8')
st.download_button(
label="💾 Descargar CSV (Filtrado)",
data=csv,
file_name=f"maps_scraper_{keyword.replace(' ', '_')}_{location.replace(' ', '_')}.csv",
mime="text/csv",
)
with tab2:
st.map(df, size=20)
with tab3:
st.subheader("Distribución de Ratings")
if 'Rating' in df.columns:
# Limpiar ratings N/A para el gráfico
ratings = df[df['Rating'] != 'N/A']['Rating'].astype(float)
st.bar_chart(ratings.value_counts())
except Exception as e:
st.error(f"Ocurrió un error crítico: {e}")
# === MODO HISTORIAL ===
elif mode == "🗄️ Historial":
st.header("🗄️ Historial de Búsquedas")
df_history = load_history()
if df_history.empty:
st.info("Aún no tienes búsquedas guardadas. Ve al 'Buscador' y realiza tu primera búsqueda.")
else:
# Filtros del Historial
st.sidebar.header("Filtros de Historial")
# Filtro por Rubro
all_terms = list(df_history['search_content'].unique())
selected_terms = st.sidebar.multiselect("Filtrar por Rubro", all_terms, default=all_terms)
# Filtro por Ciudad
all_cities = list(df_history['city'].unique())
selected_cities = st.sidebar.multiselect("Filtrar por Ciudad", all_cities, default=all_cities)
# Aplicar filtros
df_filtered = df_history.copy()
if selected_terms:
df_filtered = df_filtered[df_filtered['search_content'].isin(selected_terms)]
if selected_cities:
df_filtered = df_filtered[df_filtered['city'].isin(selected_cities)]
# KPIs Históricos
# KPIs Históricos
kpi1, kpi2 = st.columns(2)
kpi1.metric("Leads Totales", len(df_filtered))
unique_emails = df_filtered[df_filtered['emails'] != '']['emails'].count()
kpi2.metric("Emails Únicos", unique_emails)
st.markdown("---")
st.subheader("📢 CRM & Generador de Oportunidades")
st.caption("Gestiona tus leads y genera speeches inteligentes basados en tecnología.")
# Iterar sobre las filas (Limitamos a 50 para performance)
# Asegurarse de tener 'tech_stack' y 'has_ssl' aunque sean viejos (fillna)
if 'tech_stack' not in df_filtered.columns: df_filtered['tech_stack'] = 'N/A'
if 'has_ssl' not in df_filtered.columns: df_filtered['has_ssl'] = 'N/A'
if 'lead_status' not in df_filtered.columns: df_filtered['lead_status'] = 'Nuevo'
for index, row in df_filtered.head(50).iterrows():
# Color del status
status_emoji = "🆕"
if row['lead_status'] == "Contactado": status_emoji = "📩"
elif row['lead_status'] == "Interesado": status_emoji = "🔥"
elif row['lead_status'] == "Cliente": status_emoji = "💰"
with st.expander(f"{status_emoji} {row['nombre']} ({row['lead_status']}) - {row['rating']}⭐"):
c1, c2 = st.columns([3, 2])
with c1:
st.write(f"**📍 Dirección:** {row['direccion']}")
st.write(f"**🌐 Web:** {row['website']} (SSL: {row['has_ssl']})")
st.write(f"**🛠️ Tech:** {row['tech_stack']}")
if row['emails']:
st.write(f"**📧 Email:** {row['emails']}")
# Generar Pitch
pitch = generate_sales_pitch(row['nombre'], row['search_content'], row['city'], row['website'], row['tech_stack'], row['has_ssl'])
st.text_area("💬 Script de Venta Inteligente:", value=pitch, height=180, key=f"pitch_{index}")
with c2:
# Gestión de Estado (CRM)
st.write("**Gestión de Lead**")
current_status = row['lead_status'] if row['lead_status'] else "Nuevo"
new_status = st.selectbox("Estado", ["Nuevo", "Contactado", "Interesado", "Rechazado", "Cliente"], index=["Nuevo", "Contactado", "Interesado", "Rechazado", "Cliente"].index(current_status), key=f"status_{row['id']}")
if new_status != current_status:
update_lead_status(row['id'], new_status)
st.toast(f"Estado actualizado a: {new_status}")
time.sleep(1)
st.rerun()
st.markdown("---")
st.write("**Accesos Directos:**")
if row['instagram']: st.write(f"[Instagram]({row['instagram']})")
if row['facebook']: st.write(f"[Facebook]({row['facebook']})")
if row['linkedin']: st.write(f"[LinkedIn]({row['linkedin']})")
if row['whatsapp_link']:
st.markdown(f"**[💬 Abrir WhatsApp]({row['whatsapp_link']})**")
elif row['telefono'] != 'N/A':
clean_tel = re.sub(r'\D', '', str(row['telefono']))
st.markdown(f"[Intentar WhatsApp](https://web.whatsapp.com/send?phone={clean_tel})")
st.markdown("---")
st.subheader("Base Completa")
st.dataframe(df_filtered, use_container_width=True)
csv_hist = df_filtered.to_csv(index=False).encode('utf-8')
st.download_button(
label="💾 Descargar Historial Completo",
data=csv_hist,
file_name="historial_leads.csv",
mime="text/csv",
)
st.markdown("---")
st.caption("Desarrollado para uso interno.")