Update app.py
Browse files
app.py
CHANGED
|
@@ -2,93 +2,101 @@ import streamlit as st
|
|
| 2 |
import pandas as pd
|
| 3 |
import joblib
|
| 4 |
import matplotlib.pyplot as plt
|
|
|
|
| 5 |
from langchain_google_genai import GoogleGenerativeAI
|
| 6 |
from langchain.prompts import PromptTemplate
|
| 7 |
from langchain.chains import LLMChain
|
| 8 |
|
| 9 |
-
# β
|
| 10 |
st.set_page_config(page_title="Interactive Sleep Predictor", layout="wide")
|
| 11 |
|
| 12 |
-
# UI
|
| 13 |
st.title("β° Interactive Sleep & Health Predictor")
|
| 14 |
-
st.markdown("Track your sleep & get personalized health
|
| 15 |
|
| 16 |
-
# Load
|
| 17 |
@st.cache_resource
|
| 18 |
def load_model():
|
| 19 |
-
return joblib.load("log_reg_model.pkl") # Update
|
| 20 |
|
| 21 |
model = load_model()
|
| 22 |
|
| 23 |
# LangChain Setup
|
| 24 |
api_key = st.secrets.get('genai_key')
|
| 25 |
-
llm= GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
|
| 26 |
|
| 27 |
-
#
|
| 28 |
prompt_template = """
|
| 29 |
-
You are a health
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
"""
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
def
|
| 36 |
-
prompt = PromptTemplate(
|
|
|
|
|
|
|
|
|
|
| 37 |
chain = LLMChain(llm=llm, prompt=prompt)
|
| 38 |
-
return chain.run({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
# User
|
| 41 |
with st.form("predictor_form"):
|
| 42 |
-
step = st.number_input("πΆ
|
| 43 |
-
hour = st.slider("β°
|
| 44 |
-
submit_button = st.form_submit_button("Predict Sleep/Wake State")
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
|
|
|
|
|
|
|
| 51 |
# Predict sleep state (0 = awake, 1 = asleep)
|
|
|
|
| 52 |
prediction = model.predict(input_df)[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
sleep_duration = 8 if prediction == 1 else 0
|
| 56 |
|
| 57 |
# Display prediction
|
| 58 |
-
|
| 59 |
-
st.success(f"π΄ **You are likely asleep**. You might sleep for **{sleep_duration} hours**.")
|
| 60 |
-
else:
|
| 61 |
-
st.info(f"π **You are likely awake**. Stay active and hydrated today!")
|
| 62 |
-
|
| 63 |
-
# Generate and display health tips based on sleep duration
|
| 64 |
-
health_tips = generate_health_tips(sleep_duration)
|
| 65 |
-
st.markdown("### Health Tips:")
|
| 66 |
-
st.write(f"**{health_tips}**")
|
| 67 |
-
|
| 68 |
-
# Exercise Tips based on the user's state (asleep vs awake)
|
| 69 |
-
if prediction == 0: # Awake
|
| 70 |
-
exercise_tips = """
|
| 71 |
-
- πββοΈ **Go for a walk or jog**: 20-30 minutes of aerobic exercise can boost your energy.
|
| 72 |
-
- οΏ½οΏ½οΏ½ββοΈ **Stretch or do yoga**: Focus on flexibility and relaxation to stay active.
|
| 73 |
-
- ποΈββοΈ **Strength Training**: Include bodyweight exercises like squats and push-ups.
|
| 74 |
-
"""
|
| 75 |
-
else: # Asleep
|
| 76 |
-
exercise_tips = "Rest is the best exercise. Ensure you are getting quality sleep for good health."
|
| 77 |
-
|
| 78 |
-
st.markdown("### Exercise Suggestions:")
|
| 79 |
-
st.write(f"**{exercise_tips}**")
|
| 80 |
-
|
| 81 |
-
# Visual representation: Sleep Prediction Bar Chart
|
| 82 |
-
fig, ax = plt.subplots(figsize=(8, 4))
|
| 83 |
-
ax.barh(["Predicted Sleep"], sleep_duration, color="lightblue")
|
| 84 |
-
ax.set_xlim(0, 10) # Limit max sleep time
|
| 85 |
-
ax.set_xlabel("Hours of Sleep")
|
| 86 |
-
ax.set_title("Predicted Sleep Duration")
|
| 87 |
-
st.pyplot(fig)
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
# """)
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import joblib
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
from langchain_google_genai import GoogleGenerativeAI
|
| 7 |
from langchain.prompts import PromptTemplate
|
| 8 |
from langchain.chains import LLMChain
|
| 9 |
|
| 10 |
+
# β
Streamlit page config (must be first command)
|
| 11 |
st.set_page_config(page_title="Interactive Sleep Predictor", layout="wide")
|
| 12 |
|
| 13 |
+
# UI Title
|
| 14 |
st.title("β° Interactive Sleep & Health Predictor")
|
| 15 |
+
st.markdown("Track your sleep, activity & get personalized health + fitness advice with Gemini π§ πͺ")
|
| 16 |
|
| 17 |
+
# Load model
|
| 18 |
@st.cache_resource
|
| 19 |
def load_model():
|
| 20 |
+
return joblib.load("log_reg_model.pkl") # Update if your model path is different
|
| 21 |
|
| 22 |
model = load_model()
|
| 23 |
|
| 24 |
# LangChain Setup
|
| 25 |
api_key = st.secrets.get('genai_key')
|
| 26 |
+
llm = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
|
| 27 |
|
| 28 |
+
# LangChain Prompt Template
|
| 29 |
prompt_template = """
|
| 30 |
+
You are a certified health and fitness advisor.
|
| 31 |
+
|
| 32 |
+
A user has recorded:
|
| 33 |
+
- Sleep Duration: {sleep_duration} hours
|
| 34 |
+
- Step Count: {step_count} steps
|
| 35 |
+
- Current State: {state} (awake or asleep)
|
| 36 |
+
|
| 37 |
+
Based on these values:
|
| 38 |
+
1. Give a personalized health and wellness suggestion (max 5 lines).
|
| 39 |
+
2. Give specific exercise tips suitable for their state and activity level (step count).
|
| 40 |
+
3. Mention if their step count is low/average/high and whether they should increase activity.
|
| 41 |
+
|
| 42 |
+
Start with "π€ Summary for the User:" and then provide your insights.
|
| 43 |
"""
|
| 44 |
|
| 45 |
+
# Chain to generate Gemini suggestions
|
| 46 |
+
def generate_personalized_insights(sleep_duration, step_count, state):
|
| 47 |
+
prompt = PromptTemplate(
|
| 48 |
+
input_variables=["sleep_duration", "step_count", "state"],
|
| 49 |
+
template=prompt_template
|
| 50 |
+
)
|
| 51 |
chain = LLMChain(llm=llm, prompt=prompt)
|
| 52 |
+
return chain.run({
|
| 53 |
+
"sleep_duration": sleep_duration,
|
| 54 |
+
"step_count": step_count,
|
| 55 |
+
"state": state
|
| 56 |
+
})
|
| 57 |
|
| 58 |
+
# User form
|
| 59 |
with st.form("predictor_form"):
|
| 60 |
+
step = st.number_input("πΆ Step Count (today)", min_value=0, step=10)
|
| 61 |
+
hour = st.slider("β° Hour of the Day", min_value=0, max_value=23)
|
|
|
|
| 62 |
|
| 63 |
+
col1, col2 = st.columns(2)
|
| 64 |
+
with col1:
|
| 65 |
+
sleep_time = st.time_input("π Sleep Onset Time")
|
| 66 |
+
with col2:
|
| 67 |
+
wake_time = st.time_input("π Wake-Up Time")
|
| 68 |
+
|
| 69 |
+
submit_button = st.form_submit_button("Predict & Get Gemini Tips")
|
| 70 |
|
| 71 |
+
# On Submit
|
| 72 |
+
if submit_button:
|
| 73 |
# Predict sleep state (0 = awake, 1 = asleep)
|
| 74 |
+
input_df = pd.DataFrame([[step, hour]], columns=["step", "hour"])
|
| 75 |
prediction = model.predict(input_df)[0]
|
| 76 |
+
state = "asleep" if prediction == 1 else "awake"
|
| 77 |
+
emoji = "π΄" if state == "asleep" else "π"
|
| 78 |
+
|
| 79 |
+
# Sleep duration calculation
|
| 80 |
+
today = datetime.today()
|
| 81 |
+
sleep_dt = datetime.combine(today, sleep_time)
|
| 82 |
+
wake_dt = datetime.combine(today, wake_time)
|
| 83 |
+
if wake_dt < sleep_dt:
|
| 84 |
+
wake_dt += timedelta(days=1)
|
| 85 |
|
| 86 |
+
sleep_duration = round((wake_dt - sleep_dt).seconds / 3600, 2)
|
|
|
|
| 87 |
|
| 88 |
# Display prediction
|
| 89 |
+
st.success(f"{emoji} **You're likely {state}**. You've logged **{sleep_duration} hours** of sleep and taken **{step} steps** today.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# LangChain Gemini Suggestions
|
| 92 |
+
insights = generate_personalized_insights(sleep_duration, step, state)
|
| 93 |
+
st.markdown("### π§ Gemini-Generated Tips:")
|
| 94 |
+
st.markdown(insights)
|
|
|
|
| 95 |
|
| 96 |
+
# Sleep Visualization
|
| 97 |
+
fig, ax = plt.subplots(figsize=(8, 4))
|
| 98 |
+
ax.barh(["Your Sleep Duration"], sleep_duration, color="skyblue")
|
| 99 |
+
ax.set_xlim(0, 10)
|
| 100 |
+
ax.set_xlabel("Hours")
|
| 101 |
+
ax.set_title("Logged Sleep Duration")
|
| 102 |
+
st.pyplot(fig)
|