Spaces:
Runtime error
Runtime error
Update app.py
Browse files19 unmodified lines202122232425264 unmodified lines3132333435363738394041424344454647484950515253545 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929394951 unmodified line9798991001011021031041051061071081091101111121131141151161171181191201211221231246 unmodified lines1311321331341351361372 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631648 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951963 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332344 unmodified lines23924024124224324424524624719 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 1. GENERADOR DE URLS ---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}"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 $1500000patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:# Convertir a entero: quitar puntos y comasprecios = [int(p.replace('.', '').replace(',', '')) for p in coincidencias]return max(precios) # Retorna el precio más alto encontrado en el textoreturn 0# --- 3. MOTOR DE EXTRACCIÓN CAMUFLADO ---5 unmodified linesua = UserAgent()with sync_playwright() as p:# LANZAMIENTO EN MODO FURTIVObrowser = p.chromium.launch(headless=True,args=['--disable-blink-features=AutomationControlled', # Oculta que es un robot'--no-sandbox','--disable-setuid-sandbox','--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 humanocontext = browser.new_context(user_agent=ua.random,viewport={'width': 1366, 'height': 768},locale='es-CO',timezone_id='America/Bogota')# Script para evasión de detección de WebDriverinit_script = """Object.defineProperty(navigator, 'webdriver', {get: () => undefined});"""context.add_init_script(init_script)# --- FINCA RAÍZ ---try:1 unmodified linelog_visible += "🔄 Conectando a FR...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)# Simulamos comportamiento humano antes de buscarpage.mouse.move(random.randint(100, 500), random.randint(100, 500))page.mouse.wheel(0, 500)time.sleep(random.uniform(2, 4))# Scroll lentofor _ in range(3):page.mouse.wheel(0, 1500)time.sleep(1)# ESTRATEGIA: Buscar TODOS los enlaces que contengan un precio dentroelementos = page.query_selector_all("a") # Buscamos cualquier linkcont_fr = 0for el in elementos:if cont_fr >= 6: breaktxt = el.inner_text()# Si tiene signo pesos, es un candidatoif "$" in txt:precio = extraer_precio_regex(txt)if precio > 500000: # Filtro de "precio lógico" (evitar precios de garajes solos)href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href.startswith("/") else href6 unmodified lines})cont_fr += 1page.close()log_visible += f"✅ FR: {cont_fr} datos extraídos.\n"except Exception as e: log_visible += f"⚠️ Error FR: {e}\n"# --- METROCUADRADO ---2 unmodified lineslog_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)# MC suele usar Li o Div cards. Buscamos contenedores genéricoscards = page.query_selector_all("li, div[class*='card']")cont_mc = 0for card in cards:if cont_mc >= 6: breaktxt = card.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 500000:# Buscamos el link dentro de esa tarjetaenlace = card.query_selector("a")if enlace:href = enlace.get_attribute("href")8 unmodified lines})cont_mc += 1page.close()log_visible += f"✅ MC: {cont_mc} datos 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, "---"df = pd.DataFrame(resultados).drop_duplicates(subset=['URL'])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():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 linespdf.set_text_color(0,0,0); pdf.ln(3)pdf.output(pdf_path)# Cálculospromedio = df['Precio'].mean()minimo = df['Precio'].min()maximo = df['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}")return f"{log_visible}\n✅ Proceso Terminado.", df, pdf_path, resumen# --- INTERFAZ ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("## 🤖 TramitIA Pro: Modo Camuflaje")with gr.Row():with gr.Column(scale=1):c = gr.Textbox(label="Ciudad", value="Bogota")z = gr.Textbox(label="Zona", value="Fontibon")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)b = gr.Number(label="Baños", value=2)p = gr.Number(label="Park", 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 lineswith 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()btn.click(motor_tramitia_camuflado, [z, c, a, t, h, b, p, e], [msg, out_df, out_pdf, res_fin])19 unmodified lines202122232425264 unmodified lines313233343536373839404142434445464748495051525354555 unmodified lines61626364656667686970717273747576777879801 unmodified line8283848586878889909192939495969798991001011026 unmodified lines1091101111121131141152 unmodified lines1181191201211221231241251261271281291301311321331341351368 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801813 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182194 unmodified lines22422522622722822923023123219 unmodified linessubprocess.run(["pip", "install", "fake-useragent"], check=True)from fake_useragent import UserAgent# --- 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"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}"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):patron = r'\$\s?(\d{1,3}(?:[.,]\d{3})*)'coincidencias = re.findall(patron, texto)if coincidencias:precios = [int(p.replace('.', '').replace(',', '')) for p in coincidencias]return max(precios)return 0# --- 3. MOTOR DE EXTRACCIÓN CAMUFLADO ---5 unmodified linesua = UserAgent()with sync_playwright() as p:browser = p.chromium.launch(headless=True,args=['--disable-blink-features=AutomationControlled','--no-sandbox','--disable-infobars'])context = browser.new_context(user_agent=ua.random,viewport={'width': 1366, 'height': 768},locale='es-CO')context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")# --- FINCA RAÍZ ---try:1 unmodified linelog_visible += "🔄 Conectando a FR...\n"page.goto(url_fr, wait_until="domcontentloaded", timeout=60000)page.mouse.move(200, 200)for _ in range(4):page.mouse.wheel(0, 1500)time.sleep(1.5)# Buscamos enlaces (aumentamos a 20 para sobrevivir a la eliminación de duplicados)elementos = page.query_selector_all("a")cont_fr = 0for el in elementos:if cont_fr >= 15: break # Extraemos de más a propósitotxt = el.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 500000:href = el.get_attribute("href")full_url = f"https://www.fincaraiz.com.co{href}" if href.startswith("/") else href6 unmodified lines})cont_fr += 1page.close()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 lineslog_visible += "🔄 Conectando a MC...\n"page.goto(url_mc, wait_until="domcontentloaded", timeout=60000)for _ in range(4):page.mouse.wheel(0, 1000)time.sleep(1.5)cards = page.query_selector_all("li, div[class*='card']")cont_mc = 0for card in cards:if cont_mc >= 15: break # Extraemos de más a propósitotxt = card.inner_text()if "$" in txt:precio = extraer_precio_regex(txt)if precio > 500000:enlace = card.query_selector("a")if enlace:href = enlace.get_attribute("href")8 unmodified lines})cont_mc += 1page.close()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.", None, None, "---"# --- LIMPIEZA DE DUPLICADOS Y LIMITACIÓN ---# 1. Convertimos a DataFramedf_crudo = pd.DataFrame(resultados)# 2. Borramos los que tienen la misma URL (los clones)df_limpio = df_crudo.drop_duplicates(subset=['URL'])# 3. Forzamos a que sean máximo 6 únicos por cada portaldf_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 nuevodf_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_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 linespdf.set_text_color(0,0,0); pdf.ln(3)pdf.output(pdf_path)# --- CÁLCULOS ---promedio = df_final['Precio_M2'].mean() * areaminimo = df_final['Precio'].min()maximo = 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}")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: Extracción Balanceada")with gr.Row():with gr.Column(scale=1):c = gr.Textbox(label="Ciudad", value="Bogota")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="Habitaciones", value=3)b = gr.Number(label="Baños", value=2)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 lineswith gr.Column(scale=2):res_fin = gr.Markdown("### 💰 Resultado...")with gr.Tabs():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