Spaces:
Sleeping
Sleeping
File size: 9,753 Bytes
779bb9b 4335246 8ee580a 64b21b3 8ee580a 42f3f9c 8ee580a c627e4b 8ee580a 5526d83 8ee580a 5526d83 c627e4b 5526d83 8ee580a 5526d83 8ee580a c627e4b 8ee580a f62d086 8ee580a 5526d83 8ee580a 42f3f9c 8ee580a 42f3f9c 8ee580a 42f3f9c 8ee580a c627e4b 8ee580a f776692 6ccbf34 c73dde2 5526d83 8ee580a 5526d83 8ee580a d4cf179 5526d83 f776692 8ee580a c73dde2 8ee580a c73dde2 34f26fc c627e4b 34f26fc 8ee580a 5526d83 c627e4b 5526d83 8ee580a 34f26fc 8ee580a 34f26fc 8ee580a 5526d83 c627e4b 5526d83 c627e4b 5526d83 42f3f9c 8ee580a 42f3f9c 34f26fc 8ee580a c627e4b 8ee580a c627e4b 8ee580a c627e4b 34f26fc f776692 c627e4b 34f26fc 8ee580a c627e4b 4335246 c627e4b |
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 239 240 241 242 243 244 245 246 |
import os
import pandas as pd
import numpy as np
import streamlit as st
from dotenv import load_dotenv
from huggingface_hub import InferenceClient, login
import google.generativeai as genai
from io import StringIO
import time
import requests
# ======================================================
# βοΈ APP CONFIGURATION
# ======================================================
st.set_page_config(page_title="π Smart Data Analyst Pro", layout="wide")
st.title("π Smart Data Analyst Pro (Chat Mode)")
st.caption("Chat with your dataset β AI cleans, analyzes, and visualizes data. Hugging Face + Gemini compatible.")
# ======================================================
# π Load Environment Variables
# ======================================================
load_dotenv()
HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_API_KEY")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
if not HF_TOKEN:
st.error("β Missing HF_TOKEN. Please set it in your .env file.")
else:
login(token=HF_TOKEN)
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
else:
st.warning("β οΈ Gemini API key missing. Gemini 2.5 Flash will not work.")
# ======================================================
# π§ MODEL SETUP
# ======================================================
with st.sidebar:
st.header("βοΈ Model Settings")
CLEANER_MODEL = st.selectbox(
"Select Cleaner Model:",
[
"Qwen/Qwen2.5-Coder-14B",
"mistralai/Mistral-7B-Instruct-v0.3"
],
index=0
)
ANALYST_MODEL = st.selectbox(
"Select Analysis Model:",
[
"Gemini 2.5 Flash (Google)",
"Qwen/Qwen2.5-14B-Instruct",
"mistralai/Mistral-7B-Instruct-v0.3",
"HuggingFaceH4/zephyr-7b-beta"
],
index=0
)
temperature = st.slider("Temperature", 0.0, 1.0, 0.3)
max_tokens = st.slider("Max Tokens", 128, 4096, 1024)
hf_cleaner_client = InferenceClient(model=CLEANER_MODEL, token=HF_TOKEN)
hf_analyst_client = None
if ANALYST_MODEL != "Gemini 2.5 Flash (Google)":
hf_analyst_client = InferenceClient(model=ANALYST_MODEL, token=HF_TOKEN)
# ======================================================
# π§© SAFE GENERATION FUNCTION
# ======================================================
def safe_hf_generate(client, prompt, temperature=0.3, max_tokens=512, retries=2):
"""Try text generation, with retry + fallback on service errors."""
for attempt in range(retries + 1):
try:
resp = client.text_generation(
prompt,
temperature=temperature,
max_new_tokens=max_tokens,
return_full_text=False,
)
return resp.strip()
except Exception as e:
err = str(e)
# π©Ή FIX: Handle common server overloads gracefully
if "503" in err or "Service Temporarily Unavailable" in err:
time.sleep(2)
if attempt < retries:
continue # retry
else:
return "β οΈ The Hugging Face model is temporarily unavailable. Please try again or switch to Gemini."
elif "Supported task: conversational" in err:
chat_resp = client.chat_completion(
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
temperature=temperature,
)
return chat_resp["choices"][0]["message"]["content"].strip()
else:
raise e
return "β οΈ Failed after retries."
# ======================================================
# π§© DATA CLEANING
# ======================================================
def fallback_clean(df: pd.DataFrame) -> pd.DataFrame:
df = df.copy()
df.dropna(axis=1, how="all", inplace=True)
df.columns = [c.strip().replace(" ", "_").lower() for c in df.columns]
for col in df.columns:
if df[col].dtype == "O":
if not df[col].mode().empty:
df[col].fillna(df[col].mode()[0], inplace=True)
else:
df[col].fillna("Unknown", inplace=True)
else:
df[col].fillna(df[col].median(), inplace=True)
df.drop_duplicates(inplace=True)
return df
def ai_clean_dataset(df: pd.DataFrame) -> (pd.DataFrame, str):
if len(df) > 50:
return df, "β οΈ AI cleaning skipped: dataset has more than 50 rows."
csv_text = df.to_csv(index=False)
prompt = f"""
You are a professional data cleaning assistant.
Clean and standardize the dataset below dynamically:
1. Handle missing values
2. Fix column name inconsistencies
3. Convert data types (dates, numbers, categories)
4. Remove irrelevant or duplicate rows
Return ONLY a valid CSV text (no markdown, no explanations).
Dataset:
{csv_text}
"""
try:
cleaned_str = safe_hf_generate(hf_cleaner_client, prompt, temperature=0.1, max_tokens=4096)
cleaned_str = cleaned_str.replace("```csv", "").replace("```", "").replace("###", "").strip()
cleaned_df = pd.read_csv(StringIO(cleaned_str), on_bad_lines="skip")
cleaned_df.columns = [c.strip().replace(" ", "_").lower() for c in cleaned_df.columns]
return cleaned_df, "β
AI cleaning completed successfully."
except Exception as e:
return df, f"β οΈ AI cleaning failed: {str(e)}"
# ======================================================
# π§© DATA SUMMARY (Token-efficient)
# ======================================================
def summarize_for_analysis(df: pd.DataFrame, sample_rows=10) -> str:
summary = [f"Rows: {len(df)}, Columns: {len(df.columns)}"]
for col in df.columns:
non_null = int(df[col].notnull().sum())
if pd.api.types.is_numeric_dtype(df[col]):
desc = df[col].describe().to_dict()
summary.append(f"- {col}: mean={desc.get('mean', np.nan):.2f}, median={df[col].median():.2f}, non_null={non_null}")
else:
top = df[col].value_counts().head(3).to_dict()
summary.append(f"- {col}: top_values={top}, non_null={non_null}")
sample = df.head(sample_rows).to_csv(index=False)
summary.append("--- Sample Data ---")
summary.append(sample)
return "\n".join(summary)
# ======================================================
# π§ ANALYSIS FUNCTION
# ======================================================
def query_analysis_model(df: pd.DataFrame, user_query: str, dataset_name: str) -> str:
prompt_summary = summarize_for_analysis(df)
prompt = f"""
You are a professional data analyst.
Analyze the dataset '{dataset_name}' and answer the user's question.
--- DATA SUMMARY ---
{prompt_summary}
--- USER QUESTION ---
{user_query}
Respond with:
1. Key insights and patterns
2. Quantitative findings
3. Notable relationships or anomalies
4. Data-driven recommendations
"""
try:
if ANALYST_MODEL == "Gemini 2.5 Flash (Google)":
response = genai.GenerativeModel("gemini-2.5-flash").generate_content(
prompt,
generation_config={
"temperature": temperature,
"max_output_tokens": max_tokens
}
)
return response.text if hasattr(response, "text") else "No valid text response."
else:
# π©Ή FIX: wrap in retry-aware generator
result = safe_hf_generate(hf_analyst_client, prompt, temperature=temperature, max_tokens=max_tokens)
# fallback to Gemini if Hugging Face failed entirely
if "temporarily unavailable" in result.lower() and GEMINI_API_KEY:
alt = genai.GenerativeModel("gemini-2.5-flash").generate_content(prompt)
return f"π Fallback to Gemini:\n\n{alt.text}"
return result
except Exception as e:
# π©Ή FIX: fallback if server rejects or 5xx
if "503" in str(e) and GEMINI_API_KEY:
response = genai.GenerativeModel("gemini-2.5-flash").generate_content(prompt)
return f"π Fallback to Gemini due to 503 error:\n\n{response.text}"
return f"β οΈ Analysis failed: {str(e)}"
# ======================================================
# π MAIN CHATBOT LOGIC
# ======================================================
uploaded = st.file_uploader("π Upload CSV or Excel file", type=["csv", "xlsx"])
if "messages" not in st.session_state:
st.session_state.messages = []
if uploaded:
df = pd.read_csv(uploaded) if uploaded.name.endswith(".csv") else pd.read_excel(uploaded)
with st.spinner("π§Ό Cleaning your dataset..."):
cleaned_df, cleaning_status = ai_clean_dataset(df)
st.subheader("β
Cleaning Status")
st.info(cleaning_status)
st.subheader("π Dataset Preview")
st.dataframe(cleaned_df.head(), use_container_width=True)
st.subheader("π¬ Chat with Your Dataset")
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
if user_query := st.chat_input("Ask something about your dataset..."):
st.session_state.messages.append({"role": "user", "content": user_query})
with st.chat_message("user"):
st.markdown(user_query)
with st.chat_message("assistant"):
with st.spinner("π€ Analyzing..."):
result = query_analysis_model(cleaned_df, user_query, uploaded.name)
st.markdown(result)
st.session_state.messages.append({"role": "assistant", "content": result})
else:
st.info("π₯ Upload a dataset to begin chatting with your AI analyst.")
|