-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodules.py
More file actions
613 lines (505 loc) · 20.5 KB
/
modules.py
File metadata and controls
613 lines (505 loc) · 20.5 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
#############################################################################
# modules.py
#
# Shared UI modules for the StudySync app.
#############################################################################
from html import escape
from pathlib import Path
from textwrap import dedent
from typing import Dict, List, Optional
from urllib.parse import quote_plus
from data_fetcher import get_nearby_groups, get_final_recommendations, get_user_identity_data
import streamlit as st
def _project_root() -> Path:
return Path(__file__).resolve().parent
def _go_to_page(page: str) -> None:
st.session_state.page = page
st.query_params["page"] = page
st.rerun()
def apply_styles() -> None:
css_path = Path(__file__).resolve().parent / "styles.css"
if not css_path.exists():
st.warning(f"styles.css not found at {css_path}")
return
css = css_path.read_text(encoding="utf-8")
st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)
def render_top_nav(selected_page: str = "Explore Groups") -> None:
labels = ["Explore Groups", "My Groups", "User Profile", "AI Recommendations", "Account Settings"]
def pill(label: str) -> str:
active = "active" if label == selected_page else ""
href = f"?page={quote_plus(label)}"
return (
f'<a class="nav-pill {active}" href="{href}" target="_self">'
f"{escape(label)}"
f"</a>"
)
links = "".join([pill(label) for label in labels])
nav_html = f"""
<div class="top-nav-wrap">
<div class="top-nav-shell">
<div class="brand-pill">StudySync</div>
<div class="top-nav-links">
{links}
</div>
<div class="utility-pill">Campus Focus</div>
</div>
</div>
"""
st.markdown(dedent(nav_html).strip(), unsafe_allow_html=True)
def create_component_from_template(data: Dict[str, str], html_file_name: str) -> None:
import streamlit.components.v1 as components
base = _project_root()
html_path = base / "custom_components" / f"{html_file_name}.html"
if not html_path.exists():
st.warning(f"Custom component HTML not found: {html_path}")
return
html = html_path.read_text(encoding="utf-8")
for k, v in data.items():
html = html.replace(f"{{{{{k}}}}}", str(v))
components.html(html, height=220, scrolling=False)
def display_my_custom_component(value: str) -> None:
data = {"NAME": value}
create_component_from_template(data, "my_custom_component")
def navigation_bar(full_group_list: List[Dict], user_id) -> List[Dict]:
st.markdown(
dedent(
"""
<div class="section-toolbar">
<div class="page-title">Explore Groups</div>
<div class="page-subtitle">
Discover study sessions that match your schedule and interests.
</div>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
# Layout: search bar + filter button
col1, col2 = st.columns([4, 2])
with col1:
search_query = st.text_input(
"Search",
placeholder="Search by title, subject, or description...",
label_visibility="collapsed",
key="explore_search"
)
with col2:
selected_subjects = []
selected_subjects = st.multiselect(
"Filter by subject",
options=[
"Computer Science",
"Mathematics",
"Biology",
"Chemistry",
"Physics"
],
label_visibility="collapsed", # <-- THIS fixes alignment
placeholder="Filter by subject",
key="subject_filter"
)
filter = [f.lower() for f in selected_subjects]
# Process search
q = search_query.lower().strip() if search_query else ""
# Call backend with filters
return get_nearby_groups(
user_id=user_id,
search=q,
lon=0,
lat=0,
filter=filter
)
def study_group_card(
group_id: str,
group_title: str,
subject: str,
description: str,
date: str,
time: str,
location: str,
capacity: str
) -> None:
html = f"""
<div class="glass-card">
<div class="card-header">
<div>
<div class="card-title">{escape(group_title)}</div>
<div class="card-subject">{escape(subject)}</div>
</div>
<div class="card-meta">
<div class="meta-pill">{escape(date)} · {escape(time)}</div>
</div>
</div>
<div class="card-description">{escape(description)}</div>
<div class="card-inline-meta">📍 {escape(location)}</div>
<div class="card-inline-meta">👥 Max: {escape(capacity)}</div>
</div>
"""
st.markdown(dedent(html).strip(), unsafe_allow_html=True)
if st.button("View Details", key=f"btn_{group_id}", use_container_width=True):
st.session_state.selected_group = group_title
def display_explore_page(group_list: List[Dict]) -> None:
if not group_list:
st.info("No groups found.")
return
cards_per_row = 4
for i in range(0, len(group_list), cards_per_row):
row_groups = group_list[i : i + cards_per_row]
cols = st.columns(cards_per_row)
for idx, col in enumerate(cols):
with col:
if idx < len(row_groups):
group = row_groups[idx]
study_group_card(
group_id=str(group.get("id", "")),
group_title=str(group.get("title", "")),
subject=str(group.get("subject", "")),
description=str(group.get("description", "")),
date=str(group.get("schedule", "")[0]["day_of_week"]),
time=str(group.get("schedule", "")[0]["start_time"]),
location=str(group.get("location_text", "")),
capacity=str(group.get("capacity", "")),
)
else:
st.empty()
def _render_stat_card(label: str, value: str) -> None:
st.markdown(
dedent(
f"""
<div class="stat-card">
<div class="stat-label">{escape(str(label))}</div>
<div class="stat-value">{escape(str(value))}</div>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
@st.dialog("Share Profile")
def share_profile_dialog(profile: Dict) -> None:
"""
Popup dialog that displays a shareable summary of the user's profile.
Triggered when the user clicks the 'Share Profile' button.
Args
profile : dict – The user's profile data.
"""
full_name = f"{profile.get('first_name', '')} {profile.get('last_name', '')}".strip()
major = str(profile.get("major", ""))
year = str(profile.get("year", ""))
institution = str(profile.get("institution", ""))
email = str(profile.get("email", ""))
subjects = profile.get("focus_subjects", [])
st.markdown(
dedent(
f"""
<div class="profile-name" style="font-size:1.2rem;">{escape(full_name)}</div>
<div class="profile-subline">{escape(major)} · {escape(year)}</div>
<div class="profile-meta-line" style="margin-top:4px;">
<span>🏛 {escape(institution)}</span>
<span>✉ {escape(email)}</span>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
if subjects:
st.markdown("**Focus Subjects**")
chips = "".join(
[f"<span class='tag-chip'>{escape(str(s))}</span>" for s in subjects]
)
st.markdown(chips, unsafe_allow_html=True)
st.divider()
share_url = f"https://studysync.app/profile/{escape(email)}"
st.markdown("**Share this link**")
st.code(share_url, language=None)
st.caption("Anyone with this link can view your public profile.")
def display_user_profile(profile: Optional[Dict]) -> None:
if not profile:
st.warning("No profile data available.")
return
st.markdown('<div class="page-title">User Profile</div>', unsafe_allow_html=True)
st.markdown(
'<div class="page-subtitle">Your academic profile, focus subjects, and study availability.</div>',
unsafe_allow_html=True,
)
initials = (
str(profile.get("first_name", ""))[:1] + str(profile.get("last_name", ""))[:1]
).upper() or "U"
col_avatar, col_info, col_btns = st.columns([1.2, 5, 2])
with col_avatar:
st.markdown(
dedent(
f"""
<div class="profile-avatar-card">
<div class="profile-avatar-initials">{escape(initials)}</div>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
with col_info:
full_name = (
f"{profile.get('first_name', '')} {profile.get('last_name', '')}".strip()
)
institution = str(profile.get("institution", profile.get("university", "")))
email = str(profile.get("email", ""))
major = str(profile.get("major", ""))
year = str(profile.get("year", profile.get("education_level", "")))
st.markdown(
f'<div class="profile-name">{escape(full_name)}</div>',
unsafe_allow_html=True,
)
st.markdown(
f'<div class="profile-subline">{escape(major)} · {escape(year)}</div>',
unsafe_allow_html=True,
)
st.markdown(
dedent(
f"""
<div class="profile-meta-line">
<span>🏛 {escape(institution)}</span>
<span>✉ <a class="inline-link" href="mailto:{escape(email)}">{escape(email)}</a></span>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
with col_btns:
st.button("Edit Profile", use_container_width=True, key="profile_edit")
st.button("Share Profile", use_container_width=True, key="profile_share")
if st.session_state.get("profile_share"):
share_profile_dialog(profile)
st.divider()
st.markdown("**ABOUT ME**")
st.write(profile.get("about_me", ""))
st.markdown("**FOCUS SUBJECTS**")
subjects = profile.get("focus_subjects", [])
if subjects:
chips = "".join(
[f"<span class='tag-chip'>{escape(str(s))}</span>" for s in subjects]
)
st.markdown(chips, unsafe_allow_html=True)
st.divider()
col1, col2, col3 = st.columns(3)
with col1:
_render_stat_card("Groups Joined", profile.get("groups_joined", 0))
with col2:
_render_stat_card("Study Hours", profile.get("study_hours", 0))
with col3:
_render_stat_card("Day Streak", profile.get("day_streak", 0))
st.divider()
header_col, button_col = st.columns([4, 1])
with header_col:
st.markdown("**Weekly Availability**")
with button_col:
st.button("Update Schedule", use_container_width=True, key="update_schedule")
availability = profile.get("weekly_availability", [])
if availability:
cols = st.columns(len(availability))
for col, day_data in zip(cols, availability):
slots = day_data.get("slots", [])
slot_html = "".join(
[f"<div class='availability-slot'>{escape(str(slot))}</div>" for slot in slots]
)
with col:
st.markdown(
dedent(
f"""
<div class="availability-card">
<div class="availability-day">{escape(str(day_data.get('day', '')))}</div>
{slot_html}
</div>
"""
).strip(),
unsafe_allow_html=True,
)
def display_recent_workouts(workouts_list):
pass
def create_match_card(major, title, match_pct, keywords, time, location, members):
tags = ""
if keywords:
tags = "".join(
[f"<span class='tag-chip'>{escape(str(word))}</span>" for word in keywords]
)
html = f"""
<div class="glass-card">
<div class="card-header">
<div>
<div class="card-subject">{escape(str(major))}</div>
<div class="card-title">{escape(str(title))}</div>
</div>
<div class="card-meta">
<div class="meta-pill">{escape(str(match_pct))}% match</div>
</div>
</div>
<div style="margin-top:0.8rem;">{tags}</div>
<div class="card-inline-meta">🕒 {escape(str(time))}</div>
<div class="card-inline-meta">📍 {escape(str(location))}</div>
<div class="card-inline-meta">👥 {escape(str(members))}</div>
</div>
"""
st.markdown(html, unsafe_allow_html=True)
st.button(
"Request to Join",
key=f"btn_{str(title).replace(' ', '_')}",
use_container_width=True,
)
def display_genai_advice(user_id, user_interests) -> None:
st.markdown('<div class="page-title">AI Recommendations</div>', unsafe_allow_html=True)
st.markdown(
'<div class="page-subtitle">Curated matches based on your schedule, interests, and study style.</div>',
unsafe_allow_html=True,
)
top_col, action_col = st.columns([4, 1], vertical_alignment="center")
with top_col:
st.markdown("**AI-Powered Matches**")
with action_col:
st.button("Adjust Preferences", use_container_width=True, key="adjust_prefs")
header_col, sort_col = st.columns([3, 1], vertical_alignment="bottom")
with header_col:
st.markdown("### Top Matches")
with sort_col:
st.selectbox(
"Sort by:",
options=["Match %", "Recently Active", "Shared Classes"],
index=0,
label_visibility="collapsed",
key="sort_matches",
)
# Unique cache key based on user_id and interests
cache_key = f"matches_{user_id}_{str(user_interests)}"
# Only generate if cache key is missing or changed
if "matches_cache_key" not in st.session_state or st.session_state.matches_cache_key != cache_key:
with st.spinner("Finding your perfect study groups..."):
st.session_state.matches_data = get_final_recommendations(user_id, user_interests)
st.session_state.matches_cache_key = cache_key
matches_data = st.session_state.matches_data
if not matches_data:
st.info("No recommendations found right now.")
return
cards_per_row = 2
for i in range(0, len(matches_data), cards_per_row):
row_groups = matches_data[i : i + cards_per_row]
cols = st.columns(len(row_groups))
for col, group in zip(cols, row_groups):
with col:
create_match_card(**group)
def display_my_groups_page(my_groups: List[Dict]) -> None:
st.markdown('<div class="page-title">My Study Groups</div>', unsafe_allow_html=True)
st.markdown(
'<div class="page-subtitle">Manage your active groups and discover new study partners.</div>',
unsafe_allow_html=True,
)
cards_per_row = 2
join_card_rendered = False
items = list(my_groups) + ["__JOIN_CARD__"]
for i in range(0, len(items), cards_per_row):
row_items = items[i : i + cards_per_row]
cols = st.columns(len(row_items))
for col, item in zip(cols, row_items):
with col:
if item == "__JOIN_CARD__":
if join_card_rendered:
continue
join_card_rendered = True
st.markdown(
dedent(
"""
<div class="glass-card">
<div class="my-group-row">
<div class="my-group-icon">+</div>
<div class="my-group-content">
<div class="my-group-title">Join Another Group</div>
<div class="muted-text">Find new study partners and add new courses.</div>
</div>
</div>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
if st.button(
"Add New Course",
key="mg_add_course",
use_container_width=True,
):
_go_to_page("Explore Groups")
if st.button(
"Discover Groups",
key="mg_discover",
use_container_width=True,
):
_go_to_page("Explore Groups")
else:
g = item
st.markdown(
dedent(
f"""
<div class="glass-card">
<div class="my-group-row">
<div class="my-group-icon">{escape(str(g.get("icon", "📚")))}</div>
<div class="my-group-content">
<div class="my-group-title">{escape(str(g.get("title", "")))}</div>
<div class="muted-text">{escape(str(g.get("days", "")))} · {escape(str(g.get("mode", "")))}</div>
<div class="card-inline-meta">📍 {escape(str(g.get("location", "")))}</div>
<div class="card-inline-meta">👥 {escape(str(g.get("members", "")))}</div>
</div>
</div>
</div>
"""
).strip(),
unsafe_allow_html=True,
)
st.button(
"Group Chat",
key=f"mg_chat_{g.get('title', '')}",
use_container_width=True,
)
# Account Settings Module
def display_account_settings_page(user_id):
"""
# FETCH THE DATA from Bigquery to get the real id and email
"""
if f"account_cache_{user_id}" not in st.session_state:
data = get_user_identity_data(user_id)
# If no data, use a clean "Guest" default
if not data:
data = {"id": "No data", "email": "pending@fisk.edu", "is_guest": True}
st.session_state[f"account_cache_{user_id}"] = data
user_info = st.session_state[f"account_cache_{user_id}"]
st.markdown(
"""
<div class="section-toolbar">
<div class="page-title">Account & Security</div>
<div class="page-subtitle">
Manage your private information, security preferences, and account identity.
</div>
</div>
""",
unsafe_allow_html=True,
)
st.divider()
# 3. MAIN CONTENT
col1, col2 = st.columns([1, 1], gap="large")
with col1:
# st.markdown('<div class="glass-card">', unsafe_allow_html=True)
st.subheader("Personal Information")
# We use the data fetched from BigQuery here
st.text_input("User ID", value=user_info.get('id', user_id), disabled=True, key="set_uid")
st.text_input("Email Address", value=user_info.get('email', ""), disabled=True, key="set_email")
st.markdown('<div style="margin-top: 1.5rem;"></div>', unsafe_allow_html=True)
if st.button("Edit Profile Bio", use_container_width=True):
st.info("Redirecting to profile editor...")
st.markdown('</div>', unsafe_allow_html=True)
with col2:
# st.markdown('<div class="glass-card">', unsafe_allow_html=True)
st.subheader("Security & Privacy")
st.write("**Two-Factor Authentication (2FA)**")
st.markdown('<span class="meta-pill">Status: Enabled</span>', unsafe_allow_html=True)
if st.button("Manage 2FA Settings", use_container_width=True):
st.info("2FA configuration options would appear here.")
st.markdown('</div>', unsafe_allow_html=True)
# st.markdown('<div style="margin-top: 0.1rem;"></div>', unsafe_allow_html=True)
st.write("**Password Management**")
st.caption("Last changed: 3 months ago")
if st.button("Change Password", use_container_width=True):
st.session_state.changing_password = True