|
| 1 | +"""Pure stdlib contracts for profile-driven event extraction. |
| 2 | +
|
| 3 | +All domain policy (entity types, anchor rules, number grounding) is supplied |
| 4 | +explicitly by a validated event extraction profile; no implicit defaults. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import hashlib |
| 10 | +import json |
| 11 | +import re |
| 12 | +from collections import defaultdict |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | +_ALLOWED_EVENT_KEYS = {"title", "content", "entities", "is_valid"} |
| 16 | +_ALLOWED_ENTITY_KEYS = {"type", "name", "description"} |
| 17 | +_NUMBER_RE = re.compile( |
| 18 | + r"(?<![A-Za-z0-9_.])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?%?(?![A-Za-z0-9_.])" |
| 19 | +) |
| 20 | + |
| 21 | + |
| 22 | +def numbers_in(text: str) -> set[str]: |
| 23 | + """Return numeric strings using the deterministic grounding policy.""" |
| 24 | + return set(_NUMBER_RE.findall(text or "")) |
| 25 | + |
| 26 | + |
| 27 | +def event_anchor(content: str, pattern: Optional[str]) -> Optional[str]: |
| 28 | + """Return the first configured anchor match, if any.""" |
| 29 | + if pattern is None: |
| 30 | + return None |
| 31 | + match = re.compile(pattern).search(content or "") |
| 32 | + if match is None: |
| 33 | + return None |
| 34 | + if match.lastindex: |
| 35 | + return match.group(1) |
| 36 | + return match.group(0) |
| 37 | + |
| 38 | + |
| 39 | +def event_node_name(anchor: Optional[str], title: str, content: str, *, legacy: bool = False) -> str: |
| 40 | + """Create a deterministic event node ID.""" |
| 41 | + if legacy: |
| 42 | + digest = hashlib.sha256(f"{anchor}\n{title}\n{content}".encode("utf-8")).hexdigest()[:12] |
| 43 | + return f"event:{anchor}:{digest}" |
| 44 | + digest = hashlib.sha256( |
| 45 | + json.dumps([anchor, title, content], ensure_ascii=False, separators=(",", ":")).encode("utf-8") |
| 46 | + ).hexdigest()[:20] |
| 47 | + return f"event:{digest}" |
| 48 | + |
| 49 | + |
| 50 | +def _parse_entity(entity: dict, allowed_types: set[str], dropped: dict) -> Optional[dict]: |
| 51 | + """Validate a single participant entity under the profile policy.""" |
| 52 | + if not isinstance(entity, dict): |
| 53 | + dropped["entity_not_object"] += 1 |
| 54 | + return None |
| 55 | + if set(entity) - _ALLOWED_ENTITY_KEYS: |
| 56 | + dropped["entity_extra_fields"] += 1 |
| 57 | + return None |
| 58 | + etype = str(entity.get("type") or "").strip().upper() |
| 59 | + ename = str(entity.get("name") or "").strip() |
| 60 | + edesc = str(entity.get("description") or "").strip() |
| 61 | + if not etype or not ename or not edesc: |
| 62 | + dropped["entity_blank"] += 1 |
| 63 | + return None |
| 64 | + if etype not in allowed_types: |
| 65 | + dropped["entity_type_unknown"] += 1 |
| 66 | + return None |
| 67 | + return {"type": etype, "name": ename, "description": edesc} |
| 68 | + |
| 69 | + |
| 70 | +def _event_rejection_reason( |
| 71 | + item: dict, |
| 72 | + *, |
| 73 | + evidence_numbers: set[str], |
| 74 | + anchor_pattern: Optional[str], |
| 75 | + anchor_required: bool, |
| 76 | + number_grounding: bool, |
| 77 | +) -> Optional[str]: |
| 78 | + """Return the first contract violation of an event item, if any.""" |
| 79 | + if not isinstance(item, dict): |
| 80 | + return "event_not_object" |
| 81 | + title = str(item.get("title") or "").strip() |
| 82 | + content = str(item.get("content") or "").strip() |
| 83 | + violations = ( |
| 84 | + ("event_extra_fields", bool(set(item) - _ALLOWED_EVENT_KEYS)), |
| 85 | + ("event_blank", not title or not content), |
| 86 | + ("event_self_invalid", item.get("is_valid") is False), |
| 87 | + ("event_missing_anchor", anchor_required and event_anchor(content, anchor_pattern) is None), |
| 88 | + ( |
| 89 | + "event_number_not_grounded", |
| 90 | + number_grounding |
| 91 | + and any(number not in evidence_numbers for number in numbers_in(f"{title} {content}")), |
| 92 | + ), |
| 93 | + ("event_entities_invalid", not isinstance(item.get("entities") or [], list)), |
| 94 | + ) |
| 95 | + for reason, violated in violations: |
| 96 | + if violated: |
| 97 | + return reason |
| 98 | + return None |
| 99 | + |
| 100 | + |
| 101 | +def _parse_event( |
| 102 | + item: dict, |
| 103 | + *, |
| 104 | + evidence_numbers: set[str], |
| 105 | + allowed_types: set[str], |
| 106 | + anchor_pattern: Optional[str], |
| 107 | + anchor_required: bool, |
| 108 | + number_grounding: bool, |
| 109 | + dropped: dict, |
| 110 | +) -> Optional[dict]: |
| 111 | + """Validate a single extracted event under the profile policy.""" |
| 112 | + reason = _event_rejection_reason( |
| 113 | + item, |
| 114 | + evidence_numbers=evidence_numbers, |
| 115 | + anchor_pattern=anchor_pattern, |
| 116 | + anchor_required=anchor_required, |
| 117 | + number_grounding=number_grounding, |
| 118 | + ) |
| 119 | + if reason: |
| 120 | + dropped[reason] += 1 |
| 121 | + return None |
| 122 | + title = str(item.get("title") or "").strip() |
| 123 | + content = str(item.get("content") or "").strip() |
| 124 | + entities = [ |
| 125 | + parsed |
| 126 | + for entity in item.get("entities") or [] |
| 127 | + if (parsed := _parse_entity(entity, allowed_types, dropped)) is not None |
| 128 | + ] |
| 129 | + return { |
| 130 | + "title": title, |
| 131 | + "content": content, |
| 132 | + "anchor": event_anchor(content, anchor_pattern), |
| 133 | + "entities": entities, |
| 134 | + } |
| 135 | + |
| 136 | + |
| 137 | +def parse_extraction_response( |
| 138 | + response: str, |
| 139 | + *, |
| 140 | + chunk_content: str, |
| 141 | + entity_types: list[dict], |
| 142 | + anchor_pattern: Optional[str] = None, |
| 143 | + anchor_required: bool = False, |
| 144 | + number_grounding: bool = True, |
| 145 | +) -> tuple[list[dict], dict[str, int]]: |
| 146 | + """Parse the strict event response contract under an explicit profile policy. |
| 147 | +
|
| 148 | + :param response: raw LLM response |
| 149 | + :param chunk_content: source chunk text used for number grounding |
| 150 | + :param entity_types: allowed entity types from the event profile |
| 151 | + :param anchor_pattern: optional regex applied to the event content |
| 152 | + :param anchor_required: whether an event without an anchor is dropped |
| 153 | + :param number_grounding: whether numbers must appear in the chunk content |
| 154 | + :return: (valid_events, dropped_counters) |
| 155 | + """ |
| 156 | + dropped: dict[str, int] = defaultdict(int) |
| 157 | + text = (response or "").strip() |
| 158 | + if text.startswith("```"): |
| 159 | + text = text.strip("`") |
| 160 | + if text.startswith("json"): |
| 161 | + text = text[4:] |
| 162 | + text = text.strip() |
| 163 | + try: |
| 164 | + payload = json.loads(text) |
| 165 | + except json.JSONDecodeError: |
| 166 | + dropped["response_not_json"] += 1 |
| 167 | + return [], dict(dropped) |
| 168 | + if not isinstance(payload, dict) or set(payload) != {"type", "data"}: |
| 169 | + dropped["response_contract_invalid"] += 1 |
| 170 | + return [], dict(dropped) |
| 171 | + data = payload.get("data") |
| 172 | + if not isinstance(data, dict) or set(data) != {"items"} or not isinstance(data["items"], list): |
| 173 | + dropped["response_contract_invalid"] += 1 |
| 174 | + return [], dict(dropped) |
| 175 | + |
| 176 | + allowed_types = {str(item["type"]).strip().upper() for item in entity_types} |
| 177 | + evidence_numbers = numbers_in(chunk_content) if number_grounding else set() |
| 178 | + valid_events = [ |
| 179 | + event |
| 180 | + for item in data["items"] |
| 181 | + if ( |
| 182 | + event := _parse_event( |
| 183 | + item, |
| 184 | + evidence_numbers=evidence_numbers, |
| 185 | + allowed_types=allowed_types, |
| 186 | + anchor_pattern=anchor_pattern, |
| 187 | + anchor_required=anchor_required, |
| 188 | + number_grounding=number_grounding, |
| 189 | + dropped=dropped, |
| 190 | + ) |
| 191 | + ) |
| 192 | + is not None |
| 193 | + ] |
| 194 | + return valid_events, dict(dropped) |
0 commit comments