Spaces:
Sleeping
Sleeping
Download app.py from PensionPlus/Consulta2.0: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/PensionPlus/Consulta2.0/resolve/main/app.py
- Command line
-
hf download hf://spaces/PensionPlus/Consulta2.0/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PensionPlus/Consulta2.0/resolve/main/app.py
11.2 kB
| import gradio as gr | |
| import requests | |
| from datetime import datetime | |
| import csv | |
| import io | |
| def limpiar_cedula(cedula): | |
| """Limpia la cédula: quita comas, puntos, espacios y asegura que sea una cadena.""" | |
| if not cedula: | |
| return "" | |
| # Asegura que sea una cadena antes de limpiar | |
| cedula_limpia = ''.join(filter(str.isdigit, str(cedula))) | |
| return cedula_limpia | |
| def formatear_valor(valor): | |
| """Formatea el valor monetario si es posible""" | |
| if not valor or valor == 'N/A': | |
| return 'N/A' | |
| try: | |
| # Intentar limpiar y convertir a número | |
| valor_limpio = str(valor).replace(',', '').replace('$', '').strip() | |
| # Verificar si lo que queda es un número (puede tener un punto decimal) | |
| if valor_limpio and valor_limpio.replace('.', '', 1).isdigit(): | |
| valor_num = float(valor_limpio) | |
| return f"${valor_num:,.0f}" | |
| return valor | |
| except: | |
| return valor | |
| def obtener_valor(fila, clave, default='N/A'): | |
| """Obtiene el valor de la fila, lo limpia y maneja valores vacíos.""" | |
| # La clave debe coincidir exactamente con el encabezado de la hoja de cálculo | |
| valor = fila.get(clave, '').strip() | |
| return valor if valor else default | |
| def buscar_cliente(cedula): | |
| if not cedula or not cedula.strip(): | |
| return "**💫 Vas a llegar a la comisión de tus sueños. Piensa en tus metas.**" | |
| try: | |
| # URL de exportación a CSV de la hoja de cálculo de Google | |
| # NOTA: Asegúrate que esta hoja sea PÚBLICA (Compartir → "Cualquier persona con el enlace puede ver") | |
| sheets_url = "https://docs.google.com/spreadsheets/d/1Blec5K6L6ks1Xl14iqIhcB955Fafbv3EUcXysrDGjcE/export?format=csv" | |
| # Agregar headers para evitar bloqueos | |
| 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' | |
| } | |
| response = requests.get(sheets_url, headers=headers, timeout=10) | |
| response.raise_for_status() | |
| content = response.content.decode('utf-8-sig') # Usar utf-8-sig para manejar BOM | |
| csv_reader = csv.DictReader(io.StringIO(content)) | |
| # Verificar que hay columnas | |
| if not csv_reader.fieldnames: | |
| return f"""<div style='background: #f8d7da; border-left: 4px solid #dc3545; padding: 20px; border-radius: 5px; text-align: center;'> | |
| <h3>⚠️ ERROR EN LA HOJA DE CÁLCULO</h3> | |
| <p>La hoja de cálculo no tiene encabezados válidos.</p> | |
| <p>Verifica que la primera fila tenga: Cédula, Nombre, Etapa actual, etc.</p> | |
| </div>""" | |
| cedula_limpia_busqueda = limpiar_cedula(cedula) | |
| # Mostrar las columnas disponibles para debugging (opcional) | |
| # print(f"Columnas encontradas: {csv_reader.fieldnames}") | |
| for fila in csv_reader: | |
| # Buscar en la columna 'Cédula' - verificar diferentes variantes posibles | |
| cedula_en_fila = obtener_valor(fila, 'Cédula') | |
| # Si no encuentra con 'Cédula', probar con otros nombres comunes | |
| if not cedula_en_fila or cedula_en_fila == 'N/A': | |
| cedula_en_fila = obtener_valor(fila, 'Cedula') # Sin acento | |
| if not cedula_en_fila or cedula_en_fila == 'N/A': | |
| cedula_en_fila = obtener_valor(fila, 'CEDULA') | |
| if cedula_limpia_busqueda == limpiar_cedula(cedula_en_fila): | |
| # Definición de variables con los datos de la fila encontrada | |
| cedula_cliente = obtener_valor(fila, 'Cédula') | |
| if cedula_cliente == 'N/A': | |
| cedula_cliente = obtener_valor(fila, 'Cedula') | |
| if cedula_cliente == 'N/A': | |
| cedula_cliente = obtener_valor(fila, 'CEDULA') | |
| nombre = obtener_valor(fila, 'Nombre') | |
| etapa = obtener_valor(fila, 'Etapa actual') | |
| pagaduria = obtener_valor(fila, 'Pagaduría') | |
| financiera = obtener_valor(fila, 'Financiera') | |
| valor_credito = formatear_valor(obtener_valor(fila, 'Valor')) | |
| asesor = obtener_valor(fila, 'Asesor') | |
| servicio = obtener_valor(fila, 'Servicio') | |
| condiciones = obtener_valor(fila, 'Condiciones') # Cambiado a minúsculas | |
| observaciones = obtener_valor(fila, 'Observaciones') | |
| actualizado = obtener_valor(fila, 'Actualizado') | |
| # IMPORTANTE: Eliminamos 'analista' que no estaba definido en tus variables | |
| # Si necesitas analista, debes agregarlo a la hoja y definirlo aquí | |
| return f"""<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 10px; margin-bottom: 15px;'> | |
| <h3>✅ CLIENTE ENCONTRADO</h3> | |
| </div> | |
| <div style='background: #f8f9fa; border-left: 4px solid #667eea; padding: 15px; border-radius: 5px; font-family: Arial, sans-serif;'> | |
| <table style="width: 100%; border-collapse: collapse;"> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee; width: 30%;"><strong>👤 Nombre:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{nombre}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>📋 Cédula:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{cedula_cliente}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>📊 Etapa actual:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{etapa}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>🏦 Pagaduría:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{pagaduria}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>💰 Financiera:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{financiera}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>💵 Valor:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{valor_credito}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>👨💼 Asesor:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{asesor}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>🔧 Servicio:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{servicio}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>📝 Condiciones:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{condiciones}</td></tr> | |
| <tr><td style="padding: 8px; border-bottom: 1px solid #eee;"><strong>💬 Observaciones:</strong></td><td style="padding: 8px; border-bottom: 1px solid #eee;">{observaciones}</td></tr> | |
| <tr><td style="padding: 8px;"><strong>🕐 Actualizado:</strong></td><td style="padding: 8px;">{actualizado}</td></tr> | |
| </table> | |
| </div> | |
| <div style='background: #e8f5e8; padding: 10px; border-radius: 5px; margin-top: 10px; font-size: 12px; color: #2d5016;'> | |
| 🕐 Consulta: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} | |
| </div>""" | |
| # Si termina el bucle sin encontrar | |
| return f"""<div style='background: #fff3cd; border-left: 4px solid #ffc107; padding: 20px; border-radius: 5px; text-align: center;'> | |
| <h3>❌ CLIENTE NO ENCONTRADO</h3> | |
| <p><strong>Cédula:</strong> {cedula}</p> | |
| <p>Verifique el número o contacte al administrador.</p> | |
| </div>""" | |
| except requests.exceptions.RequestException as req_err: | |
| error_msg = f"Error de red/petición: {str(req_err)}" | |
| print(error_msg) | |
| return f"""<div style='background: #f8d7da; border-left: 4px solid #dc3545; padding: 20px; border-radius: 5px; text-align: center;'> | |
| <h3>⚠️ ERROR AL CARGAR DATOS</h3> | |
| <p>No se pudo acceder a la hoja de cálculo.</p> | |
| <p>Verifica que la hoja sea pública y la URL sea correcta.</p> | |
| <p style="font-size: 10px; color: #666;">Detalle: {error_msg}</p> | |
| </div>""" | |
| except Exception as e: | |
| error_msg = str(e) | |
| print(f"Error inesperado: {error_msg}") | |
| return f"""<div style='background: #f8d7da; border-left: 4px solid #dc3545; padding: 20px; border-radius: 5px; text-align: center;'> | |
| <h3>⚠️ ERROR TEMPORAL</h3> | |
| <p>Estamos solucionando el problema técnico.</p> | |
| <p style="font-size: 10px; color: #666;">Error: {error_msg}</p> | |
| </div>""" | |
| # Interfaz más elegante | |
| with gr.Blocks( | |
| theme="soft", | |
| css=""" | |
| .gradio-container { max-width: 800px; margin: 0 auto; } | |
| .header { | |
| background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| color: white; | |
| padding: 25px; | |
| border-radius: 10px; | |
| text-align: center; | |
| margin-bottom: 20px; | |
| } | |
| .primary-button { | |
| height: 60px !important; | |
| font-size: 1.1em !important; | |
| } | |
| """, | |
| ) as demo: | |
| gr.Markdown(""" | |
| <div class="header"> | |
| <h1>🔍 CONSULTA DE ESTADO</h1> | |
| <p><strong>Vas a llegar a la comisión de tus sueños. Piensa en tus metas. 💫</strong></p> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| cedula_input = gr.Textbox( | |
| label="**INGRESE LA CÉDULA DEL CLIENTE**", | |
| placeholder="Ej: 1000000001, 444343, 8568...", | |
| max_lines=1, | |
| elem_id="cedula_input" | |
| ) | |
| buscar_btn = gr.Button("🔍 CONSULTAR ESTADO", variant="primary", elem_classes="primary-button") | |
| gr.Markdown("---") | |
| resultado = gr.HTML( | |
| value=""" | |
| <div style=' | |
| background: #f8f9fa; | |
| padding: 20px; | |
| border-radius: 5px; | |
| text-align: center; | |
| border: 2px dashed #ddd; | |
| '> | |
| <h3>👋 BIENVENIDO/A</h3> | |
| <p>Ingrese una cédula para consultar el estado del crédito.</p> | |
| </div> | |
| """ | |
| ) | |
| buscar_btn.click(buscar_cliente, inputs=cedula_input, outputs=resultado) | |
| cedula_input.submit(buscar_cliente, inputs=cedula_input, outputs=resultado) | |
| # Para subir a WordPress, necesitas: | |
| # 1. Guardar este archivo como consulta.py | |
| # 2. Instalar dependencias: pip install gradio requests | |
| # 3. Ejecutar: python consulta.py | |
| # 4. El servidor se ejecutará en http://localhost:7860 | |
| # 5. Para integrarlo en WordPress, puedes usar un iframe o el plugin de Gradio | |
| if __name__ == "__main__": | |
| # Para producción, considera cambiar estos parámetros | |
| demo.launch( | |
| server_name="0.0.0.0", # Permite conexiones externas | |
| server_port=7860, | |
| share=False # Cambia a True si quieres un enlace público temporal | |
| ) |