dp-zp-agent/tools/crzp/answering/answer.py
2026-11-20 03:42:51 +01:00

1433 lines
83 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Verified answers from CRZP metadata (/crzp).
Flow: question -> CrzpQuery -> CRZP searches (years and work types filtered by
CRZP itself, cached) -> rows filtered by person role, school and verified
workplace -> answer by intent. A topic is also searched under up to two
alternative terms (synonyms) and the answer names every searched term. Every
listed fact is copied from a parsed CRZP record and every work links to its
CRZP permalink. The model only (1) proposes base forms of names/topics and
alternative terms, checked by code, and (2) summarizes an abstract; the
summary is shown only after a separate check that it is supported by the
abstract, otherwise the abstract itself is shown.
"""
from __future__ import annotations
import json
import re
import threading
import time
from collections import Counter, OrderedDict
from tools.answers.verification.delivery_contract import fingerprint
from tools.crzp import fetch
from tools.crzp.answering import context
from tools.crzp.answering.names import name_candidates, name_variants
from tools.crzp.answering.terms import is_reviewed
from tools.crzp.answering.understand import SCHOOLS, CrzpQuery, in_question, stem_match, understand
from tools.crzp.answering.units import UNITS, in_unit, unit_label
from tools.crzp.source.client import CrzpUnavailable
from tools.crzp.source.parse import WORK_TYPE_LABELS, display_name, fold
from tools.crzp.storage import graph
ENGINE = "crzp"
LIST_LIMIT = 30
ROLE_FIELD = {"author": "authors", "supervisor": "supervisors", "opponent": "opponents"}
ROLE_LABEL = {"author": "autor", "supervisor": "vedúci", "opponent": "oponent"}
ROLE_PLURAL = {"author": "Autori", "supervisor": "Vedúci", "opponent": "Oponenti"}
# Extra results of one answer (the not shown rest of a ranking, the people it shows), set by the handlers.
import contextvars as _contextvars
_extras: _contextvars.ContextVar[dict | None] = _contextvars.ContextVar("crzp_answer_extras", default=None)
FACET = {"author": "Autor", "supervisor": "Školiteľ"}
_cache: OrderedDict = OrderedDict()
_cache_lock = threading.Lock()
CACHE_SECONDS = 600
# ------------------------------------------------------------------ matching
def name_matches(query_name: str, crzp_name: str) -> bool:
"""Every word of the asked name is a word of the CRZP name (up to inflection)."""
words = re.findall(r"[^\W\d_]+", crzp_name.split("(")[0])
asked = re.findall(r"[^\W\d_]+", query_name)
return bool(asked) and all(any(stem_match(a, w) for w in words) for a in asked)
def people_in_role(row: dict, name: str, role: str) -> list[str]:
fields = [ROLE_FIELD[role]] if role in ROLE_FIELD else list(ROLE_FIELD.values())
return [p for f in fields for p in row.get(f, []) if name_matches(name, p)]
def keep(row: dict, query: CrzpQuery) -> bool:
"""Conditions CRZP cannot filter (roles, school, workplace) plus a repeat of
the year/type filters (a year list may have gaps inside the searched range)."""
if query.sids and row.get("sid") not in query.sids:
return False # follow-up about chosen works of the previous answer
if query.school_name and university(row) != query.school_name:
return False # the chosen namesake
if query.works and work_key(row) not in query.works:
return False # the chosen namesake's works (two students of one name at one university)
if any(not people_in_role(row, p.name, p.role) for p in query.people):
return False
if query.years and row.get("year") not in query.years:
return False
if query.work_types and row.get("work_type") not in query.work_types:
return False
if query.school and SCHOOLS[query.school][1] not in fold(university(row)): # "Slovenská technická univ."
return False
if query.exclude_school and SCHOOLS[query.exclude_school][1] in fold(university(row)):
return False # "na iných školách"
if query.unit and not in_unit(row, query.unit):
return False
if query.published and not row.get("published"):
return False # "obhájili": an unpublished work may be undefended or have its publication deferred
if query.exclude_terms: # "bez RASA": a work whose title or keywords name the excluded tool is left out
from tools.crzp.answering.relevance import mentions
text = " ".join([row.get("title") or "", *(row.get("keywords") or [])])
if any(mentions(text, term, case=False) for term in query.exclude_terms):
return False
return True
def filters(query: CrzpQuery) -> dict:
"""Filters CRZP applies itself: a range of submission years and work types."""
return {"years": (min(query.years), max(query.years)) if query.years else None,
"work_types": list(query.work_types) or None}
def suffixes(query: CrzpQuery) -> list[str]:
"""What a topic search appends for a school or workplace: the school name, or every
form CRZP writes the workplace in (code "104005" and, in old records, the department name)."""
if query.unit:
return [" " + text for text in UNITS[query.unit]["search"]]
return [" " + SCHOOLS[query.school][0]] if query.school else [""]
def strip_suffix(query: CrzpQuery, text: str) -> str:
return next((text[: -len(s)] for s in suffixes(query) if s and text.endswith(s) and text != s.strip()), text)
def search_groups(query: CrzpQuery) -> list[list[str]]:
"""Search texts in order of preference; the texts of one group are searched
together and their rows merged (a topic with its alternative terms). A
verified workplace is searched by its code (CRZP indexes it, "104005") and
by its old written name."""
ends = suffixes(query)
each = lambda terms: [t + end for t in terms for end in ends]
if query.people:
return [[text] for text in person_searches(query)]
if query.title:
return [[query.title]]
if not query.topics:
if query.unit:
return [list(UNITS[query.unit]["search"]), [SCHOOLS[query.school][0]]]
return [[SCHOOLS[query.school][0]]] if query.school else []
main = " ".join(query.topics[:2])
if query.phrases and not query.from_model: # rules: the likely written phrase first
groups = [each([query.phrases[0], *query.alternatives])] + [each([p]) for p in query.phrases[1:]]
groups.append(each([main]))
else:
groups = [each([main, *query.alternatives])]
if len(query.topics) > 1: # two topic words did not occur together: the main one alone
groups.append(each([query.topics[0]]))
groups += [each([t]) for t in query.surface[:1]] # words as written (rules without the model)
if ends != [""]:
groups += [[t] for t in [main, *query.alternatives]]
unique, seen = [], set()
for group in groups:
group = [t for t in dict.fromkeys(group) if t.strip() and t not in seen]
seen.update(group)
if group:
unique.append(group)
return unique
def person_searches(query: CrzpQuery) -> dict[str, dict]:
"""Search texts of a person question in order: {text: {"names": the asked names its rows are
checked with, "candidate": another form tried only when no search found the person yet,
"surname": surname alone (one relevance-ordered read, the first name checked in the rows)}}.
- a name ZP Wiki or CRZP gives (canonical) is searched as it is;
- the model's base form first, then other forms of the typed name (names.name_candidates:
"Samuela Furdy" -> "Samuel Furda", "Samo" -> "Samuel"), then the surname alone;
- without the model, the rule forms (names.name_variants)."""
person = query.people[0]
title = " " + query.title if query.title else ""
topic = f" {query.topics[0]}" if query.topics else ""
if not query.from_model:
names = [(n, [person.name], False, False) for n in name_variants(person.name)]
elif person.canonical:
names = [(person.name, [person.name], False, False)]
else:
full, surnames = name_candidates(person.name, person.typed or person.name)
names = [(full[0], [person.name], False, False)] + [(n, [n], True, False) for n in full[1:]]
names += [(s, [person.name, *full[1:]], True, True) for s in surnames]
searches = {}
first = names[:1] if query.from_model else names
for name, asked, candidate, surname in first: # the person with the topic first ("Ján Pták IoT")
if topic and not surname:
searches.setdefault(f"{name}{topic}{title}", {"names": asked, "candidate": candidate, "surname": False})
for name, asked, candidate, surname in names:
searches.setdefault(f"{name}{title}", {"names": asked, "candidate": candidate, "surname": surname})
return searches
def _exact(name: str, crzp_name: str) -> bool:
"""Same words including diacritics, up to inflection ("Jána" is "Ján", not "Jan")."""
words = re.findall(r"[^\W\d_]+", crzp_name)
return all(any(stem_match(a, w, diacritics=True) for w in words) for a in re.findall(r"[^\W\d_]+", name))
def prefer_exact(rows: list[dict], query: CrzpQuery) -> list[dict]:
"""A name typed with diacritics keeps only the exact spellings when CRZP has them."""
for person in query.people:
typed = person.typed or person.name
if fold(typed) == typed.lower():
continue # typed without diacritics: every spelling matches
exact = [r for r in rows if any(_exact(typed, n) for n in people_in_role(r, person.name, person.role))]
if exact:
rows = exact
return rows
LEVEL = {"bachelor_thesis": 1, "diploma_thesis": 2, "doctoral_thesis": 3, "dissertation": 3, "habilitation_thesis": 4}
def work_key(row: dict) -> str:
return f"{' '.join(fold(row['title']).rstrip(' .').split())}|{row.get('year')}"
def _split_students(group: dict) -> list[dict]:
"""One student writes one work of each kind: two bachelor theses of "Ján Novák" at one
university are two persons. Works are given, oldest first, to the first person who
has no work of that kind yet and whose last work is at most 8 years older."""
persons = []
for row in sorted(group["rows"], key=lambda r: r.get("year") or 0):
kind, year = row.get("work_type"), row.get("year") or 0
target = next((p for p in persons if kind not in p["kinds"] and year - p["last"] <= 8), None)
if target is None:
target = {"kinds": set(), "last": year, "rows": []}
persons.append(target)
target["kinds"].add(kind)
target["last"] = max(target["last"], year)
target["rows"].append(row)
return [{**group, "rows": p["rows"], "count": len(p["rows"]), "years": {r.get("year") for r in p["rows"]}}
for p in persons]
def identities(rows: list[dict], person) -> list[dict]:
"""The asked name split into probable persons (CRZP has no person identifiers):
- the same written name (with diacritics) at the same university is one person,
another spelling or university another one;
- a name that is only an author there is split when it has two works of one kind
(two bachelor theses are two students);
- an author at another university whose earlier work leads to this one
(bachelor -> diploma within 4 years) is marked as possibly the same person."""
groups: dict = {}
seen = set()
for row in rows:
held = (work_key(row), tuple(sorted(fold(a) for a in row.get("authors", []))))
if held in seen:
continue # the same work held twice in CRZP (two students of one title and year are two works)
seen.add(held)
for name in people_in_role(row, person.name, person.role):
key = (display_name(name), university(row))
group = groups.setdefault(key, {"name": key[0], "school": key[1], "count": 0, "years": set(),
"roles": Counter(), "rows": []})
group["count"] += 1
group["years"].add(row.get("year"))
group["rows"].append(row)
group["roles"].update(role for role, field in ROLE_FIELD.items() if name in row.get(field, []))
result = []
for group in groups.values():
result += _split_students(group) if set(group["roles"]) == {"author"} else [group]
for group in result:
group["hint"] = None
if set(group["roles"]) != {"author"}:
continue
first = min(group["rows"], key=lambda r: r.get("year") or 0)
for other in result:
if other is group or other["name"] != group["name"] or set(other["roles"]) != {"author"}:
continue
last = max(other["rows"], key=lambda r: r.get("year") or 0)
if (other["school"] != group["school"]
and LEVEL.get(last.get("work_type"), 0) < LEVEL.get(first.get("work_type"), 0)
and 0 < (first.get("year") or 0) - (last.get("year") or 0) <= 4):
group["hint"] = f"možno tá istá osoba ako {other['school']} ({last.get('year')})"
return sorted(result, key=lambda g: (-g["count"], -max((y or 0) for y in g["years"]), g["name"], g["school"]))
def _identity_line(group: dict) -> str:
""""Lukáš Juhás — Technická univerzita v Košiciach, FEI, KEMT (autor; 2012; 1 práca: „Návrh a …“)": the
faculty or department and the newest work tell two namesakes of one school apart."""
years = sorted(y for y in group["years"] if y)
span = (f"{years[0]}–{years[-1]}" if len(years) > 1 else str(years[0])) if years else "rok neuvedený"
roles = ", ".join(ROLE_LABEL[r] for r, _ in group["roles"].most_common())
works = f"{group['count']} {'práca' if group['count'] == 1 else 'práce' if group['count'] < 5 else 'prác'}"
hint = f"; {group['hint']}" if group.get("hint") else ""
newest = max(group["rows"], key=lambda r: r.get("year") or 0) if group.get("rows") else None
place = group["school"]
if newest:
unit = unit_label(newest) if group["school"] == "Technická univerzita v Košiciach" else \
_faculty(newest.get("school") or "", group["school"]).strip(" ,")
place += f", {unit}" if unit else ""
title = newest["title"] if len(newest["title"]) <= 60 else newest["title"][:57].rstrip() + "…"
works += f": „{title}“"
return f"{group['name']} — {place} ({roles}; {span}; {works}{hint})"
def namesakes(rows: list[dict], query: CrzpQuery) -> str:
"""Notice when the asked name belongs to several probable CRZP persons."""
for person in query.people:
groups = identities(rows, person)
if len(groups) > 1:
return ("\n\nUpozornenie: menu zodpovedá v CRZP viac pravdepodobných osôb (CRZP ich nerozlišuje "
"identifikátorom):\n" + "\n".join("- " + _identity_line(g) for g in groups[:6]) +
"\nSpresni školu alebo rok.")
return ""
def clarification(rows: list[dict], query: CrzpQuery) -> tuple[str, list[dict]] | None:
"""Count, summary, keywords, relations and similar works of one person must not mix
namesakes: ask which person is meant (a list shows all with a notice instead)."""
if not query.people or query.intent in ("list", "schools") or query.school_name or query.sids or query.works:
return None
groups = identities(rows, query.people[0])
if len(groups) < 2:
return None
groups = sorted(groups, key=lambda g: g["school"] != "Technická univerzita v Košiciach")[:8] # ZP Wiki's school first
text = ("Menu „" + query.people[0].name + "“ zodpovedá v CRZP viac pravdepodobných osôb (CRZP ich nerozlišuje "
"identifikátorom). Ktorú myslíš?\n\n" + "\n".join(f"{i}. {_identity_line(g)}" for i, g in
enumerate(groups, 1)) +
"\n\nOdpovedz číslom, školou alebo celým menom.")
return text, [{"name": g["name"], "school": g["school"], "works": [work_key(r) for r in g["rows"]][:30]}
for g in groups]
def _merge(results: list[dict]) -> dict:
rows, seen = [], {}
for result in results:
for row in result["rows"]:
key = (fold(row["title"]).rstrip(" ."), row.get("year"), tuple(row.get("authors", [])))
if key not in seen:
seen[key] = row
rows.append(row)
elif row.get("sid") and not seen[key].get("sid"): # the same work read with its permalink
seen[key].update(sid=row["sid"], url=row.get("url"))
read = [r["fetched_at"] for r in results if r.get("fetched_at")]
return {"texts": [r["query"] for r in results], "totals": [r["total"] for r in results],
"fetched_at": min(read) if read else None, # the oldest data of the answer
"total": results[0]["total"] if len(results) == 1 else sum(r["total"] for r in results),
"facets": results[0]["facets"], "rows": rows, "complete": all(r["complete"] for r in results),
"incomplete": [(r["query"], r["total"], len(r["rows"])) for r in results if not r["complete"]],
"parts": results}
def _unverified(query: CrzpQuery, text: str) -> str | None:
"""The model-proposed alternative term the search text stands for (not in the reviewed table)."""
term = strip_suffix(query, text)
for alternative in query.alternatives:
if fold(alternative) == fold(term) and query.topics and not is_reviewed(alternative, query.topic_key()):
return alternative
return None
def _used_with_topic(term: str, rows: list[dict]) -> bool:
"""CRZP itself writes the term in a work found for the topic (title or keywords)."""
return any(in_question(term, r["title"] + " " + " ".join(r.get("keywords", []))) for r in rows)
AGGREGATES = ("count", "keywords", "schools", "relation")
def by_facets(query: CrzpQuery) -> bool:
"""A count, or the supervisors of works on a topic, that CRZP computes itself: every
condition is in the search (text, years, work type) and one text per meaning, so the
CRZP total and the full year/type/supervisor facets are exact without reading rows."""
counted = query.intent == "count" or query.intent == "relation" and query.target_role == "supervisor"
return (counted and not query.people and not query.title and not query.sids and not query.school_name
and not query.alternatives and len(query.topics) <= 1 and not query.published)
def reader(query: CrzpQuery):
"""How one search text is read for this question:
- counted by CRZP (by_facets): the first page with the full facets only;
- summaries (tags, schools, opponents, a person's works): every row up to
DEEP_ROWS, in year ranges at once, permalinks only where a work is shown;
- a list of a school or workplace: the newest LINKED_ROWS works, all with permalinks;
- a topic list, a summary of a work, similar works: the LINKED_ROWS most relevant rows."""
window = filters(query)
if by_facets(query):
return lambda text: fetch.search(text, links=False, depth=20, **window)
if query.intent in ("keywords", "schools", "count"):
return lambda text: fetch.search_deep(text, links=False, **window)
if query.intent in ("relation", "sources") or query.people: # a ranking and its works read every row
return lambda text: fetch.search_deep(text, links=True, **window)
if query.intent == "list" and (query.school or query.unit) and not query.topics and not query.title:
return lambda text: fetch.search_deep(text, links=True, limit=fetch.LINKED_ROWS, **window)
return lambda text: fetch.search(text, links=query.intent != "count", **window)
def _asking(query: CrzpQuery, name: str) -> CrzpQuery:
"""The query with another form of the asked person's name (rows are checked with it)."""
if name == query.people[0].name:
return query
asked = query.model_copy(deep=True)
asked.people[0].name = name
return asked
def find(query: CrzpQuery) -> tuple[dict | None, list[dict]]:
"""First search group whose rows satisfy all conditions; (merged result, rows).
A model-proposed alternative term is searched only if CRZP uses it in a work
already found for the topic, or if nothing was found yet. Another form of an
asked person's name (person_searches) is searched only while no search found
the person in any role."""
last, seen = None, []
met = None # (result, asked name) of the latest search whose rows name the asked person
query.searched = []
read = reader(query)
people = person_searches(query) if query.people else {}
for group in search_groups(query):
info = people.get(group[0]) if people else None
if info and info["candidate"] and met:
continue # the person is found under an earlier form
results, verified_rows, unverified = [], 0, []
for text in group:
term = _unverified(query, text)
if term and seen and not _used_with_topic(term, seen) and any(keep(r, query) for r in seen):
continue # "rozložená kniha" for blockchain: CRZP does not use it, no search
# (tried when nothing found so far meets the conditions, e.g. "na iných školách")
surname_only = bool(info and info["surname"])
results.append(fetch.search(text, links=True, **filters(query)) if surname_only else read(text))
query.searched.append(text)
seen += results[-1]["rows"]
if term:
unverified.append(term)
else:
verified_rows += len(results[-1]["rows"])
if not results:
continue
found = _merge(results)
asked = query
for name in (info["names"] if info else [None]):
asked = _asking(query, name) if name else query
rows = prefer_exact([r for r in found["rows"] if keep(r, asked)], asked)
if rows:
break
if info:
name = next((n for n in info["names"] if any(people_in_role(r, n, "any") for r in found["rows"])), None)
if name:
met = (found, name)
if by_facets(query) and not found["complete"]:
if len(rows) == len(found["rows"]):
found["facet_only"] = True # CRZP itself counted it; every read row meets the conditions
else: # some found works are elsewhere (e.g. a school name in a title): count the rows themselves
found = _merge([fetch.search_deep(r["query"], links=False, **filters(query)) for r in found["parts"]])
rows = prefer_exact([r for r in found["rows"] if keep(r, query)], query)
last = (found, rows)
if rows and unverified and not verified_rows:
query.unverified_only = unverified # the topic itself found nothing: say so in the answer
if rows:
if query.people: # show the name as CRZP writes it ("hladek" -> "Daniel Hládek") when it is one person
query.people[0].name = asked.people[0].name
names = Counter(n for r in rows for n in people_in_role(r, query.people[0].name, query.people[0].role))
if len(names) == 1 or not query.from_model:
query.people[0].name = display_name(names.most_common(1)[0][0])
return last
if last and query.people and query.people[0].role == "author":
# "práce X" may mean the works X supervised or reviewed: X is no author in the read rows.
base, name = met or (last[0], query.people[0].name)
relaxed = _asking(query, name).model_copy(deep=True)
# "bakalárske práce Daniela Hládka": the works he supervised; reviewed ones only when he supervised none
for role in ("supervisor", "any"):
relaxed.people[0].role = role
rows = prefer_exact([r for r in base["rows"] if keep(r, relaxed)], relaxed)
if rows:
query.people[0].role = role
query.people[0].name = name
query.relaxed_author = True
return base, rows
return last or (None, [])
def ranked(question: str, query: CrzpQuery, rows: list[dict]) -> list[dict]:
"""Topic questions: cross-encoder relevance over title + CRZP keywords; else newest first."""
rows = sorted(rows, key=lambda r: (-(r.get("year") or 0), fold(r["title"])))
if query.topics and len(rows) > 1:
from tools.retrieval import rerank
# The searched terms tell the cross-encoder what an abbreviation means ("LLM jazykový model GPT").
terms = [t for t in [*query.topics, *query.alternatives] if fold(t) not in fold(question)]
rows = rerank.order(" ".join([question, *terms]), rows, key=lambda r: r["title"] + ". " + ", ".join(r.get("keywords", [])))
return rows
# ------------------------------------------------------------------ rendering
def _names(values: list[str]) -> str:
return ", ".join(display_name(v) for v in values) or "neuvedený"
def _kind(row: dict) -> str:
return WORK_TYPE_LABELS.get(row.get("work_type"), "práca")
def _link(row: dict) -> str:
return f"[CRZP]({row['url']})" if row.get("url") else "záznam bez trvalého odkazu"
def school(row: dict) -> str:
unit = unit_label(row)
return (row.get("school") or "škola neuvedená") + (f", {unit}" if unit else "")
def work_block(row: dict, detail: dict | None = None) -> str:
record = detail or row
head = f"**{record['title']}** — {_kind(record)}, {record.get('year') or 'rok neuvedený'}, {school(record)}"
lead = "školiteľ" if record.get("work_type") in ("dissertation", "doctoral_thesis") else "vedúci"
lines = [head, f"- Autor: {_names(record.get('authors', []))}; {lead}: {_names(record.get('supervisors', []))}; "
f"oponent: {_names(record.get('opponents', []))}"]
if detail and detail.get("consultants"):
lines.append(f"- Konzultant: {_names(detail['consultants'])}")
if record.get("keywords"):
lines.append("- Kľúčové slová: " + ", ".join(record["keywords"]))
if detail:
extra = [f"{detail['pages']} strán" if detail.get("pages") else "",
f"jazyk: {detail['language']}" if detail.get("language") else "",
f"odbor: {detail['field_of_study']}" if detail.get("field_of_study") else ""]
if any(extra):
lines.append("- " + "; ".join(e for e in extra if e))
lines.append("- Zdroj: " + _link(record))
return "\n".join(lines)
def work_line(row: dict) -> str:
return (f"- {_names(row.get('authors', []))} — „{row['title']}“ ({_kind(row)}, {row.get('year') or '?'}, "
f"{school(row)}) · {_link(row)}")
def describe(query: CrzpQuery) -> str:
parts = []
for person in query.people:
label = ROLE_LABEL.get(person.role, "osoba")
if label in ("vedúci", "autor", "oponent"):
from tools.answers.presentation.unified import female
if female(display_name(person.name)):
label = {"vedúci": "vedúca", "autor": "autorka", "oponent": "oponentka"}[label]
parts.append(f"{label} {person.name}" if person.role != "any" else person.name)
if query.title:
parts.append(f"názov „{query.title}“")
if query.topics: # also beside a person ("vedúci Juraj Sipko; téma „blockchain“")
parts.append("téma „" + " ".join(query.topics[:2]) + "“")
if query.work_types:
parts.append(", ".join(WORK_TYPE_LABELS[t] for t in query.work_types))
if query.years:
parts.append("rok " + ", ".join(map(str, query.years)))
if query.sids:
parts.append("vybraná práca z predchádzajúcej odpovede" if len(query.sids) == 1
else "práce z predchádzajúcej odpovede")
if query.unit:
parts.append(UNITS[query.unit]["label"] + " " + SCHOOLS[query.school][0])
elif query.school:
parts.append(SCHOOLS[query.school][0])
if query.published:
parts.append("zverejnené, teda obhájené")
return "; ".join(parts)
def plural(count: int) -> str:
return f"{count} {'práca' if count == 1 else 'práce' if 2 <= count <= 4 else 'prác'}"
def unpublished_note(found: dict, query: CrzpQuery) -> str:
"""How many works meeting the other conditions are not published (defence not confirmed)."""
if not query.published:
return ""
other = query.model_copy(update={"published": False})
hidden = {work_key(r) for r in found["rows"] if keep(r, other) and not r.get("published")}
if not hidden:
return ""
n = len(hidden)
lead = (f"Ďalšia {n} práca je" if n == 1 else f"Ďalšie {n} práce sú" if n <= 4 else f"Ďalších {n} prác je")
return (f"\n\n{lead} {'nezverejnená' if n == 1 else 'nezverejnené' if n <= 4 else 'nezverejnených'}; "
"nie je známe, či ide o odklad zverejnenia alebo o neobhájenú prácu.")
# ------------------------------------------------------------------ model steps
SUMMARY_PROMPT = ("Si odborník, ktorý stručne vysvetľuje záverečné práce. Z abstraktu a kľúčových slov napíš po "
"slovensky 2 až 3 vlastné vety: o čom práca je, čo v nej autor urobil a s akými nástrojmi alebo "
"metódami. Píš vlastnými slovami a súvislo, neopisuj vety abstraktu doslova a nezačínaj slovami "
"„Táto práca“ ani „Abstrakt“. Použi iba informácie z abstraktu a kľúčových slov; nepridávaj "
"výsledky, čísla, nástroje ani hodnotenia, ktoré v nich nie sú. Bez nadpisu a bez odrážok.")
CHECK_PROMPT = ("Over, či je každé tvrdenie zhrnutia podložené abstraktom alebo kľúčovými slovami (preformulovanie "
"a zovšeobecnenie je v poriadku, nový fakt, číslo alebo nástroj nie). "
"Odpovedz iba JSON {\"supported\": true} alebo {\"supported\": false}.")
def _ask(system: str, payload: dict, complete=None, max_tokens: int = 400) -> str | None:
from tools.answers.generation.model_client import complete_with_configured_model
try:
response = (complete or complete_with_configured_model)(
[{"role": "system", "content": system}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}],
max_tokens=max_tokens)
return response["choices"][0]["message"]["content"].strip()
except Exception:
return None
def summary(detail: dict, complete=None) -> tuple[str, str]:
"""("Zhrnutie", text): the model's own 2-3 sentences after a passed check (second try with
the check's verdict), else a sentence built from the CRZP keywords — never the copied abstract."""
abstract = detail.get("abstract") or detail.get("abstract_secondary") or ""
keywords = detail.get("keywords", [])
if not abstract:
return "Zhrnutie", _keyword_sentence(detail) if keywords else "CRZP pri tejto práci abstrakt neuvádza."
payload = {"title": detail["title"], "abstract": abstract, "keywords": keywords}
prompt = SUMMARY_PROMPT
if _author_word(detail) == "autorka": # "Autorka navrhla …", not "Autor vyvinul …" for Iryna Kolisnichenko
prompt += " Práca je od autorky (žena): píš „autorka“ a slovesá v ženskom rode („navrhla“, „vytvorila“)."
for attempt in range(2):
text = _ask(prompt if attempt == 0 else prompt + " Drž sa výlučne faktov z abstraktu.",
payload, complete)
if not text or len(text) > 1200:
continue
verdict = _ask(CHECK_PROMPT, {"abstract": abstract, "keywords": keywords, "summary": text}, complete, max_tokens=50)
if verdict and re.search(r'"supported"\s*:\s*true', verdict):
return "Zhrnutie", text
return "Zhrnutie", _keyword_sentence(detail)
def _keyword_sentence(detail: dict) -> str:
keywords = [k for k in detail.get("keywords", []) if len(k) < 40][:6]
kind = WORK_TYPE_LABELS.get(detail.get("work_type"), "práca").capitalize()
if not keywords:
return f"{kind} sa podľa CRZP zaoberá témou „{detail['title']}“."
return f"{kind} „{detail['title']}“ sa zaoberá témami: {', '.join(keywords)}."
# ------------------------------------------------------------------ answers by intent
def _list(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
rows = ranked(question, query, rows)
hidden = 0
if query.topics and not query.title and (not query.people or len(rows) <= PERSON_JUDGED):
# only works whose topic it is (relevance.py), also a person's ("Hládkovi študenti a rozpoznávanie reči":
# all of the person's works are judged, a supervisor's 64 works are no topic list)
rows, hidden = topical(rows, query, complete, limit=PERSON_JUDGED if query.people else TOPICAL_JUDGED)
limit = query.show or LIST_LIMIT
if query.show: # "vypíš prvých 8": the newest first
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
header = f"Našl{'a' if len(rows) == 1 else 'i' if len(rows) < 5 else 'o'} sa {len(rows)} {'práca' if len(rows) == 1 else 'práce' if len(rows) < 5 else 'prác'} ({describe(query)})" + (
f"; {limit} najnovších:" if query.show and len(rows) > limit else ":")
if not found["complete"] and found["total"] > len(found["rows"]):
newest = not query.topics and not query.title and not query.people
header = (f"Hľadaniu zodpovedá {found['total']} výsledkov ({describe(query)}); prehľadaných bolo "
f"{len(found['rows'])} {'najnovších' if newest else 'najrelevantnejších'}, z nich zodpovedá {len(rows)}:")
note = f"\n\nĎalších {plural(hidden)} tento pojem len spomína, nie sú uvedené." if hidden else ""
if len(rows) <= 5 and not query.show:
return header + "\n\n" + "\n\n".join(work_block(r) for r in rows) + note, rows
shown = rows[:limit]
text = header + "\n\n" + "\n".join(work_line(r) for r in shown)
if len(rows) > limit and not query.show:
text += f"\n\nZobrazených je {limit} z {len(rows)}; spresni rok, typ práce alebo tému."
return text + note, shown
TOPICAL_JUDGED = 60 # works of a topic list judged per question (the most relevant first)
PERSON_JUDGED = 160 # all works of one person (a supervisor's) judged for a topic (relevance.MAX_MODEL_ROWS)
def topical(rows: list[dict], query: CrzpQuery, complete=None, limit: int = TOPICAL_JUDGED) -> tuple[list[dict], int]:
"""The ranked works whose topic is the asked one (title, or judged so) first, the not yet judged
after them; works that only mention the topic are left out: (rows, how many left out)."""
from tools.crzp.answering import relevance
verdicts = relevance.judge(rows[:limit], query, complete=complete)
first = [r for r in rows[:limit] if verdicts.get(relevance.work_id(r)) == relevance.TOPIC]
unsure = [r for r in rows[:limit]
if verdicts.get(relevance.work_id(r)) in (relevance.UNSURE, relevance.UNJUDGED, relevance.SKIPPED)]
hidden = len(rows[:limit]) - len(first) - len(unsure)
return first + unsure + rows[limit:], hidden
TYPE_FACET = {"bakalárska": "bakalárska práca", "diplomová": "diplomová práca", "dizertačná": "dizertačná práca",
"habilitačná": "habilitačná práca", "rigorózna": "rigorózna práca"}
def _facet_type(label: str) -> str:
return next((v for k, v in TYPE_FACET.items() if k in label.lower()), label)
def _count(question, query, found, rows) -> tuple[str, list[dict]]:
count, note = len(rows), ""
person = query.people[0] if query.people else None
types = Counter(_kind(r) for r in rows)
years = Counter(r.get("year") for r in rows if r.get("year"))
if found.get("facet_only"):
# CRZP's own total and full facets (texts of one workplace are disjoint: code vs. old written name)
count, types, years = found["total"], Counter(), Counter()
for part in found["parts"]:
years.update(fetch.year_counts(part))
types.update({_facet_type(f["label"]): f["count"] for f in part["facets"].get("Typ práce", [])})
note = " (súhrnný počet z CRZP)"
elif not found["complete"]:
facet = FACET.get(person.role) if person else None
values = [f["count"] for f in found["facets"].get(facet, []) if name_matches(person.name, f["label"])] if facet else []
if values and len(found["texts"]) == 1 and not (query.school or query.unit or len(query.people) > 1):
count, note = sum(values), " (súhrnný počet z CRZP)"
else:
note = (f" (najmenej toľko: hľadanie má {found['total']} výsledkov, prečítaných bolo {len(found['rows'])} "
"a ďalšie môžu tiež zodpovedať)")
text = f"Počet prác ({describe(query)}): **{count}**{note}." + unpublished_note(found, query)
sentence = person_count(query, count, note)
if sentence: # "Daniel Hládek viedol v roku 2024 **5** bakalárskych prác."
text = sentence + unpublished_note(found, query)
defended_place = query.published and not query.people and not query.topics and (query.unit or query.school) \
and len(query.work_types) <= 1
if defended_place: # "Koľko diplomových prác obhájili na KEMT v roku 2022?" -> one sentence
when = f" v roku {query.years[0]}" if len(query.years) == 1 else (f" v rokoch {min(query.years)}–{max(query.years)}" if query.years else "")
text = f"Na {_place(query)}{when} obhájili {works_phrase(count, query.work_types)}{note}." + unpublished_note(found, query)
if (query.published and not query.people and not query.topics and (query.unit or query.school)
and len(query.work_types) == 2 and not found.get("facet_only") and count and query.split != "year"
and len(set(query.years)) <= 1):
# "Koľko bakalárskych a koľko diplomových prác obhájili na KEMT v roku 2024?" -> both in one sentence
when = f" v roku {query.years[0]}" if len(query.years) == 1 else ""
parts = [works_phrase(sum(1 for r in rows if r.get("work_type") == t), [t]) for t in query.work_types]
text = (f"Na {_place(query)}{when} obhájili {parts[0]} a {parts[1]}, spolu {count}{note}."
+ unpublished_note(found, query))
return text, counted_sources(rows)
asked_years = sorted(set(query.years))
compare = len(asked_years) == 2 and (query.split == "year" or COMPARE.search(fold(question)))
if compare and count: # "o koľko viac v 2025 ako v 2024", "koľko v 2024 a koľko v 2025": each year and the change
first, second = asked_years
a, b = years.get(first, 0), years.get(second, 0)
change = "teda rovnako" if a == b else f"teda o {abs(b - a)} {'viac' if b > a else 'menej'}"
if defended_place:
text = f"Na {_place(query)} obhájili v roku {first} {works_phrase(a, query.work_types)} a v roku {second} {b}, {change}"
elif person and len(query.people) == 1:
from tools.answers.presentation.unified import female
verbs = VERBS.get(person.role, VERBS["supervisor"])
text = (f"{display_name(person.name)} {verbs[1] if female(display_name(person.name)) else verbs[0]} v roku {first} "
f"{works_phrase(a, query.work_types)} a v roku {second} {b}, {change}")
elif not query.people and not query.topics and len(query.work_types) <= 1 and (query.unit or query.school):
# "Bolo v roku 2023 na KEMT viac diplomových prác ako v roku 2022?"
text = f"Na {_place(query)} bolo v roku {first} {works_phrase(a, query.work_types)} a v roku {second} {b}, {change}"
else:
rest = describe(query.model_copy(update={"years": []}))
text = f"Prác{' (' + rest + ')' if rest else ''} bolo v roku {first} {a} a v roku {second} {b}, {change}"
text += f"{note}." + unpublished_note(found, query)
yes_no = _yes_no(question, first, second, a, b)
if yes_no:
text = yes_no + " " + text
if query.topics and not query.people and not found.get("facet_only") and count:
from tools.crzp.answering import relevance
named = sum(relevance.names_topic(r, relevance.topic_terms(query)) for r in rows)
if named < count: # CRZP finds the word anywhere in a record: say how many name it in the title
text += (f"\n\nTému „{query.topic_key()}“ má v názve {named} z nich; ostatné ju majú v kľúčových slovách "
"alebo v abstrakte, nemusí to byť ich hlavná téma.")
if count and len(years) > 1 and re.search(r"\bv\s+ktor\w*\s+rok\w*", fold(question)) \
and re.search(r"\bnaj(?:viac|menej)\b", fold(question)):
# "V ktorom roku obhájili na KEMT najviac diplomových prác?": the year first, the counts below
fewest = bool(re.search(r"\bnajmenej\b", fold(question)))
year, n = (min if fewest else max)(years.items(), key=lambda kv: (kv[1], kv[0]))
text = (f"{'Najmenej' if fewest else 'Najviac'} prác ({describe(query.model_copy(update={'years': []}))}) bolo "
f"v roku {year}: {n}.\n\n" + text)
if count and query.split == "year" and len(years) > 1 and not compare: # "rozdeľ to podľa rokov"
by_year = {y: Counter(_kind(r) for r in rows if r.get("year") == y) for y in years} if not found.get("facet_only") else {}
lines = [f"- {y}: {n}" + (" (" + ", ".join(f"{k} {c}" for k, c in by_year[y].most_common()) + ")"
if len(by_year.get(y) or {}) > 1 else "") for y, n in sorted(years.items(), reverse=True)]
return text + "\n\nPodľa rokov (od najnovšieho):\n" + "\n".join(lines), counted_sources(rows)
if count and query.split == "type" and len(types) == 1: # one type only: no one-line list
kind = next(iter(types))
return text + f"\n\nVšetky sú {'práce typu ' + kind if kind not in WORK_TYPE_PLURAL else WORK_TYPE_PLURAL[kind]}.", counted_sources(rows)
if count and query.split == "type" and types: # "rozdeľ na bakalárske a diplomové"
return text + "\n\nPodľa typu práce:\n" + "\n".join(f"- {k}: {v}" for k, v in types.most_common()), counted_sources(rows)
if count and len(types) > 1: # one asked type or year needs no breakdown
text += "\n\n- Podľa typu: " + ", ".join(f"{k} {v}" for k, v in types.most_common())
if count and len(years) > 1 and not compare:
text += ("\n" if len(types) > 1 else "\n\n") + "- Podľa roku: " + ", ".join(
f"{y}: {n}" for y, n in sorted(years.items(), reverse=True))
return text, counted_sources(rows)
WORK_TYPE_PLURAL = {"bakalárska práca": "bakalárske", "diplomová práca": "diplomové", "dizertačná práca": "dizertačné",
"habilitačná práca": "habilitačné", "rigorózna práca": "rigorózne"}
def counted_sources(rows: list[dict]) -> list[dict]:
"""The sources of a count: its few works (at most 10, newest first); a larger count lists none at random
("aké napr." lists them)."""
return sorted(rows, key=lambda r: -(r.get("year") or 0))[:10] if len(rows) <= 10 else []
# "o koľko viac", "rozdiel", "koľko v 2024 a koľko v 2025", "a v roku 2024": each of two years and the change
COMPARE = re.compile(r"\bo\s+kolko\b|\brozdiel\w*|\bviac\b|\bmenej\b|\bporovn\w*|\boproti\b|\bnez\b|\bako\s+v\b"
r"|\ba\s+(?:kolko\s+)?(?:bolo\s+)?v\s+(?:roku\s+)?(?:19|20)\d\d|\ba\s+kolko\b")
def _yes_no(question: str, first: int, second: int, a: int, b: int) -> str:
""""Bolo v roku 2023 viac prác ako v roku 2022?" -> "Áno." / "Nie." (a question, not "koľko")."""
low = fold(question)
if re.search(r"\bkolk\w*|\bpocet\b|\bo\s+kolko\b", low) or not re.search(r"\b(?:viac|menej)\b", low):
return ""
order = [int(y) for y in re.findall(r"\b(?:19|20)\d{2}\b", question)]
if len(order) < 2:
return ""
asked_year = order[0] # "v roku 2025 viac … ako v roku 2024": 2025 is compared
mine, other = (b, a) if asked_year == second else (a, b)
more = bool(re.search(r"\bviac\b", low))
true = mine > other if more else mine < other
return "Áno." if true else "Nie."
def _of(name: str) -> str:
""""Technická univerzita v Košiciach" -> "Technickej univerzity v Košiciach" (genitive)."""
head, _, town = name.partition(" v ")
words = [w[:-1] + "ej" if w.endswith("á") else w[:-1] + "y" if w.endswith("a") else w for w in head.split()]
return " ".join(words) + (" v " + town if town else "")
def _place(query: CrzpQuery) -> str:
""""KEMT FEI Technickej univerzity v Košiciach", "Technickej univerzite v Košiciach" (after "na")."""
if query.unit:
school = _of(SCHOOLS[query.school][0]) if query.school else ""
return (UNITS[query.unit]["label"] + " " + school).strip()
return _at(SCHOOLS[query.school][0]) if query.school else ""
def _at(name: str) -> str:
""""Technická univerzita v Košiciach" -> "Technickej univerzite v Košiciach" (locative, after "na")."""
head, _, town = name.partition(" v ")
words = [w[:-1] + "ej" if w.endswith("á") else w[:-1] + "e" if w.endswith("a") else w for w in head.split()]
return " ".join(words) + (" v " + town if town else "")
def person_count(query: CrzpQuery, count: int, note: str) -> str:
"""One person's count as a sentence: "Daniel Hládek viedol v roku 2024 **5** bakalárskych prác.",
"Juraj Sipko viedol **8** prác na tému „blockchain“."; "" for any other count."""
if len(query.people) != 1 or query.title or query.sids or len(query.work_types) > 1:
return ""
person = query.people[0]
if person.role not in VERBS:
return ""
from tools.answers.presentation.unified import female
name = display_name(person.name)
verb = VERBS[person.role][1 if female(name) else 0]
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 == list(range(years[0], years[-1] + 1)) else " v rokoch " + ", ".join(map(str, years))) if years else ""
place = f" na {_place(query)}" if query.unit or query.school not in (None, "tuke") else ""
topic = f" na tému „{query.topic_key()}“" if query.topics else ""
if not count:
return f"{name} {'ne' + verb}{when}{place} žiadnu prácu{topic}{note}."
phrase = works_phrase(count, query.work_types)
return f"{name} {verb}{when}{place} **{count}**{phrase[len(str(count)):]}{topic}{note}."
def works_phrase(count: int, work_types: list[str]) -> str:
""""1 diplomovú prácu", "3 bakalárske práce", "34 diplomových prác" (the object of "obhájili", "viedol")."""
kind = WORK_TYPE_LABELS[work_types[0]] if len(work_types) == 1 else "záverečná práca"
words = kind.split()
def form(word, long, short): # rhythmic law: "diplomových", but "bakalárskych" after a long syllable
stem = word[:-1]
return stem + (short if re.search(r"[áéíóúýô]", stem[-4:]) else long)
adjectives = words[:-1]
if count == 1:
return "1 " + " ".join([w[:-1] + "ú" if w.endswith("á") else w[:-1] + "u" if w.endswith("a") else w
for w in adjectives] + ["prácu"])
if 2 <= count <= 4:
return f"{count} " + " ".join([form(w, "é", "e") if w.endswith(("á", "a")) else w for w in adjectives] + ["práce"])
return f"{count} " + " ".join([form(w, "ých", "ych") if w.endswith(("á", "a")) else w for w in adjectives] + ["prác"])
def _about(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
unique, seen = [], set()
for row in ranked(question, query, rows): # CRZP sometimes holds one work twice (two records)
key = (fold(row["title"]).rstrip(" ."), row.get("year"), tuple(row.get("authors", [])))
if key not in seen:
seen.add(key)
unique.append(row)
unique = resubmissions(unique) if len(unique) > 1 else unique
if len(unique) <= ABOUT_ALL: # "o čom boli?" about the 4 works of a count: all of them, newest first
rows = sorted(unique, key=lambda r: -(r.get("year") or 0))
else: # many works: the most relevant ones, newest first
rows = sorted(unique[:ABOUT_ALL], key=lambda r: -(r.get("year") or 0))
# The records and the model summaries (and their checks) run two at a time (the model has two slots).
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as pool:
details = list(pool.map(lambda r: fetch.detail(r["sid"]) if r.get("sid") else None, rows))
summaries = list(pool.map(lambda d: summary(d, complete) if d else None, details))
blocks = []
for row, detail, done in zip(rows, details, summaries):
head = (f"**{row['title']}** — {_kind(row)}, {row.get('year') or 'rok neuvedený'}, {university(row)}; "
f"{_author_word(row)} {_names(row.get('authors', []))}")
if re.search(r"oponent|ved[uú]c|[sš]kolite", question.lower()): # "Kto bol oponentom … a o čom je?"
head += f"; vedúci {_names(row.get('supervisors', []))}; oponent {_names(row.get('opponents', []))}"
if detail is None:
blocks.append(head + "\n\nCRZP k tejto práci neposkytuje trvalý odkaz, preto abstrakt nemám.")
continue
_, text = done
blocks.append(head + f"\n\n{text}\n\nZdroj: {_link(row)}")
more = len(unique) > len(rows)
tail = (f"\n\nZodpovedá {plural(len(unique))}; zhrnutých je {len(rows)} najrelevantnejších. Spresni typ práce, "
"rok alebo tému." if more else "")
return "\n\n".join(blocks) + tail, rows
ABOUT_ALL = 8 # "o čom boli?": up to this many works are all summarized
def _keywords(question, query, found, rows) -> tuple[str, list[dict]]:
rows = ranked(question, query, rows)
if len(rows) <= 3:
lines = [f"**{r['title']}** ({_kind(r)}, {r.get('year') or '?'}): " +
(", ".join(r["keywords"]) if r.get("keywords") else "CRZP kľúčové slová neuvádza") + f" · {_link(r)}"
for r in rows]
return "Kľúčové slová (tagy) v CRZP:\n\n" + "\n\n".join(lines), rows
counts = Counter(k.lower() for r in rows for k in r.get("keywords", []))
lines = [f"- {k} ({n})" for k, n in counts.most_common(20)]
return (f"Najčastejšie kľúčové slová (tagy) v {len(rows)} prácach ({describe(query)}):\n\n" + "\n".join(lines),
rows)
ROLE_INSTRUMENTAL = {"author": ("Autorom", "Autormi", "Autorkou"), "supervisor": ("Vedúcim", "Vedúcimi", "Vedúcou"),
"opponent": ("Oponentom", "Oponentmi", "Oponentkou")}
DOCTORAL = ("Školiteľom", "Školiteľmi", "Školiteľkou") # a dissertation has a "školiteľ", a thesis a "vedúci"
def _female_name(name: str) -> bool:
from tools.answers.presentation.unified import female
return female(display_name(name))
def _author_word(row: dict) -> str:
""""autorka" for one female author, "autori" for several, else "autor"."""
authors = row.get("authors") or []
if len(authors) > 1:
return "autori"
from tools.answers.presentation.unified import female
return "autorka" if authors and female(display_name(authors[0])) else "autor"
VERBS = {"supervisor": ("viedol", "viedla", "viedli"), "opponent": ("oponoval", "oponovala", "oponovali"),
"author": ("napísal", "napísala", "napísali")}
SHORT_SCHOOL = {"Technická univerzita v Košiciach": "TUKE", "Slovenská technická univerzita v Bratislave": "STU v Bratislave",
"Univerzita Komenského v Bratislave": "UK v Bratislave",
"Univerzita Pavla Jozefa Šafárika v Košiciach": "UPJŠ v Košiciach", "Žilinská univerzita v Žiline": "UNIZA",
"Univerzita Mateja Bela v Banskej Bystrici": "UMB v Banskej Bystrici",
"Ekonomická univerzita v Bratislave": "EU v Bratislave", "Prešovská univerzita v Prešove": "PU v Prešove",
"Univerzita Konštantína Filozofa v Nitre": "UKF v Nitre",
"Slovenská poľnohospodárska univerzita v Nitre": "SPU v Nitre",
"Trenčianska univerzita Alexandra Dubčeka v Trenčíne": "TnUAD"}
OTHERS_MAX = 7 # "Ďalší s viacerými prácami": at most this many (and everyone tied with the last one)
def short_school(name: str) -> str:
return SHORT_SCHOOL.get(name, name)
def _relation_sentences(query: CrzpQuery, target: str, rows: list[dict]) -> str:
""""Oponentmi habilitačnej práce Daniela Hládka „…“ (2024) boli Roman Jarina, … a Miloš Oravec."
One sentence for one work, a short list for a person's few works."""
from tools.answers.presentation.unified import TYPES, CRZP_TYPES, female, genitive, join
person = query.people[0] if query.people else None
owner = f" {genitive(display_name(person.name))}" if person and person.role in ("author", "any") else ""
def kind(row, case):
names = TYPES.get(CRZP_TYPES.get(row.get("work_type"), row.get("work_type")))
return names[case] if names else _kind(row)
def names(row):
return [display_name(n) for n in row.get(ROLE_FIELD[target], [])]
if len(rows) == 1:
row, who = rows[0], names(rows[0])
if not who:
return f"Pri {kind(row, 2)}{owner} „{row['title']}“ ({row.get('year') or '?'}) CRZP {ROLE_LABEL[target]}ho neuvádza."
woman = len(who) == 1 and female(who[0])
forms = DOCTORAL if target == "supervisor" and row.get("work_type") in ("dissertation", "doctoral_thesis") \
else ROLE_INSTRUMENTAL[target]
role = forms[2 if woman else int(len(who) > 1)]
verb = "boli" if len(who) > 1 else "bola" if woman else "bol"
return f"{role} {kind(row, 1)}{owner} „{row['title']}“ ({row.get('year') or '?'}) {verb} {join(who)}."
head = f"{ROLE_PLURAL[target]} prác{owner}:" if owner else f"{ROLE_PLURAL[target]} prác ({describe(query)}):"
lines = [f"- {kind(r, 0)[:1].upper() + kind(r, 0)[1:]} ({r.get('year') or '?'}) „{r['title']}“: "
f"{join(names(r)) or 'neuvedený'}" for r in rows]
return head + "\n\n" + "\n".join(lines)
def resubmissions(rows: list[dict]) -> list[dict]:
"""One work per author, title and type: a work submitted again within two years (CRZP keeps both
records of a repeated defence) counts once, its newest record kept. Different authors of one
title (the same topic given to two students) stay two works."""
kept, seen = [], {}
for row in sorted(rows, key=lambda r: -(r.get("year") or 0)):
authors = tuple(sorted(fold(a) for a in row.get("authors") or []))
key = (" ".join(fold(row.get("title") or "").rstrip(" .").split()), row.get("work_type"), authors)
years = seen.setdefault(key, [])
if authors and any(abs((row.get("year") or 0) - year) <= 2 for year in years):
continue
years.append(row.get("year") or 0)
kept.append(row)
return kept
def topic_ranking(query: CrzpQuery, rows: list[dict], target: str, complete=None) -> dict:
"""People of the target role by the works whose topic is the asked one (relevance.judge: the title,
else the model over title, keywords, faculty and abstract), each person once per school, newest
work first. The works of the people with the most works are judged first."""
from tools.crzp.answering import relevance
rows = resubmissions(rows)
field = ROLE_FIELD[target]
people: dict = {}
for row in rows:
for name in row.get(field, []):
people.setdefault((display_name(name), university(row)), []).append(row)
ordered, seen = [], set()
for _, works in sorted(people.items(), key=lambda item: (-len(item[1]), item[0])):
for work in works:
if relevance.work_id(work) not in seen:
seen.add(relevance.work_id(work))
ordered.append(work)
ordered += [r for r in rows if relevance.work_id(r) not in seen]
verdicts = relevance.judge(ordered, query, complete=complete)
ranking = []
for (name, school), works in people.items():
topical = [w for w in works if verdicts.get(relevance.work_id(w)) == relevance.TOPIC]
if topical:
ranking.append({"name": name, "school": school, "works": topical, "count": len(topical)})
ranking.sort(key=lambda p: (-p["count"], fold(p["name"])))
values = [verdicts.get(relevance.work_id(r)) for r in rows]
return {"ranking": ranking, "rows": rows, "topic": values.count(relevance.TOPIC),
"failed": values.count(relevance.UNJUDGED), "skipped": values.count(relevance.SKIPPED)}
def ranking_parts(ranking: list[dict]) -> tuple[list[dict], list[dict], list[dict]]:
"""(the leaders, the others shown: at least a third of the leader's count and two works, at most
OTHERS_MAX plus ties, the rest offered)."""
if not ranking:
return [], [], []
top = ranking[0]["count"]
leaders = [p for p in ranking if p["count"] == top]
pool = ranking[len(leaders):]
floor = max(2, -(-top // 3))
others = [p for p in pool if p["count"] >= floor]
if len(others) > OTHERS_MAX:
last = others[OTHERS_MAX - 1]["count"]
others = [p for p in others if p["count"] >= last] if sum(p["count"] >= last for p in others) <= OTHERS_MAX + 3 \
else others[:OTHERS_MAX]
return leaders, others, pool[len(others):]
def _who(person: dict) -> str:
return f"{person['name']} ({short_school(person['school'])})"
def _newest_link(person: dict) -> dict | None:
return next((w for w in sorted(person["works"], key=lambda w: -(w.get("year") or 0)) if w.get("url")), None)
def _topic_relation(question, query, rows, target, complete=None) -> tuple[str, list[dict]]:
""""Najviac prác na tému „blockchain“ viedol Kristián Košťál (STU v Bratislave) – 36." The others with
several works follow, the rest is offered; one source per person shown (the newest work)."""
from tools.answers.presentation.unified import female, join
data = topic_ranking(query, rows, target, complete)
ranking, topic = data["ranking"], query.topic_key()
conditions = describe(query.model_copy(update={"topics": [], "alternatives": [], "phrases": []}))
where = f" ({conditions})" if conditions else ""
if not ranking:
return (f"V CRZP som nenašiel prácu, ktorej témou je „{topic}“{where}; nájdené práce tento pojem len "
"spomínajú." if not data["failed"] else
"Posúdenie, ktoré práce sú naozaj o tejto téme, momentálne nie je dostupné. Skús otázku o chvíľu."), []
leaders, others, rest = ranking_parts(ranking)
verbs = VERBS[target]
count = leaders[0]["count"]
if len(leaders) == 1:
verb = verbs[1] if female(leaders[0]["name"]) else verbs[0]
text = f"Najviac prác na tému „{topic}“{where} {verb} {_who(leaders[0])} – {count}."
else:
text = f"Najviac prác na tému „{topic}“{where} {verbs[2]} {join([_who(p) for p in leaders])} – po {count}."
if others:
text += "\n\nĎalší s viacerými prácami na túto tému:\n" + "\n".join(f"- {_who(p)} – {p['count']}" for p in others)
text += (f"\n\nZapočítané sú práce, ktorých témou je „{topic}“ ({data['topic']} z {plural(len(data['rows']))}); "
+ ("ostatné tento pojem len spomínajú." if not data["skipped"] else
"ostatné ho len spomínajú alebo patria ľuďom s menej prácami, pri ktorých sa téma neposudzovala "
f"({data['skipped']})."))
if data["failed"]:
text += " Časť prác sa nepodarilo posúdiť; započítané sú len posúdené."
shown = [*leaders, *others]
extras = _extras.get()
if extras is not None:
extras["entities"] = [{"name": p["name"], "school": p["school"], "source": "crzp", "role": target,
**({"url": _newest_link(p)["url"]} if _newest_link(p) else {})} for p in shown]
if rest:
extras["rest"] = [{"name": f"{_who(p)} – {p['count']}", "source": "crzp", "text": "",
"urls": [w["url"] for w in [_newest_link(p)] if w]} for p in rest]
extras["offer"] = (f"Chceš vidieť ďalších (" + str(len(rest)) + ")?")
return text, [w for w in (_newest_link(p) for p in shown) if w]
def _sources(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
""""málo zdrojov" after "Kto viedol najviac prác o X?": the works of every person shown."""
target = query.target_role if query.target_role in ROLE_FIELD else "supervisor"
if not query.topics or query.people:
return _list(question, query, found, rows, complete)
data = topic_ranking(query, rows, target, complete)
leaders, others, _ = ranking_parts(data["ranking"])
blocks, used = [], []
for person in [*leaders, *others]:
works = sorted(person["works"], key=lambda w: -(w.get("year") or 0))[:5]
more = f" (zobrazených 5 najnovších z {person['count']})" if person["count"] > 5 else ""
blocks.append(f"**{_who(person)}**{more}\n" + "\n".join(f"- „{w['title']}“ ({_kind(w)}, {w.get('year') or '?'})"
for w in works))
used += [w for w in works if w.get("url")]
if not blocks:
return f"K téme „{query.topic_key()}“ nemám ďalšie práce.", []
extras = _extras.get()
if extras is not None: # "a z akých škôl sú?" asks about these people, not about the authors listed
extras["entities"] = [{"name": p["name"], "school": p["school"], "source": "crzp", "role": target,
**({"url": _newest_link(p)["url"]} if _newest_link(p) else {})} for p in [*leaders, *others]]
return f"Práce na tému „{query.topic_key()}“ ľudí z predchádzajúcej odpovede:\n\n" + "\n\n".join(blocks), used
def _relation(question, query, found, rows, complete=None) -> tuple[str, list[dict]]:
target = query.target_role
if query.title: # the asked work itself, if CRZP has that exact title
exact = [r for r in rows if fold(r["title"]).rstrip(" .") == fold(query.title).rstrip(" .")]
rows = exact or rows
aggregate = re.search(r"najcast|najviac|najcastejs|kolk|pocet", fold(question))
if len(rows) <= 3 or query.people and len(rows) <= 8 and not aggregate: # a person's few works: each with its role
rows = sorted(rows, key=lambda r: -(r.get("year") or 0))
return _relation_sentences(query, target, rows), rows
if not query.people: # "Kto viedol práce o X?": the target role over the found works
if (found.get("facet_only") and target == "supervisor" and not found["complete"]
and all(part["facets"].get("Školiteľ") for part in found["parts"])): # only CRZP's supervisor facet
counts = Counter()
for part in found["parts"]:
counts.update({f["label"]: f["count"] for f in part["facets"].get("Školiteľ", [])})
lines = [f"- {display_name(n)} – {c}" for n, c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))[:15]]
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}) podľa súhrnu CRZP z {plural(found['total'])} "
"(počty zahŕňajú aj práce, ktoré tému len spomínajú):\n\n" + ("\n".join(lines) or "- CRZP ich neuvádza")), \
ranked(question, query, rows)[:len(lines)]
if query.topics:
return _topic_relation(question, query, rows, target, complete)
counts = Counter((display_name(n), university(r)) for r in resubmissions(rows) for n in r.get(ROLE_FIELD[target], []))
ranking = [{"name": n, "school": sch, "count": c, "works": [r for r in rows if any(display_name(x) == n for x in r.get(ROLE_FIELD[target], []))]}
for (n, sch), c in sorted(counts.items(), key=lambda i: (-i[1], i[0]))]
lines = [f"- {_who(p)} – {p['count']}" for p in ranking[:15]]
return (f"{ROLE_PLURAL[target]} prác ({describe(query)}; spočítané z {plural(len(rows))}):\n\n" +
("\n".join(lines) or "- CRZP ich neuvádza")), [w for w in (_newest_link(p) for p in ranking[:15]) if w]
person = query.people[0]
source = person.role if person.role in ROLE_FIELD else max(
ROLE_FIELD, key=lambda role: sum(bool(people_in_role(r, person.name, role)) for r in rows))
names = sorted({n for r in rows for n in people_in_role(r, person.name, source)})
pairs = graph.relation(rows, names, source, target)
lines = [f"- {display_name(n)} ({plural(c)})" for n, c in pairs[:15]]
conditions = describe(query.model_copy(update={"people": []}))
text = (f"{ROLE_PLURAL[target]} prác, pri ktorých je {display_name(names[0]) if names else person.name} "
f"{ROLE_LABEL[source]} ({conditions + '; ' if conditions else ''}{plural(len(rows))}):\n\n" + ("\n".join(lines) or "- CRZP ich neuvádza"))
field = ROLE_FIELD[target]
newest = [] # one source per person shown: the newest work where he or she had the role
for name, _ in pairs[:15]:
work = next((r for r in sorted(rows, key=lambda r: -(r.get("year") or 0)) if name in r.get(field, []) and r.get("url")), None)
if work and work not in newest:
newest.append(work)
return text, newest or rows
def university(row: dict) -> str:
"""The school without its faculty/department ("Slovenská technická univ. v Bratislave FEI ÚMIKT")."""
name = row.get("school") or "škola neuvedená"
folded = fold(name).replace("univ.", "univerzita").replace("p.j. safarika", "pavla jozefa safarika")
folded = folded.replace("a.dubceka", "alexandra dubceka")
known = next((full for full, part in SCHOOLS.values() if part in folded), None)
if known:
return known
town = re.match(r"^(.*?\bv[eo]?\s+[^\W\d_]+)", name) # "… univerzita v Trnave FF KSJ" -> up to the town
return town.group(1) if town else name
def _faculty(raw: str, name: str) -> str:
"""The part of a raw CRZP school after the university's town ("… v Bratislave FEI ÚMIKT" -> "FEI ÚMIKT")."""
town = fold(name.split()[-1])
at = fold(raw).find(town)
return raw[at + len(town):] if at >= 0 else ""
def _schools(question, query, found, rows) -> tuple[str, list[dict]]:
""""Z akých škôl boli tí študenti?": schools of the found works, with their workplaces."""
plural = lambda c: f"{c} {'práca' if c == 1 else 'práce' if c < 5 else 'prác'}"
by_school: dict[str, Counter] = {}
for r in rows:
unit = unit_label(r) if university(r) == r.get("school") else _faculty(r.get("school") or "", university(r))
by_school.setdefault(university(r), Counter())[unit.strip(" ,") or ""] += 1
order = sorted(by_school.items(), key=lambda i: (-sum(i[1].values()), i[0]))
lines = []
for name, units in order[:20]:
# units written only as codes ("01000 01140" at other schools) name nothing: not shown
parts = [f"{u} {c}" for u, c in units.most_common() if u and not re.fullmatch(r"[\d\s,]+", u)][:4]
lines.append(f"- {name} ({plural(sum(units.values()))}" + (": " + "; ".join(parts) if parts else "") + ")")
more = f"\n- … a ďalšie ({len(order) - 20})" if len(order) > 20 else ""
return (f"Školy prác v CRZP ({describe(query)}; {plural(len(rows))}):\n\n"
+ "\n".join(lines) + more), ranked(question, query, rows)[:10]
GENERIC_TAGS = {fold(w.strip()) for w in """detekcia, analýza, systém, aplikácia, návrh, implementácia, model, modelovanie,
metóda, metódy, dáta, údaje, databáza, simulácia, optimalizácia, riadenie, meranie, testovanie, vývoj, softvér, hardvér,
internet, web, python, java, c#, matlab, korpus, korpus dát, dataset, klasifikácia, algoritmus, algoritmy""".split(",")}
def specific_tags(work: dict) -> list[str]:
"""The work's keywords most likely to find related works: multi-word and non-generic first."""
tags = [k for k in work.get("keywords", []) if fold(k) not in GENERIC_TAGS]
return sorted(tags, key=lambda k: (-min(len(k.split()), 3), -len(k)))
def _similar(question, query, found, rows) -> tuple[str, list[dict]]:
work = ranked(question, query, rows)[0]
if query.title:
work = next((r for r in rows if fold(r["title"]).rstrip(" .") == fold(query.title).rstrip(" .")), work)
searched, candidates = [], []
# Most specific tags first; a tag only this work has ("rasa forms") gives nothing,
# so the next one is searched until five related works are found (at most four searches).
for term in specific_tags(work)[:4]:
try:
candidates += fetch.search(term)["rows"]
except CrzpUnavailable:
break
searched.append(term)
if len(graph.shared_keywords(work, candidates)) >= 5:
break
pairs = graph.shared_keywords(work, candidates)
if len(pairs) > 1: # equal numbers of shared tags: the closer title and tags first (cross-encoder)
from tools.retrieval import rerank
profile = work["title"] + ". " + ", ".join(work.get("keywords", []))
scores = rerank.scores(profile, [c["title"] + ". " + ", ".join(c.get("keywords", [])) for c, _ in pairs]) or [0] * len(pairs)
pairs = [p for _, p in sorted(zip(scores, pairs), key=lambda item: (-len(item[1][1]), -item[0]))]
pairs = pairs[:5]
if not pairs:
return (f"K práci **{work['title']}** som medzi prácami s jej kľúčovými slovami nenašiel inú so spoločnými "
f"kľúčovými slovami. · {_link(work)}"), [work]
lines = [f"- {_names(c.get('authors', []))} — {university(c)}: „{c['title']}“ ({_kind(c)}, {c.get('year') or '?'}); "
f"spoločné: {', '.join(shared)} · {_link(c)}" for c, shared in pairs]
text = (f"Práce so spoločnými kľúčovými slovami CRZP ako **{work['title']}** ({_link(work)}); porovnané s prácami "
f"nájdenými podľa kľúčových slov „{'“, „'.join(searched)}“:\n\n" + "\n".join(lines))
return text, [work] + [c for c, _ in pairs]
# ------------------------------------------------------------------ entry point
def _result(question: str, status: str, text: str, *, reason=None, rows=(), complete=None, truncated=False,
reasons=(), count=None) -> dict:
urls = list(dict.fromkeys(r["url"] for r in rows if r.get("url")))
result = {"status": status, "reason": reason, "accepted_for_delivery": status in ("ok", "no_answer", "ambiguous"),
"answer": text, "source_urls": urls, "claims": [], "index_version": None,
"complete": complete, "truncated": truncated, "truncation_reasons": list(reasons),
"delivery_check": {"layer": {"ok": "delivery", "ambiguous": "planning"}.get(status, "retrieval")
if reason not in ("invalid_context", "expired_context") else "context",
"code": ("partial" if truncated else "complete") if status == "ok"
else "evidence_not_found" if status == "no_answer"
else "clarification_required" if status == "ambiguous" else "unavailable",
"request_fingerprint": fingerprint(question, ENGINE)}}
if count is not None:
result["count"] = count
return result
def answer(question: str, *, limit: int = 5, complete=None, context_token: str | None = None) -> dict:
key = (question.strip(), limit, context_token or "")
with _cache_lock:
hit = _cache.get(key)
if hit and time.monotonic() - hit[0] < CACHE_SECONDS and complete is None:
return hit[1]
result = _answer(question.strip(), complete, context_token)
if result["status"] == "ok" and complete is None:
with _cache_lock:
_cache[key] = (time.monotonic(), result)
while len(_cache) > 256:
_cache.popitem(last=False)
return result
def other_roles(rows: list[dict], query: CrzpQuery) -> str:
""""Hládek viedol 0 bakalárok v 2023" may still be his opponent role in such works."""
if not query.people or query.people[0].role not in ROLE_FIELD:
return ""
person = query.people[0]
relaxed = query.model_copy(deep=True)
relaxed.people[0].role = "any"
roles = Counter(role for r in rows if keep(r, relaxed) for role, field in ROLE_FIELD.items()
if role != person.role and any(name_matches(person.name, n) for n in r.get(field, [])))
if not roles:
return ""
parts = ", ".join(f"{ROLE_LABEL[role]} pri {c} {'práci' if c == 1 else 'prácach'}" for role, c in roles.most_common())
return f"\n\nS rovnakými ostatnými podmienkami je {person.name} v CRZP v inej role: {parts}."
def _without_suffix(query: CrzpQuery, texts: list[str]) -> list[str]:
"""Searched texts without the school or workplace appended to each of them."""
return list(dict.fromkeys(strip_suffix(query, t) for t in texts))
def _answer(question: str, complete=None, context_token: str | None = None) -> dict:
previous = None
if context_token:
try:
previous = context.restore(context_token)
except context.ContextError as error:
return _result(question, "error", "Kontext predchádzajúcej otázky už neplatí; polož otázku celú "
"(meno, téma, rok).", reason=str(error))
if complete is None:
fetch.prepare() # CRZP home page loads while the model reads the question
query = understand(question, complete=complete)
if query.intent == "refused":
return _result(question, "no_answer", "Pokyny na zmenu pravidiel nevykonávam a celý obsah CRZP, prihlasovacie "
"údaje ani systémové nastavenia nevypisujem. Opýtaj sa na konkrétnu prácu, osobu, školu, tému "
"alebo rok.", reason="request_out_of_scope")
if previous:
query, clarification = context.follow_up(question, query, previous)
if clarification:
result = _result(question, "ambiguous", clarification, reason="clarification_required")
if clarification.startswith("Ktorú prácu"): # the reply ("2") answers this question
if query.intent == "list" and re.search(r"\bo com\b|\bo com je\b", fold(question)):
query.intent = "about"
result["conversation_context"] = context.reissue(question, query, previous) or {
"token": context_token, "work_options": [], "meeting_options": []}
else:
result["conversation_context"] = {"token": context_token, "work_options": [], "meeting_options": []}
return result
result = _answer_query(question, query, complete)
if result["status"] in ("ok", "no_answer", "ambiguous") and result.get("reason") != "request_out_of_scope":
conversation = context.issue(question, result.pop("_asked", query), result.pop("_shown", []),
result.pop("_options", None), matched=result.pop("_matched", None))
if conversation:
result["conversation_context"] = conversation
result.pop("_shown", None), result.pop("_asked", None), result.pop("_options", None), result.pop("_matched", None)
return result
def _answer_query(question: str, query: CrzpQuery, complete=None) -> dict:
asked = query.model_copy(deep=True) # before find() adapts names and roles: the follow-up repeats this
if not query.search_text():
return _result(question, "no_answer", "Na vyhľadanie v CRZP uveď meno študenta, vedúceho alebo oponenta, "
"názov práce alebo tému.", reason="missing_search_terms")
try:
found, rows = find(query)
if found is None:
return _result(question, "no_answer", "Otázke nezodpovedá žiadne vyhľadávanie v CRZP.",
reason="missing_search_terms")
if not rows and query.intent == "count" and query.people and (query.school or query.unit):
# "Koľko prác viedol Hládek na Žilinskej univerzite?": 0, and where the person's works are
person = query.people[0]
elsewhere = Counter(university(r) for r in found["rows"] if people_in_role(r, person.name, person.role))
from tools.answers.presentation.unified import female
name = display_name(person.name)
verb = {"supervisor": "neviedol", "opponent": "neoponoval"}.get(person.role, "nemá")
verb = verb + "a" if verb != "nemá" and female(name) else verb
text = f"Podľa registra záverečných prác {name} na {_place(query)} {verb} žiadnu prácu."
if elsewhere:
text += " Práce, pri ktorých je uvedený, sú z " + ", ".join(
f"{_of(school)} ({n})" for school, n in elsewhere.most_common(3)) + "."
result = _result(question, "ok", text, complete=found["complete"], count=0)
result["_shown"], result["_asked"], result["_matched"] = [], asked, 0
return result
if not rows:
tried = "„" + "“, „".join(_without_suffix(query, query.searched)) + "“"
result = _result(question, "no_answer",
f"V CRZP som nenašiel prácu, ktorá by zodpovedala otázke ({describe(query)}). "
f"Hľadal som {tried}; žiadny nájdený záznam nespĺňa všetky podmienky. "
"CRZP hľadá presné tvary slov, preto to nemusí znamenať, že taká práca neexistuje."
+ other_roles(found["rows"], query),
reason="no_matching_record", complete=found["complete"])
result["_shown"], result["_asked"] = [], asked
return result
asked_who = clarification(rows, query)
if asked_who:
result = _result(question, "ambiguous", asked_who[0], reason="clarification_required")
result["_shown"], result["_asked"], result["_options"] = [], asked, asked_who[1]
return result
# The exact number of works meeting the conditions (every row read, or CRZP's own total of a search
# whose read rows all qualify); an "at least" reading has none and is never compared.
hidden = 0
if query.intent == "count" and query.topics and query.people and not query.title and len(rows) <= PERSON_JUDGED:
rows, hidden = topical(ranked(question, query, rows), query, complete, limit=PERSON_JUDGED)
exact = len(rows) if found["complete"] else (found["total"] if found.get("facet_only") else None)
changed = (query.previous_count is not None and exact is not None and exact != query.previous_count)
handler = {"list": _list, "count": _count, "keywords": _keywords, "relation": _relation,
"similar": _similar, "schools": _schools, "sources": _sources}.get(query.intent)
extras = {}
marker = _extras.set(extras)
try:
if query.intent in ("about", "relation", "sources", "list"): # these may ask the model
body, used = (_about if query.intent == "about" else handler)(question, query, found, rows, complete)
else:
body, used = handler(question, query, found, rows)
finally:
_extras.reset(marker)
except CrzpUnavailable:
return _result(question, "error", "CRZP momentálne neodpovedá alebo obmedzil počet požiadaviek. Skús to o chvíľu.",
reason="crzp_unavailable")
if hidden and query.intent == "count":
body += (f"\n\nĎalších {plural(hidden)} tento pojem len spomína (napr. v kľúčových slovách), nie je ich hlavnou "
"témou; nie sú započítané.")
if getattr(query, "relaxed_author", False) and not (query.people[0].role == "supervisor" and query.intent == "count"):
# (a count of supervised works says "X viedol …" itself)
led = query.people[0].role == "supervisor"
body = (f"{query.people[0].name} nie je v CRZP autorom žiadnej z nájdených prác; uvedené sú práce, "
+ ("ktoré viedol" + ("a" if _female_name(query.people[0].name) else "") if led
else "pri ktorých je školiteľom alebo oponentom") + ".\n\n" + body)
if query.intent in ("about", "keywords", "list"):
body += namesakes(used, query)
if query.unverified_only:
body = (f"Výraz „{query.topic_key()}“ sa v CRZP nenašiel; uvedené práce sú nájdené pod navrhnutým "
f"príbuzným výrazom „{'“, „'.join(query.unverified_only)}“ (návrh, nie overené synonymum).\n\n" + body)
if changed: # the count and the list behind it never contradict each other unexplained
body += f"\n\nOd predchádzajúcej odpovede sa počet nájdených prác zmenil z {query.previous_count} na {exact}."
body += data_date(query, found)
truncated = not found["complete"] and not found.get("facet_only") # a CRZP total needs no read rows
reasons = ["crzp_result_limit"] if truncated else []
body += "\n\nZdroj: Centrálny register záverečných prác (CRZP), metadáta záznamov."
result = _result(question, "ok", body, rows=used, complete=not truncated, truncated=truncated, reasons=reasons,
count=len(rows) if query.intent == "count" else None)
result["_shown"], result["_asked"], result["_matched"] = used, asked, exact
result["_entities"] = extras.get("entities") or displayed_entities(query, body, used, rows)
if extras.get("rest"): # "Chceš vidieť ďalších?": the rest of a ranking, kept by the combined answer
result["_rest"], result["_offer"] = extras["rest"], extras["offer"]
return result
DATA_AGE = 86400 # data of the current year older than this get their date in the answer
def data_date(query: CrzpQuery, found: dict) -> str:
""""Údaje sú k 14. 11. 2026." for a count, list or ranking of the current year whose data were read more than
a day ago (works of this year are still being added); nothing otherwise."""
fetched = found.get("fetched_at")
if (query.intent not in ("count", "list", "relation", "sources") or not fetched
or time.localtime().tm_year not in query.years or time.time() - fetched <= DATA_AGE):
return ""
day = time.localtime(fetched)
return f"\n\nÚdaje sú k {day.tm_mday}. {day.tm_mon}. {day.tm_year}."
def _school_of(name: str, rows: list[dict], field: str) -> str:
schools = Counter(university(r) for r in rows if any(display_name(n) == name for n in r.get(field, [])))
return schools.most_common(1)[0][0] if schools else "škola neuvedená"
def displayed_entities(query: CrzpQuery, body: str, used: list[dict], rows: list[dict]) -> list[dict]:
"""The people the answer shows, in its order, with their school ("a z akých škôl sú?",
"a čo robil prvý z nich?"): the counted supervisors/opponents, else the authors of the shown works."""
if query.intent == "relation" and query.target_role in ROLE_FIELD and not query.people:
field = ROLE_FIELD[query.target_role]
names = re.findall(r"^- (.+?) \(\d+ pr[aá]c\w*\)$", body, re.M)
if names:
return [{"name": n, "school": _school_of(n, rows, field), "source": "crzp", "role": query.target_role}
for n in names]
entities, text = [], fold(body)
for row in used:
for author in row.get("authors", [])[:1]:
# only what the text shows: a count names no work, its sources are links ("tretí z nich" is not one of them)
if fold(display_name(author)) in text or fold(row["title"][:40]) in text:
entities.append({"name": display_name(author), "school": university(row), "source": "crzp",
"role": "author", "sid": row.get("sid"), "title": row["title"]})
return entities