Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
238 lines (212 loc) Β· 9.17 KB
/
Copy pathapp.py
File metadata and controls
238 lines (212 loc) Β· 9.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# --- Imports ---
from appwrite.client import Client
from appwrite.services.storage import Storage
from appwrite.services.account import Account
import base64
import textwrap
import plotly.io as pio
import streamlit as st
import pandas as pd
import plotly.express as px
from openai import AzureOpenAI
import pdfkit
import time
from dotenv import load_dotenv
import os
# --- Environment Setup ---
load_dotenv()
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
AZURE_OPENAI_API_BASE = os.getenv("AZURE_OPENAI_API_BASE")
AZURE_OPENAI_API_VERSION = os.getenv("AZURE_OPENAI_API_VERSION")
AZURE_OPENAI_DEPLOYMENT_NAME = os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME")
client = AzureOpenAI(
api_key=AZURE_OPENAI_API_KEY,
api_version=AZURE_OPENAI_API_VERSION,
azure_endpoint=AZURE_OPENAI_API_BASE
)
PDFKIT_CONFIG = pdfkit.configuration(wkhtmltopdf=r"/usr/local/bin/wkhtmltopdf")
# --- Utility Functions ---
def load_uploaded_file(uploaded_file):
try:
if uploaded_file.name.endswith('.csv'):
try:
df = pd.read_csv(uploaded_file, encoding='utf-8')
except UnicodeDecodeError:
df = pd.read_csv(uploaded_file, encoding='ISO-8859-1')
else:
df = pd.read_excel(uploaded_file)
df.dropna(inplace=True)
return df
except Exception as e:
st.error(f"Error loading file: {e}")
return None
def get_column_types(df):
return {col: str(df[col].dtype) for col in df.columns}
def get_chart_suggestions(column_types):
prompt = f"""
Given these columns and their data types:
{column_types}
Suggest 5 suitable visualization types (Pie, Bar, Line, Scatter, Histogram).
Only return the chart names as a comma-separated list.
"""
try:
response = client.chat.completions.create(
model=AZURE_OPENAI_DEPLOYMENT_NAME,
messages=[
{"role": "system", "content": "You are a helpful data analyst."},
{"role": "user", "content": prompt}
],
temperature=0.5,
max_tokens=100
)
ai_text = response.choices[0].message.content
viz_types = [v.strip().lower() for v in ai_text.split(",") if v.strip().lower() in ["pie", "bar", "line", "scatter", "histogram"]]
if len(viz_types) < 5:
viz_types = ["bar", "line", "pie", "scatter", "histogram"][:5]
return viz_types
except Exception as e:
st.error(f"AI Error: {e}")
return []
def generate_charts(df, viz_types):
charts = []
for viz in viz_types:
st.subheader(f"π {viz.capitalize()} Chart")
fig = None
if viz == "pie":
column = st.selectbox("Select column for Pie Chart", df.columns, key="pie")
fig = px.pie(df, names=column, title=f"Distribution of {column}")
elif viz == "bar":
x_col = st.selectbox("X-axis for Bar Chart", df.columns, key="bar_x")
y_col = st.selectbox("Y-axis for Bar Chart", df.columns, key="bar_y")
fig = px.bar(df, x=x_col, y=y_col, title=f"{y_col} by {x_col}")
elif viz == "line":
x_col = st.selectbox("X-axis for Line Chart", df.columns, key="line_x")
y_col = st.selectbox("Y-axis for Line Chart", df.columns, key="line_y")
fig = px.line(df, x=x_col, y=y_col, title=f"Trend of {y_col} over {x_col}")
elif viz == "scatter":
x_col = st.selectbox("X-axis for Scatter Plot", df.columns, key="scatter_x")
y_col = st.selectbox("Y-axis for Scatter Plot", df.columns, key="scatter_y")
fig = px.scatter(df, x=x_col, y=y_col, title=f"Scatter Plot of {y_col} vs {x_col}")
elif viz == "histogram":
column = st.selectbox("Select column for Histogram", df.columns, key="hist")
fig = px.histogram(df, x=column, title=f"Distribution of {column}")
if fig:
charts.append((fig, viz))
st.plotly_chart(fig, use_container_width=True)
return charts
def generate_ai_summary(df):
summary_prompt = f"Given this dataset with columns: {', '.join(df.columns)}, provide a short summary of insights, trends, and possible business improvements."
try:
summary_response = client.chat.completions.create(
model=AZURE_OPENAI_DEPLOYMENT_NAME,
messages=[
{"role": "system", "content": "You are a helpful data analyst."},
{"role": "user", "content": summary_prompt}
],
temperature=0.7,
max_tokens=300
)
return summary_response.choices[0].message.content
except Exception as e:
return f"No insights generated. Error: {e}"
def generate_pdf_report(summary_text, charts):
chart_images = []
summary_html = f"""
<h1 style=\"text-align:center; color:#2C3E50;\"> Invisora.AI</h1>
<h2 style=\"color:#1F618D;\"> Key Insights</h2>
<p style=\"font-size:16px; line-height:1.6; color:#283747;\">{summary_text}</p>
<hr>
<h2 style=\"color:#1F618D;\"> Data Visualizations</h2>
<p>Charts below are static snapshots. For interactive version, visit: <a href='https://yourapp.streamlit.app'>Open Invisora.AI App</a></p>
"""
for i, (fig, viz_name) in enumerate(charts):
chart_path = f"chart_{i}.png"
pio.write_image(fig, chart_path)
chart_images.append(chart_path)
with open(chart_path, "rb") as img_file:
base64_img = base64.b64encode(img_file.read()).decode()
summary_html += f"""
<div style=\"margin-bottom:30px;\">
<h3 style=\"color:#1F618D;\">Chart {i+1} β {viz_name.capitalize()} Chart</h3>
<p style=\"color:#555;\">Snapshot of data visualization from your uploaded dataset.</p>
<img src=\"data:image/png;base64,{base64_img}\" style=\"width:100%; margin-bottom:20px;\">
</div>
"""
pdf_path = "Invisora_Report.pdf"
pdfkit.from_string(summary_html, pdf_path, configuration=PDFKIT_CONFIG)
return pdf_path
def chatbot_response(df, user_query):
sample_data = df.head(3).to_dict(orient="records")
column_types = get_column_types(df)
query_prompt = f"""
You are a business analyst.
Dataset info:
- Columns: {', '.join(df.columns)}
- Data Types: {column_types}
- Sample Rows: {sample_data}
User Query:
{user_query}
Answer based on this dataset only.
"""
chat_response = client.chat.completions.create(
model=AZURE_OPENAI_DEPLOYMENT_NAME,
messages=[
{"role": "system", "content": "You are a helpful business analyst."},
{"role": "user", "content": query_prompt}
],
temperature=0.7,
max_tokens=400
)
return chat_response.choices[0].message.content.strip()
# --- Streamlit App ---
st.set_page_config(page_title="Invisora.AI β AI-Powered Business Insights", layout="wide")
st.title("π€ Invisora.AI")
st.write("Upload your business data to get interactive reports and AI-driven insights.")
uploaded_file = st.file_uploader("Upload CSV or Excel File", type=["csv", "xlsx"])
if uploaded_file:
df = load_uploaded_file(uploaded_file)
if df is None:
st.stop()
st.subheader("Select Columns to Keep")
selected_columns = st.multiselect("Choose columns:", df.columns.tolist(), default=df.columns.tolist())
if selected_columns:
df = df[selected_columns]
st.write("### Preview of Processed Data")
st.dataframe(df.head())
st.write("π *Analyzing Data...* Please wait while AI generates insights.")
time.sleep(2)
column_types = get_column_types(df)
viz_types = get_chart_suggestions(column_types)
st.write(f"*AI Selected Visualizations:* {', '.join(viz_types)}")
charts = generate_charts(df, viz_types)
st.markdown("---")
st.subheader("π AI-Generated Business Insights")
st.write("Analyzing data for key takeaways...")
summary_text = generate_ai_summary(df)
st.write(f"*Business Insights:* {summary_text}")
st.markdown("---")
st.subheader("π Data Visualizations (5 Worksheets)")
cols = st.columns(3)
for i, (fig, _) in enumerate(charts[:5]):
with cols[i % 3]:
st.plotly_chart(fig, use_container_width=True, key=f"worksheet_{i}")
if st.button("π
Download Report as PDF"):
st.write("π Generating Report... Please wait.")
pdf_path = generate_pdf_report(summary_text, charts)
with open(pdf_path, "rb") as file:
st.download_button("π
Download Report", file, file_name="Invisora_Report.pdf", mime="application/pdf")
st.markdown("---")
st.subheader("π§ AI Chatbot for Data Queries")
chat_history = st.session_state.get("chat_history", [])
with st.expander("π¬ Open AI Chatbot"):
st.write("Ask questions about your uploaded data.")
user_query = st.text_input("Enter your query:")
if st.button("Ask AI"):
if user_query:
response = chatbot_response(df, user_query)
chat_history.append({"query": user_query, "response": response})
st.session_state.chat_history = chat_history
if chat_history:
for chat in reversed(chat_history):
st.markdown(f"**You:** {chat['query']}")
st.markdown(f"**AI:** {chat['response']}")