Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,177 +1,277 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
| 3 |
-
import fitz
|
| 4 |
-
import docx
|
| 5 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
from openai import OpenAI
|
| 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 |
-
if
|
| 157 |
-
|
| 158 |
-
return "
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import annotations
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import List, Dict, Any
|
| 8 |
+
import markdown
|
| 9 |
import gradio as gr
|
| 10 |
from openai import OpenAI
|
| 11 |
+
|
| 12 |
+
# --- 1. BACKEND LOGIC & CONFIG (from your first script) ---
|
| 13 |
+
|
| 14 |
+
# --- LLM Configuration ---
|
| 15 |
+
MODEL_NAME = "openai/gpt-oss-120b"
|
| 16 |
+
DEEPINFRA_API_KEY = "kPEm10rrnxXrCf0TuB6Xcd7Y7lp3YgKa" # Replace with your key if needed
|
| 17 |
+
BASE_URL = "https://api.deepinfra.com/v1/openai"
|
| 18 |
+
|
| 19 |
+
if not DEEPINFRA_API_KEY:
|
| 20 |
+
print("[WARN] DEEPINFRA_API_KEY is not set. The chatbot will likely fail.")
|
| 21 |
+
|
| 22 |
+
client = OpenAI(api_key=DEEPINFRA_API_KEY, base_url=BASE_URL)
|
| 23 |
+
|
| 24 |
+
# --- Language & Routing Configuration ---
|
| 25 |
+
ARABIC_RANGE = (
|
| 26 |
+
(0x0600, 0x06FF), (0x0750, 0x077F), (0x08A0, 0x08FF),
|
| 27 |
+
(0xFB50, 0xFDFF), (0xFE70, 0xFEFF), (0x1EE00, 0x1EEFF)
|
| 28 |
)
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class Route:
|
| 32 |
+
audience: str
|
| 33 |
+
intent: str
|
| 34 |
+
language: str
|
| 35 |
+
|
| 36 |
+
KB: Dict[str, Dict[str, str]] = {
|
| 37 |
+
"student_registration": {
|
| 38 |
+
"en": (
|
| 39 |
+
"**How to register / create an account (Student)**\n\n"
|
| 40 |
+
"1. Go to the EduNatives site and choose Sign Up.\n"
|
| 41 |
+
"2. Use your university email if possible and verify it.\n"
|
| 42 |
+
"3. Complete your profile (major, skills, interests).\n"
|
| 43 |
+
"4. Enable notifications for internships/scholarships."
|
| 44 |
+
),
|
| 45 |
+
"ar": (
|
| 46 |
+
"**طريقة التسجيل وإنشاء حساب (طلاب)**\n\n"
|
| 47 |
+
"١. اذهب إلى موقع EduNatives واختر Sign Up.\n"
|
| 48 |
+
"٢. يفضل استخدام إيميل الجامعة وتأكيده.\n"
|
| 49 |
+
"٣. أكمل ملفك الشخصي (التخصص، المهارات، الاهتمامات).\n"
|
| 50 |
+
"٤. فعّل التنبيهات لفرص التدريب والمنح."
|
| 51 |
+
),
|
| 52 |
+
},
|
| 53 |
+
"student_internships": {
|
| 54 |
+
"en": (
|
| 55 |
+
"**Finding internships & scholarships**\n\n"
|
| 56 |
+
"- Use the search filters: field, location, duration, paid/unpaid.\n"
|
| 57 |
+
"- Follow companies and set up alerts for new opportunities.\n"
|
| 58 |
+
"- Keep your profile and resume updated."
|
| 59 |
+
),
|
| 60 |
+
"ar": (
|
| 61 |
+
"**كيفية العثور على تدريب أو منحة**\n\n"
|
| 62 |
+
"- استخدم فلاتر البحث: التخصص، المكان، المدة، مدفوع/غير مدفوع.\n"
|
| 63 |
+
"- تابع الشركات وفعّل التنبيهات للفرص الجديدة.\n"
|
| 64 |
+
"- حافظ على تحديث ملفك الشخصي وسيرتك الذاتية."
|
| 65 |
+
),
|
| 66 |
+
},
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
KEYS = {
|
| 70 |
+
"student_registration": [
|
| 71 |
+
"register", "sign up", "signup", "create account", "account",
|
| 72 |
+
"تسجيل", "انشاء", "إنشاء", "حساب", "اعمل حساب", "سجل"
|
| 73 |
+
],
|
| 74 |
+
"student_internships": [
|
| 75 |
+
"intern", "internship", "training", "scholar", "scholarship", "grant", "opportunity",
|
| 76 |
+
"تدريب", "تدريبي", "منحة", "منح", "فرصة", "فرص", "انترنشيب"
|
| 77 |
+
],
|
| 78 |
+
"student_mentors": [
|
| 79 |
+
"mentor", "advisor", "professor", "supervisor", "faculty", "connect",
|
| 80 |
+
"منتور", "مشرف", "دكتور", "أستاذ", "استاذ", "التواصل", "اكلم"
|
| 81 |
+
],
|
| 82 |
+
"university_publish": [
|
| 83 |
+
"publish", "paper", "research", "preprint", "conference", "event", "seminar", "webinar",
|
| 84 |
+
"نشر", "أبحاث", "ابحاث", "بحث", "مؤتمر", "فعالية", "فعاليات", "ندوة", "ورشة"
|
| 85 |
+
],
|
| 86 |
+
"university_connect": [
|
| 87 |
+
"students", "connect with students", "reach students", "collaborate",
|
| 88 |
+
"طلاب", "تواصل مع الطلاب", "التواصل مع الطلاب", "تعاون"
|
| 89 |
+
],
|
| 90 |
+
"company_post_jobs": [
|
| 91 |
+
"job", "jobs", "post job", "hiring", "hire", "internships", "graduate",
|
| 92 |
+
"وظيفة", "وظائف", "اعلان", "إعلان", "نشر وظيفة", "توظيف", "فرص تدريب", "خريجين"
|
| 93 |
+
],
|
| 94 |
+
"company_find_talent": [
|
| 95 |
+
"talent", "candidate", "recruit", "search", "find", "pipeline",
|
| 96 |
+
"موهبة", "مواهب", "مرشحين", "تعيين", "تجنيد", "ابحث", "دور على"
|
| 97 |
+
],
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
AUDIENCE_MAP = {
|
| 101 |
+
"student_registration": "student",
|
| 102 |
+
"student_internships": "student",
|
| 103 |
+
"student_mentors": "student",
|
| 104 |
+
"university_publish": "university",
|
| 105 |
+
"university_connect": "university",
|
| 106 |
+
"company_post_jobs": "company",
|
| 107 |
+
"company_find_talent": "company",
|
| 108 |
}
|
| 109 |
|
| 110 |
+
SYSTEM_PROMPT_BASE = (
|
| 111 |
+
"You are **EduNatives Assistant**, a helpful, friendly, and precise academic/career guide. "
|
| 112 |
+
"You serve three primary audiences: Students, Universities/Researchers, and Companies.\n\n"
|
| 113 |
+
"Goals by audience:\n"
|
| 114 |
+
"- Students: registration/account help; finding internships/scholarships; connecting with mentors or professors.\n"
|
| 115 |
+
"- Universities/Researchers: publish research or announce events; connect/collaborate with students.\n"
|
| 116 |
+
"- Companies: post jobs/internships/graduate roles; discover student talent.\n\n"
|
| 117 |
+
"General rules:\n"
|
| 118 |
+
"- Reply in the user's language (Arabic if the user writes Arabic; otherwise English).\n"
|
| 119 |
+
"- Be concise, step-by-step, and action-oriented (lists, bullets, checklists).\n"
|
| 120 |
+
"- If information is unavailable, state that clearly and suggest the next best step.\n"
|
| 121 |
+
)
|
| 122 |
+
CONTEXT_INJECT_TEMPLATE = (
|
| 123 |
+
"Context to guide your answer (do not repeat verbatim):\n"
|
| 124 |
+
"- Audience: {audience}\n- Intent: {intent}\n- Extra hints: Keep it practical for this audience."
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# --- Core Functions ---
|
| 128 |
+
def is_arabic(text: str) -> bool:
|
| 129 |
+
for ch in text:
|
| 130 |
+
code = ord(ch)
|
| 131 |
+
for a, b in ARABIC_RANGE:
|
| 132 |
+
if a <= code <= b:
|
| 133 |
+
return True
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
def route_intent(text: str, forced_audience: str | None = None) -> Route:
|
| 137 |
+
lang = "ar" if is_arabic(text) else "en"
|
| 138 |
+
match_label = None
|
| 139 |
+
text_l = text.lower()
|
| 140 |
+
for label, kws in KEYS.items():
|
| 141 |
+
for kw in kws:
|
| 142 |
+
if kw in text_l:
|
| 143 |
+
match_label = label
|
| 144 |
+
break
|
| 145 |
+
if match_label:
|
| 146 |
+
break
|
| 147 |
+
|
| 148 |
+
if match_label is None:
|
| 149 |
+
audience = forced_audience if forced_audience else "general"
|
| 150 |
+
return Route(audience=audience, intent="general", language=lang)
|
| 151 |
+
|
| 152 |
+
audience = AUDIENCE_MAP.get(match_label, "general")
|
| 153 |
+
if forced_audience and forced_audience in {"student", "university", "company"}:
|
| 154 |
+
audience = forced_audience
|
| 155 |
+
|
| 156 |
+
return Route(audience=audience, intent=match_label, language=lang)
|
| 157 |
+
|
| 158 |
+
def call_llm(user_message: str, history: List[Dict[str, str]], route: Route) -> str:
|
| 159 |
+
messages: List[Dict[str, str]] = [
|
| 160 |
+
{"role": "system", "content": SYSTEM_PROMPT_BASE},
|
| 161 |
+
{"role": "system", "content": CONTEXT_INJECT_TEMPLATE.format(audience=route.audience, intent=route.intent)},
|
| 162 |
+
]
|
| 163 |
+
MAX_TURNS = 3
|
| 164 |
+
trimmed_history = history[-MAX_TURNS*2:]
|
| 165 |
+
messages.extend(trimmed_history)
|
| 166 |
+
messages.append({"role": "user", "content": user_message})
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
resp = client.chat.completions.create(
|
| 170 |
+
model=MODEL_NAME,
|
| 171 |
+
messages=messages,
|
| 172 |
+
temperature=0.6,
|
| 173 |
+
top_p=0.9,
|
| 174 |
+
max_tokens=800,
|
| 175 |
+
)
|
| 176 |
+
return resp.choices[0].message.content or ""
|
| 177 |
+
except Exception as e:
|
| 178 |
+
print(f"[ERROR] LLM call failed: {e}")
|
| 179 |
+
return ""
|
| 180 |
+
|
| 181 |
+
def kb_fallback(route: Route) -> str:
|
| 182 |
+
if route.intent in KB:
|
| 183 |
+
block = KB[route.intent]
|
| 184 |
+
return block.get(route.language, block.get("en", ""))
|
| 185 |
+
if route.language == "ar":
|
| 186 |
+
return (
|
| 187 |
+
"عذراً، لم أجد معلومات كافية. يرجى توضيح طلبك أو السؤال عن أحد المواضيع التالية: "
|
| 188 |
+
"(تسجيل، تدريب/منح، مشرفين، نشر أبحاث، وظائف)."
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
return (
|
| 192 |
+
"I couldn't find enough info. Please clarify your request or ask about "
|
| 193 |
+
"registration, internships/scholarships, mentors, publishing research, or jobs."
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
with gr.Blocks(css="""
|
| 199 |
+
.chatbot {height: 500px; overflow: auto;}
|
| 200 |
+
.user-bubble {background-color: #DCF8C6; padding: 10px; border-radius: 12px; max-width: 75%; float: right; clear: both; margin: 5px; word-wrap: break-word;}
|
| 201 |
+
.bot-bubble {background-color: #F1F0F0; padding: 10px; border-radius: 12px; max-width: 75%; float: left; clear: both; margin: 5px; word-wrap: break-word;}
|
| 202 |
+
.chatbox-container {display: flex; gap: 8px; margin-top: 10px;}
|
| 203 |
+
/* Basic styling for tables inside the bot bubble */
|
| 204 |
+
.bot-bubble table {border-collapse: collapse; width: 100%;}
|
| 205 |
+
.bot-bubble th, .bot-bubble td {border: 1px solid #ddd; padding: 8px; text-align: left;}
|
| 206 |
+
.bot-bubble th {background-color: #e9e9e9;}
|
| 207 |
+
""") as demo:
|
| 208 |
+
|
| 209 |
+
gr.Markdown("# 🤖 EduNatives Assistant\nYour smart, bilingual guide for academic and career opportunities.")
|
| 210 |
+
|
| 211 |
+
with gr.Row():
|
| 212 |
+
audience_dd = gr.Dropdown(
|
| 213 |
+
label="Audience",
|
| 214 |
+
choices=["Auto", "Student", "University-Research", "Company"],
|
| 215 |
+
value="Auto",
|
| 216 |
+
interactive=True,
|
| 217 |
+
info="Select your role. 'Auto' detects it from your message."
|
| 218 |
+
)
|
| 219 |
+
clear_btn = gr.Button("🧹 Clear Chat")
|
| 220 |
+
|
| 221 |
+
status = gr.Markdown("Status: Ready.")
|
| 222 |
+
chatbot_html = gr.HTML("<div class='chatbot' id='chatbot'></div>")
|
| 223 |
+
|
| 224 |
+
chat_history_state = gr.State([])
|
| 225 |
+
|
| 226 |
+
with gr.Row(elem_classes="chatbox-container"):
|
| 227 |
+
msg = gr.Textbox(
|
| 228 |
+
placeholder="اكتب سؤالك هنا... / Ask your question here...",
|
| 229 |
+
lines=2,
|
| 230 |
+
scale=4,
|
| 231 |
+
autofocus=True,
|
| 232 |
+
)
|
| 233 |
+
send_btn = gr.Button("➡️ Send", scale=1, variant="primary")
|
| 234 |
+
|
| 235 |
+
def format_chat_html(history: List[Dict[str, str]]) -> str:
|
| 236 |
+
html = "<div class='chatbot'>"
|
| 237 |
+
for message in history:
|
| 238 |
+
role = message["role"]
|
| 239 |
+
content = message["content"]
|
| 240 |
+
if role == "user":
|
| 241 |
+
# User messages are plain text, no need to render markdown
|
| 242 |
+
html += f"<div class='user-bubble'>{content}</div>"
|
| 243 |
+
elif role == "assistant":
|
| 244 |
+
# Convert bot's markdown response to HTML
|
| 245 |
+
html_content = markdown.markdown(content, extensions=['tables'])
|
| 246 |
+
html += f"<div class='bot-bubble'>{html_content}</div>"
|
| 247 |
+
html += "</div>"
|
| 248 |
+
return html
|
| 249 |
+
|
| 250 |
+
# The 'respond' and 'clear_chat' functions remain exactly the same
|
| 251 |
+
def respond(user_text: str, history: List[Dict[str, str]], audience_choice: str):
|
| 252 |
+
if not user_text.strip():
|
| 253 |
+
return "", format_chat_html(history), history, "Status: Please type a message."
|
| 254 |
+
forced = {
|
| 255 |
+
"Student": "student",
|
| 256 |
+
"University-Research": "university",
|
| 257 |
+
"Company": "company"
|
| 258 |
+
}.get(audience_choice)
|
| 259 |
+
route = route_intent(user_text, forced_audience=forced)
|
| 260 |
+
status_text = f"**Audience**: {route.audience} | **Intent**: {route.intent} | **Lang**: {route.language.upper()}"
|
| 261 |
+
answer = call_llm(user_text, history, route)
|
| 262 |
+
if not answer:
|
| 263 |
+
answer = kb_fallback(route)
|
| 264 |
+
history.append({"role": "user", "content": user_text})
|
| 265 |
+
history.append({"role": "assistant", "content": answer})
|
| 266 |
+
updated_html = format_chat_html(history)
|
| 267 |
+
return "", updated_html, history, status_text
|
| 268 |
+
|
| 269 |
+
def clear_chat():
|
| 270 |
+
return "", [], "Status: Ready."
|
| 271 |
+
|
| 272 |
+
send_btn.click(respond, [msg, chat_history_state, audience_dd], [msg, chatbot_html, chat_history_state, status], queue=True)
|
| 273 |
+
msg.submit(respond, [msg, chat_history_state, audience_dd], [msg, chatbot_html, chat_history_state, status], queue=True)
|
| 274 |
+
clear_btn.click(clear_chat, outputs=[chatbot_html, chat_history_state, status], queue=False)
|
| 275 |
+
|
| 276 |
+
if __name__ == "__main__":
|
| 277 |
+
demo.launch()
|