mgbam commited on
Commit
773f0cf
·
verified ·
1 Parent(s): e490e03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -54
app.py CHANGED
@@ -1,132 +1,167 @@
1
- # app.py — BizIntel AI Ultra (Gemini 1.5 Pro, interactive Plotly visuals)
 
 
2
 
3
  import os
4
  import tempfile
 
 
5
  import pandas as pd
6
  import streamlit as st
7
  import google.generativeai as genai
8
  import plotly.graph_objects as go
9
 
10
  from tools.csv_parser import parse_csv_tool
11
- from tools.plot_generator import plot_sales_tool # accepts date_col, returns Figure or str
12
- from tools.forecaster import forecast_tool # accepts date_col
13
  from tools.visuals import (
14
  histogram_tool,
15
  scatter_matrix_tool,
16
  corr_heatmap_tool,
17
  )
 
18
 
19
  # ──────────────────────────────────────────────────────────────
20
- # 1. GEMINI CONFIG (1.5‑Pro, temperature 0.7)
21
  # ──────────────────────────────────────────────────────────────
22
  genai.configure(api_key=os.getenv("GEMINI_APIKEY"))
23
  gemini = genai.GenerativeModel(
24
  "gemini-1.5-pro-latest",
25
- generation_config={
26
- "temperature": 0.7,
27
- "top_p": 0.9,
28
- "response_mime_type": "text/plain", # must be allowed type
29
- },
30
  )
31
 
32
  # ──────────────────────────────────────────────────────────────
33
- # 2. STREAMLIT PAGE SETUP
34
  # ──────────────────────────────────────────────────────────────
35
- st.set_page_config(page_title="BizIntel AI Ultra – Gemini 1.5 Pro", layout="wide")
36
- st.title("📊 BizIntel AI Ultra – Advanced Analytics")
37
 
38
  TEMP_DIR = tempfile.gettempdir()
39
 
40
  # ──────────────────────────────────────────────────────────────
41
- # 3. CSV UPLOAD
42
  # ──────────────────────────────────────────────────────────────
43
- csv_file = st.file_uploader("Upload CSV (≤ 200 MB)", type=["csv"])
44
- if csv_file is None:
45
- st.info("⬆️ Upload a CSV to begin.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  st.stop()
47
 
48
- csv_path = os.path.join(TEMP_DIR, csv_file.name)
49
- with open(csv_path, "wb") as f:
50
- f.write(csv_file.read())
51
- st.success("CSV saved ✅")
52
 
53
- # Preview & date column selection
 
 
54
  df_preview = pd.read_csv(csv_path, nrows=5)
55
  st.dataframe(df_preview)
 
56
  date_col = st.selectbox("Select date/time column for forecasting", df_preview.columns)
57
 
58
  # ──────────────────────────────────────────────────────────────
59
- # 4. LOCAL TOOL EXECUTION
60
  # ──────────────────────────────────────────────────────────────
61
- with st.spinner("🔍 Parsing CSV…"):
62
  summary_text = parse_csv_tool(csv_path)
63
 
64
- with st.spinner("📈 Generating sales trend chart…"):
65
  sales_fig = plot_sales_tool(csv_path, date_col=date_col)
66
 
67
- # Show chart or warn
68
  if isinstance(sales_fig, go.Figure):
69
  st.plotly_chart(sales_fig, use_container_width=True)
70
- else: # returned error message
71
  st.warning(sales_fig)
72
 
73
- with st.spinner("🔮 Forecasting future metrics…"):
74
- forecast_text = forecast_tool(csv_path, date_col=date_col)
 
 
 
 
 
75
 
76
- # Display forecast PNG if created
77
  if os.path.exists("forecast_plot.png"):
78
  st.image("forecast_plot.png", caption="Sales Forecast", use_column_width=True)
79
 
 
 
 
 
 
 
80
  # ──────────────────────────────────────────────────────────────
81
- # 5. GEMINI 1.5‑PRO STRATEGY
82
  # ──────────────────────────────────────────────────────────────
83
  prompt = (
84
  f"You are **BizIntel Strategist AI**.\n\n"
85
- f"### CSV Summary\n```\n{summary_text}\n```\n\n"
86
- f"### Forecast Output\n```\n{forecast_text}\n```\n\n"
 
 
87
  "Return **Markdown** with:\n"
88
- "1. Five key insights (bullets)\n"
89
  "2. Three actionable strategies (with expected impact)\n"
90
  "3. Risk factors or anomalies\n"
91
  "4. Suggested additional visuals\n"
92
  )
93
 
94
  st.subheader("🚀 Strategy Recommendations (Gemini 1.5 Pro)")
95
- with st.spinner("Gemini 1.5 Pro is generating insights…"):
96
  strategy_md = gemini.generate_content(prompt).text
97
  st.markdown(strategy_md)
98
 
 
 
 
99
  # ──────────────────────────────────────────────────────────────
100
- # 6. OPTIONAL EXPLORATORY VISUALS
101
  # ──────────────────────────────────────────────────────────────
102
  st.markdown("---")
103
  st.subheader("🔍 Optional Exploratory Visuals")
104
 
105
  num_cols = df_preview.select_dtypes("number").columns
106
 
107
- # Histogram
108
- if st.checkbox("Show histogram"):
109
- hist_col = st.selectbox("Histogram variable", num_cols, key="hist")
110
- fig_hist = histogram_tool(csv_path, hist_col)
111
- st.plotly_chart(fig_hist, use_container_width=True)
112
 
113
- # Scatter‑matrix
114
- if st.checkbox("Show scatter‑matrix"):
115
- mult_cols = st.multiselect(
116
- "Choose up to 5 columns", num_cols, default=num_cols[:3], key="scatter"
117
- )
118
- if mult_cols:
119
- fig_scatter = scatter_matrix_tool(csv_path, mult_cols)
120
- st.plotly_chart(fig_scatter, use_container_width=True)
121
 
122
- # Correlation heat‑map
123
- if st.checkbox("Show correlation heat‑map"):
124
- fig_corr = corr_heatmap_tool(csv_path)
125
- st.plotly_chart(fig_corr, use_container_width=True)
126
 
127
  # ──────────────────────────────────────���───────────────────────
128
- # 7. CSV SUMMARY TEXT
129
  # ──────────────────────────────────────────────────────────────
130
  st.markdown("---")
131
- st.subheader("📑 CSV Summary (full stats)")
132
  st.text(summary_text)
 
1
+ # app.py — BizIntel AI Ultra v2
2
+ # Features: CSV upload, SQL DB fetch, interactive Plotly, Gemini 1.5 Pro,
3
+ # optional EDA, download buttons.
4
 
5
  import os
6
  import tempfile
7
+ from io import StringIO, BytesIO
8
+
9
  import pandas as pd
10
  import streamlit as st
11
  import google.generativeai as genai
12
  import plotly.graph_objects as go
13
 
14
  from tools.csv_parser import parse_csv_tool
15
+ from tools.plot_generator import plot_sales_tool
16
+ from tools.forecaster import forecast_tool # returns text & PNG; we’ll also grab df
17
  from tools.visuals import (
18
  histogram_tool,
19
  scatter_matrix_tool,
20
  corr_heatmap_tool,
21
  )
22
+ from db_connector import fetch_data_from_db, list_tables, SUPPORTED_ENGINES
23
 
24
  # ──────────────────────────────────────────────────────────────
25
+ # Gemini 1.5‑Pro
26
  # ──────────────────────────────────────────────────────────────
27
  genai.configure(api_key=os.getenv("GEMINI_APIKEY"))
28
  gemini = genai.GenerativeModel(
29
  "gemini-1.5-pro-latest",
30
+ generation_config={"temperature": 0.7, "top_p": 0.9, "response_mime_type": "text/plain"},
 
 
 
 
31
  )
32
 
33
  # ──────────────────────────────────────────────────────────────
34
+ # Streamlit page
35
  # ──────────────────────────────────────────────────────────────
36
+ st.set_page_config(page_title="BizIntel AI Ultra", layout="wide")
37
+ st.title("📊 BizIntel AI Ultra – Advanced Analytics + Gemini 1.5 Pro")
38
 
39
  TEMP_DIR = tempfile.gettempdir()
40
 
41
  # ──────────────────────────────────────────────────────────────
42
+ # 1. CHOOSE DATA SOURCE
43
  # ──────────────────────────────────────────────────────────────
44
+ data_source = st.radio("Select data source", ["Upload CSV", "Connect to SQL Database"])
45
+ csv_path: str | None = None
46
+
47
+ if data_source == "Upload CSV":
48
+ csv_file = st.file_uploader("Upload CSV (≤ 200 MB)", type=["csv"])
49
+ if csv_file:
50
+ csv_path = os.path.join(TEMP_DIR, csv_file.name)
51
+ with open(csv_path, "wb") as f:
52
+ f.write(csv_file.read())
53
+ st.success("CSV saved ✅")
54
+
55
+ elif data_source == "Connect to SQL Database":
56
+ engine = st.selectbox("DB engine", SUPPORTED_ENGINES)
57
+ conn_str = st.text_input("SQLAlchemy connection string")
58
+ if conn_str:
59
+ try:
60
+ tables = list_tables(conn_str)
61
+ except Exception as e:
62
+ st.error(f"Connection failed: {e}")
63
+ st.stop()
64
+
65
+ table = st.selectbox("Select table", tables)
66
+ if st.button("Fetch table"):
67
+ csv_path = fetch_data_from_db(conn_str, table)
68
+ st.success(f"Fetched ‘{table}’ into CSV ✅")
69
+
70
+ # Stop if we still don’t have a CSV
71
+ if csv_path is None:
72
  st.stop()
73
 
74
+ # Offer original CSV download
75
+ with open(csv_path, "rb") as f:
76
+ st.download_button("⬇️ Download original CSV", f, file_name=os.path.basename(csv_path))
 
77
 
78
+ # ──────────────────────────────────────────────────────────────
79
+ # 2. PREVIEW + DATE COL
80
+ # ──────────────────────────────────────────────────────────────
81
  df_preview = pd.read_csv(csv_path, nrows=5)
82
  st.dataframe(df_preview)
83
+
84
  date_col = st.selectbox("Select date/time column for forecasting", df_preview.columns)
85
 
86
  # ──────────────────────────────────────────────────────────────
87
+ # 3. RUN LOCAL TOOLS
88
  # ──────────────────────────────────────────────────────────────
89
+ with st.spinner("Parsing CSV…"):
90
  summary_text = parse_csv_tool(csv_path)
91
 
92
+ with st.spinner("Generating sales trend…"):
93
  sales_fig = plot_sales_tool(csv_path, date_col=date_col)
94
 
 
95
  if isinstance(sales_fig, go.Figure):
96
  st.plotly_chart(sales_fig, use_container_width=True)
97
+ else:
98
  st.warning(sales_fig)
99
 
100
+ with st.spinner("Forecasting…"):
101
+ forecast_text = forecast_tool(csv_path, date_col=date_col) # PNG created
102
+ # Also capture forecast df from statsmodels if you return it (optional)
103
+ try:
104
+ forecast_df = pd.read_csv(StringIO(forecast_text))
105
+ except Exception:
106
+ forecast_df = None
107
 
108
+ # Forecast plot preview
109
  if os.path.exists("forecast_plot.png"):
110
  st.image("forecast_plot.png", caption="Sales Forecast", use_column_width=True)
111
 
112
+ # Download forecast CSV if df exists
113
+ if forecast_df is not None and not forecast_df.empty:
114
+ buf = StringIO()
115
+ forecast_df.to_csv(buf, index=False)
116
+ st.download_button("⬇️ Download Forecast CSV", buf.getvalue(), file_name="forecast.csv")
117
+
118
  # ──────────────────────────────────────────────────────────────
119
+ # 4. GEMINI STRATEGY
120
  # ──────────────────────────────────────────────────────────────
121
  prompt = (
122
  f"You are **BizIntel Strategist AI**.\n\n"
123
+ "### CSV Summary\n"
124
+ f"```\n{summary_text}\n```\n\n"
125
+ "### Forecast Output\n"
126
+ f"```\n{forecast_text}\n```\n\n"
127
  "Return **Markdown** with:\n"
128
+ "1. Five key insights\n"
129
  "2. Three actionable strategies (with expected impact)\n"
130
  "3. Risk factors or anomalies\n"
131
  "4. Suggested additional visuals\n"
132
  )
133
 
134
  st.subheader("🚀 Strategy Recommendations (Gemini 1.5 Pro)")
135
+ with st.spinner("Generating insights…"):
136
  strategy_md = gemini.generate_content(prompt).text
137
  st.markdown(strategy_md)
138
 
139
+ # Download strategy as Markdown
140
+ st.download_button("⬇️ Download Strategy (.md)", strategy_md, file_name="strategy.md")
141
+
142
  # ──────────────────────────────────────────────────────────────
143
+ # 5. OPTIONAL EXPLORATORY VISUALS
144
  # ──────────────────────────────────────────────────────────────
145
  st.markdown("---")
146
  st.subheader("🔍 Optional Exploratory Visuals")
147
 
148
  num_cols = df_preview.select_dtypes("number").columns
149
 
150
+ if st.checkbox("Histogram"):
151
+ col = st.selectbox("Variable", num_cols, key="hist")
152
+ st.plotly_chart(histogram_tool(csv_path, col), use_container_width=True)
 
 
153
 
154
+ if st.checkbox("Scatter‑matrix"):
155
+ cols = st.multiselect("Choose up to 5 columns", num_cols, default=num_cols[:3])
156
+ if cols:
157
+ st.plotly_chart(scatter_matrix_tool(csv_path, cols), use_container_width=True)
 
 
 
 
158
 
159
+ if st.checkbox("Correlation heat‑map"):
160
+ st.plotly_chart(corr_heatmap_tool(csv_path), use_container_width=True)
 
 
161
 
162
  # ──────────────────────────────────────���───────────────────────
163
+ # 6. FULL SUMMARY
164
  # ──────────────────────────────────────────────────────────────
165
  st.markdown("---")
166
+ st.subheader("📑 CSV Summary (stats)")
167
  st.text(summary_text)