Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,6 +3,8 @@ import re
|
|
| 3 |
import time
|
| 4 |
from pathlib import Path
|
| 5 |
from typing import Optional, List, Dict, Any, Tuple
|
|
|
|
|
|
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
from openai import OpenAI
|
|
@@ -10,46 +12,45 @@ from openai import OpenAI
|
|
| 10 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 11 |
|
| 12 |
# ============================================================
|
| 13 |
-
#
|
| 14 |
# ============================================================
|
| 15 |
-
|
| 16 |
-
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
|
| 17 |
-
|
| 18 |
-
# Hard timeout for OpenAI calls (seconds). Prevents "processing forever".
|
| 19 |
-
OAI_TIMEOUT = float(os.getenv("OPENAI_TIMEOUT", "25"))
|
| 20 |
-
# Keep retries low; long retries make UI look "stuck".
|
| 21 |
-
OAI_MAX_RETRIES = int(os.getenv("OPENAI_MAX_RETRIES", "1"))
|
| 22 |
-
|
| 23 |
-
FALLBACK_EN = (
|
| 24 |
-
"I'm not certain from my current references. "
|
| 25 |
-
"Please contact admission@cheshireacademy.org | +1-203-439-7250."
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
# ============================================================
|
| 29 |
-
# Load Cheshire Academy sources (RAG)
|
| 30 |
-
# ============================================================
|
| 31 |
-
|
| 32 |
BASE_DIR = Path(__file__).parent
|
| 33 |
SOURCES_DIR = BASE_DIR / "sources"
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
def _strip_html(text: str) -> str:
|
| 37 |
text = re.sub(r"<[^>]+>", " ", text)
|
| 38 |
text = re.sub(r"\s+", " ", text)
|
| 39 |
return text.strip()
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
docs: List[Dict[str, str]] = []
|
|
|
|
|
|
|
|
|
|
| 44 |
if not SOURCES_DIR.exists():
|
| 45 |
print("WARNING: sources/ folder not found")
|
| 46 |
-
return docs
|
| 47 |
|
|
|
|
| 48 |
for path in SOURCES_DIR.rglob("*"):
|
| 49 |
if not path.is_file():
|
| 50 |
continue
|
| 51 |
if path.suffix.lower() not in {".txt", ".md", ".html", ".htm"}:
|
| 52 |
continue
|
|
|
|
| 53 |
try:
|
| 54 |
raw = path.read_text(encoding="utf-8", errors="ignore")
|
| 55 |
except Exception as e:
|
|
@@ -64,122 +65,98 @@ def _load_sources() -> List[Dict[str, str]]:
|
|
| 64 |
if not plain:
|
| 65 |
continue
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
snippet = plain[:
|
| 69 |
-
docs.append({"path": str(path.relative_to(BASE_DIR)), "text": snippet})
|
| 70 |
|
| 71 |
-
|
| 72 |
-
return docs
|
| 73 |
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
#
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
("切舍尔", ["cheshire academy", "cheshireacademy"]),
|
| 84 |
-
("柴郡", ["cheshire academy"]),
|
| 85 |
-
("柴俊学院", ["cheshire academy"]),
|
| 86 |
-
("体育", ["athletics", "sports"]),
|
| 87 |
-
("比赛", ["game", "match", "results"]),
|
| 88 |
-
("赛季", ["season"]),
|
| 89 |
-
("篮球", ["basketball"]),
|
| 90 |
-
("足球", ["soccer", "football"]),
|
| 91 |
-
("美式足球", ["football"]),
|
| 92 |
-
("网球", ["tennis"]),
|
| 93 |
-
("棒球", ["baseball"]),
|
| 94 |
-
("曲棍球", ["hockey"]),
|
| 95 |
-
("田径", ["track", "track and field"]),
|
| 96 |
-
("游泳", ["swimming"]),
|
| 97 |
-
("高尔夫", ["golf"]),
|
| 98 |
-
("比分", ["score"]),
|
| 99 |
-
("赢", ["won", "win"]),
|
| 100 |
-
("输", ["lost", "loss"]),
|
| 101 |
-
("对手", ["opponent"]),
|
| 102 |
-
]
|
| 103 |
|
|
|
|
| 104 |
|
| 105 |
def _retrieve(message: str, top_k: int = 4) -> List[Dict[str, str]]:
|
| 106 |
if not DOCS:
|
| 107 |
return []
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
# tokenization for English-ish text
|
| 113 |
-
tokens = [w for w in re.split(r"[^a-z0-9]+", q) if len(w) > 2]
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# IB expansion
|
| 118 |
if "ib" in q:
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# bilingual hints
|
| 122 |
-
for zh, en_list in ZH_EN_HINTS:
|
| 123 |
-
if zh in q_raw:
|
| 124 |
-
extra_keywords += en_list
|
| 125 |
|
| 126 |
-
|
| 127 |
-
if not keywords:
|
| 128 |
return []
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if kw and kw in text:
|
| 136 |
-
score += 1
|
| 137 |
-
if score > 0:
|
| 138 |
-
scores.append((score, doc))
|
| 139 |
-
|
| 140 |
-
if not scores:
|
| 141 |
-
return []
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
hits = _retrieve(message, top_k=1)
|
| 150 |
-
return bool(hits)
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# ============================================================
|
| 154 |
-
# Guardrails /
|
| 155 |
# ============================================================
|
| 156 |
-
|
| 157 |
CA_ENTITY_KEYWORDS = [
|
| 158 |
-
"cheshire", "cheshire academy", "cheshireacademy",
|
| 159 |
"切舍尔", "切舍尔中学", "柴郡", "柴郡学院", "柴俊学院",
|
| 160 |
-
"cheshireacademy.org",
|
| 161 |
]
|
| 162 |
|
| 163 |
-
#
|
| 164 |
CA_TOPIC_KEYWORDS = [
|
| 165 |
-
# English
|
| 166 |
"admission", "apply", "application", "deadline", "tuition", "fees", "scholarship",
|
| 167 |
"boarding", "dorm", "campus", "athletics", "sports", "calendar", "forms",
|
| 168 |
"ib", "international baccalaureate", "class", "course", "academics",
|
| 169 |
"financial aid", "visit", "open house",
|
| 170 |
-
"
|
| 171 |
-
"
|
| 172 |
-
"news", "events", "announcement",
|
| 173 |
-
# Chinese
|
| 174 |
"招生", "申请", "报名", "截止", "截止日期", "学费", "费用", "奖学金", "助学金",
|
| 175 |
-
"寄宿", "宿舍", "校园", "体育", "运动", "日历", "表格", "课程", "学术", "
|
| 176 |
-
"
|
| 177 |
-
"比赛", "比分", "成绩", "对手", "赛季", "校队", "战报", "新闻", "活动",
|
| 178 |
]
|
| 179 |
|
| 180 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 181 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 182 |
-
"
|
| 183 |
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控",
|
| 184 |
]
|
| 185 |
|
|
@@ -193,50 +170,39 @@ SELF_HARM_KEYWORDS = [
|
|
| 193 |
"自杀", "想死", "自残", "割腕", "结束生命",
|
| 194 |
]
|
| 195 |
|
| 196 |
-
|
| 197 |
def _contains_any(text: str, keywords: List[str]) -> bool:
|
| 198 |
t = (text or "").lower()
|
| 199 |
return any(k.lower() in t for k in keywords if k)
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
| 205 |
return "zh"
|
| 206 |
return "en"
|
| 207 |
|
| 208 |
-
|
| 209 |
REFUSAL_TEMPLATES = {
|
| 210 |
"non_ca": {
|
| 211 |
"en": (
|
| 212 |
-
"I can only answer questions about **Cheshire Academy** (academics, admissions, "
|
| 213 |
-
"campus life, athletics, forms, calendars, etc.).\n\n"
|
| 214 |
"Please re-ask your question **about Cheshire Academy**."
|
| 215 |
),
|
| 216 |
"zh": (
|
| 217 |
-
"我只能回答 **Cheshire Academy(切舍尔中学)** 相关的问题(学术、招生、校园生活、体育、表格、日历等)。\n\n"
|
| 218 |
-
"请
|
| 219 |
-
),
|
| 220 |
-
},
|
| 221 |
-
"maybe_ca": {
|
| 222 |
-
"en": (
|
| 223 |
-
"If you’re asking about **Cheshire Academy**, I can help — but I need a bit more context.\n\n"
|
| 224 |
-
"Please specify it’s about Cheshire Academy (e.g., which sport/team/season), then ask again."
|
| 225 |
-
),
|
| 226 |
-
"zh": (
|
| 227 |
-
"如果你是在问 **切舍尔中学(Cheshire Academy)** 的事情,我可以帮你查。\n\n"
|
| 228 |
-
"但我需要你补充一点信息:比如是哪项运动/哪支校队/大概哪个赛季或对手。请补充后再问一遍。"
|
| 229 |
),
|
| 230 |
},
|
| 231 |
"sensitive_school": {
|
| 232 |
"en": (
|
| 233 |
"I’m here to help with **Cheshire Academy admissions and campus information**. "
|
| 234 |
-
"This
|
| 235 |
-
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life,** etc."
|
| 236 |
),
|
| 237 |
"zh": (
|
| 238 |
"我可以帮助回答 **切舍尔中学的招生与校园信息**。但这个问题涉及不适合在这里讨论的内容(例如法律纠纷/指控/具体案件)。\n\n"
|
| 239 |
-
"请
|
| 240 |
),
|
| 241 |
},
|
| 242 |
"adult": {
|
|
@@ -264,58 +230,58 @@ REFUSAL_TEMPLATES = {
|
|
| 264 |
},
|
| 265 |
}
|
| 266 |
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
-
def
|
| 269 |
-
base = (lang_code or "").split("-")[0].strip().lower()
|
| 270 |
-
if not base:
|
| 271 |
-
base = _guess_lang_code_from_message(message)
|
| 272 |
-
if base not in ("en", "zh"):
|
| 273 |
-
base = "en"
|
| 274 |
-
return REFUSAL_TEMPLATES.get(kind, {}).get(base) or REFUSAL_TEMPLATES["non_ca"]["en"]
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
def _route_message(message: str) -> str:
|
| 278 |
"""
|
| 279 |
-
Returns
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
-
|
| 283 |
-
- sensitive_school -> refuse sensitive topics
|
| 284 |
-
- adult -> refuse
|
| 285 |
-
- self_harm -> safety refusal
|
| 286 |
"""
|
| 287 |
m = (message or "").strip()
|
| 288 |
if not m:
|
| 289 |
-
return "allow"
|
| 290 |
|
|
|
|
| 291 |
if _contains_any(m, SELF_HARM_KEYWORDS):
|
| 292 |
-
return "self_harm"
|
| 293 |
if _contains_any(m, ADULT_CONTENT_KEYWORDS):
|
| 294 |
-
return "adult"
|
| 295 |
if _contains_any(m, SENSITIVE_SCHOOL_CASE_KEYWORDS):
|
| 296 |
-
return "sensitive_school"
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
has_hit = _has_any_retrieval_hit(m)
|
| 301 |
-
is_topicish = _contains_any(m, CA_TOPIC_KEYWORDS)
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
| 305 |
|
| 306 |
-
|
| 307 |
-
if is_topicish:
|
| 308 |
-
return "maybe_ca"
|
| 309 |
|
| 310 |
-
|
|
|
|
| 311 |
|
|
|
|
| 312 |
|
| 313 |
# ============================================================
|
| 314 |
-
# OpenAI
|
| 315 |
# ============================================================
|
|
|
|
| 316 |
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
|
|
|
|
| 319 |
|
| 320 |
def _get_oai_client() -> Optional[OpenAI]:
|
| 321 |
global _OAI_CLIENT
|
|
@@ -329,47 +295,40 @@ def _get_oai_client() -> Optional[OpenAI]:
|
|
| 329 |
return None
|
| 330 |
|
| 331 |
try:
|
| 332 |
-
#
|
| 333 |
-
_OAI_CLIENT = OpenAI(
|
| 334 |
-
api_key=api_key,
|
| 335 |
-
timeout=OAI_TIMEOUT,
|
| 336 |
-
max_retries=OAI_MAX_RETRIES,
|
| 337 |
-
)
|
| 338 |
return _OAI_CLIENT
|
| 339 |
except Exception as e:
|
| 340 |
print("OpenAI client init error:", e)
|
| 341 |
_OAI_CLIENT = None
|
| 342 |
return None
|
| 343 |
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
-
def
|
| 346 |
-
return (code or "en").split("-")[0]
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
| 350 |
system = (
|
| 351 |
-
"You are a multilingual Cheshire Academy
|
| 352 |
-
"You are given reference text from the official Cheshire Academy website.\n"
|
| 353 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 354 |
-
"
|
| 355 |
-
"If the
|
| 356 |
"Do NOT answer general knowledge, politics, or unrelated questions.\n"
|
| 357 |
-
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users
|
| 358 |
"Be concise and student-friendly.\n"
|
| 359 |
)
|
| 360 |
|
| 361 |
if forced_lang and forced_lang != "auto":
|
| 362 |
-
|
|
|
|
| 363 |
|
| 364 |
-
retrieved = _retrieve(message, top_k=4)
|
| 365 |
context = ""
|
| 366 |
if retrieved:
|
| 367 |
chunks = []
|
| 368 |
for doc in retrieved:
|
| 369 |
chunks.append(f"Source file: {doc['path']}\n{doc['text']}")
|
| 370 |
context = (
|
| 371 |
-
"
|
| 372 |
-
"Use them as the primary source for your answer:\n\n"
|
| 373 |
+ "\n\n---\n\n".join(chunks)
|
| 374 |
)
|
| 375 |
|
|
@@ -380,27 +339,24 @@ def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
|
| 380 |
|
| 381 |
client = _get_oai_client()
|
| 382 |
if client is None:
|
| 383 |
-
return
|
| 384 |
|
| 385 |
try:
|
| 386 |
-
# Ensure request cannot hang forever
|
| 387 |
resp = client.chat.completions.create(
|
| 388 |
model=MODEL,
|
| 389 |
messages=messages,
|
| 390 |
temperature=0.1,
|
| 391 |
-
|
| 392 |
)
|
| 393 |
-
|
|
|
|
| 394 |
except Exception as e:
|
| 395 |
print("OpenAI error:", e)
|
| 396 |
-
return
|
| 397 |
-
|
| 398 |
|
| 399 |
# ============================================================
|
| 400 |
-
# Languages & greetings (
|
| 401 |
-
# -> prevents language switch from "processing forever"
|
| 402 |
# ============================================================
|
| 403 |
-
|
| 404 |
LANG_ITEMS = [
|
| 405 |
("auto", "Auto / 自动 (auto)"),
|
| 406 |
("en", "English"),
|
|
@@ -457,6 +413,9 @@ LANG_ITEMS = [
|
|
| 457 |
LANG_LABEL_BY_CODE = {code: label for code, label in LANG_ITEMS}
|
| 458 |
LANG_CODE_BY_LABEL = {label: code for code, label in LANG_ITEMS}
|
| 459 |
|
|
|
|
|
|
|
|
|
|
| 460 |
SEARCH_PLACEHOLDERS = {
|
| 461 |
"en": "Search languages",
|
| 462 |
"zh": "搜索语言",
|
|
@@ -482,93 +441,119 @@ SEARCH_PLACEHOLDERS = {
|
|
| 482 |
GREETINGS = {
|
| 483 |
"en": (
|
| 484 |
"👋 Hi! I'm the Cheshire Academy Chatbot.\n\n"
|
| 485 |
-
"I can answer questions about academics, admissions, campus life, athletics, forms, calendars, and
|
| 486 |
"• Ask in English or change the language via the globe icon.\n"
|
| 487 |
"• One clear question at a time works best.\n\n"
|
| 488 |
"How can I help today?"
|
| 489 |
),
|
| 490 |
"zh": (
|
| 491 |
"👋 你好,我是切舍尔中学的智能助手。\n\n"
|
| 492 |
-
"我可以解答:课程与学术、招生申请、校园生活、体育项目、表格与日历等问题。\n"
|
| 493 |
"• 可直接用中文提问,或点击右上角地球图标切换语言。\n"
|
| 494 |
"• 建议一次只问一个清晰的问题,效果更好。\n\n"
|
| 495 |
"请问你想了解什么?"
|
| 496 |
),
|
| 497 |
}
|
| 498 |
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
if base in GREETINGS:
|
| 504 |
-
return GREETINGS[base]
|
| 505 |
-
# fallback: keep it instant
|
| 506 |
-
return GREETINGS["en"]
|
| 507 |
-
|
| 508 |
|
| 509 |
def search_placeholder_for(code: str) -> str:
|
| 510 |
-
|
| 511 |
-
return SEARCH_PLACEHOLDERS.get(
|
| 512 |
-
|
| 513 |
|
| 514 |
# ============================================================
|
| 515 |
-
#
|
| 516 |
# ============================================================
|
| 517 |
-
|
| 518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
if not history:
|
| 520 |
return []
|
| 521 |
|
|
|
|
| 522 |
if isinstance(history, list) and history:
|
| 523 |
first = history[0]
|
| 524 |
-
# Already messages format?
|
| 525 |
-
if isinstance(first, dict) and "role" in first and "content" in first:
|
| 526 |
-
out: List[Dict[str, str]] = []
|
| 527 |
-
for m in history:
|
| 528 |
-
if isinstance(m, dict) and "role" in m and "content" in m:
|
| 529 |
-
out.append({"role": str(m["role"]), "content": str(m["content"])})
|
| 530 |
-
return out
|
| 531 |
|
| 532 |
-
#
|
| 533 |
if isinstance(first, (tuple, list)) and len(first) == 2:
|
| 534 |
-
out
|
| 535 |
for pair in history:
|
| 536 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
continue
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
if
|
| 542 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
return out
|
| 544 |
|
| 545 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
|
|
|
|
| 547 |
|
|
|
|
|
|
|
|
|
|
| 548 |
def respond(message: str, history, lang_code: str):
|
| 549 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 550 |
-
|
| 551 |
|
| 552 |
message = (message or "").strip()
|
| 553 |
if not message:
|
| 554 |
-
return "",
|
| 555 |
|
| 556 |
-
#
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
answer = _render_refusal(route, forced, message)
|
| 560 |
-
else:
|
| 561 |
-
answer = _ask(message, forced_lang=forced)
|
| 562 |
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
|
|
|
| 566 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
|
| 568 |
def greet(lang_code: str):
|
| 569 |
msg = greeting_for(lang_code)
|
| 570 |
-
|
| 571 |
-
|
| 572 |
|
| 573 |
def toggle_lang_menu(is_open: bool, lang_code: str):
|
| 574 |
new_open = not bool(is_open)
|
|
@@ -589,7 +574,6 @@ def toggle_lang_menu(is_open: bool, lang_code: str):
|
|
| 589 |
gr.update(),
|
| 590 |
)
|
| 591 |
|
| 592 |
-
|
| 593 |
def filter_languages(search: str, lang_code: str):
|
| 594 |
search = (search or "").strip().lower()
|
| 595 |
if search:
|
|
@@ -608,7 +592,6 @@ def filter_languages(search: str, lang_code: str):
|
|
| 608 |
|
| 609 |
return gr.update(choices=choices, value=current_label), lang_code
|
| 610 |
|
| 611 |
-
|
| 612 |
def select_language(label: str):
|
| 613 |
code = LANG_CODE_BY_LABEL.get(label, "auto")
|
| 614 |
return (
|
|
@@ -619,11 +602,9 @@ def select_language(label: str):
|
|
| 619 |
False,
|
| 620 |
)
|
| 621 |
|
| 622 |
-
|
| 623 |
# ============================================================
|
| 624 |
-
# CSS
|
| 625 |
# ============================================================
|
| 626 |
-
|
| 627 |
CSS = """
|
| 628 |
#ca-wrapper {
|
| 629 |
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
@@ -640,6 +621,7 @@ CSS = """
|
|
| 640 |
justify-content:space-between;
|
| 641 |
}
|
| 642 |
|
|
|
|
| 643 |
#ca-title {
|
| 644 |
font-size:18px;
|
| 645 |
font-weight:600;
|
|
@@ -668,9 +650,9 @@ CSS = """
|
|
| 668 |
filter:brightness(1.03);
|
| 669 |
}
|
| 670 |
|
| 671 |
-
/* Language panel */
|
| 672 |
#ca-lang-panel {
|
| 673 |
-
position:absolute;
|
| 674 |
top:52px;
|
| 675 |
right:16px;
|
| 676 |
width:280px;
|
|
@@ -682,6 +664,9 @@ CSS = """
|
|
| 682 |
z-index:50;
|
| 683 |
}
|
| 684 |
|
|
|
|
|
|
|
|
|
|
| 685 |
/* Search box */
|
| 686 |
#ca-lang-search textarea {
|
| 687 |
resize:none !important;
|
|
@@ -702,33 +687,34 @@ CSS = """
|
|
| 702 |
"""
|
| 703 |
|
| 704 |
# ============================================================
|
| 705 |
-
#
|
| 706 |
# ============================================================
|
| 707 |
-
|
| 708 |
with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
| 709 |
lang_state = gr.State("auto")
|
| 710 |
menu_open = gr.State(False)
|
| 711 |
|
|
|
|
| 712 |
with gr.Row(elem_id="ca-header"):
|
| 713 |
gr.HTML('<div id="ca-title">Cheshire Academy Chatbot</div>')
|
| 714 |
lang_btn = gr.Button("🌐", elem_id="ca-lang-btn", scale=0)
|
| 715 |
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
|
|
|
| 732 |
|
| 733 |
chatbot = gr.Chatbot(height=420)
|
| 734 |
msg_box = gr.Textbox(
|
|
@@ -737,8 +723,9 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 737 |
lines=2,
|
| 738 |
)
|
| 739 |
send_btn = gr.Button("Send")
|
| 740 |
-
gr.ClearButton([chatbot, msg_box])
|
| 741 |
|
|
|
|
| 742 |
send_btn.click(
|
| 743 |
respond,
|
| 744 |
inputs=[msg_box, chatbot, lang_state],
|
|
@@ -747,24 +734,29 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 747 |
|
| 748 |
demo.load(greet, inputs=[lang_state], outputs=[chatbot])
|
| 749 |
|
|
|
|
| 750 |
lang_btn.click(
|
| 751 |
toggle_lang_menu,
|
| 752 |
inputs=[menu_open, lang_state],
|
| 753 |
outputs=[menu_open, lang_panel, lang_search, lang_radio],
|
|
|
|
| 754 |
)
|
| 755 |
|
| 756 |
lang_search.change(
|
| 757 |
filter_languages,
|
| 758 |
inputs=[lang_search, lang_state],
|
| 759 |
outputs=[lang_radio, lang_state],
|
|
|
|
| 760 |
)
|
| 761 |
|
| 762 |
lang_radio.change(
|
| 763 |
select_language,
|
| 764 |
inputs=[lang_radio],
|
| 765 |
outputs=[lang_state, chatbot, lang_search, lang_panel, menu_open],
|
|
|
|
| 766 |
)
|
| 767 |
|
|
|
|
| 768 |
gr.HTML(
|
| 769 |
"""
|
| 770 |
<script>
|
|
@@ -778,7 +770,8 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 778 |
|
| 779 |
document.addEventListener('click', function(ev) {
|
| 780 |
const style = window.getComputedStyle(panel);
|
| 781 |
-
|
|
|
|
| 782 |
if (panel.contains(ev.target) || btnWrapper.contains(ev.target)) return;
|
| 783 |
btn.click();
|
| 784 |
});
|
|
|
|
| 3 |
import time
|
| 4 |
from pathlib import Path
|
| 5 |
from typing import Optional, List, Dict, Any, Tuple
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from math import log
|
| 8 |
|
| 9 |
import gradio as gr
|
| 10 |
from openai import OpenAI
|
|
|
|
| 12 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 13 |
|
| 14 |
# ============================================================
|
| 15 |
+
# Paths
|
| 16 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
BASE_DIR = Path(__file__).parent
|
| 18 |
SOURCES_DIR = BASE_DIR / "sources"
|
| 19 |
|
| 20 |
+
# ============================================================
|
| 21 |
+
# Utilities
|
| 22 |
+
# ============================================================
|
| 23 |
+
_WORD_RE = re.compile(r"[a-z0-9]+")
|
| 24 |
|
| 25 |
def _strip_html(text: str) -> str:
|
| 26 |
text = re.sub(r"<[^>]+>", " ", text)
|
| 27 |
text = re.sub(r"\s+", " ", text)
|
| 28 |
return text.strip()
|
| 29 |
|
| 30 |
+
def _tokenize_en(text: str) -> List[str]:
|
| 31 |
+
# English-ish tokenizer, fast and stable
|
| 32 |
+
t = (text or "").lower()
|
| 33 |
+
return [m.group(0) for m in _WORD_RE.finditer(t) if len(m.group(0)) > 2]
|
| 34 |
|
| 35 |
+
# ============================================================
|
| 36 |
+
# Load sources + build lightweight inverted index (fast retrieval)
|
| 37 |
+
# ============================================================
|
| 38 |
+
def _load_sources() -> Tuple[List[Dict[str, str]], List[set], Dict[str, List[int]], Dict[str, float]]:
|
| 39 |
docs: List[Dict[str, str]] = []
|
| 40 |
+
doc_tokens: List[set] = []
|
| 41 |
+
postings: Dict[str, List[int]] = defaultdict(list)
|
| 42 |
+
|
| 43 |
if not SOURCES_DIR.exists():
|
| 44 |
print("WARNING: sources/ folder not found")
|
| 45 |
+
return docs, doc_tokens, postings, {}
|
| 46 |
|
| 47 |
+
# Load
|
| 48 |
for path in SOURCES_DIR.rglob("*"):
|
| 49 |
if not path.is_file():
|
| 50 |
continue
|
| 51 |
if path.suffix.lower() not in {".txt", ".md", ".html", ".htm"}:
|
| 52 |
continue
|
| 53 |
+
|
| 54 |
try:
|
| 55 |
raw = path.read_text(encoding="utf-8", errors="ignore")
|
| 56 |
except Exception as e:
|
|
|
|
| 65 |
if not plain:
|
| 66 |
continue
|
| 67 |
|
| 68 |
+
# Keep context smaller to reduce latency and token bloat
|
| 69 |
+
snippet = plain[:2500]
|
|
|
|
| 70 |
|
| 71 |
+
docs.append({"path": str(path.relative_to(BASE_DIR)), "text": snippet})
|
|
|
|
| 72 |
|
| 73 |
+
toks = set(_tokenize_en(snippet))
|
| 74 |
+
doc_tokens.append(toks)
|
| 75 |
|
| 76 |
+
# Build postings
|
| 77 |
+
for i, toks in enumerate(doc_tokens):
|
| 78 |
+
for tok in toks:
|
| 79 |
+
postings[tok].append(i)
|
| 80 |
|
| 81 |
+
# Build IDF (simple)
|
| 82 |
+
N = max(1, len(docs))
|
| 83 |
+
idf: Dict[str, float] = {}
|
| 84 |
+
for tok, lst in postings.items():
|
| 85 |
+
df = len(lst)
|
| 86 |
+
idf[tok] = log((N + 1) / (df + 1)) + 1.0
|
| 87 |
|
| 88 |
+
print(f"Loaded {len(docs)} source documents.")
|
| 89 |
+
return docs, doc_tokens, postings, idf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
DOCS, DOC_TOKENS, POSTINGS, IDF = _load_sources()
|
| 92 |
|
| 93 |
def _retrieve(message: str, top_k: int = 4) -> List[Dict[str, str]]:
|
| 94 |
if not DOCS:
|
| 95 |
return []
|
| 96 |
|
| 97 |
+
q = (message or "").lower()
|
| 98 |
+
# Query tokens (English-ish)
|
| 99 |
+
q_tokens = set(_tokenize_en(q))
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# small helper for IB mention
|
|
|
|
|
|
|
| 102 |
if "ib" in q:
|
| 103 |
+
q_tokens |= {"international", "baccalaureate", "programme", "program"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
if not q_tokens:
|
|
|
|
| 106 |
return []
|
| 107 |
|
| 108 |
+
# Candidate docs via postings union
|
| 109 |
+
candidates = set()
|
| 110 |
+
for tok in q_tokens:
|
| 111 |
+
for idx in POSTINGS.get(tok, []):
|
| 112 |
+
candidates.add(idx)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
if not candidates:
|
| 115 |
+
return []
|
| 116 |
|
| 117 |
+
# Score candidates (presence-weighted IDF)
|
| 118 |
+
scored: List[Tuple[float, int]] = []
|
| 119 |
+
for idx in candidates:
|
| 120 |
+
toks = DOC_TOKENS[idx]
|
| 121 |
+
overlap = q_tokens.intersection(toks)
|
| 122 |
+
if not overlap:
|
| 123 |
+
continue
|
| 124 |
+
score = sum(IDF.get(t, 1.0) for t in overlap)
|
| 125 |
+
scored.append((score, idx))
|
| 126 |
|
| 127 |
+
if not scored:
|
| 128 |
+
return []
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
scored.sort(reverse=True, key=lambda x: x[0])
|
| 131 |
+
out = []
|
| 132 |
+
for _, idx in scored[:top_k]:
|
| 133 |
+
out.append(DOCS[idx])
|
| 134 |
+
return out
|
| 135 |
|
| 136 |
# ============================================================
|
| 137 |
+
# Guardrails / routing
|
| 138 |
# ============================================================
|
|
|
|
| 139 |
CA_ENTITY_KEYWORDS = [
|
| 140 |
+
"cheshire", "cheshire academy", "cheshireacademy", "cheshireacademy.org",
|
| 141 |
"切舍尔", "切舍尔中学", "柴郡", "柴郡学院", "柴俊学院",
|
|
|
|
| 142 |
]
|
| 143 |
|
| 144 |
+
# 只作为“弱信号”辅助;是否CA相关优先用 retrieval 命中判断
|
| 145 |
CA_TOPIC_KEYWORDS = [
|
|
|
|
| 146 |
"admission", "apply", "application", "deadline", "tuition", "fees", "scholarship",
|
| 147 |
"boarding", "dorm", "campus", "athletics", "sports", "calendar", "forms",
|
| 148 |
"ib", "international baccalaureate", "class", "course", "academics",
|
| 149 |
"financial aid", "visit", "open house",
|
| 150 |
+
"news", "game", "match", "score", "team", "tournament", "championship",
|
| 151 |
+
"basketball", "soccer", "baseball", "football", "tennis", "golf", "track",
|
|
|
|
|
|
|
| 152 |
"招生", "申请", "报名", "截止", "截止日期", "学费", "费用", "奖学金", "助学金",
|
| 153 |
+
"寄宿", "宿舍", "校园", "体育", "运动", "日历", "表格", "课程", "学术", "访校", "开放日",
|
| 154 |
+
"新闻", "比赛", "赛事", "比分", "球队", "锦标赛", "冠军", "篮球", "足球", "网球", "田径",
|
|
|
|
| 155 |
]
|
| 156 |
|
| 157 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 158 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 159 |
+
"allegation", "scandal",
|
| 160 |
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控",
|
| 161 |
]
|
| 162 |
|
|
|
|
| 170 |
"自杀", "想死", "自残", "割腕", "结束生命",
|
| 171 |
]
|
| 172 |
|
|
|
|
| 173 |
def _contains_any(text: str, keywords: List[str]) -> bool:
|
| 174 |
t = (text or "").lower()
|
| 175 |
return any(k.lower() in t for k in keywords if k)
|
| 176 |
|
| 177 |
+
def _guess_refusal_lang(message: str, forced_lang: Optional[str]) -> str:
|
| 178 |
+
base = (forced_lang or "").split("-")[0].strip().lower()
|
| 179 |
+
if base in ("en", "zh"):
|
| 180 |
+
return base
|
| 181 |
+
# auto guess: CJK => zh else en
|
| 182 |
+
if re.search(r"[\u4e00-\u9fff]", message or ""):
|
| 183 |
return "zh"
|
| 184 |
return "en"
|
| 185 |
|
|
|
|
| 186 |
REFUSAL_TEMPLATES = {
|
| 187 |
"non_ca": {
|
| 188 |
"en": (
|
| 189 |
+
"I can only answer questions about **Cheshire Academy** (academics, admissions, campus life, athletics, forms, calendars, news/updates, etc.).\n\n"
|
|
|
|
| 190 |
"Please re-ask your question **about Cheshire Academy**."
|
| 191 |
),
|
| 192 |
"zh": (
|
| 193 |
+
"我只能回答 **Cheshire Academy(切舍尔中学)** 相关的问题(学术、招生、校园生活、体育、表格、日历、新闻动态等)。\n\n"
|
| 194 |
+
"请把问题改成 **与切舍尔中学有关** 的问题再问一遍。"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
),
|
| 196 |
},
|
| 197 |
"sensitive_school": {
|
| 198 |
"en": (
|
| 199 |
"I’m here to help with **Cheshire Academy admissions and campus information**. "
|
| 200 |
+
"This topic isn’t appropriate to discuss here (e.g., legal cases/allegations).\n\n"
|
| 201 |
+
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life, athletics,** etc."
|
| 202 |
),
|
| 203 |
"zh": (
|
| 204 |
"我可以帮助回答 **切舍尔中学的招生与校园信息**。但这个问题涉及不适合在这里讨论的内容(例如法律纠纷/指控/具体案件)。\n\n"
|
| 205 |
+
"请换一个关于 **课程项目、招生申请、学费、截止日期、寄宿与校园生活、体育动态** 等方面的问题再问一遍。"
|
| 206 |
),
|
| 207 |
},
|
| 208 |
"adult": {
|
|
|
|
| 230 |
},
|
| 231 |
}
|
| 232 |
|
| 233 |
+
def _render_refusal(kind: str, message: str, forced_lang: Optional[str]) -> str:
|
| 234 |
+
lang = _guess_refusal_lang(message, forced_lang)
|
| 235 |
+
return REFUSAL_TEMPLATES.get(kind, {}).get(lang) or REFUSAL_TEMPLATES["non_ca"]["en"]
|
| 236 |
|
| 237 |
+
def _route_message(message: str, forced_lang: Optional[str]) -> Tuple[str, List[Dict[str, str]]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
"""
|
| 239 |
+
Returns (route, retrieved_docs)
|
| 240 |
+
route in: allow | non_ca | sensitive_school | adult | self_harm
|
| 241 |
+
Key change:
|
| 242 |
+
- Use retrieval hit as primary CA-signal (more reliable than keywords)
|
|
|
|
|
|
|
|
|
|
| 243 |
"""
|
| 244 |
m = (message or "").strip()
|
| 245 |
if not m:
|
| 246 |
+
return "allow", []
|
| 247 |
|
| 248 |
+
# Hard blocks first (instant, no OpenAI)
|
| 249 |
if _contains_any(m, SELF_HARM_KEYWORDS):
|
| 250 |
+
return "self_harm", []
|
| 251 |
if _contains_any(m, ADULT_CONTENT_KEYWORDS):
|
| 252 |
+
return "adult", []
|
| 253 |
if _contains_any(m, SENSITIVE_SCHOOL_CASE_KEYWORDS):
|
| 254 |
+
return "sensitive_school", []
|
| 255 |
|
| 256 |
+
# Retrieval-based CA signal (important!)
|
| 257 |
+
retrieved = _retrieve(m, top_k=4)
|
|
|
|
|
|
|
| 258 |
|
| 259 |
+
# CA signals
|
| 260 |
+
has_entity = _contains_any(m, CA_ENTITY_KEYWORDS)
|
| 261 |
+
has_topic_hint = _contains_any(m, CA_TOPIC_KEYWORDS)
|
| 262 |
+
has_retrieval_hit = bool(retrieved)
|
| 263 |
|
| 264 |
+
is_ca = has_entity or has_retrieval_hit or has_topic_hint
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
if not is_ca:
|
| 267 |
+
return "non_ca", retrieved
|
| 268 |
|
| 269 |
+
return "allow", retrieved
|
| 270 |
|
| 271 |
# ============================================================
|
| 272 |
+
# OpenAI
|
| 273 |
# ============================================================
|
| 274 |
+
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
|
| 275 |
|
| 276 |
+
FALLBACK_EN = (
|
| 277 |
+
"I'm not certain from my current references. "
|
| 278 |
+
"Please contact admission@cheshireacademy.org | +1-203-439-7250."
|
| 279 |
+
)
|
| 280 |
+
FALLBACK_ZH = (
|
| 281 |
+
"我无法从当前资料中确认答案。建议联系 admission@cheshireacademy.org 或 +1-203-439-7250。"
|
| 282 |
+
)
|
| 283 |
|
| 284 |
+
_OAI_CLIENT: Optional[OpenAI] = None
|
| 285 |
|
| 286 |
def _get_oai_client() -> Optional[OpenAI]:
|
| 287 |
global _OAI_CLIENT
|
|
|
|
| 295 |
return None
|
| 296 |
|
| 297 |
try:
|
| 298 |
+
# IMPORTANT: explicit timeout to prevent infinite "processing"
|
| 299 |
+
_OAI_CLIENT = OpenAI(api_key=api_key, timeout=20.0, max_retries=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
return _OAI_CLIENT
|
| 301 |
except Exception as e:
|
| 302 |
print("OpenAI client init error:", e)
|
| 303 |
_OAI_CLIENT = None
|
| 304 |
return None
|
| 305 |
|
| 306 |
+
def _fallback_by_lang(forced_lang: Optional[str], message: str) -> str:
|
| 307 |
+
base = _guess_refusal_lang(message, forced_lang)
|
| 308 |
+
return FALLBACK_ZH if base == "zh" else FALLBACK_EN
|
| 309 |
|
| 310 |
+
def _ask(message: str, retrieved: List[Dict[str, str]], forced_lang: Optional[str]) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
system = (
|
| 312 |
+
"You are a multilingual Cheshire Academy assistant.\n"
|
|
|
|
| 313 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 314 |
+
"Use the provided reference excerpts as the primary source.\n"
|
| 315 |
+
"If the excerpts do not clearly answer, say you are not certain and suggest contacting the school instead of guessing.\n"
|
| 316 |
"Do NOT answer general knowledge, politics, or unrelated questions.\n"
|
| 317 |
+
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users to admissions/campus questions.\n"
|
| 318 |
"Be concise and student-friendly.\n"
|
| 319 |
)
|
| 320 |
|
| 321 |
if forced_lang and forced_lang != "auto":
|
| 322 |
+
base = forced_lang.split("-")[0]
|
| 323 |
+
system += f"Always answer in the language whose base code is '{base}'.\n"
|
| 324 |
|
|
|
|
| 325 |
context = ""
|
| 326 |
if retrieved:
|
| 327 |
chunks = []
|
| 328 |
for doc in retrieved:
|
| 329 |
chunks.append(f"Source file: {doc['path']}\n{doc['text']}")
|
| 330 |
context = (
|
| 331 |
+
"Reference excerpts from Cheshire Academy official pages:\n\n"
|
|
|
|
| 332 |
+ "\n\n---\n\n".join(chunks)
|
| 333 |
)
|
| 334 |
|
|
|
|
| 339 |
|
| 340 |
client = _get_oai_client()
|
| 341 |
if client is None:
|
| 342 |
+
return _fallback_by_lang(forced_lang, message)
|
| 343 |
|
| 344 |
try:
|
|
|
|
| 345 |
resp = client.chat.completions.create(
|
| 346 |
model=MODEL,
|
| 347 |
messages=messages,
|
| 348 |
temperature=0.1,
|
| 349 |
+
max_tokens=700,
|
| 350 |
)
|
| 351 |
+
out = (resp.choices[0].message.content or "").strip()
|
| 352 |
+
return out or _fallback_by_lang(forced_lang, message)
|
| 353 |
except Exception as e:
|
| 354 |
print("OpenAI error:", e)
|
| 355 |
+
return _fallback_by_lang(forced_lang, message)
|
|
|
|
| 356 |
|
| 357 |
# ============================================================
|
| 358 |
+
# Languages & greetings (NO runtime OpenAI translation to avoid hangs)
|
|
|
|
| 359 |
# ============================================================
|
|
|
|
| 360 |
LANG_ITEMS = [
|
| 361 |
("auto", "Auto / 自动 (auto)"),
|
| 362 |
("en", "English"),
|
|
|
|
| 413 |
LANG_LABEL_BY_CODE = {code: label for code, label in LANG_ITEMS}
|
| 414 |
LANG_CODE_BY_LABEL = {label: code for code, label in LANG_ITEMS}
|
| 415 |
|
| 416 |
+
def base_lang(code: str) -> str:
|
| 417 |
+
return (code or "en").split("-")[0]
|
| 418 |
+
|
| 419 |
SEARCH_PLACEHOLDERS = {
|
| 420 |
"en": "Search languages",
|
| 421 |
"zh": "搜索语言",
|
|
|
|
| 441 |
GREETINGS = {
|
| 442 |
"en": (
|
| 443 |
"👋 Hi! I'm the Cheshire Academy Chatbot.\n\n"
|
| 444 |
+
"I can answer questions about academics, admissions, campus life, athletics, forms, calendars, and official updates.\n"
|
| 445 |
"• Ask in English or change the language via the globe icon.\n"
|
| 446 |
"• One clear question at a time works best.\n\n"
|
| 447 |
"How can I help today?"
|
| 448 |
),
|
| 449 |
"zh": (
|
| 450 |
"👋 你好,我是切舍尔中学的智能助手。\n\n"
|
| 451 |
+
"我可以解答:课程与学术、招生申请、校园生活、体育项目、表格与日历、官方新闻动态等问题。\n"
|
| 452 |
"• 可直接用中文提问,或点击右上角地球图标切换语言。\n"
|
| 453 |
"• 建议一次只问一个清晰的问题,效果更好。\n\n"
|
| 454 |
"请问你想了解什么?"
|
| 455 |
),
|
| 456 |
}
|
| 457 |
|
| 458 |
+
def greeting_for(lang_code: str) -> str:
|
| 459 |
+
# IMPORTANT: no runtime OpenAI call here, to avoid “processing forever”
|
| 460 |
+
b = base_lang(lang_code)
|
| 461 |
+
return GREETINGS.get(b, GREETINGS["en"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
|
| 463 |
def search_placeholder_for(code: str) -> str:
|
| 464 |
+
b = base_lang(code)
|
| 465 |
+
return SEARCH_PLACEHOLDERS.get(b, SEARCH_PLACEHOLDERS["en"])
|
|
|
|
| 466 |
|
| 467 |
# ============================================================
|
| 468 |
+
# History format fixer (prevents dict/text/type from breaking UI)
|
| 469 |
# ============================================================
|
| 470 |
+
def _ensure_tuple_history(history: Any) -> List[Tuple[Optional[str], Optional[str]]]:
|
| 471 |
+
"""
|
| 472 |
+
Canonical format for gr.Chatbot in gradio==6.1.0:
|
| 473 |
+
[(user, assistant), ...]
|
| 474 |
+
This function aggressively converts:
|
| 475 |
+
- list of dicts with role/content
|
| 476 |
+
- list of dicts with text/type
|
| 477 |
+
- list of tuples/lists
|
| 478 |
+
"""
|
| 479 |
if not history:
|
| 480 |
return []
|
| 481 |
|
| 482 |
+
# Already tuple/list pairs?
|
| 483 |
if isinstance(history, list) and history:
|
| 484 |
first = history[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
+
# Case 1: [(u,a), ...]
|
| 487 |
if isinstance(first, (tuple, list)) and len(first) == 2:
|
| 488 |
+
out = []
|
| 489 |
for pair in history:
|
| 490 |
+
if isinstance(pair, (tuple, list)) and len(pair) == 2:
|
| 491 |
+
u, a = pair
|
| 492 |
+
out.append((u if u is None else str(u), a if a is None else str(a)))
|
| 493 |
+
return out
|
| 494 |
+
|
| 495 |
+
# Case 2: [{"role":"assistant","content":"..."}, ...]
|
| 496 |
+
if isinstance(first, dict) and ("role" in first and "content" in first):
|
| 497 |
+
out: List[Tuple[Optional[str], Optional[str]]] = []
|
| 498 |
+
pending_user: Optional[str] = None
|
| 499 |
+
for m in history:
|
| 500 |
+
if not isinstance(m, dict):
|
| 501 |
continue
|
| 502 |
+
role = str(m.get("role", "")).lower()
|
| 503 |
+
content = m.get("content", "")
|
| 504 |
+
content = None if content is None else str(content)
|
| 505 |
+
if role == "user":
|
| 506 |
+
pending_user = content
|
| 507 |
+
elif role == "assistant":
|
| 508 |
+
out.append((pending_user, content))
|
| 509 |
+
pending_user = None
|
| 510 |
+
# if dangling user, keep it
|
| 511 |
+
if pending_user is not None:
|
| 512 |
+
out.append((pending_user, None))
|
| 513 |
return out
|
| 514 |
|
| 515 |
+
# Case 3: [{"text":"...", "type":"text"}, ...] (ChatMessage-like)
|
| 516 |
+
if isinstance(first, dict) and ("text" in first and "type" in first):
|
| 517 |
+
# Treat these as assistant-only messages
|
| 518 |
+
out: List[Tuple[Optional[str], Optional[str]]] = []
|
| 519 |
+
for m in history:
|
| 520 |
+
if isinstance(m, dict) and "text" in m:
|
| 521 |
+
out.append((None, str(m.get("text", ""))))
|
| 522 |
+
return out
|
| 523 |
|
| 524 |
+
return []
|
| 525 |
|
| 526 |
+
# ============================================================
|
| 527 |
+
# Gradio callbacks
|
| 528 |
+
# ============================================================
|
| 529 |
def respond(message: str, history, lang_code: str):
|
| 530 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 531 |
+
history_pairs = _ensure_tuple_history(history)
|
| 532 |
|
| 533 |
message = (message or "").strip()
|
| 534 |
if not message:
|
| 535 |
+
return "", history_pairs
|
| 536 |
|
| 537 |
+
# Make sure we NEVER hang the request
|
| 538 |
+
try:
|
| 539 |
+
route, retrieved = _route_message(message, forced)
|
|
|
|
|
|
|
|
|
|
| 540 |
|
| 541 |
+
if route != "allow":
|
| 542 |
+
answer = _render_refusal(route, message, forced)
|
| 543 |
+
else:
|
| 544 |
+
answer = _ask(message, retrieved=retrieved, forced_lang=forced)
|
| 545 |
|
| 546 |
+
history_pairs.append((message, answer))
|
| 547 |
+
return "", history_pairs
|
| 548 |
+
except Exception as e:
|
| 549 |
+
print("respond() error:", e)
|
| 550 |
+
history_pairs.append((message, _fallback_by_lang(forced, message)))
|
| 551 |
+
return "", history_pairs
|
| 552 |
|
| 553 |
def greet(lang_code: str):
|
| 554 |
msg = greeting_for(lang_code)
|
| 555 |
+
# assistant-only first bubble
|
| 556 |
+
return [(None, msg)]
|
| 557 |
|
| 558 |
def toggle_lang_menu(is_open: bool, lang_code: str):
|
| 559 |
new_open = not bool(is_open)
|
|
|
|
| 574 |
gr.update(),
|
| 575 |
)
|
| 576 |
|
|
|
|
| 577 |
def filter_languages(search: str, lang_code: str):
|
| 578 |
search = (search or "").strip().lower()
|
| 579 |
if search:
|
|
|
|
| 592 |
|
| 593 |
return gr.update(choices=choices, value=current_label), lang_code
|
| 594 |
|
|
|
|
| 595 |
def select_language(label: str):
|
| 596 |
code = LANG_CODE_BY_LABEL.get(label, "auto")
|
| 597 |
return (
|
|
|
|
| 602 |
False,
|
| 603 |
)
|
| 604 |
|
|
|
|
| 605 |
# ============================================================
|
| 606 |
+
# CSS (includes small fixes for stray blank bar / panel)
|
| 607 |
# ============================================================
|
|
|
|
| 608 |
CSS = """
|
| 609 |
#ca-wrapper {
|
| 610 |
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
|
|
| 621 |
justify-content:space-between;
|
| 622 |
}
|
| 623 |
|
| 624 |
+
/* Title */
|
| 625 |
#ca-title {
|
| 626 |
font-size:18px;
|
| 627 |
font-weight:600;
|
|
|
|
| 650 |
filter:brightness(1.03);
|
| 651 |
}
|
| 652 |
|
| 653 |
+
/* Language panel: card at top-right */
|
| 654 |
#ca-lang-panel {
|
| 655 |
+
position:absolute !important;
|
| 656 |
top:52px;
|
| 657 |
right:16px;
|
| 658 |
width:280px;
|
|
|
|
| 664 |
z-index:50;
|
| 665 |
}
|
| 666 |
|
| 667 |
+
/* Prevent any placeholder bar below header */
|
| 668 |
+
#ca-lang-panel:empty { display:none !important; }
|
| 669 |
+
|
| 670 |
/* Search box */
|
| 671 |
#ca-lang-search textarea {
|
| 672 |
resize:none !important;
|
|
|
|
| 687 |
"""
|
| 688 |
|
| 689 |
# ============================================================
|
| 690 |
+
# UI
|
| 691 |
# ============================================================
|
|
|
|
| 692 |
with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
| 693 |
lang_state = gr.State("auto")
|
| 694 |
menu_open = gr.State(False)
|
| 695 |
|
| 696 |
+
# Header row (put panel INSIDE header to avoid layout ghosts)
|
| 697 |
with gr.Row(elem_id="ca-header"):
|
| 698 |
gr.HTML('<div id="ca-title">Cheshire Academy Chatbot</div>')
|
| 699 |
lang_btn = gr.Button("🌐", elem_id="ca-lang-btn", scale=0)
|
| 700 |
|
| 701 |
+
# Language panel inside header (absolute positioned)
|
| 702 |
+
with gr.Column(visible=False, elem_id="ca-lang-panel") as lang_panel:
|
| 703 |
+
lang_search = gr.Textbox(
|
| 704 |
+
value="",
|
| 705 |
+
placeholder=search_placeholder_for("en"),
|
| 706 |
+
label="",
|
| 707 |
+
show_label=False,
|
| 708 |
+
lines=1,
|
| 709 |
+
elem_id="ca-lang-search",
|
| 710 |
+
)
|
| 711 |
+
lang_radio = gr.Radio(
|
| 712 |
+
choices=[label for _, label in LANG_ITEMS],
|
| 713 |
+
value=LANG_LABEL_BY_CODE["auto"],
|
| 714 |
+
label="",
|
| 715 |
+
show_label=False,
|
| 716 |
+
elem_id="ca-lang-radio",
|
| 717 |
+
)
|
| 718 |
|
| 719 |
chatbot = gr.Chatbot(height=420)
|
| 720 |
msg_box = gr.Textbox(
|
|
|
|
| 723 |
lines=2,
|
| 724 |
)
|
| 725 |
send_btn = gr.Button("Send")
|
| 726 |
+
clear_btn = gr.ClearButton([chatbot, msg_box])
|
| 727 |
|
| 728 |
+
# Chat logic (keep queued because it may call OpenAI)
|
| 729 |
send_btn.click(
|
| 730 |
respond,
|
| 731 |
inputs=[msg_box, chatbot, lang_state],
|
|
|
|
| 734 |
|
| 735 |
demo.load(greet, inputs=[lang_state], outputs=[chatbot])
|
| 736 |
|
| 737 |
+
# UI-only events: MUST be queue=False so language toggle never gets stuck behind model calls
|
| 738 |
lang_btn.click(
|
| 739 |
toggle_lang_menu,
|
| 740 |
inputs=[menu_open, lang_state],
|
| 741 |
outputs=[menu_open, lang_panel, lang_search, lang_radio],
|
| 742 |
+
queue=False,
|
| 743 |
)
|
| 744 |
|
| 745 |
lang_search.change(
|
| 746 |
filter_languages,
|
| 747 |
inputs=[lang_search, lang_state],
|
| 748 |
outputs=[lang_radio, lang_state],
|
| 749 |
+
queue=False,
|
| 750 |
)
|
| 751 |
|
| 752 |
lang_radio.change(
|
| 753 |
select_language,
|
| 754 |
inputs=[lang_radio],
|
| 755 |
outputs=[lang_state, chatbot, lang_search, lang_panel, menu_open],
|
| 756 |
+
queue=False,
|
| 757 |
)
|
| 758 |
|
| 759 |
+
# JS: click outside panel closes it (queue-free)
|
| 760 |
gr.HTML(
|
| 761 |
"""
|
| 762 |
<script>
|
|
|
|
| 770 |
|
| 771 |
document.addEventListener('click', function(ev) {
|
| 772 |
const style = window.getComputedStyle(panel);
|
| 773 |
+
const hidden = (style.display === 'none' || panel.hidden);
|
| 774 |
+
if (hidden) return;
|
| 775 |
if (panel.contains(ev.target) || btnWrapper.contains(ev.target)) return;
|
| 776 |
btn.click();
|
| 777 |
});
|