-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1768 lines (1487 loc) · 73.7 KB
/
Copy pathapp.py
File metadata and controls
1768 lines (1487 loc) · 73.7 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
from streamlit_autorefresh import st_autorefresh
from streamlit.components.v1 import html
from dotenv import load_dotenv
import os
import sys
from datetime import datetime
# --- BULLETPROOF GOOGLE CLOUD AUTHENTICATION ---
from google.oauth2 import service_account
import vertexai
if "GCP_SERVICE_ACCOUNT" in st.secrets:
creds_dict = dict(st.secrets["GCP_SERVICE_ACCOUNT"])
if "private_key" in creds_dict:
creds_dict["private_key"] = creds_dict["private_key"].replace("\\n", "\n")
credentials = service_account.Credentials.from_service_account_info(creds_dict)
vertexai.init(project=creds_dict.get("project_id", "fine-rite-497404-r7"), credentials=credentials)
# -----------------------------------------------
# Add src to path for imports
sys.path.insert(0, 'src')
# Load environment variables
load_dotenv()
# Import modules
from planning_engine import generate_health_plan
from alarm_logic import simulate_alarm_sync
from nutritional_engine import analyze_food_item
from database import DatabaseService, UserCreate, MealLogCreate, WorkoutLogCreate, HealthMetricsCreate
from dashboard_engine import (
build_weight_trend_data,
calculate_progress_metrics,
calculate_goal_progress_items,
get_health_insights,
)
from reminder_engine import (
ReminderType,
ReminderHistory,
generate_meal_reminders,
generate_water_reminders,
generate_workout_reminders,
generate_sleep_reminder,
generate_mood_check_reminder,
create_notification_from_reminder,
get_reminder_insights,
is_in_quiet_hours,
)
from reminder_scheduler import (
build_ics_calendar,
build_windows_task_script,
build_cron_job_script,
)
from database import (
ReminderSettingsCreate,
ReminderCreate,
)
import plotly.graph_objects as go
# --- PAGE CONFIG ---
st.set_page_config(
page_title="FitAgent - AI Health Co-Pilot",
page_icon="🏋️",
layout="wide",
initial_sidebar_state="expanded"
)
# --- INITIALIZE SESSION STATE ---
if "db_service" not in st.session_state:
st.session_state.db_service = DatabaseService()
st.session_state.db_service.init_db()
if "user_id" not in st.session_state:
st.session_state.user_id = None
if "current_user" not in st.session_state:
st.session_state.current_user = None
if "page" not in st.session_state:
st.session_state.page = "home"
if "plan" not in st.session_state:
st.session_state.plan = None
if "alarms_synced" not in st.session_state:
st.session_state.alarms_synced = False
if "analysis_results" not in st.session_state:
st.session_state.analysis_results = {}
if "notification_permission_requested" not in st.session_state:
st.session_state.notification_permission_requested = False
# --- HELPER FUNCTIONS ---
def set_page(page_name):
"""Navigate to a different page."""
st.session_state.page = page_name
def logout_user():
"""Logout current user."""
st.session_state.user_id = None
st.session_state.current_user = None
st.session_state.page = "home"
def load_user_profile(user_id):
"""Load user profile from database."""
db_service = st.session_state.db_service
user = db_service.get_user(user_id)
return user
def get_or_create_reminder_settings(user_id):
"""Retrieve or initialize reminder settings for the user."""
db_service = st.session_state.db_service
settings = db_service.get_reminder_settings(user_id)
if settings is None:
settings = db_service.create_reminder_settings(ReminderSettingsCreate(user_id=user_id))
return settings
def build_reminder_history(reminders):
"""Convert completed reminders into ReminderHistory items."""
history_items = []
for reminder in reminders:
if reminder.status == "completed" and reminder.completed_at:
completion_minutes = int((reminder.completed_at - reminder.scheduled_time).total_seconds() / 60)
history_items.append(ReminderHistory(
reminder_id=reminder.id,
user_id=reminder.user_id,
reminder_type=reminder.reminder_type,
title=reminder.title,
scheduled_time=reminder.scheduled_time,
completed_at=reminder.completed_at,
completion_time_minutes=completion_minutes,
))
return history_items
def get_pending_due_reminders(user_id):
"""Return pending reminders due now or overdue."""
db_service = st.session_state.db_service
reminders = db_service.get_user_reminders(user_id, days=1)
return [
reminder for reminder in reminders
if reminder.status == "pending" and reminder.scheduled_time <= datetime.utcnow()
]
def render_reminder_notification_card(reminder):
"""Render a notification-style card for a pending reminder."""
notification = create_notification_from_reminder(reminder)
card_html = f"""
<div style="border: 2px solid #4ECDC4; border-radius: 14px; padding: 16px; margin-bottom: 12px; background: linear-gradient(135deg, #f0fffb, #dcffef); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);">
<div style="font-size: 18px; font-weight: 700; margin-bottom: 8px;">🔔 {notification.title}</div>
<div style="font-size: 14px; margin-bottom: 10px;">{notification.body}</div>
<div style="font-size: 12px; color: #555;">Actions: {', '.join([button['label'] for button in notification.action_buttons])}</div>
</div>
"""
html(card_html, height=150)
def request_browser_notification_permission():
"""Request browser notification permission for mobile alerts."""
if st.session_state.notification_permission_requested:
return
html(
"""
<script>
if (!('Notification' in window)) {
console.log('Browser notifications not supported');
} else if (Notification.permission !== 'granted') {
Notification.requestPermission().then(function(permission) {
console.log('Notification permission:', permission);
});
}
</script>
""",
height=0,
)
st.session_state.notification_permission_requested = True
def show_browser_notification(title: str, body: str):
"""Show a browser notification if permission is granted."""
safe_title = title.replace('"', '\\"')
safe_body = body.replace('"', '\\"')
notification_js = f"""
<script>
if ('Notification' in window && Notification.permission === 'granted') {{
new Notification("{safe_title}", {{ body: "{safe_body}", icon: "https://cdn-icons-png.flaticon.com/512/1827/1827392.png" }});
}}
</script>
"""
html(notification_js, height=0)
def play_alarm_sound(vibrate=True):
"""Trigger a short alarm sound and vibration if supported."""
vibrate_js = "true" if vibrate else "false"
sound_js = f"""
<script>
try {{
const AudioContext = window.AudioContext || window.webkitAudioContext;
const ctx = new AudioContext();
const oscillator = ctx.createOscillator();
const gain = ctx.createGain();
oscillator.type = 'sine';
oscillator.frequency.value = 880;
gain.gain.value = 0.12;
oscillator.connect(gain);
gain.connect(ctx.destination);
oscillator.start();
oscillator.stop(ctx.currentTime + 0.20);
if ({vibrate_js} && navigator.vibrate) {{
navigator.vibrate([180, 90, 180]);
}}
}} catch (e) {{
console.log('Alarm sound disabled or blocked:', e);
}}
</script>
"""
html(sound_js, height=0)
def export_reminders_as_ics(reminders):
"""Build and download a calendar file for mobile and desktop calendar imports."""
if not reminders:
return
ics_data = build_ics_calendar(reminders)
st.download_button(
"Download reminders as .ics",
ics_data,
file_name="fitagent_reminders.ics",
mime="text/calendar",
)
st.markdown(
"Import this file into your mobile or desktop calendar app to create native OS-level scheduled reminders."
)
def export_scheduler_scripts(reminders):
"""Offer a Windows task scheduler script or Linux cron file for laptop reminders."""
if not reminders:
return
if os.name == "nt":
script = build_windows_task_script(reminders)
st.download_button(
"Download Windows Task Scheduler script",
script,
file_name="fitagent_schedule_tasks.bat",
mime="application/x-msdownload",
)
st.markdown(
"Run this downloaded script on Windows to schedule desktop reminder popups."
)
else:
script = build_cron_job_script(reminders, sys.executable, os.getcwd())
st.download_button(
"Download cron job script",
script,
file_name="fitagent_reminders.cron",
mime="text/x-sh",
)
st.markdown(
"Use this shell script on Linux/macOS to install cron jobs for reminders."
)
def ensure_daily_reminder_schedule(user):
"""Create today's default reminders if they are missing."""
db_service = st.session_state.db_service
settings = get_or_create_reminder_settings(user.id)
today = datetime.utcnow().date()
existing_reminders = db_service.get_user_reminders(user.id, days=1)
def has_reminder(reminder_type):
return any(
r.reminder_type == reminder_type and r.scheduled_time.date() == today
for r in existing_reminders
)
created = []
if settings.water_reminders_enabled and not has_reminder(ReminderType.WATER.value):
reminders = generate_water_reminders(user.id, settings.water_reminder_interval_hours)
for reminder in reminders:
created.append(db_service.create_reminder(ReminderCreate(**reminder.dict(exclude_none=True, exclude={"id", "created_at", "completed_at"}))))
if settings.sleep_reminder_enabled and not has_reminder(ReminderType.SLEEP.value):
sleep_reminder = generate_sleep_reminder(user.id, settings.sleep_reminder_time)
if sleep_reminder:
created.append(db_service.create_reminder(ReminderCreate(**sleep_reminder.dict(exclude_none=True, exclude={"id", "created_at", "completed_at"}))))
if settings.mood_check_enabled and not has_reminder(ReminderType.MOOD.value):
mood_reminder = generate_mood_check_reminder(user.id, settings.mood_check_time)
if mood_reminder:
created.append(db_service.create_reminder(ReminderCreate(**mood_reminder.dict(exclude_none=True, exclude={"id", "created_at", "completed_at"}))))
return created
def display_due_reminders(user):
"""Show an alert banner and cards for reminders due now."""
due_reminders = get_pending_due_reminders(user.id)
if not due_reminders:
return
settings = st.session_state.db_service.get_reminder_settings(user.id)
quiet_active = False
if settings:
quiet_active = is_in_quiet_hours(datetime.utcnow(), settings.quiet_hours_start, settings.quiet_hours_end)
if quiet_active:
st.info("Quiet hours are active. Notifications are shown silently in the app.")
st.warning(f"You have {len(due_reminders)} reminder(s) due now.")
for reminder in due_reminders:
render_reminder_notification_card(reminder)
if settings and settings.notification_sound_enabled:
play_alarm_sound(vibrate=settings.vibration_enabled)
if st.session_state.notification_permission_requested:
show_browser_notification(due_reminders[0].title, due_reminders[0].description)
if st.button("Open Reminders", type="secondary"):
set_page("reminders")
st.rerun()
# --- SIDEBAR ---
with st.sidebar:
st.title("FitAgent")
st.markdown("---")
if st.session_state.user_id is None:
# Not logged in - show login/signup options
st.markdown("### Get Started")
if st.button("Create New Profile", key="btn_create_profile", use_container_width=True):
set_page("create_profile")
if st.button("Load Existing Profile", key="btn_load_profile", use_container_width=True):
set_page("load_profile")
else:
# Logged in - show user menu
st.markdown(f"### Welcome, {st.session_state.current_user.name}!")
st.markdown(f"**Goal:** {st.session_state.current_user.goal}")
st.markdown(f"**Current Weight:** {st.session_state.current_user.weight_kg} kg")
st.markdown("---")
# Navigation
st.markdown("### Navigation")
if st.button("Dashboard", key="btn_dashboard", use_container_width=True):
set_page("dashboard")
if st.button("Generate Health Plan", key="btn_gen_plan", use_container_width=True):
set_page("health_plan")
if st.button("Log Meal", key="btn_log_meal", use_container_width=True):
set_page("log_meal")
if st.button("Log Workout", key="btn_log_workout", use_container_width=True):
set_page("log_workout")
if st.button("Health Metrics", key="btn_metrics", use_container_width=True):
set_page("health_metrics")
if st.button("Food Analysis", key="btn_food_analysis", use_container_width=True):
set_page("food_analysis")
if st.button("Health Dashboard", key="btn_dashboard_health", use_container_width=True):
set_page("health_dashboard")
if st.button("Reminders", key="btn_reminders", use_container_width=True):
set_page("reminders")
if st.button("Notification Inbox", key="btn_notification_inbox", use_container_width=True):
set_page("notification_inbox")
if st.button("Export Reminders", key="btn_export_reminders", use_container_width=True):
set_page("reminder_export")
if st.button("Mobile / Laptop Setup", key="btn_mobile_setup", use_container_width=True):
set_page("mobile_setup")
st.markdown("---")
if st.button("Edit Profile", key="btn_edit_profile", use_container_width=True):
set_page("edit_profile")
if st.button("Logout", key="btn_logout", use_container_width=True):
logout_user()
st.rerun()
# --- PAGE: HOME ---
def page_home():
st.title("FitAgent: Autonomous Health Co-Pilot")
st.markdown("""
Welcome to **FitAgent** - your personal AI health companion built for the **INDIA RUNS Hackathon**.
FitAgent bridges the gap between knowing *what* to do and actually *doing* it by:
- [TARGET] Generating personalized diet & exercise plans (India-focused)
- [FOOD] Analyzing nutritional content of foods ("Food as Medicine")
- [SCHEDULE] Creating actionable daily schedules with alarms
- [TRACK] Tracking health metrics and progress
- [REMIND] Sending reminders to keep you on track
---
### Getting Started
1. **Create a Profile** - Tell us your health goals, dietary preferences, and lifestyle
2. **Generate a Plan** - AI creates a personalized diet & exercise routine
3. **Log Your Progress** - Track meals, workouts, and health metrics
4. **Stay Accountable** - Daily reminders keep you on track
""")
st.info("Use the sidebar to create or load a profile!")
if st.session_state.user_id:
display_due_reminders(st.session_state.current_user)
# --- PAGE: CREATE PROFILE ---
def page_create_profile():
st.title("Create Your Profile")
st.markdown("Tell us about yourself so we can create a personalized health plan.")
with st.form("create_profile_form"):
col1, col2 = st.columns(2)
with col1:
name = st.text_input("Full Name", placeholder="e.g., Raj Kumar")
age = st.number_input("Age", min_value=15, max_value=100, value=30)
gender = st.selectbox("Gender", ["Male", "Female", "Other"])
height_cm = st.number_input("Height (cm)", min_value=140, max_value=220, value=175)
with col2:
weight_kg = st.number_input("Weight (kg)", min_value=30, max_value=200, value=75)
goal = st.selectbox(
"Primary Goal",
["weight_loss", "muscle_gain", "maintenance", "endurance"],
format_func=lambda x: x.replace("_", " ").title()
)
diet_preference = st.selectbox(
"Diet Preference",
["vegetarian", "non_veg", "vegan"],
format_func=lambda x: x.replace("_", " ").title()
)
st.markdown("---")
st.markdown("### Additional Information")
col1, col2 = st.columns(2)
with col1:
daily_water_goal = st.number_input("Daily Water Goal (liters)", min_value=1.0, max_value=5.0, value=2.5, step=0.5)
daily_steps_goal = st.number_input("Daily Steps Goal", min_value=1000, max_value=50000, value=10000, step=1000)
with col2:
dietary_restrictions = st.text_area(
"Dietary Restrictions (if any)",
placeholder="e.g., No gluten, No dairy, Nut allergy",
height=90
)
health_conditions = st.text_area(
"Health Conditions (if any)",
placeholder="e.g., Diabetes, Hypertension, PCOS",
height=90
)
lifestyle = st.text_area(
"Describe Your Lifestyle",
placeholder="e.g., I work 9-5 at a desk, I want to lose weight and gain energy. I prefer home-cooked meals.",
height=100
)
submitted = st.form_submit_button("Create Profile", type="primary", use_container_width=True)
if submitted:
if not name:
st.error("Please enter your name.")
elif not lifestyle:
st.error("Please describe your lifestyle.")
else:
try:
db_service = st.session_state.db_service
user_create = UserCreate(
name=name,
age=age,
gender=gender,
height_cm=height_cm,
weight_kg=weight_kg,
goal=goal,
diet_preference=diet_preference,
daily_water_goal=daily_water_goal,
daily_steps_goal=daily_steps_goal,
dietary_restrictions=dietary_restrictions if dietary_restrictions else None,
health_conditions=health_conditions if health_conditions else None
)
user = db_service.create_user(user_create)
st.session_state.user_id = user.id
st.session_state.current_user = user
st.success(f"Profile created successfully! Welcome, {name}!")
st.balloons()
# Redirect to dashboard
import time
time.sleep(1)
set_page("dashboard")
st.rerun()
except Exception as e:
st.error(f"Error creating profile: {str(e)}")
# --- PAGE: LOAD PROFILE ---
def page_load_profile():
st.title("Load Existing Profile")
db_service = st.session_state.db_service
all_users = db_service.get_all_users()
if not all_users:
st.warning("No profiles found. Create a new profile to get started!")
return
user_options = {f"{u.name} (ID: {u.id})": u.id for u in all_users}
selected = st.selectbox("Select a profile:", list(user_options.keys()))
if st.button("Load Profile", type="primary", use_container_width=True):
user_id = user_options[selected]
user = db_service.get_user(user_id)
st.session_state.user_id = user_id
st.session_state.current_user = user
st.success(f"Loaded profile: {user.name}")
import time
time.sleep(0.5)
set_page("dashboard")
st.rerun()
# --- PAGE: DASHBOARD ---
def page_dashboard():
st.title("Dashboard")
user = st.session_state.current_user
db_service = st.session_state.db_service
# Header with user info
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Current Weight", f"{user.weight_kg} kg")
with col2:
bmi = user.weight_kg / ((user.height_cm / 100) ** 2)
st.metric("BMI", f"{bmi:.1f}")
with col3:
st.metric("Goal", user.goal.replace("_", " ").title())
with col4:
st.metric("Diet", user.diet_preference.title())
st.markdown("---")
# Today's stats
st.markdown("### Today's Summary")
today_calories = db_service.get_today_calories(user.id)
today_burned = db_service.get_today_calories_burned(user.id)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Calories Consumed", f"{today_calories:.0f} cal")
with col2:
st.metric("Calories Burned", f"{today_burned:.0f} cal")
with col3:
net = today_calories - today_burned
st.metric("Net Calories", f"{net:.0f} cal")
st.markdown("---")
display_due_reminders(user)
# Recent activity
st.markdown("### Recent Activity")
col1, col2 = st.columns(2)
with col1:
st.markdown("#### Last 7 Days - Meals")
meals = db_service.get_user_meal_logs(user.id, days=7)
if meals:
for meal in meals[:5]:
st.write(f" {meal.meal_name} ({meal.meal_type}) - {meal.calories:.0f} cal")
else:
st.info("No meals logged yet")
with col2:
st.markdown("#### Last 7 Days - Workouts")
workouts = db_service.get_user_workout_logs(user.id, days=7)
if workouts:
for workout in workouts[:5]:
st.write(f" {workout.exercise_name} ({workout.exercise_type}) - {workout.duration_minutes} min")
else:
st.info("No workouts logged yet")
# --- PAGE: HEALTH PLAN ---
def page_health_plan():
st.title("Generate Health Plan")
user = st.session_state.current_user
db_service = st.session_state.db_service
st.markdown(f"### Generating plan for {user.name}")
st.markdown(f"- **Goal:** {user.goal.replace('_', ' ').title()}")
st.markdown(f"- **Diet:** {user.diet_preference.title()}")
if user.health_conditions:
st.markdown(f"- **Health Conditions:** {user.health_conditions}")
if user.dietary_restrictions:
st.markdown(f"- **Dietary Restrictions:** {user.dietary_restrictions}")
# No API key check required as we use Vertex AI with Default Credentials
if st.button("Generate Personalized Plan", type="primary", use_container_width=True):
with st.spinner("Analyzing your profile and generating personalized plan..."):
try:
# Get recent meal and workout history
meals = db_service.get_user_meal_logs(user.id, days=7)
workouts = db_service.get_user_workout_logs(user.id, days=7)
recent_meals = [f"{m.meal_name} ({m.calories:.0f} cal)" for m in meals] if meals else None
recent_workouts = [f"{w.exercise_name} ({w.duration_minutes} min)" for w in workouts] if workouts else None
# Generate personalized plan
plan = generate_health_plan(
user_goal=user.goal,
diet_preference=user.diet_preference,
age=user.age,
weight_kg=user.weight_kg,
height_cm=user.height_cm,
health_conditions=user.health_conditions,
dietary_restrictions=user.dietary_restrictions,
recent_meals=recent_meals,
recent_workouts=recent_workouts,
)
st.session_state.plan = plan
st.session_state.alarms_synced = False
# Display plan
st.markdown("---")
st.markdown("## Your Personalized Health Plan")
st.markdown(f"**Goal:** {plan.user_goal}")
st.markdown(f"**Summary:** {plan.summary}")
# Display daily schedule
st.markdown("### Daily Schedule")
for item in plan.daily_schedule:
with st.expander(f"{item.time} - {item.title} ({item.activity_type})"):
st.write(f"**Action:** {item.description}")
if item.medicinal_value:
st.info(f"**Health Benefit:** {item.medicinal_value}")
if item.calories_target:
st.write(f"Calorie Target: {item.calories_target}")
if item.duration_minutes:
st.write(f"Duration: {item.duration_minutes} minutes")
# Weekly focus
st.markdown("### Weekly Focus")
st.markdown(plan.weekly_focus)
# Tips
st.markdown("### Tips & Warnings")
for tip in plan.tips_and_warnings:
st.write(f"• {tip}")
# Create reminders from plan
st.markdown("---")
if st.button("Create Reminders from Plan", type="secondary"):
with st.spinner("Creating reminders from your health plan..."):
settings = get_or_create_reminder_settings(user.id)
reminders_to_save = []
if settings.meal_reminders_enabled:
reminders_to_save.extend(
generate_meal_reminders(
plan.dict(),
user.id,
settings.meal_reminder_time_before_minutes,
)
)
if settings.workout_reminders_enabled:
plan_workouts = [
{
"time": item.time,
"exercise_name": item.title,
"duration_minutes": item.duration_minutes or 30,
"intensity": "moderate",
"type": item.activity_type,
}
for item in plan.daily_schedule
if item.activity_type == "workout"
]
reminders_to_save.extend(
generate_workout_reminders(
user.id,
plan_workouts,
settings.workout_reminder_time_before_minutes,
)
)
if settings.water_reminders_enabled:
reminders_to_save.extend(
generate_water_reminders(
user.id,
settings.water_reminder_interval_hours,
)
)
if settings.sleep_reminder_enabled:
sleep_reminder = generate_sleep_reminder(
user.id,
settings.sleep_reminder_time,
)
if sleep_reminder:
reminders_to_save.append(sleep_reminder)
if settings.mood_check_enabled:
mood_reminder = generate_mood_check_reminder(
user.id,
settings.mood_check_time,
)
if mood_reminder:
reminders_to_save.append(mood_reminder)
created_reminders = []
for reminder_item in reminders_to_save:
reminder_payload = reminder_item.dict(exclude_none=True, exclude={"id", "created_at", "completed_at"})
created_reminders.append(
st.session_state.db_service.create_reminder(
ReminderCreate(**reminder_payload)
)
)
st.success(f"Created {len(created_reminders)} reminders from plan.")
if created_reminders:
st.markdown("#### Upcoming reminders created")
for reminder_item in created_reminders:
st.write(
f"{reminder_item.scheduled_time.strftime('%H:%M')} - {reminder_item.title} ({reminder_item.reminder_type})"
)
# Sync alarms
st.markdown("---")
if st.button("Sync Alarms from Plan", type="secondary"):
with st.spinner("Syncing alarms..."):
alarms = simulate_alarm_sync(plan)
st.session_state.alarms_synced = True
st.success("Alarms synced!")
st.json({"status": "success", "alarms_synced": len(plan.daily_schedule)})
except Exception as e:
st.error(f"Error generating plan: {str(e)}")
st.info("Ensure your Google Cloud credentials (ADC) are configured and you have an internet connection.")
# --- PAGE: LOG MEAL ---
def page_log_meal():
st.title("Log Meal")
user = st.session_state.current_user
with st.form("log_meal_form"):
col1, col2 = st.columns(2)
with col1:
meal_name = st.text_input("Meal Name", placeholder="e.g., Chicken Biryani")
meal_type = st.selectbox("Meal Type", ["breakfast", "lunch", "dinner", "snack"])
quantity = st.text_input("Quantity", placeholder="e.g., 1 bowl, 150g")
with col2:
calories = st.number_input("Calories", min_value=0, value=300)
protein_g = st.number_input("Protein (g)", min_value=0.0, value=0.0, step=0.5)
carbs_g = st.number_input("Carbs (g)", min_value=0.0, value=0.0, step=0.5)
fat_g = st.number_input("Fat (g)", min_value=0.0, value=0.0, step=0.5)
fiber_g = st.number_input("Fiber (g)", min_value=0.0, value=0.0, step=0.5)
ingredients = st.text_area("Ingredients (comma-separated)", placeholder="e.g., rice, chicken, onion, spices")
submitted = st.form_submit_button("Log Meal", type="primary", use_container_width=True)
if submitted:
if not meal_name:
st.error("Please enter meal name.")
else:
try:
db_service = st.session_state.db_service
meal_log = MealLogCreate(
user_id=user.id,
meal_name=meal_name,
meal_type=meal_type,
quantity=quantity,
calories=calories,
protein_g=protein_g if protein_g > 0 else None,
carbs_g=carbs_g if carbs_g > 0 else None,
fat_g=fat_g if fat_g > 0 else None,
fiber_g=fiber_g if fiber_g > 0 else None,
ingredients=ingredients if ingredients else None
)
db_service.log_meal(meal_log)
st.success(f"Meal logged: {meal_name}")
except Exception as e:
st.error(f"Error logging meal: {str(e)}")
# --- PAGE: LOG WORKOUT ---
def page_log_workout():
st.title("Log Workout")
user = st.session_state.current_user
with st.form("log_workout_form"):
col1, col2 = st.columns(2)
with col1:
exercise_name = st.text_input("Exercise Name", placeholder="e.g., Running, Yoga, Weight Training")
exercise_type = st.selectbox("Exercise Type", ["cardio", "strength", "flexibility", "sports"])
duration_minutes = st.number_input("Duration (minutes)", min_value=1, value=30)
with col2:
intensity = st.selectbox("Intensity", ["low", "moderate", "high"])
calories_burned = st.number_input("Calories Burned", min_value=0, value=200)
distance_km = st.number_input("Distance (km) - if applicable", min_value=0.0, value=0.0, step=0.1)
sets_reps = st.text_input("Sets & Reps - if applicable", placeholder="e.g., 3x10, 4x12")
notes = st.text_area("Notes", placeholder="How did you feel? Any observations?")
submitted = st.form_submit_button("Log Workout", type="primary", use_container_width=True)
if submitted:
if not exercise_name:
st.error("Please enter exercise name.")
else:
try:
db_service = st.session_state.db_service
workout_log = WorkoutLogCreate(
user_id=user.id,
exercise_name=exercise_name,
exercise_type=exercise_type,
duration_minutes=duration_minutes,
intensity=intensity,
calories_burned=calories_burned if calories_burned > 0 else None,
distance_km=distance_km if distance_km > 0 else None,
sets_reps=sets_reps if sets_reps else None,
notes=notes if notes else None
)
db_service.log_workout(workout_log)
st.success(f"Workout logged: {exercise_name}")
except Exception as e:
st.error(f"Error logging workout: {str(e)}")
# --- PAGE: HEALTH METRICS ---
def page_health_metrics():
st.title("Health Metrics")
user = st.session_state.current_user
with st.form("health_metrics_form"):
col1, col2, col3 = st.columns(3)
with col1:
weight_kg = st.number_input("Weight (kg)", min_value=30.0, value=user.weight_kg)
water_intake = st.number_input("Water Intake (liters)", min_value=0.0, value=2.0, step=0.5)
with col2:
steps = st.number_input("Steps", min_value=0, value=0)
sleep_hours = st.number_input("Sleep Hours", min_value=0.0, value=8.0, step=0.5)
with col3:
mood = st.selectbox("Mood", ["happy", "neutral", "stressed", "tired"])
energy_level = st.selectbox("Energy Level", ["low", "medium", "high"])
notes = st.text_area("Additional Notes", placeholder="Any observations about your health today?")
submitted = st.form_submit_button("Log Metrics", type="primary", use_container_width=True)
if submitted:
try:
db_service = st.session_state.db_service
bmi = weight_kg / ((user.height_cm / 100) ** 2)
metrics_log = HealthMetricsCreate(
user_id=user.id,
weight_kg=weight_kg,
bmi=bmi,
water_intake_liters=water_intake,
steps=steps,
sleep_hours=sleep_hours if sleep_hours > 0 else None,
mood=mood,
energy_level=energy_level,
notes=notes if notes else None
)
db_service.log_health_metrics(metrics_log)
st.success("Health metrics logged!")
except Exception as e:
st.error(f"Error logging metrics: {str(e)}")
# --- PAGE: FOOD ANALYSIS ---
def page_food_analysis():
st.title("Food Nutritional Analysis")
st.markdown("Deep dive into nutritional profiles and Ayurvedic benefits of any food item.")
# No API key check required as we use Vertex AI with Default Credentials
# Two analysis modes
analysis_mode = st.radio("Choose Analysis Type:", ["Quick Analysis", "Detailed Analysis"], horizontal=True)
food_item = st.text_input(
"Enter food item to analyze",
placeholder="e.g., Paneer butter masala, Dal with roti, Spinach salad"
)
if st.button("Analyze", type="primary", use_container_width=True):
if not food_item:
st.error("Please enter a food item.")
else:
with st.spinner("Analyzing food..."):
try:
if analysis_mode == "Quick Analysis":
# Simple text analysis
analysis = analyze_food_item(food_item)
st.markdown("### Nutritional & Ayurvedic Analysis")
st.write(analysis)
else:
# Detailed structured analysis
from nutritional_engine import analyze_food_item_structured
analysis = analyze_food_item_structured(food_item)
st.markdown("### Detailed Food Analysis")
# Create tabs for different sections
tab1, tab2, tab3, tab4 = st.tabs(["Nutrition", "Ayurvedic", "Recommendations", "Benefits"])
with tab1:
st.markdown(f"#### {analysis.food_name}")
st.write(f"**Serving Size:** {analysis.serving_size}")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Calories", f"{analysis.nutrition.calories:.0f}")
with col2:
st.metric("Protein", f"{analysis.nutrition.protein_g:.1f}g")
with col3:
st.metric("Carbs", f"{analysis.nutrition.carbs_g:.1f}g")
with col4:
st.metric("Fat", f"{analysis.nutrition.fat_g:.1f}g")
st.write(f"**Macro Ratios:** {analysis.macronutrient_ratio}")
if analysis.nutrition.fiber_g:
st.write(f"**Fiber:** {analysis.nutrition.fiber_g:.1f}g")
if analysis.nutrition.sugar_g:
st.write(f"**Sugar:** {analysis.nutrition.sugar_g:.1f}g")
if analysis.nutrition.sodium_mg:
st.write(f"**Sodium:** {analysis.nutrition.sodium_mg:.0f}mg")
with tab2:
st.markdown("#### Ayurvedic Benefits")
for benefit in analysis.ayurvedic_benefits:
with st.expander(f"{benefit.benefit}"):
st.write(f"**Dosha Impact:** {benefit.dosha_impact}")
st.write(f"**Principle:** {benefit.supporting_principle}")
with tab3:
st.markdown("#### Recommendations")
st.write(f"**Best Time to Eat:** {analysis.best_time_to_eat}")
st.write(f"**Digestibility:** {analysis.digestibility}")
col1, col2 = st.columns(2)
with col1:
st.write("**Pairs Well With:**")
for food in analysis.pairs_well_with:
st.write(f"✓ {food}")
with col2:
st.write("**Avoid With:**")
for food in analysis.avoid_with:
st.write(f"✗ {food}")
if analysis.precautions:
st.warning(f"**Precautions:** {analysis.precautions}")
with tab4:
st.markdown("#### Best For Health Goals")
for goal in analysis.ideal_for_goal:
st.write(f"• {goal}")
st.markdown("#### Interesting Fact")
st.info(analysis.interesting_fact)
except Exception as e:
st.error(f"Error analyzing food: {str(e)}")
st.info("Ensure your Google Cloud credentials (ADC) are configured and you have an internet connection.")