Spaces:
Runtime error
Runtime error
Update app.py
Browse files19 unmodified lines20212223232425264 unmodified lines313233343436353637383940413842434445464745484950495151525354555 unmodified lines616263636465666767686970697172737470717778727374828375768586878889909192777879801 unmodified line8283841001011021031041051068586871088889110111112909192931159495961189798121991001011026 unmodified lines1091101111341121131141152 unmodified lines1181191201431441451211221481231241501251521261271551281291301311321331611341351368 unmodified lines1451461471761481491501511521531821541551561571581591841601611861621631641651661671681691701711721731741751761771931781791801813 unmodified lines1851861872032042052061881891901911921931942102112121951961971981992152002012022032192042052062072082242092102112122132292142152312162172182194 unmodified lines22422522624224324422722822923023123219 unmodified lines subprocess.run(["pip", "install", "fake-useragent"], check=True) from fake_useragent import UserAgent
# --- 1. GENERADOR DE URLS ---# --- 1. GENERADOR DE URLS (CORREGIDO) ---def construir_urls_final(zona, ciudad, tipo, hab, ban, park, antiguedad): mapa_ant = { "Menos de 1 año": "de-0-a-1-anos",4 unmodified lines } slug_ant = mapa_ant.get(antiguedad, "de-1-a-8-anios") slug_park = f"{int(park)}-parqueadero" if int(park) == 1 else f"{int(park)}-parqueaderos" query_geo = f"{zona.lower().replace(' ', '-')}-{ciudad.lower().replace(' ', '-')}" url_fr = f"https://www.fincaraiz.com.co/arriendo/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}?&searchstring={query_geo}" z_slug = zona.lower().strip().replace(" ", "-") c_slug = ciudad.lower().strip().replace(" ", "-") # FR CORREGIDO: Se reincorpora la zona y ciudad en el path principal # Ejemplo: /arriendo/usaquen/bogota/3-o-mas-habitaciones... url_fr = f"https://www.fincaraiz.com.co/arriendo/{z_slug}/{c_slug}/{int(hab)}-o-mas-habitaciones/{int(ban)}-o-mas-banos/{slug_park}/{slug_ant}" c_slug = ciudad.lower().replace(" ", "-") url_mc = f"https://www.metrocuadrado.com/{tipo.lower()}-casa-oficina/arriendo/{c_slug}/{int(ban)}-banos-{int(hab)}-habitaciones/?search=form" return url_fr, url_mc
# --- 2. EXTRACTOR GENÉRICO (Regex) ---def extraer_precio_regex(texto): # Busca patrones como $ 1.500.000 o $1500000 patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)' coincidencias = re.findall(patron, texto) if coincidencias: # Convertir a entero: quitar puntos y comas precios = [int(p.replace('.', '').replace(',', '')) for p in coincidencias] return max(precios) # Retorna el precio más alto encontrado en el texto return max(precios) return 0
# --- 3. MOTOR DE EXTRACCIÓN CAMUFLADO ---5 unmodified lines ua = UserAgent()
with sync_playwright() as p: # LANZAMIENTO EN MODO FURTIVO browser = p.chromium.launch( headless=True, args=[ '--disable-blink-features=AutomationControlled', # Oculta que es un robot '--disable-blink-features=AutomationControlled', '--no-sandbox', '--disable-setuid-sandbox', '--disable-infobars', '--disable-infobars' '--window-position=0,0', '--ignore-certifcate-errors', '--ignore-certifcate-errors-spki-list', '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' ] ) # Contexto con Viewport aleatorio para parecer humano context = browser.new_context( user_agent=ua.random, viewport={'width': 1366, 'height': 768}, locale='es-CO', timezone_id='America/Bogota' locale='es-CO' ) # Script para evasión de detección de WebDriver init_script = """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); """ context.add_init_script(init_script) context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")
# --- FINCA RAÍZ --- try:1 unmodified line log_visible += "🔄 Conectando a FR...\n" page.goto(url_fr, wait_until="domcontentloaded", timeout=60000) # Simulamos comportamiento humano antes de buscar page.mouse.move(random.randint(100, 500), random.randint(100, 500)) page.mouse.wheel(0, 500) time.sleep(random.uniform(2, 4)) # Scroll lento for _ in range(3): page.mouse.move(200, 200) for _ in range(4): page.mouse.wheel(0, 1500) time.sleep(1) time.sleep(1.5)
# ESTRATEGIA: Buscar TODOS los enlaces que contengan un precio dentro elementos = page.query_selector_all("a") # Buscamos cualquier link # Buscamos enlaces (aumentamos a 20 para sobrevivir a la eliminación de duplicados) elementos = page.query_selector_all("a") cont_fr = 0 for el in elementos: if cont_fr >= 6: break if cont_fr >= 15: break # Extraemos de más a propósito txt = el.inner_text() # Si tiene signo pesos, es un candidato if "$" in txt: precio = extraer_precio_regex(txt) if precio > 500000: # Filtro de "precio lógico" (evitar precios de garajes solos) if precio > 500000: href = el.get_attribute("href") full_url = f"https://www.fincaraiz.com.co{href}" if href.startswith("/") else href 6 unmodified lines }) cont_fr += 1 page.close() log_visible += f"✅ FR: {cont_fr} datos extraídos.\n" log_visible += f"✅ FR: {cont_fr} datos brutos extraídos.\n" except Exception as e: log_visible += f"⚠️ Error FR: {e}\n"
# --- METROCUADRADO ---2 unmodified lines log_visible += "🔄 Conectando a MC...\n" page.goto(url_mc, wait_until="domcontentloaded", timeout=60000) page.mouse.move(random.randint(100, 500), random.randint(100, 500)) time.sleep(random.uniform(2, 4)) for _ in range(4): page.mouse.wheel(0, 1000) time.sleep(1) time.sleep(1.5) # MC suele usar Li o Div cards. Buscamos contenedores genéricos cards = page.query_selector_all("li, div[class*='card']") cont_mc = 0 for card in cards: if cont_mc >= 6: break if cont_mc >= 15: break # Extraemos de más a propósito txt = card.inner_text() if "$" in txt: precio = extraer_precio_regex(txt) if precio > 500000: # Buscamos el link dentro de esa tarjeta enlace = card.query_selector("a") if enlace: href = enlace.get_attribute("href")8 unmodified lines }) cont_mc += 1 page.close() log_visible += f"✅ MC: {cont_mc} datos extraídos.\n" log_visible += f"✅ MC: {cont_mc} datos brutos extraídos.\n" except Exception as e: log_visible += f"⚠️ Error MC: {e}\n" browser.close()
if not resultados: return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS. Bloqueo persistente.", None, None, "---" return f"{log_visible}\n❌ NO SE ENCONTRARON DATOS.", None, None, "---"
# --- LIMPIEZA DE DUPLICADOS Y LIMITACIÓN --- # 1. Convertimos a DataFrame df_crudo = pd.DataFrame(resultados) # 2. Borramos los que tienen la misma URL (los clones) df = pd.DataFrame(resultados).drop_duplicates(subset=['URL']) df_limpio = df_crudo.drop_duplicates(subset=['URL']) # PDF # 3. Forzamos a que sean máximo 6 únicos por cada portal df_fr_final = df_limpio[df_limpio['Portal'] == 'Finca Raiz'].head(6) df_mc_final = df_limpio[df_limpio['Portal'] == 'Metrocuadrado'].head(6) # 4. Unimos todo de nuevo df_final = pd.concat([df_fr_final, df_mc_final]).reset_index(drop=True) log_visible += f"\n🧹 Limpieza final: Quedaron {len(df_final)} inmuebles únicos y reales."
# --- PDF --- pdf_path = f"Reporte_{int(time.time())}.pdf" pdf = FPDF() pdf.add_page() pdf.set_font("Arial", 'B', 14) pdf.cell(0, 10, f"ESTUDIO {zona.upper()}", ln=True) pdf.ln(5) for _, r in df.iterrows(): for _, r in df_final.iterrows(): pdf.set_font("Arial", 'B', 10) pdf.cell(0, 8, f"${r['Precio']:,.0f} - {r['Portal']}", ln=True) pdf.set_font("Arial", '', 8)3 unmodified lines pdf.set_text_color(0,0,0); pdf.ln(3) pdf.output(pdf_path) # Cálculos promedio = df['Precio'].mean() minimo = df['Precio'].min() maximo = df['Precio'].max() # --- CÁLCULOS --- promedio = df_final['Precio_M2'].mean() * area minimo = df_final['Precio'].min() maximo = df_final['Precio'].max() resumen = ( f"💰 **ESTIMACIÓN DE RENTA**\n" f"🔹 **Promedio Zona:** ${promedio:,.0f}\n" f"📉 Mínimo: ${minimo:,.0f}\n" f"📈 Máximo: ${maximo:,.0f}" f"🔹 **Canon Sugerido:** ${promedio:,.0f}\n" f"📉 Mínimo Zona: ${minimo:,.0f}\n" f"📈 Máximo Zona: ${maximo:,.0f}" ) return f"{log_visible}\n✅ Proceso Terminado.", df, pdf_path, resumen return f"{log_visible}\n✅ Proceso Terminado.", df_final, pdf_path, resumen
# --- INTERFAZ ---with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("## 🤖 TramitIA Pro: Modo Camuflaje") gr.Markdown("## 🤖 TramitIA Pro: Extracción Balanceada") with gr.Row(): with gr.Column(scale=1): c = gr.Textbox(label="Ciudad", value="Bogota") z = gr.Textbox(label="Zona", value="Fontibon") z = gr.Textbox(label="Zona (Ej: Usaquen)", value="Usaquen") a = gr.Number(label="Área M2", value=60) t = gr.Dropdown(["Apartamento", "Casa"], label="Tipo", value="Apartamento") with gr.Row(): h = gr.Number(label="Hab", value=3) h = gr.Number(label="Habitaciones", value=3) b = gr.Number(label="Baños", value=2) p = gr.Number(label="Park", value=1) p = gr.Number(label="Parqueaderos", value=1) e = gr.Dropdown( ["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"],4 unmodified lines with gr.Column(scale=2): res_fin = gr.Markdown("### 💰 Resultado...") with gr.Tabs(): with gr.TabItem("Log"): msg = gr.Textbox() with gr.TabItem("Tabla"): out_df = gr.Dataframe() with gr.TabItem("PDF"): out_pdf = gr.File() with gr.TabItem("Auditoría"): msg = gr.Textbox(lines=8) with gr.TabItem("Comparables (Únicos)"): out_df = gr.Dataframe() with gr.TabItem("Descargar PDF"): out_pdf = gr.File()
btn.click(motor_tramitia_camuflado, [z, c, a, t, h, b, p, e], [msg, out_df, out_pdf, res_fin])
app.py+55-70