Skip to content

Commit fadcc89

Browse files
Merge pull request #81 from ISE-GenAI-TechX25-Section-D/displayFriendsNames
Display friends names, added caching logic, merged users posts with GenAI logic
2 parents 749898f + f73a79a commit fadcc89

14 files changed

Lines changed: 259 additions & 36 deletions

activity_page.py

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,46 @@
11
import streamlit as sl
22
from data_fetcher import get_user_workouts, insert_user_post
33
from modules import display_activity_summary, display_recent_workouts
4+
from datetime import datetime
45

5-
def display(user_id="user1"):
6-
sl.title("🏃‍♂️ Activities Dashboard")
6+
#Used GPT 4o to help with share logic
7+
8+
def display_activity_page(user_id="user1"):
9+
# sl.title("🏃‍♂️ Activities Dashboard")
710

811
fetcher = lambda: get_user_workouts(user_id)
912
workouts = fetcher()
10-
recent_workouts = workouts[-3:] if len(workouts) >= 3 else workouts
1113

12-
side_view(user_id, fetcher)
14+
# Sort by timestamp descending (most recent first)
15+
sorted_workouts = sorted(
16+
workouts,
17+
key=lambda w: w['start_timestamp'][:w['start_timestamp'].index(' ')],
18+
reverse=True
19+
)
20+
21+
# Get the 3 most recent
22+
recent_workouts = sorted_workouts[:3]
23+
24+
side_view(user_id, recent_workouts)
1325

1426
total_distance = sl.session_state.get("total_distance", 0)
1527
total_steps = sl.session_state.get("total_steps", 0)
1628
total_calories = sl.session_state.get("total_calories", 0)
1729

1830
handle_share_section(user_id, workouts, recent_workouts)
1931

20-
def side_view(user_id, fetcher):
32+
def side_view(user_id, workouts_list):
2133
left_col, right_col = sl.columns(2)
2234

2335
with left_col:
24-
sl.subheader("🕒 Recent Workouts")
25-
# display_activity_summary expects a fetcher function
26-
display_recent_workouts(userId=user_id, workouts_func=get_user_workouts, streamlit_module=sl)
36+
# Developeed with GPT 4o
37+
display_recent_workouts(
38+
user_id,
39+
workouts_func=lambda uid: sorted(get_user_workouts(uid), key=lambda w: w['start_timestamp'], reverse=True)[:3]
40+
)
2741

2842
with right_col:
29-
sl.subheader("📊 Summary")
30-
# display_recent_workouts directly takes the get_user_workouts function
31-
display_activity_summary(fetcher=fetcher)
43+
display_activity_summary(workouts_list)
3244

3345

3446
def handle_share_section(user_id, workouts, recent_workouts):
@@ -41,6 +53,9 @@ def handle_share_section(user_id, workouts, recent_workouts):
4153
share_total_stats(user_id)
4254
elif data_source == "A Specific Workout":
4355
share_specific_workout(user_id, recent_workouts)
56+
sl.markdown("---")
57+
sl.markdown("When you press the sharing button, wait a few seconds until the shared notification appears!")
58+
4459

4560
def share_total_stats(user_id):
4661

@@ -52,9 +67,9 @@ def share_total_stats(user_id):
5267

5368
if sl.button("📤 Share"):
5469
if stat_type == "Steps":
55-
message = f"👟 I walked {steps} steps this week!"
70+
message = f"👟 I walked {round(steps)} steps this week!"
5671
elif stat_type == "Distance":
57-
message = f"🏃 I ran {distance} miles this week!"
72+
message = f"🏃 I ran {round(distance)} miles this week!"
5873
elif stat_type == "Calories":
5974
message = f"🔥 I burned {calories} calories this week!"
6075
elif stat_type == "All":

app.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,26 @@
99
from modules import display_my_custom_component, display_post, display_genai_advice, display_activity_summary, display_recent_workouts
1010
from data_fetcher import get_user_posts, get_genai_advice, get_user_profile, get_user_sensor_data, get_user_workouts
1111
from streamlit_option_menu import option_menu
12-
from activity_page import display
12+
from activity_page import display_activity_page
1313
from community_page import display_community
1414

1515

16-
1716
def display_app_page():
1817
"""Displays the home page of the app."""
19-
userId = 'user1'
18+
19+
if 'userId' not in sl.session_state:
20+
sl.session_state.userId = 'user1'
21+
22+
userId = sl.session_state.userId
23+
2024
user_profile = get_user_profile(userId)
2125
user_name = user_profile['username']
2226

23-
27+
friends = user_profile['friends']
28+
friend_profiles = [get_user_profile(fid) for fid in friends]
29+
friend_names = [p['full_name'] for p in friend_profiles]
30+
friend_usernames = [p['username'] for p in friend_profiles]
31+
2432
selected = option_menu(
2533
menu_title=None, # Appears at top of sidebar
2634
options=["Home", "Activities", "Community"],
@@ -35,21 +43,24 @@ def display_app_page():
3543
sl.subheader(f"Welcome {user_profile['full_name']} to MyFitness!")
3644

3745
# Profile Card
38-
sl.image(user_profile['profile_image'], width=150, caption="Your Profile Picture")
39-
40-
sl.markdown(f"**Username:** {user_profile['username']}")
41-
sl.markdown(f"**Date of Birth:** {user_profile['date_of_birth']}")
46+
col1, col2 = sl.columns([1, 3])
47+
with col1:
48+
sl.image(user_profile['profile_image'], width=150)
49+
with col2:
50+
sl.markdown(f"**Username:** {user_profile['username']}")
51+
sl.markdown(f"**Date of Birth:** {user_profile['date_of_birth']}")
4252

4353
# Friends section
4454
sl.markdown("### 👯 Your Friends")
45-
if user_profile['friends']:
46-
for friend_id in user_profile['friends']:
47-
sl.markdown(f"- {friend_id}")
55+
if friends:
56+
for i, j in zip(friend_names, friend_usernames):
57+
sl.markdown(f"**{i}** \n`@{j}`")
58+
4859
else:
4960
sl.info("You don't have any friends yet!")
5061

5162
elif selected == "Activities":
52-
display(user_id=userId)
63+
display_activity_page(user_id=userId)
5364

5465
elif selected == "Community":
5566
display_community(userId)

bq_scripts/insert_post.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Utilized GPT 4o to generate script
2+
from google.cloud import bigquery
3+
from datetime import datetime
4+
5+
client = bigquery.Client()
6+
table_id = "diegoperez16techx25.Committees.Posts"
7+
8+
9+
def get_next_post_id():
10+
query = f"""
11+
SELECT MAX(CAST(REGEXP_EXTRACT(PostId, r'post(\\d+)') AS INT64)) AS max_id
12+
FROM `{table_id}`
13+
WHERE REGEXP_CONTAINS(PostId, r'^post\\d+$')
14+
"""
15+
result = client.query(query).result()
16+
row = next(result)
17+
return f"post{(row.max_id + 1) if row.max_id else 1}"
18+
19+
def add_post():
20+
user_id = input("👤 Enter user ID: ")
21+
image_url = input("🖼️ Enter image URL: ")
22+
content = input("📝 Enter post content: ")
23+
24+
post_id = get_next_post_id()
25+
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
26+
27+
query = f"""
28+
INSERT INTO `{table_id}` (PostId, AuthorId, Timestamp, ImageUrl, Content)
29+
VALUES (
30+
'{post_id}',
31+
'{user_id}',
32+
DATETIME '{timestamp}',
33+
'{image_url}',
34+
'{content.replace("'", "\\'")}'
35+
)
36+
"""
37+
client.query(query).result()
38+
print(f"\n✅ Post '{post_id}' successfully added for user '{user_id}'.")
39+
40+
# Update a post's image
41+
def update_post_image_url():
42+
post_id = input("🆔 Enter Post ID to update: ")
43+
new_url = input("🔗 Enter new image URL: ")
44+
45+
query = f"""
46+
UPDATE `{table_id}`
47+
SET ImageUrl = '{new_url}'
48+
WHERE PostId = '{post_id}'
49+
"""
50+
client.query(query).result()
51+
print(f"\n🔄 Image URL updated for '{post_id}'.")
52+
53+
# Main flow
54+
def main():
55+
print("📬 Welcome to the Post Manager!")
56+
choice = input("Type 'add' to create a post or 'update' to change an image URL: ").strip().lower()
57+
58+
if choice == "add":
59+
add_post()
60+
elif choice == "update":
61+
update_post_image_url()
62+
else:
63+
print("❗ Invalid choice. Please type 'add' or 'update'.")
64+
65+
if __name__ == "__main__":
66+
main()

bq_scripts/insert_workouts.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Utilized GPT 4o to generate script
2+
from google.cloud import bigquery
3+
from datetime import datetime, timedelta
4+
import random
5+
import re
6+
7+
client = bigquery.Client()
8+
9+
table_id = "diegoperez16techx25.Committees.Workouts"
10+
11+
def get_last_workout_number():
12+
query = f"""
13+
SELECT MAX(CAST(REGEXP_EXTRACT(WorkoutId, r'workout(\\d+)') AS INT64)) AS max_id
14+
FROM `{table_id}`
15+
WHERE REGEXP_CONTAINS(WorkoutId, r'^workout\\d+$')
16+
"""
17+
result = client.query(query).result()
18+
row = next(result)
19+
return row.max_id if row.max_id is not None else 0
20+
21+
def generate_sql_insert(user_id, workout_id):
22+
start_time = datetime.utcnow() - timedelta(days=random.randint(1, 30))
23+
end_time = start_time + timedelta(minutes=random.randint(20, 90))
24+
25+
return f"""
26+
INSERT INTO `{table_id}` (
27+
WorkoutId, UserId, StartTimestamp, EndTimestamp,
28+
StartLocationLat, StartLocationLong,
29+
EndLocationLat, EndLocationLong,
30+
TotalDistance, TotalSteps, CaloriesBurned
31+
)
32+
VALUES (
33+
'{workout_id}', '{user_id}',
34+
DATETIME '{start_time.strftime("%Y-%m-%d %H:%M:%S")}',
35+
DATETIME '{end_time.strftime("%Y-%m-%d %H:%M:%S")}',
36+
{round(random.uniform(-90.0, 90.0), 6)},
37+
{round(random.uniform(-180.0, 180.0), 6)},
38+
{round(random.uniform(-90.0, 90.0), 6)},
39+
{round(random.uniform(-180.0, 180.0), 6)},
40+
{round(random.uniform(1.0, 10.0), 2)},
41+
{random.randint(2000, 15000)},
42+
{round(random.uniform(100.0, 900.0), 2)}
43+
)
44+
"""
45+
46+
start_id = get_last_workout_number() + 1
47+
users = ["user4"]
48+
49+
for user in users:
50+
for i in range(3): # 3 workouts per user
51+
workout_number = start_id
52+
workout_id = f"workout{workout_number}"
53+
query = generate_sql_insert(user, workout_id)
54+
client.query(query).result()
55+
print(f"✅ Inserted {workout_id} for {user}")
56+
start_id += 1

community_page.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,33 @@
55
def display_community(user_id):
66
user_profile = get_user_profile(user_id)
77
sl.title("❤️ Community Page")
8-
left_col, right_col = sl.columns(2)
9-
with left_col:
8+
sl.subheader(f" {user_profile['full_name']}'s")
9+
10+
tab1, tab2, tab3 = sl.tabs(["👥 Friends' Posts","GenAI Advice", "👤 My Posts"])
11+
12+
with tab1:
1013
display_post(user_id)
11-
with right_col:
12-
display_genai_advice(user_id)
14+
15+
with tab2:
16+
display_genai_advice(user_id)
17+
18+
with tab3:
19+
sl.subheader("📝 Your Posts")
20+
sl.markdown("---")
21+
user_posts = get_user_posts(user_id)
22+
if user_posts:
23+
user_posts.sort(key=lambda post: post.get('timestamp', ''), reverse=True)
24+
# Generated by GPT 4o
25+
for post in user_posts:
26+
# sl.write(post) #For debugging
27+
image_url = post.get('image', '')
28+
if image_url and image_url.startswith("http"):
29+
sl.image(image_url, width=300)
30+
31+
sl.markdown(post.get('content', 'No content available.'))
32+
timestamp = post.get('timestamp', '🕒 No timestamp')
33+
sl.markdown(f"**{timestamp}**")
34+
sl.markdown("---")
35+
else:
36+
sl.info("You haven't posted anything yet.")
37+

0 commit comments

Comments
 (0)