Files
smartguide/llm_evaluations/basic_applied_experimental/summarize_classification.py
T
Roman d2dec7c6ee
LocationBasedServices/smartguide/pipeline/head This commit looks good
work-classifications
2026-07-14 00:12:31 +02:00

383 lines
12 KiB
Python

from __future__ import annotations
import json
import statistics
from pathlib import Path
from typing import Any
PROJECT_ROOT = Path(__file__).resolve().parent
LLM_RESULTS_DIR = PROJECT_ROOT / "llm_results"
CLASSIFICATION_SUMMARY_DIR = PROJECT_ROOT / "classification_summary"
OVERALL_OUTPUT = CLASSIFICATION_SUMMARY_DIR / "overall_summary.json"
PERSON_OUTPUT = CLASSIFICATION_SUMMARY_DIR / "person_summary.json"
CATEGORIES = [
"basic_research",
"applied_research",
"experimental_development",
"non_research",
]
CONFIDENCE_VALUES = [
"high",
"medium",
"low",
]
def read_json(path: Path) -> Any:
with path.open("r", encoding="utf-8") as file:
return json.load(file)
def write_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix(path.suffix + ".tmp")
temp_path.write_text(
json.dumps(data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
temp_path.replace(path)
def safe_share(numerator: int, denominator: int) -> float:
return round(numerator / denominator, 4) if denominator else 0.0
def safe_mean(values: list[int | float]) -> float | None:
return round(statistics.mean(values), 2) if values else None
def safe_median(values: list[int | float]) -> float | None:
return round(statistics.median(values), 2) if values else None
def is_numeric_score(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def has_abstract(result: dict[str, Any]) -> bool:
input_data = result.get("input") or {}
abstract = input_data.get("abstract")
return isinstance(abstract, str) and bool(abstract.strip())
def get_validation_errors(result: dict[str, Any]) -> list[str]:
debug = result.get("llm_debug") or {}
errors = debug.get("validation_errors") or []
if not isinstance(errors, list):
return []
return [str(error) for error in errors]
def is_api_error(result: dict[str, Any]) -> bool:
debug = result.get("llm_debug") or {}
return debug.get("status") != "ok"
def normalize_usage_record(usage: Any) -> dict[str, int]:
if not isinstance(usage, dict):
return {
"prompt_tokens": 0,
"uncached_prompt_tokens": 0,
"completion_tokens": 0,
"real_total_usage": 0,
}
prompt_tokens = int(usage.get("prompt_tokens") or 0)
completion_tokens = int(usage.get("completion_tokens") or 0)
if "uncached_prompt_tokens" in usage:
uncached_prompt_tokens = int(usage.get("uncached_prompt_tokens") or 0)
elif "cached_prompt_tokens" in usage:
cached_prompt_tokens = min(
int(usage.get("cached_prompt_tokens") or 0),
prompt_tokens,
)
uncached_prompt_tokens = max(
prompt_tokens - cached_prompt_tokens,
0,
)
else:
uncached_prompt_tokens = prompt_tokens
uncached_prompt_tokens = min(
max(uncached_prompt_tokens, 0),
prompt_tokens,
)
return {
"prompt_tokens": prompt_tokens,
"uncached_prompt_tokens": uncached_prompt_tokens,
"completion_tokens": completion_tokens,
"real_total_usage": (uncached_prompt_tokens + completion_tokens),
}
def has_score_range_mismatch(
validation_errors: list[str],
) -> bool:
return any("score_outside_expected_range" in error for error in validation_errors)
def validate_unique_results(
results: list[dict[str, Any]],
source_file: Path,
) -> None:
seen: set[str] = set()
duplicates: list[str] = []
for result in results:
work_id = result.get("work_id")
if not isinstance(work_id, str) or not work_id:
raise ValueError(f"Missing work_id in {source_file}")
if work_id in seen:
duplicates.append(work_id)
else:
seen.add(work_id)
if duplicates:
duplicate_list = ", ".join(sorted(set(duplicates)))
raise ValueError(f"Duplicate work_id values in {source_file}: {duplicate_list}")
def summarize_results(
results: list[dict[str, Any]],
person: dict[str, Any] | None = None,
) -> dict[str, Any]:
works_total = len(results)
valid_outputs = 0
validation_error_outputs = 0
api_error_outputs = 0
category_counts = {category: 0 for category in CATEGORIES}
confidence_counts = {confidence: 0 for confidence in CONFIDENCE_VALUES}
scores: list[int | float] = []
durations: list[int | float] = []
works_with_abstract = 0
usage = {
"prompt_tokens": 0,
"uncached_prompt_tokens": 0,
"completion_tokens": 0,
"real_total_usage": 0,
}
quality_checks = {
"high_confidence_without_abstract": 0,
"title_only_high_confidence": 0,
"non_research_with_score": 0,
"score_range_mismatches": 0,
}
problem_cases: list[dict[str, Any]] = []
for result in results:
input_data = result.get("input") or {}
classification = result.get("classification") or {}
debug = result.get("llm_debug") or {}
validation_errors = get_validation_errors(result)
api_error = is_api_error(result)
if validation_errors:
validation_error_outputs += 1
if api_error:
api_error_outputs += 1
if (
not validation_errors
and not api_error
and isinstance(result.get("classification"), dict)
):
valid_outputs += 1
category = classification.get("primary_category")
score = classification.get("applied_orientation_score")
confidence = classification.get("confidence")
signals_used = classification.get("signals_used") or []
if category in category_counts:
category_counts[category] += 1
if confidence in confidence_counts:
confidence_counts[confidence] += 1
abstract_available = has_abstract(result)
if abstract_available:
works_with_abstract += 1
if is_numeric_score(score):
scores.append(score)
result_usage = normalize_usage_record(debug.get("usage"))
for key in usage:
usage[key] += result_usage[key]
duration = debug.get("duration_seconds")
if isinstance(duration, (int, float)):
durations.append(duration)
if not abstract_available and confidence == "high":
quality_checks["high_confidence_without_abstract"] += 1
if signals_used == ["title"] and confidence == "high":
quality_checks["title_only_high_confidence"] += 1
if category == "non_research" and score is not None:
quality_checks["non_research_with_score"] += 1
if has_score_range_mismatch(validation_errors):
quality_checks["score_range_mismatches"] += 1
if validation_errors or api_error:
problem_cases.append(
{
"person_name": (person or {}).get("display_name"),
"person_id": (person or {}).get("id"),
"work_id": result.get("work_id"),
"doi": result.get("doi"),
"title": input_data.get("title"),
"year": input_data.get("year"),
"work_type": input_data.get("work_type"),
"has_abstract": abstract_available,
"primary_category": category,
"applied_orientation_score": score,
"confidence": confidence,
"classification_reason": classification.get(
"classification_reason"
),
"validation_errors": validation_errors,
"api_error": api_error,
"api_error_message": debug.get("error"),
}
)
works_without_abstract = works_total - works_with_abstract
return {
"counts": {
"works_total": works_total,
"valid_outputs": valid_outputs,
"validation_errors": validation_error_outputs,
"api_errors": api_error_outputs,
},
"category_distribution": category_counts,
"category_share": {
category: safe_share(count, works_total)
for category, count in category_counts.items()
},
"confidence_distribution": confidence_counts,
"abstract_coverage": {
"works_with_abstract": works_with_abstract,
"works_without_abstract": works_without_abstract,
"missing_abstract_share": safe_share(
works_without_abstract,
works_total,
),
},
"score_summary": {
"scored_outputs": len(scores),
"mean_applied_orientation_score": safe_mean(scores),
"median_applied_orientation_score": safe_median(scores),
"min_applied_orientation_score": (min(scores) if scores else None),
"max_applied_orientation_score": (max(scores) if scores else None),
},
"quality_checks": quality_checks,
"usage": usage,
"average_usage_per_work": {
key: (round(value / works_total, 2) if works_total else None)
for key, value in usage.items()
},
"timing": {
"average_duration_seconds_per_work": safe_mean(durations),
},
"problem_cases": problem_cases,
}
def merge_summaries(
person_items: list[dict[str, Any]],
) -> dict[str, Any]:
all_results: list[dict[str, Any]] = []
for item in person_items:
all_results.extend(item["results"])
overall = summarize_results(all_results)
overall["counts"] = {
"persons_total": len(person_items),
**overall["counts"],
}
overall["problem_cases"] = [
problem_case
for item in person_items
for problem_case in item["summary"].get("problem_cases", [])
]
return overall
def main() -> None:
if not LLM_RESULTS_DIR.exists():
raise FileNotFoundError(LLM_RESULTS_DIR)
result_files = sorted(LLM_RESULTS_DIR.glob("A*_results.json"))
if not result_files:
raise FileNotFoundError(f"No A*_results.json files found in {LLM_RESULTS_DIR}")
person_items: list[dict[str, Any]] = []
for result_file in result_files:
data = read_json(result_file)
if not isinstance(data, dict):
raise ValueError(f"Root is not an object in {result_file}")
person = data.get("person") or {}
results = data.get("results") or []
if not isinstance(person, dict):
raise ValueError(f"person is not an object in {result_file}")
if not isinstance(results, list):
raise ValueError(f"results is not a list in {result_file}")
validate_unique_results(results, result_file)
summary = summarize_results(results, person)
person_items.append(
{
"person": person,
"source_file": result_file.relative_to(PROJECT_ROOT).as_posix(),
"summary": summary,
"results": results,
}
)
overall_summary = merge_summaries(person_items)
person_output = [
{
"person": item["person"],
"source_file": item["source_file"],
"summary": item["summary"],
}
for item in person_items
]
write_json(OVERALL_OUTPUT, overall_summary)
write_json(PERSON_OUTPUT, person_output)
print("Classification summary completed.")
print(f"Persons: {overall_summary['counts']['persons_total']}")
print(f"Works: {overall_summary['counts']['works_total']}")
print(f"Valid outputs: {overall_summary['counts']['valid_outputs']}")
print(f"Validation errors: {overall_summary['counts']['validation_errors']}")
print(f"API errors: {overall_summary['counts']['api_errors']}")
print(f"Written: {OVERALL_OUTPUT.relative_to(PROJECT_ROOT).as_posix()}")
print(f"Written: {PERSON_OUTPUT.relative_to(PROJECT_ROOT).as_posix()}")
if __name__ == "__main__":
main()