DrishtiSharma commited on
Commit
857f873
·
verified ·
1 Parent(s): 5b6d428

Create app4.py

Browse files
Files changed (1) hide show
  1. app4.py +151 -0
app4.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ from pandasai import Agent
5
+ from langchain_community.embeddings.openai import OpenAIEmbeddings
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain_openai import ChatOpenAI
8
+ from langchain.chains import RetrievalQA
9
+ from langchain.schema import Document
10
+ import os
11
+
12
+ # Set title
13
+ st.title("Data Analyzer")
14
+
15
+ # Add fields to input API keys via the sidebar
16
+ api_key = os.getenv("OPENAI_API_KEY")
17
+ pandasai_api_key = os.getenv("PANDASAI_API_KEY")
18
+
19
+ if not api_key or not pandasai_api_key:
20
+ st.warning("API keys for OpenAI or PandasAI are missing. Ensure both keys are set in environment variables.")
21
+
22
+ # Function to load datasets into session
23
+ def load_dataset_into_session():
24
+ input_option = st.radio(
25
+ "Select Dataset Input:",
26
+ ["Use Repo Directory Dataset", "Use Hugging Face Dataset", "Upload CSV File"],
27
+ )
28
+
29
+ # Option 1: Load dataset from the repo directory
30
+ if input_option == "Use Repo Directory Dataset":
31
+ file_path = "./source/test.csv"
32
+ if st.button("Load Dataset"):
33
+ try:
34
+ st.session_state.df = pd.read_csv(file_path)
35
+ st.success(f"File loaded successfully from '{file_path}'!")
36
+ st.dataframe(st.session_state.df.head(10))
37
+ except Exception as e:
38
+ st.error(f"Error loading dataset from the repo directory: {e}")
39
+
40
+ # Option 2: Load dataset from Hugging Face
41
+ elif input_option == "Use Hugging Face Dataset":
42
+ dataset_name = st.text_input(
43
+ "Enter Hugging Face Dataset Name:", value="HUPD/hupd"
44
+ )
45
+ if st.button("Load Hugging Face Dataset"):
46
+ try:
47
+ from datasets import load_dataset
48
+ dataset = load_dataset(dataset_name, split="train", trust_remote_code=True)
49
+ if hasattr(dataset, "to_pandas"):
50
+ st.session_state.df = dataset.to_pandas()
51
+ else:
52
+ st.session_state.df = pd.DataFrame(dataset)
53
+ st.success(f"Hugging Face Dataset '{dataset_name}' loaded successfully!")
54
+ st.dataframe(st.session_state.df.head(10))
55
+ except Exception as e:
56
+ st.error(f"Error loading Hugging Face dataset: {e}")
57
+
58
+ # Option 3: Upload CSV File
59
+ elif input_option == "Upload CSV File":
60
+ uploaded_file = st.file_uploader("Upload a CSV File:", type=["csv"])
61
+ if uploaded_file:
62
+ try:
63
+ st.session_state.df = pd.read_csv(uploaded_file)
64
+ st.success("File uploaded successfully!")
65
+ st.dataframe(st.session_state.df.head(10))
66
+ except Exception as e:
67
+ st.error(f"Error reading uploaded file: {e}")
68
+
69
+ load_dataset_into_session()
70
+
71
+ # Check if the dataset and API keys are loaded
72
+ if "df" in st.session_state and api_key and pandasai_api_key:
73
+ # Set API keys
74
+ os.environ["OPENAI_API_KEY"] = api_key
75
+ os.environ["PANDASAI_API_KEY"] = pandasai_api_key
76
+
77
+ df = st.session_state.df
78
+ st.write("Dataset Preview:")
79
+ st.write(df.head())
80
+
81
+ # Set up PandasAI Agent
82
+ agent = Agent(df)
83
+
84
+ # Convert dataframe into documents
85
+ documents = [
86
+ Document(
87
+ page_content=", ".join([f"{col}: {row[col]}" for col in df.columns]),
88
+ metadata={"index": index}
89
+ )
90
+ for index, row in df.iterrows()
91
+ ]
92
+
93
+ # Set up RAG
94
+ embeddings = OpenAIEmbeddings()
95
+ vectorstore = FAISS.from_documents(documents, embeddings)
96
+ retriever = vectorstore.as_retriever()
97
+ qa_chain = RetrievalQA.from_chain_type(
98
+ llm=ChatOpenAI(),
99
+ chain_type="stuff",
100
+ retriever=retriever
101
+ )
102
+
103
+ # Create tabs
104
+ tab1, tab2, tab3 = st.tabs(["PandasAI Analysis", "RAG Q&A", "Data Visualization"])
105
+
106
+ with tab1:
107
+ st.header("Data Analysis with PandasAI")
108
+ pandas_question = st.text_input("Ask a question about the dataset (PandasAI):")
109
+ if pandas_question:
110
+ result = agent.chat(pandas_question)
111
+ st.write("PandasAI Answer:", result)
112
+
113
+ with tab2:
114
+ st.header("Q&A with RAG")
115
+ rag_question = st.text_input("Ask a question about the dataset (RAG):")
116
+ if rag_question:
117
+ result = qa_chain.run(rag_question)
118
+ st.write("RAG Answer:", result)
119
+
120
+ with tab3:
121
+ st.header("Data Visualization")
122
+ viz_question = st.text_input("What kind of graph would you like? (e.g., 'Show a scatter plot of salary vs experience')")
123
+ if viz_question:
124
+ try:
125
+ result = agent.chat(viz_question)
126
+
127
+ # Extract Python code from PandasAI response
128
+ import re
129
+ code_pattern = r'```python\n(.*?)\n```'
130
+ code_match = re.search(code_pattern, result, re.DOTALL)
131
+
132
+ if code_match:
133
+ viz_code = code_match.group(1)
134
+
135
+ # Replace matplotlib with plotly
136
+ viz_code = viz_code.replace('plt.', 'px.')
137
+ viz_code = viz_code.replace('plt.show()', 'fig = px.scatter(df, x=x, y=y)')
138
+
139
+ # Execute the modified code
140
+ exec(viz_code)
141
+ st.plotly_chart(fig)
142
+ else:
143
+ st.write("Unable to generate the graph. Please try a different query.")
144
+ except Exception as e:
145
+ st.write(f"An error occurred: {str(e)}")
146
+ st.write("Please try asking in a different way.")
147
+ else:
148
+ if not api_key:
149
+ st.warning("Please set the OpenAI API key in environment variables.")
150
+ if not pandasai_api_key:
151
+ st.warning("Please set the PandasAI API key in environment variables.")