#!/usr/bin/env python3 """ extract.py — cohort-aware extraction of the author + work sets from Elasticsearch. Canonical home of the extraction logic (spike_audit.py and build.py both use it). The author set is a UNION OF TWO QUERIES (a correctness requirement found during the seed audit — group 2 recovers ~4% of authors that group 1 silently drops): 1. backend_compatible last_known_institutions in the cohort AND a recent cohort affiliation (years >= extraction.affiliation_years_gte) 2. empty_last_known_recent recent cohort affiliation but NO last_known_institutions The cohort is the list of OpenAlex institution IDs from `cohorts..institution_ids` in multiplicators.yaml (falling back to the primary ID alone). This exists because OpenAlex does NOT model university hospitals as lineage children — matching only the primary institution excluded ~2,400 active UDE clinicians. The work set is ALL works by those authors, globally (full authorship lists incl. external co-authors — required for the bridging signals), paginated with search_after over an id sort, batched ~250 author IDs per terms query. """ from __future__ import annotations import gzip import json import os import time from pathlib import Path from typing import Any, Iterable, Iterator import httpx import yaml from dotenv import load_dotenv SCRIPT_DIR = Path(__file__).resolve().parent ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env" load_dotenv(dotenv_path=ENV_PATH) NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/") NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or "" INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/") INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or "" AUTHOR_PAGE_SIZE = 1000 AUTHOR_BATCH_SIZE = 250 WORK_PAGE_SIZE = 1000 REQUEST_TIMEOUT = 180.0 # --------------------------------------------------------------------- # ES helpers # --------------------------------------------------------------------- def _headers(api_key: str) -> dict[str, str]: return { "Authorization": f"ApiKey {api_key}", "Content-Type": "application/json", "Accept": "application/json", } def es_request( client: httpx.Client, method: str, base_url: str, api_key: str, path: str, body: dict[str, Any] | None = None, ) -> httpx.Response: url = f"{base_url}/{path.lstrip('/')}" return client.request( method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT ) def es_search( client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any] ) -> dict[str, Any]: response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body) if not response.is_success: raise RuntimeError( f"ES error {response.status_code} for {index}:\n{response.text[:1000]}" ) return response.json() # --------------------------------------------------------------------- # Config / cohort # --------------------------------------------------------------------- def load_config(path: str | Path) -> dict[str, Any]: with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {} def cohort_ids_for(config: dict[str, Any], primary_short_id: str) -> list[str]: cohort = (config.get("cohorts") or {}).get(primary_short_id) or {} ids = cohort.get("institution_ids") return [str(i) for i in ids] if ids else [primary_short_id] def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]: """Look up ror + display_name from openalex-institutions.""" short = institution_id.strip().rsplit("/", 1)[-1] full = f"https://openalex.org/{short}" result = es_search( client, NES_URL, NES_KEY, "openalex-institutions", {"size": 1, "query": {"term": {"id": full}}}, ) hits = result["hits"]["hits"] if not hits: raise SystemExit(f"Institution {full} not found in openalex-institutions.") source = hits[0]["_source"] return { "id": full, "short_id": short, "ror": source.get("ror"), "display_name": source.get("display_name"), } # --------------------------------------------------------------------- # Author queries # --------------------------------------------------------------------- def recent_affiliation_filter( insts: list[dict[str, Any]], year_gte: int ) -> dict[str, Any]: """Recent affiliation with ANY cohort institution (matched by id, ror as backup).""" ids = [i["id"] for i in insts] shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}] rors = [i["ror"] for i in insts if i.get("ror")] if rors: shoulds.append({"terms": {"affiliations.institution.ror": rors}}) return { "nested": { "path": "affiliations", "query": { "bool": { "filter": [ {"bool": {"should": shoulds, "minimum_should_match": 1}}, {"range": {"affiliations.years": {"gte": year_gte}}}, ] } }, } } def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]: return { "nested": { "path": "last_known_institutions", "query": { "terms": {"last_known_institutions.id": [i["id"] for i in insts]} }, } } def last_known_exists_filter() -> dict[str, Any]: return { "nested": { "path": "last_known_institutions", "query": {"exists": {"field": "last_known_institutions.display_name"}}, } } AUTHOR_SOURCE = [ "id", "display_name", "orcid", "works_count", "cited_by_count", "last_known_institutions", "affiliations", ] def collect_authors( client: httpx.Client, insts: list[dict[str, Any]], affiliation_year_gte: int, ) -> dict[str, dict[str, Any]]: groups = { "backend_compatible": { "bool": { "filter": [ last_known_filter(insts), recent_affiliation_filter(insts, affiliation_year_gte), ] } }, "empty_last_known_recent": { "bool": { "filter": [recent_affiliation_filter(insts, affiliation_year_gte)], "must_not": [last_known_exists_filter()], } }, } authors: dict[str, dict[str, Any]] = {} for group_name, query in groups.items(): search_after = None total = None read = 0 while True: body: dict[str, Any] = { "size": AUTHOR_PAGE_SIZE, "track_total_hits": True, "_source": AUTHOR_SOURCE, "query": query, "sort": [{"id": {"order": "asc"}}], } if search_after: body["search_after"] = search_after result = es_search(client, NES_URL, NES_KEY, "openalex-authors", body) hits = result["hits"]["hits"] if total is None: total = result["hits"]["total"]["value"] print(f" [{group_name}] expected {total}") if not hits: break for hit in hits: src = hit["_source"] aid = src.get("id") if not aid: continue if aid not in authors: authors[aid] = { "id": aid, "display_name": src.get("display_name"), "orcid": src.get("orcid"), "works_count": src.get("works_count"), "cited_by_count": src.get("cited_by_count"), "source_sets": [group_name], } elif group_name not in authors[aid]["source_sets"]: authors[aid]["source_sets"].append(group_name) read += 1 search_after = hits[-1]["sort"] print(f" [{group_name}] read {read}/{total}") time.sleep(0.05) return authors # --------------------------------------------------------------------- # Work queries — FULL authorships, no inner_hits # --------------------------------------------------------------------- WORK_SOURCE = [ "id", "doi", "publication_year", "type", "cited_by_count", "primary_topic.id", "primary_topic.display_name", "primary_topic.field.id", "primary_topic.field.display_name", "authorships.author.id", "authorships.author.display_name", "authorships.author_position", "authorships.is_corresponding", "authorships.institutions.id", "authorships.institutions.display_name", "authorships.institutions.type", "authorships.institutions.country_code", "authorships.institutions.lineage", ] def collect_works( client: httpx.Client, author_ids: list[str], work_year_gte: int ) -> dict[str, dict[str, Any]]: works: dict[str, dict[str, Any]] = {} total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE): batch = author_ids[i : i + AUTHOR_BATCH_SIZE] batch_no = i // AUTHOR_BATCH_SIZE + 1 search_after = None while True: body: dict[str, Any] = { "size": WORK_PAGE_SIZE, "track_total_hits": True, "_source": WORK_SOURCE, "query": { "bool": { "filter": [ {"range": {"publication_year": {"gte": work_year_gte}}}, { "nested": { "path": "authorships", "query": { "terms": {"authorships.author.id": batch} }, } }, ] } }, "sort": [{"id": {"order": "asc"}}], } if search_after: body["search_after"] = search_after result = es_search(client, NES_URL, NES_KEY, "openalex-works*", body) hits = result["hits"]["hits"] if not hits: break for hit in hits: src = hit["_source"] wid = src.get("id") if wid and wid not in works: works[wid] = src search_after = hits[-1]["sort"] print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}") time.sleep(0.05) return works # --------------------------------------------------------------------- # Cache IO # --------------------------------------------------------------------- def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None: with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f: for record in records: f.write(json.dumps(record, ensure_ascii=True) + "\n") def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]: with gzip.open(path, "rt", encoding="utf-8") as f: for line in f: line = line.strip() if line: yield json.loads(line) # --------------------------------------------------------------------- # Top-level: extract to cache # --------------------------------------------------------------------- def extract_to_cache( institution_id: str, config: dict[str, Any], cache_dir: Path, force: bool = False, ) -> tuple[Path, Path, list[dict[str, Any]]]: """Extract authors + works for the cohort to jsonl.gz caches. Returns (authors_path, works_path, resolved cohort institutions). Reuses an existing cache unless force=True. """ if not NES_URL or not NES_KEY: raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}") short = institution_id.strip().rsplit("/", 1)[-1] cache_dir.mkdir(parents=True, exist_ok=True) authors_path = cache_dir / f"authors_{short}.jsonl.gz" works_path = cache_dir / f"works_{short}.jsonl.gz" extraction_cfg = config.get("extraction") or {} affiliation_year_gte = int(extraction_cfg.get("affiliation_years_gte", 2023)) work_year_gte = int(extraction_cfg.get("work_year_gte", 1950)) with httpx.Client() as client: insts = [ resolve_institution(client, i) for i in cohort_ids_for(config, short) ] print(f"Cohort ({len(insts)} institutions, affiliation years >= {affiliation_year_gte}):") for inst in insts: print(f" {inst['short_id']:<14} {inst['display_name']}") if not force and authors_path.exists() and works_path.exists(): print("Reusing cached extract (use --force-extract to refresh).") return authors_path, works_path, insts print("\nExtracting authors...") authors = collect_authors(client, insts, affiliation_year_gte) write_jsonl_gz(authors_path, authors.values()) print(f"Authors: {len(authors)} -> {authors_path}") print("\nExtracting works (full authorships)...") works_map = collect_works(client, sorted(authors.keys()), work_year_gte) write_jsonl_gz(works_path, works_map.values()) print(f"Works: {len(works_map)} -> {works_path}") return authors_path, works_path, insts