|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import os |
| 5 | +import re |
| 6 | +from collections import defaultdict |
| 7 | +from datetime import datetime |
| 8 | + |
| 9 | +import extract_incidents as ei |
| 10 | + |
| 11 | + |
| 12 | +def parse_iso(value): |
| 13 | + if not value: |
| 14 | + return None |
| 15 | + value = value.strip() |
| 16 | + if not value: |
| 17 | + return None |
| 18 | + if len(value) == 10 and value[4] == "-" and value[7] == "-": |
| 19 | + value = f"{value}T00:00:00Z" |
| 20 | + return datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 21 | + |
| 22 | + |
| 23 | +def incident_text(incident): |
| 24 | + parts = [incident.get("title") or ""] |
| 25 | + for update in incident.get("updates") or []: |
| 26 | + if update.get("status") == "Resolved": |
| 27 | + continue |
| 28 | + message = update.get("message") |
| 29 | + if message: |
| 30 | + parts.append(message) |
| 31 | + return " ".join(part.strip() for part in parts if part.strip()) |
| 32 | + |
| 33 | + |
| 34 | +def build_alias_patterns(): |
| 35 | + return { |
| 36 | + label: [re.compile(pattern, re.IGNORECASE) for pattern in patterns] |
| 37 | + for label, patterns in ei.COMPONENT_ALIASES.items() |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | +def find_evidence(text, label, alias_patterns): |
| 42 | + for pattern in alias_patterns.get(label, []): |
| 43 | + match = pattern.search(text) |
| 44 | + if match: |
| 45 | + start = max(match.start() - 40, 0) |
| 46 | + end = min(match.end() + 40, len(text)) |
| 47 | + return text[start:end] |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +def infer_components(model, text, threshold): |
| 52 | + if not text: |
| 53 | + return [], {} |
| 54 | + result = model.extract_entities(text, ei.COMPONENT_SCHEMA, include_confidence=True) |
| 55 | + entities = result.get("entities", {}) if isinstance(result, dict) else {} |
| 56 | + components, confidences = ei.select_components_from_entities(entities, threshold) |
| 57 | + components = ei.filter_components_by_alias(components, text) |
| 58 | + if not components: |
| 59 | + return [], {} |
| 60 | + return components, {label: confidences.get(label) for label in components} |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + parser = argparse.ArgumentParser( |
| 65 | + description="Evaluate GLiNER2 component inference against HTML-tagged incidents." |
| 66 | + ) |
| 67 | + parser.add_argument( |
| 68 | + "--incidents", |
| 69 | + default="parsed/incidents.jsonl", |
| 70 | + help="Path to incidents JSONL (default: parsed/incidents.jsonl)", |
| 71 | + ) |
| 72 | + parser.add_argument( |
| 73 | + "--output-dir", |
| 74 | + default="out", |
| 75 | + help="Directory to write audit/eval files (default: out)", |
| 76 | + ) |
| 77 | + parser.add_argument( |
| 78 | + "--as-of", |
| 79 | + help="Only include incidents published on or before this ISO date/time (UTC).", |
| 80 | + ) |
| 81 | + parser.add_argument( |
| 82 | + "--model", |
| 83 | + default="fastino/gliner2-base-v1", |
| 84 | + help="GLiNER2 model name (default: fastino/gliner2-base-v1)", |
| 85 | + ) |
| 86 | + parser.add_argument( |
| 87 | + "--threshold", |
| 88 | + type=float, |
| 89 | + default=0.75, |
| 90 | + help="Minimum confidence threshold for components (default: 0.75)", |
| 91 | + ) |
| 92 | + args = parser.parse_args() |
| 93 | + |
| 94 | + if ei.GLiNER2 is None: |
| 95 | + raise SystemExit("GLiNER2 is not installed. Run `uv add gliner2` first.") |
| 96 | + |
| 97 | + model = ei.get_gliner_model(args.model) |
| 98 | + alias_patterns = build_alias_patterns() |
| 99 | + cutoff = parse_iso(args.as_of) |
| 100 | + |
| 101 | + incidents = [] |
| 102 | + with open(args.incidents, "r", encoding="utf-8") as handle: |
| 103 | + for line in handle: |
| 104 | + line = line.strip() |
| 105 | + if not line: |
| 106 | + continue |
| 107 | + incident = json.loads(line) |
| 108 | + if cutoff: |
| 109 | + published = incident.get("published_at") |
| 110 | + if published and parse_iso(published) > cutoff: |
| 111 | + continue |
| 112 | + incidents.append(incident) |
| 113 | + |
| 114 | + os.makedirs(args.output_dir, exist_ok=True) |
| 115 | + |
| 116 | + audit_path = os.path.join(args.output_dir, "gliner2_audit.jsonl") |
| 117 | + eval_path = os.path.join(args.output_dir, "gliner2_eval.json") |
| 118 | + |
| 119 | + audit_count = 0 |
| 120 | + with open(audit_path, "w", encoding="utf-8") as handle: |
| 121 | + for inc in incidents: |
| 122 | + if inc.get("components") and inc.get("components_source") != "gliner2": |
| 123 | + continue |
| 124 | + text = incident_text(inc) |
| 125 | + components, confidences = infer_components(model, text, args.threshold) |
| 126 | + if not components: |
| 127 | + continue |
| 128 | + evidence = { |
| 129 | + label: find_evidence(text, label, alias_patterns) for label in components |
| 130 | + } |
| 131 | + handle.write( |
| 132 | + json.dumps( |
| 133 | + { |
| 134 | + "id": inc.get("id"), |
| 135 | + "url": inc.get("url"), |
| 136 | + "title": inc.get("title"), |
| 137 | + "components": components, |
| 138 | + "components_confidence": confidences, |
| 139 | + "evidence": evidence, |
| 140 | + }, |
| 141 | + ensure_ascii=True, |
| 142 | + ) |
| 143 | + ) |
| 144 | + handle.write("\n") |
| 145 | + audit_count += 1 |
| 146 | + |
| 147 | + truth_pool = [ |
| 148 | + inc |
| 149 | + for inc in incidents |
| 150 | + if inc.get("components") and inc.get("components_source") != "gliner2" |
| 151 | + ] |
| 152 | + |
| 153 | + metrics = { |
| 154 | + "total": len(truth_pool), |
| 155 | + "predicted_non_empty": 0, |
| 156 | + "exact_match": 0, |
| 157 | + "tp": 0, |
| 158 | + "fp": 0, |
| 159 | + "fn": 0, |
| 160 | + } |
| 161 | + per_label = defaultdict(lambda: {"tp": 0, "fp": 0, "fn": 0}) |
| 162 | + examples_fp = [] |
| 163 | + examples_fn = [] |
| 164 | + |
| 165 | + for inc in truth_pool: |
| 166 | + text = incident_text(inc) |
| 167 | + predicted, _ = infer_components(model, text, args.threshold) |
| 168 | + truth = inc.get("components") or [] |
| 169 | + |
| 170 | + pred_set = set(predicted) |
| 171 | + truth_set = set(truth) |
| 172 | + |
| 173 | + if pred_set: |
| 174 | + metrics["predicted_non_empty"] += 1 |
| 175 | + |
| 176 | + if pred_set == truth_set: |
| 177 | + metrics["exact_match"] += 1 |
| 178 | + |
| 179 | + tp = pred_set & truth_set |
| 180 | + fp = pred_set - truth_set |
| 181 | + fn = truth_set - pred_set |
| 182 | + |
| 183 | + metrics["tp"] += len(tp) |
| 184 | + metrics["fp"] += len(fp) |
| 185 | + metrics["fn"] += len(fn) |
| 186 | + |
| 187 | + for label in tp: |
| 188 | + per_label[label]["tp"] += 1 |
| 189 | + for label in fp: |
| 190 | + per_label[label]["fp"] += 1 |
| 191 | + for label in fn: |
| 192 | + per_label[label]["fn"] += 1 |
| 193 | + |
| 194 | + if fp and len(examples_fp) < 5: |
| 195 | + examples_fp.append( |
| 196 | + { |
| 197 | + "title": inc.get("title"), |
| 198 | + "url": inc.get("url"), |
| 199 | + "predicted": sorted(pred_set), |
| 200 | + "truth": sorted(truth_set), |
| 201 | + } |
| 202 | + ) |
| 203 | + if fn and len(examples_fn) < 5: |
| 204 | + examples_fn.append( |
| 205 | + { |
| 206 | + "title": inc.get("title"), |
| 207 | + "url": inc.get("url"), |
| 208 | + "predicted": sorted(pred_set), |
| 209 | + "truth": sorted(truth_set), |
| 210 | + } |
| 211 | + ) |
| 212 | + |
| 213 | + precision = ( |
| 214 | + metrics["tp"] / (metrics["tp"] + metrics["fp"]) if (metrics["tp"] + metrics["fp"]) else 0 |
| 215 | + ) |
| 216 | + recall = ( |
| 217 | + metrics["tp"] / (metrics["tp"] + metrics["fn"]) if (metrics["tp"] + metrics["fn"]) else 0 |
| 218 | + ) |
| 219 | + exact_match_rate = metrics["exact_match"] / metrics["total"] if metrics["total"] else 0 |
| 220 | + |
| 221 | + report = { |
| 222 | + "model": args.model, |
| 223 | + "threshold": args.threshold, |
| 224 | + "as_of": args.as_of, |
| 225 | + "metrics": { |
| 226 | + **metrics, |
| 227 | + "precision": precision, |
| 228 | + "recall": recall, |
| 229 | + "exact_match_rate": exact_match_rate, |
| 230 | + }, |
| 231 | + "per_label": dict(per_label), |
| 232 | + "examples": {"false_positive": examples_fp, "false_negative": examples_fn}, |
| 233 | + "audit_count": audit_count, |
| 234 | + } |
| 235 | + |
| 236 | + with open(eval_path, "w", encoding="utf-8") as handle: |
| 237 | + json.dump(report, handle, indent=2, ensure_ascii=True) |
| 238 | + |
| 239 | + print(f"Wrote audit: {audit_path}") |
| 240 | + print(f"Wrote eval: {eval_path}") |
| 241 | + print( |
| 242 | + f"Precision {precision:.3f} | Recall {recall:.3f} | Exact match {exact_match_rate:.3f} " |
| 243 | + f"| Audit {audit_count} | Evaluated {metrics['total']}" |
| 244 | + ) |
| 245 | + |
| 246 | + |
| 247 | +if __name__ == "__main__": |
| 248 | + main() |
0 commit comments