import pandas as pd
import gradio as gr
import numpy as np
from pandasai import SmartDataframe
from pandasai.llm import OpenAI
from PIL import Image
import base64
from io import BytesIO
def ask(query, file, api_token):
data = pd.read_csv(file, index_col=0)
llm = OpenAI(api_token=api_token)
df = SmartDataframe(data, config={"llm": llm})
result = df.chat(query)
if isinstance(result, str) and result.endswith('.png'):
# Open the image file
img = Image.open('exports/charts/temp_chart.png')
# Convert the PIL Image to a base64 encoded string
buffered = BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
# Construct the HTML string to display the image
html = f""
return html
elif isinstance(result, pd.DataFrame):
html_table = result.to_html()
return html_table
else:
return result
def on_file_upload(file, api_token):
data = pd.read_csv(file, index_col=0)
llm = OpenAI(api_token=api_token)
df = SmartDataframe(data, config={"llm": llm})
result = df.chat('What are the name of my columns')
return result
with gr.Blocks() as demo:
headers = gr.Markdown("