Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import os
|
4 |
+
from pandasai import SmartDataframe
|
5 |
+
from pandasai.llm import OpenAI
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
import tempfile
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
|
10 |
+
# Load environment variables
|
11 |
+
load_dotenv()
|
12 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
13 |
+
|
14 |
+
# Ensure OpenAI API key is provided
|
15 |
+
if not openai_api_key:
|
16 |
+
st.error("OpenAI API key is not set. Please add it to a .env file.")
|
17 |
+
st.stop()
|
18 |
+
|
19 |
+
# Initialize the LLM
|
20 |
+
llm = OpenAI(api_token=openai_api_key)
|
21 |
+
|
22 |
+
st.title("Chat with Your CSV File Using PandasAI")
|
23 |
+
|
24 |
+
uploaded_file = st.file_uploader("Upload a CSV file", type="csv")
|
25 |
+
|
26 |
+
if uploaded_file:
|
27 |
+
# Read the CSV file
|
28 |
+
df = pd.read_csv(uploaded_file)
|
29 |
+
st.write("### Data Preview")
|
30 |
+
st.dataframe(df.head(10))
|
31 |
+
|
32 |
+
# Create SmartDataFrame
|
33 |
+
chat_df = SmartDataframe(df, config={"llm": llm})
|
34 |
+
|
35 |
+
st.write("### Chat with Your Data")
|
36 |
+
user_query = st.text_input("Enter your question about the data:")
|
37 |
+
|
38 |
+
if user_query:
|
39 |
+
try:
|
40 |
+
response = chat_df.chat(user_query)
|
41 |
+
st.success(f"Response: {response}")
|
42 |
+
except Exception as e:
|
43 |
+
st.error(f"Error: {e}")
|
44 |
+
|
45 |
+
st.write("### Generate and View Graphs")
|
46 |
+
plot_query = st.text_input("Enter a query to generate a graph (e.g., 'Can you plot me a bar graph of total weekly sales for each store?'):")
|
47 |
+
|
48 |
+
if plot_query:
|
49 |
+
try:
|
50 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
51 |
+
# PandasAI can handle plotting
|
52 |
+
chat_df.chat(plot_query)
|
53 |
+
|
54 |
+
# Save and display the plot
|
55 |
+
temp_plot_path = os.path.join(temp_dir, "plot.png")
|
56 |
+
plt.savefig(temp_plot_path)
|
57 |
+
st.image(temp_plot_path, caption="Generated Plot", use_column_width=True)
|
58 |
+
|
59 |
+
except Exception as e:
|
60 |
+
st.error(f"Error: {e}")
|
61 |
+
|
62 |
+
st.write("### Instructions")
|
63 |
+
st.markdown(
|
64 |
+
"1. Upload a CSV file to get started.\n"
|
65 |
+
"2. Enter a question to interact with the data.\n"
|
66 |
+
"3. Enter a query to generate and view graphs.\n"
|
67 |
+
)
|