| """Evidence-grounded structured extraction from the interim IMF corpus. |
| |
| This is a transparent deterministic baseline, not an LLM-generated gold set. |
| Every observation, recommendation, and relationship includes page evidence and |
| an explicit extraction method/confidence. Contextual links are labeled as such |
| and are never represented as explicit causal claims. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import concurrent.futures |
| import datetime as dt |
| import hashlib |
| import json |
| import os |
| import re |
| import shutil |
| import sys |
| import tempfile |
| from collections import Counter, defaultdict |
| from pathlib import Path |
| from typing import Any, Iterable, Sequence |
|
|
| import jsonschema |
|
|
| SCHEMA_VERSION = "1.1.0" |
| EXTRACTOR_VERSION = "1.1.0" |
| EXTRACTION_METHOD = "deterministic_evidence_baseline" |
|
|
| HEADING_RE = re.compile(r"^\s*#{1,6}\s+(.+?)\s*$") |
| TABLE_SEPARATOR_RE = re.compile(r"^\s*\|?\s*:?-{3,}") |
| DOI_RE = re.compile(r"\b10\.5089/[A-Za-z0-9._;()/:-]+", re.I) |
| ISBN_RE = re.compile(r"\b(?:97[89][ -]?)?(?:\d[ -]?){9}[\dXx]\b") |
| PARAGRAPH_NUMBER_RE = re.compile(r"(?:¶|paragraph\s+)?(\d{1,3})", re.I) |
|
|
| RECOMMENDATION_HEADING_RE = re.compile( |
| r"\b(recommendations?|recommended actions?|recomendaciones|recomenda(?:ç|c)[õo]es|recommandations?|" |
| r"рекомендации|рекомендация)\b|التوصيات|توصيات", |
| re.I, |
| ) |
| OBSERVATION_HEADING_RE = re.compile( |
| r"\b(executive summary|key findings?|main findings?|assessment|diagnostic|observations?|" |
| r"resumen ejecutivo|principales hallazgos|constatations|sum[aá]rio executivo|" |
| r"резюме|основные выводы|результаты)\b|ملخص|النتائج|الملاحظات", |
| re.I, |
| ) |
| EXCLUDED_SECTION_RE = re.compile( |
| r"\b(contents|table of contents|glossary|preface|appendi(?:x|ces)|annex|bibliography|references)\b", |
| re.I, |
| ) |
| STRONG_EXPLICIT_RECOMMENDATION_RE = re.compile( |
| r"\b(the mission (?:recommends?|recommended)|is recommended|are recommended|" |
| r"we recommend|recommendation is to|it is recommended|se recomienda|recomenda-se|" |
| r"il est recommand[ée]|рекомендуется)\b|توصي البعثة", |
| re.I, |
| ) |
| RECOMMENDATION_TABLE_HEADER_RE = re.compile( |
| r"^(?:(?:main|key|priority)\s+)?recommendations?$|" |
| r"^(?:short|medium|long)[- ]term projections?$|^recommended actions?$", |
| re.I, |
| ) |
|
|
| RECOMMENDATION_MODAL_RE = re.compile( |
| r"\b(should|must|needs? to|is recommended|are recommended|the mission recommends?|" |
| r"recommended that|recommendation is to|priority is to|deber[ií]a|debe(?:n)?|se recomienda|" |
| r"devrait|doit|il est recommand[ée]|deveria|deve(?:m)?|recomenda-se|" |
| r"следует|необходимо|долж(?:ен|на|ны)|рекомендуется)\b|ينبغي|يجب|يوصى", |
| re.I, |
| ) |
| IMPERATIVE_RE = re.compile( |
| r"^(strengthen|establish|develop|adopt|implement|improve|ensure|create|prepare|finalize|" |
| r"introduce|increase|reduce|review|revise|update|set up|initiate|start|continue|conduct|" |
| r"align|clarify|define|enhance|formalize|operationalize|provide|require|maintain|" |
| r"fortalecer|establecer|desarrollar|implementar|mejorar|garantizar|adoptar|" |
| r"renforcer|[ée]tablir|am[ée]liorer|mettre en œuvre|adopter|" |
| r"refor[çc]ar|estabelecer|desenvolver|implementar|melhorar|adotar|" |
| r"укрепить|создать|разработать|внедрить|улучшить|обеспечить|принять)\b|" |
| r"^(?:تعزيز|إنشاء|تطوير|تنفيذ|تحسين|ضمان|اعتماد)", |
| re.I, |
| ) |
| OBSERVATION_SIGNAL_RE = re.compile( |
| r"\b(found|finds|finding|remains?|lacks?|weak(?:ness|nesses)?|limited|insufficient|" |
| r"constraint|gap|shortcoming|challenge|risk|vulnerab|deficien|not yet|does not|do not|" |
| r"has not|have not|however|progress|improved|effective|ineffective|fragmented|outdated|" |
| r"ausencia|débil|limitad|insuficient|deficien|desaf[ií]o|riesgo|" |
| r"faible|limit[ée]|insuffisant|lacune|risque|" |
| r"fraco|limitado|insuficiente|defici[êe]ncia|desafio|risco|" |
| r"недостат|слаб|огранич|риск|проблем|отсутств)\w*\b|" |
| r"ضعف|يفتقر|محدود|تحديات|مخاطر|عدم", |
| re.I, |
| ) |
|
|
| MONTHS = { |
| "january": 1, |
| "february": 2, |
| "march": 3, |
| "april": 4, |
| "may": 5, |
| "june": 6, |
| "july": 7, |
| "august": 8, |
| "september": 9, |
| "october": 10, |
| "november": 11, |
| "december": 12, |
| } |
| MONTH_PATTERN = "|".join(MONTHS) |
| SAME_MONTH_RANGE_RE = re.compile( |
| rf"\b(?P<month>{MONTH_PATTERN})\s+(?P<start>\d{{1,2}})\s*[–—-]\s*" |
| rf"(?P<end>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b", |
| re.I, |
| ) |
| CROSS_MONTH_RANGE_RE = re.compile( |
| rf"\b(?P<month1>{MONTH_PATTERN})\s+(?P<start>\d{{1,2}})\s*[–—-]\s*" |
| rf"(?P<month2>{MONTH_PATTERN})\s+(?P<end>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b", |
| re.I, |
| ) |
| SINGLE_DATE_RE = re.compile( |
| rf"\b(?P<month>{MONTH_PATTERN})\s+(?P<day>\d{{1,2}}),?\s+(?P<year>20\d{{2}})\b", |
| re.I, |
| ) |
|
|
| _GLOBAL_FIGURES_CACHE: dict[str, dict[str, list[dict[str, Any]]]] = {} |
|
|
| STOPWORDS = { |
| "the", "a", "an", "and", "or", "of", "to", "in", "for", "on", "with", "by", |
| "that", "this", "these", "those", "is", "are", "be", "should", "must", "it", "its", |
| "as", "from", "at", "has", "have", "will", "would", "could", "their", "which", "into", |
| "imf", "mission", "recommend", "recommended", "recommendation", |
| } |
|
|
|
|
| def utc_now() -> str: |
| return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() |
|
|
|
|
| def load_json(path: Path) -> Any: |
| return json.loads(path.read_text(encoding="utf-8")) |
|
|
|
|
| def load_jsonl(path: Path) -> list[dict[str, Any]]: |
| if not path.exists(): |
| return [] |
| with path.open(encoding="utf-8") as source: |
| return [json.loads(line) for line in source if line.strip()] |
|
|
|
|
| def write_json(path: Path, value: Any) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| temporary = path.with_suffix(path.suffix + ".tmp") |
| temporary.write_text( |
| json.dumps(value, ensure_ascii=False, indent=2, sort_keys=False) + "\n", |
| encoding="utf-8", |
| ) |
| os.replace(temporary, path) |
|
|
|
|
| def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| temporary = path.with_suffix(path.suffix + ".tmp") |
| with temporary.open("w", encoding="utf-8") as output: |
| for row in rows: |
| output.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") |
| os.replace(temporary, path) |
|
|
|
|
| def clean_markdown(value: str) -> str: |
| value = re.sub(r"!\[[^\]]*\]\([^)]+\)", "", value) |
| value = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", value) |
| value = re.sub(r"<br\s*/?>", " ", value, flags=re.I) |
| value = re.sub(r"</?[^>]+>", " ", value) |
| value = re.sub(r"^\s*#{1,6}\s*", "", value) |
| value = value.replace("**", "").replace("__", "").replace("`", "") |
| value = value.replace("_", " ") |
| value = re.sub(r"^\s*[-*•]\s+", "", value) |
| value = re.sub(r"\s+", " ", value) |
| return value.strip(" |\t\r\n") |
|
|
|
|
| def normalize_evidence(value: str) -> str: |
| value = value.replace("_", " ") |
| return re.sub(r"[^\w]+", " ", value.lower(), flags=re.UNICODE).strip() |
|
|
|
|
| def evidence_id(report_id: str, page: int, quote: str) -> str: |
| digest = hashlib.sha256( |
| f"{report_id}|{page}|{normalize_evidence(quote)}".encode("utf-8") |
| ).hexdigest()[:16] |
| return f"ev-{digest}" |
|
|
|
|
| def evidence(report_id: str, page: int, quote: str, source: str = "document") -> dict[str, Any]: |
| return { |
| "evidence_id": evidence_id(report_id, page, quote), |
| "page": page, |
| "quote": quote, |
| "source": source, |
| } |
|
|
|
|
| def token_set(value: str) -> set[str]: |
| return { |
| token |
| for token in re.findall(r"\b[^\W\d_]\w{2,}\b", value.lower(), flags=re.UNICODE) |
| if token not in STOPWORDS |
| } |
|
|
|
|
| def similarity(left: str, right: str) -> float: |
| left_tokens, right_tokens = token_set(left), token_set(right) |
| if not left_tokens or not right_tokens: |
| return 0.0 |
| return len(left_tokens & right_tokens) / len(left_tokens | right_tokens) |
|
|
|
|
| def split_sentences(paragraph: str) -> list[str]: |
| paragraph = re.sub(r"\s*\n\s*", " ", paragraph).strip() |
| if not paragraph: |
| return [] |
| pieces = re.split(r"(?<=[.!?؟])\s+(?=\S)", paragraph) |
| return [piece.strip() for piece in pieces if piece.strip()] |
|
|
|
|
| def parse_table_cells(line: str) -> list[str]: |
| line = line.strip().strip("|") |
| return [clean_markdown(cell) for cell in re.split(r"(?<!\\)\|", line)] |
|
|
|
|
| def table_blocks(markdown: str) -> list[list[str]]: |
| blocks: list[list[str]] = [] |
| current: list[str] = [] |
| for line in markdown.splitlines(): |
| if line.strip().startswith("|") and line.count("|") >= 2: |
| current.append(line) |
| else: |
| if len(current) >= 2: |
| blocks.append(current) |
| current = [] |
| if len(current) >= 2: |
| blocks.append(current) |
| return blocks |
|
|
|
|
| def column_index(headers: list[str], aliases: tuple[str, ...]) -> int | None: |
| for index, header in enumerate(headers): |
| lowered = header.lower() |
| if any(alias in lowered for alias in aliases): |
| return index |
| return None |
|
|
|
|
| def fingerprint(value: str) -> str: |
| return " ".join(sorted(token_set(value))) |
|
|
|
|
| def add_unique( |
| collection: list[dict[str, Any]], |
| item: dict[str, Any], |
| *, |
| similarity_threshold: float = 0.88, |
| ) -> int: |
| item_fp = fingerprint(item["verbatim"]) |
| for index, existing in enumerate(collection): |
| existing_fp = existing.get("_fingerprint", "") |
| if item_fp == existing_fp or similarity(item["verbatim"], existing["verbatim"]) >= similarity_threshold: |
| known = {entry["evidence_id"] for entry in existing["evidence"]} |
| existing["evidence"].extend( |
| entry for entry in item["evidence"] if entry["evidence_id"] not in known |
| ) |
| if item["confidence"] > existing["confidence"]: |
| for key in ( |
| "text", "verbatim", "actor", "priority", "timeframe", |
| "section", "extraction_method", "confidence", "_page", "_paragraph_key", |
| ): |
| if key in item: |
| existing[key] = item[key] |
| return index |
| item["_fingerprint"] = item_fp |
| collection.append(item) |
| return len(collection) - 1 |
|
|
|
|
| def parse_priority(value: str) -> str | None: |
| match = re.search(r"\b(high|medium|low|critical|alta|media|baja|haute|moyenne|faible)\b", value, re.I) |
| return match.group(1).lower() if match else None |
|
|
|
|
| def parse_timeframe(value: str) -> str | None: |
| match = re.search( |
| r"\b(near[- ]term|short[- ]term|medium[- ]term|long[- ]term|immediate|" |
| r"NT|ST|MT|LT|\d+\s*(?:months?|years?))\b", |
| value, |
| re.I, |
| ) |
| return match.group(1) if match else None |
|
|
|
|
| def recommendation_item( |
| report_id: str, |
| page: int, |
| value: str, |
| *, |
| section: str, |
| method: str, |
| confidence: float, |
| actor: str | None = None, |
| priority: str | None = None, |
| timeframe: str | None = None, |
| paragraph_key: str | None = None, |
| ) -> dict[str, Any]: |
| quote = clean_markdown(value) |
| paragraph_match = PARAGRAPH_NUMBER_RE.search(quote) |
| return { |
| "text": quote, |
| "verbatim": quote, |
| "actor": actor, |
| "priority": priority, |
| "timeframe": timeframe, |
| "report_paragraph": int(paragraph_match.group(1)) if paragraph_match and "¶" in quote else None, |
| "section": section or None, |
| "evidence": [evidence(report_id, page, quote)], |
| "confidence": confidence, |
| "extraction_method": method, |
| "review_status": "unreviewed", |
| "_page": page, |
| "_paragraph_key": paragraph_key, |
| } |
|
|
|
|
| def observation_item( |
| report_id: str, |
| page: int, |
| value: str, |
| *, |
| section: str, |
| method: str, |
| confidence: float, |
| paragraph_key: str | None = None, |
| ) -> dict[str, Any]: |
| quote = clean_markdown(value) |
| return { |
| "text": quote, |
| "verbatim": quote, |
| "topic": section or None, |
| "severity": None, |
| "evidence": [evidence(report_id, page, quote)], |
| "confidence": confidence, |
| "extraction_method": method, |
| "review_status": "unreviewed", |
| "_page": page, |
| "_paragraph_key": paragraph_key, |
| } |
|
|
|
|
| def extract_tables( |
| report_id: str, |
| pages: list[dict[str, Any]], |
| recommendations: list[dict[str, Any]], |
| observations: list[dict[str, Any]], |
| ) -> list[tuple[int, int, dict[str, Any]]]: |
| explicit_links: list[tuple[int, int, dict[str, Any]]] = [] |
| for page in pages: |
| page_number = page["page"] |
| for table_number, lines in enumerate(table_blocks(page["markdown"]), start=1): |
| cells = [parse_table_cells(line) for line in lines] |
| if len(cells) < 2: |
| continue |
| headers = cells[0] |
| row_start = 2 if len(cells) > 1 and TABLE_SEPARATOR_RE.match(lines[1]) else 1 |
| rec_col = column_index( |
| headers, |
| ( |
| "recommend", "recommended action", "action required", "proposed action", |
| "recomenda", "рекоменд", "توص", |
| ), |
| ) |
| rtl_recommendation_table = False |
| if ( |
| rec_col is None |
| and len(headers) == 3 |
| and re.search(r"[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]", " ".join(headers)) |
| and page_number <= 10 |
| ): |
| |
| |
| |
| rec_col = 1 |
| rtl_recommendation_table = True |
| if rec_col is None: |
| continue |
| obs_col = column_index( |
| headers, |
| ( |
| "observation", "finding", "issue", "challenge", "weakness", "rationale", |
| "constat", "вывод", "проблем", "ملاحظ", "نتائج", "قضايا", |
| ), |
| ) |
| actor_col = column_index( |
| headers, ("responsible", "authority", "institution", "agency", "actor") |
| ) |
| if rtl_recommendation_table: |
| actor_col = None |
| priority_col = column_index(headers, ("priority", "prioridad", "priorité")) |
| time_col = column_index( |
| headers, ("timeframe", "timing", "timeline", "deadline", "term") |
| ) |
| section = f"recommendation table {table_number}" |
| for row_number, row in enumerate(cells[row_start:], start=1): |
| if rec_col >= len(row): |
| continue |
| rec_text = row[rec_col] |
| if ( |
| len(rec_text) < 15 |
| or len(token_set(rec_text)) < 3 |
| or RECOMMENDATION_HEADING_RE.fullmatch(rec_text) |
| or RECOMMENDATION_TABLE_HEADER_RE.fullmatch(rec_text) |
| ): |
| continue |
| actor = row[actor_col] if actor_col is not None and actor_col < len(row) else None |
| priority_raw = row[priority_col] if priority_col is not None and priority_col < len(row) else "" |
| time_raw = row[time_col] if time_col is not None and time_col < len(row) else "" |
| paragraph_key = f"p{page_number}-table{table_number}-row{row_number}" |
| rec_index = add_unique( |
| recommendations, |
| recommendation_item( |
| report_id, |
| page_number, |
| rec_text, |
| section=section, |
| method="recommendation_table", |
| confidence=0.98, |
| actor=actor or None, |
| priority=parse_priority(priority_raw), |
| timeframe=time_raw or parse_timeframe(rec_text), |
| paragraph_key=paragraph_key, |
| ), |
| ) |
| if obs_col is not None and obs_col < len(row) and len(row[obs_col]) >= 15: |
| obs_text = row[obs_col] |
| obs_index = add_unique( |
| observations, |
| observation_item( |
| report_id, |
| page_number, |
| obs_text, |
| section=section, |
| method="observation_recommendation_table", |
| confidence=0.98, |
| paragraph_key=paragraph_key, |
| ), |
| ) |
| explicit_links.append( |
| ( |
| obs_index, |
| rec_index, |
| { |
| "relation": "addresses", |
| "link_basis": "explicit_table_row", |
| "confidence": 1.0, |
| "evidence": [evidence(report_id, page_number, " | ".join(row))], |
| "review_status": "unreviewed", |
| }, |
| ) |
| ) |
| return explicit_links |
|
|
|
|
| def paragraphs_with_sections(pages: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| output: list[dict[str, Any]] = [] |
| section = "" |
| for page in pages: |
| markdown = page["markdown"] |
| table_line_numbers = { |
| index |
| for index, line in enumerate(markdown.splitlines()) |
| if line.strip().startswith("|") and line.count("|") >= 2 |
| } |
| current: list[str] = [] |
| paragraph_counter = 0 |
|
|
| def flush() -> None: |
| nonlocal paragraph_counter |
| value = "\n".join(current).strip() |
| current.clear() |
| cleaned = clean_markdown(value) |
| if cleaned: |
| paragraph_counter += 1 |
| output.append( |
| { |
| "page": page["page"], |
| "section": section, |
| "raw": value, |
| "text": cleaned, |
| "key": f"p{page['page']}-para{paragraph_counter}", |
| } |
| ) |
|
|
| for line_number, line in enumerate(markdown.splitlines()): |
| heading_match = HEADING_RE.match(line) |
| if heading_match: |
| flush() |
| section = clean_markdown(heading_match.group(1)) |
| continue |
| if line_number in table_line_numbers: |
| flush() |
| continue |
| if not line.strip(): |
| flush() |
| else: |
| current.append(line) |
| flush() |
| return output |
|
|
|
|
| def valid_candidate(value: str) -> bool: |
| if not 25 <= len(value) <= 900: |
| return False |
| if value.count("_") > 5 or re.search(r"_{5,}|\.{5,}", value): |
| return False |
| if re.fullmatch(r"[\W\d_]+", value): |
| return False |
| if re.search(r"IMF (?:Technical Assistance|Country) Report\s*\|?\s*\d+", value, re.I): |
| return False |
| return True |
|
|
|
|
| def extract_body_candidates( |
| report_id: str, |
| pages: list[dict[str, Any]], |
| recommendations: list[dict[str, Any]], |
| observations: list[dict[str, Any]], |
| ) -> None: |
| for paragraph in paragraphs_with_sections(pages): |
| section = paragraph["section"] |
| if EXCLUDED_SECTION_RE.search(section): |
| continue |
| recommendation_section = bool(RECOMMENDATION_HEADING_RE.search(section)) |
| observation_section = bool(OBSERVATION_HEADING_RE.search(section)) |
| raw_starts_bullet = bool(re.match(r"\s*(?:[-*•]|\d+[.)])\s+", paragraph["raw"])) |
| for sentence in split_sentences(paragraph["text"]): |
| sentence = clean_markdown(sentence) |
| if not valid_candidate(sentence): |
| continue |
| has_modal = bool(RECOMMENDATION_MODAL_RE.search(sentence)) |
| imperative = bool(IMPERATIVE_RE.search(sentence)) |
| if has_modal or (recommendation_section and (imperative or raw_starts_bullet)): |
| confidence = 0.88 if recommendation_section else 0.72 |
| method = ( |
| "recommendation_section_sentence" |
| if recommendation_section |
| else "explicit_recommendation_modal" |
| ) |
| add_unique( |
| recommendations, |
| recommendation_item( |
| report_id, |
| paragraph["page"], |
| sentence, |
| section=section, |
| method=method, |
| confidence=confidence, |
| priority=parse_priority(sentence), |
| timeframe=parse_timeframe(sentence), |
| paragraph_key=paragraph["key"], |
| ), |
| ) |
| continue |
| has_signal = bool(OBSERVATION_SIGNAL_RE.search(sentence)) |
| numbered_finding = bool(re.match(r"^\d+\.\s+", paragraph["text"])) |
| if has_signal and (observation_section or numbered_finding or len(sentence) >= 50): |
| confidence = 0.82 if observation_section else 0.62 |
| add_unique( |
| observations, |
| observation_item( |
| report_id, |
| paragraph["page"], |
| sentence, |
| section=section, |
| method=( |
| "finding_section_sentence" |
| if observation_section |
| else "diagnostic_signal_sentence" |
| ), |
| confidence=confidence, |
| paragraph_key=paragraph["key"], |
| ), |
| ) |
|
|
|
|
| def parse_iso_date(year: int, month: int, day: int) -> str | None: |
| try: |
| return dt.date(year, month, day).isoformat() |
| except ValueError: |
| return None |
|
|
|
|
| def extract_date_mentions( |
| report_id: str, |
| title: str, |
| pages: list[dict[str, Any]], |
| publication_date: str | None, |
| source_page_url: str | None, |
| ) -> list[dict[str, Any]]: |
| dates: list[dict[str, Any]] = [] |
| url_date = None |
| if source_page_url: |
| match = re.search(r"/issues/(\d{4})/(\d{2})/(\d{2})/", source_page_url, re.I) |
| if match: |
| url_date = parse_iso_date(int(match.group(1)), int(match.group(2)), int(match.group(3))) |
| primary_publication_date = url_date or (publication_date[:10] if publication_date else None) |
| if primary_publication_date: |
| dates.append( |
| { |
| "type": "publication", |
| "start": primary_publication_date, |
| "end": primary_publication_date, |
| "precision": "day", |
| "verbatim": primary_publication_date, |
| "evidence": [ |
| {"source": "imf_publication_url" if url_date else "imf_index_metadata"} |
| ], |
| "confidence": 1.0 if not url_date else 0.98, |
| } |
| ) |
| if publication_date and publication_date[:10] != primary_publication_date: |
| dates.append( |
| { |
| "type": "imf_index_date", |
| "start": publication_date[:10], |
| "end": publication_date[:10], |
| "precision": "day", |
| "verbatim": publication_date, |
| "evidence": [{"source": "imf_index_metadata"}], |
| "confidence": 1.0, |
| } |
| ) |
| search_sources = [(0, title)] + [ |
| (page["page"], page["text"]) for page in pages[:6] |
| ] |
| seen: set[tuple[str, str | None, str | None]] = set() |
| for page_number, text in search_sources: |
| for pattern, cross_month in ((CROSS_MONTH_RANGE_RE, True), (SAME_MONTH_RANGE_RE, False)): |
| for match in pattern.finditer(text): |
| year = int(match.group("year")) |
| if cross_month: |
| start_month = MONTHS[match.group("month1").lower()] |
| end_month = MONTHS[match.group("month2").lower()] |
| else: |
| start_month = end_month = MONTHS[match.group("month").lower()] |
| start = parse_iso_date(year, start_month, int(match.group("start"))) |
| end = parse_iso_date(year, end_month, int(match.group("end"))) |
| key = ("mission_or_report_range", start, end) |
| if start and end and key not in seen: |
| seen.add(key) |
| quote = match.group(0) |
| dates.append( |
| { |
| "type": "mission_or_report_range", |
| "start": start, |
| "end": end, |
| "precision": "day", |
| "verbatim": quote, |
| "evidence": ( |
| [evidence(report_id, page_number, quote)] |
| if page_number |
| else [{"source": "title", "quote": quote}] |
| ), |
| "confidence": 0.8, |
| } |
| ) |
| for match in SINGLE_DATE_RE.finditer(text): |
| year = int(match.group("year")) |
| value = parse_iso_date(year, MONTHS[match.group("month").lower()], int(match.group("day"))) |
| key = ("date_mention", value, value) |
| if value and key not in seen: |
| seen.add(key) |
| quote = match.group(0) |
| dates.append( |
| { |
| "type": "date_mention", |
| "start": value, |
| "end": value, |
| "precision": "day", |
| "verbatim": quote, |
| "evidence": ( |
| [evidence(report_id, page_number, quote)] |
| if page_number |
| else [{"source": "title", "quote": quote}] |
| ), |
| "confidence": 0.65, |
| } |
| ) |
| return dates |
|
|
|
|
| def prepared_by_statement(pages: list[dict[str, Any]]) -> tuple[int, str, str] | None: |
| stop_re = re.compile( |
| r"^(?:authoring\s+)?departments?\b|^approved\b|^authorized\b|" |
| r"^international monetary fund\b|^the mission\b|^prepared for\b", |
| re.I, |
| ) |
| department_phrase_re = re.compile( |
| r"\b(fiscal affairs|monetary and capital markets|statistics|legal|" |
| r"institute for capacity development|finance|research|department)\b", |
| re.I, |
| ) |
| for page in pages[:8]: |
| lines = [line.strip(" \t:;") for line in page["text"].splitlines()] |
| for index, line in enumerate(lines): |
| match = re.search(r"\bPrepared\s+by\b\s*[:\-]?\s*(.*)$", line, re.I) |
| if not match: |
| continue |
| collected = [match.group(1).strip()] if match.group(1).strip() else [] |
| stop_line = "" |
| for candidate in lines[index + 1 : index + 10]: |
| if not candidate: |
| continue |
| if stop_re.search(candidate): |
| stop_line = candidate |
| break |
| if re.fullmatch(r"(?:[A-Z][A-Z .&/-]+|\d{4})", candidate) and collected: |
| break |
| collected.append(candidate) |
| if len(collected) >= 4: |
| break |
| if stop_line.lower() == "department" and len(collected) > 1: |
| if department_phrase_re.search(collected[-1]): |
| collected.pop() |
| statement = re.sub( |
| r"\s+", " ", " ".join(collected).replace("_", " ") |
| ).strip(" .,;") |
| if 2 <= len(statement) <= 300: |
| raw_quote = "Prepared By\n" + "\n".join(collected) |
| return page["page"], statement, raw_quote |
| return None |
|
|
|
|
| def split_prepared_by_names(statement: str) -> list[str]: |
| normalized = re.sub(r"\s+(?:and|&)\s+", ",", statement, flags=re.I) |
| parts = [part.strip(" .;,") for part in re.split(r"[,;]", normalized)] |
| plausible = [] |
| for part in parts: |
| words = re.findall(r"[^\W\d_]+", part, flags=re.UNICODE) |
| if 2 <= len(words) <= 10 and not re.search(r"\b(department|division|team|staff)\b", part, re.I): |
| plausible.append(part) |
| return plausible or [statement] |
|
|
|
|
| def extract_authors( |
| report_id: str, report: dict[str, Any], document: dict[str, Any], pages: list[dict[str, Any]] |
| ) -> list[dict[str, Any]]: |
| authors: list[dict[str, Any]] = [] |
| indexed = report.get("author_indexed") |
| if indexed: |
| authors.append( |
| { |
| "name": indexed, |
| "role": "indexed_institutional_author", |
| "evidence": [{"source": "imf_index_metadata"}], |
| "confidence": 1.0, |
| } |
| ) |
| pdf_author = (document.get("pdf_metadata") or {}).get("author") |
| if pdf_author and pdf_author.lower() not in {str(indexed).lower(), "imf"}: |
| authors.append( |
| { |
| "name": pdf_author, |
| "role": "pdf_metadata_author", |
| "evidence": [{"source": "pdf_metadata"}], |
| "confidence": 0.9, |
| } |
| ) |
| prepared = prepared_by_statement(pages) |
| if prepared: |
| page_number, statement, quote = prepared |
| for name in split_prepared_by_names(statement): |
| if all(name.lower() != author["name"].lower() for author in authors): |
| authors.append( |
| { |
| "name": name, |
| "role": "prepared_by", |
| "verbatim_statement": statement, |
| "evidence": [evidence(report_id, page_number, quote)], |
| "confidence": 0.82, |
| } |
| ) |
| return authors |
|
|
|
|
| def extract_authoring_departments(report_id: str, pages: list[dict[str, Any]]) -> list[dict[str, Any]]: |
| departments: list[dict[str, Any]] = [] |
| known_re = re.compile( |
| r"\b(Fiscal Affairs Department|Monetary and Capital Markets Department|" |
| r"Statistics Department|Legal Department|Institute for Capacity Development|" |
| r"Research Department|Finance Department)\b", |
| re.I, |
| ) |
| for page in pages[:8]: |
| for match in known_re.finditer(re.sub(r"\s+", " ", page["text"])): |
| name = match.group(1) |
| if all(name.lower() != item["name"].lower() for item in departments): |
| departments.append( |
| { |
| "name": name, |
| "evidence": [evidence(report_id, page["page"], match.group(0))], |
| "confidence": 0.9, |
| } |
| ) |
| return departments |
|
|
|
|
| def extract_identifiers(pages: list[dict[str, Any]], report: dict[str, Any]) -> dict[str, Any]: |
| text = "\n".join(page["text"] for page in pages[:8]) |
| dois = sorted({match.group(0).rstrip(".,;)") for match in DOI_RE.finditer(text)}) |
| isbns = [] |
| for match in ISBN_RE.finditer(text): |
| compact = re.sub(r"[ -]", "", match.group(0)).upper() |
| if len(compact) in {10, 13} and compact not in isbns: |
| isbns.append(compact) |
| return { |
| "series": report.get("series", []), |
| "series_volume_no": report.get("series_volume_no"), |
| "doi": dois, |
| "isbn": isbns, |
| "subjects": report.get("subjects", []), |
| "topics": report.get("topics", []), |
| "keywords": report.get("keywords", []), |
| "description_indexed": report.get("description"), |
| } |
|
|
|
|
| def classify_recommendation(item: dict[str, Any]) -> None: |
| """Assign an explicitness taxonomy without discarding recall-oriented candidates.""" |
| text = item["verbatim"] |
| method = item["extraction_method"] |
| strong_explicit = bool(STRONG_EXPLICIT_RECOMMENDATION_RE.search(text)) |
| direct_action = bool(IMPERATIVE_RE.search(text) or RECOMMENDATION_MODAL_RE.search(text)) |
|
|
| if method == "recommendation_table": |
| recommendation_type = "explicit_table" |
| explicitness = "explicit" |
| tier = "high" |
| conservative = True |
| confidence = 0.98 |
| elif strong_explicit: |
| recommendation_type = "explicit_attributed_statement" |
| explicitness = "explicit" |
| tier = "high" |
| conservative = True |
| confidence = 0.92 |
| elif method == "recommendation_section_sentence" and direct_action: |
| recommendation_type = "direct_action_in_recommendation_section" |
| explicitness = "direct_normative" |
| tier = "high" |
| conservative = True |
| confidence = 0.85 |
| elif method == "explicit_recommendation_modal": |
| recommendation_type = "normative_modal_candidate" |
| explicitness = "implicit_candidate" |
| tier = "medium" |
| conservative = False |
| confidence = 0.65 |
| else: |
| recommendation_type = "recommendation_section_context_candidate" |
| explicitness = "context_candidate" |
| tier = "low" |
| conservative = False |
| confidence = 0.35 |
|
|
| item["recommendation_type"] = recommendation_type |
| item["explicitness"] = explicitness |
| item["confidence_tier"] = tier |
| item["in_conservative_set"] = conservative |
| item["confidence"] = confidence |
|
|
|
|
| def finalize_entities( |
| report_id: str, |
| recommendations: list[dict[str, Any]], |
| observations: list[dict[str, Any]], |
| explicit_links: list[tuple[int, int, dict[str, Any]]], |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: |
| for item in recommendations: |
| classify_recommendation(item) |
| recommendations.sort(key=lambda item: (item["_page"], -item["confidence"], item["verbatim"])) |
| observations.sort(key=lambda item: (item["_page"], -item["confidence"], item["verbatim"])) |
| |
| |
| rec_by_paragraph = defaultdict(list) |
| obs_by_paragraph = defaultdict(list) |
| for index, item in enumerate(recommendations): |
| rec_by_paragraph[item.get("_paragraph_key")].append(index) |
| for index, item in enumerate(observations): |
| obs_by_paragraph[item.get("_paragraph_key")].append(index) |
|
|
| for index, item in enumerate(recommendations, start=1): |
| item["recommendation_id"] = f"{report_id}-rec-{index:04d}" |
| for index, item in enumerate(observations, start=1): |
| item["observation_id"] = f"{report_id}-obs-{index:04d}" |
|
|
| links: list[dict[str, Any]] = [] |
| seen_pairs: set[tuple[str, str, str]] = set() |
|
|
| |
| explicit_keys = { |
| recommendations[rec_index].get("_paragraph_key") |
| for _, rec_index, _ in explicit_links |
| if 0 <= rec_index < len(recommendations) |
| } |
| |
| |
| explicit_keys.update( |
| item.get("_paragraph_key") |
| for item in recommendations |
| if item.get("extraction_method") == "recommendation_table" |
| ) |
| for key in explicit_keys: |
| if not key: |
| continue |
| for obs_index in obs_by_paragraph.get(key, []): |
| for rec_index in rec_by_paragraph.get(key, []): |
| obs = observations[obs_index] |
| rec = recommendations[rec_index] |
| pair = (obs["observation_id"], rec["recommendation_id"], "explicit_table_row") |
| if pair in seen_pairs: |
| continue |
| seen_pairs.add(pair) |
| links.append( |
| { |
| "observation_id": obs["observation_id"], |
| "recommendation_id": rec["recommendation_id"], |
| "relation": "addresses", |
| "link_basis": "explicit_table_row", |
| "evidence": rec["evidence"], |
| "confidence": 1.0, |
| "review_status": "unreviewed", |
| "recommendation_type": rec["recommendation_type"], |
| "recommendation_confidence_tier": rec["confidence_tier"], |
| "conservative_recommendation": rec["in_conservative_set"], |
| } |
| ) |
|
|
| |
| for rec in recommendations: |
| key = rec.get("_paragraph_key") |
| if not key: |
| continue |
| for obs_index in obs_by_paragraph.get(key, []): |
| obs = observations[obs_index] |
| pair = (obs["observation_id"], rec["recommendation_id"], "same_paragraph") |
| if any(existing[:2] == pair[:2] for existing in seen_pairs): |
| continue |
| seen_pairs.add(pair) |
| links.append( |
| { |
| "observation_id": obs["observation_id"], |
| "recommendation_id": rec["recommendation_id"], |
| "relation": "responds_to_context", |
| "link_basis": "same_paragraph", |
| "evidence": rec["evidence"], |
| "confidence": 0.78, |
| "review_status": "unreviewed", |
| "recommendation_type": rec["recommendation_type"], |
| "recommendation_confidence_tier": rec["confidence_tier"], |
| "conservative_recommendation": rec["in_conservative_set"], |
| } |
| ) |
|
|
| |
| linked_recommendations = {link["recommendation_id"] for link in links} |
| for rec in recommendations: |
| if rec["recommendation_id"] in linked_recommendations: |
| continue |
| candidates = [] |
| for obs in observations: |
| if abs(obs["_page"] - rec["_page"]) > 1: |
| continue |
| score = similarity(obs["verbatim"], rec["verbatim"]) |
| if score >= 0.12: |
| candidates.append((score, obs)) |
| if candidates: |
| score, obs = max(candidates, key=lambda item: item[0]) |
| links.append( |
| { |
| "observation_id": obs["observation_id"], |
| "recommendation_id": rec["recommendation_id"], |
| "relation": "contextually_associated_with", |
| "link_basis": "same_or_adjacent_page_lexical_similarity", |
| "evidence": rec["evidence"], |
| "confidence": round(min(0.65, 0.4 + score), 3), |
| "review_status": "unreviewed", |
| "recommendation_type": rec["recommendation_type"], |
| "recommendation_confidence_tier": rec["confidence_tier"], |
| "conservative_recommendation": rec["in_conservative_set"], |
| } |
| ) |
|
|
| for collection in (recommendations, observations): |
| for item in collection: |
| for key in list(item): |
| if key.startswith("_"): |
| del item[key] |
| links.sort(key=lambda item: (item["recommendation_id"], item["observation_id"])) |
| return recommendations, observations, links |
|
|
|
|
| def report_schema() -> dict[str, Any]: |
| evidence_schema = { |
| "type": "object", |
| "properties": { |
| "evidence_id": {"type": "string"}, |
| "page": {"type": "integer", "minimum": 1}, |
| "quote": {"type": "string"}, |
| "source": {"type": "string"}, |
| }, |
| "required": ["source"], |
| "additionalProperties": True, |
| } |
| return { |
| "$schema": "https://json-schema.org/draft/2020-12/schema", |
| "$id": "https://cd-eval.local/schemas/report.schema.json", |
| "title": "IMF Technical Assistance Structured Report", |
| "type": "object", |
| "required": [ |
| "schema_version", "report_id", "source_sha256", "title", "authors", |
| "countries", "dates", "metadata", "observations", "recommendations", |
| "observation_recommendation_links", "figures", "extraction", |
| ], |
| "properties": { |
| "schema_version": {"const": SCHEMA_VERSION}, |
| "report_id": {"type": "string"}, |
| "source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, |
| "title": {"type": "string"}, |
| "language": {"type": "array", "items": {"type": "string"}}, |
| "authors": {"type": "array", "items": {"type": "object"}}, |
| "countries": {"type": "array", "items": {"type": "object"}}, |
| "dates": {"type": "array", "items": {"type": "object"}}, |
| "metadata": {"type": "object"}, |
| "observations": { |
| "type": "array", |
| "items": { |
| "type": "object", |
| "required": ["observation_id", "text", "verbatim", "evidence", "confidence"], |
| "properties": {"evidence": {"type": "array", "items": evidence_schema}}, |
| "additionalProperties": True, |
| }, |
| }, |
| "recommendations": { |
| "type": "array", |
| "items": { |
| "type": "object", |
| "required": [ |
| "recommendation_id", "text", "verbatim", "evidence", "confidence", |
| "recommendation_type", "explicitness", "confidence_tier", |
| "in_conservative_set", |
| ], |
| "properties": {"evidence": {"type": "array", "items": evidence_schema}}, |
| "additionalProperties": True, |
| }, |
| }, |
| "observation_recommendation_links": { |
| "type": "array", |
| "items": { |
| "type": "object", |
| "required": [ |
| "observation_id", "recommendation_id", "relation", "link_basis", |
| "evidence", "confidence", |
| ], |
| "additionalProperties": True, |
| }, |
| }, |
| "figures": {"type": "array", "items": {"type": "object"}}, |
| "extraction": {"type": "object"}, |
| }, |
| "additionalProperties": False, |
| } |
|
|
|
|
| def validate_evidence_grounding(record: dict[str, Any], pages: list[dict[str, Any]]) -> list[str]: |
| errors: list[str] = [] |
| page_text = {page["page"]: normalize_evidence(page["text"] + " " + page["markdown"]) for page in pages} |
| page_count = len(pages) |
| for kind in ("observations", "recommendations"): |
| for item in record[kind]: |
| if not item.get("evidence"): |
| errors.append(f"{kind}:{item.get(kind[:-1] + '_id')}: missing evidence") |
| for entry in item.get("evidence", []): |
| page = entry.get("page") |
| quote = normalize_evidence(entry.get("quote", "")) |
| if not isinstance(page, int) or not 1 <= page <= page_count: |
| errors.append(f"{kind}: invalid page {page}") |
| elif quote and quote not in page_text.get(page, ""): |
| |
| |
| compact_quote = re.sub(r"\s+", "", quote) |
| compact_page = re.sub(r"\s+", "", page_text.get(page, "")) |
| quote_tokens = token_set(quote) |
| page_tokens = token_set(page_text.get(page, "")) |
| token_coverage = len(quote_tokens & page_tokens) / max(1, len(quote_tokens)) |
| if compact_quote not in compact_page and token_coverage < 0.9: |
| errors.append(f"{kind}: evidence not grounded on page {page}: {entry.get('quote','')[:80]}") |
| observation_ids = {item["observation_id"] for item in record["observations"]} |
| recommendation_ids = {item["recommendation_id"] for item in record["recommendations"]} |
| for link in record["observation_recommendation_links"]: |
| if link["observation_id"] not in observation_ids: |
| errors.append(f"link unknown observation {link['observation_id']}") |
| if link["recommendation_id"] not in recommendation_ids: |
| errors.append(f"link unknown recommendation {link['recommendation_id']}") |
| return errors |
|
|
|
|
| def global_figures_for_report(interim_dir: Path, report_id: str) -> list[dict[str, Any]]: |
| cache_key = interim_dir.resolve().as_posix() |
| if cache_key not in _GLOBAL_FIGURES_CACHE: |
| grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) |
| for figure in load_jsonl(interim_dir / "figures.jsonl"): |
| grouped[figure["report_id"]].append(figure) |
| _GLOBAL_FIGURES_CACHE[cache_key] = dict(grouped) |
| return _GLOBAL_FIGURES_CACHE[cache_key].get(report_id, []) |
|
|
|
|
| def extract_one(job: dict[str, Any]) -> dict[str, Any]: |
| report = job["report"] |
| source = job["manifest"] |
| report_id = report["report_id"] |
| interim_report_dir = Path(job["interim_dir"]) / report_id |
| processed_dir = Path(job["processed_dir"]) |
| final_path = processed_dir / "reports" / f"{report_id}.json" |
| refresh = bool(job.get("refresh")) |
|
|
| if final_path.exists() and not refresh: |
| existing = load_json(final_path) |
| if ( |
| existing.get("source_sha256") == source["sha256"] |
| and existing.get("extraction", {}).get("extractor_version") == EXTRACTOR_VERSION |
| ): |
| return { |
| "report_id": report_id, |
| "status": "existing", |
| "record": existing, |
| "validation_errors": [], |
| } |
|
|
| pages = load_jsonl(interim_report_dir / "pages.jsonl") |
| document = load_json(interim_report_dir / "document.json") |
| figures = global_figures_for_report(Path(job["interim_dir"]), report_id) |
| if not pages: |
| raise RuntimeError(f"missing interim pages for {report_id}") |
|
|
| recommendations: list[dict[str, Any]] = [] |
| observations: list[dict[str, Any]] = [] |
| explicit_links = extract_tables(report_id, pages, recommendations, observations) |
| extract_body_candidates(report_id, pages, recommendations, observations) |
| |
| if len(recommendations) > 250: |
| recommendations = sorted(recommendations, key=lambda item: -item["confidence"])[:250] |
| if len(observations) > 300: |
| observations = sorted(observations, key=lambda item: -item["confidence"])[:300] |
| recommendations, observations, links = finalize_entities( |
| report_id, recommendations, observations, explicit_links |
| ) |
|
|
| countries = [] |
| formal = report.get("formal_countries", []) |
| iso_codes = report.get("iso_codes", []) |
| names = report.get("countries", []) or formal |
| country_source = "imf_index_metadata" |
| country_confidence = 1.0 |
| if not names and ":" in (report.get("title") or ""): |
| names = [(report["title"].split(":", 1)[0]).strip()] |
| country_source = "title_prefix_fallback" |
| country_confidence = 0.9 |
| fallback_iso = { |
| "armenia": "ARM", |
| "republic of armenia": "ARM", |
| "kosovo": "XKX", |
| "republic of kosovo": "XKX", |
| "democratic republic of the congo": "COD", |
| } |
| for index, name in enumerate(names): |
| countries.append( |
| { |
| "name": name, |
| "formal_name": formal[index] if index < len(formal) else None, |
| "iso3": ( |
| iso_codes[index] |
| if index < len(iso_codes) |
| else fallback_iso.get(name.lower()) |
| ), |
| "evidence": [{"source": country_source}], |
| "confidence": country_confidence, |
| } |
| ) |
|
|
| record = { |
| "schema_version": SCHEMA_VERSION, |
| "report_id": report_id, |
| "source_sha256": source["sha256"], |
| "title": report.get("title") or "", |
| "language": report.get("language", []), |
| "authors": extract_authors(report_id, report, document, pages), |
| "countries": countries, |
| "dates": extract_date_mentions( |
| report_id, |
| report.get("title") or "", |
| pages, |
| report.get("publication_date"), |
| report.get("source_page_url"), |
| ), |
| "metadata": { |
| **extract_identifiers(pages, report), |
| "authoring_departments": extract_authoring_departments(report_id, pages), |
| "source_page_url": report.get("source_page_url"), |
| "source_pdf_url": source.get("source_pdf_url"), |
| "page_count": document["page_count"], |
| "interim_extraction_method": document["extraction_method"], |
| "needs_ocr_pages": document.get("needs_ocr_pages", []), |
| }, |
| "observations": observations, |
| "recommendations": recommendations, |
| "observation_recommendation_links": links, |
| "figures": figures, |
| "extraction": { |
| "method": EXTRACTION_METHOD, |
| "extractor_version": EXTRACTOR_VERSION, |
| "generated_at": utc_now(), |
| "review_status": "unreviewed", |
| "evidence_requirement": "page-grounded verbatim source span", |
| "limitations": [ |
| "Automated deterministic baseline; not a human-annotated gold record.", |
| "The recommendations array is recall-oriented and includes classified candidates; use in_conservative_set=true for the higher-precision subset.", |
| "Contextual links are proximity/lexical associations unless link_basis is explicit_table_row.", |
| "Priority, timeframe, and actor are null when not explicit in a recommendation table or sentence.", |
| ], |
| }, |
| } |
| schema_errors = [error.message for error in jsonschema.Draft202012Validator(report_schema()).iter_errors(record)] |
| grounding_errors = validate_evidence_grounding(record, pages) |
| errors = schema_errors + grounding_errors |
| final_path.parent.mkdir(parents=True, exist_ok=True) |
| write_json(final_path, record) |
| return { |
| "report_id": report_id, |
| "status": "extracted", |
| "record": record, |
| "validation_errors": errors, |
| } |
|
|
|
|
| def flatten_outputs( |
| results: list[dict[str, Any]], processed_dir: Path, failures: list[dict[str, str]] |
| ) -> dict[str, Any]: |
| records = [result["record"] for result in results] |
| records.sort(key=lambda record: record["report_id"]) |
| write_jsonl(processed_dir / "reports.jsonl", records) |
| write_jsonl( |
| processed_dir / "observations.jsonl", |
| ( |
| {"report_id": record["report_id"], **item} |
| for record in records |
| for item in record["observations"] |
| ), |
| ) |
| write_jsonl( |
| processed_dir / "recommendations.jsonl", |
| ( |
| {"report_id": record["report_id"], **item} |
| for record in records |
| for item in record["recommendations"] |
| ), |
| ) |
| write_jsonl( |
| processed_dir / "recommendations_conservative.jsonl", |
| ( |
| {"report_id": record["report_id"], **item} |
| for record in records |
| for item in record["recommendations"] |
| if item["in_conservative_set"] |
| ), |
| ) |
| write_jsonl( |
| processed_dir / "observation_recommendation_links.jsonl", |
| ( |
| {"report_id": record["report_id"], **item} |
| for record in records |
| for item in record["observation_recommendation_links"] |
| ), |
| ) |
| write_jsonl( |
| processed_dir / "observation_recommendation_links_conservative.jsonl", |
| ( |
| {"report_id": record["report_id"], **item} |
| for record in records |
| for item in record["observation_recommendation_links"] |
| if item.get("conservative_recommendation") |
| ), |
| ) |
| write_jsonl( |
| processed_dir / "figures.jsonl", |
| ( |
| item for record in records for item in record["figures"] |
| ), |
| ) |
| validation_errors = [ |
| {"report_id": result["report_id"], "errors": result["validation_errors"]} |
| for result in results |
| if result["validation_errors"] |
| ] |
| recommendation_type_counts = Counter( |
| item["recommendation_type"] |
| for record in records |
| for item in record["recommendations"] |
| ) |
| recommendation_tier_counts = Counter( |
| item["confidence_tier"] |
| for record in records |
| for item in record["recommendations"] |
| ) |
| conservative_recommendation_count = sum( |
| item["in_conservative_set"] |
| for record in records |
| for item in record["recommendations"] |
| ) |
| conservative_link_count = sum( |
| item.get("conservative_recommendation", False) |
| for record in records |
| for item in record["observation_recommendation_links"] |
| ) |
| reports_with_no_conservative_recommendations = [ |
| record["report_id"] |
| for record in records |
| if not any(item["in_conservative_set"] for item in record["recommendations"]) |
| ] |
| summary = { |
| "updated_at": utc_now(), |
| "schema_version": SCHEMA_VERSION, |
| "extractor_version": EXTRACTOR_VERSION, |
| "method": EXTRACTION_METHOD, |
| "report_count": len(records), |
| "observation_count": sum(len(record["observations"]) for record in records), |
| "recommendation_count": sum(len(record["recommendations"]) for record in records), |
| "recommendation_candidate_count": sum( |
| len(record["recommendations"]) for record in records |
| ), |
| "conservative_recommendation_count": conservative_recommendation_count, |
| "conservative_recommendation_report_count": ( |
| len(records) - len(reports_with_no_conservative_recommendations) |
| ), |
| "reports_with_no_conservative_recommendations": ( |
| reports_with_no_conservative_recommendations |
| ), |
| "recommendation_type_counts": dict(sorted(recommendation_type_counts.items())), |
| "recommendation_confidence_tier_counts": dict( |
| sorted(recommendation_tier_counts.items()) |
| ), |
| "link_count": sum(len(record["observation_recommendation_links"]) for record in records), |
| "conservative_link_count": conservative_link_count, |
| "explicit_table_link_count": sum( |
| link["link_basis"] == "explicit_table_row" |
| for record in records |
| for link in record["observation_recommendation_links"] |
| ), |
| "figure_count": sum(len(record["figures"]) for record in records), |
| "reports_with_no_observations": [ |
| record["report_id"] for record in records if not record["observations"] |
| ], |
| "reports_with_no_recommendations": [ |
| record["report_id"] for record in records if not record["recommendations"] |
| ], |
| "validation_error_report_count": len(validation_errors), |
| "validation_errors": validation_errors, |
| "failed_count": len(failures), |
| "failures": failures, |
| "review_status": "unreviewed_automated_baseline", |
| "recommendation_taxonomy": { |
| "explicit_table": "A recommendation/action row in a report table explicitly designated for recommendations or an action plan.", |
| "explicit_attributed_statement": "Text explicitly attributed as a recommendation (for example, 'the mission recommends' or 'is recommended').", |
| "direct_action_in_recommendation_section": "An imperative or normative action inside a recommendation section.", |
| "normative_modal_candidate": "A should/must/need-to statement outside a recommendation section; retained for recall but not in the conservative set.", |
| "recommendation_section_context_candidate": "Context in a recommendation section without a direct action signal; low-confidence candidate.", |
| }, |
| } |
| write_json(processed_dir / "validation_summary.json", summary) |
| write_json( |
| processed_dir / "recommendation_taxonomy.json", |
| { |
| "schema_version": SCHEMA_VERSION, |
| "definitions": summary["recommendation_taxonomy"], |
| "type_counts": summary["recommendation_type_counts"], |
| "confidence_tier_counts": summary[ |
| "recommendation_confidence_tier_counts" |
| ], |
| "candidate_count": summary["recommendation_candidate_count"], |
| "conservative_count": summary["conservative_recommendation_count"], |
| }, |
| ) |
| write_json(processed_dir / "schemas" / "report.schema.json", report_schema()) |
| return summary |
|
|
|
|
| def extract_corpus( |
| inventory: list[dict[str, Any]], |
| manifest: list[dict[str, Any]], |
| *, |
| interim_dir: Path, |
| processed_dir: Path, |
| workers: int, |
| refresh: bool, |
| ) -> dict[str, Any]: |
| source_by_id = {row["report_id"]: row for row in manifest} |
| jobs = [ |
| { |
| "report": report, |
| "manifest": source_by_id[report["report_id"]], |
| "interim_dir": interim_dir.as_posix(), |
| "processed_dir": processed_dir.as_posix(), |
| "refresh": refresh, |
| } |
| for report in inventory |
| ] |
| results: list[dict[str, Any]] = [] |
| failures: list[dict[str, str]] = [] |
| with concurrent.futures.ProcessPoolExecutor(max_workers=max(1, workers)) as pool: |
| futures = {pool.submit(extract_one, job): job for job in jobs} |
| for future in concurrent.futures.as_completed(futures): |
| job = futures[future] |
| try: |
| result = future.result() |
| results.append(result) |
| status = result["status"] |
| except Exception as exc: |
| failures.append( |
| { |
| "report_id": job["report"]["report_id"], |
| "error": f"{type(exc).__name__}: {exc}", |
| } |
| ) |
| status = "failed" |
| print( |
| f"extract: {len(results) + len(failures)}/{len(jobs)} {status}: " |
| f"{job['report']['report_id']}", |
| file=sys.stderr, |
| ) |
| summary = flatten_outputs(results, processed_dir, failures) |
| return summary |
|
|
|
|
| def select_reports( |
| inventory: list[dict[str, Any]], limit: int | None, ids: str | None |
| ) -> list[dict[str, Any]]: |
| if ids: |
| selected_ids = {value.strip() for value in ids.split(",") if value.strip()} |
| missing = selected_ids - {row["report_id"] for row in inventory} |
| if missing: |
| raise SystemExit(f"unknown report IDs: {sorted(missing)}") |
| inventory = [row for row in inventory if row["report_id"] in selected_ids] |
| if limit is not None: |
| inventory = inventory[:limit] |
| return inventory |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(description="Extract structured IMF recommendations and observations") |
| parser.add_argument("--raw-dir", type=Path, default=Path("data/raw")) |
| parser.add_argument("--interim-dir", type=Path, default=Path("data/interim")) |
| parser.add_argument("--processed-dir", type=Path, default=Path("data/processed")) |
| parser.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1)) |
| parser.add_argument("--limit", type=int) |
| parser.add_argument("--ids", help="comma-separated report IDs") |
| parser.add_argument("--refresh", action="store_true") |
| return parser |
|
|
|
|
| def main(argv: Sequence[str] | None = None) -> int: |
| args = build_parser().parse_args(argv) |
| inventory = load_jsonl(args.raw_dir / "manifests" / "inventory.jsonl") |
| manifest = load_jsonl(args.raw_dir / "manifests" / "download_manifest.jsonl") |
| if not inventory or not manifest: |
| raise SystemExit("raw inventory/download manifest is missing") |
| inventory = select_reports(inventory, args.limit, args.ids) |
| missing_interim = [ |
| report["report_id"] |
| for report in inventory |
| if not (args.interim_dir / report["report_id"] / "document.json").exists() |
| ] |
| if missing_interim: |
| raise SystemExit( |
| f"interim conversion missing for {len(missing_interim)} report(s); " |
| "run imf-process convert first" |
| ) |
| summary = extract_corpus( |
| inventory, |
| manifest, |
| interim_dir=args.interim_dir, |
| processed_dir=args.processed_dir, |
| workers=args.workers, |
| refresh=args.refresh, |
| ) |
| print(json.dumps(summary, ensure_ascii=False, indent=2), file=sys.stderr) |
| return 1 if summary["failed_count"] else 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|