Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +95 -251
src/streamlit_app.py
CHANGED
|
@@ -1,268 +1,112 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
import streamlit as st
|
| 5 |
-
|
| 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
|
| 20 |
-
#
|
| 21 |
load_dotenv()
|
| 22 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 23 |
if not HF_TOKEN:
|
| 24 |
-
st.error("β Missing
|
| 25 |
else:
|
| 26 |
login(token=HF_TOKEN)
|
| 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 |
-
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 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
4. Data-driven recommendations
|
| 191 |
"""
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 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 |
-
|
| 211 |
-
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
| 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.")
|
|
|
|
| 1 |
import os
|
| 2 |
+
import time
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
import streamlit as st
|
| 5 |
+
from io import StringIO
|
|
|
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
from huggingface_hub import InferenceClient, login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# ==========================================================
|
| 10 |
+
# π Load environment + authenticate
|
| 11 |
+
# ==========================================================
|
| 12 |
load_dotenv()
|
| 13 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 14 |
+
|
| 15 |
if not HF_TOKEN:
|
| 16 |
+
st.error("β Missing Hugging Face token. Please set HF_TOKEN in your .env file.")
|
| 17 |
else:
|
| 18 |
login(token=HF_TOKEN)
|
| 19 |
|
| 20 |
+
# Create HF clients
|
| 21 |
+
cleaner_client = InferenceClient(model="Qwen/Qwen2.5-Coder-14B", token=HF_TOKEN)
|
| 22 |
+
analyst_client = InferenceClient(model="Qwen/Qwen2.5-14B-Instruct", token=HF_TOKEN)
|
| 23 |
+
|
| 24 |
+
# ==========================================================
|
| 25 |
+
# ποΈ App Layout
|
| 26 |
+
# ==========================================================
|
| 27 |
+
st.set_page_config(page_title="π§Ή Smart Data Analysis", page_icon="π", layout="wide")
|
| 28 |
+
st.title("π Smart Data Analysis Assistant")
|
| 29 |
+
st.caption("Clean messy data, then run AI-powered insights and statistical analysis β all locally with open-source models.")
|
| 30 |
+
|
| 31 |
+
# ==========================================================
|
| 32 |
+
# π Upload CSV
|
| 33 |
+
# ==========================================================
|
| 34 |
+
uploaded_file = st.file_uploader("π€ Upload your CSV dataset", type=["csv"])
|
| 35 |
+
if uploaded_file:
|
| 36 |
+
df_raw = pd.read_csv(uploaded_file)
|
| 37 |
+
st.subheader("π Raw Data Preview")
|
| 38 |
+
st.dataframe(df_raw.head())
|
| 39 |
+
|
| 40 |
+
# ==========================================================
|
| 41 |
+
# π§Ή Data Cleaning
|
| 42 |
+
# ==========================================================
|
| 43 |
+
if st.button("π§Ή Clean Data using Qwen Coder 14B"):
|
| 44 |
+
with st.spinner("Cleaning data... please wait β³"):
|
| 45 |
+
try:
|
| 46 |
+
# Convert DataFrame to text for cleaning
|
| 47 |
+
csv_text = df_raw.to_csv(index=False)
|
| 48 |
+
|
| 49 |
+
prompt = f"""
|
| 50 |
+
You are a Python data cleaning assistant.
|
| 51 |
+
Clean this dataset and fix inconsistent column names, missing values, and formatting.
|
| 52 |
+
Return a clean CSV version that can be loaded into pandas directly.
|
| 53 |
+
|
| 54 |
+
Dataset:
|
| 55 |
+
{csv_text}
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
response = cleaner_client.text_generation(
|
| 59 |
+
prompt,
|
| 60 |
+
temperature=0.2,
|
| 61 |
+
max_new_tokens=2048,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
cleaned_csv = response.strip().split("```")[-1] # extract text
|
| 65 |
+
df_cleaned = pd.read_csv(StringIO(cleaned_csv))
|
| 66 |
+
|
| 67 |
+
st.session_state.cleaned_df = df_cleaned
|
| 68 |
+
st.success("β
Data cleaned successfully!")
|
| 69 |
+
st.dataframe(df_cleaned.head())
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
st.error(f"β οΈ Cleaning failed: {e}")
|
| 73 |
+
|
| 74 |
+
# ==========================================================
|
| 75 |
+
# π Data Analysis
|
| 76 |
+
# ==========================================================
|
| 77 |
+
if "cleaned_df" in st.session_state:
|
| 78 |
+
df = st.session_state.cleaned_df
|
| 79 |
+
st.divider()
|
| 80 |
+
st.subheader("π AI Data Analysis")
|
| 81 |
+
|
| 82 |
+
user_query = st.text_area("Ask about your data:", placeholder="e.g., What is the correlation between experience and salary?")
|
| 83 |
+
if st.button("π Analyze"):
|
| 84 |
+
with st.spinner("Analyzing with Qwen 14B Instruct..."):
|
| 85 |
+
try:
|
| 86 |
+
csv_excerpt = df.head(30).to_csv(index=False)
|
| 87 |
+
analysis_prompt = f"""
|
| 88 |
+
You are a data analyst. Analyze this dataset and answer the question.
|
| 89 |
+
|
| 90 |
+
Data sample (CSV):
|
| 91 |
+
{csv_excerpt}
|
| 92 |
+
|
| 93 |
+
Question:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
{user_query}
|
| 95 |
|
| 96 |
+
Instructions:
|
| 97 |
+
- Be accurate and concise.
|
| 98 |
+
- If numerical analysis is relevant, describe it.
|
| 99 |
+
- Use markdown for readability.
|
|
|
|
| 100 |
"""
|
| 101 |
|
| 102 |
+
response = analyst_client.text_generation(
|
| 103 |
+
analysis_prompt,
|
| 104 |
+
temperature=0.5,
|
| 105 |
+
max_new_tokens=1024,
|
| 106 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
st.markdown("### π§ Analysis Result")
|
| 109 |
+
st.write(response.strip())
|
| 110 |
|
| 111 |
+
except Exception as e:
|
| 112 |
+
st.error(f"β οΈ Analysis failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|