Mpavan45 commited on
Commit
559c176
Β·
verified Β·
1 Parent(s): c2781c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -59
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
- # βœ… This must be the first Streamlit command
10
  st.set_page_config(page_title="Interactive Sleep Predictor", layout="wide")
11
 
12
- # UI starts here
13
  st.title("⏰ Interactive Sleep & Health Predictor")
14
- st.markdown("Track your sleep & get personalized health tips πŸ’€πŸ’ͺ")
15
 
16
- # Load your trained model
17
  @st.cache_resource
18
  def load_model():
19
- return joblib.load("log_reg_model.pkl") # Update with your actual model path
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) # or "gpt-4", based on your requirement
26
 
27
- # Health tips prompt template
28
  prompt_template = """
29
- You are a health advisor. Based on the sleep duration (in hours), give personalized sleep and health tips.
30
- Sleep duration: {sleep_duration} hours.
31
- Health Tip:
 
 
 
 
 
 
 
 
 
 
32
  """
33
 
34
- # LangChain chain for generating health tips
35
- def generate_health_tips(sleep_duration):
36
- prompt = PromptTemplate(input_variables=["sleep_duration"], template=prompt_template)
 
 
 
37
  chain = LLMChain(llm=llm, prompt=prompt)
38
- return chain.run({"sleep_duration": sleep_duration})
 
 
 
 
39
 
40
- # User input form
41
  with st.form("predictor_form"):
42
- step = st.number_input("🚢 **Step Count** (Enter your current steps)", min_value=0, step=10, label_visibility="visible")
43
- hour = st.slider("⏰ **Hour of the Day** (24h format)", min_value=0, max_value=23, label_visibility="visible")
44
- submit_button = st.form_submit_button("Predict Sleep/Wake State")
45
 
46
- # When the user clicks the predict button
47
- if submit_button:
48
- # Prepare input for the model
49
- input_df = pd.DataFrame([[step, hour]], columns=["step", "hour"])
 
 
 
50
 
 
 
51
  # Predict sleep state (0 = awake, 1 = asleep)
 
52
  prediction = model.predict(input_df)[0]
 
 
 
 
 
 
 
 
 
53
 
54
- # Calculate sleep duration (use 8 hours if asleep, 0 if awake)
55
- sleep_duration = 8 if prediction == 1 else 0
56
 
57
  # Display prediction
58
- if prediction == 1:
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
- # # Footer for the app
90
- # st.markdown("---")
91
- # st.markdown("""
92
- # Built with ❀️ by **Pavan Manikanta Muthyala** | **Interactive Sleep Predictor** using LangChain and GenAI
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)