import streamlit as st
from datetime import datetime, timezone, timedelta
from supabase_utils import init_supabase_client, get_user_profile
import time
# Thiết lập page config
st.set_page_config(
page_title="Hồ sơ Học tập - Gia sư Toán AI",
page_icon="👤",
layout="wide"
)
def display_header(user_email: str, user_id: str, profile: dict):
"""
Hiển thị header với thông tin người dùng
"""
st.markdown("""
👤 Hồ sơ Học tập của bạn
Theo dõi tiến trình và điểm yếu cần cải thiện
""", unsafe_allow_html=True)
# Thông tin người dùng trong cards
col1, col2 = st.columns(2)
with col1:
st.markdown(f"""
""", unsafe_allow_html=True)
with col2:
updated_time = "Chưa có dữ liệu"
if profile.get("updated_at"):
try:
updated_at_str = str(profile["updated_at"])
updated_dt = None
try:
if 'T' in updated_at_str and '+00:00' in updated_at_str:
if '.' in updated_at_str:
dt_part, tz_part = updated_at_str.split('+')
if '.' in dt_part:
main_dt, microsec = dt_part.split('.')
microsec = microsec[:6].ljust(6, '0')
clean_dt_str = f"{main_dt}.{microsec}+{tz_part}"
else:
clean_dt_str = f"{dt_part}+{tz_part}"
else:
clean_dt_str = updated_at_str
updated_dt = datetime.fromisoformat(clean_dt_str)
elif updated_at_str.endswith('Z'):
updated_dt = datetime.fromisoformat(updated_at_str.replace("Z", "+00:00"))
elif '+' in updated_at_str and ':' in updated_at_str[-6:]:
updated_dt = datetime.fromisoformat(updated_at_str)
elif '+' in updated_at_str:
updated_dt = datetime.strptime(updated_at_str.split('+')[0], '%Y-%m-%d %H:%M:%S')
else:
updated_dt = datetime.fromisoformat(updated_at_str)
except ValueError as ve:
print(f"DEBUG: [Profile] ISO parsing failed: {ve}")
try:
# Format: "2024-01-01 12:00:00"
updated_dt = datetime.strptime(updated_at_str, '%Y-%m-%d %H:%M:%S')
except ValueError:
# Format: "2024-01-01T12:00:00"
updated_dt = datetime.strptime(updated_at_str, '%Y-%m-%dT%H:%M:%S')
if updated_dt:
# Chuyển đổi từ UTC sang múi giờ Việt Nam (UTC+7)
if updated_dt.tzinfo is not None:
# Nếu có timezone info, chuyển sang UTC+7
vietnam_tz = timezone(timedelta(hours=7))
vietnam_time = updated_dt.astimezone(vietnam_tz)
updated_time = vietnam_time.strftime('%d/%m/%Y %H:%M:%S')
else:
# Nếu không có timezone info, giả sử đây là UTC và thêm 7 giờ
vietnam_time = updated_dt + timedelta(hours=7)
updated_time = vietnam_time.strftime('%d/%m/%Y %H:%M:%S')
print(f"DEBUG: [Profile] Original UTC: {updated_dt}")
print(f"DEBUG: [Profile] Vietnam time: {updated_time}")
else:
updated_time = "Không thể parse"
except Exception as e:
print(f"DEBUG: [Profile] Failed to parse updated_at: {e}")
# Fallback: Hiển thị raw value
updated_time = f"Raw: {str(profile['updated_at'])[:19]}"
st.markdown(f"""
🕒
Cập nhật lần cuối
{updated_time}
""", unsafe_allow_html=True)
def display_weakness_and_stats(profile: dict):
"""
Hiển thị điểm yếu gần nhất và thống kê
"""
col1, col2 = st.columns(2)
with col1:
st.markdown("## 🎯 Điểm yếu gần nhất")
if profile.get("last_weakness"):
st.markdown(f"""
{profile['last_weakness']}
💡 Hệ thống sẽ ưu tiên tạo bài tập về chủ đề này
""", unsafe_allow_html=True)
else:
st.markdown("""
Chưa có dữ liệu phân tích
Hãy chat với gia sư AI để hệ thống có thể phân tích điểm yếu của bạn!
""", unsafe_allow_html=True)
with col2:
st.markdown("## 📊 Thống kê tổng quan")
misunderstood_count = len(profile.get("misunderstood_concepts", []))
# Tạo màu động dựa trên số lượng
if misunderstood_count == 0:
color_gradient = "linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%)"
text_color = "#2F4F4F"
icon = "🎉"
elif misunderstood_count <= 3:
color_gradient = "linear-gradient(135deg, #f093fb 0%, #f5576c 100%)"
text_color = "#8B0000"
icon = "⚠️"
else:
color_gradient = "linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%)"
text_color = "#ffffff"
icon = "🔥"
st.markdown(f"""
{icon}
Khái niệm cần cải thiện
{misunderstood_count}
{'Tuyệt vời!' if misunderstood_count == 0 else 'Cần cải thiện' if misunderstood_count <= 3 else 'Cần tập trung cao'}
""", unsafe_allow_html=True)
def display_concepts_list(profile: dict):
"""
Hiển thị danh sách khái niệm cần cải thiện
"""
st.markdown("## 📝 Danh sách khái niệm cần cải thiện")
misunderstood_concepts = profile.get("misunderstood_concepts", [])
if misunderstood_concepts:
st.markdown("""
📚 Dưới đây là những khái niệm mà hệ thống phát hiện bạn còn gặp khó khăn
""", unsafe_allow_html=True)
# Hiển thị concepts trong grid
cols = st.columns(2)
for i, concept in enumerate(misunderstood_concepts):
col_idx = i % 2
with cols[col_idx]:
# Màu sắc xoay vòng cho từng concept
colors = [
"#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4",
"#FECA57", "#FF9FF3", "#54a0ff", "#5f27cd"
]
color = colors[i % len(colors)]
st.markdown(f"""
""", unsafe_allow_html=True)
else:
st.markdown("""
🎉
Tuyệt vời! Chưa có khái niệm nào được đánh dấu là yếu.
Điều này có thể có nghĩa là:
• Bạn chưa chat đủ với gia sư AI để hệ thống phân tích
• Bạn đang làm rất tốt với các bài toán đã thảo luận
💡 Gợi ý: Hãy tiếp tục chat và hỏi nhiều câu hỏi toán học để gia sư AI có thể đưa ra các phân tích và đề xuất phù hợp nhé!
""", unsafe_allow_html=True)
def display_learning_suggestions(misunderstood_concepts: list):
"""
Hiển thị gợi ý học tập
"""
if misunderstood_concepts:
st.markdown("## 🎯 Gợi ý học tập")
suggestions = [
{
"icon": "✅",
"title": "Tạo bài tập luyện tập",
"description": "Yêu cầu gia sư AI tạo bài tập luyện tập cụ thể về các khái niệm yếu",
"color": "#00b894"
},
{
"icon": "🧠",
"title": "Giải thích lại khái niệm",
"description": "Hỏi gia sư AI giải thích lại các khái niệm khó hiểu bằng cách khác",
"color": "#6c5ce7"
},
{
"icon": "📹",
"title": "Xem video bài giảng",
"description": "Tham khảo các video bài giảng được đề xuất theo level phù hợp",
"color": "#fd79a8"
},
{
"icon": "📅",
"title": "Luyện tập đều đặn",
"description": "Dành 15-30 phút mỗi ngày để thực hành những khái niệm yếu",
"color": "#fdcb6e"
}
]
cols = st.columns(2)
for i, suggestion in enumerate(suggestions):
col_idx = i % 2
with cols[col_idx]:
st.markdown(f"""
{suggestion['icon']}
{suggestion['title']}
{suggestion['description']}
""", unsafe_allow_html=True)
# Cách sử dụng
st.markdown("""
💬 Cách sử dụng
Quay lại trang chính và nói với gia sư AI:
"Tôi muốn luyện tập" hoặc
"Cho tôi bài tập về [tên chủ đề]"
""", unsafe_allow_html=True)
def display_footer():
"""
Hiển thị footer
"""
st.markdown("---")
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
if st.button("🔄 Làm mới dữ liệu", type="primary", use_container_width=True):
st.rerun()
st.markdown("""
💡 Về hồ sơ học tập
Dữ liệu được cập nhật tự động khi bạn chat với gia sư AI.
Hồ sơ này giúp cá nhân hóa trải nghiệm học tập của bạn để đạt hiệu quả tốt nhất.
""", unsafe_allow_html=True)
def display_login_required():
"""
Hiển thị thông báo cần đăng nhập
"""
st.markdown("""
⚠️
Bạn cần đăng nhập để xem hồ sơ học tập
👈 Vui lòng đăng nhập ở sidebar của trang chính
""", unsafe_allow_html=True)
def main():
"""
Hàm chính của trang Hồ sơ học tập
"""
# Kiểm tra xem người dùng đã đăng nhập chưa
if "user" not in st.session_state or st.session_state.user is None:
display_login_required()
st.stop()
# Khởi tạo Supabase client
supabase = init_supabase_client()
# Lấy thông tin người dùng hiện tại
user = st.session_state.user
user_email = user.email
user_id = user.id
# Lấy hồ sơ học tập
with st.spinner("Đang tải hồ sơ học tập..."):
profile = get_user_profile(supabase, user_id)
# Kiểm tra xem profile có dữ liệu không
if not profile:
st.error("Không thể tải hoặc tạo hồ sơ của bạn. Vui lòng thử lại.")
st.stop()
# Hiển thị header
display_header(user_email, user_id, profile)
# Hiển thị điểm yếu và thống kê
display_weakness_and_stats(profile)
st.markdown("---")
# Hiển thị danh sách khái niệm
display_concepts_list(profile)
# Hiển thị gợi ý học tập
misunderstood_concepts = profile.get("misunderstood_concepts", [])
display_learning_suggestions(misunderstood_concepts)
# Hiển thị footer
display_footer()
if __name__ == "__main__":
main()