Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
from typing import Optional, List, Dict, Any, Tuple
|
| 5 |
-
from collections import defaultdict
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
from openai import OpenAI
|
|
@@ -10,30 +10,35 @@ from openai import OpenAI
|
|
| 10 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 11 |
|
| 12 |
# ============================================================
|
| 13 |
-
#
|
| 14 |
# ============================================================
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# ============================================================
|
| 19 |
-
#
|
| 20 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def _strip_html(text: str) -> str:
|
| 22 |
text = re.sub(r"<[^>]+>", " ", text)
|
| 23 |
text = re.sub(r"\s+", " ", text)
|
| 24 |
return text.strip()
|
| 25 |
|
| 26 |
-
_TOKEN_RE = re.compile(r"[a-z0-9]+", re.IGNORECASE)
|
| 27 |
-
|
| 28 |
-
def _tokenize(s: str) -> List[str]:
|
| 29 |
-
s = (s or "").lower()
|
| 30 |
-
toks = _TOKEN_RE.findall(s)
|
| 31 |
-
# drop very short tokens
|
| 32 |
-
return [t for t in toks if len(t) > 2]
|
| 33 |
|
| 34 |
-
# ============================================================
|
| 35 |
-
# Load sources (RAG)
|
| 36 |
-
# ============================================================
|
| 37 |
def _load_sources() -> List[Dict[str, str]]:
|
| 38 |
docs: List[Dict[str, str]] = []
|
| 39 |
if not SOURCES_DIR.exists():
|
|
@@ -45,7 +50,6 @@ def _load_sources() -> List[Dict[str, str]]:
|
|
| 45 |
continue
|
| 46 |
if path.suffix.lower() not in {".txt", ".md", ".html", ".htm"}:
|
| 47 |
continue
|
| 48 |
-
|
| 49 |
try:
|
| 50 |
raw = path.read_text(encoding="utf-8", errors="ignore")
|
| 51 |
except Exception as e:
|
|
@@ -60,135 +64,153 @@ def _load_sources() -> List[Dict[str, str]]:
|
|
| 60 |
if not plain:
|
| 61 |
continue
|
| 62 |
|
| 63 |
-
# keep
|
| 64 |
-
snippet = plain[:
|
| 65 |
-
docs.append(
|
| 66 |
-
{"path": str(path.relative_to(BASE_DIR)), "text": snippet}
|
| 67 |
-
)
|
| 68 |
|
| 69 |
print(f"Loaded {len(docs)} source documents.")
|
| 70 |
return docs
|
| 71 |
|
| 72 |
-
|
|
|
|
| 73 |
|
| 74 |
# ============================================================
|
| 75 |
-
#
|
| 76 |
# ============================================================
|
| 77 |
-
DOC_TOKENS: List[set] = []
|
| 78 |
-
INVERTED: Dict[str, List[int]] = defaultdict(list)
|
| 79 |
-
|
| 80 |
-
for i, d in enumerate(DOCS):
|
| 81 |
-
toks = set(_tokenize(d["text"]))
|
| 82 |
-
DOC_TOKENS.append(toks)
|
| 83 |
-
for t in toks:
|
| 84 |
-
INVERTED[t].append(i)
|
| 85 |
-
|
| 86 |
-
# Special expansions for common queries (kept small)
|
| 87 |
-
_EXPAND_MAP = {
|
| 88 |
-
"ib": ["international", "baccalaureate", "programme", "program"],
|
| 89 |
-
}
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
Return list of (score, doc) sorted desc.
|
| 101 |
-
Score = number of distinct query tokens found in doc token set.
|
| 102 |
-
"""
|
| 103 |
if not DOCS:
|
| 104 |
return []
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
| 111 |
-
scores_by_doc: Dict[int, int] = defaultdict(int)
|
| 112 |
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
scores_by_doc[doc_id] += 1
|
| 117 |
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
return []
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
out.sort(key=lambda x: x[0], reverse=True)
|
| 130 |
-
return out[:top_k]
|
| 131 |
|
| 132 |
# ============================================================
|
| 133 |
-
# Guardrails /
|
| 134 |
-
# NOTE: 不再依赖 CA_TOPIC_KEYWORDS 作为“唯一判断”,而是:
|
| 135 |
-
# 1) 先检索命中则视为“学校相关”(解决你提到的体育战报类问题)
|
| 136 |
-
# 2) 没命中时再用 very light heuristics 分成 non_ca / ca_unknown
|
| 137 |
# ============================================================
|
|
|
|
| 138 |
CA_ENTITY_KEYWORDS = [
|
| 139 |
-
"cheshire", "cheshire academy", "cheshireacademy",
|
| 140 |
"切舍尔", "切舍尔中学", "柴郡", "柴郡学院", "柴俊学院",
|
|
|
|
| 141 |
]
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
|
| 145 |
-
#
|
| 146 |
-
"
|
| 147 |
-
"
|
| 148 |
-
"
|
| 149 |
-
"
|
| 150 |
-
|
| 151 |
-
"
|
| 152 |
-
"
|
| 153 |
# Chinese
|
| 154 |
-
"
|
| 155 |
-
"
|
| 156 |
-
"
|
|
|
|
| 157 |
]
|
| 158 |
|
| 159 |
-
# School-related but not appropriate here
|
| 160 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 161 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 162 |
-
"
|
| 163 |
-
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控",
|
| 164 |
]
|
| 165 |
|
| 166 |
-
# Adult content
|
| 167 |
ADULT_CONTENT_KEYWORDS = [
|
| 168 |
"porn", "xxx", "nude", "sex", "hookup", "onlyfans",
|
| 169 |
"色情", "黄片", "裸照", "成人视频", "约炮", "做爰",
|
| 170 |
]
|
| 171 |
|
| 172 |
-
# Self-harm
|
| 173 |
SELF_HARM_KEYWORDS = [
|
| 174 |
"suicide", "kill myself", "self-harm", "cut myself", "end my life",
|
| 175 |
"自杀", "想死", "自残", "割腕", "结束生命",
|
| 176 |
]
|
| 177 |
|
|
|
|
| 178 |
def _contains_any(text: str, keywords: List[str]) -> bool:
|
| 179 |
t = (text or "").lower()
|
| 180 |
return any(k.lower() in t for k in keywords if k)
|
| 181 |
|
|
|
|
| 182 |
def _guess_lang_code_from_message(message: str) -> str:
|
| 183 |
s = message or ""
|
| 184 |
if re.search(r"[\u4e00-\u9fff]", s):
|
| 185 |
return "zh"
|
| 186 |
return "en"
|
| 187 |
|
|
|
|
| 188 |
REFUSAL_TEMPLATES = {
|
| 189 |
"non_ca": {
|
| 190 |
"en": (
|
| 191 |
-
"I can only answer questions about **Cheshire Academy** (academics, admissions,
|
|
|
|
| 192 |
"Please re-ask your question **about Cheshire Academy**."
|
| 193 |
),
|
| 194 |
"zh": (
|
|
@@ -196,14 +218,24 @@ REFUSAL_TEMPLATES = {
|
|
| 196 |
"请你把问题改成 **与切舍尔中学有关** 的问题再问一遍。"
|
| 197 |
),
|
| 198 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
"sensitive_school": {
|
| 200 |
"en": (
|
| 201 |
"I’m here to help with **Cheshire Academy admissions and campus information**. "
|
| 202 |
-
"This
|
| 203 |
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life,** etc."
|
| 204 |
),
|
| 205 |
"zh": (
|
| 206 |
-
"我可以帮助回答 **切舍尔中学的招生与校园信息**。但这个问题涉及不适合在这里讨论的内容(例如
|
| 207 |
"请你换一个关于 **课程项目、招生申请、学费、截止日期、寄宿与校园生活** 等方面的问题再问一遍。"
|
| 208 |
),
|
| 209 |
},
|
|
@@ -230,19 +262,9 @@ REFUSAL_TEMPLATES = {
|
|
| 230 |
"如果你愿意,也可以告诉我发生了什么,我会倾听并帮你一起寻找支持。"
|
| 231 |
),
|
| 232 |
},
|
| 233 |
-
"ca_unknown": {
|
| 234 |
-
"en": (
|
| 235 |
-
"I understand your question is about **Cheshire Academy**, but I can’t confirm the answer from my current official website references.\n\n"
|
| 236 |
-
"This bot’s sources update periodically. Please try again later, or check the Athletics/News pages on the official website. "
|
| 237 |
-
"If it’s important, contact admission@cheshireacademy.org."
|
| 238 |
-
),
|
| 239 |
-
"zh": (
|
| 240 |
-
"我理解你问的是 **切舍尔中学** 相关内容,但我暂时无法从当前已同步的官网资料中确认答案。\n\n"
|
| 241 |
-
"本机器人资料会定期更新。你可以稍后再问一次,或去官网的 Athletics/News 页面查看;需要确认的话也可以联系 admission@cheshireacademy.org。"
|
| 242 |
-
),
|
| 243 |
-
},
|
| 244 |
}
|
| 245 |
|
|
|
|
| 246 |
def _render_refusal(kind: str, lang_code: Optional[str], message: str) -> str:
|
| 247 |
base = (lang_code or "").split("-")[0].strip().lower()
|
| 248 |
if not base:
|
|
@@ -251,55 +273,50 @@ def _render_refusal(kind: str, lang_code: Optional[str], message: str) -> str:
|
|
| 251 |
base = "en"
|
| 252 |
return REFUSAL_TEMPLATES.get(kind, {}).get(base) or REFUSAL_TEMPLATES["non_ca"]["en"]
|
| 253 |
|
| 254 |
-
# Retrieve score threshold: tune this
|
| 255 |
-
MIN_RETRIEVE_SCORE = int(os.getenv("MIN_RETRIEVE_SCORE", "2"))
|
| 256 |
|
| 257 |
-
def _route_message(message: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
m = (message or "").strip()
|
| 259 |
if not m:
|
| 260 |
return "allow"
|
| 261 |
|
| 262 |
-
# safety first
|
| 263 |
if _contains_any(m, SELF_HARM_KEYWORDS):
|
| 264 |
return "self_harm"
|
| 265 |
if _contains_any(m, ADULT_CONTENT_KEYWORDS):
|
| 266 |
return "adult"
|
| 267 |
-
|
| 268 |
-
# sensitive school topics
|
| 269 |
if _contains_any(m, SENSITIVE_SCHOOL_CASE_KEYWORDS):
|
| 270 |
return "sensitive_school"
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
|
|
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
# not enough evidence in sources -> ca_unknown (avoid "non_ca" wrong refusal)
|
| 279 |
-
return "ca_unknown"
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
if
|
| 283 |
-
return "
|
| 284 |
|
| 285 |
return "non_ca"
|
| 286 |
|
|
|
|
| 287 |
# ============================================================
|
| 288 |
-
# OpenAI
|
| 289 |
# ============================================================
|
| 290 |
-
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
|
| 291 |
-
|
| 292 |
-
FALLBACK_EN = (
|
| 293 |
-
"I'm not certain from my current references. "
|
| 294 |
-
"Please contact admission@cheshireacademy.org | +1-203-439-7250."
|
| 295 |
-
)
|
| 296 |
-
FALLBACK_ZH = (
|
| 297 |
-
"我无法从当前资料中确认答案。"
|
| 298 |
-
"建议联系 admission@cheshireacademy.org | +1-203-439-7250。"
|
| 299 |
-
)
|
| 300 |
|
| 301 |
_OAI_CLIENT: Optional[OpenAI] = None
|
| 302 |
|
|
|
|
| 303 |
def _get_oai_client() -> Optional[OpenAI]:
|
| 304 |
global _OAI_CLIENT
|
| 305 |
if _OAI_CLIENT is not None:
|
|
@@ -312,55 +329,49 @@ def _get_oai_client() -> Optional[OpenAI]:
|
|
| 312 |
return None
|
| 313 |
|
| 314 |
try:
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
return _OAI_CLIENT
|
| 317 |
except Exception as e:
|
| 318 |
print("OpenAI client init error:", e)
|
| 319 |
_OAI_CLIENT = None
|
| 320 |
return None
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
| 327 |
system = (
|
| 328 |
"You are a multilingual Cheshire Academy FAQ assistant.\n"
|
| 329 |
"You are given reference text from the official Cheshire Academy website.\n"
|
| 330 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 331 |
-
"Rely ONLY on those references for
|
| 332 |
-
"If the
|
| 333 |
"Do NOT answer general knowledge, politics, or unrelated questions.\n"
|
| 334 |
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users back to admissions/campus questions.\n"
|
| 335 |
"Be concise and student-friendly.\n"
|
| 336 |
)
|
|
|
|
| 337 |
if forced_lang and forced_lang != "auto":
|
| 338 |
system += f"Always answer in the language whose base code is '{forced_lang}'.\n"
|
| 339 |
|
| 340 |
-
|
| 341 |
context = ""
|
| 342 |
if retrieved:
|
| 343 |
chunks = []
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
text = text[:2200]
|
| 352 |
-
chunk = f"Source file: {doc['path']}\n{text}"
|
| 353 |
-
if total_chars + len(chunk) > 9500:
|
| 354 |
-
break
|
| 355 |
-
chunks.append(chunk)
|
| 356 |
-
total_chars += len(chunk)
|
| 357 |
-
|
| 358 |
-
if chunks:
|
| 359 |
-
context = (
|
| 360 |
-
"Here are reference excerpts from the official Cheshire Academy website. "
|
| 361 |
-
"Use them as the primary source for your answer:\n\n"
|
| 362 |
-
+ "\n\n---\n\n".join(chunks)
|
| 363 |
-
)
|
| 364 |
|
| 365 |
messages = [{"role": "system", "content": system}]
|
| 366 |
if context:
|
|
@@ -369,27 +380,27 @@ def _ask(message: str, forced_lang: Optional[str], retrieved: List[Tuple[int, Di
|
|
| 369 |
|
| 370 |
client = _get_oai_client()
|
| 371 |
if client is None:
|
| 372 |
-
return
|
| 373 |
|
| 374 |
try:
|
|
|
|
| 375 |
resp = client.chat.completions.create(
|
| 376 |
model=MODEL,
|
| 377 |
messages=messages,
|
| 378 |
temperature=0.1,
|
| 379 |
-
|
| 380 |
-
max_tokens=450,
|
| 381 |
)
|
| 382 |
-
|
| 383 |
-
if out:
|
| 384 |
-
return out
|
| 385 |
-
return FALLBACK_ZH if (forced_lang == "zh") else FALLBACK_EN
|
| 386 |
except Exception as e:
|
| 387 |
print("OpenAI error:", e)
|
| 388 |
-
return
|
|
|
|
| 389 |
|
| 390 |
# ============================================================
|
| 391 |
-
# Languages & greetings (
|
|
|
|
| 392 |
# ============================================================
|
|
|
|
| 393 |
LANG_ITEMS = [
|
| 394 |
("auto", "Auto / 自动 (auto)"),
|
| 395 |
("en", "English"),
|
|
@@ -446,9 +457,6 @@ LANG_ITEMS = [
|
|
| 446 |
LANG_LABEL_BY_CODE = {code: label for code, label in LANG_ITEMS}
|
| 447 |
LANG_CODE_BY_LABEL = {label: code for code, label in LANG_ITEMS}
|
| 448 |
|
| 449 |
-
def base_lang(code: str) -> str:
|
| 450 |
-
return (code or "en").split("-")[0]
|
| 451 |
-
|
| 452 |
SEARCH_PLACEHOLDERS = {
|
| 453 |
"en": "Search languages",
|
| 454 |
"zh": "搜索语言",
|
|
@@ -486,58 +494,34 @@ GREETINGS = {
|
|
| 486 |
"• 建议一次只问一个清晰的问题,效果更好。\n\n"
|
| 487 |
"请问你想了解什么?"
|
| 488 |
),
|
| 489 |
-
"es": (
|
| 490 |
-
"👋 Hola, soy el chatbot de Cheshire Academy.\n\n"
|
| 491 |
-
"Puedo responder preguntas sobre estudios, admisiones, vida en el campus, deportes, formularios, calendarios y más.\n"
|
| 492 |
-
"• Pregunta en español o cambia de idioma con el icono del globo.\n"
|
| 493 |
-
"• Una pregunta clara a la vez funciona mejor.\n\n"
|
| 494 |
-
"¿En qué puedo ayudarte hoy?"
|
| 495 |
-
),
|
| 496 |
-
"fr": (
|
| 497 |
-
"👋 Bonjour ! Je suis le chatbot de Cheshire Academy.\n\n"
|
| 498 |
-
"Je peux répondre aux questions sur les études, l’admission, la vie sur le campus, le sport, les formulaires, le calendrier, etc.\n"
|
| 499 |
-
"• Pose ta question en français ou change de langue avec l’icône du globe.\n"
|
| 500 |
-
"• Une question claire à la fois, c’est l’idéal.\n\n"
|
| 501 |
-
"Comment puis-je t’aider ?"
|
| 502 |
-
),
|
| 503 |
-
"de": (
|
| 504 |
-
"👋 Hallo! Ich bin der Chatbot der Cheshire Academy.\n\n"
|
| 505 |
-
"Ich beantworte Fragen zu Unterricht, Aufnahme, Campusleben, Sport, Formularen, Kalendern und mehr.\n"
|
| 506 |
-
"• Stell deine Frage auf Deutsch oder wechsle die Sprache über das Globus-Symbol.\n"
|
| 507 |
-
"• Eine klare Frage nach der anderen funktioniert am besten.\n\n"
|
| 508 |
-
"Wobei kann ich heute helfen?"
|
| 509 |
-
),
|
| 510 |
-
"id": (
|
| 511 |
-
"👋 Hai! Saya chatbot Cheshire Academy.\n\n"
|
| 512 |
-
"Saya bisa menjawab pertanyaan tentang akademik, penerimaan, kehidupan kampus, olahraga, formulir, kalender, dan lain-lain.\n"
|
| 513 |
-
"• Tanyakan dalam Bahasa Indonesia atau ganti bahasa lewat ikon bumi.\n"
|
| 514 |
-
"• Satu pertanyaan yang jelas setiap kali akan bekerja paling baik.\n\n"
|
| 515 |
-
"Apa yang bisa saya bantu hari ini?"
|
| 516 |
-
),
|
| 517 |
}
|
| 518 |
|
|
|
|
| 519 |
def greeting_for(code: str) -> str:
|
|
|
|
| 520 |
base = base_lang(code)
|
| 521 |
-
|
| 522 |
-
|
|
|
|
|
|
|
|
|
|
| 523 |
|
| 524 |
def search_placeholder_for(code: str) -> str:
|
| 525 |
base = base_lang(code)
|
| 526 |
return SEARCH_PLACEHOLDERS.get(base, SEARCH_PLACEHOLDERS["en"])
|
| 527 |
|
|
|
|
| 528 |
# ============================================================
|
| 529 |
# Gradio callbacks
|
| 530 |
# ============================================================
|
|
|
|
| 531 |
def _ensure_messages_history(history: Any) -> List[Dict[str, str]]:
|
| 532 |
-
"""
|
| 533 |
-
Gradio 6 messages format:
|
| 534 |
-
[{"role":"user","content":"..."}, {"role":"assistant","content":"..."}]
|
| 535 |
-
"""
|
| 536 |
if not history:
|
| 537 |
return []
|
| 538 |
|
| 539 |
if isinstance(history, list) and history:
|
| 540 |
first = history[0]
|
|
|
|
| 541 |
if isinstance(first, dict) and "role" in first and "content" in first:
|
| 542 |
out: List[Dict[str, str]] = []
|
| 543 |
for m in history:
|
|
@@ -545,10 +529,13 @@ def _ensure_messages_history(history: Any) -> List[Dict[str, str]]:
|
|
| 545 |
out.append({"role": str(m["role"]), "content": str(m["content"])})
|
| 546 |
return out
|
| 547 |
|
| 548 |
-
# tolerate
|
| 549 |
if isinstance(first, (tuple, list)) and len(first) == 2:
|
| 550 |
out: List[Dict[str, str]] = []
|
| 551 |
-
for
|
|
|
|
|
|
|
|
|
|
| 552 |
if u is not None and str(u).strip():
|
| 553 |
out.append({"role": "user", "content": str(u)})
|
| 554 |
if a is not None and str(a).strip():
|
|
@@ -557,6 +544,7 @@ def _ensure_messages_history(history: Any) -> List[Dict[str, str]]:
|
|
| 557 |
|
| 558 |
return []
|
| 559 |
|
|
|
|
| 560 |
def respond(message: str, history, lang_code: str):
|
| 561 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 562 |
history_msgs = _ensure_messages_history(history)
|
|
@@ -565,27 +553,42 @@ def respond(message: str, history, lang_code: str):
|
|
| 565 |
if not message:
|
| 566 |
return "", history_msgs
|
| 567 |
|
| 568 |
-
#
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
route = _route_message(message, retrieved)
|
| 572 |
if route != "allow":
|
| 573 |
answer = _render_refusal(route, forced, message)
|
| 574 |
else:
|
| 575 |
-
answer = _ask(message, forced_lang=forced
|
| 576 |
|
| 577 |
history_msgs.append({"role": "user", "content": message})
|
| 578 |
history_msgs.append({"role": "assistant", "content": answer})
|
| 579 |
return "", history_msgs
|
| 580 |
|
|
|
|
| 581 |
def greet(lang_code: str):
|
| 582 |
msg = greeting_for(lang_code)
|
| 583 |
return [{"role": "assistant", "content": msg}]
|
| 584 |
|
| 585 |
-
|
| 586 |
-
|
| 587 |
new_open = not bool(is_open)
|
| 588 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 589 |
|
| 590 |
def filter_languages(search: str, lang_code: str):
|
| 591 |
search = (search or "").strip().lower()
|
|
@@ -605,9 +608,9 @@ def filter_languages(search: str, lang_code: str):
|
|
| 605 |
|
| 606 |
return gr.update(choices=choices, value=current_label), lang_code
|
| 607 |
|
|
|
|
| 608 |
def select_language(label: str):
|
| 609 |
code = LANG_CODE_BY_LABEL.get(label, "auto")
|
| 610 |
-
# 选择后:更新语言状态、重置对话到 greeting、清空搜索框、隐藏面板、menu_open=False
|
| 611 |
return (
|
| 612 |
code,
|
| 613 |
greet(code),
|
|
@@ -616,9 +619,11 @@ def select_language(label: str):
|
|
| 616 |
False,
|
| 617 |
)
|
| 618 |
|
|
|
|
| 619 |
# ============================================================
|
| 620 |
-
# CSS
|
| 621 |
# ============================================================
|
|
|
|
| 622 |
CSS = """
|
| 623 |
#ca-wrapper {
|
| 624 |
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
@@ -633,69 +638,55 @@ CSS = """
|
|
| 633 |
display:flex;
|
| 634 |
align-items:center;
|
| 635 |
justify-content:space-between;
|
| 636 |
-
gap: 12px;
|
| 637 |
}
|
| 638 |
|
| 639 |
#ca-title {
|
| 640 |
font-size:18px;
|
| 641 |
font-weight:600;
|
| 642 |
color:#ffffff;
|
| 643 |
-
flex: 1
|
| 644 |
padding-right:12px;
|
| 645 |
white-space:normal;
|
| 646 |
overflow:visible;
|
| 647 |
text-overflow:clip;
|
| 648 |
}
|
| 649 |
|
| 650 |
-
/* Make the globe wrapper NOT stretch */
|
| 651 |
-
#ca-lang-btn {
|
| 652 |
-
flex: 0 0 auto !important;
|
| 653 |
-
width: 44px !important;
|
| 654 |
-
max-width: 44px !important;
|
| 655 |
-
}
|
| 656 |
-
|
| 657 |
/* Globe button */
|
| 658 |
#ca-lang-btn button {
|
| 659 |
-
background:#e5e7eb
|
| 660 |
-
border-radius:999px
|
| 661 |
-
color:#1f2933
|
| 662 |
-
border:none
|
| 663 |
-
width:40px
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
align-items:center !important;
|
| 670 |
-
justify-content:center !important;
|
| 671 |
}
|
| 672 |
-
#ca-lang-btn button:hover {
|
| 673 |
-
|
| 674 |
-
/* Language panel: floating card at top-right */
|
| 675 |
-
#ca-lang-panel {
|
| 676 |
-
position:absolute !important;
|
| 677 |
-
top:52px !important;
|
| 678 |
-
right:16px !important;
|
| 679 |
-
width:280px !important;
|
| 680 |
-
max-height:360px !important;
|
| 681 |
-
background:#fff !important;
|
| 682 |
-
border-radius:12px !important;
|
| 683 |
-
box-shadow:0 12px 32px rgba(0,0,0,.35) !important;
|
| 684 |
-
padding:10px 10px 8px 10px !important;
|
| 685 |
-
z-index:9999 !important;
|
| 686 |
}
|
| 687 |
|
| 688 |
-
/*
|
| 689 |
-
#ca-lang-panel
|
| 690 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 691 |
}
|
| 692 |
|
| 693 |
-
/* Search box
|
| 694 |
-
#ca-lang-search textarea
|
| 695 |
-
#ca-lang-search input {
|
| 696 |
resize:none !important;
|
| 697 |
min-height:34px !important;
|
| 698 |
-
height:34px !important;
|
| 699 |
padding:6px 10px !important;
|
| 700 |
font-size:13px !important;
|
| 701 |
border-radius:999px !important;
|
|
@@ -704,25 +695,24 @@ CSS = """
|
|
| 704 |
|
| 705 |
/* Language list, scrollable */
|
| 706 |
#ca-lang-radio {
|
| 707 |
-
max-height:270px
|
| 708 |
-
overflow-y:auto
|
| 709 |
-
margin-top:8px
|
| 710 |
}
|
| 711 |
"""
|
| 712 |
|
| 713 |
# ============================================================
|
| 714 |
-
# UI
|
| 715 |
# ============================================================
|
| 716 |
-
|
|
|
|
| 717 |
lang_state = gr.State("auto")
|
| 718 |
menu_open = gr.State(False)
|
| 719 |
|
| 720 |
-
# Header
|
| 721 |
with gr.Row(elem_id="ca-header"):
|
| 722 |
gr.HTML('<div id="ca-title">Cheshire Academy Chatbot</div>')
|
| 723 |
lang_btn = gr.Button("🌐", elem_id="ca-lang-btn", scale=0)
|
| 724 |
|
| 725 |
-
# Floating panel
|
| 726 |
with gr.Column(visible=False, elem_id="ca-lang-panel") as lang_panel:
|
| 727 |
lang_search = gr.Textbox(
|
| 728 |
value="",
|
|
@@ -747,44 +737,34 @@ with gr.Blocks(fill_height=True, css=CSS, elem_id="ca-wrapper") as demo:
|
|
| 747 |
lines=2,
|
| 748 |
)
|
| 749 |
send_btn = gr.Button("Send")
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
# Greeting on load
|
| 753 |
-
demo.load(greet, inputs=[lang_state], outputs=[chatbot], queue=False)
|
| 754 |
|
| 755 |
-
# Send message (keep queued; this is the slow OpenAI part)
|
| 756 |
send_btn.click(
|
| 757 |
respond,
|
| 758 |
inputs=[msg_box, chatbot, lang_state],
|
| 759 |
outputs=[msg_box, chatbot],
|
| 760 |
-
queue=True,
|
| 761 |
)
|
| 762 |
|
| 763 |
-
|
|
|
|
| 764 |
lang_btn.click(
|
| 765 |
toggle_lang_menu,
|
| 766 |
-
inputs=[menu_open],
|
| 767 |
-
outputs=[menu_open, lang_panel],
|
| 768 |
-
queue=False,
|
| 769 |
)
|
| 770 |
|
| 771 |
-
# Filter languages - not queued
|
| 772 |
lang_search.change(
|
| 773 |
filter_languages,
|
| 774 |
inputs=[lang_search, lang_state],
|
| 775 |
outputs=[lang_radio, lang_state],
|
| 776 |
-
queue=False,
|
| 777 |
)
|
| 778 |
|
| 779 |
-
# Select language - not queued (hide panel immediately)
|
| 780 |
lang_radio.change(
|
| 781 |
select_language,
|
| 782 |
inputs=[lang_radio],
|
| 783 |
outputs=[lang_state, chatbot, lang_search, lang_panel, menu_open],
|
| 784 |
-
queue=False,
|
| 785 |
)
|
| 786 |
|
| 787 |
-
# Click outside = close panel (front-end click triggers globe once)
|
| 788 |
gr.HTML(
|
| 789 |
"""
|
| 790 |
<script>
|
|
@@ -798,10 +778,9 @@ with gr.Blocks(fill_height=True, css=CSS, elem_id="ca-wrapper") as demo:
|
|
| 798 |
|
| 799 |
document.addEventListener('click', function(ev) {
|
| 800 |
const style = window.getComputedStyle(panel);
|
| 801 |
-
|
| 802 |
-
if (isHidden) return;
|
| 803 |
if (panel.contains(ev.target) || btnWrapper.contains(ev.target)) return;
|
| 804 |
-
btn.click();
|
| 805 |
});
|
| 806 |
}
|
| 807 |
window.setTimeout(setup, 600);
|
|
@@ -812,6 +791,4 @@ with gr.Blocks(fill_height=True, css=CSS, elem_id="ca-wrapper") as demo:
|
|
| 812 |
)
|
| 813 |
|
| 814 |
if __name__ == "__main__":
|
| 815 |
-
|
| 816 |
-
demo.queue(default_concurrency_limit=int(os.getenv("GRADIO_CONCURRENCY", "8")))
|
| 817 |
-
demo.launch()
|
|
|
|
| 1 |
import os
|
| 2 |
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 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 11 |
|
| 12 |
# ============================================================
|
| 13 |
+
# Config
|
| 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 |
def _load_sources() -> List[Dict[str, str]]:
|
| 43 |
docs: List[Dict[str, str]] = []
|
| 44 |
if not SOURCES_DIR.exists():
|
|
|
|
| 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 |
if not plain:
|
| 65 |
continue
|
| 66 |
|
| 67 |
+
# keep context reasonably small for speed
|
| 68 |
+
snippet = plain[:3000]
|
| 69 |
+
docs.append({"path": str(path.relative_to(BASE_DIR)), "text": snippet})
|
|
|
|
|
|
|
| 70 |
|
| 71 |
print(f"Loaded {len(docs)} source documents.")
|
| 72 |
return docs
|
| 73 |
|
| 74 |
+
|
| 75 |
+
DOCS = _load_sources()
|
| 76 |
|
| 77 |
# ============================================================
|
| 78 |
+
# Retrieval helpers
|
| 79 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
# Small bilingual keyword expansion so Chinese sports questions can hit English docs
|
| 82 |
+
ZH_EN_HINTS: List[Tuple[str, List[str]]] = [
|
| 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 |
+
q_raw = (message or "").strip()
|
| 110 |
+
q = q_raw.lower()
|
| 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 |
+
extra_keywords: List[str] = []
|
|
|
|
| 116 |
|
| 117 |
+
# IB expansion
|
| 118 |
+
if "ib" in q:
|
| 119 |
+
extra_keywords += ["international baccalaureate", "ib programme", "ib program"]
|
|
|
|
| 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 |
+
keywords = tokens + extra_keywords
|
| 127 |
+
if not keywords:
|
| 128 |
return []
|
| 129 |
|
| 130 |
+
scores: List[tuple[int, Dict[str, str]]] = []
|
| 131 |
+
for doc in DOCS:
|
| 132 |
+
text = doc["text"].lower()
|
| 133 |
+
score = 0
|
| 134 |
+
for kw in keywords:
|
| 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 |
+
scores.sort(key=lambda x: x[0], reverse=True)
|
| 144 |
+
return [d for _, d in scores[:top_k]]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _has_any_retrieval_hit(message: str) -> bool:
|
| 148 |
+
# quick “is this about CA?” signal that is better than only CA_TOPIC_KEYWORDS
|
| 149 |
+
hits = _retrieve(message, top_k=1)
|
| 150 |
+
return bool(hits)
|
| 151 |
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# ============================================================
|
| 154 |
+
# Guardrails / Refusal rules
|
|
|
|
|
|
|
|
|
|
| 155 |
# ============================================================
|
| 156 |
+
|
| 157 |
CA_ENTITY_KEYWORDS = [
|
| 158 |
+
"cheshire", "cheshire academy", "cheshireacademy",
|
| 159 |
"切舍尔", "切舍尔中学", "柴郡", "柴郡学院", "柴俊学院",
|
| 160 |
+
"cheshireacademy.org",
|
| 161 |
]
|
| 162 |
|
| 163 |
+
# Topics that MAY be about CA (sports/news etc.) but should not auto-pass 100%.
|
| 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 |
+
"basketball", "soccer", "football", "baseball", "tennis", "golf", "track",
|
| 171 |
+
"match", "game", "score", "result", "opponent", "team", "tournament",
|
| 172 |
+
"news", "events", "announcement",
|
| 173 |
# Chinese
|
| 174 |
+
"招生", "申请", "报名", "截止", "截止日期", "学费", "费用", "奖学金", "助学金",
|
| 175 |
+
"寄宿", "宿舍", "校园", "体育", "运动", "日历", "表格", "课程", "学术", "IB", "访校", "开放日",
|
| 176 |
+
"篮球", "足球", "美式足球", "网球", "棒球", "田径", "游泳", "高尔夫",
|
| 177 |
+
"比赛", "比分", "成绩", "对手", "赛季", "校队", "战报", "新闻", "活动",
|
| 178 |
]
|
| 179 |
|
|
|
|
| 180 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 181 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 182 |
+
"case", "allegation", "scandal",
|
| 183 |
+
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控",
|
| 184 |
]
|
| 185 |
|
|
|
|
| 186 |
ADULT_CONTENT_KEYWORDS = [
|
| 187 |
"porn", "xxx", "nude", "sex", "hookup", "onlyfans",
|
| 188 |
"色情", "黄片", "裸照", "成人视频", "约炮", "做爰",
|
| 189 |
]
|
| 190 |
|
|
|
|
| 191 |
SELF_HARM_KEYWORDS = [
|
| 192 |
"suicide", "kill myself", "self-harm", "cut myself", "end my life",
|
| 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 |
def _guess_lang_code_from_message(message: str) -> str:
|
| 203 |
s = message or ""
|
| 204 |
if re.search(r"[\u4e00-\u9fff]", s):
|
| 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": (
|
|
|
|
| 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 question involves content that isn’t appropriate to discuss here (e.g., legal cases/allegations).\n\n"
|
| 235 |
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life,** etc."
|
| 236 |
),
|
| 237 |
"zh": (
|
| 238 |
+
"我可以帮助回答 **切舍尔中学的招生与校园信息**。但这个问题涉及不适合在这里讨论的内容(例如法律纠纷/指控/具体案件)。\n\n"
|
| 239 |
"请你换一个关于 **课程项目、招生申请、学费、截止日期、寄宿与校园生活** 等方面的问题再问一遍。"
|
| 240 |
),
|
| 241 |
},
|
|
|
|
| 262 |
"如果你愿意,也可以告诉我发生了什么,我会倾听并帮你一起寻找支持。"
|
| 263 |
),
|
| 264 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
}
|
| 266 |
|
| 267 |
+
|
| 268 |
def _render_refusal(kind: str, lang_code: Optional[str], message: str) -> str:
|
| 269 |
base = (lang_code or "").split("-")[0].strip().lower()
|
| 270 |
if not base:
|
|
|
|
| 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 |
+
- allow -> normal RAG answer
|
| 281 |
+
- non_ca -> refuse (not school)
|
| 282 |
+
- maybe_ca -> likely school topic but lacks CA anchor; ask for context fast (no OpenAI)
|
| 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 |
+
is_ca_entity = _contains_any(m, CA_ENTITY_KEYWORDS)
|
| 299 |
+
# retrieval hit is a strong signal
|
| 300 |
+
has_hit = _has_any_retrieval_hit(m)
|
| 301 |
+
is_topicish = _contains_any(m, CA_TOPIC_KEYWORDS)
|
| 302 |
|
| 303 |
+
if is_ca_entity or has_hit:
|
| 304 |
+
return "allow"
|
|
|
|
|
|
|
| 305 |
|
| 306 |
+
# topic-ish but no anchor: don't hard-refuse; ask user to clarify CA context
|
| 307 |
+
if is_topicish:
|
| 308 |
+
return "maybe_ca"
|
| 309 |
|
| 310 |
return "non_ca"
|
| 311 |
|
| 312 |
+
|
| 313 |
# ============================================================
|
| 314 |
+
# OpenAI client (with timeout)
|
| 315 |
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
_OAI_CLIENT: Optional[OpenAI] = None
|
| 318 |
|
| 319 |
+
|
| 320 |
def _get_oai_client() -> Optional[OpenAI]:
|
| 321 |
global _OAI_CLIENT
|
| 322 |
if _OAI_CLIENT is not None:
|
|
|
|
| 329 |
return None
|
| 330 |
|
| 331 |
try:
|
| 332 |
+
# Set hard timeout & low retries to avoid infinite processing
|
| 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 base_lang(code: str) -> str:
|
| 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 FAQ assistant.\n"
|
| 352 |
"You are given reference text from the official Cheshire Academy website.\n"
|
| 353 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 354 |
+
"Rely ONLY on those references for facts about programs (including IB), tuition, deadlines, policies, and campus details.\n"
|
| 355 |
+
"If the documents do not clearly answer, say you are not certain and suggest contacting the school instead of guessing.\n"
|
| 356 |
"Do NOT answer general knowledge, politics, or unrelated questions.\n"
|
| 357 |
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users back to admissions/campus questions.\n"
|
| 358 |
"Be concise and student-friendly.\n"
|
| 359 |
)
|
| 360 |
+
|
| 361 |
if forced_lang and forced_lang != "auto":
|
| 362 |
system += f"Always answer in the language whose base code is '{forced_lang}'.\n"
|
| 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 |
+
"Here are reference excerpts from the official Cheshire Academy website. "
|
| 372 |
+
"Use them as the primary source for your answer:\n\n"
|
| 373 |
+
+ "\n\n---\n\n".join(chunks)
|
| 374 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
messages = [{"role": "system", "content": system}]
|
| 377 |
if context:
|
|
|
|
| 380 |
|
| 381 |
client = _get_oai_client()
|
| 382 |
if client is None:
|
| 383 |
+
return FALLBACK_EN
|
| 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 |
+
timeout=OAI_TIMEOUT,
|
|
|
|
| 392 |
)
|
| 393 |
+
return (resp.choices[0].message.content or "").strip() or FALLBACK_EN
|
|
|
|
|
|
|
|
|
|
| 394 |
except Exception as e:
|
| 395 |
print("OpenAI error:", e)
|
| 396 |
+
return FALLBACK_EN
|
| 397 |
+
|
| 398 |
|
| 399 |
# ============================================================
|
| 400 |
+
# Languages & greetings (IMPORTANT: NO dynamic OpenAI translation)
|
| 401 |
+
# -> prevents language switch from "processing forever"
|
| 402 |
# ============================================================
|
| 403 |
+
|
| 404 |
LANG_ITEMS = [
|
| 405 |
("auto", "Auto / 自动 (auto)"),
|
| 406 |
("en", "English"),
|
|
|
|
| 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": "搜索语言",
|
|
|
|
| 494 |
"• 建议一次只问一个清晰的问题,效果更好。\n\n"
|
| 495 |
"请问你想了解什么?"
|
| 496 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
}
|
| 498 |
|
| 499 |
+
|
| 500 |
def greeting_for(code: str) -> str:
|
| 501 |
+
# IMPORTANT: do NOT call OpenAI here (prevents language switch stuck)
|
| 502 |
base = base_lang(code)
|
| 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 |
base = base_lang(code)
|
| 511 |
return SEARCH_PLACEHOLDERS.get(base, SEARCH_PLACEHOLDERS["en"])
|
| 512 |
|
| 513 |
+
|
| 514 |
# ============================================================
|
| 515 |
# Gradio callbacks
|
| 516 |
# ============================================================
|
| 517 |
+
|
| 518 |
def _ensure_messages_history(history: Any) -> List[Dict[str, str]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
|
|
| 529 |
out.append({"role": str(m["role"]), "content": str(m["content"])})
|
| 530 |
return out
|
| 531 |
|
| 532 |
+
# tolerate tuples: [(user, assistant), ...]
|
| 533 |
if isinstance(first, (tuple, list)) and len(first) == 2:
|
| 534 |
out: List[Dict[str, str]] = []
|
| 535 |
+
for pair in history:
|
| 536 |
+
if not isinstance(pair, (tuple, list)) or len(pair) != 2:
|
| 537 |
+
continue
|
| 538 |
+
u, a = pair
|
| 539 |
if u is not None and str(u).strip():
|
| 540 |
out.append({"role": "user", "content": str(u)})
|
| 541 |
if a is not None and str(a).strip():
|
|
|
|
| 544 |
|
| 545 |
return []
|
| 546 |
|
| 547 |
+
|
| 548 |
def respond(message: str, history, lang_code: str):
|
| 549 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 550 |
history_msgs = _ensure_messages_history(history)
|
|
|
|
| 553 |
if not message:
|
| 554 |
return "", history_msgs
|
| 555 |
|
| 556 |
+
# Fast guardrails first (NO OpenAI calls)
|
| 557 |
+
route = _route_message(message)
|
|
|
|
|
|
|
| 558 |
if route != "allow":
|
| 559 |
answer = _render_refusal(route, forced, message)
|
| 560 |
else:
|
| 561 |
+
answer = _ask(message, forced_lang=forced)
|
| 562 |
|
| 563 |
history_msgs.append({"role": "user", "content": message})
|
| 564 |
history_msgs.append({"role": "assistant", "content": answer})
|
| 565 |
return "", history_msgs
|
| 566 |
|
| 567 |
+
|
| 568 |
def greet(lang_code: str):
|
| 569 |
msg = greeting_for(lang_code)
|
| 570 |
return [{"role": "assistant", "content": msg}]
|
| 571 |
|
| 572 |
+
|
| 573 |
+
def toggle_lang_menu(is_open: bool, lang_code: str):
|
| 574 |
new_open = not bool(is_open)
|
| 575 |
+
if new_open:
|
| 576 |
+
choices = [label for _, label in LANG_ITEMS]
|
| 577 |
+
current_label = LANG_LABEL_BY_CODE.get(lang_code, LANG_LABEL_BY_CODE["auto"])
|
| 578 |
+
return (
|
| 579 |
+
new_open,
|
| 580 |
+
gr.update(visible=True),
|
| 581 |
+
gr.update(value="", placeholder=search_placeholder_for(lang_code)),
|
| 582 |
+
gr.update(choices=choices, value=current_label),
|
| 583 |
+
)
|
| 584 |
+
else:
|
| 585 |
+
return (
|
| 586 |
+
new_open,
|
| 587 |
+
gr.update(visible=False),
|
| 588 |
+
gr.update(),
|
| 589 |
+
gr.update(),
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
|
| 593 |
def filter_languages(search: str, lang_code: str):
|
| 594 |
search = (search or "").strip().lower()
|
|
|
|
| 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 (
|
| 615 |
code,
|
| 616 |
greet(code),
|
|
|
|
| 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;
|
|
|
|
| 638 |
display:flex;
|
| 639 |
align-items:center;
|
| 640 |
justify-content:space-between;
|
|
|
|
| 641 |
}
|
| 642 |
|
| 643 |
#ca-title {
|
| 644 |
font-size:18px;
|
| 645 |
font-weight:600;
|
| 646 |
color:#ffffff;
|
| 647 |
+
flex: 1;
|
| 648 |
padding-right:12px;
|
| 649 |
white-space:normal;
|
| 650 |
overflow:visible;
|
| 651 |
text-overflow:clip;
|
| 652 |
}
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
/* Globe button */
|
| 655 |
#ca-lang-btn button {
|
| 656 |
+
background:#e5e7eb;
|
| 657 |
+
border-radius:999px;
|
| 658 |
+
color:#1f2933;
|
| 659 |
+
border:none;
|
| 660 |
+
width:40px;
|
| 661 |
+
height:40px;
|
| 662 |
+
font-size:20px;
|
| 663 |
+
display:flex;
|
| 664 |
+
align-items:center;
|
| 665 |
+
justify-content:center;
|
|
|
|
|
|
|
| 666 |
}
|
| 667 |
+
#ca-lang-btn button:hover {
|
| 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;
|
| 677 |
+
max-height:360px;
|
| 678 |
+
background:#fff;
|
| 679 |
+
border-radius:12px;
|
| 680 |
+
box-shadow:0 12px 32px rgba(0,0,0,.35);
|
| 681 |
+
padding:10px 10px 8px 10px;
|
| 682 |
+
z-index:50;
|
| 683 |
}
|
| 684 |
|
| 685 |
+
/* Search box */
|
| 686 |
+
#ca-lang-search textarea {
|
|
|
|
| 687 |
resize:none !important;
|
| 688 |
min-height:34px !important;
|
| 689 |
+
max-height:34px !important;
|
| 690 |
padding:6px 10px !important;
|
| 691 |
font-size:13px !important;
|
| 692 |
border-radius:999px !important;
|
|
|
|
| 695 |
|
| 696 |
/* Language list, scrollable */
|
| 697 |
#ca-lang-radio {
|
| 698 |
+
max-height:270px;
|
| 699 |
+
overflow-y:auto;
|
| 700 |
+
margin-top:8px;
|
| 701 |
}
|
| 702 |
"""
|
| 703 |
|
| 704 |
# ============================================================
|
| 705 |
+
# Gradio UI
|
| 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 |
with gr.Column(visible=False, elem_id="ca-lang-panel") as lang_panel:
|
| 717 |
lang_search = gr.Textbox(
|
| 718 |
value="",
|
|
|
|
| 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],
|
| 745 |
outputs=[msg_box, chatbot],
|
|
|
|
| 746 |
)
|
| 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 |
|
| 779 |
document.addEventListener('click', function(ev) {
|
| 780 |
const style = window.getComputedStyle(panel);
|
| 781 |
+
if (style.display === 'none' || panel.hidden) return;
|
|
|
|
| 782 |
if (panel.contains(ev.target) || btnWrapper.contains(ev.target)) return;
|
| 783 |
+
btn.click();
|
| 784 |
});
|
| 785 |
}
|
| 786 |
window.setTimeout(setup, 600);
|
|
|
|
| 791 |
)
|
| 792 |
|
| 793 |
if __name__ == "__main__":
|
| 794 |
+
demo.launch(css=CSS)
|
|
|
|
|
|