Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,24 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
-
from typing import Optional, List, Dict, Any
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
from openai import OpenAI
|
| 8 |
|
| 9 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 10 |
|
| 11 |
-
#
|
|
|
|
|
|
|
|
|
|
| 12 |
BASE_DIR = Path(__file__).parent
|
| 13 |
SOURCES_DIR = BASE_DIR / "sources"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def _strip_html(text: str) -> str:
|
|
@@ -20,25 +28,40 @@ def _strip_html(text: str) -> str:
|
|
| 20 |
return text.strip()
|
| 21 |
|
| 22 |
|
| 23 |
-
def _load_sources() -> List[Dict[str,
|
| 24 |
"""
|
| 25 |
-
Load all .txt / .md / .html / .htm files under sources/ into memory
|
| 26 |
-
|
| 27 |
"""
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
if not SOURCES_DIR.exists():
|
| 30 |
print("WARNING: sources/ folder not found")
|
|
|
|
| 31 |
return docs
|
| 32 |
|
| 33 |
for path in SOURCES_DIR.rglob("*"):
|
| 34 |
if not path.is_file():
|
| 35 |
continue
|
|
|
|
|
|
|
| 36 |
if path.suffix.lower() not in {".txt", ".md", ".html", ".htm"}:
|
| 37 |
continue
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
raw = path.read_text(encoding="utf-8", errors="ignore")
|
| 40 |
-
except Exception
|
| 41 |
-
print("Read error:", path, e)
|
| 42 |
continue
|
| 43 |
|
| 44 |
# strip HTML tags if needed
|
|
@@ -50,82 +73,71 @@ def _load_sources() -> List[Dict[str, str]]:
|
|
| 50 |
if not plain:
|
| 51 |
continue
|
| 52 |
|
| 53 |
-
snippet = plain[:
|
| 54 |
-
docs.append(
|
| 55 |
-
{
|
| 56 |
-
"path": str(path.relative_to(BASE_DIR)),
|
| 57 |
-
"text": snippet,
|
| 58 |
-
}
|
| 59 |
-
)
|
| 60 |
|
|
|
|
|
|
|
| 61 |
print(f"Loaded {len(docs)} source documents.")
|
| 62 |
return docs
|
| 63 |
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _retrieve(message: str, top_k: int = 4) -> List[Dict[str, str]]:
|
| 69 |
"""
|
| 70 |
-
|
| 71 |
- tokenizes the question,
|
| 72 |
- matches keywords in each doc,
|
| 73 |
- returns the top_k docs with highest match counts.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"""
|
| 75 |
-
|
|
|
|
| 76 |
return []
|
| 77 |
|
| 78 |
q = (message or "").lower()
|
| 79 |
tokens = [w for w in re.split(r"[^a-z0-9]+", q) if len(w) > 2]
|
| 80 |
|
| 81 |
-
#
|
| 82 |
extra_keywords = []
|
| 83 |
if "ib" in q:
|
| 84 |
-
extra_keywords
|
| 85 |
-
extra_keywords.append("ib programme")
|
| 86 |
-
extra_keywords.append("ib program")
|
| 87 |
keywords = tokens + extra_keywords
|
| 88 |
|
| 89 |
-
|
| 90 |
-
for
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
score = 0
|
| 93 |
for kw in keywords:
|
| 94 |
if kw and kw in text:
|
| 95 |
score += 1
|
| 96 |
if score > 0:
|
| 97 |
-
|
| 98 |
|
| 99 |
-
if not
|
| 100 |
return []
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
|
| 106 |
# ============================================================
|
| 107 |
-
# Guardrails / Refusal rules
|
| 108 |
# ============================================================
|
| 109 |
|
| 110 |
-
CA_ENTITY_KEYWORDS = [
|
| 111 |
-
"cheshire", "cheshire academy", "cheshireacademy",
|
| 112 |
-
"切舍尔", "切舍尔中学", "柴郡", "柴郡学院", "柴俊学院",
|
| 113 |
-
"cheshireacademy.org",
|
| 114 |
-
]
|
| 115 |
-
|
| 116 |
-
CA_TOPIC_KEYWORDS = [
|
| 117 |
-
"admission", "apply", "application", "deadline", "tuition", "fees", "scholarship",
|
| 118 |
-
"boarding", "dorm", "campus", "athletics", "sports", "calendar", "forms",
|
| 119 |
-
"ib", "international baccalaureate", "class", "course", "academics",
|
| 120 |
-
"financial aid", "visit", "open house",
|
| 121 |
-
"招生", "申请", "报名", "截止", "截止日期", "学费", "费用", "奖学金", "助学金",
|
| 122 |
-
"寄宿", "宿舍", "校园", "体育", "运动", "日历", "表格", "课程", "学术", "IB", "访校", "开放日",
|
| 123 |
-
]
|
| 124 |
-
|
| 125 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 126 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 127 |
-
"
|
| 128 |
-
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控",
|
| 129 |
]
|
| 130 |
|
| 131 |
ADULT_CONTENT_KEYWORDS = [
|
|
@@ -141,7 +153,7 @@ SELF_HARM_KEYWORDS = [
|
|
| 141 |
|
| 142 |
def _contains_any(text: str, keywords: List[str]) -> bool:
|
| 143 |
t = (text or "").lower()
|
| 144 |
-
return any(k.lower() in t for k in keywords if k)
|
| 145 |
|
| 146 |
|
| 147 |
def _guess_lang_code_from_message(message: str) -> str:
|
|
@@ -166,7 +178,7 @@ REFUSAL_TEMPLATES = {
|
|
| 166 |
"sensitive_school": {
|
| 167 |
"en": (
|
| 168 |
"I’m here to help with **Cheshire Academy admissions and campus information**. "
|
| 169 |
-
"This
|
| 170 |
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life,** etc."
|
| 171 |
),
|
| 172 |
"zh": (
|
|
@@ -201,18 +213,28 @@ REFUSAL_TEMPLATES = {
|
|
| 201 |
|
| 202 |
|
| 203 |
def _render_refusal(kind: str, lang_code: Optional[str], message: str) -> str:
|
| 204 |
-
base = (lang_code or "").split("-")[0].strip().lower()
|
| 205 |
-
if not base:
|
| 206 |
-
base = _guess_lang_code_from_message(message)
|
| 207 |
if base not in ("en", "zh"):
|
| 208 |
base = "en"
|
| 209 |
return REFUSAL_TEMPLATES.get(kind, {}).get(base) or REFUSAL_TEMPLATES["non_ca"]["en"]
|
| 210 |
|
| 211 |
|
| 212 |
-
def _route_message(message: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
m = (message or "").strip()
|
| 214 |
if not m:
|
| 215 |
return "allow"
|
|
|
|
| 216 |
if _contains_any(m, SELF_HARM_KEYWORDS):
|
| 217 |
return "self_harm"
|
| 218 |
if _contains_any(m, ADULT_CONTENT_KEYWORDS):
|
|
@@ -220,13 +242,20 @@ def _route_message(message: str) -> str:
|
|
| 220 |
if _contains_any(m, SENSITIVE_SCHOOL_CASE_KEYWORDS):
|
| 221 |
return "sensitive_school"
|
| 222 |
|
| 223 |
-
|
| 224 |
-
if
|
| 225 |
-
return "
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
|
| 229 |
-
#
|
|
|
|
|
|
|
|
|
|
| 230 |
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
|
| 231 |
|
| 232 |
FALLBACK_EN = (
|
|
@@ -238,7 +267,6 @@ _OAI_CLIENT: Optional[OpenAI] = None
|
|
| 238 |
|
| 239 |
|
| 240 |
def _get_oai_client() -> Optional[OpenAI]:
|
| 241 |
-
"""Lazy-init OpenAI client so the app won't crash at import-time."""
|
| 242 |
global _OAI_CLIENT
|
| 243 |
if _OAI_CLIENT is not None:
|
| 244 |
return _OAI_CLIENT
|
|
@@ -261,11 +289,11 @@ def _get_oai_client() -> Optional[OpenAI]:
|
|
| 261 |
def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
| 262 |
system = (
|
| 263 |
"You are a multilingual Cheshire Academy FAQ assistant.\n"
|
| 264 |
-
"You are given reference text from the official Cheshire Academy
|
| 265 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 266 |
-
"Rely ONLY on those references for facts
|
| 267 |
-
"If the
|
| 268 |
-
"Do NOT answer
|
| 269 |
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users back to admissions/campus questions.\n"
|
| 270 |
"Be concise and student-friendly.\n"
|
| 271 |
)
|
|
@@ -280,7 +308,7 @@ def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
|
| 280 |
for doc in retrieved:
|
| 281 |
chunks.append(f"Source file: {doc['path']}\n{doc['text']}")
|
| 282 |
context = (
|
| 283 |
-
"Here are reference excerpts from
|
| 284 |
"Use them as the primary source for your answer:\n\n"
|
| 285 |
+ "\n\n---\n\n".join(chunks)
|
| 286 |
)
|
|
@@ -306,7 +334,9 @@ def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
|
| 306 |
return FALLBACK_EN
|
| 307 |
|
| 308 |
|
| 309 |
-
#
|
|
|
|
|
|
|
| 310 |
|
| 311 |
LANG_ITEMS = [
|
| 312 |
("auto", "Auto / 自动 (auto)"),
|
|
@@ -471,132 +501,40 @@ def greeting_for(code: str) -> str:
|
|
| 471 |
_dynamic_greetings[base] = msg
|
| 472 |
return msg
|
| 473 |
return GREETINGS["en"]
|
| 474 |
-
except Exception
|
| 475 |
-
print("Greeting translation error:", e)
|
| 476 |
return GREETINGS["en"]
|
| 477 |
|
| 478 |
|
| 479 |
def search_placeholder_for(code: str) -> str:
|
| 480 |
-
|
| 481 |
-
return SEARCH_PLACEHOLDERS.get(base, SEARCH_PLACEHOLDERS["en"])
|
| 482 |
|
| 483 |
|
| 484 |
# ============================================================
|
| 485 |
-
#
|
|
|
|
| 486 |
# ============================================================
|
| 487 |
|
| 488 |
-
def
|
| 489 |
-
"""
|
| 490 |
-
Gradio 6 often stores Chatbot message content as a list of parts, e.g.
|
| 491 |
-
[{"type":"text","text":"..."}]
|
| 492 |
-
If we blindly str() this, it renders as code.
|
| 493 |
-
This function converts common part-lists back into plain strings.
|
| 494 |
-
"""
|
| 495 |
-
if content is None:
|
| 496 |
-
return ""
|
| 497 |
-
|
| 498 |
-
if isinstance(content, str):
|
| 499 |
-
return content
|
| 500 |
-
|
| 501 |
-
# If Gradio gives a list of parts: [{"type":"text","text":"..."}]
|
| 502 |
-
if isinstance(content, list):
|
| 503 |
-
texts: List[str] = []
|
| 504 |
-
for part in content:
|
| 505 |
-
if isinstance(part, str):
|
| 506 |
-
texts.append(part)
|
| 507 |
-
elif isinstance(part, dict):
|
| 508 |
-
# most common structure
|
| 509 |
-
if "text" in part:
|
| 510 |
-
texts.append(str(part.get("text") or ""))
|
| 511 |
-
elif "content" in part:
|
| 512 |
-
texts.append(str(part.get("content") or ""))
|
| 513 |
-
joined = "".join(texts).strip()
|
| 514 |
-
return joined if joined else ""
|
| 515 |
-
|
| 516 |
-
# If it is a simple dict that still represents text
|
| 517 |
-
if isinstance(content, dict):
|
| 518 |
-
if "text" in content and len(content.keys()) <= 2:
|
| 519 |
-
return str(content.get("text") or "")
|
| 520 |
-
return content # keep other dict content types as-is
|
| 521 |
-
|
| 522 |
-
return str(content)
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
def _get_role_content(item: Any) -> tuple[Optional[str], Any]:
|
| 526 |
-
# dict style
|
| 527 |
-
if isinstance(item, dict):
|
| 528 |
-
return item.get("role"), item.get("content")
|
| 529 |
-
# ChatMessage-like object style
|
| 530 |
-
role = getattr(item, "role", None)
|
| 531 |
-
content = getattr(item, "content", None)
|
| 532 |
-
return role, content
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
def _ensure_messages_history(history: Any) -> List[Dict[str, Any]]:
|
| 536 |
-
"""
|
| 537 |
-
Gradio 6 expects messages format:
|
| 538 |
-
[{"role":"user","content":"..."}, {"role":"assistant","content":"..."}]
|
| 539 |
-
|
| 540 |
-
This helper tolerates:
|
| 541 |
-
- messages list (dicts / ChatMessage-like objects)
|
| 542 |
-
- legacy tuples list (rare, but keep compatibility)
|
| 543 |
-
and normalizes content so it never shows as "[{'text':...}]".
|
| 544 |
-
"""
|
| 545 |
-
out: List[Dict[str, Any]] = []
|
| 546 |
-
if not history:
|
| 547 |
-
return out
|
| 548 |
-
if not isinstance(history, list):
|
| 549 |
-
return out
|
| 550 |
-
|
| 551 |
-
for item in history:
|
| 552 |
-
# legacy tuple/list
|
| 553 |
-
if isinstance(item, (tuple, list)) and len(item) == 2:
|
| 554 |
-
u, a = item
|
| 555 |
-
if u is not None and str(u).strip():
|
| 556 |
-
out.append({"role": "user", "content": _normalize_message_content(u)})
|
| 557 |
-
if a is not None and str(a).strip():
|
| 558 |
-
out.append({"role": "assistant", "content": _normalize_message_content(a)})
|
| 559 |
-
continue
|
| 560 |
-
|
| 561 |
-
role, content = _get_role_content(item)
|
| 562 |
-
if not role:
|
| 563 |
-
continue
|
| 564 |
-
|
| 565 |
-
role_str = str(role).strip().lower()
|
| 566 |
-
if role_str not in ("user", "assistant", "system"):
|
| 567 |
-
# fallback mapping
|
| 568 |
-
role_str = "assistant" if role_str in ("bot", "ai") else "user"
|
| 569 |
-
|
| 570 |
-
out.append({"role": role_str, "content": _normalize_message_content(content)})
|
| 571 |
-
|
| 572 |
-
return out
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
# -------------- Gradio callbacks --------------
|
| 576 |
-
|
| 577 |
-
def respond(message: str, history, lang_code: str):
|
| 578 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 579 |
-
|
| 580 |
|
| 581 |
message = (message or "").strip()
|
| 582 |
if not message:
|
| 583 |
-
return "",
|
| 584 |
|
| 585 |
-
route = _route_message(message)
|
| 586 |
if route != "allow":
|
| 587 |
answer = _render_refusal(route, forced, message)
|
| 588 |
else:
|
| 589 |
answer = _ask(message, forced_lang=forced)
|
| 590 |
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
return "", history_msgs
|
| 594 |
|
| 595 |
|
| 596 |
def greet(lang_code: str):
|
| 597 |
msg = greeting_for(lang_code)
|
| 598 |
-
|
| 599 |
-
return [{"role": "assistant", "content": msg}]
|
| 600 |
|
| 601 |
|
| 602 |
def toggle_lang_menu(is_open: bool, lang_code: str):
|
|
@@ -611,12 +549,7 @@ def toggle_lang_menu(is_open: bool, lang_code: str):
|
|
| 611 |
gr.update(choices=choices, value=current_label),
|
| 612 |
)
|
| 613 |
else:
|
| 614 |
-
return (
|
| 615 |
-
new_open,
|
| 616 |
-
gr.update(visible=False),
|
| 617 |
-
gr.update(),
|
| 618 |
-
gr.update(),
|
| 619 |
-
)
|
| 620 |
|
| 621 |
|
| 622 |
def filter_languages(search: str, lang_code: str):
|
|
@@ -649,7 +582,9 @@ def select_language(label: str):
|
|
| 649 |
)
|
| 650 |
|
| 651 |
|
| 652 |
-
#
|
|
|
|
|
|
|
| 653 |
|
| 654 |
CSS = """
|
| 655 |
#ca-wrapper {
|
|
@@ -728,10 +663,7 @@ CSS = """
|
|
| 728 |
}
|
| 729 |
"""
|
| 730 |
|
| 731 |
-
|
| 732 |
-
# -------------- Gradio UI --------------
|
| 733 |
-
|
| 734 |
-
with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
| 735 |
lang_state = gr.State("auto")
|
| 736 |
menu_open = gr.State(False)
|
| 737 |
|
|
@@ -756,23 +688,12 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 756 |
elem_id="ca-lang-radio",
|
| 757 |
)
|
| 758 |
|
| 759 |
-
# IMPORTANT: Gradio 6.1.0 on your Space does NOT accept type="messages" here.
|
| 760 |
chatbot = gr.Chatbot(height=420)
|
| 761 |
-
|
| 762 |
-
msg_box = gr.Textbox(
|
| 763 |
-
label="Ask a question",
|
| 764 |
-
placeholder="Type your question here…",
|
| 765 |
-
lines=2,
|
| 766 |
-
)
|
| 767 |
send_btn = gr.Button("Send")
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
send_btn.click(
|
| 771 |
-
respond,
|
| 772 |
-
inputs=[msg_box, chatbot, lang_state],
|
| 773 |
-
outputs=[msg_box, chatbot],
|
| 774 |
-
)
|
| 775 |
|
|
|
|
| 776 |
demo.load(greet, inputs=[lang_state], outputs=[chatbot])
|
| 777 |
|
| 778 |
lang_btn.click(
|
|
@@ -781,11 +702,7 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 781 |
outputs=[menu_open, lang_panel, lang_search, lang_radio],
|
| 782 |
)
|
| 783 |
|
| 784 |
-
lang_search.change(
|
| 785 |
-
filter_languages,
|
| 786 |
-
inputs=[lang_search, lang_state],
|
| 787 |
-
outputs=[lang_radio, lang_state],
|
| 788 |
-
)
|
| 789 |
|
| 790 |
lang_radio.change(
|
| 791 |
select_language,
|
|
@@ -819,4 +736,4 @@ with gr.Blocks(fill_height=True, elem_id="ca-wrapper") as demo:
|
|
| 819 |
)
|
| 820 |
|
| 821 |
if __name__ == "__main__":
|
| 822 |
-
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
|
| 9 |
|
| 10 |
print(">>> GRADIO VERSION:", gr.__version__)
|
| 11 |
|
| 12 |
+
# ============================================================
|
| 13 |
+
# Load Cheshire Academy sources (RAG)
|
| 14 |
+
# ============================================================
|
| 15 |
+
|
| 16 |
BASE_DIR = Path(__file__).parent
|
| 17 |
SOURCES_DIR = BASE_DIR / "sources"
|
| 18 |
+
MANIFEST_PATH = SOURCES_DIR / "_manifest.json"
|
| 19 |
+
|
| 20 |
+
_DOCS: List[Dict[str, Any]] = []
|
| 21 |
+
_DOCS_MTIME: float = 0.0
|
| 22 |
|
| 23 |
|
| 24 |
def _strip_html(text: str) -> str:
|
|
|
|
| 28 |
return text.strip()
|
| 29 |
|
| 30 |
|
| 31 |
+
def _load_sources(force: bool = False) -> List[Dict[str, Any]]:
|
| 32 |
"""
|
| 33 |
+
Load all .txt / .md / .html / .htm files under sources/ into memory.
|
| 34 |
+
Uses manifest mtime to auto-reload after git updates.
|
| 35 |
"""
|
| 36 |
+
global _DOCS, _DOCS_MTIME
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
mtime = MANIFEST_PATH.stat().st_mtime if MANIFEST_PATH.exists() else 0.0
|
| 40 |
+
except Exception:
|
| 41 |
+
mtime = 0.0
|
| 42 |
+
|
| 43 |
+
if (not force) and _DOCS and mtime and mtime <= _DOCS_MTIME:
|
| 44 |
+
return _DOCS
|
| 45 |
+
|
| 46 |
+
docs: List[Dict[str, Any]] = []
|
| 47 |
if not SOURCES_DIR.exists():
|
| 48 |
print("WARNING: sources/ folder not found")
|
| 49 |
+
_DOCS = docs
|
| 50 |
return docs
|
| 51 |
|
| 52 |
for path in SOURCES_DIR.rglob("*"):
|
| 53 |
if not path.is_file():
|
| 54 |
continue
|
| 55 |
+
if path.name.startswith("."):
|
| 56 |
+
continue
|
| 57 |
if path.suffix.lower() not in {".txt", ".md", ".html", ".htm"}:
|
| 58 |
continue
|
| 59 |
+
if path.name == "_manifest.json":
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
try:
|
| 63 |
raw = path.read_text(encoding="utf-8", errors="ignore")
|
| 64 |
+
except Exception:
|
|
|
|
| 65 |
continue
|
| 66 |
|
| 67 |
# strip HTML tags if needed
|
|
|
|
| 73 |
if not plain:
|
| 74 |
continue
|
| 75 |
|
| 76 |
+
snippet = plain[:6000] # keep more for sports pages (opponents/scores)
|
| 77 |
+
docs.append({"path": str(path.relative_to(BASE_DIR)), "text": snippet})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
_DOCS = docs
|
| 80 |
+
_DOCS_MTIME = mtime or time.time()
|
| 81 |
print(f"Loaded {len(docs)} source documents.")
|
| 82 |
return docs
|
| 83 |
|
| 84 |
|
| 85 |
+
def _retrieve(message: str, top_k: int = 4) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
|
|
|
| 86 |
"""
|
| 87 |
+
Tiny keyword-based retrieval:
|
| 88 |
- tokenizes the question,
|
| 89 |
- matches keywords in each doc,
|
| 90 |
- returns the top_k docs with highest match counts.
|
| 91 |
+
|
| 92 |
+
IMPORTANT: This is also used as a "CA-related detector":
|
| 93 |
+
if we can retrieve relevant CA docs, we treat the question as CA-related
|
| 94 |
+
even if the user didn't mention "Cheshire Academy" explicitly.
|
| 95 |
"""
|
| 96 |
+
docs = _load_sources(force=False)
|
| 97 |
+
if not docs:
|
| 98 |
return []
|
| 99 |
|
| 100 |
q = (message or "").lower()
|
| 101 |
tokens = [w for w in re.split(r"[^a-z0-9]+", q) if len(w) > 2]
|
| 102 |
|
| 103 |
+
# Add a few helpful expansions
|
| 104 |
extra_keywords = []
|
| 105 |
if "ib" in q:
|
| 106 |
+
extra_keywords += ["international baccalaureate", "ib programme", "ib program"]
|
|
|
|
|
|
|
| 107 |
keywords = tokens + extra_keywords
|
| 108 |
|
| 109 |
+
# Prevent ultra-generic words from triggering false positives
|
| 110 |
+
stop = {"the", "and", "for", "with", "this", "that", "what", "who", "when", "where", "why", "how"}
|
| 111 |
+
keywords = [k for k in keywords if k and k not in stop]
|
| 112 |
+
|
| 113 |
+
scored: List[Tuple[int, Dict[str, Any]]] = []
|
| 114 |
+
for doc in docs:
|
| 115 |
+
text = (doc.get("text") or "").lower()
|
| 116 |
score = 0
|
| 117 |
for kw in keywords:
|
| 118 |
if kw and kw in text:
|
| 119 |
score += 1
|
| 120 |
if score > 0:
|
| 121 |
+
scored.append((score, doc))
|
| 122 |
|
| 123 |
+
if not scored:
|
| 124 |
return []
|
| 125 |
|
| 126 |
+
scored.sort(key=lambda x: x[0], reverse=True)
|
| 127 |
+
out = []
|
| 128 |
+
for s, d in scored[:top_k]:
|
| 129 |
+
out.append({"path": d["path"], "text": d["text"], "score": s})
|
| 130 |
+
return out
|
| 131 |
|
| 132 |
|
| 133 |
# ============================================================
|
| 134 |
+
# Guardrails / Refusal rules
|
| 135 |
# ============================================================
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
SENSITIVE_SCHOOL_CASE_KEYWORDS = [
|
| 138 |
"lawsuit", "litigation", "sued", "court", "settlement", "complaint",
|
| 139 |
+
"allegation", "scandal", "defamation",
|
| 140 |
+
"诉讼", "起诉", "官司", "法院", "和解", "案件", "丑闻", "指控", "诽谤",
|
| 141 |
]
|
| 142 |
|
| 143 |
ADULT_CONTENT_KEYWORDS = [
|
|
|
|
| 153 |
|
| 154 |
def _contains_any(text: str, keywords: List[str]) -> bool:
|
| 155 |
t = (text or "").lower()
|
| 156 |
+
return any((k.lower() in t) for k in keywords if k)
|
| 157 |
|
| 158 |
|
| 159 |
def _guess_lang_code_from_message(message: str) -> str:
|
|
|
|
| 178 |
"sensitive_school": {
|
| 179 |
"en": (
|
| 180 |
"I’m here to help with **Cheshire Academy admissions and campus information**. "
|
| 181 |
+
"This topic isn’t appropriate to discuss here (e.g., legal cases/allegations).\n\n"
|
| 182 |
"Please ask a different question about **programs, admissions, tuition, deadlines, boarding, campus life,** etc."
|
| 183 |
),
|
| 184 |
"zh": (
|
|
|
|
| 213 |
|
| 214 |
|
| 215 |
def _render_refusal(kind: str, lang_code: Optional[str], message: str) -> str:
|
| 216 |
+
base = (lang_code or "").split("-")[0].strip().lower() or _guess_lang_code_from_message(message)
|
|
|
|
|
|
|
| 217 |
if base not in ("en", "zh"):
|
| 218 |
base = "en"
|
| 219 |
return REFUSAL_TEMPLATES.get(kind, {}).get(base) or REFUSAL_TEMPLATES["non_ca"]["en"]
|
| 220 |
|
| 221 |
|
| 222 |
+
def _route_message(message: str, forced_lang: Optional[str]) -> str:
|
| 223 |
+
"""
|
| 224 |
+
Return one of:
|
| 225 |
+
- "allow"
|
| 226 |
+
- "non_ca"
|
| 227 |
+
- "sensitive_school"
|
| 228 |
+
- "adult"
|
| 229 |
+
- "self_harm"
|
| 230 |
+
|
| 231 |
+
Key change: do NOT rely on CA_TOPIC_KEYWORDS being perfect.
|
| 232 |
+
Main signal = retrieval hit from sources/.
|
| 233 |
+
"""
|
| 234 |
m = (message or "").strip()
|
| 235 |
if not m:
|
| 236 |
return "allow"
|
| 237 |
+
|
| 238 |
if _contains_any(m, SELF_HARM_KEYWORDS):
|
| 239 |
return "self_harm"
|
| 240 |
if _contains_any(m, ADULT_CONTENT_KEYWORDS):
|
|
|
|
| 242 |
if _contains_any(m, SENSITIVE_SCHOOL_CASE_KEYWORDS):
|
| 243 |
return "sensitive_school"
|
| 244 |
|
| 245 |
+
hit = _retrieve(m, top_k=1)
|
| 246 |
+
if hit:
|
| 247 |
+
return "allow"
|
| 248 |
+
|
| 249 |
+
if re.search(r"cheshire\s+academy|cheshireacademy\.org|切舍尔|柴郡|柴俊学院", m, re.I):
|
| 250 |
+
return "allow"
|
| 251 |
+
|
| 252 |
+
return "non_ca"
|
| 253 |
|
| 254 |
|
| 255 |
+
# ============================================================
|
| 256 |
+
# OpenAI
|
| 257 |
+
# ============================================================
|
| 258 |
+
|
| 259 |
MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
|
| 260 |
|
| 261 |
FALLBACK_EN = (
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def _get_oai_client() -> Optional[OpenAI]:
|
|
|
|
| 270 |
global _OAI_CLIENT
|
| 271 |
if _OAI_CLIENT is not None:
|
| 272 |
return _OAI_CLIENT
|
|
|
|
| 289 |
def _ask(message: str, forced_lang: Optional[str] = None) -> str:
|
| 290 |
system = (
|
| 291 |
"You are a multilingual Cheshire Academy FAQ assistant.\n"
|
| 292 |
+
"You are given reference text from the official Cheshire Academy web pages (crawled into 'sources/').\n"
|
| 293 |
"Answer ONLY questions about Cheshire Academy.\n"
|
| 294 |
+
"Rely ONLY on those references for facts (programs including IB, tuition, deadlines, policies, campus details, athletics pages/results).\n"
|
| 295 |
+
"If the references do not clearly answer, say you are not certain and suggest contacting the school instead of guessing.\n"
|
| 296 |
+
"Do NOT answer politics or unrelated general knowledge.\n"
|
| 297 |
"Do NOT discuss allegations, lawsuits, or specific legal cases; redirect users back to admissions/campus questions.\n"
|
| 298 |
"Be concise and student-friendly.\n"
|
| 299 |
)
|
|
|
|
| 308 |
for doc in retrieved:
|
| 309 |
chunks.append(f"Source file: {doc['path']}\n{doc['text']}")
|
| 310 |
context = (
|
| 311 |
+
"Here are reference excerpts from official Cheshire Academy pages. "
|
| 312 |
"Use them as the primary source for your answer:\n\n"
|
| 313 |
+ "\n\n---\n\n".join(chunks)
|
| 314 |
)
|
|
|
|
| 334 |
return FALLBACK_EN
|
| 335 |
|
| 336 |
|
| 337 |
+
# ============================================================
|
| 338 |
+
# Languages & greetings
|
| 339 |
+
# ============================================================
|
| 340 |
|
| 341 |
LANG_ITEMS = [
|
| 342 |
("auto", "Auto / 自动 (auto)"),
|
|
|
|
| 501 |
_dynamic_greetings[base] = msg
|
| 502 |
return msg
|
| 503 |
return GREETINGS["en"]
|
| 504 |
+
except Exception:
|
|
|
|
| 505 |
return GREETINGS["en"]
|
| 506 |
|
| 507 |
|
| 508 |
def search_placeholder_for(code: str) -> str:
|
| 509 |
+
return SEARCH_PLACEHOLDERS.get(base_lang(code), SEARCH_PLACEHOLDERS["en"])
|
|
|
|
| 510 |
|
| 511 |
|
| 512 |
# ============================================================
|
| 513 |
+
# Gradio callbacks (Gradio 6.1.0 compatible)
|
| 514 |
+
# Chatbot history format: List[Tuple[user, assistant]]
|
| 515 |
# ============================================================
|
| 516 |
|
| 517 |
+
def respond(message: str, history: List[Tuple[Optional[str], Optional[str]]], lang_code: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 518 |
forced = None if lang_code == "auto" else base_lang(lang_code)
|
| 519 |
+
history = history or []
|
| 520 |
|
| 521 |
message = (message or "").strip()
|
| 522 |
if not message:
|
| 523 |
+
return "", history
|
| 524 |
|
| 525 |
+
route = _route_message(message, forced)
|
| 526 |
if route != "allow":
|
| 527 |
answer = _render_refusal(route, forced, message)
|
| 528 |
else:
|
| 529 |
answer = _ask(message, forced_lang=forced)
|
| 530 |
|
| 531 |
+
history.append((message, answer))
|
| 532 |
+
return "", history
|
|
|
|
| 533 |
|
| 534 |
|
| 535 |
def greet(lang_code: str):
|
| 536 |
msg = greeting_for(lang_code)
|
| 537 |
+
return [(None, msg)]
|
|
|
|
| 538 |
|
| 539 |
|
| 540 |
def toggle_lang_menu(is_open: bool, lang_code: str):
|
|
|
|
| 549 |
gr.update(choices=choices, value=current_label),
|
| 550 |
)
|
| 551 |
else:
|
| 552 |
+
return new_open, gr.update(visible=False), gr.update(), gr.update()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
|
| 554 |
|
| 555 |
def filter_languages(search: str, lang_code: str):
|
|
|
|
| 582 |
)
|
| 583 |
|
| 584 |
|
| 585 |
+
# ============================================================
|
| 586 |
+
# CSS + UI
|
| 587 |
+
# ============================================================
|
| 588 |
|
| 589 |
CSS = """
|
| 590 |
#ca-wrapper {
|
|
|
|
| 663 |
}
|
| 664 |
"""
|
| 665 |
|
| 666 |
+
with gr.Blocks(css=CSS, fill_height=True, elem_id="ca-wrapper") as demo:
|
|
|
|
|
|
|
|
|
|
| 667 |
lang_state = gr.State("auto")
|
| 668 |
menu_open = gr.State(False)
|
| 669 |
|
|
|
|
| 688 |
elem_id="ca-lang-radio",
|
| 689 |
)
|
| 690 |
|
|
|
|
| 691 |
chatbot = gr.Chatbot(height=420)
|
| 692 |
+
msg_box = gr.Textbox(label="Ask a question", placeholder="Type your question here…", lines=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
send_btn = gr.Button("Send")
|
| 694 |
+
gr.ClearButton([chatbot, msg_box])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 695 |
|
| 696 |
+
send_btn.click(respond, inputs=[msg_box, chatbot, lang_state], outputs=[msg_box, chatbot])
|
| 697 |
demo.load(greet, inputs=[lang_state], outputs=[chatbot])
|
| 698 |
|
| 699 |
lang_btn.click(
|
|
|
|
| 702 |
outputs=[menu_open, lang_panel, lang_search, lang_radio],
|
| 703 |
)
|
| 704 |
|
| 705 |
+
lang_search.change(filter_languages, inputs=[lang_search, lang_state], outputs=[lang_radio, lang_state])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
|
| 707 |
lang_radio.change(
|
| 708 |
select_language,
|
|
|
|
| 736 |
)
|
| 737 |
|
| 738 |
if __name__ == "__main__":
|
| 739 |
+
demo.launch()
|