DasariHarshitha commited on
Commit
e57d7ca
ยท
verified ยท
1 Parent(s): c83685f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -178
app.py CHANGED
@@ -1,178 +1,169 @@
1
- import streamlit as st
2
- import pickle
3
- import numpy as np
4
- import pandas as pd
5
- import matplotlib.pyplot as plt
6
- import seaborn as sns
7
-
8
- # ----------- Page Configuration ------------
9
- st.set_page_config("Sleep State Detection", layout="wide")
10
- st.title(" Sleep State Detection App")
11
-
12
- # ----------- Navigation Sidebar ------------
13
- page = st.sidebar.radio("๐Ÿ“ Navigation", ["Overview", "EDA", "Predict"])
14
-
15
- # ----------- Load Data & Model ------------
16
- @st.cache_data
17
- def load_data(filepath):
18
- return pd.read_csv(filepath)
19
-
20
- @st.cache_data
21
- def load_model(filepath):
22
- with open(filepath, "rb") as f:
23
- return pickle.load(f)
24
-
25
- # ----------- Histogram Plot Function ------------
26
- def plot_histogram(df, column, color):
27
- fig, ax = plt.subplots()
28
- sns.histplot(df[column], bins=30, kde=True, color=color, ax=ax)
29
- ax.set_title(f"Distribution of {column}")
30
- st.pyplot(fig, use_container_width=True)
31
- plt.close()
32
-
33
- # ----------- Overview Page ------------
34
- if page == "Overview":
35
- st.header(" Project Overview")
36
- st.markdown("This app detects **sleep onset** and **wake-up states** using `anglez` and `enmo` values from a wearable sensor.")
37
-
38
- with st.expander(" Problem Statement"):
39
- st.markdown("""
40
- - Detect sleep and wake-up periods using wearable sensor data.
41
- - Sleep is estimated from low-movement patterns.
42
- """)
43
-
44
- with st.expander(" Objective"):
45
- st.markdown("""
46
- - Classify sleep vs wake states
47
- - Build an ML model that generalizes to real users
48
- """)
49
-
50
- with st.expander(" Constraints"):
51
- st.markdown("""
52
- - Missing or noisy data
53
- - Ensure low false alarms
54
- - Simple, real-time capable models
55
- """)
56
-
57
- # ----------- EDA Page ------------
58
- elif page == "EDA":
59
- st.header(" Exploratory Data Analysis")
60
- df = load_data("cleaned_sleep_data.csv")
61
-
62
- # ---- Multi-select Filter Sleep/Wake ----
63
- st.markdown("### ๐Ÿ”Ž Filter by Sleep State")
64
- state_options = st.multiselect("Select sleep states to display", ["Sleep", "Wake-Up"], default=["Sleep", "Wake-Up"])
65
-
66
- if state_options:
67
- filter_map = {"Sleep": 1, "Wake-Up": 0}
68
- selected_values = [filter_map[opt] for opt in state_options]
69
- df = df[df["sleep"].isin(selected_values)]
70
-
71
- # ---- Histograms ----
72
- col1, col2 = st.columns(2)
73
- with col1:
74
- st.subheader(" Anglez")
75
- plot_histogram(df, "anglez", "#74b9ff")
76
- st.markdown("- Distribution typical of rest posture")
77
-
78
- with col2:
79
- st.subheader(" ENMO")
80
- plot_histogram(df, "enmo", "#81ecec")
81
- st.markdown("- ENMO reflects movement intensity")
82
-
83
- # ---- Pairplot ----
84
- st.subheader(" Feature Relationships")
85
- with st.spinner("Creating pairplot..."):
86
- pairplot_fig = sns.pairplot(df, vars=['anglez', 'enmo'], hue='sleep', palette='coolwarm')
87
- st.pyplot(pairplot_fig.fig, use_container_width=True)
88
- plt.close()
89
-
90
- # ---- Boxplots ----
91
- st.subheader(" Boxplots")
92
- fig, axs = plt.subplots(1, 2, figsize=(12, 5))
93
- sns.boxplot(y=df["anglez"], ax=axs[0], color='#74b9ff')
94
- axs[0].set_title("Boxplot: Anglez")
95
- sns.boxplot(y=df["enmo"], ax=axs[1], color='#81ecec')
96
- axs[1].set_title("Boxplot: ENMO")
97
- st.pyplot(fig, use_container_width=True)
98
- plt.close()
99
-
100
- # ---- Correlation ----
101
- st.subheader(" Correlation Heatmap")
102
- fig, ax = plt.subplots()
103
- sns.heatmap(df[["anglez", "enmo"]].corr(), annot=True, cmap="coolwarm", ax=ax)
104
- st.pyplot(fig, use_container_width=True)
105
- plt.close()
106
-
107
- # ----------- Predict Page ------------
108
- elif page == "Predict":
109
- st.header(" Sleep Prediction")
110
- model = load_model("new_sleep_model.pkl")
111
-
112
- # ---- Sleep/Wake Filter Dropdown
113
- st.markdown("### Select Sample Type")
114
- state_choice = st.selectbox("Choose Sample Type", ["Custom Input", "Sleep Sample", "Wake-Up Sample"])
115
-
116
- # ---- Default Values Based on Choice
117
- if state_choice == "Sleep Sample":
118
- default_anglez = -45.0
119
- default_enmo = 0.01
120
- elif state_choice == "Wake-Up Sample":
121
- default_anglez = 20.0
122
- default_enmo = 0.2
123
- else:
124
- default_anglez = 0.0
125
- default_enmo = 0.0
126
-
127
- # ---- Input Sliders
128
- col1, col2 = st.columns(2)
129
- with col1:
130
- anglez = st.slider(" Anglez (-180ยฐ to 180ยฐ)", -180.0, 180.0, default_anglez)
131
- with col2:
132
- enmo = st.slider(" ENMO (0.0 to 1.0)", 0.0, 1.0, default_enmo)
133
-
134
- # ---- Prediction
135
- if st.button(" Predict Sleep State"):
136
- input_vector = np.array([[anglez, enmo]])
137
- prediction = model.predict(input_vector)[0]
138
-
139
- if hasattr(model, "predict_proba"):
140
- proba = model.predict_proba(input_vector)[0]
141
- confidence = round(np.max(proba) * 100, 2)
142
- st.metric(" Model Confidence", f"{confidence}%")
143
-
144
- labels = {
145
- 0: (" Wake-Up", "You're likely **awake** โ€” motion and posture detected."),
146
- 1: (" Sleep Onset", "Low motion detected โ€” you may be **falling asleep**.")
147
- }
148
-
149
- label, message = labels.get(prediction, ("โ“ Unknown", "โš ๏ธ No clear state detected."))
150
- st.success(f"** Predicted State:** {label}")
151
- st.info(message)
152
-
153
- # Display image based on prediction
154
- if prediction == 1:
155
- st.image(
156
- "https://huggingface.co/spaces/Saidee156/AI_SLEEP_DETECTION/resolve/main/th%20(1).jpeg",
157
- use_container_width=True,
158
- )
159
- st.markdown("""
160
- ### Personalized Sleep Tips
161
- **Tips to Fall Asleep Faster**
162
- - Avoid screens 30 mins before bed
163
- - Keep the room cool and dark
164
- - Try deep breathing or meditation
165
- - Stick to a regular sleep schedule
166
- """)
167
- else:
168
- st.image(
169
- "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",
170
- use_container_width=True,
171
- )
172
- st.markdown("""
173
- ### Tips to Wake Up Refreshed
174
- - Get morning sunlight exposure
175
- - Move or stretch your body
176
- - Eat a light, energizing breakfast
177
- - Cold water splash or shower helps
178
- """)
 
1
+ import streamlit as st
2
+ import pickle
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import seaborn as sns
7
+
8
+ # ----------- Page Configuration ------------
9
+ st.set_page_config("Smart Sleep Monitor", layout="wide")
10
+ st.title(" ๐ŸŒš Smart Sleep Monitoring System")
11
+
12
+ # ----------- Navigation Sidebar ------------
13
+ page = st.sidebar.radio("๐Ÿ“ Navigate", ["Overview", "EDA", "Predict"])
14
+
15
+ # ----------- Load Data & Model ------------
16
+ @st.cache_data
17
+ def load_data(filepath):
18
+ return pd.read_csv(filepath)
19
+
20
+ @st.cache_data
21
+ def load_model(filepath):
22
+ with open(filepath, "rb") as f:
23
+ return pickle.load(f)
24
+
25
+ # ----------- Histogram Plot Function ------------
26
+ def plot_histogram(df, column, color):
27
+ fig, ax = plt.subplots()
28
+ sns.histplot(df[column], bins=30, kde=True, color=color, ax=ax)
29
+ ax.set_title(f"Distribution of {column}")
30
+ st.pyplot(fig, use_container_width=True)
31
+ plt.close()
32
+
33
+ # ----------- Overview Page ------------
34
+ if page == "Overview":
35
+ st.header(" ๐Ÿ”Ž Project Overview")
36
+ st.markdown("This application predicts **sleep** and **wake** states using data from wearable sensors, focusing on `anglez` and `enmo` values to monitor body motion and position.")
37
+
38
+ with st.expander(" ๐Ÿ“„ Problem Statement"):
39
+ st.markdown("""
40
+ - Increasing mental health issues in fast-paced environments are linked to poor sleep quality.
41
+ - This system helps in early identification of irregular sleep patterns to support healthier lifestyles.
42
+ """)
43
+
44
+ with st.expander(" ๐Ÿ”ฎ Objective"):
45
+ st.markdown("""
46
+ - Accurately classify sleep vs wake states using sensor inputs
47
+ - Provide doctors and users with actionable insights into sleep behavior
48
+ - Develop lightweight, real-time deployable models
49
+ """)
50
+
51
+ with st.expander(" โš ๏ธ Constraints"):
52
+ st.markdown("""
53
+ - Noisy or missing data from wearables
54
+ - Balancing sensitivity with low false-positive rate
55
+ - Ensuring usability across diverse users and environments
56
+ """)
57
+
58
+ # ----------- EDA Page ------------
59
+ elif page == "EDA":
60
+ st.header(" ๐Ÿ” Exploratory Data Analysis")
61
+ df = load_data("cleaned_sleep_data.csv")
62
+
63
+ st.markdown("### ๐Ÿ” Filter by Sleep State")
64
+ state_options = st.multiselect("Select sleep states to display", ["Sleep", "Wake-Up"], default=["Sleep", "Wake-Up"])
65
+
66
+ if state_options:
67
+ filter_map = {"Sleep": 1, "Wake-Up": 0}
68
+ selected_values = [filter_map[opt] for opt in state_options]
69
+ df = df[df["sleep"].isin(selected_values)]
70
+
71
+ col1, col2 = st.columns(2)
72
+ with col1:
73
+ st.subheader(" Anglez")
74
+ plot_histogram(df, "anglez", "#6c5ce7")
75
+ st.markdown("- Postural behavior during rest")
76
+
77
+ with col2:
78
+ st.subheader(" ENMO")
79
+ plot_histogram(df, "enmo", "#00cec9")
80
+ st.markdown("- Captures motion intensity")
81
+
82
+ st.subheader(" Feature Relationships")
83
+ with st.spinner("Creating pairplot..."):
84
+ pairplot_fig = sns.pairplot(df, vars=['anglez', 'enmo'], hue='sleep', palette='Set2')
85
+ st.pyplot(pairplot_fig.fig, use_container_width=True)
86
+ plt.close()
87
+
88
+ st.subheader(" Boxplots")
89
+ fig, axs = plt.subplots(1, 2, figsize=(12, 5))
90
+ sns.boxplot(y=df["anglez"], ax=axs[0], color='#6c5ce7')
91
+ axs[0].set_title("Boxplot: Anglez")
92
+ sns.boxplot(y=df["enmo"], ax=axs[1], color='#00cec9')
93
+ axs[1].set_title("Boxplot: ENMO")
94
+ st.pyplot(fig, use_container_width=True)
95
+ plt.close()
96
+
97
+ st.subheader(" Correlation Heatmap")
98
+ fig, ax = plt.subplots()
99
+ sns.heatmap(df[["anglez", "enmo"]].corr(), annot=True, cmap="Purples", ax=ax)
100
+ st.pyplot(fig, use_container_width=True)
101
+ plt.close()
102
+
103
+ # ----------- Predict Page ------------
104
+ elif page == "Predict":
105
+ st.header(" ๐Ÿค– Sleep Prediction")
106
+ model = load_model("new_sleep_model.pkl")
107
+
108
+ st.markdown("### Select Sample Type")
109
+ state_choice = st.selectbox("Choose Sample Type", ["Custom Input", "Sleep Sample", "Wake-Up Sample"])
110
+
111
+ if state_choice == "Sleep Sample":
112
+ default_anglez = -45.0
113
+ default_enmo = 0.01
114
+ elif state_choice == "Wake-Up Sample":
115
+ default_anglez = 20.0
116
+ default_enmo = 0.2
117
+ else:
118
+ default_anglez = 0.0
119
+ default_enmo = 0.0
120
+
121
+ col1, col2 = st.columns(2)
122
+ with col1:
123
+ anglez = st.slider(" Anglez (-180ยฐ to 180ยฐ)", -180.0, 180.0, default_anglez)
124
+ with col2:
125
+ enmo = st.slider(" ENMO (0.0 to 1.0)", 0.0, 1.0, default_enmo)
126
+
127
+ if st.button(" ๐Ÿ”Ž Predict Sleep State"):
128
+ input_vector = np.array([[anglez, enmo]])
129
+ prediction = model.predict(input_vector)[0]
130
+
131
+ if hasattr(model, "predict_proba"):
132
+ proba = model.predict_proba(input_vector)[0]
133
+ confidence = round(np.max(proba) * 100, 2)
134
+ st.metric(" Model Confidence", f"{confidence}%")
135
+
136
+ labels = {
137
+ 0: (" Wake-Up", "You're likely **awake** โ€” motion and posture detected."),
138
+ 1: (" Sleep Onset", "Low motion detected โ€” you may be **falling asleep**.")
139
+ }
140
+
141
+ label, message = labels.get(prediction, ("โ“ Unknown", "โš ๏ธ No clear state detected."))
142
+ st.success(f"** Predicted State:** {label}")
143
+ st.info(message)
144
+
145
+ if prediction == 1:
146
+ st.image(
147
+ "https://huggingface.co/spaces/DasariHarshitha/Sleep_Detection_App/resolve/main/th%20(1).jpeg",
148
+ use_container_width=True,
149
+ )
150
+ st.markdown("""
151
+ ### ๐Ÿ›๏ธ Personalized Sleep Tips
152
+ **Tips to Fall Asleep Faster**
153
+ - Avoid screens 30 mins before bed
154
+ - Keep the room cool and dark
155
+ - Try deep breathing or meditation
156
+ - Stick to a regular sleep schedule
157
+ """)
158
+ else:
159
+ st.image(
160
+ "https://huggingface.co/spaces/DasariHarshitha/Sleep_Detection_App/resolve/main/cute-little-boy-wake-up-in-morning-stretching-hands-on-bed-in-bedroom-vector.jpg",
161
+ use_container_width=True,
162
+ )
163
+ st.markdown("""
164
+ ### ๐ŸŒž Tips to Wake Up Refreshed
165
+ - Get morning sunlight exposure
166
+ - Move or stretch your body
167
+ - Eat a light, energizing breakfast
168
+ - Cold water splash or shower helps
169
+ """)