Spaces:
Runtime error
Runtime error
Update app.py
Browse files19 unmodified lines2021222324252627284 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757614 unmodified lines919293949596979 unmodified lines10710810911011111211314 unmodified lines1281291301311321331348 unmodified lines14314414514614714814934 unmodified lines18418518618718818919014 unmodified lines2052062072082092102112124 unmodified lines2172182192202212222232242252262272282292302312322332342352363 unmodified lines2402412422432442452462 unmodified lines24925025125225325419 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 1. GENERADOR DE URLS (LLAVE MAESTRA) ---def construir_urls_final(barrio, ciudad, tipo, hab, ban, park, antiguedad):# Mapeo exacto de antigüedad (Con "anos")mapa_ant = {"Menos de 1 año": "de-0-a-1-anos","1 a 8 años": "de-1-a-8-anos",4 unmodified linesslug_ant = mapa_ant.get(antiguedad, "de-1-a-8-anos")slug_park = f"{int(park)}-parqueadero" if int(park) == 1 else f"{int(park)}-parqueaderos"# Limpieza de zonab_slug = barrio.lower().strip().replace(" ", "-")c_slug = ciudad.lower().strip().replace(" ", "-")# Manejo de tipos de inmueble (Agrupación descubierta por el usuario)tipo_slug = tipo.lower().strip()if tipo_slug in ["apartamento", "casa"]:tipo_fr = "casas-y-apartamentos-y-apartaestudios"else:tipo_fr = tipo_slug + "s" # bodegas, lotes, oficinas# --- URL FINCA RAÍZ EXACTA ---if tipo_slug in ["bodega", "lote", "oficina"]:url_fr = f"https://www.fincaraiz.com.co/arriendo/{tipo_fr}/{b_slug}/{c_slug}/{slug_park}/{slug_ant}"else:url_fr = f"https://www.fincaraiz.com.co/arriendo/{tipo_fr}/{b_slug}/{c_slug}/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}"# --- URL METROCUADRADO ---url_mc = f"https://www.metrocuadrado.com/{tipo_slug}-casa-oficina/arriendo/{c_slug}/{b_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"return url_fr, url_mc# --- 2. EXTRACTOR DE PRECIO INTELIGENTE (REGEX) ---def extraer_precio_regex(texto):patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:precios = [int(p.replace('.', '').replace(',', '')) for p in coincidencias]# Filtro: Ignorar precios de venta (> 40 millones)precios_validos = [p for p in precios if 600000 <= p <= 40000000]if precios_validos:return precios_validos[0]return 0# --- 3. MOTOR DE EXTRACCIÓN ROBUSTO ---def motor_tramitia_final(barrio, ciudad, area, tipo, hab, ban, park, antiguedad):resultados = []url_fr, url_mc = construir_urls_final(barrio, ciudad, tipo, hab, ban, park, antiguedad)log_visible = f"✅ URLs GENERADAS (AUDITORÍA):\nFR: {url_fr}\nMC: {url_mc}\n\n"ua = UserAgent()14 unmodified lines# --- FINCA RAÍZ ---try:page = context.new_page()log_visible += "🔄 Escaneando Finca Raíz...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)page.mouse.move(random.randint(100, 500), random.randint(100, 500))9 unmodified linestxt = el.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 0:href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href14 unmodified lines# --- METROCUADRADO ---try:page = context.new_page()log_visible += "🔄 Escaneando Metrocuadrado...\n"page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)for _ in range(5):8 unmodified linestxt = card.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 0:enlace = card.query_selector("a")if enlace:34 unmodified linespdf = FPDF()pdf.add_page()pdf.set_font("Arial", 'B', 14)pdf.cell(0, 10, f"ESTUDIO DE MERCADO: {barrio.upper()}", ln=True)pdf.ln(5)for _, r in df_final.iterrows():14 unmodified linesmaximo = df_final['Precio'].max()resumen = (f"💰 **ESTIMACIÓN DE RENTA**\n"f"🔹 **Canon Sugerido:** ${promedio:,.0f}\n"f"📉 Mínimo Zona: ${minimo:,.0f}\n"f"📈 Máximo Zona: ${maximo:,.0f}")4 unmodified lines# --- INTERFAZ GRÁFICA ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("## 🤖 TramitIA Pro: Analizador Inmobiliario (Rutas Exactas)")with gr.Row():with gr.Column(scale=1):c = gr.Textbox(label="Ciudad", value="Barranquilla")b = gr.Textbox(label="Barrio (Ej: La Concepcion)", value="La Concepcion")a = gr.Number(label="Área M2", value=70)t = gr.Dropdown(["Apartamento", "Casa", "Bodega", "Lote", "Oficina"],label="Tipo",value="Apartamento")with gr.Row():h = gr.Number(label="Habitaciones", value=3)ban = gr.Number(label="Baños", value=2)3 unmodified lines["Menos de 1 año", "1 a 8 años", "9 a 15 años", "16 a 30 años", "Más de 30 años"],label="Antigüedad", value="1 a 8 años")btn = gr.Button("EJECUTAR ANÁLISIS", variant="primary")with gr.Column(scale=2):res_fin = gr.Markdown("### 💰 El resultado aparecerá aquí...")2 unmodified lineswith gr.TabItem("Tabla de Resultados"): out_df = gr.Dataframe()with gr.TabItem("Descargar PDF"): out_pdf = gr.File()btn.click(motor_tramitia_final, [b, c, a, t, h, ban, p, e], [msg, out_df, out_pdf, res_fin])demo.launch()19 unmodified lines20212223242526274 unmodified lines3233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828314 unmodified lines98991001011021031049 unmodified lines11411511611711811912014 unmodified lines1351361371381391401418 unmodified lines15015115215315415515634 unmodified lines19119219319419519619714 unmodified lines2122132142152162172182194 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492502513 unmodified lines2552562572582592602612 unmodified lines26426526626726826927027119 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 1. GENERADOR DE URLS (VENTA/ARRIENDO Y EXTRAS) ---def construir_urls_final(operacion, barrio, ciudad, tipo, hab, ban, park, antiguedad, m2_min, m2_max, ascensor, piscina):mapa_ant = {"Menos de 1 año": "de-0-a-1-anos","1 a 8 años": "de-1-a-8-anos",4 unmodified linesslug_ant = mapa_ant.get(antiguedad, "de-1-a-8-anos")slug_park = f"{int(park)}-parqueadero" if int(park) == 1 else f"{int(park)}-parqueaderos"b_slug = barrio.lower().strip().replace(" ", "-")c_slug = ciudad.lower().strip().replace(" ", "-")op_slug = operacion.lower().strip() # 'venta' o 'arriendo'tipo_slug = tipo.lower().strip()if tipo_slug in ["apartamento", "casa"]:tipo_fr = "casas-y-apartamentos-y-apartaestudios"else:tipo_fr = tipo_slug + "s"# --- URL FINCA RAÍZ MULTIFILTRO ---url_fr_base = f"https://www.fincaraiz.com.co/{op_slug}/{tipo_fr}/{b_slug}/{c_slug}/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}/m2-desde-{int(m2_min)}/m2-hasta-{int(m2_max)}"# Extras condicionalesif ascensor: url_fr_base += "/con-ascensor"if piscina: url_fr_base += "/con-piscina"url_fr = url_fr_base# --- URL METROCUADRADO ---# MC usa un formato más simple, le pasamos la operación dinámicaurl_mc = f"https://www.metrocuadrado.com/{tipo_slug}-casa-oficina/{op_slug}/{c_slug}/{b_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form"return url_fr, url_mc# --- 2. EXTRACTOR DE PRECIO DINÁMICO ---def extraer_precio_regex(texto, operacion):patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:precios = [int(p.replace('.', '').replace(',', '')) for p in coincidencias]# Filtro de cordura según si es Venta o Arriendoif operacion == "Arriendo":precios_validos = [p for p in precios if 600000 <= p <= 40000000] # Ignora ventas y admónelse: # Ventaprecios_validos = [p for p in precios if p >= 40000000] # Ignora arriendos cruzadosif precios_validos:return precios_validos[0]return 0# --- 3. MOTOR DE EXTRACCIÓN ---def motor_tramitia_final(operacion, barrio, ciudad, area, m2_min, m2_max, tipo, hab, ban, park, antiguedad, ascensor, piscina):resultados = []url_fr, url_mc = construir_urls_final(operacion, barrio, ciudad, tipo, hab, ban, park, antiguedad, m2_min, m2_max, ascensor, piscina)log_visible = f"✅ URLs GENERADAS (AUDITORÍA):\nFR: {url_fr}\nMC: {url_mc}\n\n"ua = UserAgent()14 unmodified lines# --- FINCA RAÍZ ---try:page = context.new_page()log_visible += f"🔄 Escaneando Finca Raíz ({operacion})...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)page.mouse.move(random.randint(100, 500), random.randint(100, 500))9 unmodified linestxt = el.inner_text()if "$" in txt:precio = extraer_precio_regex(txt, operacion) # Pasamos la operaciónif precio > 0:href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href and href.startswith("/") else href14 unmodified lines# --- METROCUADRADO ---try:page = context.new_page()log_visible += f"🔄 Escaneando Metrocuadrado ({operacion})...\n"page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)for _ in range(5):8 unmodified linestxt = card.inner_text()if "$" in txt:precio = extraer_precio_regex(txt, operacion)if precio > 0:enlace = card.query_selector("a")if enlace:34 unmodified linespdf = FPDF()pdf.add_page()pdf.set_font("Arial", 'B', 14)pdf.cell(0, 10, f"ESTUDIO DE MERCADO: {barrio.upper()} ({operacion.upper()})", ln=True)pdf.ln(5)for _, r in df_final.iterrows():14 unmodified linesmaximo = df_final['Precio'].max()resumen = (f"💰 **ESTIMACIÓN DE {operacion.upper()}**\n"f"🔹 **Valor Sugerido:** ${promedio:,.0f}\n"f"📉 Mínimo Zona: ${minimo:,.0f}\n"f"📈 Máximo Zona: ${maximo:,.0f}")4 unmodified lines# --- INTERFAZ GRÁFICA ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("## 🤖 TramitIA Pro: Tasador Inmobiliario Integral")with gr.Row():with gr.Column(scale=1):op = gr.Radio(["Arriendo", "Venta"], label="¿Qué deseas hacer?", value="Arriendo")c = gr.Textbox(label="Ciudad", value="Barranquilla")b = gr.Textbox(label="Barrio (Ej: La Concepcion)", value="La Concepcion")with gr.Row():t = gr.Dropdown(["Apartamento", "Casa", "Bodega", "Lote", "Oficina"], label="Tipo", value="Apartamento")a = gr.Number(label="Área M2 (Tu Cliente)", value=70)gr.Markdown("### Filtros de Búsqueda")with gr.Row():m2_min = gr.Number(label="M2 Mínimo", value=10)m2_max = gr.Number(label="M2 Máximo", value=200)with gr.Row():ascensor = gr.Checkbox(label="Con Ascensor")piscina = gr.Checkbox(label="Con Piscina")with gr.Row():h = gr.Number(label="Habitaciones", value=3)ban = gr.Number(label="Baños", value=2)3 unmodified lines["Menos de 1 año", "1 a 8 años", "9 a 15 años", "16 a 30 años", "Más de 30 años"],label="Antigüedad", value="1 a 8 años")btn = gr.Button("EJECUTAR ANÁLISIS COMERCIAL", variant="primary")with gr.Column(scale=2):res_fin = gr.Markdown("### 💰 El resultado aparecerá aquí...")2 unmodified lineswith gr.TabItem("Tabla de Resultados"): out_df = gr.Dataframe()with gr.TabItem("Descargar PDF"): out_pdf = gr.File()btn.click(motor_tramitia_final,[op, b, c, a, m2_min, m2_max, t, h, ban, p, e, ascensor, piscina],[msg, out_df, out_pdf, res_fin])demo.launch()
app.py+53-36