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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import datetime
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from typing import Dict, List, Tuple
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
import plotly.express as px
|
| 9 |
+
from dataclasses import dataclass, asdict
|
| 10 |
+
import google.generativeai as genai
|
| 11 |
+
|
| 12 |
+
# Data structure for health records
|
| 13 |
+
@dataclass
|
| 14 |
+
class HealthRecord:
|
| 15 |
+
date: str
|
| 16 |
+
morning_mood: int
|
| 17 |
+
morning_energy: int
|
| 18 |
+
morning_sleep_quality: int
|
| 19 |
+
afternoon_water_intake: int
|
| 20 |
+
afternoon_physical_activity: int
|
| 21 |
+
afternoon_stress_level: int
|
| 22 |
+
evening_meal_quality: int
|
| 23 |
+
evening_screen_time: int
|
| 24 |
+
evening_gratitude: int
|
| 25 |
+
daily_score: float
|
| 26 |
+
ai_recommendation: str
|
| 27 |
+
|
| 28 |
+
class AIDoctor:
|
| 29 |
+
def __init__(self):
|
| 30 |
+
self.data_file = "health_data.json"
|
| 31 |
+
self.setup_gemini()
|
| 32 |
+
self.load_data()
|
| 33 |
+
|
| 34 |
+
def setup_gemini(self):
|
| 35 |
+
"""Setup Google Gemini AI"""
|
| 36 |
+
# Get API key from environment variable or Hugging Face Secrets
|
| 37 |
+
api_key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
|
| 38 |
+
|
| 39 |
+
if api_key:
|
| 40 |
+
genai.configure(api_key=api_key)
|
| 41 |
+
self.model = genai.GenerativeModel('gemini-pro')
|
| 42 |
+
self.gemini_available = True
|
| 43 |
+
else:
|
| 44 |
+
self.gemini_available = False
|
| 45 |
+
print("β οΈ Gemini API key not found. Using fallback recommendations.")
|
| 46 |
+
|
| 47 |
+
def load_data(self):
|
| 48 |
+
"""Load existing health data"""
|
| 49 |
+
if os.path.exists(self.data_file):
|
| 50 |
+
try:
|
| 51 |
+
with open(self.data_file, 'r') as f:
|
| 52 |
+
data = json.load(f)
|
| 53 |
+
self.records = [HealthRecord(**record) for record in data]
|
| 54 |
+
except:
|
| 55 |
+
self.records = []
|
| 56 |
+
else:
|
| 57 |
+
self.records = []
|
| 58 |
+
|
| 59 |
+
def save_data(self):
|
| 60 |
+
"""Save health data to file"""
|
| 61 |
+
try:
|
| 62 |
+
with open(self.data_file, 'w') as f:
|
| 63 |
+
json.dump([asdict(record) for record in self.records], f, indent=2)
|
| 64 |
+
except:
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
def calculate_daily_score(self, morning_data: Dict, afternoon_data: Dict, evening_data: Dict) -> float:
|
| 68 |
+
"""Calculate daily health score (0-100)"""
|
| 69 |
+
# Morning score (30% weight)
|
| 70 |
+
morning_score = (
|
| 71 |
+
morning_data['mood'] * 0.4 +
|
| 72 |
+
morning_data['energy'] * 0.4 +
|
| 73 |
+
morning_data['sleep_quality'] * 0.2
|
| 74 |
+
) * 10
|
| 75 |
+
|
| 76 |
+
# Afternoon score (40% weight)
|
| 77 |
+
afternoon_score = (
|
| 78 |
+
min(morning_data['water_intake'] / 8, 1) * 40 + # 8 glasses target
|
| 79 |
+
min(afternoon_data['physical_activity'] / 60, 1) * 40 + # 60 min target
|
| 80 |
+
(10 - afternoon_data['stress_level']) * 2 # Lower stress is better
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Evening score (30% weight)
|
| 84 |
+
evening_score = (
|
| 85 |
+
evening_data['meal_quality'] * 8 +
|
| 86 |
+
max(0, (8 - evening_data['screen_time'])) * 2 + # Less than 8 hours
|
| 87 |
+
evening_data['gratitude'] * 10
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
# Weighted total
|
| 91 |
+
total_score = (morning_score * 0.3 + afternoon_score * 0.4 + evening_score * 0.3)
|
| 92 |
+
return min(100, max(0, total_score))
|
| 93 |
+
|
| 94 |
+
def generate_ai_recommendation(self, score: float, morning_data: Dict, afternoon_data: Dict, evening_data: Dict) -> str:
|
| 95 |
+
"""Generate AI doctor recommendations using Gemini"""
|
| 96 |
+
|
| 97 |
+
if self.gemini_available:
|
| 98 |
+
try:
|
| 99 |
+
# Create detailed health context for Gemini
|
| 100 |
+
health_context = f"""
|
| 101 |
+
You are an AI Health Doctor analyzing a patient's daily health data. Provide personalized, actionable health recommendations.
|
| 102 |
+
|
| 103 |
+
PATIENT DAILY HEALTH DATA:
|
| 104 |
+
- Overall Health Score: {score:.1f}/100
|
| 105 |
+
|
| 106 |
+
Morning Metrics:
|
| 107 |
+
- Mood: {morning_data['mood']}/10
|
| 108 |
+
- Energy Level: {morning_data['energy']}/10
|
| 109 |
+
- Sleep Quality: {morning_data['sleep_quality']}/10
|
| 110 |
+
|
| 111 |
+
Afternoon Metrics:
|
| 112 |
+
- Water Intake: {morning_data['water_intake']} glasses (target: 8)
|
| 113 |
+
- Physical Activity: {afternoon_data['physical_activity']} minutes (target: 60)
|
| 114 |
+
- Stress Level: {afternoon_data['stress_level']}/10 (lower is better)
|
| 115 |
+
|
| 116 |
+
Evening Metrics:
|
| 117 |
+
- Meal Quality: {evening_data['meal_quality']}/10
|
| 118 |
+
- Screen Time: {evening_data['screen_time']} hours
|
| 119 |
+
- Gratitude Practice: {evening_data['gratitude']}/10
|
| 120 |
+
|
| 121 |
+
INSTRUCTIONS:
|
| 122 |
+
1. Analyze the overall health pattern
|
| 123 |
+
2. Identify 2-3 key areas for improvement
|
| 124 |
+
3. Provide specific, actionable recommendations
|
| 125 |
+
4. Use encouraging, doctor-like tone
|
| 126 |
+
5. Include emojis for better engagement
|
| 127 |
+
6. Keep response under 300 words
|
| 128 |
+
7. Focus on the lowest-scoring metrics
|
| 129 |
+
|
| 130 |
+
Format: Start with overall assessment, then provide specific recommendations for improvement areas.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
# Get historical context if available
|
| 134 |
+
if len(self.records) >= 3:
|
| 135 |
+
recent_scores = [r.daily_score for r in self.records[-3:]]
|
| 136 |
+
trend = "improving" if recent_scores[-1] > recent_scores[0] else "declining" if recent_scores[-1] < recent_scores[0] else "stable"
|
| 137 |
+
health_context += f"\n\nRecent 3-day trend: {trend} (scores: {recent_scores})"
|
| 138 |
+
|
| 139 |
+
# Generate response with Gemini
|
| 140 |
+
response = self.model.generate_content(health_context)
|
| 141 |
+
return response.text
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
print(f"Gemini API error: {e}")
|
| 145 |
+
return self.fallback_recommendations(score, morning_data, afternoon_data, evening_data)
|
| 146 |
+
else:
|
| 147 |
+
return self.fallback_recommendations(score, morning_data, afternoon_data, evening_data)
|
| 148 |
+
|
| 149 |
+
def fallback_recommendations(self, score: float, morning_data: Dict, afternoon_data: Dict, evening_data: Dict) -> str:
|
| 150 |
+
"""Fallback recommendations when Gemini is not available"""
|
| 151 |
+
recommendations = []
|
| 152 |
+
|
| 153 |
+
# Score-based general advice
|
| 154 |
+
if score >= 85:
|
| 155 |
+
recommendations.append("π Excellent health habits! You're doing amazing!")
|
| 156 |
+
elif score >= 70:
|
| 157 |
+
recommendations.append("π Good health practices! Small improvements can make you even better.")
|
| 158 |
+
elif score >= 50:
|
| 159 |
+
recommendations.append("β οΈ Moderate health status. Focus on key areas for improvement.")
|
| 160 |
+
else:
|
| 161 |
+
recommendations.append("π¨ Your health needs attention. Let's work on fundamental habits.")
|
| 162 |
+
|
| 163 |
+
# Specific recommendations
|
| 164 |
+
if morning_data['sleep_quality'] < 6:
|
| 165 |
+
recommendations.append("π€ Sleep Quality: Aim for 7-9 hours of sleep. Create a bedtime routine.")
|
| 166 |
+
|
| 167 |
+
if morning_data['mood'] < 6:
|
| 168 |
+
recommendations.append("π Mood: Try 10 minutes of meditation or journaling in the morning.")
|
| 169 |
+
|
| 170 |
+
if morning_data['energy'] < 6:
|
| 171 |
+
recommendations.append("β‘ Energy: Consider a protein-rich breakfast and light morning exercise.")
|
| 172 |
+
|
| 173 |
+
if morning_data['water_intake'] < 6:
|
| 174 |
+
recommendations.append("π§ Hydration: Aim for 8 glasses of water daily. Set hourly reminders.")
|
| 175 |
+
|
| 176 |
+
if afternoon_data['physical_activity'] < 30:
|
| 177 |
+
recommendations.append("π Activity: Try to get at least 30 minutes of physical activity daily.")
|
| 178 |
+
|
| 179 |
+
if afternoon_data['stress_level'] > 7:
|
| 180 |
+
recommendations.append("π§ Stress: Practice deep breathing or take short breaks throughout the day.")
|
| 181 |
+
|
| 182 |
+
if evening_data['meal_quality'] < 6:
|
| 183 |
+
recommendations.append("π₯ Nutrition: Focus on whole foods, vegetables, and balanced meals.")
|
| 184 |
+
|
| 185 |
+
if evening_data['screen_time'] > 6:
|
| 186 |
+
recommendations.append("π± Screen Time: Reduce screen time before bed for better sleep quality.")
|
| 187 |
+
|
| 188 |
+
return " | ".join(recommendations)
|
| 189 |
+
|
| 190 |
+
def morning_checkin(self, mood: int, energy: int, sleep_quality: int, water_goal: int) -> str:
|
| 191 |
+
"""Process morning check-in"""
|
| 192 |
+
today = datetime.date.today().isoformat()
|
| 193 |
+
|
| 194 |
+
# Store morning data temporarily
|
| 195 |
+
self.temp_morning = {
|
| 196 |
+
'mood': mood,
|
| 197 |
+
'energy': energy,
|
| 198 |
+
'sleep_quality': sleep_quality,
|
| 199 |
+
'water_intake': water_goal
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
return f"β
Morning check-in completed!\n\nMood: {mood}/10\nEnergy: {energy}/10\nSleep Quality: {sleep_quality}/10\nWater Goal: {water_goal} glasses\n\nπ Complete your afternoon check-in next!"
|
| 203 |
+
|
| 204 |
+
def afternoon_checkin(self, water_consumed: int, physical_activity: int, stress_level: int) -> str:
|
| 205 |
+
"""Process afternoon check-in"""
|
| 206 |
+
if not hasattr(self, 'temp_morning'):
|
| 207 |
+
return "β Please complete your morning check-in first!"
|
| 208 |
+
|
| 209 |
+
self.temp_afternoon = {
|
| 210 |
+
'physical_activity': physical_activity,
|
| 211 |
+
'stress_level': stress_level
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
# Update water intake
|
| 215 |
+
self.temp_morning['water_intake'] = water_consumed
|
| 216 |
+
|
| 217 |
+
return f"β
Afternoon check-in completed!\n\nWater Consumed: {water_consumed} glasses\nPhysical Activity: {physical_activity} minutes\nStress Level: {stress_level}/10\n\nπ Complete your evening check-in to get your daily score!"
|
| 218 |
+
|
| 219 |
+
def evening_checkin(self, meal_quality: int, screen_time: int, gratitude: int) -> Tuple[str, str, object]:
|
| 220 |
+
"""Process evening check-in and generate daily report"""
|
| 221 |
+
if not hasattr(self, 'temp_morning') or not hasattr(self, 'temp_afternoon'):
|
| 222 |
+
return "β Please complete morning and afternoon check-ins first!", "", None
|
| 223 |
+
|
| 224 |
+
evening_data = {
|
| 225 |
+
'meal_quality': meal_quality,
|
| 226 |
+
'screen_time': screen_time,
|
| 227 |
+
'gratitude': gratitude
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
# Calculate daily score
|
| 231 |
+
score = self.calculate_daily_score(self.temp_morning, self.temp_afternoon, evening_data)
|
| 232 |
+
|
| 233 |
+
# Generate AI recommendation
|
| 234 |
+
recommendation = self.generate_ai_recommendation(score, self.temp_morning, self.temp_afternoon, evening_data)
|
| 235 |
+
|
| 236 |
+
# Create health record
|
| 237 |
+
today = datetime.date.today().isoformat()
|
| 238 |
+
record = HealthRecord(
|
| 239 |
+
date=today,
|
| 240 |
+
morning_mood=self.temp_morning['mood'],
|
| 241 |
+
morning_energy=self.temp_morning['energy'],
|
| 242 |
+
morning_sleep_quality=self.temp_morning['sleep_quality'],
|
| 243 |
+
afternoon_water_intake=self.temp_morning['water_intake'],
|
| 244 |
+
afternoon_physical_activity=self.temp_afternoon['physical_activity'],
|
| 245 |
+
afternoon_stress_level=self.temp_afternoon['stress_level'],
|
| 246 |
+
evening_meal_quality=evening_data['meal_quality'],
|
| 247 |
+
evening_screen_time=evening_data['screen_time'],
|
| 248 |
+
evening_gratitude=evening_data['gratitude'],
|
| 249 |
+
daily_score=score,
|
| 250 |
+
ai_recommendation=recommendation
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Save record
|
| 254 |
+
self.records = [r for r in self.records if r.date != today] # Remove today's old record
|
| 255 |
+
self.records.append(record)
|
| 256 |
+
self.save_data()
|
| 257 |
+
|
| 258 |
+
# Generate report
|
| 259 |
+
report = f"""
|
| 260 |
+
# π₯ Daily Health Report - {today}
|
| 261 |
+
|
| 262 |
+
## π Your Health Score: {score:.1f}/100
|
| 263 |
+
|
| 264 |
+
### π
Morning Metrics:
|
| 265 |
+
- Mood: {self.temp_morning['mood']}/10
|
| 266 |
+
- Energy: {self.temp_morning['energy']}/10
|
| 267 |
+
- Sleep Quality: {self.temp_morning['sleep_quality']}/10
|
| 268 |
+
|
| 269 |
+
### π Afternoon Metrics:
|
| 270 |
+
- Water Intake: {self.temp_morning['water_intake']} glasses
|
| 271 |
+
- Physical Activity: {self.temp_afternoon['physical_activity']} minutes
|
| 272 |
+
- Stress Level: {self.temp_afternoon['stress_level']}/10
|
| 273 |
+
|
| 274 |
+
### π Evening Metrics:
|
| 275 |
+
- Meal Quality: {evening_data['meal_quality']}/10
|
| 276 |
+
- Screen Time: {evening_data['screen_time']} hours
|
| 277 |
+
- Gratitude Practice: {gratitude}/10
|
| 278 |
+
|
| 279 |
+
## π€ AI Doctor Recommendations:
|
| 280 |
+
{recommendation}
|
| 281 |
+
|
| 282 |
+
---
|
| 283 |
+
*Keep up the great work! Consistency is key to better health.* π
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
# Create progress chart
|
| 287 |
+
chart = self.create_progress_chart()
|
| 288 |
+
|
| 289 |
+
# Clear temporary data
|
| 290 |
+
delattr(self, 'temp_morning')
|
| 291 |
+
delattr(self, 'temp_afternoon')
|
| 292 |
+
|
| 293 |
+
return f"β
Evening check-in completed!", report, chart
|
| 294 |
+
|
| 295 |
+
def create_progress_chart(self):
|
| 296 |
+
"""Create progress visualization"""
|
| 297 |
+
if len(self.records) < 2:
|
| 298 |
+
return None
|
| 299 |
+
|
| 300 |
+
df = pd.DataFrame([asdict(record) for record in self.records[-7:]]) # Last 7 days
|
| 301 |
+
|
| 302 |
+
fig = go.Figure()
|
| 303 |
+
fig.add_trace(go.Scatter(
|
| 304 |
+
x=df['date'],
|
| 305 |
+
y=df['daily_score'],
|
| 306 |
+
mode='lines+markers',
|
| 307 |
+
name='Daily Health Score',
|
| 308 |
+
line=dict(color='#2E86AB', width=3),
|
| 309 |
+
marker=dict(size=8)
|
| 310 |
+
))
|
| 311 |
+
|
| 312 |
+
fig.update_layout(
|
| 313 |
+
title='π Your 7-Day Health Progress',
|
| 314 |
+
xaxis_title='Date',
|
| 315 |
+
yaxis_title='Health Score',
|
| 316 |
+
yaxis=dict(range=[0, 100]),
|
| 317 |
+
template='plotly_white',
|
| 318 |
+
height=400
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
return fig
|
| 322 |
+
|
| 323 |
+
def get_weekly_summary(self) -> str:
|
| 324 |
+
"""Generate weekly health summary"""
|
| 325 |
+
if len(self.records) < 7:
|
| 326 |
+
return "π Complete 7 days of check-ins to see your weekly summary!"
|
| 327 |
+
|
| 328 |
+
recent_records = self.records[-7:]
|
| 329 |
+
avg_score = sum(r.daily_score for r in recent_records) / len(recent_records)
|
| 330 |
+
|
| 331 |
+
# Find trends
|
| 332 |
+
scores = [r.daily_score for r in recent_records]
|
| 333 |
+
trend = "π Improving" if scores[-1] > scores[0] else "π Declining" if scores[-1] < scores[0] else "β‘οΈ Stable"
|
| 334 |
+
|
| 335 |
+
best_day = max(recent_records, key=lambda x: x.daily_score)
|
| 336 |
+
|
| 337 |
+
summary = f"""
|
| 338 |
+
# π
Weekly Health Summary
|
| 339 |
+
|
| 340 |
+
## π― Average Score: {avg_score:.1f}/100
|
| 341 |
+
## π Trend: {trend}
|
| 342 |
+
## π Best Day: {best_day.date} (Score: {best_day.daily_score:.1f})
|
| 343 |
+
|
| 344 |
+
### Key Insights:
|
| 345 |
+
- Best performing area: {"Sleep" if sum(r.morning_sleep_quality for r in recent_records) > 42 else "Physical Activity" if sum(r.afternoon_physical_activity for r in recent_records) > 210 else "Nutrition"}
|
| 346 |
+
- Focus area: {"Sleep routine" if sum(r.morning_sleep_quality for r in recent_records) < 35 else "Exercise" if sum(r.afternoon_physical_activity for r in recent_records) < 140 else "Stress management"}
|
| 347 |
+
|
| 348 |
+
*Keep building those healthy habits! πͺ*
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
return summary
|
| 352 |
+
|
| 353 |
+
# Initialize AI Doctor
|
| 354 |
+
ai_doctor = AIDoctor()
|
| 355 |
+
|
| 356 |
+
# Create Gradio Interface
|
| 357 |
+
with gr.Blocks(title="π₯ AI Doctor - Daily Health Checkup", theme=gr.themes.Soft()) as app:
|
| 358 |
+
gr.Markdown("""
|
| 359 |
+
# π₯ AI Doctor - Your Personal Health Assistant
|
| 360 |
+
|
| 361 |
+
Complete 3 daily check-ins to track your health and get **AI-powered recommendations from Google Gemini**! π€β¨
|
| 362 |
+
|
| 363 |
+
**π± How it works:**
|
| 364 |
+
1. **Morning Check-in** - Rate your mood, energy, and sleep
|
| 365 |
+
2. **Afternoon Check-in** - Log water, activity, and stress
|
| 366 |
+
3. **Evening Check-in** - Rate meals, screen time, and gratitude
|
| 367 |
+
|
| 368 |
+
Get your daily health score and personalized AI recommendations!
|
| 369 |
+
|
| 370 |
+
> π **Setup**: Add your `GEMINI_API_KEY` in Hugging Face Secrets for enhanced AI recommendations!
|
| 371 |
+
""")
|
| 372 |
+
|
| 373 |
+
# API Key status indicator
|
| 374 |
+
if ai_doctor.gemini_available:
|
| 375 |
+
gr.Markdown("β
**Gemini AI Active** - Enhanced recommendations enabled!")
|
| 376 |
+
else:
|
| 377 |
+
gr.Markdown("β οΈ **Gemini AI Inactive** - Add GEMINI_API_KEY for enhanced recommendations (using fallback mode)")
|
| 378 |
+
|
| 379 |
+
with gr.Tabs():
|
| 380 |
+
# Morning Check-in Tab
|
| 381 |
+
with gr.TabItem("π
Morning Check-in"):
|
| 382 |
+
gr.Markdown("### Start your day with a quick health check!")
|
| 383 |
+
|
| 384 |
+
with gr.Row():
|
| 385 |
+
mood_slider = gr.Slider(1, 10, value=7, label="π How's your mood? (1=Terrible, 10=Amazing)")
|
| 386 |
+
energy_slider = gr.Slider(1, 10, value=7, label="β‘ Energy level? (1=Exhausted, 10=Energetic)")
|
| 387 |
+
|
| 388 |
+
with gr.Row():
|
| 389 |
+
sleep_slider = gr.Slider(1, 10, value=7, label="π€ Sleep quality? (1=Terrible, 10=Perfect)")
|
| 390 |
+
water_goal = gr.Slider(4, 12, value=8, label="π§ Water goal today? (glasses)")
|
| 391 |
+
|
| 392 |
+
morning_btn = gr.Button("Complete Morning Check-in β
", variant="primary")
|
| 393 |
+
morning_output = gr.Textbox(label="Morning Status", lines=6)
|
| 394 |
+
|
| 395 |
+
morning_btn.click(
|
| 396 |
+
ai_doctor.morning_checkin,
|
| 397 |
+
inputs=[mood_slider, energy_slider, sleep_slider, water_goal],
|
| 398 |
+
outputs=morning_output
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Afternoon Check-in Tab
|
| 402 |
+
with gr.TabItem("π Afternoon Check-in"):
|
| 403 |
+
gr.Markdown("### Midday health update!")
|
| 404 |
+
|
| 405 |
+
with gr.Row():
|
| 406 |
+
water_consumed = gr.Slider(0, 15, value=4, label="π§ Water consumed so far? (glasses)")
|
| 407 |
+
activity_minutes = gr.Slider(0, 180, value=30, label="π Physical activity? (minutes)")
|
| 408 |
+
|
| 409 |
+
stress_slider = gr.Slider(1, 10, value=5, label="π° Stress level? (1=Zen, 10=Overwhelmed)")
|
| 410 |
+
|
| 411 |
+
afternoon_btn = gr.Button("Complete Afternoon Check-in β
", variant="primary")
|
| 412 |
+
afternoon_output = gr.Textbox(label="Afternoon Status", lines=6)
|
| 413 |
+
|
| 414 |
+
afternoon_btn.click(
|
| 415 |
+
ai_doctor.afternoon_checkin,
|
| 416 |
+
inputs=[water_consumed, activity_minutes, stress_slider],
|
| 417 |
+
outputs=afternoon_output
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
# Evening Check-in Tab
|
| 421 |
+
with gr.TabItem("π Evening Check-in"):
|
| 422 |
+
gr.Markdown("### End your day and get your health score!")
|
| 423 |
+
|
| 424 |
+
with gr.Row():
|
| 425 |
+
meal_quality = gr.Slider(1, 10, value=7, label="π₯ Meal quality today? (1=Junk, 10=Nutritious)")
|
| 426 |
+
screen_time = gr.Slider(0, 12, value=4, label="π± Screen time? (hours)")
|
| 427 |
+
|
| 428 |
+
gratitude_slider = gr.Slider(1, 10, value=7, label="π Gratitude practice? (1=None, 10=Very mindful)")
|
| 429 |
+
|
| 430 |
+
evening_btn = gr.Button("Complete Evening Check-in & Get Score! π―", variant="primary")
|
| 431 |
+
|
| 432 |
+
with gr.Row():
|
| 433 |
+
evening_status = gr.Textbox(label="Evening Status")
|
| 434 |
+
daily_report = gr.Markdown(label="π Daily Health Report")
|
| 435 |
+
|
| 436 |
+
progress_chart = gr.Plot(label="π Progress Chart")
|
| 437 |
+
|
| 438 |
+
evening_btn.click(
|
| 439 |
+
ai_doctor.evening_checkin,
|
| 440 |
+
inputs=[meal_quality, screen_time, gratitude_slider],
|
| 441 |
+
outputs=[evening_status, daily_report, progress_chart]
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
# Progress Tab
|
| 445 |
+
with gr.TabItem("π Weekly Summary"):
|
| 446 |
+
gr.Markdown("### Your health journey overview")
|
| 447 |
+
|
| 448 |
+
summary_btn = gr.Button("Generate Weekly Summary π
", variant="secondary")
|
| 449 |
+
weekly_summary = gr.Markdown()
|
| 450 |
+
|
| 451 |
+
summary_btn.click(
|
| 452 |
+
ai_doctor.get_weekly_summary,
|
| 453 |
+
outputs=weekly_summary
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
gr.Markdown("""
|
| 457 |
+
---
|
| 458 |
+
|
| 459 |
+
### π‘ Health Tips:
|
| 460 |
+
- **Consistency** is more important than perfection
|
| 461 |
+
- Aim for **8 glasses** of water daily
|
| 462 |
+
- Get **7-9 hours** of quality sleep
|
| 463 |
+
- **30+ minutes** of physical activity
|
| 464 |
+
- Practice **gratitude** for mental wellness
|
| 465 |
+
|
| 466 |
+
*Your AI Doctor is here to help you build lasting healthy habits! π*
|
| 467 |
+
""")
|
| 468 |
+
|
| 469 |
+
if __name__ == "__main__":
|
| 470 |
+
app.launch()
|