File size: 1,936 Bytes
1682b9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

import gradio as gr
import pandas as pd
from pandasai import SmartDataframe

df_global = None
sdf = None

def cargar_csv(file):
    global df_global, sdf
    try:
        df_global = pd.read_csv(file.name)
        sdf = SmartDataframe(df_global, config={"enable_cache": False})
        return f"Archivo cargado con éxito. Filas: {len(df_global)}, Columnas: {len(df_global.columns)}"
    except Exception as e:
        return f"Error al cargar el archivo: {str(e)}"

def responder_pregunta(pregunta):
    global sdf
    if sdf is None:
        return "Primero debes cargar un archivo CSV."
    try:
        respuesta = sdf.chat(pregunta)

        # Protección explícita contra errores de tipo booleano o vacío
        if isinstance(respuesta, bool) or respuesta is None:
            return "La pregunta no puede interpretarse correctamente sin un modelo LLM. Intenta otra más específica sobre columnas o datos."

        return str(respuesta)
    except Exception as e:
        if "bool" in str(e) and "iterable" in str(e):
            return "Error: La respuesta generada no es válida. Intenta otra pregunta o usa un modelo LLM si es necesario."
        return f"Ocurrió un error al responder la pregunta: {str(e)}"

with gr.Blocks() as demo:
    gr.Markdown("# Asistente CSV sin LLM (a prueba de errores)")

    with gr.Row():
        archivo = gr.File(label="Sube tu archivo CSV", file_types=[".csv"])
        salida_carga = gr.Textbox(label="Resultado de carga")
        boton_carga = gr.Button("Cargar CSV")

    with gr.Row():
        pregunta = gr.Textbox(label="Escribe tu pregunta sobre los datos")
        salida_respuesta = gr.Textbox(label="Respuesta")
        boton_pregunta = gr.Button("Responder")

    boton_carga.click(cargar_csv, inputs=[archivo], outputs=[salida_carga])
    boton_pregunta.click(responder_pregunta, inputs=[pregunta], outputs=[salida_respuesta])

if __name__ == "__main__":
    demo.launch()