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