Spaces:
Running
Running
Download app/query_plan.py from fdsafd4555/campus-rag-backend: direct link, hf CLI and curl.
- Browser
- Download file 26.7 kB
-
https://huggingface.co/spaces/fdsafd4555/campus-rag-backend/resolve/main/app/query_plan.py
- Command line
-
hf download hf://spaces/fdsafd4555/campus-rag-backend/app/query_plan.py
-
curl -L -o query_plan.py https://huggingface.co/spaces/fdsafd4555/campus-rag-backend/resolve/main/app/query_plan.py
26.7 kB
| """Ground a search plan in the user's words before running any retrieval.""" | |
| from __future__ import annotations | |
| import re | |
| from datetime import datetime, timezone, timedelta | |
| from functools import lru_cache | |
| import json | |
| from typing import Literal | |
| from pydantic import BaseModel, Field | |
| from . import department_focus as departments | |
| from .freshness import current_term, query_term, says_this_term | |
| from .course_identity import PROFILE_REFERENCE, instructor_name, instructor_names, course_level, is_course_list, is_single_offering_question, resolve_course_question | |
| from .document_focus import tuition_row_key | |
| from .faculty import PERSON_FIELDS, PERSON_REFERENCE, PROFILE_FIELDS, ROSTER | |
| from .query_transform import normalize_search_terms | |
| KST = timezone(timedelta(hours=9)) | |
| TOPICS = re.compile(r"ν΄ν|볡ν|μ κ³Ό|볡μμ 곡|λΆμ 곡|μ‘Έμ |μκ°|곡결|μΆμ|μ±μ |μ₯ν|λ±λ‘κΈ|κ΅ννμ|κ΅νμν|κΈ°μμ¬|μνκ΄|λμκ΄|μ¦λͺ μ|μλ΄μΌν°|보건μ§λ£μ|μμ΄νμ΄|μ·¨μ |κ°μκ³ν|κ΅μ¬|(?<!μΈ)곡μ§(?!λ₯)|μΊ‘μ€ν€|νμμ¦|μ ν[ \t]*λ²μ€") | |
| REFERENT = re.compile(r"κ±°κΈ°|κ·Έκ³³|κ·Έκ±°|κ·Έκ²|ν΄λΉ\s*(?:μ μ²|νλ‘κ·Έλ¨)|κ·Έ\s*(?:μ μ²|νλ‘κ·Έλ¨|μ₯νκΈ|λΆμ)") | |
| _GENERIC_OFFICE = re.compile(r"(?<![κ°-ν£A-Za-z])(?:νλΆ|νκ³Ό|μ 곡)\s*μ¬λ¬΄μ€") | |
| _CONTACT_RE = re.compile(r"μ ν\s*λ²νΈ|μ°λ½μ²") | |
| SCHOOL_ALIASES = {"λΆκ²½λ": "λΆκ²½λνκ΅", "μ μ£Όλ": "μ μ£Όλνκ΅", "λΆμ°λ": "λΆμ°λνκ΅", "μ°½μλ": "μ°½μλνκ΅", "μΆ©λΆλ": "μΆ©λΆλνκ΅"} | |
| AUDIENCES = {"μΈκ΅μΈ": ("μΈκ΅μΈ", "μ νμ", "international student"), "λ΄κ΅μΈ": ("λ΄κ΅μΈ",), | |
| "λνμ": ("λνμ", "μμ¬", "λ°μ¬"), "νλΆ": ("νλΆμ", "νλΆκ³Όμ "), | |
| "μ μ μ": ("μ μ μ", "μ μ ν"), "νΈμ μ": ("νΈμ μ", "νΈμ ν"), | |
| "μ¬νμ": ("μ¬νμ",), "ν΄νμ": ("ν΄νμ",)} | |
| PROGRAM_CONTEXTS = {"νμ₯μ€μ΅": r"νμ₯μ€μ΅|μ€μ΅μ|μνΈλ£¨\s*(?:ν\s*)?μ½μ ", "κ΅λ₯νλ‘κ·Έλ¨": r"νμ \s*κ΅λ₯|κ΅λ₯\s*μν|κ΅λ₯\s*νλ‘κ·Έλ¨|λνμ\s*κ΅λ₯", | |
| "κ΅ννμ": r"κ΅ννμ|κ΅ν\s*μν", "νκ΅μ΄μ°μ": r"νκ΅μ΄\s*μ°μ", | |
| "λνμ°Έκ°": r"κ²½μ§λν|κ²½μ°λν|곡λͺ¨μ ", "μ±κ³Όλ°νν": r"μ±κ³Ό\s*λ°νν", | |
| "ν΄μΈμ°μ": r"ν΄μΈ\s*μ°μ|μ΄ν\s*μ°μ", | |
| "κ°μΌλ³": r"μ½λ‘λ|λ°±μ |κ°μΌλ³"} | |
| GRADE_RE = re.compile(r"(?<!\d)([1-6])\s*νλ (?!λ)") | |
| ADMISSION_RE = re.compile(r"(?<!\d)(20\d{2}|\d{2})\s*(?:νλ²|(?:νλ λ|λ )\s*(?:μ μ ν|μ ν))") | |
| def _admission_years(text: str) -> list[int]: | |
| years = [] | |
| for match in ADMISSION_RE.finditer(text): | |
| year = int(match[1]) | |
| if year < 100: | |
| year += 2000 if year <= datetime.now(KST).year % 100 else 1900 | |
| years.append(year) | |
| return years | |
| class Target(BaseModel): | |
| school: str = "λΆκ²½λνκ΅" | |
| subject: str | None = None | |
| department: str | None = None | |
| department_id: str | None = None | |
| audiences: list[str] = Field(default_factory=list) | |
| contexts: list[str] = Field(default_factory=list) | |
| grade: int | None = None | |
| admission_year: int | None = None | |
| instructor: str | None = None | |
| level: str | None = None | |
| class Conditions(BaseModel): | |
| kind: Literal["search", "latest", "open", "courses"] = "search" | |
| limit: int | None = Field(default=5, ge=1, le=20) | |
| order_by: Literal["relevance", "published_at_desc", "course_name"] = "relevance" | |
| as_of: datetime = Field(default_factory=lambda: datetime.now(KST)) | |
| year: int | None = None | |
| term: str | None = None | |
| topic: str | None = None | |
| class SearchTask(BaseModel): | |
| text: str | |
| purpose: Literal["general", "eligibility", "procedure", "deadline", "contact", "assessment", "textbook", "weekly", "prerequisites", "instructor", "course_list"] = "general" | |
| target: Target = Field(default_factory=Target) | |
| conditions: Conditions = Field(default_factory=Conditions) | |
| required_conditions: list[str] = Field(default_factory=list) | |
| class QuestionPlan(BaseModel): | |
| route: Literal["search", "clarification", "small_talk", "refused"] = "search" | |
| tasks: list[SearchTask] = Field(default_factory=list, max_length=3) | |
| missing_fields: list[str] = Field(default_factory=list) | |
| clarification: str | None = None | |
| response_format: str | None = None | |
| resolved_question: str = "" | |
| comparison_targets: list[str] = Field(default_factory=list) | |
| def queries(self) -> list[str]: | |
| return [task.text for task in self.tasks] | |
| def department_catalog() -> tuple[dict, ...]: | |
| path = departments._registry_path() | |
| if path is None: | |
| return () | |
| return tuple(json.loads(path.read_text(encoding="utf-8")).get("departments", [])) | |
| def department_identity(text: str) -> tuple[str | None, str | None]: | |
| normalized = departments.normalize(text) | |
| aliases = [name for alias, names in departments.ALIASES.items() if alias in normalized for name in names] | |
| names = aliases + [name for name in departments.DEPARTMENT_NAMES if departments.normalize(name) in normalized] | |
| if not names: | |
| # Students say "μ»΄ν¨ν°κ³΅νκ³Ό"/"μ μ곡νκ³Ό"; the registry has μ»΄ν¨ν°κ³΅νμ 곡/μ μ곡νμ 곡. | |
| # 2026-11-11: unresolved, the department search ranked other departments' | |
| # κ΅μμ§ pages first and "μ»΄ν¨ν°κ³΅νκ³Ό κ΅μλ λͺ©λ‘" found nothing. | |
| names = [name for name in departments.DEPARTMENT_NAMES | |
| if departments._stem(name) != name and departments.normalize(departments._stem(name)) + "κ³Ό" in normalized] | |
| if names: | |
| names = [max(names, key=lambda name: len(departments._stem(name)))] | |
| if not names: | |
| return None, None | |
| name = max(names, key=len) if not aliases else aliases[-1] | |
| for entry in department_catalog(): | |
| labels = [entry.get("name"), entry.get("department"), *(entry.get("majors") or [])] | |
| if any(departments.normalize(name) in departments.normalize(str(label or "")) for label in labels): | |
| return name, entry.get("dataset") | |
| return name, None | |
| def _subject_names(text: str) -> set[str]: | |
| return set(TOPICS.findall(normalize_search_terms(text))) | |
| def _explicit_departments(text: str) -> list[str]: | |
| normalized = departments.normalize(text) | |
| names = [name for name in departments.DEPARTMENT_NAMES if departments.normalize(name) in normalized] | |
| names.extend(alias for alias in departments.ALIASES if alias in normalized) | |
| names = [name for name in names if not any( | |
| name != other and departments.normalize(name) in departments.normalize(other) for other in names)] | |
| return sorted(set(names), key=lambda name: normalized.index(departments.normalize(name))) | |
| def _mentions_entity(query: str, entity: str) -> bool: | |
| # Only explicit aliases may expand. A quoted title mentioning a department | |
| # must still match the whole title; an AI course is not the AI major. | |
| # The alias itself counts too: "컴곡 μ΅μ 곡μ§" mentions 컴곡, but comparing | |
| # only its expansions dropped every sub-query and merged a compound question | |
| # back into one ("컴곡 κ³΅μ§ 3κ°μ λμκ΄ μ νλ²νΈ", 2026-11-12). | |
| variants = (entity, *departments.ALIASES.get(entity, ())) | |
| variants = tuple(departments.normalize(value) for value in variants) | |
| return departments.mentions(query, variants) | |
| def _names_department(text: str, department: str) -> bool: | |
| """Whether the user's own words name `department`, also as 컴곡 or μ»΄ν¨ν°κ³΅νκ³Ό.""" | |
| normalized = departments.normalize(text) | |
| if departments.normalize(department) in normalized: | |
| return True | |
| if any(alias in normalized and department in names for alias, names in departments.ALIASES.items()): | |
| return True | |
| stem = departments._stem(department) | |
| return stem != department and departments.normalize(stem) + "κ³Ό" in normalized | |
| def _ground_queries(original: str, queries: list[str], plan: QuestionPlan) -> list[str]: | |
| """Keep explicit names and both sides of a department comparison in search. | |
| This is a conservative guard for registry names, university names and quoted | |
| titles, not a general named-entity recognizer. Unsafe rewrites use the user text. | |
| """ | |
| names = _explicit_departments(original) | |
| comparison = len(names) > 1 and re.search(r"λΉκ΅|μ°¨μ΄|κ°μ|κ°λμ|λμΌ|λ€λ₯Έ|λ€λ₯΄", original) | |
| if comparison: | |
| plan.comparison_targets = names | |
| covered = all(any(_mentions_entity(query, name) and not any( | |
| _mentions_entity(query, other) for other in names if other != name) for query in queries) for name in names) | |
| # Several explicit years can refer to different sides. Do not assign them | |
| # to both sides by rewriting the full question mechanically. | |
| years = set(re.findall(r"(?<!\d)(?:20\d{2}|\d{2})\s*(?:νλ²|νλ λ|λ )", original)) | |
| if not covered and len(names) <= 3 and len(years) <= 1: | |
| queries = [] | |
| for name in names: | |
| query = original | |
| for other in names: | |
| if other != name: | |
| query = re.sub(re.escape(other) + r"(?:κ³Ό|μ|μ|μ|λ)?", " ", query) | |
| query = re.sub(re.escape(name) + r"(?:κ³Ό|μ|μ|μ|λ)?", name + " ", query) | |
| query = re.sub(r"(?:μ΄|κ°)?\s*(?:κ°μκ°μ|κ°λμ|λμΌνκ°μ|λ€λ₯Έκ°μ|λ€λ₯΄λμ)[?!.]*$", "", query) | |
| queries.append(re.sub(r"\s+", " ", query).strip()) | |
| institutions = re.findall(r"(?<![κ°-ν£A-Za-z])([κ°-ν£A-Za-zΒ·]{2,}(?:λνκ΅|λν|λ))(?=μ|μ|μ|κ³Ό|\s|[,?!]|$)", original) | |
| quoted = re.findall(r'["ββ]([^"ββ\n]{2,100})["ββ]', original) | |
| anchors = [*names, *institutions, *quoted] | |
| if any(not any(_mentions_entity(query, anchor) for query in queries) for anchor in anchors): | |
| return [original] | |
| people = instructor_names(original) | |
| if people and PROFILE_FIELDS.search(original): | |
| rewritten_people = {name for query in queries for name in instructor_names(query)} | |
| if not people <= rewritten_people: | |
| return [original] | |
| topics = _subject_names(original) | |
| if len(topics) == 1 and not names and not institutions and not quoted: | |
| # E.g. "μ νλ²μ€ λ Έμ " / "μ€λ μ€μκ° λμ°© μκ°": each sub-query | |
| # needs its subject, not just the generation prompt that sees both. | |
| topic = next(iter(topics)) | |
| queries = [query if topic in normalize_search_terms(query) else f"{topic} {query}" for query in queries] | |
| return queries | |
| def resolve_context(question: str, history: list[dict]) -> tuple[str, bool]: | |
| """Use only a user's explicit, unique subject; never an assistant's guess.""" | |
| course_question = resolve_course_question(question, history) | |
| if course_question != question: | |
| return course_question, False | |
| previous = next((t.get("content", "") for t in reversed(history) if t.get("role") == "user"), "") | |
| if PERSON_REFERENCE.search(question) and (PROFILE_FIELDS.search(question) or PERSON_FIELDS.search(question)): | |
| if not instructor_names(question): | |
| if len(instructor_names(previous)) == 1: | |
| return question + " / " + previous, False | |
| return question, True | |
| if ROSTER.search(question) and not PERSON_REFERENCE.search(question) and _explicit_departments(question): | |
| return question, False | |
| if _GENERIC_OFFICE.search(question) and not _explicit_departments(question): | |
| if len(_explicit_departments(previous)) == 1: | |
| return question + " / " + previous, False | |
| slot_answer = re.search(r"μ¬νμ|μ μ μ|νΈμ μ|λνμ|μΈκ΅μΈ|\d+\s*(?:νκΈ°|λΆλ°|νλ )|컴곡|[κ°-ν£]+(?:νκ³Ό|μ 곡)", question) | |
| if previous and slot_answer and not TOPICS.search(question) and len(_subject_names(previous)) == 1: | |
| return question + " / " + previous, False | |
| referential = bool(REFERENT.search(question)) | |
| contact = bool(_CONTACT_RE.search(question)) | |
| generic = (contact or bool(re.search(r"μ μ²|κΈ°ν|λ§κ°|μΈμ κΉμ§", question))) and not TOPICS.search(question) | |
| if not (referential or generic): | |
| return question, False | |
| # Named offices, departments and courses are already subjects. | |
| name = re.search(r"[κ°-ν£A-Za-zΒ·]+(?:μΌν°|μ¬λ¬΄μ€|νκ³Ό|μ 곡|νλΆ|νλ‘κ·Έλ¨|μ₯νκΈ|λ³ΈλΆ|[κ³Όμ²κ΄μν])", question) | |
| if name and not referential: | |
| return question, False | |
| residual = re.sub(r"\d+\s*νλ (?:μΈλ°|μΈ|μ΄μΌ|μ λλ€)?|μ λ|μ κ°|μ |μ μ²|κΈ°ν|κΈ°κ°|λ§κ°|μΈμ (?:κΉμ§)?(?:μμ|μμ|μΈκ°μ|μ λκΉ|μΌ|μ£ )?|κΉμ§μΌ|κΉμ§|μ ν\s*λ²νΈ|μ°λ½μ²|μλ €\s*μ€|μλ €μ£ΌμΈμ|λ|무μ|μ΄λ€|ν \s*μ|μμ΄μ|κ°λ₯νμ§|κ°λ₯ν΄|ν΄μ|[?!.\s]", "", question) | |
| if len(residual) >= 2 and not referential: | |
| # An unfamiliar programme name should be resolved by the planner, | |
| # rather than rejected merely because it is absent from TOPICS. | |
| return question, False | |
| subjects = _subject_names(previous) | |
| # 'λμκ΄ μ νλ²νΈμ μ¦λͺ μ λ°κΈ' contains two possible referents. | |
| place = bool(re.search(r"λμκ΄|보건μ§λ£μ|μλ΄μΌν°|[κ°-ν£]+(?:μ¬λ¬΄μ€|μΌν°|νκ³Ό|λ³ΈλΆ|κ³Ό|μ²|κ΄|ν)", previous)) | |
| broad_scholarship = subjects == {"μ₯ν"} and not re.search(r"[κ°-ν£]{2,}μ₯νκΈ", previous) | |
| if previous and len(subjects) == 1 and not broad_scholarship and (not contact or place): | |
| return question + " / " + previous, False | |
| return question, True | |
| def target_for(text: str) -> Target: | |
| school = next((full for alias, full in SCHOOL_ALIASES.items() if alias in text), None) | |
| explicit = re.search(r"([κ°-ν£]+λνκ΅)", text) | |
| if explicit: | |
| school = explicit[1].removeprefix("κ΅λ¦½") | |
| name, identity = department_identity(text) | |
| subject = re.search(r"[κ°-ν£A-Za-z0-9Β·]+(?:μ₯νκΈ|νλ‘κ·Έλ¨|μΌν°|λμκ΄)", text) | |
| if not subject and not TOPICS.search(text): | |
| subject = re.search(r"[κ°-ν£A-Za-zΒ·]{2,}(?:λ³ΈλΆ|μ¬λ¬΄μ€|κ³Ό|μ²|κ΄|ν)", text) | |
| grade = GRADE_RE.search(text) | |
| admissions = _admission_years(text) | |
| admission_year = admissions[0] if admissions else None | |
| return Target(school=school or "λΆκ²½λνκ΅", subject=subject[0] if subject else next(iter(sorted(_subject_names(text), key=len, reverse=True)), None), | |
| department=name, department_id=identity, grade=int(grade[1]) if grade else None, admission_year=admission_year, | |
| audiences=[key for key, words in AUDIENCES.items() if any(w in text.lower() for w in words)], | |
| contexts=[key for key, pattern in PROGRAM_CONTEXTS.items() if re.search(pattern, text)], | |
| instructor=instructor_name(text), level=course_level(text)) | |
| def purpose_for(text: str) -> str: | |
| text = normalize_search_terms(text) | |
| if is_course_list(text): | |
| return "course_list" | |
| for purpose, pattern in (("contact", r"μ νλ²νΈ|μ°λ½μ²"), ("prerequisites", r"μ μ\s*κ³Όλͺ©"), | |
| ("assessment", r"νκ°\s*(?:λΉμ¨|λ°©λ²)|λ°°μ "), ("textbook", r"κ΅μ¬"), | |
| ("weekly", r"μ£Όμ°¨|μ£Όλ³"), ("instructor", r"λ΄λΉ\s*κ΅μ"), | |
| ("eligibility", r"μ격|μ§μ\s*쑰건"), ("deadline", r"μΈμ |λ§κ°|κΈ°ν"), | |
| ("procedure", r"λ°©λ²|μ μ°¨|μ΄λ»κ²")): | |
| if re.search(pattern, text): | |
| return purpose | |
| return "general" | |
| def conditions_for(text: str) -> Conditions: | |
| kind = "search" | |
| if is_course_list(text): | |
| kind = "courses" | |
| elif re.search(r"곡μ§|κ²μκΈ|κ²μλ¬Ό", text) and re.search(r"μ΅κ·Ό|μ΅μ |λ§μ§λ§|μλ‘", text): | |
| kind = "latest" | |
| elif re.search(r"(?:μ€λ|μ§κΈ|νμ¬).{0,30}(?:μ μ²\s*κ°λ₯|μ μ²ν \s*μ|λͺ¨μ§\s*μ€|μ μ\s*μ€)|(?:μ μ²\s*κ°λ₯|λͺ¨μ§\s*μ€|μ μ\s*μ€).{0,15}(?:λͺ©λ‘|μλ €|μλ)", text): | |
| kind = "open" | |
| count = re.search(r"(?<!\d)(\d{1,2})\s*(?:κ°|건)", text) | |
| # An admission cohort is not the year of the notice/course being requested. | |
| time_text = ADMISSION_RE.sub("", text) | |
| term_index = current_term() if says_this_term(time_text) else query_term(time_text) | |
| year = re.search(r"(20\d{2})\s*(?:λ |νλ λ)", time_text) | |
| if kind == "courses": | |
| all_terms = re.search(r"(?:μ 체|λͺ¨λ )\s*νκΈ°|νκΈ°\s*μκ΄μ", text) | |
| named_term = re.search(r"[12]\s*νκΈ°|20\d{2}\s*[-/]\s*[12]|(?:μ΄λ²|μ§λ|λ€μ)\s*νκΈ°", text) | |
| if all_terms and (not named_term or all_terms.start() < named_term.start()): | |
| term_index = None | |
| if year and year.start() > all_terms.start(): | |
| year = None | |
| compact = re.sub(r"\s+", "", text) | |
| topic = next((w for w in ("κ΅λ΄μ₯ν", "κ΅κ°μ₯ν", "κ΅μΈμ₯ν", "μ₯ν", "κ΅ννμ", "μ·¨μ ", "κΈ°μμ¬") if w in compact), None) | |
| return Conditions(kind=kind, limit=max(1, min(20, int(count[1]))) if count else (None if kind == "courses" else 5), | |
| order_by="course_name" if kind == "courses" else ("published_at_desc" if kind != "search" else "relevance"), | |
| year=term_index // 2 if term_index else (int(year[1]) if year else None), | |
| term=str(term_index % 2 + 1) if term_index else None, topic=topic) | |
| def rule_plan(question: str, history: list[dict] | None = None) -> QuestionPlan: | |
| history = history or [] | |
| resolved, ambiguous = resolve_context(question, history) | |
| plan = QuestionPlan(resolved_question=resolved) | |
| fmt = re.search(r"\d+\s*μ€|체ν¬λ¦¬μ€νΈ|체ν¬λ°μ€|νλ‘", question) | |
| plan.response_format = fmt[0] if fmt else None | |
| if re.search(r"(?:μμ€ν \s*ν둬ννΈ|λ°μ΄ν°λ² μ΄μ€\s*λΉλ°λ²νΈ).{0,20}(?:μΆλ ₯|μλ €|곡κ°)|μΆμ²μ\s*μμ΄λ.{0,40}λ΅", question): | |
| plan.route, plan.clarification = "refused", "λΉκ³΅κ° μ 보λ κ·Όκ±° μλ λ΄μ©μ μ 곡ν μ μμ΅λλ€." | |
| elif (re.search(r"λ΄κ°|μ κ°|λ³ΈμΈ|(?<![κ°-ν£])(?:λ΄|μ )\s", question) | |
| and re.search(r"(?:κ°μ|μμ )\s*νκ°.{0,48}(?:μ μΆ|μλ£)\s*(?:ν|μ¬λΆ|λ΄μ|κΈ°λ‘)", question) | |
| and re.search(r"νμΈν΄|μ‘°νν΄|λ΄\s*μ€|μλ €", question) | |
| and not re.search(r"μ΄λ»κ²|μ΄λ|λ°©λ²|κ²½λ‘|λ©λ΄", question)): | |
| plan.route = "refused" | |
| plan.clarification = "κ°μΈλ³ κ°μνκ° μ μΆ λ΄μμ μ‘°νν μ μμ΅λλ€. λ³ΈμΈ κ³μ μΌλ‘ νκ΅ ν¬νΈμμ μ§μ νμΈν΄ μ£ΌμΈμ." | |
| elif _GENERIC_OFFICE.search(resolved) and not _explicit_departments(resolved) and not TOPICS.search(resolved): | |
| plan.route, plan.missing_fields = "clarification", ["department"] | |
| plan.clarification = "μ΄λ νλΆΒ·νκ³ΌΒ·μ 곡 μ¬λ¬΄μ€μ μ°λ½μ²κ° νμνμ κ°μ?" | |
| elif ambiguous: | |
| plan.route, plan.missing_fields = "clarification", ["subject"] | |
| if PERSON_REFERENCE.search(question): | |
| plan.clarification = "μ΄λ κ΅μλμ λ§μνμλμ§ μ±ν¨μ΄λ μμμ μλ €μ£ΌμΈμ." | |
| else: | |
| plan.clarification = "μ΄λ λΆμλ μμ€μ μ νλ²νΈκ° νμνμ κ°μ?" if _CONTACT_RE.search(question) else "μ΄λ€ μ μ²μ΄λ νλ‘κ·Έλ¨μ λν΄ λ¬ΌμΌμλ 건κ°μ?" | |
| elif re.search(r"κΈ°μμ¬|μνκ΄", resolved) and re.search(r"μ격|μ μ²\s*λμ|μ μ€\s*λμ", resolved): | |
| audiences = target_for(resolved).audiences | |
| if not set(audiences) & {"μ μ μ", "νΈμ μ", "μ¬νμ", "λνμ", "νλΆ"}: | |
| plan.route, plan.missing_fields = "clarification", ["audience"] | |
| plan.clarification = "μ μ μΒ·μ¬νμΒ·λνμμ μ€ μ΄λ νμ μ νμ κΈ°μμ¬ μ μ² μκ²©μ΄ κΆκΈνμ κ°μ?" | |
| return plan | |
| def finish_plan(plan: QuestionPlan, question: str, queries: list[str], payload: dict | None = None) -> QuestionPlan: | |
| if plan.route != "search": | |
| return plan | |
| if (is_course_list(plan.resolved_question) or is_single_offering_question(plan.resolved_question) | |
| or tuition_row_key(plan.resolved_question) | |
| or (PROFILE_REFERENCE.search(plan.resolved_question) and len(instructor_names(plan.resolved_question)) == 1)): | |
| # Exact catalogue lookups do not depend on a model's wording or omissions. | |
| queries = [plan.resolved_question] | |
| payload = None | |
| if payload and payload.get("route") == "clarification" and isinstance(payload.get("missing_fields"), list): | |
| missing = [f for f in payload["missing_fields"] if f in {"subject", "department", "audience", "year", "term", "section"}] | |
| known_target = target_for(plan.resolved_question) | |
| known_conditions = conditions_for(plan.resolved_question) | |
| known = {"subject": known_target.subject, "department": known_target.department, "audience": known_target.audiences, | |
| "year": known_conditions.year, "term": known_conditions.term, | |
| "section": re.search(r"\d+\s*λΆλ°", plan.resolved_question)} | |
| missing = [field for field in missing if not known[field]] | |
| if missing and isinstance(payload.get("clarification"), str) and payload["clarification"].strip(): | |
| plan.route, plan.missing_fields, plan.clarification = "clarification", missing, payload["clarification"].strip()[:300] | |
| return plan | |
| if not queries: | |
| queries = [plan.resolved_question] | |
| original = plan.resolved_question or question | |
| queries = _ground_queries(original, queries[:3], plan) | |
| if not queries: | |
| # A model cannot route a substantive university question to small talk. | |
| if TOPICS.search(question) or ROSTER.search(original) or instructor_names(original): | |
| queries = [plan.resolved_question] | |
| else: | |
| plan.route = "small_talk" | |
| return plan | |
| global_target = target_for(original) | |
| if len(_explicit_departments(original)) > 1: | |
| global_target.department, global_target.department_id = None, None | |
| grades = set(GRADE_RE.findall(original)) | |
| cohorts = set(_admission_years(original)) | |
| if len(grades) > 1: | |
| global_target.grade = None | |
| if len(cohorts) > 1: | |
| global_target.admission_year = None | |
| global_conditions = conditions_for(original) | |
| if len(queries) == 1: | |
| rewritten = conditions_for(queries[0]) | |
| # A standalone rewrite cannot drop, substitute or invent a semester, | |
| # notice year or admission cohort. Comparison tasks keep local dates. | |
| requested_period = (global_conditions.year, global_conditions.term) | |
| rewritten_period = (rewritten.year, rewritten.term) | |
| if rewritten_period != requested_period or set(_admission_years(queries[0])) != cohorts: | |
| queries = [original] | |
| # Never adopt a department/student type invented by the planner. | |
| for query in queries[:3]: | |
| target = target_for(query) | |
| if len(_explicit_departments(query)) > 1: | |
| target.department, target.department_id = None, None | |
| if target.department and target.department not in (global_target.department, None): | |
| if not _names_department(original, target.department): | |
| target.department, target.department_id = global_target.department, global_target.department_id | |
| independent = re.search(r"λμκ΄|μ¦λͺ μ|보건μ§λ£μ|μλ΄μΌν°|νμμ¦", query) | |
| if not target.department and not independent: | |
| target.department, target.department_id = global_target.department, global_target.department_id | |
| if target.subject and departments.normalize(target.subject) not in departments.normalize(original): | |
| target.subject = global_target.subject | |
| if not any(name in original for name in (target.school, *(alias for alias, full in SCHOOL_ALIASES.items() if full == target.school))): | |
| target.school = global_target.school | |
| target.audiences = [a for a in target.audiences if a in global_target.audiences] or global_target.audiences | |
| target.contexts = [c for c in target.contexts if c in global_target.contexts] or ([] if independent else global_target.contexts) | |
| # Do not copy the first side's cohort/grade onto every comparison task. | |
| local_grades = set(GRADE_RE.findall(query)) | |
| local_cohorts = set(_admission_years(query)) | |
| if not (len(grades) > 1 and len(local_grades) == 1 and local_grades <= grades): | |
| target.grade = global_target.grade | |
| if not (len(cohorts) > 1 and len(local_cohorts) == 1 and local_cohorts <= cohorts): | |
| target.admission_year = global_target.admission_year | |
| if target.instructor not in instructor_names(original): | |
| target.instructor = global_target.instructor | |
| target.level = global_target.level or target.level | |
| conditions = conditions_for(query) | |
| if (global_conditions.kind == "latest" and re.search(r"곡μ§|κ²μκΈ|κ²μλ¬Ό", query)) or ( | |
| global_conditions.kind == "open" and (global_conditions.topic is None or global_conditions.topic in re.sub(r"\s+", "", query) or ("μ₯ν" in (global_conditions.topic or "") and "μ₯ν" in query)) | |
| ): | |
| conditions = global_conditions.model_copy(deep=True) | |
| local_count = re.search(r"(?<!\d)(\d{1,2})\s*(?:κ°|건)", query) | |
| if local_count: | |
| conditions.limit = max(1, min(20, int(local_count[1]))) | |
| query = re.sub(r"\d+\s*μ€(?:λ‘)?|체ν¬λ¦¬μ€νΈ|체ν¬λ°μ€|νλ‘", "", query).strip() | |
| required = ["school"] | |
| if target.department: required.append("department") | |
| if target.audiences: required.append("audience") | |
| if target.contexts: required.append("program_context") | |
| if target.grade: required.append("grade") | |
| if target.admission_year: required.append("admission_year") | |
| if target.instructor: required.append("instructor") | |
| if conditions.kind == "courses": required.extend(("year", "term", "level")) | |
| if conditions.kind == "open": required.extend(("application_start", "application_end")) | |
| if conditions.kind == "latest": required.extend(("published_at", "order", "limit")) | |
| plan.tasks.append(SearchTask(text=query, purpose=purpose_for(query), target=target, conditions=conditions, required_conditions=required)) | |
| return plan | |