WaysAhead Global commited on
Commit
ef8abc8
Β·
verified Β·
1 Parent(s): 0c9367a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+
4
+ st.set_page_config(page_title="AI Data Analysis & Chatbot", layout="wide")
5
+
6
+ import pandas as pd
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+ import networkx as nx
11
+ from pycaret.classification import setup as setup_clf, compare_models as compare_clf
12
+ from pycaret.regression import setup as setup_reg, compare_models as compare_reg
13
+ from sklearn.linear_model import LinearRegression
14
+ from sklearn.cluster import KMeans
15
+ from langchain_openai import ChatOpenAI
16
+ from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
17
+ from langchain.agents.agent_types import AgentType
18
+ from langchain.schema import HumanMessage, AIMessage
19
+ from fuzzywuzzy import process # For fuzzy name matching
20
+ from crewai import Crew, Agent, Task
21
+ import os
22
+ import threading
23
+ from dotenv import load_dotenv
24
+
25
+ # Load environment variables
26
+ load_dotenv()
27
+ openai_api_key = os.getenv("OPENAI_API_KEY")
28
+ if not openai_api_key:
29
+ st.error("❌ OpenAI API Key is missing! Set it in your .env file.")
30
+
31
+ # Title
32
+ st.title("πŸ“Š AI-Powered Data Analysis & Chatbot")
33
+
34
+ # πŸ“‚ File Upload Section
35
+ uploaded_file = st.file_uploader("πŸ“‚ Upload your CSV or Excel file", type=["csv", "xlsx"], key="file_uploader_1")
36
+
37
+ if uploaded_file is not None:
38
+ # Read File
39
+ file_extension = uploaded_file.name.split(".")[-1]
40
+ if file_extension == "csv":
41
+ df = pd.read_csv(uploaded_file)
42
+ elif file_extension == "xlsx":
43
+ df = pd.read_excel(uploaded_file, engine="openpyxl")
44
+
45
+ # Display the dataset
46
+ st.subheader("πŸ“‹ Data Preview")
47
+ st.dataframe(df.head())
48
+
49
+ # βœ… CrewAI Agents & Tasks
50
+ cleaning_agent = Agent(
51
+ role="Data Cleaning Agent",
52
+ goal="Clean and preprocess dataset.",
53
+ backstory="An expert data scientist specializing in handling missing values, cleaning data, and ensuring data quality.",
54
+ llm=ChatOpenAI(model="gpt-3.5-turbo-0125"),
55
+ allow_delegation=True
56
+ )
57
+
58
+ analysis_agent = Agent(
59
+ role="Data Analysis Expert",
60
+ goal="Perform exploratory data analysis and generate insights.",
61
+ backstory="An AI analyst skilled in identifying patterns, correlations, and visualizing trends.",
62
+ llm=ChatOpenAI(model="gpt-3.5-turbo-0125"),
63
+ allow_delegation=True
64
+ )
65
+
66
+ prediction_agent = Agent(
67
+ role="Prediction Specialist",
68
+ goal="Run AutoML to identify the best model for predicting future trends.",
69
+ backstory="An AI-powered machine learning specialist that automates model selection and predictions.",
70
+ llm=ChatOpenAI(model="gpt-3.5-turbo-0125"),
71
+ allow_delegation=True
72
+ )
73
+
74
+ # Tasks
75
+ cleaning_task = Task(
76
+ description="Clean dataset and handle missing values.",
77
+ agent=cleaning_agent,
78
+ expected_output="A cleaned dataset with missing values handled."
79
+ )
80
+
81
+ analysis_task = Task(
82
+ description="Analyze dataset, detect trends, and generate visualizations.",
83
+ agent=analysis_agent,
84
+ expected_output="A report summarizing key trends, correlations, and insights."
85
+ )
86
+
87
+ prediction_task = Task(
88
+ description="Run AutoML to identify the best predictive model.",
89
+ agent=prediction_agent,
90
+ expected_output="A machine learning model recommendation with performance metrics."
91
+ )
92
+
93
+ # CrewAI Execution
94
+ crew = Crew(
95
+ agents=[cleaning_agent, analysis_agent, prediction_agent],
96
+ tasks=[cleaning_task, analysis_task, prediction_task]
97
+ )
98
+
99
+ # Run CrewAI in a separate thread to prevent blocking
100
+ thread = threading.Thread(target=crew.kickoff, daemon=True)
101
+ thread.start()
102
+
103
+ # βœ… AI Chatbot Agent with Name Matching
104
+ pandas_agent = create_pandas_dataframe_agent(
105
+ ChatOpenAI(model="gpt-3.5-turbo-0125"),
106
+ df,
107
+ verbose=True,
108
+ agent_type=AgentType.OPENAI_FUNCTIONS,
109
+ allow_dangerous_code=True,
110
+ )
111
+
112
+ def find_closest_match(user_input, column_name):
113
+ """Find the closest matching value in a specific column using fuzzy matching."""
114
+ if column_name in df.columns:
115
+ choices = df[column_name].dropna().unique().tolist()
116
+ best_match, score = process.extractOne(user_input, choices)
117
+ return best_match if score > 80 else None # Only return if confidence is high
118
+ return None
119
+
120
+ def process_ai_response(user_input):
121
+ """AI response processing with fuzzy name matching."""
122
+ for column in df.columns: # Search for closest match in all columns
123
+ closest_match = find_closest_match(user_input, column)
124
+ if closest_match:
125
+ st.info(f"πŸ” Did you mean **{closest_match}**?")
126
+ user_input = user_input.replace(user_input, closest_match)
127
+
128
+ try:
129
+ ai_response = pandas_agent.invoke(user_input)
130
+ graph_result = render_ai_graph(ai_response)
131
+
132
+ if graph_result:
133
+ ai_response = graph_result
134
+ elif isinstance(ai_response, dict) and "plot" in ai_response:
135
+ fig = ai_response["plot"]
136
+ st.pyplot(fig)
137
+ else:
138
+ if isinstance(ai_response, dict):
139
+ ai_response = str(ai_response)
140
+ st.markdown(ai_response)
141
+
142
+ return ai_response
143
+ except Exception as e:
144
+ return f"❌ Error processing request: {str(e)}"
145
+
146
+ def render_ai_graph(ai_response):
147
+ """Detects AI-generated graph code and executes it properly inside Streamlit."""
148
+ if isinstance(ai_response, dict) and "graph_code" in ai_response:
149
+ graph_code = ai_response["graph_code"]
150
+
151
+ try:
152
+ exec(graph_code, globals(), locals()) # Execute the AI-generated graph
153
+ fig = plt.gcf()
154
+
155
+ if fig and fig.get_axes():
156
+ st.pyplot(fig)
157
+ return "πŸ“Š AI-Generated Graph Displayed Successfully!"
158
+ else:
159
+ return "⚠ AI generated an empty graph, please refine your request."
160
+ except Exception as e:
161
+ return f"❌ Error executing AI graph: {str(e)}"
162
+
163
+ return None # If no graph was generated, return None
164
+
165
+ st.subheader("πŸ’¬ Chat with AI")
166
+ if "chat_history" not in st.session_state:
167
+ st.session_state.chat_history = []
168
+
169
+ for msg in st.session_state.chat_history:
170
+ if isinstance(msg, HumanMessage):
171
+ st.markdown(f"**You:** {msg.content}")
172
+ elif isinstance(msg, AIMessage):
173
+ st.markdown(f"πŸ€– **AI:** {msg.content}")
174
+
175
+ # βœ… User Input for Chatbot
176
+ user_input = st.text_input("Ask AI About Your Data:")
177
+
178
+ if user_input:
179
+ st.session_state.chat_history.append(HumanMessage(content=user_input))
180
+ ai_response = process_ai_response(user_input)
181
+ st.session_state.chat_history.append(AIMessage(content=ai_response))
182
+
183
+ # Footer
184
+ st.markdown("---")
185
+ st.markdown("πŸ’‘ Built with ❀️ using **Streamlit, CrewAI, LangChain, PyCaret & GPT-3.5-Turbo-0125**")