Shreneek commited on
Commit
9ddb455
·
verified ·
1 Parent(s): a98185d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from io import StringIO
4
+ from pandasai import PandasAI
5
+ from pandasai.llm.huggingface import HuggingFaceLLM
6
+
7
+ # Initialize an open-source LLM.
8
+ # Here we use "google/flan-t5-small", a small free model from Hugging Face.
9
+ llm = HuggingFaceLLM(model_name="google/flan-t5-small")
10
+ pandas_ai = PandasAI(llm)
11
+
12
+ def process_file_and_query(file_obj, question):
13
+ """
14
+ This function reads the uploaded CSV file, converts it into a DataFrame,
15
+ and then uses PandasAI to answer the user's question about the data.
16
+ """
17
+ if file_obj is None:
18
+ return "Please upload a CSV file."
19
+
20
+ try:
21
+ # Read the file content. file_obj.read() returns bytes, so decode to string.
22
+ file_contents = file_obj.read().decode("utf-8")
23
+ # Use StringIO to convert the string data into a stream for pandas
24
+ df = pd.read_csv(StringIO(file_contents))
25
+ except Exception as e:
26
+ return f"Error reading CSV file: {e}"
27
+
28
+ try:
29
+ # Use PandasAI to answer the question using the DataFrame.
30
+ answer = pandas_ai.run(df, prompt=question)
31
+ return answer
32
+ except Exception as e:
33
+ return f"Error processing the query: {e}"
34
+
35
+ # Create a Gradio interface.
36
+ iface = gr.Interface(
37
+ fn=process_file_and_query,
38
+ inputs=[
39
+ gr.File(label="Upload CSV file"),
40
+ gr.Textbox(label="Ask a question about your data", placeholder="E.g., What is the average of column X?")
41
+ ],
42
+ outputs="text",
43
+ title="Chat with Your CSV",
44
+ description=(
45
+ "Upload your CSV file and ask questions about the data. "
46
+ "This app uses an open-source LLM (google/flan-t5-small) via PandasAI to answer your questions interactively."
47
+ )
48
+ )
49
+
50
+ if __name__ == "__main__":
51
+ iface.launch()