Starberry15 commited on
Commit
779bb9b
Β·
verified Β·
1 Parent(s): be3e3d9

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +218 -32
src/streamlit_app.py CHANGED
@@ -1,40 +1,226 @@
1
- import altair as alt
2
- import numpy as np
3
  import pandas as pd
 
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import os
 
2
  import pandas as pd
3
+ import numpy as np
4
  import streamlit as st
5
+ import plotly.express as px
6
+ import plotly.figure_factory as ff
7
+ from dotenv import load_dotenv
8
+ from huggingface_hub import InferenceClient, login
9
+ from io import StringIO
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
11
+
12
+ # ======================================================
13
+ # βš™οΈ APP CONFIGURATION
14
+ # ======================================================
15
+ st.set_page_config(page_title="πŸ“Š Smart Data Analyst Pro", layout="wide")
16
+ st.title("πŸ“Š Smart Data Analyst Pro")
17
+ st.caption("AI that cleans, analyzes, and visualizes your data β€” powered by Hugging Face Inference API and local open-source models.")
18
+
19
+ # ======================================================
20
+ # πŸ” Load Environment Variables
21
+ # ======================================================
22
+ load_dotenv()
23
+ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_API_KEY")
24
+ if not HF_TOKEN:
25
+ st.error("❌ Missing HF_TOKEN. Please set it in your .env file.")
26
+ else:
27
+ login(token=HF_TOKEN)
28
+
29
+ # ======================================================
30
+ # 🧠 MODEL SETTINGS
31
+ # ======================================================
32
+ with st.sidebar:
33
+ st.header("βš™οΈ Model Settings")
34
+
35
+ CLEANER_MODEL = st.selectbox(
36
+ "Select Cleaner Model:",
37
+ [
38
+ "Qwen/Qwen2.5-Coder-7B-Instruct",
39
+ "meta-llama/Meta-Llama-3-8B-Instruct",
40
+ "microsoft/Phi-3-mini-4k-instruct"
41
+ ],
42
+ index=0
43
+ )
44
+
45
+ ANALYST_MODEL = st.selectbox(
46
+ "Select Analysis Model (Local Open-Source Recommended):",
47
+ [
48
+ "meta-llama/Meta-Llama-3-8B-Instruct",
49
+ "Qwen/Qwen2.5-Coder-7B-Instruct",
50
+ "HuggingFaceH4/zephyr-7b-beta",
51
+ "mistralai/Mistral-7B-Instruct-v0.3"
52
+ ],
53
+ index=0
54
+ )
55
 
56
+ temperature = st.slider("Temperature", 0.0, 1.0, 0.3)
57
+ max_tokens = st.slider("Max Tokens", 128, 2048, 512)
58
+
59
+ # Initialize cleaner client (HF API)
60
+ cleaner_client = InferenceClient(model=CLEANER_MODEL, token=HF_TOKEN)
61
+
62
+ # Initialize local analyst if open-source
63
+ local_analyst = None
64
+ if ANALYST_MODEL in ["meta-llama/Meta-Llama-3-8B-Instruct"]:
65
+ try:
66
+ tokenizer = AutoTokenizer.from_pretrained(ANALYST_MODEL)
67
+ model = AutoModelForCausalLM.from_pretrained(ANALYST_MODEL)
68
+ local_analyst = pipeline("text-generation", model=model, tokenizer=tokenizer)
69
+ except Exception as e:
70
+ st.warning(f"⚠️ Failed to load local analyst: {e}")
71
+
72
+ # ======================================================
73
+ # 🧩 DATA CLEANING FUNCTIONS
74
+ # ======================================================
75
+ def fallback_clean(df: pd.DataFrame) -> pd.DataFrame:
76
+ df = df.copy()
77
+ df.dropna(axis=1, how="all", inplace=True)
78
+ df.columns = [c.strip().replace(" ", "_").lower() for c in df.columns]
79
+ for col in df.columns:
80
+ if df[col].dtype == "O":
81
+ df[col].fillna(df[col].mode()[0] if not df[col].mode().empty else "Unknown", inplace=True)
82
+ else:
83
+ df[col].fillna(df[col].median(), inplace=True)
84
+ df.drop_duplicates(inplace=True)
85
+ return df
86
+
87
+ def ai_clean_dataset(df: pd.DataFrame) -> pd.DataFrame:
88
+ raw_preview = df.head(5).to_csv(index=False)
89
+ prompt = f"""
90
+ You are a Python data cleaning expert.
91
+ Clean and standardize the dataset dynamically:
92
+ - Handle missing values logically
93
+ - Correct and normalize column names
94
+ - Detect and fix datatype inconsistencies
95
+ - Remove duplicates or invalid rows
96
+ Return ONLY valid CSV text (no Markdown).
97
+
98
+ --- RAW SAMPLE ---
99
+ {raw_preview}
100
  """
101
+ try:
102
+ response = cleaner_client.text_generation(prompt, max_new_tokens=1024, temperature=0.1, return_full_text=False)
103
+ cleaned_str = response.strip()
104
+ except Exception as e:
105
+ st.warning(f"⚠️ AI cleaning failed: {e}")
106
+ return fallback_clean(df)
107
+
108
+ cleaned_str = cleaned_str.replace("```csv","").replace("```","").replace("###","").replace(";",",").strip()
109
+ lines = [l for l in cleaned_str.splitlines() if "," in l]
110
+ cleaned_str = "\n".join(lines)
111
 
112
+ try:
113
+ cleaned_df = pd.read_csv(StringIO(cleaned_str), on_bad_lines="skip")
114
+ cleaned_df.dropna(axis=1, how="all", inplace=True)
115
+ cleaned_df.columns = [c.strip().replace(" ", "_").lower() for c in cleaned_df.columns]
116
+ return cleaned_df
117
+ except Exception as e:
118
+ st.warning(f"⚠️ CSV parse failed: {e}")
119
+ return fallback_clean(df)
120
 
121
+ def summarize_dataframe(df: pd.DataFrame) -> str:
122
+ lines = [f"Rows: {len(df)} | Columns: {len(df.columns)}", "Column summaries:"]
123
+ for col in df.columns[:10]:
124
+ non_null = int(df[col].notnull().sum())
125
+ if pd.api.types.is_numeric_dtype(df[col]):
126
+ mean = df[col].mean()
127
+ median = df[col].median() if non_null > 0 else None
128
+ lines.append(f"- {col}: mean={mean:.3f}, median={median}, non_null={non_null}")
129
+ else:
130
+ top = df[col].value_counts().head(3).to_dict()
131
+ lines.append(f"- {col}: top_values={top}, non_null={non_null}")
132
+ return "\n".join(lines)
133
+
134
+ # ======================================================
135
+ # 🧠 ANALYSIS FUNCTION
136
+ # ======================================================
137
+ def query_analysis_model(df: pd.DataFrame, user_query: str, dataset_name: str) -> str:
138
+ df_summary = summarize_dataframe(df)
139
+ sample = df.head(6).to_csv(index=False)
140
+ prompt = f"""
141
+ You are a data analyst.
142
+ Analyze '{dataset_name}' and answer the question below.
143
+ Base your insights only on the provided data.
144
+
145
+ --- SUMMARY ---
146
+ {df_summary}
147
+
148
+ --- SAMPLE DATA ---
149
+ {sample}
150
+
151
+ --- QUESTION ---
152
+ {user_query}
153
+
154
+ Respond concisely with key insights, numbers, patterns, and recommended steps.
155
  """
156
+ if local_analyst:
157
+ try:
158
+ response = local_analyst(prompt, max_new_tokens=max_tokens, temperature=temperature)
159
+ return response[0]['generated_text']
160
+ except Exception as e:
161
+ return f"⚠️ Local analysis failed: {e}"
162
+ else:
163
+ st.warning("⚠️ Analyst model is not local. Using HF API may require payment.")
164
+ return "Analysis not available for free model."
165
+
166
+ # ======================================================
167
+ # πŸš€ MAIN APP
168
+ # ======================================================
169
+ uploaded = st.file_uploader("πŸ“Ž Upload CSV or Excel file", type=["csv", "xlsx"])
170
+
171
+ if uploaded:
172
+ try:
173
+ df = pd.read_csv(uploaded) if uploaded.name.endswith(".csv") else pd.read_excel(uploaded)
174
+ except Exception as e:
175
+ st.error(f"❌ File load failed: {e}")
176
+ st.stop()
177
+
178
+ with st.spinner("🧼 AI Cleaning your dataset..."):
179
+ cleaned_df = ai_clean_dataset(df)
180
+
181
+ st.subheader("βœ… Cleaned Dataset Preview")
182
+ st.dataframe(cleaned_df.head(), use_container_width=True)
183
+
184
+ with st.expander("πŸ“‹ Cleaning Summary"):
185
+ st.text(summarize_dataframe(cleaned_df))
186
+
187
+ with st.expander("πŸ“ˆ Quick Visualizations", expanded=True):
188
+ numeric_cols = cleaned_df.select_dtypes(include="number").columns.tolist()
189
+ categorical_cols = cleaned_df.select_dtypes(exclude="number").columns.tolist()
190
+ viz_type = st.selectbox("Visualization Type", ["Scatter Plot", "Histogram", "Box Plot", "Correlation Heatmap", "Categorical Count"])
191
+
192
+ if viz_type == "Scatter Plot" and len(numeric_cols) >= 2:
193
+ x = st.selectbox("X-axis", numeric_cols)
194
+ y = st.selectbox("Y-axis", numeric_cols, index=min(1,len(numeric_cols)-1))
195
+ color = st.selectbox("Color", ["None"] + categorical_cols)
196
+ fig = px.scatter(cleaned_df, x=x, y=y, color=None if color=="None" else color)
197
+ st.plotly_chart(fig, use_container_width=True)
198
+ elif viz_type == "Histogram" and numeric_cols:
199
+ col = st.selectbox("Column", numeric_cols)
200
+ fig = px.histogram(cleaned_df, x=col, nbins=30)
201
+ st.plotly_chart(fig, use_container_width=True)
202
+ elif viz_type == "Box Plot" and numeric_cols:
203
+ col = st.selectbox("Column", numeric_cols)
204
+ fig = px.box(cleaned_df, y=col)
205
+ st.plotly_chart(fig, use_container_width=True)
206
+ elif viz_type == "Correlation Heatmap" and len(numeric_cols) > 1:
207
+ corr = cleaned_df[numeric_cols].corr()
208
+ fig = ff.create_annotated_heatmap(z=corr.values, x=list(corr.columns), y=list(corr.index),
209
+ annotation_text=corr.round(2).values, showscale=True)
210
+ st.plotly_chart(fig, use_container_width=True)
211
+ elif viz_type == "Categorical Count" and categorical_cols:
212
+ cat = st.selectbox("Category", categorical_cols)
213
+ fig = px.bar(cleaned_df[cat].value_counts().reset_index(), x="index", y=cat)
214
+ st.plotly_chart(fig, use_container_width=True)
215
+ else:
216
+ st.warning("⚠️ Not enough columns for this visualization type.")
217
 
218
+ st.subheader("πŸ’¬ Ask AI About Your Data")
219
+ user_query = st.text_area("Enter your question:", placeholder="e.g. What factors influence sales?")
220
+ if st.button("Analyze with AI", use_container_width=True) and user_query:
221
+ with st.spinner("πŸ€– Interpreting data..."):
222
+ result = query_analysis_model(cleaned_df, user_query, uploaded.name)
223
+ st.markdown("### πŸ’‘ Insights")
224
+ st.markdown(result)
225
+ else:
226
+ st.info("πŸ“₯ Upload a dataset to begin smart analysis.")