Spaces:
Sleeping
Sleeping
first push
Browse files- src/streamlit_app.py +67 -133
src/streamlit_app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
import os
|
| 4 |
import pickle
|
| 5 |
from sklearn.preprocessing import LabelEncoder
|
| 6 |
from sklearn.model_selection import train_test_split
|
|
@@ -9,18 +8,23 @@ from sklearn.neighbors import KNeighborsClassifier
|
|
| 9 |
from sklearn.tree import DecisionTreeClassifier
|
| 10 |
from sklearn.metrics import accuracy_score, r2_score
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
st.sidebar.title("Navigation")
|
| 26 |
page = st.sidebar.selectbox("Go to", ["Upload File", "Preprocess Data", "Train & Select Model", "Create App"])
|
|
@@ -33,34 +37,21 @@ if page == "Upload File":
|
|
| 33 |
uploaded_file = st.file_uploader("Upload a CSV or SQL file", type=["csv", "sql"])
|
| 34 |
|
| 35 |
if uploaded_file is not None:
|
| 36 |
-
|
| 37 |
-
with open(save_path, "wb") as f:
|
| 38 |
-
f.write(uploaded_file.getbuffer())
|
| 39 |
-
st.success(f"File saved to {save_path}")
|
| 40 |
-
|
| 41 |
if uploaded_file.name.endswith(".csv"):
|
| 42 |
-
df = pd.read_csv(
|
| 43 |
-
st.dataframe(df)
|
| 44 |
elif uploaded_file.name.endswith(".sql"):
|
| 45 |
-
|
| 46 |
-
sql_content = f.read()
|
| 47 |
st.text_area("SQL Content", sql_content, height=300)
|
|
|
|
| 48 |
|
| 49 |
# ========================
|
| 50 |
# Preprocess Data Page
|
| 51 |
# ========================
|
| 52 |
elif page == "Preprocess Data":
|
| 53 |
st.title("Preprocess Uploaded CSV")
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
if files:
|
| 57 |
-
selected_file = st.selectbox("Select a CSV file to preprocess", files)
|
| 58 |
-
file_path = os.path.join(UPLOAD_DIR, selected_file)
|
| 59 |
-
|
| 60 |
-
if "df" not in st.session_state or st.session_state.file_path != file_path:
|
| 61 |
-
st.session_state.df = pd.read_csv(file_path)
|
| 62 |
-
st.session_state.file_path = file_path
|
| 63 |
-
|
| 64 |
st.write("Current Data:")
|
| 65 |
st.dataframe(st.session_state.df)
|
| 66 |
|
|
@@ -73,11 +64,7 @@ elif page == "Preprocess Data":
|
|
| 73 |
if st.button("Drop Missing / Placeholder Values"):
|
| 74 |
st.session_state.df = st.session_state.df.replace(missing_placeholders, pd.NA)
|
| 75 |
st.session_state.df = st.session_state.df.dropna()
|
| 76 |
-
st.success("
|
| 77 |
-
missing_after = st.session_state.df.isnull().sum()
|
| 78 |
-
st.write("Missing values per column AFTER drop:")
|
| 79 |
-
st.dataframe(missing_after.rename("Missing Count"))
|
| 80 |
-
st.dataframe(st.session_state.df)
|
| 81 |
|
| 82 |
col_to_drop = st.multiselect("Select columns to drop", st.session_state.df.columns)
|
| 83 |
if st.button("Drop Selected Columns"):
|
|
@@ -85,25 +72,18 @@ elif page == "Preprocess Data":
|
|
| 85 |
st.success(f"Dropped columns: {col_to_drop}")
|
| 86 |
|
| 87 |
if st.button("Label Encode Object Columns"):
|
| 88 |
-
|
| 89 |
for col in st.session_state.df.select_dtypes(include=['object']).columns:
|
| 90 |
le = LabelEncoder()
|
| 91 |
st.session_state.df[col] = le.fit_transform(st.session_state.df[col].astype(str))
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
for col, le in label_encoders.items():
|
| 95 |
-
with open(f"{ENCODERS_DIR}/{selected_file}_{col}_encoder.pkl", "wb") as f:
|
| 96 |
-
pickle.dump(le, f)
|
| 97 |
-
|
| 98 |
-
st.success("All object columns label-encoded and encoders saved!")
|
| 99 |
-
st.dataframe(st.session_state.df)
|
| 100 |
|
| 101 |
-
if st.button("Save Preprocessed
|
| 102 |
-
|
| 103 |
-
st.
|
| 104 |
-
st.success(f"Preprocessed file saved to: {processed_path}")
|
| 105 |
else:
|
| 106 |
-
st.warning("
|
| 107 |
|
| 108 |
# ========================
|
| 109 |
# Train & Select Model Page
|
|
@@ -111,35 +91,26 @@ elif page == "Preprocess Data":
|
|
| 111 |
elif page == "Train & Select Model":
|
| 112 |
st.title("Train Models and Select the Best One")
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
if processed_files:
|
| 117 |
-
selected_file = st.selectbox("Select a processed CSV", processed_files)
|
| 118 |
-
file_path = os.path.join(PROCESSED_DIR, selected_file)
|
| 119 |
-
|
| 120 |
-
df = pd.read_csv(file_path)
|
| 121 |
-
st.dataframe(df.head())
|
| 122 |
-
|
| 123 |
target_col = st.selectbox("Select target column", df.columns)
|
| 124 |
-
st.dataframe(df[target_col].value_counts())
|
| 125 |
|
| 126 |
if target_col:
|
| 127 |
X = df.drop(columns=[target_col])
|
| 128 |
y = df[target_col]
|
| 129 |
|
| 130 |
if y.dtype == "object" or len(y.unique()) <= 20:
|
| 131 |
-
problem_type = "classification"
|
| 132 |
else:
|
| 133 |
-
problem_type = "regression"
|
| 134 |
|
| 135 |
-
test_size = st.slider("Test size (%)",
|
| 136 |
-
X_train, X_test, y_train, y_test = train_test_split(
|
| 137 |
-
X, y, test_size=test_size/100, random_state=42
|
| 138 |
-
)
|
| 139 |
|
| 140 |
results = {}
|
|
|
|
| 141 |
|
| 142 |
-
if problem_type == "classification":
|
| 143 |
models = {
|
| 144 |
"Logistic Regression": LogisticRegression(max_iter=500),
|
| 145 |
"KNN": KNeighborsClassifier(),
|
|
@@ -150,6 +121,7 @@ elif page == "Train & Select Model":
|
|
| 150 |
preds = model.predict(X_test)
|
| 151 |
acc = accuracy_score(y_test, preds)
|
| 152 |
results[name] = acc
|
|
|
|
| 153 |
else:
|
| 154 |
models = {
|
| 155 |
"Linear Regression": LinearRegression(),
|
|
@@ -160,20 +132,18 @@ elif page == "Train & Select Model":
|
|
| 160 |
preds = model.predict(X_test)
|
| 161 |
score = r2_score(y_test, preds)
|
| 162 |
results[name] = score
|
|
|
|
| 163 |
|
| 164 |
-
st.subheader("Model
|
| 165 |
-
for
|
| 166 |
-
st.write(f"{
|
| 167 |
|
| 168 |
-
|
| 169 |
if st.button("Save Selected Model"):
|
| 170 |
-
final_model = models[
|
| 171 |
-
|
| 172 |
-
with open(pkl_path, "wb") as f:
|
| 173 |
-
pickle.dump(final_model, f)
|
| 174 |
-
st.success(f"Model saved as {pkl_path}")
|
| 175 |
else:
|
| 176 |
-
st.warning("
|
| 177 |
|
| 178 |
# ========================
|
| 179 |
# Create App Page
|
|
@@ -181,61 +151,25 @@ elif page == "Train & Select Model":
|
|
| 181 |
elif page == "Create App":
|
| 182 |
st.title("Use Model for Prediction")
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
if processed_files:
|
| 187 |
-
selected_csv = st.selectbox("Select a processed CSV file", processed_files)
|
| 188 |
-
df = pd.read_csv(os.path.join(PROCESSED_DIR, selected_csv))
|
| 189 |
target_col = st.selectbox("Select target column", df.columns)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
else:
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
if os.path.exists(encoder_path):
|
| 208 |
-
with open(encoder_path, "rb") as f:
|
| 209 |
-
encoders[col] = pickle.load(f)
|
| 210 |
-
|
| 211 |
-
target_encoder = None
|
| 212 |
-
target_encoder_path = f"{ENCODERS_DIR}/{selected_csv}_{target_col}_encoder.pkl"
|
| 213 |
-
if os.path.exists(target_encoder_path):
|
| 214 |
-
with open(target_encoder_path, "rb") as f:
|
| 215 |
-
target_encoder = pickle.load(f)
|
| 216 |
-
|
| 217 |
-
user_input = {}
|
| 218 |
-
for col in X.columns:
|
| 219 |
-
if col in encoders:
|
| 220 |
-
options = encoders[col].classes_.tolist()
|
| 221 |
-
val = st.selectbox(f"Select {col}", options)
|
| 222 |
-
user_input[col] = encoders[col].transform([val])[0]
|
| 223 |
-
else:
|
| 224 |
-
if X[col].dtype in ["int64", "float64"]:
|
| 225 |
-
val = st.number_input(f"Enter {col}", value=float(X[col].mean()))
|
| 226 |
-
user_input[col] = val
|
| 227 |
-
else:
|
| 228 |
-
val = st.text_input(f"Enter {col}")
|
| 229 |
-
user_input[col] = val
|
| 230 |
-
|
| 231 |
-
if st.button("Predict"):
|
| 232 |
-
input_df = pd.DataFrame([user_input])
|
| 233 |
-
prediction = model.predict(input_df)
|
| 234 |
-
|
| 235 |
-
st.subheader("Prediction")
|
| 236 |
-
if problem_type == "classification" and target_encoder is not None:
|
| 237 |
-
st.text(target_encoder.inverse_transform(prediction)[0])
|
| 238 |
-
else:
|
| 239 |
-
st.text(prediction[0])
|
| 240 |
else:
|
| 241 |
-
st.warning("
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
| 3 |
import pickle
|
| 4 |
from sklearn.preprocessing import LabelEncoder
|
| 5 |
from sklearn.model_selection import train_test_split
|
|
|
|
| 8 |
from sklearn.tree import DecisionTreeClassifier
|
| 9 |
from sklearn.metrics import accuracy_score, r2_score
|
| 10 |
|
| 11 |
+
# Initialize session state variables
|
| 12 |
+
if "uploaded_file_name" not in st.session_state:
|
| 13 |
+
st.session_state.uploaded_file_name = None
|
| 14 |
+
if "df" not in st.session_state:
|
| 15 |
+
st.session_state.df = None
|
| 16 |
+
if "processed_df" not in st.session_state:
|
| 17 |
+
st.session_state.processed_df = None
|
| 18 |
+
if "encoders" not in st.session_state:
|
| 19 |
+
st.session_state.encoders = {}
|
| 20 |
+
if "models" not in st.session_state:
|
| 21 |
+
st.session_state.models = {}
|
| 22 |
+
if "final_model" not in st.session_state:
|
| 23 |
+
st.session_state.final_model = None
|
| 24 |
+
if "problem_type" not in st.session_state:
|
| 25 |
+
st.session_state.problem_type = None
|
| 26 |
+
if "target_encoder" not in st.session_state:
|
| 27 |
+
st.session_state.target_encoder = None
|
| 28 |
|
| 29 |
st.sidebar.title("Navigation")
|
| 30 |
page = st.sidebar.selectbox("Go to", ["Upload File", "Preprocess Data", "Train & Select Model", "Create App"])
|
|
|
|
| 37 |
uploaded_file = st.file_uploader("Upload a CSV or SQL file", type=["csv", "sql"])
|
| 38 |
|
| 39 |
if uploaded_file is not None:
|
| 40 |
+
st.session_state.uploaded_file_name = uploaded_file.name
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
if uploaded_file.name.endswith(".csv"):
|
| 42 |
+
st.session_state.df = pd.read_csv(uploaded_file)
|
| 43 |
+
st.dataframe(st.session_state.df)
|
| 44 |
elif uploaded_file.name.endswith(".sql"):
|
| 45 |
+
sql_content = uploaded_file.read().decode("utf-8")
|
|
|
|
| 46 |
st.text_area("SQL Content", sql_content, height=300)
|
| 47 |
+
st.success("File loaded into memory!")
|
| 48 |
|
| 49 |
# ========================
|
| 50 |
# Preprocess Data Page
|
| 51 |
# ========================
|
| 52 |
elif page == "Preprocess Data":
|
| 53 |
st.title("Preprocess Uploaded CSV")
|
| 54 |
+
if st.session_state.df is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
st.write("Current Data:")
|
| 56 |
st.dataframe(st.session_state.df)
|
| 57 |
|
|
|
|
| 64 |
if st.button("Drop Missing / Placeholder Values"):
|
| 65 |
st.session_state.df = st.session_state.df.replace(missing_placeholders, pd.NA)
|
| 66 |
st.session_state.df = st.session_state.df.dropna()
|
| 67 |
+
st.success("Missing values dropped!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
col_to_drop = st.multiselect("Select columns to drop", st.session_state.df.columns)
|
| 70 |
if st.button("Drop Selected Columns"):
|
|
|
|
| 72 |
st.success(f"Dropped columns: {col_to_drop}")
|
| 73 |
|
| 74 |
if st.button("Label Encode Object Columns"):
|
| 75 |
+
st.session_state.encoders = {}
|
| 76 |
for col in st.session_state.df.select_dtypes(include=['object']).columns:
|
| 77 |
le = LabelEncoder()
|
| 78 |
st.session_state.df[col] = le.fit_transform(st.session_state.df[col].astype(str))
|
| 79 |
+
st.session_state.encoders[col] = le
|
| 80 |
+
st.success("Object columns label-encoded!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
if st.button("Save Preprocessed Data"):
|
| 83 |
+
st.session_state.processed_df = st.session_state.df.copy()
|
| 84 |
+
st.success("Preprocessed data saved in memory!")
|
|
|
|
| 85 |
else:
|
| 86 |
+
st.warning("Please upload a CSV first.")
|
| 87 |
|
| 88 |
# ========================
|
| 89 |
# Train & Select Model Page
|
|
|
|
| 91 |
elif page == "Train & Select Model":
|
| 92 |
st.title("Train Models and Select the Best One")
|
| 93 |
|
| 94 |
+
if st.session_state.processed_df is not None:
|
| 95 |
+
df = st.session_state.processed_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
target_col = st.selectbox("Select target column", df.columns)
|
|
|
|
| 97 |
|
| 98 |
if target_col:
|
| 99 |
X = df.drop(columns=[target_col])
|
| 100 |
y = df[target_col]
|
| 101 |
|
| 102 |
if y.dtype == "object" or len(y.unique()) <= 20:
|
| 103 |
+
st.session_state.problem_type = "classification"
|
| 104 |
else:
|
| 105 |
+
st.session_state.problem_type = "regression"
|
| 106 |
|
| 107 |
+
test_size = st.slider("Test size (%)", 20, 50, 30, step=5)
|
| 108 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size/100, random_state=42)
|
|
|
|
|
|
|
| 109 |
|
| 110 |
results = {}
|
| 111 |
+
st.session_state.models = {}
|
| 112 |
|
| 113 |
+
if st.session_state.problem_type == "classification":
|
| 114 |
models = {
|
| 115 |
"Logistic Regression": LogisticRegression(max_iter=500),
|
| 116 |
"KNN": KNeighborsClassifier(),
|
|
|
|
| 121 |
preds = model.predict(X_test)
|
| 122 |
acc = accuracy_score(y_test, preds)
|
| 123 |
results[name] = acc
|
| 124 |
+
st.session_state.models[name] = model
|
| 125 |
else:
|
| 126 |
models = {
|
| 127 |
"Linear Regression": LinearRegression(),
|
|
|
|
| 132 |
preds = model.predict(X_test)
|
| 133 |
score = r2_score(y_test, preds)
|
| 134 |
results[name] = score
|
| 135 |
+
st.session_state.models[name] = model
|
| 136 |
|
| 137 |
+
st.subheader("Model Scores")
|
| 138 |
+
for name, score in results.items():
|
| 139 |
+
st.write(f"{name}: {score:.4f}")
|
| 140 |
|
| 141 |
+
selected_model = st.selectbox("Select model to save", list(results.keys()))
|
| 142 |
if st.button("Save Selected Model"):
|
| 143 |
+
st.session_state.final_model = st.session_state.models[selected_model]
|
| 144 |
+
st.success("Model saved in memory!")
|
|
|
|
|
|
|
|
|
|
| 145 |
else:
|
| 146 |
+
st.warning("Please preprocess a file first.")
|
| 147 |
|
| 148 |
# ========================
|
| 149 |
# Create App Page
|
|
|
|
| 151 |
elif page == "Create App":
|
| 152 |
st.title("Use Model for Prediction")
|
| 153 |
|
| 154 |
+
if st.session_state.final_model is not None and st.session_state.processed_df is not None:
|
| 155 |
+
df = st.session_state.processed_df
|
|
|
|
|
|
|
|
|
|
| 156 |
target_col = st.selectbox("Select target column", df.columns)
|
| 157 |
+
X = df.drop(columns=[target_col])
|
| 158 |
+
|
| 159 |
+
user_input = {}
|
| 160 |
+
for col in X.columns:
|
| 161 |
+
if col in st.session_state.encoders:
|
| 162 |
+
options = st.session_state.encoders[col].classes_.tolist()
|
| 163 |
+
val = st.selectbox(f"Select {col}", options)
|
| 164 |
+
user_input[col] = st.session_state.encoders[col].transform([val])[0]
|
| 165 |
else:
|
| 166 |
+
val = st.number_input(f"Enter {col}", value=float(X[col].mean()))
|
| 167 |
+
user_input[col] = val
|
| 168 |
+
|
| 169 |
+
if st.button("Predict"):
|
| 170 |
+
input_df = pd.DataFrame([user_input])
|
| 171 |
+
prediction = st.session_state.final_model.predict(input_df)
|
| 172 |
+
st.subheader("Prediction")
|
| 173 |
+
st.write(prediction[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
else:
|
| 175 |
+
st.warning("Please train and save a model first.")
|