dp-zp-agent/tools/answer_evaluation/render_answer.py
2026-11-03 13:36:42 +01:00

74 lines
4.0 KiB
Python

"""Render only validated structured facts; never infer facts or read gold."""
from copy import deepcopy
import re
from tools.graphrag.graphrag import WORK_TYPE_LABELS
from .presentation import fact_sentences, no_answer_text
def render_graph_answer(answer: dict, context: dict) -> dict:
out = deepcopy(answer)
lines = []
if out['status'] == 'ok':
comparison = context.get('academic_year_comparison')
if comparison:
people = comparison.get('people', [])
witnessed = [{claim['year'] for claim in out['claims']
if claim.get('person') == person and claim.get('year') is not None} for person in people]
visible = set.intersection(*witnessed) if witnessed else set()
years = sorted(visible & set(comparison.get('shared_years', [])))
if years:
label = ('Spoločný evidovaný rok je' if len(years) == 1 else 'Spoločné evidované roky sú')
if context.get('complete') is not True or context.get('truncated'):
label = 'Medzi doložené spoločné roky patria'
lines.extend([label + ' **' + ', '.join(map(str, years)) + '**.', ''])
records = {}
for claim in out['claims']:
if claim.get('record_id'):
records.setdefault(claim['person'], []).append(claim)
else:
lines.append(fact_sentences(claim, context.get('question', '')))
index = 0
for person, claims in records.items():
lines.extend([f'{person} má v dostupných podkladoch tieto práce a projekty:', ''])
# Stable sorting retains the source order of same-year projects.
for claim in sorted(claims, key=lambda row: (row.get('year') is None, row.get('year') or 0)):
index += 1
kind = WORK_TYPE_LABELS.get(claim.get('work_type'), 'Práca')
label = claim.get('work_label') or kind
details = []
if kind.casefold() not in label.casefold():
details.append(kind)
if claim.get('year') is not None and not re.search(r'\b' + str(claim['year']) + r'\b', label):
details.append(f'rok práce: {claim["year"]}')
if claim.get('year') is None:
details.append('rok v zdroji nie je uvedený')
title = '**' + claim['title'].rstrip('.') + '**' if claim.get('title') else 'názov v zdroji nie je uvedený'
lines.append(f'{index}. **{label}**' + (' (' + '; '.join(details) + ')' if details else '') + f' — {title}.')
extra = {key: claim[key] for key in ('person', 'keyword', 'category', 'document_author', 'start_year')
if claim.get(key) is not None}
if len(extra) > 1:
lines.append(fact_sentences(extra))
lines.append('')
if out.get('count') is not None:
lines.append(f'Počet vyhovujúcich osôb: {out["count"]}.')
if context.get('complete') is False or context.get('truncated'):
lines.append('Výpis je neúplný.')
if records:
lines.append('Výpis môžeš zúžiť uvedením osoby, typu práce alebo konkrétneho roku.')
elif context.get('complete') is None:
lines.append('Úplnosť vyhľadania nemožno zaručiť.')
elif out['status'] == 'ambiguous':
lines.append('Požiadavka je nejednoznačná; údaje nemožno spoľahlivo určiť.')
elif out['status'] == 'error':
lines.append('Vyhľadanie zlyhalo; odpoveď nemožno pripraviť.')
else:
if context.get('academic_year_comparison') is not None:
lines.append('V dostupných podkladoch sa pre zadané podmienky spoločný rok nenašiel.')
else:
lines.append(no_answer_text(context))
if out['source_urls']:
lines.extend(['', ('Zdroj: ' if len(out['source_urls']) == 1 else 'Zdroje: ') + ', '.join(out['source_urls'])])
out['answer'] = '\n'.join(lines)
return out