import streamlit as st
import requests
import uuid
import re
# =========================
# ⚙️ CONFIGURATION
# =========================
st.set_page_config(
page_title="UNIQ AI Assistant",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
BASE_URL = "https://uniq-project-ai-uniq-backendd.hf.space"
CHAT_URL = f"{BASE_URL}/chat"
CALC_URL = f"{BASE_URL}/calculate-gpa"
PLAN_URL = f"{BASE_URL}/plan-gpa"
# =========================
# 🎨 GLOBAL CSS
# =========================
st.markdown("""
""", unsafe_allow_html=True)
# =========================
# 👤 USERS
# =========================
DB_USERS = {
"مستخدم عشوائي (Guest)": "random",
"أحمد (user_01)": "user_01",
"كنزي (user_02)": "user_02",
"مريم (user_04)": "user_04",
}
# =========================
# 💡 SUGGESTIONS
# =========================
SUGGESTIONS = [
"اسجل Convex Optimization ولا Bayesian Statistics؟",
"عايز احسب الـ GPA",
"عايز أوصل GPA 3.5 وأنا دلوقتي 2",
"الـ GPA عبارة عن ايه؟",
"ايه ال prerequisite لـ Data Structure؟",
"رشحلي مواد سهلة الترم الجاي",
]
# =========================
# 🧠 SESSION STATE
# =========================
def _init_state():
if "selected_user_label" not in st.session_state:
st.session_state.selected_user_label = "مستخدم عشوائي (Guest)"
st.session_state.user_id = str(uuid.uuid4())
if "messages" not in st.session_state:
st.session_state.messages = []
if "gpa_rows" not in st.session_state:
st.session_state.gpa_rows = 1
if "current_intent" not in st.session_state:
st.session_state.current_intent = None
if "last_bot_answer" not in st.session_state:
st.session_state.last_bot_answer = ""
if "pending_prompt" not in st.session_state:
st.session_state.pending_prompt = None
if "calc_result" not in st.session_state:
st.session_state.calc_result = None
if "plan_result" not in st.session_state:
st.session_state.plan_result = None
if "invalid_grades" not in st.session_state:
st.session_state.invalid_grades = []
_init_state()
# =========================
# 🛠️ HELPER: build gpa_calc result bubble HTML
# =========================
def _build_calc_bubble(gpa_val: float) -> str:
return f"""
{gpa_val}
📊 المعدل التراكمي المحسوب
"""
# =========================
# 🛠️ HELPER: build gpa_plan result bubble HTML
# =========================
def _build_plan_bubble(pr: dict) -> str:
if not pr.get("possible"):
return """
❌ صعب توصل للمعدل المطلوب بالساعات المتبقية
"""
grades_html = "".join(
f''
f'{m["hours"]} ساعات'
f'{m["grade"]}'
f'
'
for m in (pr.get("min_grades") or [])
)
return f"""
{pr["required_avg_gpa"]}
🎯 المعدل الفصلي المطلوب لتحقيق هدفك
أقل التقديرات المطلوبة لكل ساعة
{grades_html}
"""
# =========================
# ⚙️ SIDEBAR
# =========================
with st.sidebar:
st.markdown("""
""", unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
selected_label = st.selectbox(
"user_select",
options=list(DB_USERS.keys()),
index=list(DB_USERS.keys()).index(st.session_state.selected_user_label),
label_visibility="collapsed",
)
if selected_label != st.session_state.selected_user_label:
st.session_state.selected_user_label = selected_label
st.session_state.user_id = (
str(uuid.uuid4())
if DB_USERS[selected_label] == "random"
else DB_USERS[selected_label]
)
st.session_state.messages = []
st.session_state.current_intent = None
st.session_state.calc_result = None
st.session_state.plan_result = None
st.session_state.invalid_grades = []
st.rerun()
st.markdown(f"""
🆔 User ID
{st.session_state.user_id}
""", unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
if st.button("🗑️ مسح المحادثة", use_container_width=True):
st.session_state.messages = []
st.session_state.current_intent = None
st.session_state.gpa_rows = 1
st.session_state.calc_result = None
st.session_state.plan_result = None
st.session_state.invalid_grades = []
st.rerun()
# =========================
# 🤖 TOP HEADER
# =========================
st.markdown("""
""", unsafe_allow_html=True)
st.markdown("", unsafe_allow_html=True)
# =========================
# 💬 CHAT HISTORY
# =========================
for msg in st.session_state.messages:
if msg["role"] == "user":
st.markdown(f"""
""", unsafe_allow_html=True)
elif msg["role"] == "assistant":
st.markdown(f"""
""", unsafe_allow_html=True)
elif msg["role"] == "result":
# ✅ نتيجة الـ GPA تظهر كبابل bot ثابت في الشات
st.markdown(f"""
""", unsafe_allow_html=True)
# =========================
# 💡 SUGGESTIONS (empty state)
# =========================
if len(st.session_state.messages) == 0:
st.markdown('💡 اقتراحات سريعة
', unsafe_allow_html=True)
col_a, col_b = st.columns(2)
for i, sug in enumerate(SUGGESTIONS):
target = col_a if i % 2 == 0 else col_b
with target:
st.markdown('', unsafe_allow_html=True)
if st.button(sug, key=f"sug_{i}", use_container_width=True):
st.session_state.pending_prompt = sug
st.rerun()
st.markdown('
', unsafe_allow_html=True)
# =========================
# 🎯 GPA CALCULATOR PANEL
# =========================
if st.session_state.current_intent == "gpa_calc":
with st.expander("🧮 GPA Calculator", expanded=True):
st.info(st.session_state.last_bot_answer or "أدخل درجاتك لحساب المعدل")
subjects_data = []
for i in range(st.session_state.gpa_rows):
c1, c2 = st.columns([3, 1])
with c1:
grade = st.text_input(
f"الدرجة / التقدير (مادة {i+1})",
key=f"grade_{i}"
)
with c2:
hours = st.selectbox(
"الساعات",
[1, 2, 3, 4],
index=2,
key=f"hours_{i}"
)
if grade:
subjects_data.append({"grade": grade, "credit_hours": hours})
st.markdown("", unsafe_allow_html=True)
btn_c1, btn_c2, btn_c3 = st.columns(3)
# ➕ ADD ROW
with btn_c1:
if st.button("➕ إضافة مادة", key="add_row"):
st.session_state.gpa_rows += 1
st.session_state.calc_result = None
st.rerun()
# 🧮 CALCULATE
with btn_c2:
if st.button("🧮 احسب الآن", key="calc_now", type="primary"):
valid_letters = [
"A+","A","A-","B+","B","B-",
"C+","C","C-","D+","D","F"
]
validated_subjects = []
error_found = False
st.session_state.invalid_grades = []
for i in range(st.session_state.gpa_rows):
grade_raw = st.session_state.get(f"grade_{i}", "").strip()
hours = st.session_state.get(f"hours_{i}", 3)
if grade_raw != "":
cleaned_grade = grade_raw.upper()
is_valid = False
if cleaned_grade in valid_letters:
is_valid = True
else:
try:
numeric_grade = float(cleaned_grade)
if 0 <= numeric_grade <= 100:
is_valid = True
except:
pass
if is_valid:
validated_subjects.append({
"grade": cleaned_grade,
"credit_hours": hours
})
else:
st.error(f"⚠️ القيمة '{grade_raw}' غير صحيحة!")
st.session_state.invalid_grades.append(i)
error_found = True
if error_found:
st.warning("❌ يوجد أخطاء في الدرجات، صححها أولاً.")
elif validated_subjects:
try:
res = requests.post(CALC_URL, json={"subjects": validated_subjects})
if res.status_code == 200:
gpa_val = res.json().get("gpa")
st.session_state.calc_result = gpa_val
# ✅ أضف النتيجة كـ "result" message في الشات
bubble_html = _build_calc_bubble(gpa_val)
st.session_state.messages.append({
"role": "result",
"content": bubble_html
})
# ✅ أغلق الفورم تلقائياً بعد الحساب
st.session_state.current_intent = None
st.session_state.gpa_rows = 1
st.session_state.invalid_grades = []
st.rerun()
else:
st.error(f"❌ خطأ في الحساب: {res.text}")
except Exception as e:
st.error(f"❌ تعذر الاتصال بالسيرفر: {e}")
else:
st.warning("⚠️ أدخل مادة واحدة على الأقل")
# ❌ CLOSE PANEL
with btn_c3:
if st.button("❌ إغلاق", key="calc_close"):
st.session_state.current_intent = None
st.session_state.gpa_rows = 1
st.session_state.calc_result = None
st.session_state.invalid_grades = []
st.rerun()
# =========================
# 🎯 GPA PLANNER PANEL
# =========================
elif st.session_state.current_intent == "gpa_plan":
with st.expander("🎯 GPA Planner", expanded=True):
st.info(st.session_state.last_bot_answer or "حدد بياناتك لحساب الخطة")
pc1, pc2 = st.columns(2)
with pc1:
target = st.number_input("المعدل المستهدف", value=3.5, min_value=0.0, max_value=4.0, step=0.1, key="plan_target")
done = st.number_input("الساعات المنجزة", value=60, min_value=0, key="plan_done")
with pc2:
current = st.number_input("المعدل الحالي", value=2.5, min_value=0.0, max_value=4.0, step=0.1, key="plan_current")
remain = st.number_input("الساعات المتبقية", value=15, min_value=1, key="plan_remain")
st.markdown("", unsafe_allow_html=True)
pb1, pb2 = st.columns(2)
with pb1:
if st.button("احسب الخطة", key="calc_plan", type="primary"):
try:
res = requests.post(PLAN_URL, json={
"target_gpa": target,
"current_gpa": current,
"completed_hours": done,
"remaining_hours": remain,
})
if res.status_code == 200:
pr = res.json()
# ✅ أضف النتيجة كـ "result" message في الشات
bubble_html = _build_plan_bubble(pr)
st.session_state.messages.append({
"role": "result",
"content": bubble_html
})
# ✅ أغلق الفورم تلقائياً بعد الحساب
st.session_state.current_intent = None
st.session_state.plan_result = None
st.rerun()
else:
st.error(f"❌ خطأ في الحساب: {res.text}")
except Exception as e:
st.error(f"❌ تعذر الاتصال بالسيرفر: {e}")
with pb2:
if st.button("❌ إغلاق الخطة", key="plan_close"):
st.session_state.current_intent = None
st.session_state.plan_result = None
st.rerun()
# =========================
# 💬 CHAT INPUT
# =========================
user_input = st.chat_input("اسأل UNIQ عن موادك أو معدلك أو خطتك الدراسية...")
if st.session_state.pending_prompt:
user_input = st.session_state.pending_prompt
st.session_state.pending_prompt = None
# =========================
# 🚀 SEND & RECEIVE
# =========================
if user_input:
st.session_state.messages.append({"role": "user", "content": user_input})
with st.spinner("🤖 جاري التفكير..."):
try:
res = requests.post(
CHAT_URL,
json={"user_id": st.session_state.user_id, "query": user_input},
timeout=30,
)
if res.status_code == 200:
data = res.json()
answer = data.get("answer", "")
intent = data.get("intent")
st.session_state.last_bot_answer = answer
blocked = any(
m in answer for m in ["متاحة فقط للطلاب", "للطلاب المسجلين"]
)
st.session_state.current_intent = None if blocked else intent
st.session_state.calc_result = None
st.session_state.plan_result = None
html = answer
html = html.replace("&", "&").replace("<", "<").replace(">", ">")
html = re.sub(r'\*\*(.+?)\*\*', r'\1', html)
html = re.sub(r'\*(.+?)\*', r'\1', html)
html = re.sub(r'`(.+?)`', r'\1', html)
html = re.sub(r'^### (.+)$', r'\1
', html, flags=re.M)
html = re.sub(r'^## (.+)$', r'\1
', html, flags=re.M)
html = re.sub(r'^# (.+)$', r'\1
', html, flags=re.M)
html = re.sub(r'^- (.+)$', r'\1', html, flags=re.M)
html = re.sub(r'(.*?)', r'', html, flags=re.S)
html = html.replace("\n", "
")
st.session_state.messages.append({"role": "assistant", "content": html})
else:
st.session_state.messages.append({
"role": "assistant",
"content": f"❌ خطأ من السيرفر: {res.status_code}"
})
except Exception as e:
st.session_state.messages.append({
"role": "assistant",
"content": "❌ تعذر الاتصال بالسيرفر"
})
st.rerun()