diff --git a/test/planning/test_question_catalog_routes.py b/test/planning/test_question_catalog_routes.py new file mode 100644 index 0000000..5cc6119 --- /dev/null +++ b/test/planning/test_question_catalog_routes.py @@ -0,0 +1,22 @@ +"""Catalog routes that keep a question's topic and exclusion (19. 11. 2026 suite).""" +from tools.answers.planning.question_catalog import CatalogDecision, _topic_in_question, route_for + + +def decision(**fields): + base = dict(type="students_of_advisor", people=["Daniela Hládka"], topic=None, topic_canonical=None, exclude=None, + action="any", facets=[], presentation="default", meeting="none", work_types=[]) + return CatalogDecision(**{**base, **fields}) + + +def test_students_of_a_supervisor_who_did_a_topic_search_the_topic_with_the_exclusion(): + question = "Ktorí študenti Daniela Hládka od roku 2024 robili s LLM, bez RASA?" + resolution = {"matches": [{"name": "Daniel Hladek", "input": "Daniela Hládka"}], "resolved_query": question} + route = route_for(decision(topic="LLM", exclude="RASA"), resolution) + assert route.type == "who_did_topic" and route.topic == "LLM" and route.exclusion == "RASA" + + +def test_a_plain_roster_keeps_its_type_even_with_a_guessed_topic(): + question = "Kto sú študenti Daniela Hládka?" + resolution = {"matches": [{"name": "Daniel Hladek", "input": "Daniela Hládka"}], "resolved_query": question} + assert route_for(decision(topic="študenti"), resolution).type == "students_of_advisor" + assert not _topic_in_question("RAG", question) diff --git a/tools/answers/planning/question_catalog.py b/tools/answers/planning/question_catalog.py index 4992125..cfde019 100644 --- a/tools/answers/planning/question_catalog.py +++ b/tools/answers/planning/question_catalog.py @@ -215,6 +215,19 @@ class Route: status: bool = False +GENERIC_TOPICS = {"student", "studenti", "studentov", "prace", "praca", "prac", "tema", "temy", "projekt", "projekty"} +ACTIVITY = re.compile(r"\b(?:robil\w*|pracoval\w*|venoval\w*|zaoberal\w*|pouzi\w*|vyuzi\w*|riesil\w*|skusal\w*|" + r"vyskusal\w*|trenoval\w*|dotrenoval\w*|implementoval\w*|vytvoril\w*|vyvijal\w*|testoval\w*)\b") + + +def _topic_in_question(topic: str, question: str) -> bool: + """The classifier's topic is a topic of this question: its words are in the question, it is no generic word + ("študenti", "práce") and the question asks what someone did with it.""" + from tools.answers.verification.context_policy import normalized + q, words = normalized(question), normalized(topic).split() + return bool(words) and not set(words) <= GENERIC_TOPICS and all(w[:4] in q for w in words) and bool(ACTIVITY.search(q)) + + def route_for(decision: CatalogDecision | None, resolution: dict) -> Route | None: """A route the planner can execute, or None to keep the rule-based plan.""" if decision is None or decision.type in {"unclear", "out_of_scope"}: @@ -224,6 +237,13 @@ def route_for(decision: CatalogDecision | None, resolution: dict) -> Route | Non return None if decision.type == "compare_students" and len(matches) < 2: return None + if (decision.type in {"students_of_advisor", "activity_in_period"} and decision.topic + and not any(m.get("source_document") for m in matches) + and _topic_in_question(decision.topic, resolution.get("resolved_query") or "")): + # "Ktorí študenti Hládka (od roku 2024) robili s LLM, bez RASA?": who did a topic, among one supervisor's + # students or in a period. As who_did_topic the topic, the exclusion and the person/period filters stay; + # the other type would drop the topic and refuse the exclusion. + decision = decision.model_copy(update={"type": "who_did_topic"}) if decision.type == "who_did_topic" and any(m.get("source_document") for m in matches): return None # a named student: "what did X do with Y" is not a roster search if decision.type == "who_did_topic" and decision.exclude and ( diff --git a/tools/answers/planning/question_plan.py b/tools/answers/planning/question_plan.py index 6d693c4..73cfc35 100644 --- a/tools/answers/planning/question_plan.py +++ b/tools/answers/planning/question_plan.py @@ -184,6 +184,10 @@ def direct_spec(question, resolution, *, meeting=None, route=None, relative_year global_discovery=discovery_question(q) if route is None and mode not in {'similar','supervisor','advisors','completion','meeting','period','proposal'} and global_discovery: mode='discovery' + elif route is None and mode=='period' and global_discovery and re.search(r'\b(?:kto|ktori|ktory|ktora|ktore)\b',n): + # "Ktorí študenti od roku 2024 robili s LLM?": who did a topic, in a period; the period filters the + # records (below), the question stays a discovery with its conditions ("bez RASA") + mode='discovery' # Facet questions without an academic lifecycle intent share one execution # path, including GraphRAG's content evidence. Explicit metadata stays metadata. if route is None and (not mode or mode=='progress' and facets) and content_question(q):mode='facets' @@ -330,7 +334,9 @@ def direct_spec(question, resolution, *, meeting=None, route=None, relative_year # "Kto robil chatbota bez RASA?": students of the topic whose records # never mention the excluded term. The answer says that an absent # mention is not proof of non-use; other modes keep refusing. - excluded=re.search(r'\bbez\s+(?:pouzitia\s+|vyuzitia\s+)?([^?.,;!]{2,40}?)\s*(?:[?.,;!]|$)',exclusion_text) + # the excluded term ends where the next condition begins ("bez Pythonu v roku 2025", "bez RASA a …") + excluded=re.search(r'\bbez\s+(?:pouzitia\s+|vyuzitia\s+)?([^?.,;!]{2,40}?)\s*(?:[?.,;!]|$' + r'|\s(?:v|vo|od|do|a|ale|aj|s|so|pri|na|z|zo|za|pocas|ktor\w*|kto|ako|kedy|s\s+akymi)\s)',exclusion_text) if mode=='discovery' and not students and excluded and len(excluded[1].split())<=3: exclusions.append(Condition(kind='exclusion',quote=excluded[1].strip())) elif not (route is not None and route.exclusion and mode=='discovery'):unsupported.append('exclusion') diff --git a/tools/crzp/answering/answer.py b/tools/crzp/answering/answer.py index ad75ed5..6d4050a 100644 --- a/tools/crzp/answering/answer.py +++ b/tools/crzp/answering/answer.py @@ -80,6 +80,11 @@ def keep(row: dict, query: CrzpQuery) -> bool: return False if query.published and not row.get("published"): return False # "obhájili": an unpublished work may be undefended or have its publication deferred + if query.exclude_terms: # "bez RASA": a work whose title or keywords name the excluded tool is left out + from tools.crzp.answering.relevance import mentions + text = " ".join([row.get("title") or "", *(row.get("keywords") or [])]) + if any(mentions(text, term, case=False) for term in query.exclude_terms): + return False return True diff --git a/tools/crzp/answering/understand.py b/tools/crzp/answering/understand.py index bb25cef..0ba4d66 100644 --- a/tools/crzp/answering/understand.py +++ b/tools/crzp/answering/understand.py @@ -120,6 +120,7 @@ class CrzpQuery(BaseModel): show: int | None = None # follow-up "vypíš prvých 8": how many works to list split: str | None = None # follow-up "rozdeľ podľa rokov / typov": "year" or "type" previous_count: int | None = None # follow-up of the same search: the exact count the previous answer had + exclude_terms: list[str] = Field(default_factory=list, max_length=3) # "bez RASA", "nepoužil Python" def topic_key(self) -> str: """The topic the alternative terms belong to (the rule phrase without the model).""" @@ -436,9 +437,29 @@ def understand(question: str, *, complete=None, use_model: bool = True) -> CrzpQ query.target_role = None # "Koľkokrát oponoval X" asks about X's own role, not about another person if query.intent == "relation" and query.target_role is None: query.intent = "list" + query.exclude_terms = excluded_terms(question) + if query.exclude_terms: # the excluded tool is no topic of the search + query.topics = [t for t in query.topics if not any(fold(t).startswith(e[:4]) for e in query.exclude_terms)] return query +# "bez RASA", "bez použitia Pythonu v roku 2025", "ale nepoužil RASA": a tool the works must not name. The term ends +# where the next condition begins; "bez domýšľania" and similar presentation wishes are no exclusion. +EXCLUDED = re.compile(r"\bbez\s+(?:pouzitia\s+|vyuzitia\s+)?([a-z0-9][a-z0-9\-]*(?:\s+[a-z0-9\-]+){0,2}?)" + r"(?=\s*(?:[?.,;!]|$)|\s+(?:v|vo|od|do|a|ale|aj|s|so|pri|na|z|zo|za|pocas|ktor\w*|kto|ako|kedy)\b)" + r"|\bnepouzi\w*\s+([a-z0-9][a-z0-9\-]{1,30})") +NOT_EXCLUSIONS = {"domyslania", "dohadov", "spekulacii", "nepodlozenych tvrdeni", "zdrojov", "vysvetlenia", "obmedzenia"} + + +def excluded_terms(question: str) -> list[str]: + terms = [] + for match in EXCLUDED.finditer(fold(question)): + term = (match.group(1) or match.group(2) or "").strip() + if term and term not in NOT_EXCLUSIONS and len(term.split()) <= 3: + terms.append(term) + return list(dict.fromkeys(terms))[:3] + + def names_a_school(term: str) -> bool: """"KEMT", "TUKE", "FEI" or a school name is a filter, not a topic to search.""" folded = " ".join(fold(term).split()) diff --git a/tools/crzp/tests/test_crzp.py b/tools/crzp/tests/test_crzp.py index dcf60eb..50a5cc8 100644 --- a/tools/crzp/tests/test_crzp.py +++ b/tools/crzp/tests/test_crzp.py @@ -979,3 +979,13 @@ def test_suite_fixes_count_wording(): assert relevance.names_topic({"title": "Automatické rozpoznávanie reči"}, ["rozpoznávanie reči"]) assert A._at("Technická univerzita v Košiciach") == "Technickej univerzite v Košiciach" assert A._author_word({"authors": ["Kolisnichenko, Iryna"]}) in ("autorka", "autor") + + +def test_an_excluded_tool_leaves_out_works_that_name_it(): + from tools.crzp.answering.understand import CrzpQuery, excluded_terms + assert excluded_terms("Ktorí študenti robili s LLM bez Pythonu v roku 2025?") == ["pythonu"] + assert excluded_terms("Kto robil chatbota, ale nepoužil RASA?") == ["rasa"] + assert excluded_terms("Odpovedz bez domýšľania, kto robil RAG?") == [] + query = CrzpQuery(exclude_terms=["pythonu"]) + assert not A.keep({"title": "Využitie GPT v jazyku Python", "keywords": []}, query) + assert A.keep({"title": "Hodnotenie odpovedí pomocou LLM", "keywords": ["NLP"]}, query)