Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +256 -128
src/streamlit_app.py
CHANGED
|
@@ -1,140 +1,268 @@
|
|
| 1 |
-
# streamlit_data_analysis_app.py
|
| 2 |
-
# Streamlit Data Analysis App with LLM-powered cleaning and insights
|
| 3 |
-
# Features:
|
| 4 |
-
# - Upload CSV / Excel
|
| 5 |
-
# - Dataset cleaned automatically by Qwen 2.5 Coder
|
| 6 |
-
# - Preprocessing, visualizations, summaries
|
| 7 |
-
# - Insights via Mistral, Mixtral, Qwen 14B, Gemini
|
| 8 |
-
|
| 9 |
import os
|
| 10 |
-
import streamlit as st
|
| 11 |
import pandas as pd
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
import
|
| 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 |
try:
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
def call_gemini(prompt: str, model="gemini-2.0-flash"):
|
| 53 |
-
if not GEMINI_API_KEY:
|
| 54 |
-
return "β οΈ Gemini API key not found."
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
-
response = model_obj.generate_content(prompt)
|
| 58 |
-
return response.text
|
| 59 |
except Exception as e:
|
| 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 |
else:
|
| 136 |
-
|
| 137 |
-
st.write(resp)
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
else:
|
| 140 |
-
st.info("π₯ Upload a dataset to begin.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 11 |
+
# ======================================================
|
| 12 |
+
# βοΈ APP CONFIGURATION
|
| 13 |
+
# ======================================================
|
| 14 |
+
st.set_page_config(page_title="π Smart Data Analyst Pro", layout="wide")
|
| 15 |
+
st.title("π Smart Data Analyst Pro")
|
| 16 |
+
st.caption("AI that cleans, analyzes, and visualizes your data β powered by Hugging Face Inference API.")
|
| 17 |
+
|
| 18 |
+
# ======================================================
|
| 19 |
+
# π Load Environment Variables
|
| 20 |
+
# ======================================================
|
| 21 |
+
load_dotenv()
|
| 22 |
+
HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_API_KEY")
|
| 23 |
+
if not HF_TOKEN:
|
| 24 |
+
st.error("β Missing HF_TOKEN. Please set it in your .env file.")
|
| 25 |
+
else:
|
| 26 |
+
login(token=HF_TOKEN)
|
| 27 |
+
|
| 28 |
+
# ======================================================
|
| 29 |
+
# π§ MODEL SETUP
|
| 30 |
+
# ======================================================
|
| 31 |
+
with st.sidebar:
|
| 32 |
+
st.header("βοΈ Model Settings")
|
| 33 |
+
|
| 34 |
+
CLEANER_MODEL = st.selectbox(
|
| 35 |
+
"Select Cleaner Model:",
|
| 36 |
+
[
|
| 37 |
+
"Qwen/Qwen2.5-Coder-7B-Instruct",
|
| 38 |
+
"meta-llama/Meta-Llama-3-8B-Instruct",
|
| 39 |
+
"microsoft/Phi-3-mini-4k-instruct",
|
| 40 |
+
"mistralai/Mistral-7B-Instruct-v0.3"
|
| 41 |
+
],
|
| 42 |
+
index=0
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
ANALYST_MODEL = st.selectbox(
|
| 46 |
+
"Select Analysis Model:",
|
| 47 |
+
[
|
| 48 |
+
"Qwen/Qwen2.5-14B-Instruct",
|
| 49 |
+
"mistralai/Mistral-7B-Instruct-v0.3",
|
| 50 |
+
"HuggingFaceH4/zephyr-7b-beta"
|
| 51 |
+
],
|
| 52 |
+
index=0
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
temperature = st.slider("Temperature", 0.0, 1.0, 0.3)
|
| 56 |
+
max_tokens = st.slider("Max Tokens", 128, 2048, 512)
|
| 57 |
+
|
| 58 |
+
# Initialize inference clients
|
| 59 |
+
cleaner_client = InferenceClient(model=CLEANER_MODEL, token=HF_TOKEN)
|
| 60 |
+
analyst_client = InferenceClient(model=ANALYST_MODEL, token=HF_TOKEN)
|
| 61 |
+
|
| 62 |
+
# ======================================================
|
| 63 |
+
# π§© SAFE GENERATION FUNCTION
|
| 64 |
+
# ======================================================
|
| 65 |
+
def safe_hf_generate(client, prompt, temperature=0.3, max_tokens=512):
|
| 66 |
+
"""
|
| 67 |
+
Tries text_generation first, then falls back to chat_completion if not supported.
|
| 68 |
+
Returns plain string content.
|
| 69 |
+
"""
|
| 70 |
try:
|
| 71 |
+
resp = client.text_generation(
|
| 72 |
+
prompt,
|
| 73 |
+
temperature=temperature,
|
| 74 |
+
max_new_tokens=max_tokens,
|
| 75 |
+
return_full_text=False,
|
| 76 |
+
)
|
| 77 |
+
return resp.strip()
|
| 78 |
except Exception as e:
|
| 79 |
+
if "Supported task: conversational" in str(e) or "not supported" in str(e):
|
| 80 |
+
chat_resp = client.chat_completion(
|
| 81 |
+
messages=[{"role": "user", "content": prompt}],
|
| 82 |
+
max_tokens=max_tokens,
|
| 83 |
+
temperature=temperature,
|
| 84 |
+
)
|
| 85 |
+
return chat_resp["choices"][0]["message"]["content"].strip()
|
| 86 |
+
else:
|
| 87 |
+
raise e
|
| 88 |
+
|
| 89 |
+
# ======================================================
|
| 90 |
+
# π§© SMART DATA CLEANING
|
| 91 |
+
# ======================================================
|
| 92 |
+
def fallback_clean(df: pd.DataFrame) -> pd.DataFrame:
|
| 93 |
+
"""Backup rule-based cleaner."""
|
| 94 |
+
df = df.copy()
|
| 95 |
+
df.dropna(axis=1, how="all", inplace=True)
|
| 96 |
+
df.columns = [c.strip().replace(" ", "_").lower() for c in df.columns]
|
| 97 |
+
for col in df.columns:
|
| 98 |
+
if df[col].dtype == "O":
|
| 99 |
+
if not df[col].mode().empty:
|
| 100 |
+
df[col].fillna(df[col].mode()[0], inplace=True)
|
| 101 |
+
else:
|
| 102 |
+
df[col].fillna("Unknown", inplace=True)
|
| 103 |
+
else:
|
| 104 |
+
df[col].fillna(df[col].median(), inplace=True)
|
| 105 |
+
df.drop_duplicates(inplace=True)
|
| 106 |
+
return df
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def ai_clean_dataset(df: pd.DataFrame) -> pd.DataFrame:
|
| 110 |
+
"""Cleans the dataset using the selected AI model. Falls back gracefully if the model fails."""
|
| 111 |
+
raw_preview = df.head(5).to_csv(index=False)
|
| 112 |
+
prompt = f"""
|
| 113 |
+
You are a professional data cleaning assistant.
|
| 114 |
+
Clean and standardize the dataset below dynamically:
|
| 115 |
+
1. Handle missing values
|
| 116 |
+
2. Fix column name inconsistencies
|
| 117 |
+
3. Convert data types (dates, numbers, categories)
|
| 118 |
+
4. Remove irrelevant or duplicate rows
|
| 119 |
+
Return ONLY a valid CSV text (no markdown, no explanations).
|
| 120 |
+
|
| 121 |
+
--- RAW SAMPLE ---
|
| 122 |
+
{raw_preview}
|
| 123 |
+
"""
|
| 124 |
|
|
|
|
|
|
|
|
|
|
| 125 |
try:
|
| 126 |
+
cleaned_str = safe_hf_generate(cleaner_client, prompt, temperature=0.1, max_tokens=1024)
|
|
|
|
|
|
|
| 127 |
except Exception as e:
|
| 128 |
+
st.warning(f"β οΈ AI cleaning failed: {e}")
|
| 129 |
+
return fallback_clean(df)
|
| 130 |
|
| 131 |
+
cleaned_str = (
|
| 132 |
+
cleaned_str.replace("```csv", "")
|
| 133 |
+
.replace("```", "")
|
| 134 |
+
.replace("###", "")
|
| 135 |
+
.replace(";", ",")
|
| 136 |
+
.strip()
|
| 137 |
+
)
|
| 138 |
|
| 139 |
+
lines = cleaned_str.splitlines()
|
| 140 |
+
lines = [line for line in lines if "," in line and not line.lower().startswith(("note", "summary"))]
|
| 141 |
+
cleaned_str = "\n".join(lines)
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
cleaned_df = pd.read_csv(StringIO(cleaned_str), on_bad_lines="skip")
|
| 145 |
+
cleaned_df = cleaned_df.dropna(axis=1, how="all")
|
| 146 |
+
cleaned_df.columns = [c.strip().replace(" ", "_").lower() for c in cleaned_df.columns]
|
| 147 |
+
return cleaned_df
|
| 148 |
+
except Exception as e:
|
| 149 |
+
st.warning(f"β οΈ AI CSV parse failed: {e}")
|
| 150 |
+
return fallback_clean(df)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def summarize_dataframe(df: pd.DataFrame) -> str:
|
| 154 |
+
"""Generate a concise summary of the dataframe."""
|
| 155 |
+
lines = [f"Rows: {len(df)} | Columns: {len(df.columns)}", "Column summaries:"]
|
| 156 |
+
for col in df.columns[:10]:
|
| 157 |
+
non_null = int(df[col].notnull().sum())
|
| 158 |
+
if pd.api.types.is_numeric_dtype(df[col]):
|
| 159 |
+
desc = df[col].describe().to_dict()
|
| 160 |
+
mean = float(desc.get("mean", np.nan))
|
| 161 |
+
median = float(df[col].median()) if non_null > 0 else None
|
| 162 |
+
lines.append(f"- {col}: mean={mean:.3f}, median={median}, non_null={non_null}")
|
| 163 |
+
else:
|
| 164 |
+
top = df[col].value_counts().head(3).to_dict()
|
| 165 |
+
lines.append(f"- {col}: top_values={top}, non_null={non_null}")
|
| 166 |
+
return "\n".join(lines)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def query_analysis_model(df: pd.DataFrame, user_query: str, dataset_name: str) -> str:
|
| 170 |
+
"""Send the dataframe and user query to the analysis model for interpretation."""
|
| 171 |
+
df_summary = summarize_dataframe(df)
|
| 172 |
+
sample = df.head(6).to_csv(index=False)
|
| 173 |
+
prompt = f"""
|
| 174 |
+
You are a professional data analyst.
|
| 175 |
+
Analyze the dataset '{dataset_name}' and answer the user's question.
|
| 176 |
+
|
| 177 |
+
--- SUMMARY ---
|
| 178 |
+
{df_summary}
|
| 179 |
+
|
| 180 |
+
--- SAMPLE DATA ---
|
| 181 |
+
{sample}
|
| 182 |
+
|
| 183 |
+
--- USER QUESTION ---
|
| 184 |
+
{user_query}
|
| 185 |
+
|
| 186 |
+
Respond with:
|
| 187 |
+
1. Key insights and patterns
|
| 188 |
+
2. Quantitative findings
|
| 189 |
+
3. Notable relationships or anomalies
|
| 190 |
+
4. Data-driven recommendations
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
try:
|
| 194 |
+
response = safe_hf_generate(analyst_client, prompt, temperature=temperature, max_tokens=max_tokens)
|
| 195 |
+
return response
|
| 196 |
+
except Exception as e:
|
| 197 |
+
return f"β οΈ Analysis failed: {e}"
|
| 198 |
+
|
| 199 |
+
# ======================================================
|
| 200 |
+
# π MAIN APP LOGIC
|
| 201 |
+
# ======================================================
|
| 202 |
+
uploaded = st.file_uploader("π Upload CSV or Excel file", type=["csv", "xlsx"])
|
| 203 |
+
|
| 204 |
+
if uploaded:
|
| 205 |
+
df = pd.read_csv(uploaded) if uploaded.name.endswith(".csv") else pd.read_excel(uploaded)
|
| 206 |
+
|
| 207 |
+
with st.spinner("π§Ό AI Cleaning your dataset..."):
|
| 208 |
+
cleaned_df = ai_clean_dataset(df)
|
| 209 |
+
|
| 210 |
+
st.subheader("β
Cleaned Dataset Preview")
|
| 211 |
+
st.dataframe(cleaned_df.head(), use_container_width=True)
|
| 212 |
+
|
| 213 |
+
with st.expander("π Cleaning Summary", expanded=False):
|
| 214 |
+
st.text(summarize_dataframe(cleaned_df))
|
| 215 |
+
|
| 216 |
+
with st.expander("π Quick Visualizations", expanded=True):
|
| 217 |
+
numeric_cols = cleaned_df.select_dtypes(include="number").columns.tolist()
|
| 218 |
+
categorical_cols = cleaned_df.select_dtypes(exclude="number").columns.tolist()
|
| 219 |
+
|
| 220 |
+
viz_type = st.selectbox(
|
| 221 |
+
"Visualization Type",
|
| 222 |
+
["Scatter Plot", "Histogram", "Box Plot", "Correlation Heatmap", "Categorical Count"]
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if viz_type == "Scatter Plot" and len(numeric_cols) >= 2:
|
| 226 |
+
x = st.selectbox("X-axis", numeric_cols)
|
| 227 |
+
y = st.selectbox("Y-axis", numeric_cols, index=min(1, len(numeric_cols)-1))
|
| 228 |
+
color = st.selectbox("Color", ["None"] + categorical_cols)
|
| 229 |
+
fig = px.scatter(cleaned_df, x=x, y=y, color=None if color=="None" else color)
|
| 230 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 231 |
+
|
| 232 |
+
elif viz_type == "Histogram" and numeric_cols:
|
| 233 |
+
col = st.selectbox("Column", numeric_cols)
|
| 234 |
+
fig = px.histogram(cleaned_df, x=col, nbins=30)
|
| 235 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 236 |
+
|
| 237 |
+
elif viz_type == "Box Plot" and numeric_cols:
|
| 238 |
+
col = st.selectbox("Column", numeric_cols)
|
| 239 |
+
fig = px.box(cleaned_df, y=col)
|
| 240 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 241 |
+
|
| 242 |
+
elif viz_type == "Correlation Heatmap" and len(numeric_cols) > 1:
|
| 243 |
+
corr = cleaned_df[numeric_cols].corr()
|
| 244 |
+
fig = ff.create_annotated_heatmap(
|
| 245 |
+
z=corr.values,
|
| 246 |
+
x=list(corr.columns),
|
| 247 |
+
y=list(corr.index),
|
| 248 |
+
annotation_text=corr.round(2).values,
|
| 249 |
+
showscale=True
|
| 250 |
+
)
|
| 251 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 252 |
+
|
| 253 |
+
elif viz_type == "Categorical Count" and categorical_cols:
|
| 254 |
+
cat = st.selectbox("Category", categorical_cols)
|
| 255 |
+
fig = px.bar(cleaned_df[cat].value_counts().reset_index(), x="index", y=cat)
|
| 256 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 257 |
else:
|
| 258 |
+
st.warning("β οΈ Not enough columns for this visualization type.")
|
|
|
|
| 259 |
|
| 260 |
+
st.subheader("π¬ Ask AI About Your Data")
|
| 261 |
+
user_query = st.text_area("Enter your question:", placeholder="e.g. What factors influence sales the most?")
|
| 262 |
+
if st.button("Analyze with AI", use_container_width=True) and user_query:
|
| 263 |
+
with st.spinner("π€ Interpreting data..."):
|
| 264 |
+
result = query_analysis_model(cleaned_df, user_query, uploaded.name)
|
| 265 |
+
st.markdown("### π‘ Insights")
|
| 266 |
+
st.markdown(result)
|
| 267 |
else:
|
| 268 |
+
st.info("π₯ Upload a dataset to begin smart analysis.")
|