Spaces:
Sleeping
Sleeping
File size: 6,798 Bytes
e57d7ca 4b79ca6 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 4b79ca6 e57d7ca 914b4b8 e57d7ca 4b79ca6 914b4b8 e57d7ca 4b79ca6 e57d7ca 4b79ca6 1206cdb 4b79ca6 e57d7ca 4b79ca6 1206cdb 4b79ca6 8856700 4b79ca6 e57d7ca 4b79ca6 e57d7ca 1206cdb 4b79ca6 e57d7ca 4b79ca6 e57d7ca 4b79ca6 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 e57d7ca 914b4b8 |
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 |
import streamlit as st
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# ----------- Page Configuration ------------
st.set_page_config("Sleep State Detection", layout="wide")
st.title(" Sleep State Detection App")
# ----------- Navigation Sidebar ------------
page = st.sidebar.radio("π Navigation", ["Overview", "EDA", "Predict"])
# ----------- Load Data & Model ------------
@st.cache_data
def load_data(filepath):
return pd.read_csv(filepath)
@st.cache_data
def load_model(filepath):
with open(filepath, "rb") as f:
return pickle.load(f)
# ----------- Histogram Plot Function ------------
def plot_histogram(df, column, color):
fig, ax = plt.subplots()
sns.histplot(df[column], bins=30, kde=True, color=color, ax=ax)
ax.set_title(f"Distribution of {column}")
st.pyplot(fig, use_container_width=True)
plt.close()
# ----------- Overview Page ------------
if page == "Overview":
st.header(" Project Overview")
st.markdown("This app detects **sleep onset** and **wake-up states** using `anglez` and `enmo` values from a wearable sensor.")
with st.expander(" Problem Statement"):
st.markdown("""
- Detect sleep and wake-up periods using wearable sensor data.
- Sleep is estimated from low-movement patterns.
""")
with st.expander(" Objective"):
st.markdown("""
- Classify sleep vs wake states
- Build an ML model that generalizes to real users
""")
with st.expander(" Constraints"):
st.markdown("""
- Missing or noisy data
- Ensure low false alarms
- Simple, real-time capable models
""")
# ----------- EDA Page ------------
elif page == "EDA":
st.header(" Exploratory Data Analysis")
df = load_data("cleaned_sleep_data.csv")
# ---- Multi-select Filter Sleep/Wake ----
st.markdown("### π Filter by Sleep State")
state_options = st.multiselect("Select sleep states to display", ["Sleep", "Wake-Up"], default=["Sleep", "Wake-Up"])
if state_options:
filter_map = {"Sleep": 1, "Wake-Up": 0}
selected_values = [filter_map[opt] for opt in state_options]
df = df[df["sleep"].isin(selected_values)]
# ---- Histograms ----
col1, col2 = st.columns(2)
with col1:
st.subheader(" Anglez")
plot_histogram(df, "anglez", "#81ecec")
st.markdown("- Distribution typical of rest posture")
with col2:
st.subheader(" ENMO")
plot_histogram(df, "enmo", "#a29bfe")
st.markdown("- ENMO reflects movement intensity")
# fig, ax = plt.subplots(figsize=(12, 4))
# ax.plot(df["timestamp"], df["anglez"], color="#1abc9c", label="Anglez")
# ax.plot(df["timestamp"], df["enmo"], color="#c56cf0", label="ENMO")
# ax.fill_between(df["timestamp"], 0, 1, where=df["sleep"]==1,
# color="#ffeaa7", alpha=0.3, transform=ax.get_xaxis_transform())
# ax.set_title("Sensor Data over Time with Sleep Periods")
# ax.legend()
# st.pyplot(fig)
# ---- Pairplot ----
st.subheader(" Feature Relationships")
with st.spinner("Creating pairplot..."):
pairplot_fig = sns.pairplot(df, vars=['anglez', 'enmo'], hue='sleep', palette='coolwarm')
st.pyplot(pairplot_fig.fig, use_container_width=True)
plt.close()
# ---- Boxplots ----
st.subheader(" Boxplots")
fig, axs = plt.subplots(1, 2, figsize=(12, 5))
sns.boxplot(y=df["anglez"], ax=axs[0], color='#ff7f0e')
axs[0].set_title("Boxplot: Anglez")
sns.boxplot(y=df["enmo"], ax=axs[1], color='#81ecec')
axs[1].set_title("Boxplot: ENMO")
st.pyplot(fig, use_container_width=True)
plt.close()
# ---- Correlation ----
st.subheader(" Correlation Heatmap")
fig, ax = plt.subplots()
sns.heatmap(df[["anglez", "enmo"]].corr(), annot=True, cmap="coolwarm", ax=ax)
st.pyplot(fig, use_container_width=True)
plt.close()
# ----------- Predict Page ------------
elif page == "Predict":
st.header(" Sleep Prediction")
model = load_model("new_sleep_model.pkl")
# ---- Sleep/Wake Filter Dropdown
st.markdown("### Select Sample Type")
state_choice = st.selectbox("Choose Sample Type", ["Custom Input", "Sleep Sample", "Wake-Up Sample"])
# ---- Default Values Based on Choice
if state_choice == "Sleep Sample":
default_anglez = -45.0
default_enmo = 0.01
elif state_choice == "Wake-Up Sample":
default_anglez = 20.0
default_enmo = 0.2
else:
default_anglez = 0.0
default_enmo = 0.0
# ---- Input Sliders
col1, col2 = st.columns(2)
with col1:
anglez = st.slider(" Anglez (-180Β° to 180Β°)", -180.0, 180.0, default_anglez)
with col2:
enmo = st.slider(" ENMO (0.0 to 1.0)", 0.0, 1.0, default_enmo)
# ---- Prediction
if st.button(" Predict Sleep State"):
input_vector = np.array([[anglez, enmo]])
prediction = model.predict(input_vector)[0]
if hasattr(model, "predict_proba"):
proba = model.predict_proba(input_vector)[0]
confidence = round(np.max(proba) * 100, 2)
st.metric(" Model Confidence", f"{confidence}%")
labels = {
0: (" Wake-Up", "You're likely **awake** β motion and posture detected."),
1: (" Sleep Onset", "Low motion detected β you may be **falling asleep**.")
}
label, message = labels.get(prediction, ("β Unknown", "β οΈ No clear state detected."))
st.success(f"** Predicted State:** {label}")
st.info(message)
# Display image based on prediction
if prediction == 1:
st.image(
"https://huggingface.co/spaces/Saidee156/AI_SLEEP_DETECTION/resolve/main/th%20(1).jpeg",
use_container_width=True,
)
st.markdown("""
### Personalized Sleep Tips
**Tips to Fall Asleep Faster**
- Avoid screens 30 mins before bed
- Keep the room cool and dark
- Try deep breathing or meditation
- Stick to a regular sleep schedule
""")
else:
st.image(
"https://huggingface.co/spaces/Saidee156/AI_SLEEP_DETECTION/resolve/main/cute-little-boy-wake-up-in-morning-stretching-hands-on-bed-in-bedroom-vector.jpg",
use_container_width=True,
)
st.markdown("""
### Tips to Wake Up Refreshed
- Get morning sunlight exposure
- Move or stretch your body
- Eat a light, energizing breakfast
- Cold water splash or shower helps
""")
|