dp-zp-agent/tools/crzp/answering/relevance.py
jp170na e3fa2be4f4 opravy zo sady
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:21:06 +01:00

201 lines
10 KiB
Python

"""Is the asked topic a work's own topic, or only mentioned in it?
CRZP finds a word anywhere in a record (title, keywords, abstract), so a work found
for "blockchain" may be about the history of accounting and only list "blockchain"
among its keywords. Questions over the works of a topic ("Kto viedol najviac prác o
blockchaine?", the works listed for a topic) count a work only when the topic is
its topic:
1. its title names the topic (or a term that is the topic itself, RELATED:
"smart kontrakt", "DeFi" for blockchain) -> topic, no model;
2. otherwise the model judges the title, the author's keywords and the school and
faculty (a law or economics faculty vs. informatics) -> "tema" / "zmienka" /
"nesuvisi" / "neiste"; a keyword alone, or its position, decides nothing;
3. "neiste" works are judged again with their abstract (the CRZP record detail),
at most MAX_DETAILS per question; a work still unsure counts as a mention.
The code accepts "tema" only when a topic term really is in the judged text. A
verdict is stored once per topic and work (crzp.sqlite, table relevance) and never
asked again; a failed model call stores nothing (the work stays unjudged).
"""
from __future__ import annotations
import json
import os
import re
from concurrent.futures import ThreadPoolExecutor
from tools.crzp.source.parse import fold
TOPIC, MENTION, UNRELATED, UNSURE = "topic", "mention", "unrelated", "unsure"
UNJUDGED, SKIPPED = "unjudged", "skipped" # the model failed / over the per-question budget
BATCH = 40 # works judged in one model call
MAX_MODEL_ROWS = int(os.getenv("CRZP_RELEVANCE_ROWS", "160")) # works judged by the model per question
MAX_DETAILS = int(os.getenv("CRZP_RELEVANCE_DETAILS", "20")) # abstracts read per question
# Terms that are the topic itself when a title names them (reviewed by hand; never searched).
RELATED = {
"blockchain": ["smart kontrakt", "smart contract", "inteligentné zmluvy", "ethereum", "hyperledger", "defi",
"decentralizovaná aplikácia", "decentralized application", "dapp", "web3", "nft", "dao",
"distributed ledger", "distribuovaná databáza transakcií", "kryptografický reťazec", "solana"],
"chatbot": ["dialógový systém", "konverzačný agent", "četbot", "chatbot"],
"rag": ["retrieval augmented generation", "retrieval-augmented"],
"llm": ["jazykový model", "language model", "gpt"],
}
PROMPT_VERSION = "v2" # part of the stored verdict key: a changed prompt never reuses older verdicts
PROMPT = ("Posudzuješ záverečné práce. Pre každú očíslovanú prácu rozhodni, či je „{topic}“ jej predmetom.\n"
"- \"tema\": predmetom práce (podľa názvu) je „{topic}“ alebo jeho priama technická súčasť či využitie "
"(navrhuje, implementuje, skúma alebo hodnotí ho, alebo systém postavený na ňom);\n"
"- \"zmienka\": predmetom práce je iný jav (napr. ekonomický, finančný, právny, spoločenský alebo iný "
"produkt či trh) a „{topic}“ je len súvisiaci pojem, napr. v kľúčových slovách;\n"
"- \"nesuvisi\": s témou nesúvisí;\n"
"- \"neiste\": z uvedených údajov sa to nedá rozhodnúť.\n"
"Rozhoduj podľa názvu, kľúčových slov, fakulty a abstraktu, ak je uvedený. Samotný výskyt pojmu v "
"kľúčových slovách nestačí: ak názov hovorí o inom predmete, je to zmienka, pokiaľ abstrakt nepotvrdí opak. "
"Odpovedz iba JSON objektom, napr. {{\"1\": \"tema\", \"2\": \"zmienka\"}}.")
VERDICTS = {"tema": TOPIC, "zmienka": MENTION, "nesuvisi": UNRELATED, "nesúvisí": UNRELATED, "neiste": UNSURE,
"neisté": UNSURE}
def work_id(row: dict) -> str:
"""The work's CRZP id, else its title, year and first author."""
if row.get("sid"):
return row["sid"]
authors = row.get("authors") or [""]
return f"{' '.join(fold(row.get('title') or '').split())}|{row.get('year')}|{fold(authors[0])}"
def topic_terms(query) -> list[str]:
"""The asked topic, its searched alternatives and the related terms that are the topic itself."""
topic = query.topic_key()
terms = [topic, *(query.topics[:1]), *query.alternatives, *RELATED.get(" ".join(fold(topic).split()), [])]
return list(dict.fromkeys(t for t in terms if t and t.strip()))
def _words(text: str) -> list[str]:
return re.findall(r"[a-z0-9]+", fold(text))
def acronym(term: str) -> bool:
""""WER", "RAG", "NFT": an upper-case abbreviation, matched in its own letter case (never "Wer", "rag")."""
term = term.strip()
return 2 <= len(term) <= 6 and term.isupper() and term.isalnum()
def mentions(text: str, term: str, case: bool = True) -> bool:
"""Every word of the term in the text, up to inflection ("blockchainu", "smart kontraktov"); in a
title (case=True) an abbreviation in upper case only ("WER" is not the German "Wer"); keywords are
often written in lower case ("rag"), so they are compared with case=False."""
if acronym(term) and case:
return bool(re.search(r"(?<![\w])" + re.escape(term.strip()) + r"(?:-?[a-zá-ž]{1,3})?(?![\w])", text))
words = _words(text)
wanted = _words(term)
def same(word: str, asked: str) -> bool:
if len(asked) <= 4: # "defi", "nft", "rag": the word itself or a short ending, never "definícia"
return word.startswith(asked) and len(word) - len(asked) <= 2
stem = asked[:len(asked) - 1] if len(asked) <= 6 else asked[:len(asked) - 2]
return word.startswith(stem)
return bool(wanted) and all(any(same(w, t) for w in words) for t in wanted)
def names_topic(row: dict, terms: list[str]) -> bool:
"""The title names the topic: a phrase's words next to each other ("rozpoznávanie nenávistnej reči" does not
name "rozpoznávanie reči"; such a title goes to the model)."""
title = row.get("title") or ""
return any(mentions(title, term) and (acronym(term) or len(_words(term)) < 2 or adjacent(title, term))
for term in terms)
def adjacent(text: str, term: str) -> bool:
words, wanted = _words(text), _words(term)
return any(all(mentions(words[i + j], wanted[j], case=False) for j in range(len(wanted)))
for i in range(len(words) - len(wanted) + 1))
def _line(number: int, row: dict, abstract: str | None) -> str:
keywords = ", ".join((row.get("keywords") or [])[:12]) or "neuvedené"
line = f"{number}. Názov: {row.get('title')} | Kľúčové slová: {keywords} | Škola: {row.get('school') or 'neuvedená'}"
return line + (f" | Abstrakt: {' '.join(abstract.split())[:900]}" if abstract else "")
def _ask(topic: str, batch: list[tuple[dict, str | None]], complete) -> dict[int, str]:
"""{position: verdict} of one model call; {} when the model fails."""
from tools.answers.generation.model_client import complete_with_configured_model
lines = "\n".join(_line(i, row, abstract) for i, (row, abstract) in enumerate(batch, 1))
try:
response = (complete or complete_with_configured_model)(
[{"role": "system", "content": PROMPT.format(topic=topic)}, {"role": "user", "content": lines}],
max_tokens=12 * len(batch) + 60)
text = response["choices"][0]["message"]["content"]
found = json.loads(re.search(r"\{[\s\S]*\}", text).group(0))
except Exception:
return {}
return {int(k): VERDICTS[str(v).strip().lower()] for k, v in found.items()
if str(k).strip().isdigit() and str(v).strip().lower() in VERDICTS and 1 <= int(k) <= len(batch)}
def _judge(topic: str, items: list[tuple[dict, str | None]], complete) -> dict[str, str]:
batches = [items[i:i + BATCH] for i in range(0, len(items), BATCH)]
verdicts: dict[str, str] = {}
with ThreadPoolExecutor(max_workers=2) as pool: # the school model has two slots
for batch, answer in zip(batches, pool.map(lambda b: _ask(topic, b, complete), batches)):
for position, (row, _) in enumerate(batch, 1):
if position in answer:
verdicts[work_id(row)] = answer[position]
return verdicts
def judge(rows: list[dict], query, *, complete=None, store=None, detail=None) -> dict[str, str]:
"""{work_id: TOPIC | MENTION | UNRELATED | UNSURE | UNJUDGED | SKIPPED} for the given works (the most
important first: the model budget goes to the first ones, the rest is SKIPPED)."""
from tools.crzp import fetch
store = store or fetch.store()
detail = detail or fetch.detail
topic = query.topic_key()
key = PROMPT_VERSION + "|" + " ".join(fold(topic).split())
terms = topic_terms(query)
verdicts, rest = {}, []
for row in rows:
if names_topic(row, terms):
verdicts[work_id(row)] = TOPIC
else:
rest.append(row)
try:
stored = store.get_verdicts(key, [work_id(r) for r in rest])
except Exception:
stored = {}
verdicts.update({w: v for w, v in stored.items()})
open_rows = [r for r in rest if work_id(r) not in stored]
asked, over = open_rows[:MAX_MODEL_ROWS], open_rows[MAX_MODEL_ROWS:]
first = _judge(topic, [(r, None) for r in asked], complete) if asked else {}
unsure = [r for r in asked if first.get(work_id(r)) == UNSURE and r.get("sid")][:MAX_DETAILS]
abstracts = {}
for row in unsure:
try:
abstracts[work_id(row)] = (detail(row["sid"]) or {}).get("abstract") or ""
except Exception:
abstracts[work_id(row)] = ""
second = _judge(topic, [(r, abstracts[work_id(r)]) for r in unsure if abstracts.get(work_id(r))],
complete) if unsure else {}
new = {}
for row in asked:
wid = work_id(row)
verdict = second.get(wid) or first.get(wid)
if verdict is None:
verdicts[wid] = UNJUDGED # the model failed: nothing stored, asked again next time
continue
judged_text = " ".join([row.get("title") or "", *(row.get("keywords") or []), abstracts.get(wid, "")])
if verdict == TOPIC and not any(mentions(judged_text, t, case=False) for t in terms):
verdict = UNSURE # the model may not promote a work whose judged text lacks the topic
if verdict == UNSURE and wid in second:
verdict = MENTION # judged with the abstract and still unsure: not the topic
verdicts[wid] = verdict
if verdict != UNSURE or not row.get("sid"): # unsure without an abstract to read stays so
new[wid] = verdict
for row in over:
verdicts[work_id(row)] = SKIPPED
if new:
try:
store.put_verdicts(key, new)
except Exception:
pass
return verdicts