DrishtiSharma commited on
Commit
d22278f
·
verified ·
1 Parent(s): da93c7d

Create correct_output.py

Browse files
Files changed (1) hide show
  1. mylab/correct_output.py +153 -0
mylab/correct_output.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # API keys
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
+ except Exception as e:
37
+ st.error(f"Error loading dataset from the repo directory: {e}")
38
+
39
+ # Option 2: Load dataset from Hugging Face
40
+ elif input_option == "Use Hugging Face Dataset":
41
+ dataset_name = st.text_input(
42
+ "Enter Hugging Face Dataset Name:", value="HUPD/hupd"
43
+ )
44
+ if st.button("Load Hugging Face Dataset"):
45
+ try:
46
+ from datasets import load_dataset
47
+ dataset = load_dataset(dataset_name, split="train", trust_remote_code=True)
48
+ if hasattr(dataset, "to_pandas"):
49
+ st.session_state.df = dataset.to_pandas()
50
+ else:
51
+ st.session_state.df = pd.DataFrame(dataset)
52
+ st.success(f"Hugging Face Dataset '{dataset_name}' loaded successfully!")
53
+ except Exception as e:
54
+ st.error(f"Error loading Hugging Face dataset: {e}")
55
+
56
+ # Option 3: Upload CSV File
57
+ elif input_option == "Upload CSV File":
58
+ uploaded_file = st.file_uploader("Upload a CSV File:", type=["csv"])
59
+ if uploaded_file:
60
+ try:
61
+ st.session_state.df = pd.read_csv(uploaded_file)
62
+ st.success("File uploaded successfully!")
63
+ except Exception as e:
64
+ st.error(f"Error reading uploaded file: {e}")
65
+
66
+ load_dataset_into_session()
67
+
68
+ # Check if the dataset and API keys are loaded
69
+ if "df" in st.session_state and api_key and pandasai_api_key:
70
+ # Set API keys
71
+ os.environ["OPENAI_API_KEY"] = api_key
72
+ os.environ["PANDASAI_API_KEY"] = pandasai_api_key
73
+
74
+ df = st.session_state.df
75
+ st.write("Dataset Preview:")
76
+ st.write(df.head()) # Ensure the dataset preview is displayed only once
77
+
78
+ # Set up PandasAI Agent
79
+ agent = Agent(df)
80
+
81
+ # Convert dataframe into documents
82
+ documents = [
83
+ Document(
84
+ page_content=", ".join([f"{col}: {row[col]}" for col in df.columns]),
85
+ metadata={"index": index}
86
+ )
87
+ for index, row in df.iterrows()
88
+ ]
89
+
90
+ # Set up RAG
91
+ embeddings = OpenAIEmbeddings()
92
+ vectorstore = FAISS.from_documents(documents, embeddings)
93
+ retriever = vectorstore.as_retriever()
94
+ qa_chain = RetrievalQA.from_chain_type(
95
+ llm=ChatOpenAI(),
96
+ chain_type="stuff",
97
+ retriever=retriever
98
+ )
99
+
100
+ # Create tabs
101
+ tab1, tab2, tab3 = st.tabs(["PandasAI Analysis", "RAG Q&A", "Data Visualization"])
102
+
103
+ with tab1:
104
+ #st.header("Data Analysis with PandasAI")
105
+ pandas_question = st.text_input("Ask a question about the dataset (PandasAI):")
106
+ if pandas_question:
107
+ try:
108
+ result = agent.chat(pandas_question)
109
+ st.write("PandasAI Answer:", result)
110
+ except Exception as e:
111
+ st.error(f"PandasAI encountered an error: {str(e)}")
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
+ try:
118
+ result = qa_chain.run(rag_question)
119
+ st.write("RAG Answer:", result)
120
+ except Exception as e:
121
+ st.error(f"RAG encountered an error: {str(e)}")
122
+
123
+ with tab3:
124
+ st.header("Data Visualization")
125
+ viz_question = st.text_input("What kind of graph would you like? (e.g., 'Show a scatter plot of salary vs experience')")
126
+ if viz_question:
127
+ try:
128
+ result = agent.chat(viz_question)
129
+
130
+ # Extract Python code from PandasAI response
131
+ import re
132
+ code_pattern = r'```python\n(.*?)\n```'
133
+ code_match = re.search(code_pattern, result, re.DOTALL)
134
+
135
+ if code_match:
136
+ viz_code = code_match.group(1)
137
+
138
+ # Replace matplotlib with plotly
139
+ viz_code = viz_code.replace('plt.', 'px.')
140
+ viz_code = viz_code.replace('plt.show()', 'fig = px.scatter(df, x=x, y=y)')
141
+
142
+ # Execute the modified code
143
+ exec(viz_code)
144
+ st.plotly_chart(fig)
145
+ else:
146
+ st.write("Unable to generate the graph. Please try a different query.")
147
+ except Exception as e:
148
+ st.error(f"An error occurred during visualization: {str(e)}")
149
+ else:
150
+ if not api_key:
151
+ st.warning("Please set the OpenAI API key in environment variables.")
152
+ if not pandasai_api_key:
153
+ st.warning("Please set the PandasAI API key in environment variables.")