"""Small, dependency-free HTML view for completed evaluation artifacts."""
from __future__ import annotations
import html
import json
import math
from typing import Any
from collections.abc import Mapping
from urllib.parse import urlsplit
from ..models import deep_thaw
from .models import ReportData
def _bar(value: Any, maximum: float, *, unavailable: bool = False) -> str:
if unavailable or value is None:
return 'unavailable'
try:
number = float(value)
except (TypeError, ValueError):
return 'unavailable'
if not math.isfinite(number) or number < 0:
return ""
width = 0 if maximum <= 0 or number == 0 else max(2, min(100, number / maximum * 100))
return f''
def _numeric_value(value: Any) -> float | None:
"""Return a safe chart scalar without knowing evaluator or metric names.
Scalar measurements are directly chartable. For structured values, a
conventional numeric ``total`` is used when present; arbitrary mappings
remain structured unless they contain exactly one numeric leaf. This
keeps the renderer generic while avoiding a misleading choice between
unrelated fields such as p50/p95/count.
"""
if isinstance(value, Mapping):
total = value.get("total")
if isinstance(total, (int, float)) and not isinstance(total, bool):
value = total
else:
numeric = [item for item in value.values()
if isinstance(item, (int, float)) and not isinstance(item, bool)]
value = numeric[0] if len(numeric) == 1 else None
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
try:
number = float(value)
except OverflowError:
return None
return number if math.isfinite(number) else None
def _chart_maxima(rows: list[Mapping[str, Any]]) -> dict[str, float]:
"""Return independent chart scales for each declared measurement unit.
Units are part of the generic measurement contract, so values in seconds,
tokens, or a future evaluator-defined unit must not distort one another's
bars. No evaluator or metric identifier is inspected here.
"""
maxima: dict[str, float] = {}
for row in rows:
number = _numeric_value(row.get("value"))
if number is None:
continue
unit = str(row.get("unit") or "")
maxima[unit] = max(maxima.get(unit, 0.0), number)
return maxima
def _display_value(value: Any) -> str:
if isinstance(value, (Mapping, list, tuple)):
return json.dumps(deep_thaw(value), ensure_ascii=False, sort_keys=True)
if value is None:
return "unavailable"
return str(value)
def _json_text(value: Any) -> str:
try:
return json.dumps(deep_thaw(value), ensure_ascii=False, sort_keys=True, indent=2, default=str)
except (TypeError, ValueError):
return str(value)
def _rounded_value(value: Any) -> Any:
"""Display precision only; persisted scores and chart scales stay exact."""
if isinstance(value, Mapping):
return {key: _rounded_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [_rounded_value(item) for item in value]
if isinstance(value, float) and math.isfinite(value):
return round(value, 1)
return value
def _measurement_value_html(value: Any, unit: Any, maximum: float) -> str:
numeric = _numeric_value(value)
structured = isinstance(value, (Mapping, list, tuple))
primary = f"{numeric:,.1f}" if numeric is not None else ("" if structured else _display_value(value))
rounded = _rounded_value(value)
parts = [
'
',
f'
{html.escape(primary)}'
f'{html.escape(str(unit or ""))}
',
_bar(numeric, maximum) if numeric is not None and numeric >= 0 else "",
]
if structured:
parts.append(f'
{html.escape(_display_value(rounded))}
')
if _display_value(rounded) != _display_value(value):
parts.append(f'Exact value
Evidence: {_evidence_links(finding.get("evidence_refs") or [])}
'
'
'
)
findings_html = f'
{"".join(findings)}
' if findings else ""
duration = row["duration_seconds"]
selection = []
if duration is not None:
selection.append(f'duration={html.escape(_display_value(_rounded_value(duration)))}s')
if row["rank"] is not None:
selection.append(f'rank={html.escape(str(row["rank"]))}')
if row["evidence_completeness"] is not None:
selection.append(f'evidence={html.escape(str(row["evidence_completeness"]))}')
rendered.append("".join((
'',
f'
'
def _backend_link(url: str | None) -> str:
"""An optional UI entrance, never an inferred evidence deep link."""
if not isinstance(url, str) or any(char.isspace() or ord(char) < 32 for char in url):
return ""
try:
parsed = urlsplit(url)
if (parsed.scheme not in {"http", "https"} or not parsed.hostname
or parsed.username is not None or parsed.password is not None):
return ""
parsed.port # Reject malformed ports as well as malformed host brackets.
except ValueError:
return ""
return f'Open backend UI ↗'
def _publication_html(backend: Mapping[str, Any]) -> str:
metadata = backend.get("metadata") or {}
warnings = metadata.get("warnings") or []
publications = metadata.get("publications") or {}
if not warnings and not publications:
return ""
rows = "".join(
f'
{html.escape(str(warning.get("operation", "publication")))} '
f'{html.escape(str(warning.get("code", "warning")))}'
f'
{html.escape(str(warning.get("message", "")))}
'
for warning in warnings if isinstance(warning, Mapping)
)
cards = []
for operation, stats in publications.items():
fields = stats.items() if isinstance(stats, Mapping) else [("Value", stats)]
values = ''.join(
f'
{html.escape(str(key).replace("_", " "))}
'
f'
{html.escape(_display_value(value))}
'
for key, value in fields
)
cards.append(''
f'
{html.escape(str(operation).replace("_", " "))}
'
f'
{values}
')
return ('
Backend publication
'
'Optional result publishing · separate from evaluation scores
'
f'
{"".join(cards)}
'
+ (f'
{rows}
' if rows else '
No publication warnings
')
+ f'Raw publication data
{html.escape(_json_text(publications))}
')
def _safe_task_link(value: str) -> bool:
if not isinstance(value, str) or not value or any(ord(c) < 33 for c in value) or "\\" in value:
return False
try:
parsed = urlsplit(value)
return (not parsed.scheme and not parsed.netloc and not value.startswith("/")
and not parsed.query and not parsed.fragment)
except ValueError:
return False
def render_evaluation_document(result: ReportData, *, backend_ui_url: str | None = None,
task_links: Mapping[str, str] | None = None) -> str:
"""Shared HTML view for a persisted native experiment or a local audit report."""
if not isinstance(result, ReportData):
raise TypeError("renderer requires ReportData")
measurements = _measurement_rows(result)
assessments = _assessment_rows(result)
diagnostics = _diagnostic_rows(result)
run_metadata = [getattr(run, "metadata", {}) or {} for run in result.runs]
adapter = next((item.get("adapter") for item in run_metadata if item.get("adapter")), None)
model = next((item.get("model") for item in run_metadata if item.get("model")), None)
chart_maxima = _chart_maxima(measurements)
rows_html: list[str] = []
for row in measurements:
metric = row["metric"]
value = row["value"]
status_class = _status_class(row["attribution_status"]) if row["attribution_status"] else "muted"
rows_html.append(
"
"
f"
{html.escape(str(row['case_id']))}
"
f"
{html.escape(str(row['evaluator_id']))}
"
f"
{html.escape(str(row['stage'] or '—'))}
"
f"
{html.escape(str(metric))}
"
f"
{_measurement_value_html(value, row['unit'], chart_maxima.get(str(row['unit'] or ''), 0.0))}
"
f"
{html.escape(str(row['status']))}
"
f"
{html.escape(str(row['attribution_status'] or '—'))}
'
artifact_links: list[str] = []
for run in result.runs:
link = (task_links or {}).get(run.run_id, "")
target = (f'task-artifact.json'
if _safe_task_link(link) else html.escape(run.run_id))
artifact_links.append(
f'