Update app.py
Browse files11 unmodified lines1213141516171819202122232425262728291 unmodified line3132333435363738394041424344454647484950515253545556575859606162636465666710 unmodified lines7879808182838485868788899091929394959697982 unmodified lines10110210310410510610710810911011111211311411514 unmodified lines1301311321331341351361371381391401411421431444 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552564 unmodified lines26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538611 unmodified linesimport tracebackimport logging# Selenium: la herramienta para sitios web dinámicos (JavaScript)from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom webdriver_manager.chrome import ChromeDriverManager# --- CONFIGURACIÓN ---TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")HISTORY_FILE = "history.json"USER_AGENTS = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",1 unmodified line"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.2 Safari/605.1.15"]MAX_WORKERS = 3 # Máximo de hilos para ejecución concurrenteREQUEST_TIMEOUT = 20 # Tiempo máximo para peticiones HTTPSELENIUM_TIMEOUT = 30 # Tiempo máximo para esperas en Selenium# Configuración de logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# --- GESTIÓN DEL HISTORIAL ---def cargar_historial():"""Carga el historial de búsquedas desde el archivo JSON"""if os.path.exists(HISTORY_FILE):try:with open(HISTORY_FILE, 'r', encoding='utf-8') as f:return json.load(f)except (json.JSONDecodeError, IOError) as e:logger.error(f"Error cargando historial: {str(e)}")return {}return {}def guardar_historial(historial):"""Guarda el historial de búsquedas en el archivo JSON"""try:with open(HISTORY_FILE, 'w', encoding='utf-8') as f:json.dump(historial, f, indent=4, ensure_ascii=False)except IOError as e:logger.error(f"Error guardando historial: {str(e)}")# --- SCRAPERS ---def buscar_ebay(modelo, precio_max):"""Busca productos en eBay España"""resultados = []url = f"https://www.ebay.es/sch/i.html?_from=R40&_nkw={modelo.replace(' ', '+')}&_sacat=0&LH_ItemCondition=3000&_udhi={precio_max}"logger.info(f"Buscando en eBay: {url}")10 unmodified linesfor item in items:try:title_elem = item.select_one('div.s-item__title > span')if not title_elem:continuetitulo = title_elem.text.strip()if "Anuncio de" in titulo or titulo.lower() == "usado":continueprice_elem = item.select_one('span.s-item__price')link_elem = item.select_one('a.s-item__link')if price_elem and link_elem:precio_texto = price_elem.text.replace('EUR', '').replace('€', '').replace('.', '').replace(',', '.').strip()precio_match = re.search(r'(\d+\.?\d*)', precio_texto)if precio_match:precio = float(precio_match.group(1))if precio <= precio_max:resultados.append({2 unmodified lines"enlace": link_elem['href'],"fuente": "eBay"})except Exception as e:logger.error(f"Error procesando item eBay: {str(e)}")except Exception as e:logger.error(f"Error en eBay: {str(e)}")return resultadosdef buscar_cashconverters(modelo, precio_max):"""Busca productos en Cash Converters España"""resultados = []url = f"https://es.cashconverters.es/es/es/search.html?q={modelo.replace(' ', '+')}"logger.info(f"Buscando en Cash Converters: {url}")14 unmodified linesif title_link_elem and price_elem:precio_texto = price_elem.text.replace('€', '').replace('.', '').replace(',', '.').strip()precio_match = re.search(r'(\d+\.?\d*)', precio_texto)if precio_match:precio = float(precio_match.group(1))if precio <= precio_max:titulo = title_link_elem.get('title', '').strip()if not titulo:titulo = title_link_elem.text.strip()enlace = title_link_elem.get('href', '')if not enlace.startswith('http'):enlace = f"https://es.cashconverters.es{enlace}"4 unmodified lines"enlace": enlace,"fuente": "Cash Converters"})except Exception as e:logger.error(f"Error procesando item Cash Converters: {str(e)}")except Exception as e:logger.error(f"Error en Cash Converters: {str(e)}")return resultadosdef buscar_wallapop(modelo, precio_max):"""Busca en Wallapop usando Selenium para manejar JavaScript"""resultados = []url = f"https://es.wallapop.com/app/search?keywords={modelo.replace(' ', '%20')}&max_price={int(precio_max)}"logger.info(f"Buscando en Wallapop: {url}")# Configuración de Seleniumchrome_options = Options()chrome_options.add_argument("--headless")chrome_options.add_argument("--no-sandbox")chrome_options.add_argument("--disable-dev-shm-usage")chrome_options.add_argument("--disable-gpu")chrome_options.add_argument("--window-size=1920,1080")chrome_options.add_argument(f"user-agent={random.choice(USER_AGENTS)}")chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])driver = Nonetry:# Inicia el navegador Chromeservice = ChromeService(ChromeDriverManager().install())driver = webdriver.Chrome(service=service, options=chrome_options)driver.get(url)logger.info("Navegador Chrome iniciado para Wallapop")# 1. Intentar aceptar cookiestry:accept_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler")))accept_button.click()logger.info("Cookies aceptadas en Wallapop")time.sleep(1) # Pequeña pausa después de aceptar cookiesexcept Exception as e:logger.warning(f"No se pudo aceptar cookies en Wallapop: {str(e)}")# 2. Esperar a que los productos carguen (CORRECCIÓN APLICADA)WebDriverWait(driver, SELENIUM_TIMEOUT).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.Card_card__g6_C4")))logger.info("Productos cargados en Wallapop")# 3. Hacer scroll para cargar más productosdriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")time.sleep(2) # Esperar a que carguen nuevos items# 4. Procesar los resultadossoup = BeautifulSoup(driver.page_source, 'html.parser')items = soup.select("div.Card_card__g6_C4")logger.info(f"Wallapop: {len(items)} items encontrados")for item in items:try:title_elem = item.select_one("p.Card_title__Y5aG4")price_elem = item.select_one("span.Price_price__2hT3C")link_elem = item.select_one("a.Card_card-link__fUfPr")if all([title_elem, price_elem, link_elem]):titulo = title_elem.text.strip()enlace = "https://es.wallapop.com" + link_elem['href']# Limpieza de precioprecio_texto = price_elem.text.replace('€', '').strip()precio = float(precio_texto)resultados.append({"titulo": titulo,"precio": precio,"enlace": enlace,"fuente": "Wallapop"})except Exception as e:logger.error(f"Error procesando item Wallapop: {str(e)}")except Exception as e:logger.error(f"Error en Wallapop: {str(e)}")logger.debug(traceback.format_exc())finally:if driver:driver.quit()logger.info("Navegador Chrome cerrado")return resultados# --- ORQUESTADOR PRINCIPAL ---def ejecutar_scrapers(modelo, precio_max):"""Ejecuta todos los scrapers de forma concurrente"""scrapers = [(buscar_ebay, modelo, precio_max),(buscar_cashconverters, modelo, precio_max),(buscar_wallapop, modelo, precio_max)]resultados = []with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:futures = {executor.submit(scraper[0], *scraper[1:]): scraper for scraper in scrapers}for future in concurrent.futures.as_completed(futures):try:4 unmodified linesreturn resultadosdef buscar_ofertas(modelo, precio_max):"""Función principal para buscar ofertas"""if not modelo or not isinstance(precio_max, (int, float)) or precio_max <= 0:return "⚠️ Modelo y precio máximo son obligatorios.", []start_time = time.time()historial = cargar_historial()logger.info(f"\n--- INICIANDO BÚSQUEDA: {modelo} hasta {precio_max}€ ---")# Ejecutar todos los scrapers concurrentementeresultados_totales = ejecutar_scrapers(modelo, float(precio_max))logger.info(f"BÚSQUEDA COMPLETADA. Resultados brutos: {len(resultados_totales)}. Tiempo: {time.time()-start_time:.2f}s")# Filtrar duplicados y ordenarseen = set()resultados_unicos = []for item in resultados_totales:item_hash = hashlib.md5(item['enlace'].encode('utf-8')).hexdigest()if item_hash not in seen:seen.add(item_hash)resultados_unicos.append(item)resultados_ordenados = sorted(resultados_unicos, key=lambda x: x['precio'])# Preparar resultados para la UInuevos_items = []tabla_display = []for item in resultados_ordenados:item_hash = hashlib.md5(item['enlace'].encode('utf-8')).hexdigest()tabla_display.append([item['titulo'],f"{item['precio']:.2f} €",item['fuente'],item['enlace']])if item_hash not in historial:nuevos_items.append(item)historial[item_hash] = {"descubierto": datetime.now().isoformat(),"titulo": item['titulo'],"precio": item['precio']}guardar_historial(historial)mensaje = f"✅ Búsqueda completada: {len(tabla_display)} anuncios. ✨ Nuevos: {len(nuevos_items)}"logger.info(mensaje)return mensaje, tabla_display# --- INTERFAZ DE GRADIO (VERSIÓN SIMPLIFICADA Y COMPATIBLE) ---with gr.Blocks(theme=gr.themes.Soft(), title="Buscador de Chollos") as app:gr.Markdown("# 🤖 Buscador de Chollos v3.0")gr.Markdown("""**Encuentra las mejores ofertas en eBay, Cash Converters y Wallapop**⚠️ La búsqueda en Wallapop es más lenta porque usa un navegador real.⏱️ Por favor, ten paciencia (puede tomar 30-60 segundos).""")with gr.Row():with gr.Column(scale=3):modelo_input = gr.Textbox(label="Modelo del producto",placeholder="Ej: Fujifilm X100V, iPhone 15 Pro, Nintendo Switch",value="Fujifilm X100V")with gr.Column(scale=1):precio_input = gr.Number(label="Precio Máximo (€)",minimum=1,maximum=100000,value=1000)buscar_btn = gr.Button("🚀 Buscar en TODAS las tiendas", variant="primary")with gr.Row():estado_output = gr.Textbox(label="Estado",interactive=False,placeholder="Esperando para buscar...")with gr.Row():# Configuración simplificada y compatible del DataFrameresultados_output = gr.DataFrame(label="Resultados de la Búsqueda",headers=["Producto", "Precio", "Tienda", "Enlace"],interactive=False,col_count=(4, "fixed"))# Ejemplos predefinidosgr.Examples(examples=[["Fujifilm X100V", 1000],["Sony A7 III", 1500],["Nintendo Switch OLED", 250],["iPhone 15 Pro", 900]],inputs=[modelo_input, precio_input],label="Ejemplos rápidos:")# Pie de páginagr.Markdown("""---*Nota: Los resultados pueden variar dependiendo de la disponibilidad en cada plataforma.**Este buscador es solo con fines educativos y de demostración.*""")buscar_btn.click(fn=buscar_ofertas,inputs=[modelo_input, precio_input],outputs=[estado_output, resultados_output],api_name="buscar_ofertas")if __name__ == "__main__":11 unmodified lines12131415161718192021221 unmodified line24252627282930313233343536373839404142434445464748495051525310 unmodified lines64656667686970717273747576777879802 unmodified lines838485868788899091929394959614 unmodified lines1111121131141151161171181191204 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272284 unmodified lines23323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733811 unmodified linesimport tracebackimport logging# Configuración de logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# --- CONFIGURACIÓN ---HISTORY_FILE = "history.json"USER_AGENTS = ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",1 unmodified line"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.2 Safari/605.1.15"]MAX_WORKERS = 3REQUEST_TIMEOUT = 15SELENIUM_TIMEOUT = 25# --- GESTIÓN DEL HISTORIAL ---def cargar_historial():if os.path.exists(HISTORY_FILE):try:with open(HISTORY_FILE, 'r', encoding='utf-8') as f:return json.load(f)except Exception as e:logger.error(f"Error cargando historial: {str(e)}")return {}return {}def guardar_historial(historial):try:with open(HISTORY_FILE, 'w', encoding='utf-8') as f:json.dump(historial, f, indent=4, ensure_ascii=False)except Exception as e:logger.error(f"Error guardando historial: {str(e)}")# --- SCRAPERS ESTÁTICOS ---def buscar_ebay(modelo, precio_max):resultados = []url = f"https://www.ebay.es/sch/i.html?_from=R40&_nkw={modelo.replace(' ', '+')}&_sacat=0&LH_ItemCondition=3000&_udhi={precio_max}"logger.info(f"Buscando en eBay: {url}")10 unmodified linesfor item in items:try:title_elem = item.select_one('div.s-item__title > span')if not title_elem: continuetitulo = title_elem.text.strip()if "Anuncio de" in titulo: continueprice_elem = item.select_one('span.s-item__price')link_elem = item.select_one('a.s-item__link')if price_elem and link_elem:precio_texto = price_elem.text.replace('EUR', '').replace('€', '').replace('.', '').replace(',', '.').strip()if precio_match := re.search(r'(\d+\.?\d*)', precio_texto):precio = float(precio_match.group(1))if precio <= precio_max:resultados.append({2 unmodified lines"enlace": link_elem['href'],"fuente": "eBay"})except Exception:continueexcept Exception as e:logger.error(f"Error en eBay: {str(e)}")return resultadosdef buscar_cashconverters(modelo, precio_max):resultados = []url = f"https://es.cashconverters.es/es/es/search.html?q={modelo.replace(' ', '+')}"logger.info(f"Buscando en Cash Converters: {url}")14 unmodified linesif title_link_elem and price_elem:precio_texto = price_elem.text.replace('€', '').replace('.', '').replace(',', '.').strip()if precio_match := re.search(r'(\d+\.?\d*)', precio_texto):precio = float(precio_match.group(1))if precio <= precio_max:titulo = title_link_elem.get('title', '').strip() or title_link_elem.text.strip()enlace = title_link_elem.get('href', '')if not enlace.startswith('http'):enlace = f"https://es.cashconverters.es{enlace}"4 unmodified lines"enlace": enlace,"fuente": "Cash Converters"})except Exception:continueexcept Exception as e:logger.error(f"Error en Cash Converters: {str(e)}")return resultados# --- SCRAPER DINÁMICO (SELENIUM) ---def buscar_wallapop(modelo, precio_max):"""Busca en Wallapop usando Selenium (optimizado para espacios limitados)"""from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom webdriver_manager.chrome import ChromeDriverManagerresultados = []url = f"https://es.wallapop.com/app/search?keywords={modelo.replace(' ', '%20')}&max_price={int(precio_max)}"logger.info(f"Buscando en Wallapop: {url}")try:chrome_options = Options()chrome_options.add_argument("--headless=new")chrome_options.add_argument("--no-sandbox")chrome_options.add_argument("--disable-dev-shm-usage")chrome_options.add_argument("--disable-gpu")chrome_options.add_argument("--window-size=1280,720")chrome_options.add_argument(f"user-agent={random.choice(USER_AGENTS)}")chrome_options.add_argument("--disable-extensions")chrome_options.add_argument("--disable-software-rasterizer")chrome_options.add_argument("--disable-setuid-sandbox")service = ChromeService(ChromeDriverManager().install())driver = webdriver.Chrome(service=service, options=chrome_options)driver.set_page_load_timeout(SELENIUM_TIMEOUT)driver.get(url)logger.info("Navegador Chrome iniciado")# Intentar aceptar cookiestry:WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))).click()logger.info("Cookies aceptadas")time.sleep(1)except Exception:logger.warning("No se pudo aceptar cookies")# Esperar resultadosWebDriverWait(driver, SELENIUM_TIMEOUT).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.Card_card__g6_C4")))logger.info("Productos cargados")# Procesar HTMLsoup = BeautifulSoup(driver.page_source, 'html.parser')for item in soup.select("div.Card_card__g6_C4"):try:title_elem = item.select_one("p.Card_title__Y5aG4")price_elem = item.select_one("span.Price_price__2hT3C")link_elem = item.select_one("a.Card_card-link__fUfPr")if all([title_elem, price_elem, link_elem]):precio = float(price_elem.text.replace('€', '').strip())resultados.append({"titulo": title_elem.text.strip(),"precio": precio,"enlace": "https://es.wallapop.com" + link_elem['href'],"fuente": "Wallapop"})except Exception:continueexcept Exception as e:logger.error(f"Error en Wallapop: {str(e)}")finally:if 'driver' in locals():driver.quit()logger.info("Navegador cerrado")return resultados# --- ORQUESTADOR PRINCIPAL ---def ejecutar_scrapers(modelo, precio_max):scrapers = [buscar_ebay, buscar_cashconverters]# Ejecutar Wallapop solo si el precio es razonableif precio_max <= 2000:scrapers.append(buscar_wallapop)else:logger.info("Saltando Wallapop (precio máximo muy alto)")resultados = []with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:futures = {executor.submit(scraper, modelo, precio_max): scraper for scraper in scrapers}for future in concurrent.futures.as_completed(futures):try:4 unmodified linesreturn resultadosdef buscar_ofertas(modelo, precio_max):if not modelo or precio_max <= 0:return "⚠️ Modelo y precio máximo son obligatorios.", []start_time = time.time()historial = cargar_historial()# Limitar parámetros para evitar abusosmodelo = modelo[:50]precio_max = min(float(precio_max), 5000)logger.info(f"Búsqueda iniciada: {modelo} hasta {precio_max}€")try:resultados_totales = ejecutar_scrapers(modelo, precio_max)except Exception as e:logger.error(f"Error crítico: {str(e)}")return f"❌ Error: {str(e)}", []logger.info(f"Resultados brutos: {len(resultados_totales)} | Tiempo: {time.time()-start_time:.1f}s")# Procesar resultadosseen = set()resultados_unicos = []nuevos_items = []tabla_display = []for item in sorted(resultados_totales, key=lambda x: x['precio']):item_hash = hashlib.md5(item['enlace'].encode()).hexdigest()if item_hash not in seen:seen.add(item_hash)resultados_unicos.append(item)# Formatear para tablatabla_display.append([item['titulo'][:100] + ("..." if len(item['titulo']) > 100 else ""),f"{item['precio']:.2f} €",item['fuente'],item['enlace']])if item_hash not in historial:nuevos_items.append(item)historial[item_hash] = datetime.now().isoformat()guardar_historial(historial)mensaje = f"✅ {len(tabla_display)} resultados | ✨ {len(nuevos_items)} nuevos"return mensaje, tabla_display# --- INTERFAZ GRADIO OPTIMIZADA ---with gr.Blocks(title="Buscador de Chollos", theme=gr.themes.Soft()) as app:gr.Markdown("## 🔍 Buscador de Ofertas")gr.Markdown("Busca productos en eBay, Cash Converters y Wallapop")with gr.Row():modelo_input = gr.Textbox(label="Producto",placeholder="Ej: iPhone 15, Nintendo Switch",max_lines=1,value="Fujifilm X100V")precio_input = gr.Number(label="Precio Máximo (€)",value=1000,minimum=1,maximum=5000)buscar_btn = gr.Button("Buscar", variant="primary")estado_output = gr.Textbox(label="Estado",interactive=False,value="Esperando búsqueda...")resultados_output = gr.DataFrame(label="Resultados",headers=["Producto", "Precio", "Tienda", "Enlace"],interactive=False,wrap=True,max_rows=20)gr.Examples(examples=[["PlayStation 5", 400],["Macbook Air M2", 900],["Kindle Paperwhite", 100],["Nikon Z5", 800]],inputs=[modelo_input, precio_input])gr.Markdown("> ⚠️ Wallapop puede tardar hasta 30 segundos")buscar_btn.click(buscar_ofertas,inputs=[modelo_input, precio_input],outputs=[estado_output, resultados_output])if __name__ == "__main__":
app.py+136-184