File size: 15,080 Bytes
7bcd860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62050a4
 
 
 
 
 
 
 
 
 
7bcd860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62050a4
7bcd860
62050a4
7bcd860
 
62050a4
7bcd860
 
 
 
62050a4
7bcd860
 
 
62050a4
7bcd860
 
 
 
 
 
 
 
 
 
 
 
 
 
62050a4
7bcd860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""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()