"""Normalize raw OpenAlex JSONL into tidy Parquet parts. Responsibilities: reconstruct abstracts from the inverted index, normalize DOIs/dates/identifiers, flatten nested OpenAlex objects into flat columns and compact relation tables, drop malformed rows, and deduplicate by work id and DOI. Runs as a streaming pass so memory stays bounded regardless of corpus size. """ from __future__ import annotations import argparse import gzip import json import os from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq from common import ( Checkpoint, ensure_dirs, get_logger, load_config, p, read_json, utc_now, write_json, ) from schema import WORKS_BASE, WORK_AUTHORS, WORK_INSTITUTIONS, WORK_TOPICS BATCH = 2000 def reconstruct_abstract(inv: dict | None) -> str | None: if not inv: return None positions: dict[int, str] = {} for token, idxs in inv.items(): if not isinstance(idxs, list): continue for i in idxs: positions[i] = token if not positions: return None return " ".join(positions[i] for i in sorted(positions)) def norm_doi(doi: str | None) -> str | None: if not doi: return None d = doi.strip().lower() for prefix in ("https://doi.org/", "http://doi.org/", "https://dx.doi.org/", "doi:"): if d.startswith(prefix): d = d[len(prefix):] d = d.strip() return d or None def norm_date(value: str | None) -> str | None: if not value or not isinstance(value, str): return None v = value.strip() if len(v) >= 10 and v[4] == "-" and v[7] == "-": try: int(v[0:4]); int(v[5:7]); int(v[8:10]) return v[:10] except ValueError: return None return None def _nn(xs) -> list: """Replace null elements with empty strings. Nulls inside list columns trip an offset bug in some downstream Parquet readers (e.g. an off-by-one in length spanned by list offsets). Emitting empty strings instead keeps the arrays trivially decodable everywhere. """ return ["" if x is None else x for x in (xs or [])] def _name(obj) -> str | None: if isinstance(obj, dict): return obj.get("display_name") or obj.get("name") return None def _short_id(oid) -> str | None: if isinstance(oid, str) and "/" in oid: return oid.rsplit("/", 1)[-1] return oid def _recent_citations(w: dict, ref_year: int, window: int = 3) -> int | None: cby = w.get("counts_by_year") if not isinstance(cby, list): return None lo = ref_year - window + 1 total = sum(int(c.get("cited_by_count") or 0) for c in cby if isinstance(c.get("year"), int) and lo <= c["year"] <= ref_year) return total def process_work(w: dict, ref_year: int = 2025): wid = _short_id(w.get("id")) title = (w.get("title") or w.get("display_name") or "").strip() if not wid or not title: return None, None, None, None year = w.get("publication_year") if not isinstance(year, int): year = None pdate = norm_date(w.get("publication_date")) month = None if pdate: month = int(pdate[5:7]) pt = w.get("primary_topic") or {} sub = pt.get("subfield") or {} fld = pt.get("field") or {} dom = pt.get("domain") or {} topic_ids, topic_names = [], [] topic_rows = [] for t in (w.get("topics") or []): tid = _short_id(t.get("id")) tname = t.get("display_name") if not tid: continue topic_ids.append(tid) topic_names.append(tname) ts, tf, td = t.get("subfield") or {}, t.get("field") or {}, t.get("domain") or {} topic_rows.append({ "work_id": wid, "topic_id": tid, "topic_name": tname, "score": float(t.get("score")) if t.get("score") is not None else None, "is_primary": tid == _short_id(pt.get("id")), "subfield_id": _short_id(ts.get("id")), "subfield_name": ts.get("display_name"), "field_id": _short_id(tf.get("id")), "field_name": tf.get("display_name"), "domain_id": _short_id(td.get("id")), "domain_name": td.get("display_name"), }) author_rows = [] author_names, author_ids, author_orcids = [], [], [] countries: set[str] = set() inst_map: dict[str, dict] = {} corresponding = {_short_id(c) for c in (w.get("corresponding_author_ids") or [])} for a in (w.get("authorships") or []): au = a.get("author") or {} aid = _short_id(au.get("id")) aname = au.get("display_name") aorc = au.get("orcid") aorc = aorc.rsplit("/", 1)[-1] if isinstance(aorc, str) and "/" in aorc else aorc author_ids.append(aid) author_names.append(aname) author_orcids.append(aorc) a_countries = [c for c in (a.get("countries") or []) if c] countries.update(a_countries) a_insts = [] for inst in (a.get("institutions") or []): iid = _short_id(inst.get("id")) if not iid: continue a_insts.append(iid) if iid not in inst_map: inst_map[iid] = { "work_id": wid, "institution_id": iid, "institution_name": inst.get("display_name"), "country_code": inst.get("country_code"), "institution_type": inst.get("type"), } author_rows.append({ "work_id": wid, "author_id": aid, "author_name": aname, "orcid": aorc, "author_position": a.get("author_position"), "is_corresponding": (_short_id(au.get("id")) in corresponding) or bool(a.get("is_corresponding")), "institution_ids": a_insts, "country_codes": a_countries, }) for inst in (w.get("institutions") or []): iid = _short_id(inst.get("id")) if not iid: continue if inst.get("country_code"): countries.add(inst["country_code"]) if iid not in inst_map: inst_map[iid] = { "work_id": wid, "institution_id": iid, "institution_name": inst.get("display_name"), "country_code": inst.get("country_code"), "institution_type": inst.get("type"), } inst_rows = list(inst_map.values()) loc = w.get("primary_location") or {} src = loc.get("source") or {} best = w.get("best_oa_location") or {} license_ = loc.get("license") or best.get("license") license_id = loc.get("license_id") or best.get("license_id") oa = w.get("open_access") or {} issns = src.get("issn") or [] mesh_terms = [] for m in (w.get("mesh") or []): dn = m.get("descriptor_name") qn = m.get("qualifier_name") if dn and qn: mesh_terms.append(f"{dn} / {qn}") elif dn: mesh_terms.append(dn) keywords = [k.get("display_name") for k in (w.get("keywords") or []) if k.get("display_name")] abstract = reconstruct_abstract(w.get("abstract_inverted_index")) ref_ids = [_short_id(r) for r in (w.get("referenced_works") or [])] row = { "work_id": wid, "doi": norm_doi(w.get("doi")), "title": title, "publication_date": pdate, "publication_year": year, "publication_month": month, "type": w.get("type"), "primary_topic_id": _short_id(pt.get("id")), "primary_topic_name": pt.get("display_name"), "primary_topic_score": float(pt.get("score")) if pt.get("score") is not None else None, "field_id": _short_id(fld.get("id")), "field_name": fld.get("display_name"), "subfield_id": _short_id(sub.get("id")), "subfield_name": sub.get("display_name"), "domain_id": _short_id(dom.get("id")), "domain_name": dom.get("display_name"), "topic_ids": _nn(topic_ids), "topic_names": _nn(topic_names), "topic_count": len(topic_ids), "author_count": len(author_ids), "author_names": _nn(author_names), "author_ids": _nn(author_ids), "author_orcids": _nn(author_orcids), "institution_count": len(inst_map), "institution_ids": list(inst_map.keys()), "institution_names": _nn([v["institution_name"] for v in inst_map.values()]), "institution_countries": sorted({v["country_code"] for v in inst_map.values() if v["country_code"]}), "country_codes": sorted(countries), "country_count": len(countries), "source_id": _short_id(src.get("id")), "source_name": src.get("display_name"), "source_type": src.get("type"), "issn_l": src.get("issn_l"), "issns": _nn(issns), "publisher": src.get("host_organization_name"), "cited_by_count": int(w.get("cited_by_count") or 0), "recent_citations_3y": _recent_citations(w, ref_year), "referenced_works_count": int(w.get("referenced_works_count") or 0), "referenced_work_ids": _nn(ref_ids), "is_oa": bool(oa.get("is_oa")), "oa_status": oa.get("oa_status"), "oa_url": oa.get("oa_url"), "license": license_, "license_id": license_id, "language": w.get("language"), "abstract": abstract, "has_abstract": abstract is not None, "is_retracted": bool(w.get("is_retracted")), "is_paratext": bool(w.get("is_paratext")), "fwci": float(w["fwci"]) if w.get("fwci") is not None else None, "openalex_citation_percentile": ( float(w["citation_normalized_percentile"]["value"]) if isinstance(w.get("citation_normalized_percentile"), dict) and w["citation_normalized_percentile"].get("value") is not None else None), "created_date": norm_date(w.get("created_date")) or w.get("created_date"), "updated_date": norm_date(w.get("updated_date")) or w.get("updated_date"), "mesh_terms": _nn(mesh_terms), "keywords": _nn(keywords), } return row, author_rows, inst_rows, topic_rows class PartWriter: def __init__(self, directory: Path, schema: pa.Schema, prefix: str): self.dir = directory self.dir.mkdir(parents=True, exist_ok=True) self.schema = schema self.prefix = prefix self.buf: list[dict] = [] self.files: list[str] = [] self.n = 0 self._part = 0 def add(self, rows: list[dict]) -> None: self.buf.extend(rows) if len(self.buf) >= BATCH: self.flush() def flush(self) -> None: if not self.buf: return self._part += 1 fpath = self.dir / f"{self.prefix}.part{self._part:05d}.parquet" tbl = pa.Table.from_pylist(self.buf, schema=self.schema) pq.write_table(tbl, fpath, compression="zstd") self.files.append(str(fpath)) self.n += len(self.buf) self.buf = [] def close(self) -> None: self.flush() def _iter_raw_raws(cfg, checkpoint): raw_dir = p(cfg, "raw") / "works" done = set(checkpoint.get("processed_raw_files", [])) files = sorted(raw_dir.glob("*.jsonl.gz")) todo = [str(f) for f in files if str(f) not in done] return todo, done, files def run(cfg: dict | None = None) -> dict: cfg = cfg or load_config() ensure_dirs(cfg) logger = get_logger("diversa.normalize", p(cfg, "logs") / "pipeline.log") ck = Checkpoint(p(cfg, "checkpoints") / "normalize.json") ref_year = int(cfg["scope"]["year_end"]) seen_dir = p(cfg, "staging") / "seen" seen_dir.mkdir(parents=True, exist_ok=True) ids_file = seen_dir / "work_ids.txt" dois_file = seen_dir / "dois.txt" def _load(path: Path) -> set[str]: if not path.exists(): return set() with open(path, "r", encoding="utf-8") as fh: return {ln.strip() for ln in fh if ln.strip()} seen_ids = _load(ids_file) seen_dois = _load(dois_file) ids_fh = open(ids_file, "a", encoding="utf-8") dois_fh = open(dois_file, "a", encoding="utf-8") todo, done, files = _iter_raw_raws(cfg, ck) logger.info("normalize: %d raw files pending (%d already processed)", len(todo), len(done)) parts_dir = p(cfg, "parts") ww = PartWriter(parts_dir / "works", WORKS_BASE, "works") aw = PartWriter(parts_dir / "work_authors", WORK_AUTHORS, "work_authors") iw = PartWriter(parts_dir / "work_institutions", WORK_INSTITUTIONS, "work_institutions") tw = PartWriter(parts_dir / "work_topics", WORK_TOPICS, "work_topics") stats = {"raw_rows": 0, "kept": 0, "malformed": 0, "dup_id": 0, "dup_doi": 0, "files": 0} for fpath in todo: try: with gzip.open(fpath, "rt", encoding="utf-8") as fh: for line in fh: line = line.strip() if not line: continue stats["raw_rows"] += 1 try: w = json.loads(line) except json.JSONDecodeError: stats["malformed"] += 1 continue row, authors, insts, topics = process_work(w, ref_year=ref_year) if row is None: stats["malformed"] += 1 continue if row["work_id"] in seen_ids: stats["dup_id"] += 1 continue doi = row["doi"] if doi and doi in seen_dois: stats["dup_doi"] += 1 continue seen_ids.add(row["work_id"]) ids_fh.write(row["work_id"] + "\n") if doi: seen_dois.add(doi) dois_fh.write(doi + "\n") ww.add([row]) aw.add(authors) iw.add(insts) tw.add(topics) stats["kept"] += 1 except Exception as exc: # noqa: BLE001 logger.error("failed on %s: %s", fpath, exc) continue done.add(fpath) stats["files"] += 1 ids_fh.flush(); dois_fh.flush() ck.update(processed_raw_files=sorted(done)) if cfg["collection"].get("delete_raw_after_normalize", False): try: os.remove(fpath) except OSError: pass if stats["files"] % 10 == 0: logger.info("normalized %d files; kept=%s malformed=%s dups=%s", stats["files"], f"{stats['kept']:,}", stats["malformed"], f"{stats['dup_id'] + stats['dup_doi']:,}") ww.close(); aw.close(); iw.close(); tw.close() ids_fh.close(); dois_fh.close() stats["works_parts"] = len(ww.files) stats["finished_at"] = utc_now() write_json(p(cfg, "checkpoints") / "normalize_stats.json", stats) logger.info("normalize done: kept=%s malformed=%s dup_id=%s dup_doi=%s", f"{stats['kept']:,}", stats["malformed"], stats["dup_id"], stats["dup_doi"]) return stats if __name__ == "__main__": run()