2394 lines
145 KiB
Python
2394 lines
145 KiB
Python
"""ZP Wiki and CRZP in one answer for /rag and /graphrag.
|
||
|
||
Every question is answered from ZP Wiki (the normal RAG / GraphRAG path) and,
|
||
at the same time, from CRZP when CRZP can add something (see crzp_plan):
|
||
- a person ZP Wiki knows: that person's works in CRZP at Technická univerzita
|
||
v Košiciach (supervisor, opponent, abstract, keywords the wiki may lack);
|
||
- a topic or "similar works": CRZP works on the same topic, with their schools;
|
||
- a question naming CRZP, another school, opponents or defended works of a
|
||
department: CRZP is the main source.
|
||
Meetings, tasks, progress and results stay ZP Wiki only.
|
||
|
||
The answer is one text: a list of people is one numbered list (ZP Wiki people
|
||
first, then CRZP works, each marked with its source), the first PAGE items are
|
||
shown and the rest is offered ("Chceš vidieť ďalších?"); all sources are in one
|
||
line at the end. The context of the next message (the wiki's own token, the
|
||
shown people for "a z akých škôl sú?" and "a čo robil prvý z nich?", the id of
|
||
the not yet shown items of tools/answers/pages.py) is one conversation step on
|
||
the server (tools/answers/context_store.py); Claude gets a short signed token
|
||
of that step, and a message may refer to an older step of the conversation.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import contextvars
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
|
||
|
||
from tools.answers.verification.context_policy import normalized
|
||
from tools.answers.verification.delivery_contract import fingerprint
|
||
|
||
CRZP_SECONDS = float(os.getenv("CRZP_COMBINED_SECONDS", "45"))
|
||
# CRZP is the only source that can answer (a person ZP Wiki does not know, defended works of a
|
||
# department, "v CRZP") or ZP Wiki has nothing: the answer waits for CRZP this long from the start
|
||
# of the question, under the 90 s limit of the MCP client (packages/claude/client.py), and then
|
||
# says the search is still running instead of showing a weak wiki answer or "nenašiel".
|
||
CRZP_WAIT_SECONDS = float(os.getenv("CRZP_WAIT_SECONDS", "80"))
|
||
CRZP_PENDING = ("Hľadanie v registri záverečných prác (CRZP) ešte prebieha. Zopakuj otázku o chvíľu, "
|
||
"výsledok už bude pripravený.")
|
||
_probe: contextvars.ContextVar[dict | None] = contextvars.ContextVar("crzp_probe", default=None)
|
||
_inflight: dict = {} # a CRZP part still running for the same question: (future, probe)
|
||
_inflight_lock = threading.Lock()
|
||
LIFETIME = 24 * 3600
|
||
PREFIX = "zc1." # plain JSON body (still read)
|
||
PREFIX2 = "zc2." # zlib-compressed JSON body (still read; issued with ANSWER_CONTEXT_STORE=0)
|
||
PREFIX3 = "zc3." # the id of a step kept on the server (tools/answers/context_store.py) and its signature
|
||
# crzp_plan dropped the wiki person of "… a koľko podobných prác je na iných školách?": the CRZP part is an addition
|
||
_addition: contextvars.ContextVar[bool] = contextvars.ContextVar("crzp_addition", default=False)
|
||
_parent: contextvars.ContextVar[str | None] = contextvars.ContextVar("answer_parent_step", default=None)
|
||
# The person the conversation is about (the last question naming exactly one person, or the one chosen from a list):
|
||
# stored with each step, so "kto je jeho konzultant?" or "a kto ho viedol?" knows whom it asks about.
|
||
_subject: contextvars.ContextVar[str | None] = contextvars.ContextVar("answer_subject", default=None)
|
||
TUKE = "Technická univerzita v Košiciach"
|
||
WIKI_SCHOOL = "Technická univerzita v Košiciach (KEMT FEI)"
|
||
# What only the wiki records: CRZP is not asked.
|
||
WIKI_ONLY = re.compile(r"\b(?:stretnut\w*|pokrok\w*|progres\w*|uloh\w*|zadan\w*|plan\w*|termin\w*|tyzd\w*|"
|
||
r"repozitar\w*|git\w*|stav\w*|poznam\w*|konzult\w*|zaciat\w*|studi\w*|obhaj\w*|ukonc\w*|"
|
||
r"dokonc\w*|uspes\w*|statnic\w*|hodnot\w*|znamk\w*|problem\w*|vtedy|posledn\w*|"
|
||
r"zacal\w*|studoval\w*|studovat|cen[auy]|ocenen\w*|svoc|vyznamen\w*)\b")
|
||
EXPLICIT = re.compile(r"\b(?:crzp|registr\w*|register|celoslovensk\w*|na slovensku|(?:inych|inej|inom|ostatnych|"
|
||
r"vsetkych|dalsich|slovensk\w+)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*|mimo tuke|"
|
||
r"oponent\w*|oponoval\w*)\b")
|
||
NAMED_CRZP = re.compile(r"\b(?:crzp|registr\w*|register)\b") # the register itself is asked, not only opponents
|
||
NAMED_WIKI = re.compile(r"\b(?:zp\s*wiki|wiki\w*)\b") # the wiki asked too: "podľa registra a čo uvádza ZP Wiki"
|
||
METHODS = re.compile(r"\b(?:technolog\w*|nastroj\w*|metod\w*|pouziv\w*|pouzil\w*|vyuziv\w*|vyuzil\w*|framework\w*)\b")
|
||
ABOUT = re.compile(r"\b(?:o com|zhrn\w*|abstrakt\w*|ciel\w*)\b") # not "čomu sa venuje": the current work
|
||
# A question about a thesis (not "na čom pracuje", which CRZP's submitted works cannot answer).
|
||
THESIS = re.compile(r"\b(?:prac(?:a|e|u|i|ou|ach|ami)?|bakalar\w*|diplom\w*|dizerta\w*|habilita\w*|bp|dp|tem(?:a|u|y|ou)|"
|
||
r"oponent\w*|vedu\w*|skolitel\w*|abstrakt\w*|klucov\w*|tagy?)\b")
|
||
BARE_COMPLETION = re.compile(r"^(?:obhajil\w*|ukoncil\w*|dokoncil\w*)\s+(?:[^\W\d_]+\s+){1,3}"
|
||
r"(?:(?:bakalar|diplom|dizert)\w*\s+)?(?:prac\w*|bakalark\w*|diplomovk\w*)\W*$")
|
||
WIKI_CLARIFICATION_YIELDS = {"missing_subject", "unsupported_content_question", "unsupported_constraint",
|
||
"content_count_not_established"} # "the wiki cannot count this": CRZP counts it
|
||
# "Koľko prác obhájili na KEMT v roku 2024?": defended works of a school or department are CRZP's
|
||
# published works, not a wiki question about one student's defence.
|
||
# "Prečo si myslíš, že …?", "Odkiaľ vieš, že …?", "Na základe čoho tvrdíš, že …?" (+ "Odkiaľ to vieš?")
|
||
EXPLAIN = re.compile(r"^\W*(?:pre[čc]o|odkia[ľl]|ako|na\s+z[áa]klade\s+[čc]oho)\s+(?:si\s+mysl[íi][šs]|vie[šs]|tvrd[íi][šs])"
|
||
r"\s*,?\s*(?:že|ze)\s+(.+?)\s*\?(?:\s*(?:odkia[ľl]|ako|pre[čc]o)\s+to\s+(?:vie[šs]|tvrd[íi][šs])\s*\?)?\s*$",
|
||
re.I)
|
||
# A topic named in a count ("na tému blockchain", "o rozpoznávaní reči", "s LLM"; not "o koľko")
|
||
TOPIC_CUE = re.compile(r"\b(?:na\s+temu|tem\w*|o(?!\s+kolk)|ohladom|s|so|v\s+oblasti|tykal\w*\s+sa|tyka\w*\s+sa|"
|
||
r"zameran\w*\s+na|venoval\w*\s+sa|zaoberal\w*\s+sa)\s+[a-z0-9]{2,}")
|
||
DEFENDED = re.compile(r"\b(?:obhaj\w*|obhajen\w*|obhajil\w*|uspesn\w*)\b")
|
||
TOPIC_MIN_SCORE = float(os.getenv("CRZP_TOPIC_MIN_SCORE", "0"))
|
||
PAGE = int(os.getenv("ANSWER_PAGE_SIZE", "6"))
|
||
MAX_SOURCES = 40 # CRZP links in one "Zdroje:" line (every work an answer lists or counts per person)
|
||
WIKI_FIRST = 4 # a mixed list shows at most this many ZP Wiki people before the CRZP works
|
||
REFUSED = {"request_out_of_scope", "irrelevant", "unsupported_request", "out_of_scope"}
|
||
RELATED = re.compile(r"\b(?:suvis\w*|pribuzn\w*)\b")
|
||
SIMILAR = re.compile(r"\b(?:podobn\w*|suvisiac\w*|pribuzn\w*|spolupra\w*|rovnak\w* tem\w*)\b")
|
||
TOPIC_LIST = re.compile(r"^\W*(?:kto|ktor\w*|ak\w*|vypis\w*|ukaz\w*|daj\s+mi)\b")
|
||
SCHOOLS = re.compile(r"\b(?:z|zo|na) (?:akych|akej|ktorych|ktorej) (?:skol|univerzit|fakult)\w*|\bkde (?:studoval\w*|studuj\w*)"
|
||
r"|\b(?:ktor|ak)\w* (?:skol|univerzit)\w*")
|
||
CHOICE_WIKI = re.compile(r"\b(?:wiki|diplom\w*|dp)\b")
|
||
CHOICE_CRZP = re.compile(r"\b(?:crzp|bakalar\w*|bp)\b")
|
||
|
||
|
||
_shared = {"pool": None}
|
||
_shared_lock = threading.Lock()
|
||
|
||
|
||
def _pool() -> ThreadPoolExecutor:
|
||
"""One pool for all questions (no new threads per request)."""
|
||
with _shared_lock:
|
||
if _shared["pool"] is None:
|
||
_shared["pool"] = ThreadPoolExecutor(max_workers=int(os.getenv("ANSWER_COMBINED_WORKERS", "6")),
|
||
thread_name_prefix="answer")
|
||
return _shared["pool"]
|
||
|
||
|
||
def enabled() -> bool:
|
||
return os.getenv("ANSWER_WITH_CRZP", "1") != "0"
|
||
|
||
|
||
# ------------------------------------------------------------------ token
|
||
|
||
def _key() -> bytes | None:
|
||
secret = os.getenv("SEARCH_API_KEY", "")
|
||
return hashlib.sha256(("zp-combined-v1\0" + secret).encode()).digest() if secret else None
|
||
|
||
|
||
def _b64(value: bytes) -> str:
|
||
return base64.urlsafe_b64encode(value).decode().rstrip("=")
|
||
|
||
|
||
def _signature(key: bytes, step: str) -> str:
|
||
return _b64(hmac.digest(key, (PREFIX3 + step).encode(), "sha256"))[:16]
|
||
|
||
|
||
def step_token(step: str | None) -> str | None:
|
||
"""The short token of a stored step ("zc3.<id>.<signature>")."""
|
||
key = _key()
|
||
return PREFIX3 + step + "." + _signature(key, step) if key and step else None
|
||
|
||
|
||
def token_step(token: str | None) -> str | None:
|
||
"""The step id of a genuine short token, else None."""
|
||
key = _key()
|
||
if not isinstance(token, str) or not token.startswith(PREFIX3) or key is None:
|
||
return None
|
||
parts = token[len(PREFIX3):].split(".")
|
||
if len(parts) != 2 or not re.fullmatch(r"[A-Za-z0-9_-]{16}", parts[0]):
|
||
return None
|
||
return parts[0] if hmac.compare_digest(parts[1], _signature(key, parts[0])) else None
|
||
|
||
|
||
def seal(payload: dict) -> str | None:
|
||
"""The token of the answer's context: a short step token (the context kept on the server after the
|
||
step the message continued), or, with ANSWER_CONTEXT_STORE=0 or a failed store, the signed and
|
||
compressed context itself (the wiki's and CRZP's own tokens inside make it long)."""
|
||
import zlib
|
||
from tools.answers import context_store
|
||
key = _key()
|
||
if key is None:
|
||
return None
|
||
if context_store.enabled():
|
||
token = step_token(context_store.save(payload, _parent.get()))
|
||
if token:
|
||
return token
|
||
raw = json.dumps({**payload, "expires": int(time.time()) + LIFETIME}, ensure_ascii=False, separators=(",", ":"))
|
||
body = _b64(zlib.compress(raw.encode(), 9))
|
||
token = PREFIX2 + body + "." + _b64(hmac.digest(key, body.encode(), "sha256"))
|
||
return token if len(token) <= 16000 else None
|
||
|
||
|
||
def unseal(token: str | None) -> dict | None:
|
||
"""The combined context (a stored step also gives its id as "_step"), or None for a token that
|
||
is not ours (a plain wiki token)."""
|
||
import zlib
|
||
if isinstance(token, str) and token.startswith(PREFIX3) and _key() is not None:
|
||
from tools.answers import context_store
|
||
step = token_step(token)
|
||
if step is None:
|
||
return {"error": "invalid_context"}
|
||
value = context_store.load(step)
|
||
return {**value, "_step": step} if value is not None else {"error": "expired_context"}
|
||
if not isinstance(token, str) or not token.startswith((PREFIX, PREFIX2)) or _key() is None:
|
||
return None
|
||
try:
|
||
body, signature = token[4:].split(".")
|
||
expected = hmac.digest(_key(), body.encode(), "sha256")
|
||
if not hmac.compare_digest(base64.b64decode(signature + "=" * (-len(signature) % 4), altchars=b"-_"), expected):
|
||
raise ValueError
|
||
data = base64.b64decode(body + "=" * (-len(body) % 4), altchars=b"-_")
|
||
value = json.loads(zlib.decompress(data) if token.startswith(PREFIX2) else data)
|
||
if value.get("expires", 0) < time.time():
|
||
return {"error": "expired_context"}
|
||
return value
|
||
except (ValueError, TypeError, UnicodeError, zlib.error):
|
||
return {"error": "invalid_context"}
|
||
|
||
|
||
# ------------------------------------------------------------------ wiki facts
|
||
|
||
_index_cache: dict = {}
|
||
_index_lock = threading.Lock()
|
||
|
||
|
||
def _index():
|
||
"""The published knowledge index, reloaded only when its version changes."""
|
||
from tools.knowledge.store import load_index
|
||
from tools.rag.common import DB_FILE
|
||
from tools.sync.index_state import read_version
|
||
version = read_version(DB_FILE.parent)
|
||
key = (version or {}).get("version")
|
||
with _index_lock:
|
||
if _index_cache.get("key") != key:
|
||
_index_cache.update(key=key, index=load_index(DB_FILE.parent, version))
|
||
return _index_cache["index"]
|
||
|
||
|
||
# "Kto je Ján Novák?", "Čo robil Peter Kováč?": a question about a person (for CRZP when the wiki does not know it).
|
||
PERSON_Q = re.compile(r"^\W*(?:kto\s+(?:je|bol|bola|bude)|co\s+(?:robi|robil|robila|riesil|riesila)|na\s+com\s+pracoval\w*|"
|
||
r"kde\s+studoval\w*|o\s+kom|povedz\s+mi\s+o)\b")
|
||
HUMAN_NAME = re.compile(r"[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][a-záäčďéíĺľňóôŕšťúýž]+(?:-[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][a-záäčďéíĺľňóôŕšťúýž]+)?(?:\s+[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][a-záäčďéíĺľňóôŕšťúýž]+(?:-[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][a-záäčďéíĺľňóôŕšťúýž]+)?){1,2}")
|
||
def COMPARE_TWO(low: str) -> bool:
|
||
""""Mohol by A spolupracovať s B?", "Porovnaj A a B": two people named, a comparison of the pair."""
|
||
return bool(COMPARE.search(low)) and not TOPIC_LIST.match(low)
|
||
|
||
|
||
COUNT_STUDENTS = re.compile(r"\bkolk\w*\s+(?:studentov|student\w*)\b")
|
||
STUDY_START = re.compile(r"\b(?:zaciat\w*\s+stud\w*|zacal\w*\s+stud\w*)\b")
|
||
COMPARE = re.compile(r"\b(?:porovn\w*|rozdiel\w*|odlis\w*|v com sa lis\w*|spolupr\w*)\b")
|
||
# "a Ján Pták?", "a čo Ján Pták?", "a Ján Pták by mohol?": the previous question about another person.
|
||
ELLIPSIS = re.compile(r"^\W*a(?:\s+(?:co|ako|kto|aj))?\s+\S")
|
||
COULD = re.compile(r"\b(?:mohol|mohla|mohli|moze|mozu|hodil|hodila)\b")
|
||
|
||
|
||
def _one_person(question: str) -> dict | None:
|
||
"""{"name", "input"}: the one ZP Wiki person a question names, with the words naming it."""
|
||
from tools.answers.planning.question_plan import planning_catalog
|
||
from tools.rag.common import DB_FILE
|
||
from tools.retrieval.person_names import resolve_person_names
|
||
try:
|
||
resolution = resolve_person_names(question, planning_catalog(DB_FILE) or [])
|
||
except Exception:
|
||
return None
|
||
matches = resolution.get("matches") or []
|
||
if resolution.get("status") != "ok" or len({m["name"] for m in matches}) != 1:
|
||
return None
|
||
return {"name": matches[0]["name"], "input": matches[0].get("input") or matches[0]["name"]}
|
||
|
||
|
||
def ellipsis(question: str, previous: dict | None) -> str | None:
|
||
"""The full question behind a short follow-up about another person: "a Ján Pták?" after
|
||
"Kto je vedúci práce Jakuba Schwarca?" -> "Kto je vedúci práce Ján Pták?"; "a Ján Pták by mohol?"
|
||
after "Kto by mohol spolupracovať s Jakubom Schwarcom?" -> whether these two could work together."""
|
||
low = normalized(question)
|
||
if not previous or not previous.get("question") or not ELLIPSIS.match(low) or len(low.split()) > 7:
|
||
return None
|
||
bare = re.sub(r"(?i)^\W*a(?:\s+(?:čo|co|ako|kto|aj))?\s+", "", question)
|
||
bare = re.sub(r"(?i)\s+by\s+(?:mohol|mohla|mohli)\W*$|\W+$", "", bare)
|
||
new, old = _one_person(bare) or _one_person(question), _one_person(previous["question"])
|
||
if not new and re.fullmatch(r"[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][\w\-]+(?:\s+[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][\w\-]+){1,2}", bare):
|
||
new = {"name": bare, "input": bare} # a teacher is resolved only in a question ("Koho vedie Matúš Pleva?")
|
||
if not new or not old or new["name"] == old["name"]:
|
||
return None
|
||
asked = previous["question"]
|
||
if COULD.search(low) and SIMILAR.search(normalized(asked)):
|
||
return f"Mohol by {new['name']} spolupracovať s osobou {old['name']}?"
|
||
if old["input"] in asked:
|
||
return asked.replace(old["input"], new["name"], 1)
|
||
return None
|
||
|
||
|
||
BACK_WORK = re.compile(r"(?i)\b(?:tej|tejto|tom|tomto|tú|tu|túto|tuto|jeho|jej|svojej)\s+"
|
||
r"((?:bakal|diplom|dizerta|záverečn|zaverecn|prác|prac|projekt)\w*)")
|
||
|
||
|
||
def named_back(question: str, previous: dict | None) -> str | None:
|
||
""""kto bol oponentom tej bakalárky?" after a question about one person, naming no one: the person of the
|
||
previous question is put in ("… bakalárky Ján Pták?"), so the roles of that person's work are read."""
|
||
if not previous or not previous.get("question") or previous.get("options") or _one_person(question):
|
||
return None
|
||
match = BACK_WORK.search(question)
|
||
old = _one_person(previous["question"]) if match else None
|
||
if not old:
|
||
return None
|
||
return question[:match.start()] + match.group(1) + " " + old["name"] + question[match.end():]
|
||
|
||
|
||
# "Koho vedie X?", "Komu robí vedúceho X?", "Akých študentov má X?", "študenti pod vedením X"
|
||
SUPERVISES = re.compile(r"\bkoho\s+(?:vedie|viedol|viedla|skoli\w*)|\bkomu\s+robi\s+veduc\w*|"
|
||
r"\b(?:akych|ktorych|kolkych|kolko)\s+studentov\b|\bstudent\w*\s+(?:pod\s+vedenim|ma|vedie)\b|"
|
||
r"\bpod\s+(?:sebou|vedenim)\b")
|
||
SAME_OPPONENT = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn\w*)\s+oponent\w*")
|
||
SAME_SUPERVISOR = re.compile(r"\b(?:rovnak\w*|toho\s+ist\w*|ten\s+ist\w*|spolocn\w*)\s+(?:veduc\w*|skolitel\w*)")
|
||
# "práce študentov, ktorých viedol X": X as the supervisor of others, not X's own theses
|
||
STUDENTS_OF = re.compile(r"\bstudent\w*\b[^?]*\bktor\w*\s+(?:viedol|viedla|vedie|vedu)\b")
|
||
CONTACT = re.compile(r"\b(?:e[\s-]?mail\w*|mailov\w*\s+adres\w*|telefon\w*|tel\.?\s+cisl\w*|kontaktn\w*|kontakt\s+na)\b")
|
||
# "jeho vedúci", "jej konzultant": the subject's; "kto ho viedol", "čo mu funguje": about the subject
|
||
POSSESSIVE = re.compile(r"(?i)\b(?:jeho|jej)\s+([^\W\d_]{3,})")
|
||
OBJECT = re.compile(r"(?i)\b(?:ho|mu|jemu|ju|neho|nemu)\b")
|
||
SIMILAR_TO = re.compile(r"\b(?:podobn\w*|rovnak\w*\s+tem\w*|spolupra\w*)\b")
|
||
|
||
|
||
def with_subject(question: str, previous: dict | None) -> str | None:
|
||
"""A follow-up that points at the conversation's person by a pronoun gets the person's name: "kto je jeho
|
||
konzultant?" -> "kto je konzultant Samuela Vasiľa?", "a kto ho viedol?" -> "a kto viedol Samuela Vasiľa?",
|
||
"kto robil niečo podobné?" -> "… ako Samuel Vasiľ?". Questions naming a person or a work stay as they are."""
|
||
person = (previous or {}).get("person")
|
||
if not person or previous.get("options") or _one_person(question):
|
||
return None
|
||
from tools.answers.presentation.unified import genitive
|
||
match = POSSESSIVE.search(question)
|
||
if match:
|
||
return question[:match.start()] + match.group(1) + " " + genitive(person) + question[match.end():]
|
||
match = OBJECT.search(question)
|
||
if match:
|
||
rest = re.sub(r"\s{2,}", " ", question[:match.start()] + question[match.end():]).strip()
|
||
return re.sub(r"\s*\?*\s*$", "", rest) + " " + genitive(person) + "?"
|
||
low = normalized(question)
|
||
if SIMILAR_TO.search(low) and len(question.split()) <= 6:
|
||
return re.sub(r"\s*\?*\s*$", "", question) + " ako " + person + "?"
|
||
if (len(low.split()) <= 7 and IMPLIED_SUBJECT.search(low) and not re.match(r"^\W*(?:a\s+)?kto\b", low)
|
||
and not re.search(r"\b(?:z\s+nich|tento|tito|ten|ta|tej|tom|nej|nom)\b", low)):
|
||
# "aké technológie ešte použil?", "a čo robil v roku 2024?": the verb's subject is the conversation's person
|
||
return re.sub(r"\s*\?*\s*$", "", question) + " " + person + "?"
|
||
return None
|
||
|
||
|
||
# a past-tense verb without its subject ("použil", "robila", "mal"), in a question that is not "kto …?"
|
||
IMPLIED_SUBJECT = re.compile(r"^\W*(?:a\s+)?(?:ake|aky|aka|co|kedy|kde|ako|kolko|s\s+cim|na\s+com|preco)\b.*\b\w+(?:il|al|ol|el|ul|yl)a?\b")
|
||
|
||
|
||
NEWEST_OF = re.compile(r"\bktor\w*\s+z\s+nich\b.*\b(najnov\w*|najstar\w*|posledn\w*)\b|"
|
||
r"\b(najnov\w*|najstar\w*)\s+z\s+nich\b")
|
||
|
||
|
||
def _newest_of(question: str, low: str, previous: dict | None, engine: str) -> dict | None:
|
||
""""a ktorý z nich je najnovší?": the listed person with the newest (or oldest) work, from the list itself."""
|
||
match = NEWEST_OF.search(low)
|
||
entities = [e for e in (previous or {}).get("entities") or [] if e.get("year")]
|
||
if not match or not entities:
|
||
return None
|
||
oldest = (match.group(1) or match.group(2) or "").startswith("najstar")
|
||
chosen = (min if oldest else max)(entities, key=lambda e: e["year"])
|
||
word = "najstaršiu" if oldest else "najnovšiu"
|
||
text = f"Spomedzi uvedených má {word} prácu {chosen['name']} ({chosen['year']})."
|
||
url = entity_url(chosen)
|
||
_subject.set(chosen["name"])
|
||
result = _ok(question, engine, text + (f"\n\nZdroje: {url}" if url else ""), [url] if url else [], {})
|
||
return _with_token(result, entities=previous["entities"], question=question, crzp=previous.get("crzp"),
|
||
primary=previous.get("primary", "wiki"))
|
||
|
||
|
||
BACK_TO = re.compile(r"(?i)^\W*vr[aá]ť(?:me)?\s+sa\s+(?:k|ku)\s+([^,:?]+?)\s*[,:]\s*(.+)$")
|
||
|
||
|
||
def _back_to_person(question: str) -> str | None:
|
||
""""vráť sa k Vasiľovi, kedy začal študovať?" -> "kedy začal študovať Samuel Vasiľ?" (a person, not a question)."""
|
||
match = BACK_TO.match(question)
|
||
if not match or _one_person(match.group(2)):
|
||
return None
|
||
found = _one_person(match.group(1))
|
||
if not found:
|
||
return None
|
||
return re.sub(r"\s*\?*\s*$", "", match.group(2)) + " " + found["name"] + "?"
|
||
|
||
|
||
AGAIN_FILLERS = {"a", "ale", "no", "tak", "teda", "este", "presne", "vlastne", "konkretne", "mi", "povedz", "napis", "prosim"}
|
||
|
||
|
||
def again(question: str, previous: dict | None) -> str | None:
|
||
""""ale čo robil?" after "Čo robil Ján Pták v bakalárskej práci?": the user asks the previous
|
||
question once more (every content word of the reply is in it, no person is named)."""
|
||
if not previous or not previous.get("question") or previous.get("options"):
|
||
return None
|
||
words = [w for w in re.findall(r"[a-z0-9]+", normalized(question)) if w not in AGAIN_FILLERS]
|
||
before = set(re.findall(r"[a-z0-9]+", normalized(previous["question"])))
|
||
if not words or len(words) > 4 or not set(words) <= before or _one_person(question):
|
||
return None
|
||
return previous["question"]
|
||
|
||
|
||
def comparison_block(names: list[str]) -> str | None:
|
||
""""Porovnanie": the most specific concepts both students document and those only one does
|
||
(content graph, no model call), shown above the two students' records."""
|
||
try:
|
||
from tools.knowledge.activities import load_graph, compare_people
|
||
from tools.rag.common import DB_FILE
|
||
index = _index()
|
||
graph = load_graph(DB_FILE.parent, index) if index else None
|
||
if graph is None or len(names) != 2:
|
||
return None
|
||
paths = [{u["source_path"] for u in index["units"] if u.get("person") == name} for name in names]
|
||
if not all(paths):
|
||
return None
|
||
shared, left, right = compare_people(graph, paths[0], paths[1])
|
||
except Exception:
|
||
return None
|
||
lines = ["**Porovnanie** (podľa pojmov doložených v záznamoch):"]
|
||
if shared:
|
||
lines.append("- Spoločné: " + ", ".join(shared) + ".")
|
||
if left:
|
||
lines.append(f"- Len {names[0]}: " + ", ".join(left) + ".")
|
||
if right:
|
||
lines.append(f"- Len {names[1]}: " + ", ".join(right) + ".")
|
||
return "\n".join(lines) if len(lines) > 1 else None
|
||
|
||
|
||
def with_comparison(question: str, head: list[str], items: list[dict]) -> list[str]:
|
||
low = normalized(question)
|
||
# "Porovnaj A a B", "Mohol by A spolupracovať s B?" compare two people; "Kto by mohol spolupracovať
|
||
# s A?" lists candidates (two of them are no pair to compare).
|
||
if COMPARE.search(low) and len(items) == 2 and not TOPIC_LIST.match(low):
|
||
block = comparison_block([items[0]["name"], items[1]["name"]])
|
||
if block:
|
||
return [*head, block]
|
||
return head
|
||
|
||
|
||
def wiki_units(person: str) -> list[dict]:
|
||
try:
|
||
return [u for u in (_index() or {}).get("units", []) if u.get("person") == person]
|
||
except Exception:
|
||
return []
|
||
|
||
|
||
def wiki_works(person: str) -> dict[str, dict]:
|
||
"""work label -> {"type", "topic"} of the person's ZP Wiki works."""
|
||
works = {}
|
||
for unit in wiki_units(person):
|
||
label = unit.get("work_label")
|
||
if not label:
|
||
continue
|
||
work = works.setdefault(label, {"type": unit.get("work_type"), "topic": None})
|
||
if unit.get("kind") == "topic" and not work["topic"] and not unit["text"].strip().endswith(":"):
|
||
work["topic"] = re.sub(r"^\s*(?:Téma|Názov)\s*:\s*", "", unit["text"]).strip()
|
||
return works
|
||
|
||
|
||
def same_person_work(person: str, row: dict) -> bool:
|
||
"""A TUKE CRZP work of the person's name is confirmed as that person's when its title matches a
|
||
ZP Wiki work topic or its supervisor is the person's ZP Wiki supervisor; else it may be a namesake's."""
|
||
def stems(text):
|
||
return {w[:5] for w in normalized(text or "").split() if len(w) > 3}
|
||
title = stems(row.get("title"))
|
||
for work in wiki_works(person).values():
|
||
topic = stems(work.get("topic"))
|
||
if title and topic and len(title & topic) >= max(1, min(len(title), len(topic)) // 2):
|
||
return True
|
||
from tools.knowledge.sources import profile_authors
|
||
units = wiki_units(person)
|
||
paths = {u["source_path"] for u in units}
|
||
known = {normalized(profile_authors().get(p) or "") for p in paths}
|
||
known |= {normalized(u["text"]) for u in units if u.get("kind") == "supervisor"}
|
||
names = [set(n.split()) for n in known if n]
|
||
# Both name parts must agree ("Hládek, Daniel" and the profile author "Daniel Hladek").
|
||
return any(len(set(normalized(s).replace(",", " ").split()) & n) >= 2
|
||
for s in row.get("supervisors", []) for n in names)
|
||
|
||
|
||
FRAMEWORKS = {"python", "fastapi", "flask", "django", "streamlit", "react", "docker", "kubernetes", "git", "github",
|
||
"gitlab", "pandas", "numpy", "jupyter", "colab", "linux", "javascript", "typescript", "java", "html", "css",
|
||
"llm", "ai", "nlp", "veľký jazykový model", "umelá inteligencia", "zpwiki", "openwebui", "skills", "skill"}
|
||
|
||
|
||
def wiki_terms(person: str) -> list[str]:
|
||
"""The person's most specific topics and tools (reviewed topic groups first, frameworks never):
|
||
the words to look for in CRZP to find similar works."""
|
||
from tools.answers.evidence.content_selection import named_tools
|
||
from tools.retrieval.synonyms import base_name, group_of
|
||
counts: dict[str, float] = {}
|
||
for unit in wiki_units(person):
|
||
if unit.get("phase") not in {"result", "progress", "assignment"} and unit.get("kind") != "topic":
|
||
continue
|
||
for concept in unit.get("concepts") or []:
|
||
if not isinstance(concept, str):
|
||
continue
|
||
if len(group_of(concept)) > 1:
|
||
name, weight = base_name(concept), 2.0
|
||
elif named_tools(concept) and len(concept.split()) <= 2 and not re.search(r"[./]", concept):
|
||
name, weight = concept, 1.0
|
||
else:
|
||
continue
|
||
if normalized(name) not in FRAMEWORKS:
|
||
counts[name] = counts.get(name, 0) + weight
|
||
return sorted(counts, key=lambda n: (-counts[n], n))[:4]
|
||
|
||
|
||
def wiki_profile(person: str) -> str:
|
||
"""Topic titles and terms of the person's works: the text similar CRZP works are ranked against."""
|
||
works = wiki_works(person)
|
||
return ". ".join([*(w["topic"] for w in works.values() if w.get("topic")), ", ".join(wiki_terms(person))])
|
||
|
||
|
||
# ------------------------------------------------------------------ CRZP part
|
||
|
||
def _canonical_person(query, person: str) -> None:
|
||
""""kto bol oponent bakalárky oleh poiansik": the wiki resolved the misspelled name, the register is searched
|
||
for the real one (a name read from the question that is close to the resolved person becomes that person)."""
|
||
from tools.retrieval.person_names import _distance, normalize as fold_name
|
||
target = fold_name(person).split()
|
||
|
||
def close(a, b):
|
||
return _distance(a, b) <= max(1, min(len(a), len(b)) // 3)
|
||
for item in query.people:
|
||
words = fold_name(item.name).split()
|
||
if words == target or len(words) != len(target):
|
||
continue
|
||
if all(close(a, b) for a, b in zip(words, target)) or all(close(a, b) for a, b in zip(words, target[::-1])):
|
||
item.name, item.canonical = person, True
|
||
|
||
|
||
def crzp_plan(question: str, person: str | None, complete=None, student: bool = True):
|
||
"""(mode, CrzpQuery) or None when CRZP adds nothing to this question."""
|
||
from tools.crzp.answering.understand import Person, understand
|
||
from tools.crzp.answering.units import unit_in_question
|
||
low = normalized(question)
|
||
explicit = bool(EXPLICIT.search(low))
|
||
defended_scope = bool(DEFENDED.search(low) and not person and (
|
||
unit_in_question(question) or re.search(r"\b(?:univerzit\w*|fakult\w*|katedr\w*|skol\w*|tuke|stu|kemt|fei)\b", low)))
|
||
# "V ktorom roku obhájil X diplomovú prácu?": the defence of a thesis is what the register records (a
|
||
# submitted, published thesis); the other wiki-only words (meetings, tasks, the start of studies) still keep CRZP out
|
||
# (the bare "Obhájil Ján Holp diplomovú prácu?" stays the wiki's: a record in the register is no proof of a defence)
|
||
gated = re.sub(r"\b(?:obhaj\w*|ukonc\w*|dokonc\w*|uspes\w*)\b", " ", low) if THESIS.search(low) \
|
||
and not BARE_COMPLETION.match(low) else low
|
||
if WIKI_ONLY.search(gated) and not explicit and not defended_scope:
|
||
return None
|
||
from tools.answers.presentation.unified import TAG_Q
|
||
if TAG_Q.search(low) and not RELATED.search(low): # a ZP Wiki tag or category, which CRZP does not have
|
||
return None
|
||
# A person ZP Wiki knows needs no model reading of the question (the person and school are
|
||
# fixed below; rules give the intent): one model call less, the wiki part has the slots.
|
||
topical_person = bool(person and TOPIC_CUE.search(low)) # "Koľko prác o chatbotoch viedol Hládek?"
|
||
query = understand(question, complete=complete, use_model=not person or explicit or topical_person)
|
||
if query.intent == "refused":
|
||
return None
|
||
other_school = query.school not in (None, "tuke") or explicit or bool(query.exclude_school)
|
||
if person and other_school and not query.from_model:
|
||
query = understand(question, complete=complete)
|
||
if person and query.people:
|
||
_canonical_person(query, person)
|
||
if query.target_role and len(query.people) > 1:
|
||
# "Kto bol naozaj oponentom …?": the asked role is unknown, a name given for it ("napíš, že oponentom bol
|
||
# Peter Novák") is a claim, never a search condition
|
||
query.people = [p for p in query.people if p.role != query.target_role] or query.people
|
||
if query.exclude_school and re.search(r"\baj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich)\b", low) \
|
||
and re.search(r"\b(?:kemt\w*|tuke\w*|fei)\b", low):
|
||
query.exclude_school = None # "na KEMT a sú podobné práce aj na iných školách": both, not only the others
|
||
if query.intent == "similar" and query.topics and not query.title and not query.sids and not (query.people and not person):
|
||
query.intent = "list" # "sú podobné práce aj na iných školách?" names no work to compare: works of the topic
|
||
if not query.people and not query.exclude_school and query.school in (None, "tuke"):
|
||
query.school, query.unit = None, None
|
||
return "topic", query # "Kto robil s Whisper na KEMT a sú podobné práce aj inde?": one list with the wiki
|
||
if (query.topics and not query.people and not query.exclude_school and not query.title
|
||
and re.search(r"\baj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich|inej)\b", low)):
|
||
query.school, query.unit = None, None # "Kto robil s Whisper na KEMT a sú podobné práce aj na iných školách?"
|
||
return "topic", query # both: one list of the wiki people and the register's works of the topic
|
||
if query.exclude_school and query.topics and query.people and re.search(r"\bpodobn\w*", low) \
|
||
and query.intent in ("count", "list"):
|
||
# "Ktorí študenti Hládka robili s LLM … a koľko podobných prác je na iných školách?": the other
|
||
# schools' works of the topic, not the person's (the wiki answers about the person's students)
|
||
query.people = []
|
||
_addition.set(True)
|
||
if person and not student and not other_school and supervisor_count(question):
|
||
# "Koľko bakalárok viedol Hládek v roku 2024 a 2025?": CRZP counts the submitted works per year and type
|
||
# (the wiki lists students, not counts); a future year stays with the wiki (CRZP has no such works yet)
|
||
query.people = [Person(name=person, role="opponent" if re.search(r"\bopon\w*", low) else "supervisor",
|
||
typed=person, canonical=True)]
|
||
query.intent, query.school, query.unit, query.from_model, query.title = "count", "tuke", None, True, None
|
||
if not TOPIC_CUE.search(low): # rule words of a plain count are no topic ("robilo", "viac")
|
||
query.topics, query.alternatives, query.phrases, query.surface = [], [], [], []
|
||
return "explicit", query
|
||
if person and not other_school:
|
||
if SIMILAR.search(low) and student:
|
||
return "similar", query
|
||
role = query.people[0].role if query.people else "any"
|
||
if student and SUPERVISES.search(low):
|
||
role = "supervisor" # "Akých študentov má Maroš Harahus?": a doctoral student as a supervisor
|
||
elif student:
|
||
role = "author" # a student's works are those he or she wrote ("Kto vedie Jána Ptáka?": his own works;
|
||
# a doctoral student who also reviews works keeps them out of "his works")
|
||
elif role not in ("supervisor", "opponent"):
|
||
role = "supervisor" # a supervisor's works are those he or she led
|
||
query.people = [Person(name=person, role=role, typed=person, canonical=True)]
|
||
query.school, query.unit, query.from_model, query.title = "tuke", None, True, None
|
||
if not (not student and topical_person and query.topics): # a supervisor's works of a topic keep it
|
||
query.topics, query.alternatives = [], []
|
||
return "person", query
|
||
if query.people and not person and query.search_text() and (
|
||
THESIS.search(low) or METHODS.search(low) or PERSON_Q.search(low) and HUMAN_NAME.fullmatch(query.people[0].name)):
|
||
return "explicit", query # a person ZP Wiki does not know: CRZP knows the theses of all schools
|
||
if query.topics and not query.people and RELATED.search(low) and not re.search(r"\b(?:tag\w*|klucov\w*)\b", low):
|
||
query.intent = "keywords" # "Ktoré témy súvisia s X?": topics of works about X, and who did them
|
||
return "related", query
|
||
if query.topics and not query.people and RELATED.search(low):
|
||
query.intent = "keywords" # "Ktoré tagy súvisia s X?": the CRZP tags themselves
|
||
return "explicit", query
|
||
if query.topics and not query.people and query.intent in ("relation", "count", "keywords", "schools"):
|
||
return "explicit", query # "Kto viedol najviac prác o X?", "Koľko prác o X…": computed over CRZP
|
||
if (other_school or ((query.school or query.unit) and not query.people)) and query.search_text():
|
||
return "explicit", query # another school, CRZP itself, opponents, or a school/department as a whole
|
||
if query.topics and not query.people and (TOPIC_LIST.search(low) or SIMILAR.search(low)):
|
||
return "topic", query
|
||
return None
|
||
|
||
|
||
def _crzp_follow_up_methods(question: str, low: str, previous: dict, engine: str, complete) -> dict | None:
|
||
""""a aké technológie použila?" after a CRZP answer about one person: that person's technologies
|
||
(crzp_person_methods: one work -> a sentence, two or more -> which one?)."""
|
||
if not METHODS.search(low):
|
||
return None
|
||
from tools.crzp.answering import context as crzp_context
|
||
try:
|
||
query = crzp_context.restore(previous["crzp"])["query"]
|
||
except Exception:
|
||
return None
|
||
if not query.people:
|
||
return None
|
||
from tools.crzp.answering.understand import WORK_CUES
|
||
query.work_types = [t for t, cue in WORK_CUES.items() if re.search(cue, question.lower())] or query.work_types
|
||
query.intent, query.sids, query.topics, query.alternatives = "list", [], [], []
|
||
part = crzp_person_methods(question, query, complete)
|
||
if part is None:
|
||
return None
|
||
result = _ok(question, engine, part["text"] + ("\n\nZdroje: " + ", ".join(part["urls"]) if part["urls"] else ""),
|
||
part["urls"], {})
|
||
if part["status"] == "ambiguous":
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, options=part["options"], question=f"Aké technológie využíva {part['person']}?",
|
||
crzp=previous.get("crzp"), primary="crzp")
|
||
return _with_token(result, question=question, crzp=previous.get("crzp"), primary="crzp")
|
||
|
||
|
||
def _future_defences(question: str, low: str) -> str:
|
||
"""The count of defences in a year that has not come yet: unknown (ZP Wiki plans theses by category,
|
||
e.g. dp2027, but a defence is recorded only after it)."""
|
||
from tools.crzp.answering.understand import years_in
|
||
years = years_in(question)
|
||
now = time.localtime().tm_year
|
||
if not years or min(years) <= now or not DEFENDED.search(low) or not re.search(r"\bkolk\w*|\bpocet\b", low):
|
||
return ""
|
||
when = f"v roku {years[0]}" if len(years) == 1 else f"v rokoch {min(years)}–{max(years)}"
|
||
return (f"Počet prác obhájených {when} zatiaľ nie je známy: obhajoba sa zaznamená až po nej a v registri "
|
||
f"záverečných prác sú práce najviac z roku {now}. V ZP Wiki môžu byť pripravované práce študentov s "
|
||
f"kategóriou podľa roku obhajoby (napr. dp{now + 1}).")
|
||
|
||
|
||
def supervisor_count(question: str) -> bool:
|
||
"""A count of a supervisor's works in a year or of a type, of past years only."""
|
||
from tools.crzp.answering.understand import WORK_CUES, years_in
|
||
low = normalized(question)
|
||
years = years_in(question)
|
||
counted = re.search(r"\bkolk\w*|\bpocet\b", low) or len(years) >= 2 and re.search(r"\b(?:viac|menej)\b", low)
|
||
works = re.search(r"\bprac\w*\b", low) and not re.search(r"\bstudent\w*|\bludi\b|\bosob\w*", low)
|
||
return bool(counted and (years or any(re.search(cue, question.lower()) for cue in WORK_CUES.values())
|
||
or works and TOPIC_CUE.search(low))
|
||
and all(y <= time.localtime().tm_year for y in years))
|
||
|
||
|
||
def crzp_person_methods(question: str, query, complete=None) -> dict | None:
|
||
""""Aké technológie využíva Bohdan Kuchinka v bakalárskej práci?" about a person only CRZP knows:
|
||
the work's keywords and the tools its abstract names (crzp_methods). Two or more theses and the
|
||
question names no type: which one? None when CRZP has no work (the general answer says so)."""
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.source.parse import display_name
|
||
found, rows = crzp.find(query)
|
||
rows = [r for r in crzp.resubmissions(rows) if crzp.people_in_role(r, query.people[0].name, "author")]
|
||
if not rows:
|
||
return None
|
||
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
||
name = display_name(rows[0]["authors"][0]) if rows[0].get("authors") else query.people[0].name
|
||
if len(rows) > 1 and not query.work_types:
|
||
options = [{"source": "crzp", "label": f"{_kind(r)} ({r.get('year') or '?'}) „{r['title']}“",
|
||
"type": r.get("work_type"), "key": crzp.work_key(r)} for r in rows[:4]]
|
||
text = (f"{name} má {len(options)} {'záverečné práce' if len(options) < 5 else 'záverečných prác'}:\n\n"
|
||
+ "\n".join(f"{i}. {o['label']}" for i, o in enumerate(options, 1))
|
||
+ "\n\nZ ktorej chceš vedieť, aké technológie využíva?")
|
||
return {"mode": "explicit", "status": "ambiguous", "text": text, "rows": [], "urls": [], "crzp_token": None,
|
||
"entities": [], "options": options, "intent": "methods", "person": name}
|
||
lines, used = [], []
|
||
for row in rows[:3]:
|
||
detail = crzp.fetch.detail(row["sid"]) if row.get("sid") else None
|
||
lines.append(crzp_methods(name, row, detail))
|
||
used.append(row)
|
||
return {"mode": "explicit", "status": "ok", "text": "\n\n".join(lines), "rows": used,
|
||
"urls": [r["url"] for r in used if r.get("url")], "crzp_token": None, "entities": [],
|
||
"intent": "methods", "person": name}
|
||
|
||
|
||
def crzp_comparison(query, complete=None, collaboration: bool = False, low: str = "") -> dict | None:
|
||
""""Porovnaj prácu Jána Ptáka a Samuela Furdu." when one of them is known only to CRZP: each person's
|
||
works as author (ZP Wiki works of a wiki person merged in), one table as for two wiki people."""
|
||
from tools.answers.presentation import unified as U
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.answering.understand import Person
|
||
from tools.crzp.source.parse import display_name
|
||
names, rows_all = [], []
|
||
for person in query.people:
|
||
known = U.catalog()["works"].get(person.name) and person.name
|
||
single = query.model_copy(update={"people": [Person(name=person.name, role="author", typed=person.typed)],
|
||
"intent": "list", "work_types": [], "years": []}, deep=True)
|
||
_, rows = crzp.find(single)
|
||
rows = [r for r in crzp.resubmissions(rows) if crzp.people_in_role(r, person.name, "author")]
|
||
if not rows and not known:
|
||
return None # not a person of either source: the general answer says so
|
||
name = known or display_name(rows[0]["authors"][0])
|
||
names.append(name)
|
||
rows_all.extend(rows)
|
||
out = U.comparison(names, collaboration=collaboration, crzp_rows=rows_all, low=low)
|
||
if out is None:
|
||
return None
|
||
return {"mode": "explicit", "status": "ok", "text": out["text"] if isinstance(out, dict) else out,
|
||
"rows": rows_all[:10], "urls": list(dict.fromkeys(
|
||
[*(out.get("urls", []) if isinstance(out, dict) else []), *[r["url"] for r in rows_all if r.get("url")]]))[:10],
|
||
"crzp_token": None, "entities": [], "intent": "compare", "person": None}
|
||
|
||
|
||
def clean_crzp(text: str) -> str:
|
||
"""CRZP answer text inside a combined answer: its own source lines go to the common "Zdroje CRZP" line."""
|
||
lines = [l for l in text.split("\n") if not re.match(r"^\s*(?:-\s*)?Zdroj:\s", l)]
|
||
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|
||
|
||
|
||
def explicit_part(question: str, result: dict) -> dict | None:
|
||
"""A whole CRZP answer (CRZP is the main source), with its conversation token for follow-ups."""
|
||
from tools.crzp.answering import context as crzp_context
|
||
if result.get("status") not in ("ok", "ambiguous"):
|
||
return None
|
||
rows = result.pop("_shown", None) or []
|
||
asked = result.pop("_asked", None)
|
||
options = result.pop("_options", None)
|
||
token = None
|
||
if asked is not None:
|
||
issued = crzp_context.issue(question, asked, rows, options)
|
||
token = issued["token"] if issued else None
|
||
entities = result.pop("_entities", None) or []
|
||
return {"mode": "explicit", "status": result["status"], "text": clean_crzp(result["answer"]), "rows": rows,
|
||
"urls": result.get("source_urls", []), "crzp_token": token, "entities": entities,
|
||
"rest": result.pop("_rest", None), "offer": result.pop("_offer", None),
|
||
"intent": getattr(asked, "intent", None), "person": (asked.people[0].name if getattr(asked, "people", None) else None)}
|
||
|
||
|
||
def _kind(row) -> str:
|
||
from tools.crzp.answering.answer import _kind as kind
|
||
return kind(row)
|
||
|
||
|
||
def _names(values) -> str:
|
||
from tools.crzp.source.parse import display_name
|
||
return ", ".join(display_name(v) for v in values) or "neuvedený"
|
||
|
||
|
||
def _work(row) -> str:
|
||
return f"{_kind(row)} {row.get('year') or ''}".strip() + f" „{row['title']}“"
|
||
|
||
|
||
# Keywords that name no technology or method of a work (everything else of the author's keywords counts:
|
||
# "vývoj a testovanie četbotov", "Rasa", "Python").
|
||
METHOD_STOP = {"analyza", "navrh", "system", "systemy", "aplikacia", "implementacia", "model", "modelovanie", "metoda",
|
||
"metody", "data", "udaje", "vyvoj", "softver", "hardver", "riesenie", "praca", "teoria", "prehlad",
|
||
"vyskum", "studia", "experiment", "experimenty", "vysledky", "porovnanie", "testovanie"}
|
||
|
||
|
||
SK_LETTERS = re.compile(r"[áäčďéíĺľňóôŕšťúýž]", re.I)
|
||
|
||
|
||
def one_language(keywords: list[str]) -> list[str]:
|
||
"""CRZP keywords often come twice, in English and in Slovak ("reinforcement learning", "posilňované učenie"):
|
||
with about as many plain lower-case English phrases as Slovak ones, the English ones are left out. Names
|
||
and abbreviations ("PPO", "Gymnasium", "IoT") stay."""
|
||
english = [k for k in keywords if k.isascii() and k == k.lower() and re.search(r"[a-z]{4}", k)]
|
||
slovak = [k for k in keywords if SK_LETTERS.search(k)]
|
||
if len(slovak) >= 2 and len(english) >= 2 and abs(len(english) - len(slovak)) <= 1:
|
||
return [k for k in keywords if k not in english]
|
||
return keywords
|
||
|
||
|
||
def crzp_methods(person: str, row: dict, detail: dict | None) -> str:
|
||
""""Ján Pták vo svojej bakalárskej práci „…“ (2025) využíva: ESP32, MQTT, InfluxDB, Home Assistant." —
|
||
the work's keywords and the tools its abstract names."""
|
||
from tools.answers.evidence.content_selection import named_tools
|
||
record = detail or row
|
||
abstract = record.get("abstract") or ""
|
||
found = []
|
||
for keyword in one_language(record.get("keywords", [])): # the author's own keywords: technologies and methods
|
||
spelled = re.search(r"(?i)(?<!\w)" + re.escape(keyword) + r"(?!\w)", abstract)
|
||
name = (spelled.group(0) if spelled else keyword).strip()
|
||
if name and normalized(name) not in METHOD_STOP:
|
||
found.append(name)
|
||
found += [t.rstrip(".,;:") for t in named_tools(abstract)]
|
||
tools = []
|
||
for name in found:
|
||
key = normalized(name)
|
||
if key and len(key) > 1 and not any(f" {key} " in f" {normalized(t)} " for t in tools):
|
||
tools = [t for t in tools if f" {normalized(t)} " not in f" {key} "]
|
||
tools.append(name)
|
||
where = {"bachelor_thesis": "vo svojej bakalárskej práci", "diploma_thesis": "vo svojej diplomovej práci",
|
||
"dissertation": "vo svojej dizertačnej práci"}.get(row.get("work_type"), "vo svojej práci")
|
||
return f"{person} {where} „{row['title']}“ ({row.get('year')}) využíva: {', '.join(tools)}."
|
||
|
||
|
||
def remember(rows: list[dict]) -> None:
|
||
"""Project the used CRZP works into Neo4j, linked to ZP Wiki people and topics (in the background)."""
|
||
from tools.crzp.storage import graph
|
||
rows = [r for r in rows if r.get("sid")]
|
||
if rows and os.getenv("CRZP_GRAPH_LINKS", "1") != "0":
|
||
_pool().submit(graph.project, rows)
|
||
|
||
|
||
def crzp_part(question: str, person: str | None, *, complete=None, student: bool = True) -> dict | None:
|
||
"""The CRZP contribution: {"mode", "text", "rows", "people", "works"} or None."""
|
||
part = _crzp_part(question, person, complete=complete, student=student)
|
||
if part:
|
||
remember(part.get("rows") or [])
|
||
return part
|
||
|
||
|
||
def _crzp_part(question: str, person: str | None, *, complete=None, student: bool = True) -> dict | None:
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.source.client import CrzpUnavailable
|
||
try:
|
||
_addition.set(False) # (a pool thread keeps its context from the previous question)
|
||
planned = crzp_plan(question, person, complete, student)
|
||
probe = _probe.get()
|
||
if probe is not None: # the waiting answer learns whether CRZP is the main source (see needs_crzp)
|
||
probe["mode"] = planned[0] if planned else None
|
||
if planned is None:
|
||
return None
|
||
mode, query = planned
|
||
low = normalized(question)
|
||
if mode == "similar":
|
||
return crzp_similar(person, complete=complete)
|
||
if mode == "related":
|
||
return related_part(query)
|
||
if mode == "explicit":
|
||
if COMPARE.search(low) and len(query.people) == 2 and not query.topics:
|
||
compared = crzp_comparison(query, complete, collaboration=bool(re.search(r"\bspolupr", low)), low=low)
|
||
if compared is not None:
|
||
return compared
|
||
if (METHODS.search(low) and query.people and query.people[0].role in ("author", "any")
|
||
and not re.search(r"\bstudent\w*", low)):
|
||
# technologies of a person known only to CRZP ("technológie" is no topic); not of a supervisor's students
|
||
methods = crzp_person_methods(question, query, complete)
|
||
if methods is not None:
|
||
return methods
|
||
if person and student and query.intent == "similar" and query.exclude_school == "tuke":
|
||
# "Kto na iných školách písal prácu na podobnú tému ako X?": X's own topics (not a namesake's work found
|
||
# outside TUKE), the works of the other schools
|
||
found = crzp_similar(person, complete=complete)
|
||
keep = [(i, r) for i, r in zip(found["items"], found["rows"]) if crzp.university(r) != TUKE] if found else []
|
||
if keep:
|
||
return {**found, "items": [i for i, _ in keep], "rows": [r for _, r in keep],
|
||
"urls": [r["url"] for _, r in keep if r.get("url")], "home_excluded": True}
|
||
result = crzp._answer_query(question, query, complete)
|
||
part = explicit_part(question, result)
|
||
if part is not None and query.people:
|
||
part["person"] = query.people[0].name # as CRZP writes it (find() set it)
|
||
if query.exclude_school == "tuke": # "na iných školách": the ZP Wiki (TUKE) part is not asked
|
||
if part is None: # nothing found: CRZP's own "not found" answer, not the wiki's
|
||
part = {"mode": "explicit", "status": "ok", "rows": [], "urls": [], "crzp_token": None,
|
||
"entities": [], "text": clean_crzp(result.get("answer") or "V CRZP sa taká práca nenašla.")}
|
||
# (unless the question also asks about a wiki person: "študenti Hládka … a podobné práce inde")
|
||
addition = _addition.get()
|
||
part["home_excluded"], part["addition"] = not addition, addition
|
||
return part
|
||
found, rows = crzp.find(query)
|
||
if not rows:
|
||
return None
|
||
if mode == "topic":
|
||
rows, _ = crzp.topical(relevant(question, query, rows)[:24], query, complete)
|
||
rows = rows[:12]
|
||
if not rows:
|
||
return None # nothing in CRZP is really about the topic: no filler works
|
||
return {"mode": mode, "items": [crzp_item(r) for r in rows], "rows": rows, "text": "",
|
||
"urls": [r["url"] for r in rows if r.get("url")]}
|
||
rows = crzp.ranked(question, query, rows)
|
||
# person: that person's works at TUKE
|
||
rows = [r for r in rows if crzp.university(r) == TUKE]
|
||
if not rows:
|
||
return None
|
||
if not student or query.people and query.people[0].role == "supervisor":
|
||
# a supervisor (also a doctoral student asked about his students): the works he or she led, newest first
|
||
if query.topics: # "… a týkali sa generovania jazyka": only works whose topic it is
|
||
rows, _ = crzp.topical(rows, query, complete, limit=crzp.PERSON_JUDGED)
|
||
if not rows:
|
||
return None
|
||
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
|
||
lines = [f"- {_names(r.get('authors', []))} — „{r['title']}“ ({_kind(r)}, {r.get('year')})" for r in rows[:8]]
|
||
more = f"\n\nSpolu {len(rows)} prác v CRZP na TUKE; zobrazených je 8 najnovších." if len(rows) > 8 else ""
|
||
return {"mode": mode, "text": supervisor_header(person, query, rows) + "\n\n"
|
||
+ "\n".join(lines) + more, "rows": rows[:8], "urls": [r["url"] for r in rows[:8] if r.get("url")]}
|
||
lines, details = [], {}
|
||
for row in rows[:3]:
|
||
if ABOUT.search(low) or METHODS.search(low):
|
||
details[row.get("sid")] = crzp.fetch.detail(row["sid"]) if row.get("sid") else None
|
||
detail = details.get(row.get("sid"))
|
||
if METHODS.search(low):
|
||
lines.append(crzp_methods(person, row, detail))
|
||
elif ABOUT.search(low) and detail:
|
||
label, text = crzp.summary(detail, complete)
|
||
lines.append(f"**{row['title']}** ({_kind(row)}, {row.get('year')})\n\n{text}")
|
||
else:
|
||
authored = crzp.people_in_role(row, person, "author")
|
||
lines.append(f"- {_work(row)} — "
|
||
+ ("" if authored else f"autor {_names(row.get('authors', []))}; ")
|
||
+ f"vedúci {_names(row.get('supervisors', []))}; "
|
||
f"oponent {_names(row.get('opponents', []))}"
|
||
+ ("" if not authored or same_person_work(person, row) else
|
||
" (v ZP Wiki k tejto práci záznam nie je; môže ísť o menovca)"))
|
||
return {"mode": mode, "text": "\n\n".join(lines), "rows": rows[:3],
|
||
"urls": [r["url"] for r in rows[:3] if r.get("url")],
|
||
"works": [{"source": "crzp", "label": _work(r), "type": r.get("work_type"), "key": crzp.work_key(r)}
|
||
for r in rows[:3]]}
|
||
except CrzpUnavailable:
|
||
probe = _probe.get()
|
||
if probe is not None:
|
||
probe["failed"] = True # not "nothing found": CRZP did not answer
|
||
return None
|
||
|
||
|
||
def crzp_similar(person: str, *, complete=None) -> dict | None:
|
||
"""CRZP works sharing the person's specific tools/topics (searched in CRZP by them)."""
|
||
from tools.crzp import fetch
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.source.parse import fold
|
||
terms = wiki_terms(person)
|
||
if not terms:
|
||
return None
|
||
scored: dict = {}
|
||
for term in terms:
|
||
for row in fetch.search(term)["rows"]:
|
||
if any(fold(person.split()[-1]) in fold(a) for a in row.get("authors", [])):
|
||
continue
|
||
text = fold(row["title"] + " " + " ".join(row.get("keywords", [])))
|
||
shared = [t for t in terms if fold(t) in text]
|
||
if shared:
|
||
key = crzp.work_key(row)
|
||
scored[key] = (row, sorted(set(shared) | set(scored.get(key, (None, []))[1])))
|
||
if not scored:
|
||
return None
|
||
candidates = list(scored.values())
|
||
from tools.retrieval import rerank
|
||
profile = wiki_profile(person)
|
||
order = rerank.scores(profile, [r["title"] + ". " + ", ".join(r.get("keywords", [])) for r, _ in candidates]) \
|
||
or [0] * len(candidates)
|
||
# Closest by content first; more shared topics/tools break ties.
|
||
best = [c for _, c in sorted(zip(order, candidates), key=lambda i: (-i[0], -len(i[1][1])))][:12]
|
||
return {"mode": "similar", "items": [crzp_item(r, shared) for r, shared in best], "text": "",
|
||
"rows": [r for r, _ in best], "urls": [r["url"] for r, _ in best if r.get("url")]}
|
||
|
||
|
||
_tag_cache: dict = {}
|
||
_tag_lock = threading.Lock()
|
||
|
||
|
||
def tag_frequencies() -> tuple[dict, int]:
|
||
"""In how many cached CRZP works each tag (its reviewed base name) occurs, and of how many works:
|
||
a tag most works carry ("umelá inteligencia", "python") names no specific related topic."""
|
||
from collections import Counter
|
||
from tools.crzp.fetch import store
|
||
stamp = int(time.time() // 1800) # recounted at most every half hour
|
||
with _tag_lock:
|
||
if _tag_cache.get("stamp") == stamp:
|
||
return _tag_cache["df"], _tag_cache["total"]
|
||
from tools.retrieval.synonyms import base_name
|
||
counts, seen = Counter(), set()
|
||
for row in store().cached_rows():
|
||
key = (row.get("title"), row.get("year"))
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
counts.update({normalized(base_name(k.strip())) for k in row.get("keywords", []) if k.strip()})
|
||
with _tag_lock:
|
||
_tag_cache.update(stamp=stamp, df=dict(counts), total=max(1, len(seen)))
|
||
return _tag_cache["df"], _tag_cache["total"]
|
||
|
||
|
||
def wiki_people_for(topic: str) -> list[str]:
|
||
"""ZP Wiki students whose own records (topic, assignment, progress, results) name the topic."""
|
||
from tools.retrieval.synonyms import variants_pattern
|
||
pattern = variants_pattern(topic)
|
||
people = {}
|
||
for unit in (_index() or {}).get("units", []):
|
||
if unit.get("kind") in {"reference", "meeting", "supervisor", "consultant", "lifecycle"}:
|
||
continue
|
||
if pattern.search(normalized(unit.get("text", ""))) or any(
|
||
pattern.fullmatch(normalized(c)) for c in unit.get("concepts", []) if isinstance(c, str)):
|
||
people.setdefault(unit["person"], unit.get("source_url"))
|
||
return list(people)
|
||
|
||
|
||
def related_part(query) -> dict | None:
|
||
"""Topics related to the asked one: the CRZP keywords of works about it, weighted by how specific
|
||
they are, each with the ZP Wiki students and CRZP works that have it."""
|
||
import math
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.retrieval.synonyms import base_name, group_of, variants_pattern
|
||
found, rows = crzp.find(query)
|
||
if not rows:
|
||
return None
|
||
asked = [t for t in [*query.topics, *query.phrases] if t]
|
||
patterns = [variants_pattern(t) for t in asked]
|
||
asked_words = {w for t in asked for x in group_of(t) for w in normalized(x).split()}
|
||
generic = {normalized(g) for g in crzp.GENERIC_TAGS} | {"umela inteligencia", "strojove ucenie", "python"}
|
||
df, total = tag_frequencies()
|
||
stats: dict = {}
|
||
for row in rows:
|
||
for keyword in {base_name(k.strip()) for k in row.get("keywords", []) if k.strip()}:
|
||
key = normalized(keyword)
|
||
if (len(key) < 3 or key in generic or set(key.split()) <= asked_words
|
||
or any(p.fullmatch(key) for p in patterns)):
|
||
continue # the asked topic itself, a synonym, a part of it or a generic word
|
||
entry = stats.setdefault(key, {"label": keyword, "rows": []})
|
||
if keyword[:1].isupper() and not entry["label"][:1].isupper():
|
||
entry["label"] = keyword
|
||
entry["rows"].append(row)
|
||
ranked = sorted((e for e in stats.values() if len(e["rows"]) >= 2),
|
||
key=lambda e: -len(e["rows"]) * math.log(total / (1 + df.get(normalized(e["label"]), 0))))
|
||
# The same topic in two languages ("Konverzačný marketing" / "Conversational marketing") is one
|
||
# topic: CRZP works carry bilingual keywords, so both tag (nearly) the same works.
|
||
from difflib import SequenceMatcher
|
||
merged = []
|
||
for entry in ranked:
|
||
works = {crzp.work_key(r) for r in entry["rows"]}
|
||
key = normalized(entry["label"])
|
||
twin = next((m for m in merged if len(works & m["works"]) >= 0.8 * max(len(works), len(m["works"]))
|
||
and SequenceMatcher(None, key, normalized(m["label"])).ratio() >= 0.6), None)
|
||
if twin is None:
|
||
merged.append({**entry, "works": works})
|
||
ranked = merged[:18]
|
||
if not ranked:
|
||
return None
|
||
items = []
|
||
for entry in ranked:
|
||
label = entry["label"][:1].upper() + entry["label"][1:]
|
||
example = max(entry["rows"], key=lambda r: r.get("year") or 0)
|
||
authors = example.get("authors") or []
|
||
from tools.crzp.source.parse import display_name
|
||
wiki = wiki_people_for(entry["label"])
|
||
from tools.answers.presentation.unified import catalog as wiki_catalog, join
|
||
text = (f"{crzp.plural(len(entry['rows']))}, napr. „{example['title']}“ "
|
||
f"({display_name(authors[0]) if authors else 'autor neuvedený'}, {crzp.university(example)}, "
|
||
f"{example.get('year') or 'rok neuvedený'})")
|
||
if wiki:
|
||
text += "; venujú sa mu aj " + join(wiki[:4]) + (f" a ďalší ({len(wiki) - 4})" if len(wiki) > 4 else "")
|
||
people = wiki_catalog()["people"]
|
||
urls = [example["url"]] if example.get("url") else []
|
||
urls += [(people.get(name) or {}).get("url") for name in wiki[:4]]
|
||
items.append({"name": label, "source": "topic", "text": text, "urls": [u for u in urls if u]})
|
||
topic = base_name(asked[0]) if asked else ""
|
||
return {"mode": "related", "items": items, "topic": topic, "rows": [e["rows"][0] for e in ranked], "text": "",
|
||
"urls": [i["urls"][0] for i in items if i["urls"]]}
|
||
|
||
|
||
def crzp_item(row: dict, shared: list[str] | None = None) -> dict:
|
||
"""One CRZP work as an item of a combined list."""
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.source.parse import display_name
|
||
authors = row.get("authors") or []
|
||
name = display_name(authors[0]) if authors else "autor neuvedený"
|
||
school = crzp.university(row)
|
||
line = f"{school}: „{row['title']}“ ({_kind(row)}, {row.get('year') or 'rok neuvedený'})"
|
||
if shared:
|
||
line += "; spoločné: " + ", ".join(shared)
|
||
return {"name": name, "school": school, "source": "crzp", "text": line, "year": row.get("year"),
|
||
"urls": [row["url"]] if row.get("url") else [],
|
||
"sid": row.get("sid"), "title": row["title"]}
|
||
|
||
|
||
def relevant(question: str, query, rows: list[dict]) -> list[dict]:
|
||
"""CRZP works really about the asked topic, most relevant first: the topic (or a reviewed
|
||
synonym, in any case form) in the title or the CRZP keywords, or a cross-encoder score
|
||
above CRZP_TOPIC_MIN_SCORE. A work found only through its abstract ("Fairy Tale
|
||
Intertexts" for "anotácie") is no answer to a topic question."""
|
||
from tools.retrieval import rerank
|
||
from tools.retrieval.synonyms import variants_pattern
|
||
if not rows:
|
||
return []
|
||
terms = [t for t in [*query.topics, *query.phrases] if t]
|
||
patterns = [variants_pattern(t) for t in terms]
|
||
texts = [r["title"] + ". " + ", ".join(r.get("keywords", [])) for r in rows]
|
||
asked = " ".join([question, *[t for t in [*query.topics, *query.alternatives] if normalized(t) not in normalized(question)]])
|
||
scores = rerank.scores(asked, texts)
|
||
if scores is not None: # the cross-encoder scores at most MAX_PAIRS texts; the rest only by name
|
||
scores = list(scores) + [float("-inf")] * (len(texts) - len(scores))
|
||
from tools.crzp.answering.relevance import acronym, mentions
|
||
kept = []
|
||
for i, (row, text) in enumerate(zip(rows, texts)):
|
||
keywords = ", ".join(row.get("keywords", [])) # authors' tags: any letter case ("rag")
|
||
named = any(mentions(row["title"], t) or p.search(normalized(keywords)) if acronym(t) else p.search(normalized(text))
|
||
for t, p in zip(terms, patterns))
|
||
score = scores[i] if scores is not None else (1.0 if named else -1.0)
|
||
if named or score >= TOPIC_MIN_SCORE:
|
||
kept.append((score + (1.0 if named else 0.0), i, row))
|
||
return [row for _, _, row in sorted(kept, key=lambda k: (-k[0], k[1]))]
|
||
|
||
|
||
# ------------------------------------------------------------------ items of a list answer
|
||
|
||
HEADING = re.compile(r"^\*\*([^*\n]+?)\*\*\s*$")
|
||
PERSON_NAME = re.compile(r"[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][\w'’.-]+(?:\s+[A-ZÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ][\w'’.-]+){1,3}")
|
||
# Blocks after the people of a wiki list (they belong to the whole list).
|
||
TAIL = re.compile(r"^(?:Téma je len v zadaní|Len štúdium alebo poznámky|Tému majú len|Podklady k porovnávanej osobe)")
|
||
SOURCE_LINE = re.compile(r"^Zdroj(?:e)?(?: CRZP)?:\s*(.+)$", re.M)
|
||
|
||
|
||
def split_sources(text: str) -> tuple[str, list[str]]:
|
||
"""The answer without its source lines, and their links."""
|
||
urls = []
|
||
for match in SOURCE_LINE.finditer(text or ""):
|
||
urls += re.findall(r"https?://[^\s,)\]]+", match.group(1))
|
||
body = SOURCE_LINE.sub("", text or "")
|
||
return re.sub(r"\n{3,}", "\n\n", body).strip(), list(dict.fromkeys(urls))
|
||
|
||
|
||
def _slug(name: str) -> str:
|
||
return "_".join(normalized(name).split())
|
||
|
||
|
||
def wiki_items(body: str, urls: list[str]) -> tuple[list[str], list[dict], list[str], list[str]]:
|
||
"""(head blocks, one item per person, tail blocks, links not tied to a person) of a wiki answer."""
|
||
blocks = [b.strip() for b in re.split(r"\n\s*\n", body) if b.strip()]
|
||
head, items, tail = [], [], []
|
||
current = None
|
||
for block in blocks:
|
||
first = block.split("\n", 1)[0]
|
||
heading = HEADING.match(first)
|
||
name = re.split(r"\s+—\s+", heading.group(1))[0].strip() if heading else ""
|
||
if tail or TAIL.match(block):
|
||
tail.append(block)
|
||
elif heading and PERSON_NAME.fullmatch(name) and not name.endswith(":"):
|
||
same = next((i for i in items if i["name"] == name), None)
|
||
if same is not None:
|
||
current = same
|
||
current["blocks"].append(block) # the same person's next work (also when listed apart)
|
||
else:
|
||
current = {"name": name, "school": WIKI_SCHOOL, "source": "wiki", "blocks": [block]}
|
||
items.append(current)
|
||
elif current is None:
|
||
head.append(block)
|
||
else:
|
||
current["blocks"].append(block)
|
||
general = []
|
||
for url in urls:
|
||
owner = next((i for i in items if _slug(i["name"]) in url), None)
|
||
if owner is not None:
|
||
owner.setdefault("urls", []).append(url)
|
||
else:
|
||
general.append(url)
|
||
for item in items:
|
||
item["text"] = "\n\n".join(item.pop("blocks"))
|
||
item.setdefault("urls", [])
|
||
return head, items, tail, general
|
||
|
||
|
||
def render_item(number: int, item: dict, mixed: bool) -> str:
|
||
if item["source"] in ("topic", "crzp", "line"):
|
||
return f"**{number}. {item['name']}** — {item['text']}"
|
||
first, _, rest = item["text"].partition("\n")
|
||
heading = HEADING.match(first)
|
||
title = heading.group(1) if heading else item["name"]
|
||
return f"**{number}. {title}**" + ("\n" + rest if rest else "")
|
||
|
||
|
||
def bare_name(question: str, person: str) -> bool:
|
||
"""The question is only the person's name ("Ján Holp", "Matej Scislak?")."""
|
||
words = re.findall(r"[a-z0-9]+", normalized(question))
|
||
return bool(words) and 2 <= len(words) <= 3 and set(words) <= set(re.findall(r"[a-z0-9]+", normalized(person)))
|
||
|
||
|
||
def supervisor_header(person: str, query, rows: list[dict]) -> str:
|
||
""""Bakalárske práce, ktoré viedol Daniel Hládek v rokoch 2024–2025:" — the name as the register writes it
|
||
(with diacritics), the role, type and years the question asked."""
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.source.parse import display_name
|
||
from tools.answers.presentation.unified import female
|
||
role = query.people[0].role if query.people and query.people[0].role in ("supervisor", "opponent") else "supervisor"
|
||
spelled = next((display_name(n) for r in rows for n in r.get(crzp.ROLE_FIELD[role], [])
|
||
if crzp.name_matches(person, n)), person)
|
||
verb = crzp.VERBS[role][1 if female(spelled) else 0]
|
||
kinds = [crzp.WORK_TYPE_PLURAL.get(crzp.WORK_TYPE_LABELS.get(t, ""), "") for t in query.work_types]
|
||
lead = (kinds[0].capitalize() + " práce") if len(kinds) == 1 and kinds[0] else "Práce"
|
||
years = sorted(set(query.years))
|
||
when = (f" v roku {years[0]}" if len(years) == 1 else f" v rokoch {years[0]}–{years[-1]}") if years else ""
|
||
topic = f" na tému „{query.topic_key()}“" if query.topics else ""
|
||
return f"{lead}{topic}, ktoré {verb} {spelled}{when}:"
|
||
|
||
|
||
def merge_people(wiki: list[dict], crzp_items: list[dict]) -> list[dict]:
|
||
"""A CRZP work of a person already in the ZP Wiki list joins that person's item (no person twice)."""
|
||
by_name = {normalized(item["name"]): item for item in wiki}
|
||
rest = []
|
||
for item in crzp_items:
|
||
owner = by_name.get(normalized(item["name"]))
|
||
if owner is not None and item.get("school") == TUKE:
|
||
work = item["text"].split(": ", 1)[-1] # "„Názov“ (bakalárska práca, 2026)" -> "Bakalárska práca 2026: „Názov“"
|
||
shaped = re.match(r"^(„[^“]+“)\s*\(([^,()]+),\s*(\d{4})\)\s*$", work)
|
||
owner["text"] += (f"\n- {shaped.group(2)[:1].upper()}{shaped.group(2)[1:]} {shaped.group(3)}: {shaped.group(1)}"
|
||
if shaped else f"\n- Záverečná práca: {work}")
|
||
owner.setdefault("urls", []).extend(item.get("urls", []))
|
||
else:
|
||
rest.append(item)
|
||
return rest
|
||
|
||
|
||
def newest_first(items: list[dict]) -> list[dict]:
|
||
"""People of a list from the one with the newest work or record (stable for equal dates)."""
|
||
from tools.answers.presentation.unified import recency
|
||
return sorted(items, key=lambda i: recency(i["name"]) if i.get("source") == "wiki" else str(i.get("year") or ""),
|
||
reverse=True)
|
||
|
||
|
||
def first_page(wiki: list[dict], crzp_items: list[dict]) -> tuple[list[dict], list[dict]]:
|
||
"""(shown, rest): ZP Wiki people first (at most WIKI_FIRST when CRZP has works too), CRZP fills the page;
|
||
each group from the newest work."""
|
||
wiki = newest_first(wiki)
|
||
crzp_items = newest_first(merge_people(wiki, crzp_items))
|
||
take_wiki = min(len(wiki), WIKI_FIRST if crzp_items else PAGE)
|
||
take_crzp = min(len(crzp_items), PAGE - take_wiki)
|
||
take_wiki = min(len(wiki), PAGE - take_crzp)
|
||
shown = wiki[:take_wiki] + crzp_items[:take_crzp]
|
||
return shown, wiki[take_wiki:] + crzp_items[take_crzp:]
|
||
|
||
|
||
def more_line(rest: list[dict]) -> str:
|
||
if all(i["source"] == "topic" for i in rest):
|
||
word = "ďalšia téma" if len(rest) == 1 else "ďalšie témy" if len(rest) < 5 else "ďalších tém"
|
||
return f"Našl{'a' if len(rest) == 1 else 'i' if len(rest) < 5 else 'o'} sa ešte {len(rest)} {word}. Chceš vidieť ďalšie?"
|
||
word = "ďalšia osoba" if len(rest) == 1 else "ďalšie osoby" if len(rest) < 5 else "ďalších osôb"
|
||
return f"Našl{'a' if len(rest) == 1 else 'i' if len(rest) < 5 else 'o'} sa ešte {len(rest)} {word}. Chceš vidieť ďalšie?"
|
||
|
||
|
||
def compose_list(head: list[str], shown: list[dict], rest: list[dict], tail: list[str], general_urls: list[str],
|
||
*, start: int = 1, mixed: bool) -> tuple[str, list[str], str | None]:
|
||
"""(text, sources, id of the stored rest)."""
|
||
blocks = list(head) + [render_item(start + i, item, mixed) for i, item in enumerate(shown)] + list(tail)
|
||
urls = list(dict.fromkeys([*general_urls, *[u for item in shown for u in item.get("urls", [])]]))
|
||
if urls:
|
||
blocks.append("Zdroje: " + ", ".join(urls))
|
||
from tools.answers import pages
|
||
page_id = pages.put(rest, {"mixed": mixed}) if rest else None
|
||
if rest and page_id:
|
||
blocks.append(more_line(rest))
|
||
return "\n\n".join(blocks), urls, page_id
|
||
|
||
|
||
def entity(item: dict, number: int) -> dict:
|
||
years = [int(y) for y in re.findall(r"\b(?:19|20)\d{2}\b", item.get("text") or "")
|
||
if int(y) <= time.localtime().tm_year + 3] # the newest work year the item shows
|
||
return {k: v for k, v in {"n": number, "name": item["name"], "school": item.get("school"),
|
||
"source": item.get("source"), "sid": item.get("sid"), "title": item.get("title"),
|
||
"url": (item.get("urls") or [None])[0] or item.get("url"),
|
||
"year": max(years) if years else None}.items()
|
||
if v is not None}
|
||
|
||
|
||
def entity_url(entity: dict) -> str | None:
|
||
"""The source of a listed person: the wiki profile or the CRZP work it was listed with."""
|
||
if entity.get("url"):
|
||
return entity["url"]
|
||
if entity.get("sid"):
|
||
from tools.crzp.source.client import PERMALINK
|
||
return PERMALINK.format(sid=entity["sid"])
|
||
return None
|
||
|
||
|
||
# ------------------------------------------------------------------ composition
|
||
|
||
def _ok(question, engine, text, urls, base) -> dict:
|
||
keep = {k: v for k, v in base.items() if k not in ("answer", "status", "reason", "delivery_check",
|
||
"source_urls", "conversation_context")}
|
||
return {**keep, "status": "ok", "reason": None, "accepted_for_delivery": True, "answer": text,
|
||
"source_urls": list(dict.fromkeys(urls)), "claims": base.get("claims", []),
|
||
"index_version": base.get("index_version"), "complete": base.get("complete", True),
|
||
"truncated": base.get("truncated", False), "truncation_reasons": base.get("truncation_reasons", []),
|
||
"delivery_check": {"layer": "delivery", "code": "complete", "request_fingerprint": fingerprint(question, engine)}}
|
||
|
||
|
||
def _with_token(result: dict, *, wiki_context=None, entities=(), options=(), question="", crzp=None,
|
||
primary="wiki", page=None) -> dict:
|
||
wiki_context = wiki_context or {}
|
||
token = seal({"wiki": wiki_context.get("token"), "entities": list(entities)[:40], "options": list(options)[:6],
|
||
"question": question, "crzp": crzp, "primary": primary, "page": page,
|
||
"urls": list(result.get("source_urls") or [])[:30], "person": _subject.get()})
|
||
if token:
|
||
result["conversation_context"] = {**{k: v for k, v in wiki_context.items() if k != "token"},
|
||
"token": token, "work_options": wiki_context.get("work_options", []),
|
||
"meeting_options": wiki_context.get("meeting_options", [])}
|
||
return result
|
||
|
||
|
||
NEXT_PAGE = re.compile(r"\b(?:dalsi\w*|dalej|viac|ostatn\w*|zvysn\w*|pokracuj\w*|zvysok|vsetk\w*)\b")
|
||
# Words of a paging reply ("áno, ukáž ďalších", "pokračuj"): a message with any other word is a new question
|
||
# ("a čo robil ďalej?", "povedz viac o jeho práci").
|
||
PAGER_WORDS = {"a", "ano", "aj", "jasne", "ok", "okej", "hej", "chcem", "daj", "ukaz", "zobraz", "vypis", "prosim",
|
||
"urcite", "samozrejme", "mi", "ich", "ho", "este", "dalsich", "dalsie", "dalsi", "dalej", "viac", "ostatnych",
|
||
"ostatne", "zvysnych", "zvysne", "zvysok", "pokracuj", "pokracovat", "vidiet", "chcel", "chcela", "by", "som",
|
||
"tych", "ty", "tie", "osoby", "ludi", "studentov", "temy", "prace", "polozky", "stranu", "dalsiu", "zoznam",
|
||
"vsetky", "vsetko", "vsetkych", "technologie", "technologii", "nastroje", "metody", "aj"}
|
||
# A question starting like a new one is never a choice reply ("Kto robil RAG?" while a work choice is pending).
|
||
NEW_QUESTION = re.compile(r"^\W*(?:kto|co|ako|kedy|kde|ktor\w*|kolk\w*|ak[eyaou]\w*|preco|najdi|porovnaj|vypis|ukaz)\b")
|
||
YES = re.compile(r"^\W*(?:ano|jasne|ok|okej|hej|chcem|daj|ukaz|prosim|urcite|samozrejme)(?:\s+(?:ano|prosim|daj|ukaz|ich|mi|ho|aj))*\W*$")
|
||
ORDINAL_WORDS = {"prv": 1, "druh": 2, "tret": 3, "stvrt": 4, "piat": 5, "siest": 6, "siedm": 7, "osm": 8, "deviat": 9,
|
||
"desiat": 10}
|
||
REFERENCE = re.compile(
|
||
r"(?i)\b(?:(?:t[eé]n|t[aá]|t[uú]|toho|tej|tomu|tom|tou)\s+)?"
|
||
r"(prv|druh|tret|štvrt|stvrt|piat|šiest|siest|siedm|ôsm|osm|deviat|desiat|posledn)\w*"
|
||
r"(?:\s+(?:z\s+nich|zo\s+zoznamu|v\s+poradí|v\s+poradi|študent\w*|student\w*|osob\w*|človek\w*|clovek\w*))"
|
||
r"|\b(?:číslo|cislo|č\.)\s*(\d{1,2})\b")
|
||
|
||
|
||
def _reference(question: str, entities: list[dict]) -> tuple[re.Match, dict] | None:
|
||
""""prvý z nich", "toho tretieho študenta", "číslo 2" -> the shown person it points at."""
|
||
match = REFERENCE.search(question)
|
||
if not match or not entities:
|
||
return None
|
||
if match.group(2):
|
||
number = int(match.group(2))
|
||
else:
|
||
word = normalized(match.group(1))
|
||
number = len(entities) if word.startswith("posledn") else next(
|
||
(n for stem, n in ORDINAL_WORDS.items() if word.startswith(stem)), None)
|
||
chosen = next((e for e in entities if e.get("n") == number), None)
|
||
return (match, chosen) if chosen else None
|
||
|
||
|
||
# "vráť sa k otázke o blockchaine", "späť k Hládkovi", "pri tej predošlej otázke o RAG": an older step.
|
||
BACK = re.compile(r"\b(?:vrat\w*\s+sa|vratme\s+sa|spat|naspat)\s+(?:k|ku|na)\b"
|
||
r"|\b(?:k|ku|pri)\s+(?:(?:tej|tu)\s+)?(?:predosl|predchadzajuc|minul|skorsej|starsej|povodn)\w*\s+otazk\w*"
|
||
r"|\b(?:k|ku|pri)\s+(?:tej|tu)\s+otazk\w*|\b(?:k|ku|pri)\s+otazke\s+o\b")
|
||
PREVIOUS_ONE = re.compile(r"\b(?:predosl|predchadzajuc|minul)\w*")
|
||
BACK_WORDS = {"vrat", "vratme", "vratit", "sa", "spat", "naspat", "k", "ku", "na", "pri", "tej", "tu", "tom", "o", "a",
|
||
"aj", "este", "raz", "znova", "prosim", "otazke", "otazku", "otazky", "otazka", "predoslej", "predchadzajucej",
|
||
"minulej", "skorsej", "starsej", "povodnej", "prvej", "druhej", "tomu", "ktora", "bola", "ktoru", "som", "sme",
|
||
"dal", "dala", "dali", "pytal", "pytala", "kde", "tam"}
|
||
MAX_BACK = 6 # older steps "a čo robil druhý z nich?" may point to (the newest one with such people wins)
|
||
|
||
|
||
def _stems(text: str) -> set[str]:
|
||
return {w[:max(4, len(w) - 2)] for w in re.findall(r"[a-z0-9]+", normalized(text))
|
||
if len(w) >= 3 and w not in BACK_WORDS}
|
||
|
||
|
||
def _split_return(message: str) -> tuple[str, str]:
|
||
""""Vráť sa k otázke o blockchaine, z akých škôl boli?" -> (the return, the question asked there)."""
|
||
parts = re.split(r"\s*[,;:–—]\s*", message.strip(), maxsplit=1)
|
||
at = next((i for i, part in enumerate(parts) if BACK.search(normalized(part))), 0)
|
||
rest = " ".join(part for i, part in enumerate(parts) if i != at).strip()
|
||
return parts[at], rest if re.search(r"[^\W\d_]{2}", rest) else ""
|
||
|
||
|
||
def _keep_context(result: dict, previous: dict) -> dict:
|
||
"""A clarification that leaves the conversation where it was."""
|
||
return _with_token(result, wiki_context={"token": previous.get("wiki")}, entities=previous.get("entities") or [],
|
||
question=previous.get("question", ""), crzp=previous.get("crzp"),
|
||
primary=previous.get("primary", "wiki"), page=previous.get("page"))
|
||
|
||
|
||
def _back_reference(question: str, previous: dict, *, engine: str, limit: int, complete, deliver) -> dict | None:
|
||
"""A message returning to an older question of the conversation: the step whose question shares
|
||
the most words with the return part (the newest one of equal ones); two different questions
|
||
matching equally are offered as a choice."""
|
||
from tools.answers import context_store
|
||
reference, _ = _split_return(question)
|
||
wanted = _stems(reference)
|
||
if not wanted: # "vráť sa k predošlej otázke": the question before the latest one
|
||
if not PREVIOUS_ONE.search(normalized(reference)):
|
||
return None
|
||
older = context_store.chain(previous["_step"], limit=2)
|
||
if len(older) < 2:
|
||
return None
|
||
return _return_to(question, older[1]["id"], engine=engine, limit=limit, complete=complete, deliver=deliver)
|
||
match = lambda a, b: a.startswith(b) or b.startswith(a)
|
||
scored = []
|
||
for position, step in enumerate(context_store.chain(previous["_step"])):
|
||
payload = step["payload"]
|
||
known = _stems(payload.get("question") or "") | {s for e in payload.get("entities") or [] for s in _stems(e.get("name", ""))}
|
||
score = sum(any(match(w, k) for k in known) for w in wanted)
|
||
if score:
|
||
scored.append((score, position, step))
|
||
if not scored:
|
||
text = "V tejto konverzácii som nenašiel otázku, ku ktorej sa chceš vrátiť. Napíš ju prosím celú."
|
||
result = _ok(question, engine, text, [], {})
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _keep_context(result, previous)
|
||
best = max(score for score, _, _ in scored)
|
||
distinct = {}
|
||
for score, position, step in sorted(scored, key=lambda item: item[1]): # newest first
|
||
asked = normalized(step["payload"].get("question") or "")
|
||
if score == best and asked not in distinct:
|
||
distinct[asked] = step
|
||
if len(distinct) == 1:
|
||
return _return_to(question, next(iter(distinct.values()))["id"], engine=engine, limit=limit,
|
||
complete=complete, deliver=deliver)
|
||
options = [{"source": "step", "step": step["id"], "label": f"„{step['payload'].get('question')}“"}
|
||
for step in list(distinct.values())[:4]]
|
||
text = ("Ku ktorej otázke sa chceš vrátiť?\n\n" + "\n".join(f"{i}. {o['label']}" for i, o in enumerate(options, 1))
|
||
+ "\n\nOdpovedz číslom.")
|
||
result = _ok(question, engine, text, [], {})
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, options=options, question=question, entities=previous.get("entities") or [])
|
||
|
||
|
||
def _return_to(message: str, step: str, *, engine: str, limit: int, complete, deliver) -> dict:
|
||
"""The message answered in the context of an older step; a bare return ("vráť sa k otázke o
|
||
blockchaine") asks that older question again, in the context it was asked in."""
|
||
from tools.answers import context_store
|
||
_, rest = _split_return(message)
|
||
if rest:
|
||
result = _answer(rest, engine=engine, limit=limit, context_token=step_token(step), complete=complete,
|
||
deliver=deliver)
|
||
return {**result, "_asked_as": [rest, *result.pop("_asked_as", [])]}
|
||
steps = context_store.chain(step, limit=2)
|
||
asked = steps[0]["payload"].get("question") if steps else None
|
||
if not asked:
|
||
from tools.answers.presentation.answer_errors import public_failure
|
||
failure = public_failure({"reason": "expired_context", "engine": engine})
|
||
failure["delivery_check"] = {"layer": "context", "code": "unavailable",
|
||
"request_fingerprint": fingerprint(message, engine)}
|
||
return failure
|
||
parent = steps[1]["id"] if len(steps) > 1 else None
|
||
result = _answer(asked, engine=engine, limit=limit, context_token=step_token(parent), complete=complete,
|
||
deliver=deliver)
|
||
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
||
|
||
|
||
# A remark about the previous answer starts no search ("to nie je ono", "málo zdrojov" of a wiki answer).
|
||
REMARK = re.compile(r"^\W*(?:no\s+|ale\s+)?(?:to\s+)?(?:nie\s+je\s+(?:to\s+)?(?:ono|pravda|spravne|dobre)|nesedi|je\s+to\s+zle|"
|
||
r"to\s+je\s+zle|zle|nespravne|nie\s+to|hm+|nerozumiem|divne|blbost|nezmysel|to\s+nedava\s+zmysel|"
|
||
r"nieco\s+je\s+zle|chyba)\W*$")
|
||
NEGATIVE = re.compile(r"^\W*(?:nie|netreba|nechcem|nie\s+dakujem|nie\s+treba|staci|to\s+staci|ok\s+staci|dobre\s+staci)\W*$")
|
||
THANKS = re.compile(r"^\W*(?:dakujem|dakujeme|vdaka|diky)(?:\s+(?:velmi|pekne|moc|krasne))?\W*$")
|
||
NOTED = re.compile(r"^\W*(?:super|ok|okej|dobre|jasne|perfektne|vyborne|rozumiem|aha)\W*$") # no question, no search
|
||
CRZP_AGAIN = re.compile(r"\b(?:hladaj|pohladaj|vyhladaj|pozri|skus|skontroluj|over|najdi)\w*\s+(?:to\s+|aj\s+|este\s+|mi\s+)*"
|
||
r"(?:v|na|do|cez|z)\s+(?:crzp|registr\w*|centraln\w*)|^\W*(?:a\s+)?(?:v|na|z)\s+crzp\W*$")
|
||
|
||
|
||
def _note(question: str, engine: str, text: str, previous: dict | None, clarify: bool = False) -> dict:
|
||
result = _ok(question, engine, text, [], {})
|
||
if clarify:
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _keep_context(result, previous) if previous else result
|
||
|
||
|
||
def _remark(question: str, low: str, words: list[str], previous: dict | None, *, engine, limit, complete, deliver):
|
||
"""A message about the previous answer, not a new question: a remark or "nie" (no search), "hľadaj
|
||
v CRZP" (the previous question answered from CRZP), "málo zdrojov" after a wiki answer (its sources)."""
|
||
from tools.crzp.answering.context import SOURCES
|
||
if NEGATIVE.match(low) or THANKS.match(low) or NOTED.match(low):
|
||
return _note(question, engine, "Rado sa stalo." if THANKS.match(low) else "Dobre.", previous)
|
||
if REMARK.match(low):
|
||
return _note(question, engine, "Upresni prosím, čo mám hľadať alebo čo v odpovedi nesedí: osobu, tému, rok, "
|
||
"školu alebo typ práce.", previous, clarify=True)
|
||
if CRZP_AGAIN.search(low) and len(words) <= 8:
|
||
asked = (previous or {}).get("question")
|
||
if not asked:
|
||
return _note(question, engine, "Napíš, čo mám hľadať v CRZP: osobu, tému alebo názov práce.", previous,
|
||
clarify=True)
|
||
if not EXPLICIT.search(normalized(asked)):
|
||
asked = asked.rstrip(" ?.!") + " v CRZP?"
|
||
from tools.answers import context_store
|
||
steps = context_store.chain(previous.get("_step"), limit=2) if previous.get("_step") else []
|
||
parent = step_token(steps[1]["id"]) if len(steps) > 1 else None # the context that question was asked in
|
||
result = _answer(asked, engine=engine, limit=limit, context_token=parent, complete=complete, deliver=deliver)
|
||
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
||
if SOURCES.search(low) and not (previous and previous.get("primary") == "crzp" and previous.get("crzp")):
|
||
urls = (previous or {}).get("urls") or []
|
||
if not urls:
|
||
return _note(question, engine, "Predchádzajúca odpoveď nemá ďalšie zdroje. Polož otázku na konkrétnu osobu, "
|
||
"tému alebo prácu.", previous)
|
||
result = _ok(question, engine, "Predchádzajúca odpoveď vychádza z týchto zdrojov:\n\n"
|
||
+ "\n".join(f"- {u}" for u in urls), urls, {})
|
||
return _keep_context(result, previous)
|
||
return None
|
||
|
||
|
||
def _with_people(question: str, low: str, previous: dict) -> dict:
|
||
"""The latest step, unless the message points at listed people ("druhý z nich", "a z akých škôl
|
||
sú?") the latest answer has not listed: then the newest of the last MAX_BACK steps that has them."""
|
||
from tools.crzp.answering.wiki_bridge import wiki_person
|
||
entities = previous.get("entities") or []
|
||
words = re.findall(r"[a-z0-9]+", low)
|
||
schools = bool(SCHOOLS.search(low) and not THESIS.search(low) and len(words) <= 8 and not wiki_person(question))
|
||
if not (REFERENCE.search(question) or schools) or _reference(question, entities) or schools and entities:
|
||
return previous
|
||
from tools.answers import context_store
|
||
for step in context_store.chain(previous["_step"], limit=MAX_BACK + 1)[1:]:
|
||
older = step["payload"].get("entities") or []
|
||
if older and (schools or _reference(question, older)):
|
||
return {**step["payload"], "_step": step["id"]}
|
||
return previous
|
||
|
||
|
||
def _stamp(result: dict, question: str, engine: str) -> dict:
|
||
"""An answer prepared for a question this layer rewrote ("prvý z nich" -> the name, "2" -> the
|
||
pending question about the chosen work) is bound to the message the user sent. Any other
|
||
fingerprint stays as it is, so the client still rejects an answer that belongs elsewhere."""
|
||
internal = result.pop("_asked_as", None) or []
|
||
result.pop("_plan", None) # internal summary of the wiki plan
|
||
check = result.get("delivery_check")
|
||
if isinstance(check, dict) and check.get("request_fingerprint") in {fingerprint(q, engine) for q in internal}:
|
||
result["delivery_check"] = {**check, "request_fingerprint": fingerprint(question, engine)}
|
||
return result
|
||
|
||
|
||
_warmed = threading.Event()
|
||
|
||
|
||
def answer(question: str, *, engine: str, limit: int = 5, context_token: str | None = None, complete=None,
|
||
deliver=None) -> dict:
|
||
"""deliver: the ZP Wiki answer function (the API passes its own, tests replace it)."""
|
||
question = question.strip()
|
||
if enabled() and not _warmed.is_set(): # tag rarity for related topics, counted once in the background
|
||
_warmed.set()
|
||
_pool().submit(tag_frequencies)
|
||
parent = _parent.set(token_step(context_token)) # every step of this answer continues the sent one
|
||
previous = unseal(context_token) if context_token else None
|
||
subject = _subject.set((previous or {}).get("person") if isinstance(previous, dict) else None)
|
||
try:
|
||
result = _stamp(_answer(question, engine=engine, limit=limit, context_token=context_token, complete=complete,
|
||
deliver=deliver), question, engine)
|
||
full = _subject_retry(question, result, previous)
|
||
if full: # "a čo zásobník úloh?" -> "Uveď celé meno…" although the conversation is about one person
|
||
retried = _answer(full, engine=engine, limit=limit, context_token=context_token, complete=complete,
|
||
deliver=deliver)
|
||
retried["_asked_as"] = [full, *(retried.get("_asked_as") or [])] # bound to the sent question
|
||
retried = _stamp(retried, question, engine)
|
||
if retried.get("status") == "ok":
|
||
result = retried
|
||
return _carry_context(result, question, context_token, previous)
|
||
finally:
|
||
_subject.reset(subject)
|
||
_parent.reset(parent)
|
||
|
||
|
||
def _subject_retry(question: str, result: dict, previous: dict | None) -> str | None:
|
||
"""The question once more with the conversation's person when the answer asks who is meant: a short follow-up
|
||
without a pronoun or a verb ("a čo zásobník úloh?") after an answer about one person."""
|
||
person = previous.get("person") if isinstance(previous, dict) else None
|
||
if result.get("reason") != "missing_subject" or not person or previous.get("options") or _one_person(question):
|
||
return None
|
||
from tools.answers.presentation.unified import TYPES, asked_types, genitive
|
||
base = re.sub(r"\s*\?*\s*$", "", question)
|
||
kinds = [k for k in asked_types(normalized(previous.get("question") or "")) if k in TYPES]
|
||
if len(kinds) == 1 and not asked_types(normalized(question)):
|
||
# "… oponentom jeho diplomovky? => a kto bol vedúcim?": the work of the step before
|
||
return f"{base} {TYPES[kinds[0]][1]} {genitive(person)}?"
|
||
return base + " " + genitive(person) + "?"
|
||
|
||
|
||
LOST = {"missing_subject", "answer_rejected", "backend_timeout", "backend_unavailable", "model_unavailable",
|
||
"crzp_unavailable", "no_content_evidence", "missing_evidence"}
|
||
|
||
|
||
def _carry_context(result: dict, question: str, context_token: str | None, previous: dict | None) -> dict:
|
||
"""A step that answered nothing ("Uveď celé meno…", a rejected or failed answer) does not replace the context:
|
||
the next follow-up continues from the last step that did ("a kto ho viedol?" still knows the person). A plain
|
||
wiki token (a wiki clarification) is kept inside a step of ours, so the person stays with it."""
|
||
context = result.get("conversation_context") or {}
|
||
token = context.get("token")
|
||
failed = result.get("status") in ("error", "no_answer") or result.get("reason") in LOST
|
||
if failed and previous and not previous.get("error") and isinstance(context_token, str) \
|
||
and context_token.startswith(PREFIX3):
|
||
return {**result, "conversation_context": {**context, "token": context_token}}
|
||
if isinstance(token, str) and token and not token.startswith(PREFIX3) and result.get("status") in ("ok", "ambiguous"):
|
||
check = result.get("delivery_check")
|
||
wrapped = _with_token({k: v for k, v in result.items() if k != "conversation_context"},
|
||
wiki_context=context, question=question)
|
||
return {**wrapped, "delivery_check": check} if check else wrapped
|
||
return result
|
||
|
||
|
||
def _ask_choice(question: str, engine: str, previous: dict) -> dict:
|
||
options = previous["options"]
|
||
text = ("Odpovedz prosím číslom: " + ", ".join(f"{i} – {o['label']}" for i, o in enumerate(options, 1)) + ".")
|
||
result = _ok(question, engine, text, [], {})
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, options=options, question=previous["question"])
|
||
|
||
|
||
def _next_page(question: str, engine: str, previous: dict) -> dict:
|
||
from tools.answers import pages
|
||
stored = pages.get(previous.get("page"))
|
||
entities = previous.get("entities") or []
|
||
if not stored:
|
||
return _ok(question, engine, "Ďalšie položky predchádzajúcej odpovede už nie sú k dispozícii; zopakuj otázku.",
|
||
[], {})
|
||
items, mixed = stored["items"], stored["meta"].get("mixed", False)
|
||
if stored["meta"].get("kind") == "lines": # the rest of a ranking ("- Gabriel Bugár (TUKE) – 6"), page by page
|
||
shown, rest = items[:PAGE * 2], items[PAGE * 2:]
|
||
urls = list(dict.fromkeys(u for item in shown for u in item.get("urls") or []))
|
||
text = "\n".join(f"- {item['name']}" for item in shown) + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||
page_id = None
|
||
if rest:
|
||
from tools.answers import pages
|
||
page_id = pages.put(rest, {"kind": "lines"})
|
||
if page_id:
|
||
text += f"\n\nChceš vidieť ďalších ({len(rest)})?"
|
||
return _with_token(_ok(question, engine, text, urls, {}), entities=entities, question=question, page=page_id,
|
||
crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||
if stored["meta"].get("kind") == "tools": # the rest of a list of technologies: all of it, once
|
||
text = stored["meta"]["lead"] + ", ".join(i["name"] for i in items) + "."
|
||
return _with_token(_ok(question, engine, text, [], {}), entities=entities, question=question,
|
||
crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||
start = max((e.get("n", 0) for e in entities), default=0) + 1
|
||
text, urls, page_id = compose_list([], items[:PAGE], items[PAGE:], [], [], start=start, mixed=mixed)
|
||
shown = entities + [entity(item, start + i) for i, item in enumerate(items[:PAGE])]
|
||
return _with_token(_ok(question, engine, text, urls, {}), entities=shown, question=question, page=page_id,
|
||
crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||
|
||
|
||
def _schools_answer(question: str, engine: str, previous: dict) -> dict:
|
||
entities = previous["entities"]
|
||
lines = [f"{e.get('n', i)}. {e['name']} — {e.get('school') or 'škola neuvedená'}"
|
||
for i, e in enumerate(entities, 1)]
|
||
urls = list(dict.fromkeys(u for u in (entity_url(e) for e in entities) if u))
|
||
text = "Školy ľudí z predchádzajúcej odpovede:\n\n" + "\n".join(lines) + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||
return _with_token(_ok(question, engine, text, urls, {}), entities=entities, question=question,
|
||
page=previous.get("page"), crzp=previous.get("crzp"), primary=previous.get("primary", "wiki"))
|
||
|
||
|
||
def _crzp_work_answer(question: str, engine: str, chosen: dict, complete=None) -> dict:
|
||
"""A follow-up about a CRZP work of the previous list ("o čom je práca tretieho z nich?")."""
|
||
from tools.crzp.answering import answer as crzp
|
||
from tools.crzp.answering.understand import Person, understand
|
||
query = understand(question, complete=complete)
|
||
query.people = [Person(name=chosen["name"], role="author", typed=chosen["name"], canonical=True)]
|
||
query.sids, query.title, query.topics, query.alternatives = [chosen["sid"]], None, [], []
|
||
query.school = query.unit = None
|
||
query.from_model = True
|
||
if query.intent in ("list", "similar", "schools"):
|
||
query.intent = "about"
|
||
result = crzp._answer_query(question, query, complete)
|
||
for key in ("_shown", "_asked", "_options", "_entities"):
|
||
result.pop(key, None)
|
||
if result.get("accepted_for_delivery") is not True:
|
||
return result
|
||
from tools.answers.presentation.unified import strip_sources
|
||
body, urls = split_sources(strip_sources(clean_crzp(result["answer"])))
|
||
urls = list(dict.fromkeys([*urls, *(result.get("source_urls") or [])]))
|
||
text = body + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||
return {**result, "answer": text, "source_urls": urls,
|
||
"delivery_check": {**result["delivery_check"], "request_fingerprint": fingerprint(question, engine)}}
|
||
|
||
|
||
def _answer(question: str, *, engine: str, limit: int, context_token: str | None, complete, deliver) -> dict:
|
||
from tools.answers.answer_delivery import deliver_answer as default_deliver
|
||
deliver_answer = deliver or default_deliver
|
||
from tools.crzp.answering.wiki_bridge import wiki_match, wiki_person
|
||
previous = unseal(context_token)
|
||
if previous and previous.get("error"):
|
||
from tools.answers.presentation.answer_errors import public_failure
|
||
failure = public_failure({"reason": previous["error"], "engine": engine})
|
||
failure["delivery_check"] = {"layer": "context", "code": "unavailable",
|
||
"request_fingerprint": fingerprint(question, engine)}
|
||
return failure
|
||
wiki_token = previous.get("wiki") if previous else context_token
|
||
low = normalized(question)
|
||
words = re.findall(r"[a-z0-9]+", low)
|
||
named = _one_person(question) if words else None
|
||
if named:
|
||
_subject.set(named["name"])
|
||
newest = _newest_of(question, low, previous, engine)
|
||
if newest is not None: # "a ktorý z nich je najnovší?": chosen from the people just listed
|
||
return newest
|
||
from tools.answers.presentation import unified as U
|
||
joined = None if (previous or {}).get("options") else (
|
||
U.set_join(question, (named or {}).get("name")) or U.wiki_student_role(question)
|
||
or (U.defended_years(named["name"], question) if (named or {}).get("name") else None))
|
||
if joined: # "Ktorí študenti s tagom rag obhájili bakalársku prácu … a kto im robil oponenta?": the wiki set and
|
||
# the register's theses of its people, every condition of the question kept
|
||
text = joined["text"] + ("\n\nZdroje: " + ", ".join(joined["urls"]) if joined["urls"] else "")
|
||
return _with_token(_ok(question, engine, text, joined["urls"], {}), question=question)
|
||
supervisor = None if named else U.supervisor_in(question)
|
||
if supervisor and (U.WHO_Q.match(low) or bare_name(question, supervisor)):
|
||
# "Kto je Daniel Hládek?": a supervisor (no profile of his own), not a CRZP author or "unknown person"
|
||
_subject.set(supervisor)
|
||
out = U.supervisor_overview(supervisor)
|
||
text = out["text"] + ("\n\nZdroje: " + ", ".join(out["urls"]) if out["urls"] else "")
|
||
return _with_token(_ok(question, engine, text, out["urls"], {}), question=question)
|
||
if CONTACT.search(low) and (named or supervisor): # "Aký je e-mail Daniela Hládka?": not in the records
|
||
who = U.spelled((named or {}).get("name") or supervisor)
|
||
return _with_token(_ok(question, engine, f"Kontaktné údaje osoby {who} v podkladoch nie sú; ZP Wiki a "
|
||
"register záverečných prác uvádzajú len údaje o prácach.", [], {}), question=question)
|
||
if not named and not supervisor and not (previous or {}).get("options"):
|
||
# tags, categories, the most common topics and the start of studies come from the wiki's own metadata:
|
||
# complete, counted by code, and never sent to CRZP (CRZP has no ZP Wiki tags)
|
||
meta = (U.tag_answer(question) if U.TAG_Q.search(low) and not RELATED.search(low) else None) or (
|
||
U.top_topics() if U.TOP_TOPICS_Q.search(low) else None) or (
|
||
U.started_answer(question) if U.STARTED_Q.search(low) and not TOPIC_CUE.search(low) else None)
|
||
if meta:
|
||
text = meta["text"] + ("\n\nZdroje: " + ", ".join(meta["urls"]) if meta["urls"] else "")
|
||
return _with_token(_ok(question, engine, text, meta["urls"], {}), question=question)
|
||
back = _back_to_person(question)
|
||
if back: # "vráť sa k Vasiľovi, kedy začal študovať?"
|
||
return {**_answer(back, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver),
|
||
"_asked_as": [back]}
|
||
explained = EXPLAIN.match(question)
|
||
if explained: # "Prečo si myslíš, že X robil Y? Odkiaľ to vieš?": the claim checked again, with its records
|
||
claim = explained.group(1).strip()
|
||
asked = (re.sub(r"^(?:[A-ZÁČĎÉÍĽĹŇÓÔŔŠŤÚÝŽ][\w-]+\s+){1,3}", "Kto ", claim)
|
||
if re.search(r"\bnajviac\b", claim) else claim) + "?"
|
||
result = _answer(asked, engine=engine, limit=limit, context_token=context_token, complete=complete,
|
||
deliver=deliver)
|
||
inner = result.pop("_asked_as", [])
|
||
student = _one_person(claim)
|
||
if (student and result.get("status") == "ok"
|
||
and not any("zp.kemt" in url for url in result.get("source_urls") or [])):
|
||
# a ZP Wiki student's claim whose wiki records were not confirmed: other records are no evidence for it
|
||
text = f"Tvrdenie „{claim.rstrip('.')}“ sa v záznamoch ZP Wiki nepodarilo overiť, preto ho nepotvrdzujem."
|
||
return {**_with_token(_ok(question, engine, text, [], result), question=question), "_asked_as": [asked, *inner]}
|
||
if result.get("accepted_for_delivery") is True and result.get("status") == "ok" and result.get("source_urls"):
|
||
result = {**result, "answer": "Vychádzam zo záznamov v podkladoch, ktoré sú uvedené v zdrojoch:\n\n"
|
||
+ result["answer"]}
|
||
return {**result, "_asked_as": [asked, *inner]}
|
||
future = _future_defences(question, low)
|
||
if future: # "Koľko prác obhájia v roku 2030?": no record can hold it yet
|
||
return _with_token(_ok(question, engine, future, [], {}), question=question)
|
||
wants_more = bool(YES.match(low) or NEXT_PAGE.search(low) and words and all(w in PAGER_WORDS for w in words))
|
||
if previous and previous.get("page") and wants_more: # "áno" to "Chceš vidieť ďalšie/zvyšné?" comes first
|
||
return _next_page(question, engine, previous)
|
||
if previous and previous.get("options"): # "Ktorú prácu myslíš?" was asked
|
||
# "kto bol oponentom tej bakalárky?" is a new question, not the choice "bakalárku"
|
||
own_question = bool(NEW_QUESTION.match(low) and len(words) > 2 and not re.fullmatch(r"\W*\d+\W*", low))
|
||
chosen = None if own_question else _choice(low, previous["options"])
|
||
if chosen is not None and chosen.get("source") == "step": # "Ktorú otázku myslíš?" (a return to an older one)
|
||
return _return_to(previous["question"], chosen["step"], engine=engine, limit=limit, complete=complete,
|
||
deliver=deliver)
|
||
if chosen is not None:
|
||
result = _answer_choice(previous["question"], chosen, engine=engine, limit=limit, complete=complete,
|
||
deliver=deliver_answer)
|
||
result["_asked_as"] = [previous["question"], *result.pop("_asked_as", [])]
|
||
if result.get("accepted_for_delivery") is True and result.get("status") == "ok":
|
||
# the offer stays: "a tú druhú?" / "1" after "2" answers the same question for the other work;
|
||
# the answer's own context (wiki token, shown people, the rest of a list) stays with it
|
||
context = result.get("conversation_context") or {}
|
||
inner = unseal(context.get("token")) or {}
|
||
if inner.get("error"):
|
||
inner = {}
|
||
wiki_context = {**context, "token": inner.get("wiki")} if inner else context
|
||
result = _with_token(result, wiki_context=wiki_context, options=previous["options"],
|
||
question=previous["question"], entities=inner.get("entities") or [],
|
||
page=inner.get("page"), crzp=inner.get("crzp"), primary=inner.get("primary", "wiki"))
|
||
return result
|
||
if len(low.split()) <= 3 and not wiki_person(question) and not NEW_QUESTION.match(low):
|
||
return _ask_choice(question, engine, previous)
|
||
if previous and previous.get("entities") and wants_more: # nothing more was offered
|
||
return _with_token(_ok(question, engine, "Všetko nájdené už je v predchádzajúcej odpovedi.", [], {}),
|
||
entities=previous["entities"], question=question, crzp=previous.get("crzp"),
|
||
primary=previous.get("primary", "wiki"))
|
||
handled = _remark(question, low, words, previous, engine=engine, limit=limit, complete=complete, deliver=deliver)
|
||
if handled is not None:
|
||
return handled
|
||
if previous and previous.get("_step") and BACK.search(low): # "vráť sa k otázke o blockchaine, …"
|
||
returned = _back_reference(question, previous, engine=engine, limit=limit, complete=complete, deliver=deliver)
|
||
if returned is not None:
|
||
return returned
|
||
if previous and previous.get("_step"): # "a čo robil druhý z nich?" about the people of an older answer
|
||
previous = _with_people(question, low, previous)
|
||
entities = (previous or {}).get("entities") or []
|
||
# "a z akých škôl sú?" asks about the people shown; "Ktoré školy majú práce o RAG?" is a new question.
|
||
if entities and SCHOOLS.search(low) and not wiki_person(question) and not THESIS.search(low) and len(words) <= 8:
|
||
return _schools_answer(question, engine, previous)
|
||
asked = question
|
||
full = ellipsis(question, previous) or again(question, previous) or named_back(question, previous)
|
||
if full: # "a Ján Pták?": the previous question about this person; "ale čo robil?": that question again
|
||
return {**_answer(full, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver),
|
||
"_asked_as": [full]}
|
||
full = with_subject(question, previous)
|
||
if full: # "kto je jeho konzultant?" -> "kto je konzultant Samuela Vasiľa?" (the wiki context stays)
|
||
return {**_answer(full, engine=engine, limit=limit, context_token=context_token, complete=complete,
|
||
deliver=deliver), "_asked_as": [full]}
|
||
reference = _reference(question, entities) if entities else None
|
||
if reference:
|
||
match, chosen = reference
|
||
if chosen.get("source") == "crzp" and chosen.get("sid"):
|
||
return _crzp_work_answer(question, engine, chosen, complete)
|
||
if chosen.get("source") == "crzp" and chosen.get("role") in ("supervisor", "opponent"):
|
||
# a supervisor of a CRZP ranking ("a čo robil druhý z nich?"): the works he or she led, from CRZP
|
||
verb = "oponoval" if chosen["role"] == "opponent" else "viedol"
|
||
asked = f"Aké práce {verb} {chosen['name']} v CRZP?"
|
||
return {**_answer(asked, engine=engine, limit=limit, context_token=None, complete=complete,
|
||
deliver=deliver), "_asked_as": [asked]}
|
||
question = (question[:match.start()] + chosen["name"] + question[match.end():]).strip()
|
||
low, wiki_token, previous = normalized(question), None, None # a question about that person now
|
||
return {**_answer(question, engine=engine, limit=limit, context_token=None, complete=complete,
|
||
deliver=deliver), "_asked_as": [question]}
|
||
match = wiki_match(question)
|
||
from tools.crzp.answering.context import CONTINUES, FOLLOW
|
||
from tools.crzp.source.parse import fold
|
||
continues = bool(CONTINUES.search(fold(question)) or FOLLOW.search(fold(question))) or len(words) <= 4
|
||
if previous and previous.get("primary") == "crzp" and previous.get("crzp") and not match and continues:
|
||
# The last answer came from CRZP ("O čom je práca Jána Nováka?" -> "2", "a kto bol oponent?",
|
||
# "aké napr.", "rozdeľ to podľa rokov", "málo zdrojov").
|
||
from tools.crzp.answering import answer as crzp
|
||
methods = _crzp_follow_up_methods(question, low, previous, engine, complete)
|
||
if methods is not None:
|
||
return methods
|
||
followed = crzp._answer(question, complete, context_token=previous["crzp"])
|
||
followed.pop("_shown", None), followed.pop("_asked", None), followed.pop("_options", None)
|
||
shown = followed.pop("_entities", None) or []
|
||
rest, offer = followed.pop("_rest", None), followed.pop("_offer", None)
|
||
if followed.get("accepted_for_delivery") is True:
|
||
from tools.answers.presentation.unified import strip_sources
|
||
body, urls = split_sources(strip_sources(clean_crzp(followed["answer"])))
|
||
urls = list(dict.fromkeys([*urls, *(followed.get("source_urls") or [])]))[:MAX_SOURCES]
|
||
text = body + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||
page = None
|
||
if rest:
|
||
from tools.answers import pages
|
||
page = pages.put(rest, {"kind": "lines"})
|
||
text += "\n\n" + (offer or "Chceš vidieť ďalšie?") if page else ""
|
||
result = {**followed, "answer": text, "source_urls": urls,
|
||
"delivery_check": {**followed["delivery_check"], "request_fingerprint": fingerprint(question, engine)}}
|
||
token = (followed.get("conversation_context") or {}).get("token")
|
||
result.pop("conversation_context", None)
|
||
entities = [{**e, "n": i} for i, e in enumerate(shown, 1)] or previous.get("entities", [])
|
||
return _with_token(result, entities=entities, question=question, crzp=token or previous["crzp"],
|
||
primary="crzp", page=page)
|
||
person, student = (match["name"], match["student"]) if match else (None, True)
|
||
started = time.monotonic()
|
||
pool = _pool()
|
||
from tools.answers import timing
|
||
|
||
def timed(name, function, *args, **kwargs):
|
||
began = time.monotonic()
|
||
try:
|
||
return function(*args, **kwargs)
|
||
finally:
|
||
timing.step(name, time.monotonic() - began)
|
||
|
||
home = home_only(question) if enabled() else question # the other schools are CRZP's part of the question
|
||
wiki_future = pool.submit(contextvars.copy_context().run, timed, "wiki", deliver_answer, home, engine=engine,
|
||
limit=limit,
|
||
**({"context_token": wiki_token} if wiki_token else {}))
|
||
crzp_future, probe = _crzp_future(pool, timed, question, person, complete, student) if enabled() else (None, {})
|
||
wiki = wiki_future.result()
|
||
if wiki_token and wiki.get("reason") in ("stale_context", "expired_context"):
|
||
# the wiki's own context of an older step is too old (24 hours) or the wiki data changed: the
|
||
# question goes to the wiki without it (people, works and the CRZP question of the step stay)
|
||
wiki = deliver_answer(home, engine=engine, limit=limit)
|
||
part = None
|
||
if crzp_future is not None:
|
||
try:
|
||
part = crzp_future.result(timeout=max(1.0, CRZP_SECONDS - (time.monotonic() - started)))
|
||
except FutureTimeout: # CRZP is slow: only an answer that needs CRZP waits longer
|
||
if needs_crzp(wiki, probe, person):
|
||
try:
|
||
part = crzp_future.result(timeout=max(0.0, CRZP_WAIT_SECONDS - (time.monotonic() - started)))
|
||
except FutureTimeout:
|
||
timing.note("crzp_pending", True) # the search goes on and is cached for the repeated question
|
||
return _crzp_pending(question, engine, wiki)
|
||
except Exception:
|
||
part = None
|
||
except Exception:
|
||
part = None
|
||
if (part is None and crzp_future is not None and crzp_future.done() and crzp_future.exception() is None
|
||
and probe.get("mode") == "explicit" and not probe.get("failed")):
|
||
wiki = searched_both(wiki) # CRZP was searched for the person too and has nothing
|
||
result = compose(asked, question, engine, wiki, part, person)
|
||
return {**result, "_asked_as": [home, *result.pop("_asked_as", [])]} if home != question else result
|
||
|
||
|
||
# "… aj na iných školách", "a sú podobné práce aj na iných školách", "a koľko podobných prác je na iných školách
|
||
# podľa CRZP": ZP Wiki (KEMT) is not asked about other schools (its audit would rightly find that part missing)
|
||
OTHER_SCHOOLS_CLAUSE = re.compile(
|
||
r",?\s*(?:(?:a|aj)\s+)?(?:(?:su|je|bolo|boli|existuju)\s+)?(?:kolko\s+(?:je\s+)?)?(?:podobn\w+\s+(?:prac\w*|tem\w*)\s+)?"
|
||
r"(?:(?:je|su)\s+)?aj\s+(?:na|v|vo|z|zo)\s+(?:inych|ostatnych|dalsich)\s+(?:vysok\w+\s+)?(?:skol|univerzit|fakult)\w*"
|
||
r"(?:\s+podla\s+crzp)?"
|
||
r"|,?\s*a\s+kolko\s+podobn\w+\s+prac\s+(?:je\s+)?na\s+(?:inych|ostatnych|dalsich)\s+(?:skol|univerzit)\w*(?:\s+podla\s+crzp)?")
|
||
|
||
|
||
def home_only(question: str) -> str:
|
||
"""The question for ZP Wiki without its other-schools clause ("Kto pracoval s GraphRAG na KEMT aj na iných
|
||
školách?" -> "Kto pracoval s GraphRAG na KEMT?"); the question itself when it has none or is only about them."""
|
||
import unicodedata
|
||
low = "".join(next((c for c in unicodedata.normalize("NFKD", ch) if not unicodedata.combining(c)), ch)
|
||
for ch in question.lower()) # one character per character: the spans fit the question
|
||
match = OTHER_SCHOOLS_CLAUSE.search(low)
|
||
if not match or len(low) != len(question):
|
||
return question
|
||
rest = (question[:match.start()] + question[match.end():]).strip()
|
||
rest = re.sub(r"\s+([?.!,])", r"\1", re.sub(r"\s{2,}", " ", rest))
|
||
return rest if len(re.findall(r"\w+", rest)) >= 3 else question
|
||
|
||
|
||
def _crzp_future(pool, timed, question, person, complete, student):
|
||
"""The CRZP part of this question, or the one still running for the same question (a question
|
||
repeated after "Hľadanie … ešte prebieha" waits for that search instead of starting it again)."""
|
||
key = (normalized(question), person, student, id(complete), crzp_part)
|
||
with _inflight_lock:
|
||
running = _inflight.get(key)
|
||
if running is not None and not running[0].done():
|
||
return running
|
||
probe: dict = {}
|
||
|
||
def run():
|
||
_probe.set(probe)
|
||
return crzp_part(question, person, complete=complete, student=student)
|
||
future = pool.submit(contextvars.copy_context().run, timed, "crzp", run)
|
||
_inflight[key] = (future, probe)
|
||
future.add_done_callback(lambda done: _forget(key, done))
|
||
return future, probe
|
||
|
||
|
||
def _forget(key, future) -> None:
|
||
with _inflight_lock:
|
||
if _inflight.get(key, (None,))[0] is future:
|
||
del _inflight[key]
|
||
|
||
|
||
def needs_crzp(wiki: dict, probe: dict, person: str | None) -> bool:
|
||
"""Whether the answer waits for a slow CRZP: CRZP is the main source of this question
|
||
(crzp_plan mode "explicit") or ZP Wiki has nothing to give (no answer, an error)."""
|
||
mode = probe.get("mode", "unplanned") # "unplanned": CRZP is still reading the question
|
||
if mode is None or wiki.get("reason") in REFUSED:
|
||
return False # CRZP adds nothing to this question, or it is out of scope
|
||
if wiki.get("status") == "ambiguous": # the wiki asks first, unless CRZP answers the question as a whole
|
||
return person is None and mode in ("explicit", "unplanned") and wiki.get("reason") in (
|
||
*WIKI_CLARIFICATION_YIELDS, "incomplete_person_name") # "samuel furda": CRZP may know the whole name
|
||
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
||
return mode == "explicit" or not wiki_ok
|
||
|
||
|
||
def _crzp_pending(question: str, engine: str, wiki: dict) -> dict:
|
||
"""CRZP did not finish in time: say so (never "nenašiel"); the repeated question gets the result."""
|
||
result = _ok(question, engine, CRZP_PENDING, [], {"index_version": wiki.get("index_version")})
|
||
result.update(status="no_answer", reason="crzp_pending", complete=False,
|
||
delivery_check={"layer": "retrieval", "code": "unavailable",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, wiki_context=wiki.get("conversation_context"), question=question)
|
||
|
||
|
||
def searched_both(wiki: dict) -> dict:
|
||
""""Osobu X som v ZP Wiki nenašiel" when CRZP was searched for X as well and has no work of X."""
|
||
text = wiki.get("answer")
|
||
if wiki.get("reason") != "unknown_person" or not isinstance(text, str):
|
||
return wiki
|
||
return {**wiki, "answer": text.replace("som v ZP Wiki nenašiel",
|
||
"som nenašiel v ZP Wiki ani v registri záverečných prác")}
|
||
|
||
|
||
def compose(asked: str, question: str, engine: str, wiki: dict, part: dict | None, person: str | None) -> dict:
|
||
"""One answer from the ZP Wiki result and the CRZP part (without naming the sources in the text)."""
|
||
from tools.answers.presentation.unified import strip_sources
|
||
result = _compose(asked, question, engine, wiki, part, person)
|
||
if result.get("accepted_for_delivery") is True and isinstance(result.get("answer"), str):
|
||
result["answer"] = strip_sources(result["answer"])
|
||
return result
|
||
|
||
|
||
def _unified(asked, question, engine, wiki, wiki_ok, part, person, wiki_context, plan) -> dict | None:
|
||
"""The answer of a question about one person, a supervisor's students or two people, built from the
|
||
records of both sources (tools/answers/presentation/unified.py); None leaves the general composition."""
|
||
from tools.answers.presentation import unified as U
|
||
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and person is None:
|
||
return None
|
||
low = normalized(question)
|
||
rows = (part or {}).get("rows") or []
|
||
wiki_text = wiki.get("answer") if wiki_ok and isinstance(wiki.get("answer"), str) else ""
|
||
base = wiki if wiki_ok else {"index_version": wiki.get("index_version")}
|
||
|
||
def done(out, **token):
|
||
text = out["text"] + ("\n\nZdroje: " + ", ".join(out["urls"]) if out.get("urls") else "")
|
||
if out.get("rest"): # "Chceš vidieť aj zvyšné?": the rest is kept like the next page of a list
|
||
from tools.answers import pages
|
||
page = pages.put([{"name": t, "source": "tool", "text": ""} for t in out["rest"]],
|
||
{"kind": "tools", "lead": out["rest_lead"]})
|
||
if page:
|
||
text += "\n\n" + out["offer"]
|
||
token["page"] = page
|
||
return _with_token(_ok(question, engine, text, out.get("urls") or [], base), wiki_context=wiki_context,
|
||
question=question, **token)
|
||
if person is None and wiki.get("resolved_query"): # "a aké úlohy dostal?": the person of the resolved question
|
||
found = _one_person(wiki["resolved_query"])
|
||
person = found["name"] if found else None
|
||
students = U.catalog()["people"]
|
||
student = bool(person and (students.get(person) or {}).get("person_kind") in ("student", "intern"))
|
||
# A supervisor: how many students, and who (newest work first, each student once).
|
||
if wiki_ok and COUNT_STUDENTS.search(low): # also a supervisor who has a student profile of their own
|
||
count = re.search(r"počet študentov[^:]*:\s*(\d+)", wiki_text)
|
||
names = re.search(r"Študenti:\s*(.+?)\.\s*$", wiki_text, re.M)
|
||
who = person or (re.match(r"^(.+?) — počet", wiki_text) or [None, None])[1]
|
||
if count and names and who:
|
||
listed = [U.spelled(n.strip()) for n in names.group(1).split(",")]
|
||
return done({"text": f"{U.spelled(who)} vedie {U.plural_students(int(count.group(1)))}: {U.join(listed)}.",
|
||
"urls": wiki.get("source_urls") or []})
|
||
if U.ROSTER_Q.search(low) and (wiki_ok or rows):
|
||
who = person or ""
|
||
body, urls = split_sources(wiki_text)
|
||
head, items, tail, general = wiki_items(body, urls or wiki.get("source_urls") or [])
|
||
roster = U.roster_items(who, items, rows) if who else []
|
||
if roster:
|
||
shown, rest = roster[:PAGE], roster[PAGE:]
|
||
heading = [f"{U.spelled(who)} vedie tieto práce (od najnovších):"]
|
||
text, shown_urls, page_id = compose_list(heading, shown, rest, [], [], mixed=False)
|
||
return _with_token(_ok(question, engine, text, shown_urls, base), wiki_context=wiki_context,
|
||
question=question, page=page_id,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)])
|
||
# "Kto by mohol spolupracovať s X?", "Nájdi práce podobné práci X": the candidates, newest work first
|
||
if student and wiki_ok and (plan.get("intent") == "similar" or SIMILAR.search(low)) and not COMPARE_TWO(low) \
|
||
and not (part or {}).get("home_excluded"): # "na iných školách": the register's works, not the wiki's
|
||
body, urls = split_sources(wiki_text)
|
||
head, items, tail, general = wiki_items(body, urls or wiki.get("source_urls") or [])
|
||
if items:
|
||
candidates = U.similar_items(newest_first(items))
|
||
crzp_items = [i for i in (part or {}).get("items") or [] if i.get("source") == "crzp"]
|
||
anchor = U.anchor_sentence(person)
|
||
heading = [(anchor + " " if anchor else "") + "Podobnej téme sa venujú (od najnovších prác):"]
|
||
shown, rest = first_page(candidates, crzp_items)
|
||
text, shown_urls, page_id = compose_list(heading, shown, rest, [], [*general, *(U.work_urls(person, []))],
|
||
mixed=True)
|
||
return _with_token(_ok(question, engine, text, shown_urls, base), wiki_context=wiki_context,
|
||
question=question, page=page_id,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)])
|
||
if student:
|
||
works = U.person_works(person, rows)
|
||
out = None
|
||
if (students.get(person) or {}).get("person_kind") == "intern" and not works and (
|
||
U.WHO_Q.match(low) or U.DID_Q.match(low) or bare_name(question, person)):
|
||
out = U.intern_overview(person) # "Na čom pracoval stážista Dries Huybens?": topic, goals, outputs
|
||
if out:
|
||
return done(out)
|
||
supervising = re.search(r"\b(?:viedol|viedla|vedie|oponoval\w*|skolil\w*)\b", low)
|
||
card = None if (COMPARE.search(low) or SAME_SUPERVISOR.search(low) or SAME_OPPONENT.search(low) or METHODS.search(low)
|
||
or STUDY_START.search(low) or STUDENTS_OF.search(low) or SIMILAR.search(low)) \
|
||
else U.work_card(person, works, low, wiki_text)
|
||
if card: # "názov, vedúci, oponent a rok obhajoby": every asked fact, not the first rule's one
|
||
return done(card)
|
||
premise = U.school_premise(person, works, question)
|
||
if premise: # "Prečo X obhájil diplomovú prácu na Žilinskej univerzite?": the register's school instead
|
||
return done(premise)
|
||
if STUDY_START.search(low) and not re.search(r"\b(?:prac\w*|projekt\w*|nazov|tem\w*|veduc\w*)\b", low):
|
||
out = U.start_year(person) # only the start of studies; a compound question stays with the wiki answer
|
||
if out is None: # "Kedy začal študovať Maroš Harahus?": not recorded, said so (no other data instead)
|
||
out = {"text": f"Rok začiatku štúdia osoby {U.spelled(person)} v podkladoch nie je uvedený.",
|
||
"urls": U.work_urls(person, [])}
|
||
elif U.COUNT_WORKS_Q.search(low) and not supervising and not U.asked_role(low):
|
||
out = U.work_count(person, works, low) # one entry per work, a namesake's work left out
|
||
elif U.TITLE_Q.search(low) and not supervising and not U.asked_role(low) and not METHODS.search(low):
|
||
out = U.work_title(person, works, low)
|
||
elif plan.get("intent") == "meeting" or re.search(r"\bstretnut\w*", low) or U.TASKS_Q.search(low) and wiki_text:
|
||
text = U.meeting(person, wiki_text, low, follow_up=asked != question or bool(re.match(r"^\W*a\b", normalized(asked))))
|
||
out = {"text": text, "urls": wiki.get("source_urls") or U.work_urls(person, [])} if text else None
|
||
elif SAME_OPPONENT.search(low): # "… mali pri bakalárskej práci rovnakého oponenta ako Martin Šarišský?"
|
||
out = U.same_opponent(person, low)
|
||
elif SAME_SUPERVISOR.search(low): # "Ktorí študenti mali rovnakého vedúceho ako Dmytro Mural?"
|
||
out = U.same_supervisor(person)
|
||
elif U.asked_role(low) and not STUDENTS_OF.search(low) and (
|
||
re.search(r"\b(?:kto|ktor\w*|ako\s+sa\s+vola|meno)\b", low)
|
||
or re.search(r"\b(?:veduci|skolitel|oponent|konzultant)\w*\W*$", low)):
|
||
# (also "Čo robil Jánovi Ptákovi vedúci?": the role word closes the question)
|
||
out = U.roles(person, works, low, wiki_text)
|
||
if out and out.get("options"): # two or more theses: which one?
|
||
result = _ok(question, engine, out["text"], [], base)
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, wiki_context=wiki_context, options=out["options"],
|
||
question=pending_question(question, wiki, person))
|
||
elif U.METHODS_Q.search(low):
|
||
options = U.work_options(person, works, low)
|
||
if options:
|
||
text = U.options_text(person, options, "Z ktorej chceš vedieť, aké technológie využíva?")
|
||
result = _ok(question, engine, text, [], base)
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, wiki_context=wiki_context, options=options,
|
||
question=pending_question(question, wiki, person))
|
||
out = U.methods(person, works, wiki_text, (part or {}).get("text") or "", low)
|
||
for kind, line in (out or {}).pop("missing", None) or []:
|
||
# the wiki answered one of the two named works only: its tools are asked for that work alone
|
||
alone = answer(f"Aké technológie využíva {person} vo svojej {U.TYPES[kind][2]}?", engine=engine)
|
||
found = re.search(r"(?m)^.+ vo svojej " + re.escape(U.TYPES[kind][2]) + r"\b.*využíva: .+$",
|
||
alone.get("answer") or "") if alone.get("status") == "ok" else None
|
||
if found:
|
||
out["text"] = out["text"].replace(line, found.group(0))
|
||
out["urls"] = list(dict.fromkeys([*out.get("urls", []), *(alone.get("source_urls") or [])]))
|
||
if out and re.search(r"\bkto\b[^?]*\b(?:viedol|viedla|veduc\w*|oponoval\w*)\b", low):
|
||
# "… a kto ich viedol?": the roles of the same works below
|
||
led = U.roles(person, works, low, wiki_text, role="opponent" if re.search(r"\boponoval", low) else "supervisor")
|
||
if led and led.get("text") and not led.get("options"):
|
||
out = {**out, "text": out["text"] + "\n\n" + led["text"],
|
||
"urls": list(dict.fromkeys([*out.get("urls", []), *led.get("urls", [])]))}
|
||
elif U.ABOUT_Q.search(low):
|
||
out = U.about(person, works, low)
|
||
elif U.WORKS_Q.search(low) or U.DID_Q.match(low) and not plan.get("period") and not plan.get("years"):
|
||
out = U.works_list(person, works)
|
||
elif student and (U.WHO_Q.match(low) or bare_name(question, person)):
|
||
out = U.who(person, works)
|
||
if out:
|
||
return done(out)
|
||
# Two people compared: one table.
|
||
if wiki_ok and COMPARE.search(low) and not TOPIC_LIST.match(low):
|
||
body, urls = split_sources(wiki_text)
|
||
head, items, tail, general = wiki_items(body, urls)
|
||
if len(items) == 2:
|
||
out = U.comparison([items[0]["name"], items[1]["name"]], collaboration=bool(re.search(r"\bspolupr", low)), low=low)
|
||
if out:
|
||
return done(out)
|
||
return None
|
||
|
||
|
||
def _compose(asked: str, question: str, engine: str, wiki: dict, part: dict | None, person: str | None) -> dict:
|
||
"""One answer from the ZP Wiki result and the CRZP part."""
|
||
from tools.answers.presentation.finalize import finalize
|
||
low = normalized(question)
|
||
named_in_crzp = crzp_names_the_person(question, wiki, part)
|
||
from tools.answers.presentation.unified import wiki_members
|
||
members = wiki_members(question, part.get("text") or "", part.get("rows")) if (
|
||
part is not None and part["mode"] == "explicit" and part.get("status") == "ok"
|
||
and wiki.get("reason") not in REFUSED) else None
|
||
if members: # "Koľko prác viedol X v roku 2025 a ktorí z jeho študentov sú v ZP Wiki?": the register's answer and
|
||
# the ZP Wiki students among those works (also when the wiki asks for a name: the register names the person)
|
||
body, urls = split_sources(part["text"])
|
||
urls = list(dict.fromkeys([*members["urls"], *urls, *part.get("urls", [])]))[:MAX_SOURCES]
|
||
text = body.rstrip() + "\n\n" + members["text"] + ("\n\nZdroje: " + ", ".join(urls) if urls else "")
|
||
return _with_token(_ok(question, engine, text, urls, {"index_version": wiki.get("index_version")}),
|
||
question=question, crzp=part.get("crzp_token"))
|
||
dropped_rows = []
|
||
compared = (part or {}).get("intent") == "compare" # two people compared from their records: no "which work?"
|
||
if wiki.get("reason") in REFUSED or wiki.get("status") == "ambiguous" and not named_in_crzp and not compared and (
|
||
person or wiki.get("reason") not in WIKI_CLARIFICATION_YIELDS):
|
||
# refused/out of scope, or the wiki asks first (which person, which work): no CRZP part (its rows, with their
|
||
# links, still join the person's works below)
|
||
dropped_rows, part = (part or {}).get("rows") or [], None
|
||
wiki_ok = wiki.get("accepted_for_delivery") is True and wiki.get("status") == "ok"
|
||
if part is not None and part["mode"] == "explicit" and wiki.get("status") == "ambiguous":
|
||
wiki_ok = False
|
||
if part is not None and part["mode"] == "explicit" and part.get("intent") in ("count", "methods") \
|
||
and part.get("status") in ("ok", "ambiguous") and not part.get("addition") and not NAMED_WIKI.search(low) \
|
||
or part is not None and part["mode"] == "explicit" and part.get("intent") == "relation" \
|
||
and part.get("status") == "ok" and re.search(r"\bkto\s+oponoval\w*|\boponent\w*\s+prac", low):
|
||
wiki_ok = False # a CRZP count (or the technologies of a CRZP work) is the answer; a wiki list is no count
|
||
if wiki.get("accepted_for_delivery") is True and isinstance(wiki.get("answer"), str):
|
||
wiki = {**wiki, "answer": finalize(wiki["answer"], wiki.get("source_urls"))}
|
||
wiki_context = wiki.get("conversation_context")
|
||
plan = wiki.pop("_plan", None) or {}
|
||
if (part is not None and part["mode"] == "explicit" and part.get("status") == "ok" and part.get("text")
|
||
and NAMED_CRZP.search(low) and not part.get("addition") and not NAMED_WIKI.search(low)):
|
||
wiki_ok = False # "… v CRZP?", "hľadaj v registri": what CRZP itself records is asked (not "… a čo uvádza ZP Wiki")
|
||
else:
|
||
special = _unified(asked, question, engine, wiki, wiki_ok,
|
||
part if part is not None or not dropped_rows else {"rows": dropped_rows},
|
||
person, wiki_context, plan)
|
||
if special is not None:
|
||
return special
|
||
if part is None or wiki.get("status") == "ambiguous" and part["mode"] != "explicit":
|
||
# (a wiki clarification such as "Uveď meno študenta" yields to a question CRZP answers as a whole)
|
||
if wiki.get("accepted_for_delivery") is not True:
|
||
return wiki
|
||
if wiki_ok:
|
||
body, urls = split_sources(wiki["answer"])
|
||
head, items, tail, general = wiki_items(body, urls or wiki.get("source_urls") or [])
|
||
if len(items) >= 2:
|
||
head = with_comparison(question, head, items)
|
||
shown, rest = first_page(items, [])
|
||
text, shown_urls, page_id = compose_list(head, shown, rest, tail, general, mixed=False)
|
||
result = {**wiki, "answer": text, "source_urls": shown_urls}
|
||
return _with_token(result, wiki_context=wiki_context, question=question, page=page_id,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)])
|
||
return _with_token(wiki, wiki_context=wiki_context, question=question)
|
||
# Different works in the two sources and the question names none: ask which one.
|
||
if person and part["mode"] == "person" and (METHODS.search(low) or ABOUT.search(low)):
|
||
options = _work_options(person, part, low)
|
||
if options:
|
||
text = (f"{person} má v podkladoch viac prác. Ktorú myslíš?\n\n" +
|
||
"\n".join(f"{i}. {o['label']} ({'ZP Wiki' if o['source'] == 'wiki' else 'CRZP'})"
|
||
for i, o in enumerate(options, 1)) + "\n\nOdpovedz číslom alebo typom práce.")
|
||
result = _ok(question, engine, text, [], wiki)
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, wiki_context=wiki_context, options=options,
|
||
question=pending_question(question, wiki, person))
|
||
if part["mode"] == "explicit" and part.get("status") == "ambiguous": # CRZP asks which namesake or which work
|
||
result = _ok(question, engine, part["text"], [], wiki if wiki_ok else {"index_version": wiki.get("index_version")})
|
||
result.update(status="ambiguous", reason="clarification_required",
|
||
delivery_check={"layer": "planning", "code": "clarification_required",
|
||
"request_fingerprint": fingerprint(question, engine)})
|
||
return _with_token(result, question=question, crzp=part.get("crzp_token"), primary="crzp",
|
||
options=part.get("options") or ())
|
||
if part.get("home_excluded"):
|
||
wiki_ok = False # "na iných školách": the TUKE wiki part is not asked
|
||
base = wiki if wiki_ok else {"index_version": wiki.get("index_version")}
|
||
wiki_body, wiki_urls = split_sources(wiki["answer"]) if wiki_ok else ("", [])
|
||
wiki_urls = wiki_urls or (wiki.get("source_urls") or [] if wiki_ok else [])
|
||
if part["mode"] == "related": # "Ktoré témy súvisia s X?": the topics and who did them
|
||
head = [f"S témou „{part['topic']}“ súvisia tieto témy (vyskytujú sa v tých istých prácach):"]
|
||
shown, rest = part["items"][:PAGE], part["items"][PAGE:]
|
||
text, urls, page_id = compose_list(head, shown, rest, [], [], mixed=False)
|
||
return _with_token(_ok(question, engine, text, urls, base), wiki_context=wiki_context, question=question,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)], page=page_id)
|
||
if part.get("items") is not None: # topic or similar works: one numbered list with the wiki people
|
||
head, items, tail, general = wiki_items(wiki_body, wiki_urls) if wiki_ok else ([], [], [], [])
|
||
if wiki_ok and not items: # a wiki answer that is no list stays whole, the CRZP works follow it
|
||
head, tail, general = [wiki_body], [], wiki_urls
|
||
from tools.answers.presentation.finalize import SIDE
|
||
if all(any(line.startswith(label + ":") for label in SIDE.values())
|
||
for line in wiki_body.split("\n") if line.strip()):
|
||
head, tail = [], [wiki_body] # only "Téma je len v zadaní …: X." – a closing note after the works
|
||
if not wiki_ok and part.get("home_excluded") and person: # the person's topic, the other schools' works
|
||
from tools.answers.presentation.unified import anchor_sentence, work_urls
|
||
anchor = anchor_sentence(person)
|
||
head = [(anchor + " " if anchor else "") + "Na iných školách sa podobnej téme venujú (od najbližších prác):"]
|
||
general = work_urls(person, [])
|
||
elif not wiki_ok:
|
||
head = ["V ZP Wiki k tomu nie je záznam. Práce na túto tému v CRZP (Centrálny register záverečných prác):"]
|
||
shown, rest = first_page(items, part["items"])
|
||
text, urls, page_id = compose_list(head, shown, rest, tail, general, mixed=True)
|
||
return _with_token(_ok(question, engine, text, urls, base), wiki_context=wiki_context, question=question,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)], page=page_id)
|
||
crzp_body, crzp_urls = split_sources(part["text"])
|
||
crzp_urls = list(dict.fromkeys([*crzp_urls, *part.get("urls", [])]))[:MAX_SOURCES]
|
||
entities = [{**e, "n": i} for i, e in enumerate(part.get("entities") or [], 1)]
|
||
if wiki_ok: # a list of wiki people ("Koho vedie X?") is paged; the CRZP part follows the first page
|
||
head, items, tail, general = wiki_items(wiki_body, wiki_urls)
|
||
if len(items) >= 2:
|
||
head = with_comparison(question, head, items)
|
||
shown, rest = first_page(items, [])
|
||
tail = [*tail, "V CRZP (Centrálny register záverečných prác):\n\n" + crzp_body]
|
||
text, urls, page_id = compose_list(head, shown, rest, tail, [*general, *crzp_urls], mixed=False)
|
||
return _with_token(_ok(question, engine, text, urls, base), wiki_context=wiki_context, question=question,
|
||
entities=[entity(item, i) for i, item in enumerate(shown, 1)], page=page_id,
|
||
crzp=part.get("crzp_token"))
|
||
if wiki_ok and person and part["mode"] == "person":
|
||
# A work the wiki answer already names is not repeated (its link stays in "Zdroje:").
|
||
from tools.answers.presentation.unified import catalog as wiki_catalog, _same_title
|
||
titles = [w.get("title") for w in wiki_catalog()["works"].get(person, []) if w.get("title")]
|
||
kept = [b for b in re.split(r"\n\s*\n", crzp_body)
|
||
if not any(_same_title(t, (re.search(r"„([^“]+)“", b) or [None, ""])[1]) for t in titles)]
|
||
crzp_body = "Ďalšie práce:\n\n" + "\n\n".join(kept) if kept else ""
|
||
if not wiki_ok and (part["mode"] == "explicit" or wiki.get("status") == "error" or part.get("home_excluded")):
|
||
text = crzp_body
|
||
elif wiki_ok:
|
||
text = wiki_body + ("\n\n" + crzp_body if crzp_body else "")
|
||
else:
|
||
text = "V ZP Wiki k tomu nie je záznam.\n\nV CRZP (Centrálny register záverečných prác):\n\n" + crzp_body
|
||
urls = list(dict.fromkeys([*wiki_urls, *crzp_urls]))
|
||
if not wiki_ok and person and part.get("person") and normalized(part["person"]) == normalized(person) \
|
||
and not part.get("home_excluded"):
|
||
# "… podľa registra CRZP": the register's answer about a ZP Wiki student links the student's profile too
|
||
from tools.answers.presentation.unified import catalog as wiki_catalog
|
||
profile = (wiki_catalog()["people"].get(person) or {}).get("url")
|
||
urls = list(dict.fromkeys([profile, *urls])) if profile else urls
|
||
if urls:
|
||
text += "\n\nZdroje: " + ", ".join(urls)
|
||
page = None
|
||
if part.get("rest"): # "Chceš vidieť ďalších?": the rest of a ranking, shown on "áno"
|
||
from tools.answers import pages
|
||
page = pages.put(part["rest"], {"kind": "lines"})
|
||
if page:
|
||
text += "\n\n" + (part.get("offer") or "Chceš vidieť ďalšie?")
|
||
result = _ok(question, engine, text, urls, base)
|
||
return _with_token(result, wiki_context=wiki_context, entities=entities, question=question, page=page,
|
||
crzp=part.get("crzp_token"), primary="crzp" if part["mode"] == "explicit" and not wiki_ok else "wiki")
|
||
|
||
|
||
def crzp_names_the_person(question: str, wiki: dict, part: dict | None) -> bool:
|
||
"""The wiki asks which person ("Meno „samuel“ nie je jednoznačné") or does not know the name, while
|
||
CRZP found a person whose whole name (first name and surname) is in the question: CRZP answers."""
|
||
from tools.crzp.answering.understand import in_question
|
||
if not part or part.get("mode") != "explicit" or part.get("status") not in ("ok", "ambiguous") or not part.get("person"):
|
||
return False
|
||
if wiki.get("reason") not in ("incomplete_person_name", "unknown_person"):
|
||
return False
|
||
name = part["person"]
|
||
return len(name.split()) >= 2 and in_question(name, question)
|
||
|
||
|
||
def pending_question(question: str, wiki: dict, person: str | None) -> str:
|
||
"""The question a thesis choice ("diplomovku", "1") answers, with the person in it: the reply is asked
|
||
again without the conversation, so "A kto je jeho vedúci?" becomes "A kto je vedúci Jána Holpa?"."""
|
||
if not person:
|
||
return question
|
||
surname = normalized(person.split()[-1])[:4]
|
||
resolved = wiki.get("resolved_query")
|
||
if isinstance(resolved, str) and surname in normalized(resolved):
|
||
return resolved # the wiki's own resolution of the follow-up
|
||
if surname in normalized(question):
|
||
return question
|
||
from tools.answers.presentation.unified import genitive
|
||
named = re.sub(r"(?i)\b(?:jeho|jej)\s+([^\W\d_]+)", lambda m: f"{m.group(1)} {genitive(person)}", question, count=1)
|
||
return named if named != question else question.rstrip(" ?.!") + f" {person}?"
|
||
|
||
|
||
def _work_options(person: str, part: dict, low: str) -> list[dict]:
|
||
"""The person's works when the two sources hold works of different types and the question names none."""
|
||
if re.search(r"\b(?:bakalar\w*|diplom\w*|dizerta\w*|projekt\w*)\b", low):
|
||
return []
|
||
wiki = wiki_works(person)
|
||
wiki_types = {w["type"] for w in wiki.values()}
|
||
thesis = {"diploma_thesis": "diplom", "bachelor_thesis": "bakalar"}
|
||
crzp_only = [w for w in part.get("works", []) if w["type"] in thesis and w["type"] not in wiki_types]
|
||
if not crzp_only:
|
||
return []
|
||
wiki_options = [{"source": "wiki", "label": label + (f" „{w['topic']}“" if w.get("topic") else ""), "work": label}
|
||
for label, w in wiki.items() if w["type"] in thesis][:2]
|
||
return wiki_options + crzp_only if wiki_options else []
|
||
|
||
|
||
CHOICE_FILLERS = {"tak", "teda", "ta", "tu", "ten", "to", "tej", "chcem", "daj", "prosim", "cislo", "moznost", "a", "ano",
|
||
"no", "hej", "mi", "tu", "pracu", "praca", "prace", "o", "tej", "tom", "volba", "ok", "jasne", "tú"}
|
||
NUMBER_WORDS = {"jedna": 1, "jednotku": 1, "jednotka": 1, "prvu": 1, "prva": 1, "prvy": 1, "prve": 1, "prvej": 1,
|
||
"dva": 2, "dve": 2, "dvojku": 2, "dvojka": 2, "druhu": 2, "druha": 2, "druhy": 2, "druhe": 2, "druhej": 2,
|
||
"tri": 3, "trojku": 3, "trojka": 3, "tretiu": 3, "tretia": 3, "treti": 3, "tretej": 3}
|
||
|
||
|
||
def _choice(low: str, options: list[dict]) -> dict | None:
|
||
""""2", "tak 1", "tú prvú", "jednotku", "bakalársku", "z wiki" -> the chosen option."""
|
||
words = [w for w in re.findall(r"[a-z0-9]+", low) if w not in CHOICE_FILLERS]
|
||
typed = [o for o in options if o.get("type")]
|
||
if typed and len(words) <= 4: # options of different thesis types: "bakalársku", "tú diplomovú"
|
||
from tools.answers.presentation.unified import asked_type
|
||
kind = asked_type(low)
|
||
same = [o for o in typed if o["type"] == kind]
|
||
if kind and len(same) == 1:
|
||
return same[0]
|
||
if len(words) == 1:
|
||
word = words[0]
|
||
number = int(word) if word.isdigit() else NUMBER_WORDS.get(word)
|
||
if number is not None:
|
||
return options[number - 1] if 1 <= number <= len(options) else None
|
||
if len(words) <= 4 and CHOICE_CRZP.search(low):
|
||
return next((o for o in options if o["source"] == "crzp"), None)
|
||
if len(words) <= 4 and CHOICE_WIKI.search(low):
|
||
return next((o for o in options if o["source"] == "wiki"), None)
|
||
return None
|
||
|
||
|
||
def _answer_choice(question: str, chosen: dict, *, engine: str, limit: int, complete=None, deliver=None) -> dict:
|
||
"""The answer to the pending question about the chosen work (the caller binds it to the reply)."""
|
||
from tools.answers.presentation.finalize import finalize
|
||
deliver_answer = deliver
|
||
if chosen.get("type"): # one of the person's theses: the same question about that thesis
|
||
from tools.answers.presentation.unified import TYPES
|
||
nominative, genitive_, locative = TYPES[chosen["type"]]
|
||
if re.search(r"\bpráce\b", question):
|
||
asked = re.sub(r"\bpráce\b", genitive_, question, count=1)
|
||
elif re.search(r"\bpráci\b", question):
|
||
asked = re.sub(r"\bpráci\b", locative, question, count=1)
|
||
else:
|
||
asked = question.rstrip(" ?.") + f" v {locative}?"
|
||
result = _answer(asked, engine=engine, limit=limit, context_token=None, complete=complete, deliver=deliver)
|
||
return {**result, "_asked_as": [asked, *result.pop("_asked_as", [])]}
|
||
from tools.crzp.answering.wiki_bridge import wiki_person
|
||
if chosen["source"] == "wiki":
|
||
work = normalized(chosen["work"])
|
||
adjective = "diplomovej" if work.startswith("diplom") else "bakalárskej" if work.startswith("bakal") else ""
|
||
asked = re.sub(r"\b(svojej\s+|jeho\s+|jej\s+)?(práci|práce|prácu)\b", lambda m: (m.group(1) or "") + adjective + " " + m.group(2),
|
||
question, count=1) if adjective else question
|
||
if asked == question:
|
||
asked = question.rstrip(" ?.") + f" ({chosen['work']})?"
|
||
result = deliver_answer(asked, engine=engine, limit=limit)
|
||
if result.get("accepted_for_delivery") is True and isinstance(result.get("answer"), str):
|
||
result = {**result, "answer": finalize(result["answer"], result.get("source_urls"))}
|
||
return {**result, "_asked_as": [asked]}
|
||
person = wiki_person(question)
|
||
part = crzp_part(question, person, complete=complete)
|
||
rows = [r for r in (part or {}).get("rows", []) if chosen.get("key") and _key_of(r) == chosen["key"]]
|
||
if not part or not rows:
|
||
return _ok(question, engine, "Vybranú prácu sa v CRZP nepodarilo znova načítať. Skús otázku zopakovať.", [], {})
|
||
from tools.crzp.answering import answer as crzp
|
||
row = rows[0]
|
||
detail = crzp.fetch.detail(row["sid"]) if row.get("sid") else None
|
||
low = normalized(question)
|
||
if METHODS.search(low):
|
||
text = crzp_methods(person, row, detail)
|
||
else:
|
||
label, summary = crzp.summary(detail, complete) if detail else ("", "")
|
||
text = f"**{row['title']}** ({_kind(row)}, {row.get('year')})\n\n{summary}"
|
||
urls = [row["url"]] if row.get("url") else []
|
||
return _ok(question, engine, text + ("\n\nZdroj: " + urls[0] if urls else ""), urls, {})
|
||
|
||
|
||
def _key_of(row: dict) -> str:
|
||
from tools.crzp.answering import answer as crzp
|
||
return crzp.work_key(row)
|
||
|
||
|
||
# labels of the answer path (rewrite, plan, branch, source) in the timing log, for evaluation
|
||
from tools.answers import route_trace as _route_trace # noqa: E402
|
||
|
||
_route_trace.install()
|