File size: 10,694 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Extract DOIs and reference-citation lines from two sources and aggregate
them into one record per unique DOI:

  1. CMEMS EQC parsed markdown docs  (store = CMEMS,   source = eqc_refs)
  2. CDS/ADS/EWDS per-collection reference blocks
     (meta_harvest/cds_references.json; store = CDS|ADS|EWDS, source = cds_refs)

Outputs (in publications/registry/):
  - unique_dois.jsonl      one record per unique DOI aggregated across both sources
  - no_doi_refs.jsonl      {product_id|collection_id, ref_text} for DOI-less citations
  - product_self_dois.json id -> list of its own catalogue DOIs (moi/mds/24381)
  - extract_summary.json   quick counts
"""
import json
import re
import sys
from collections import defaultdict
from pathlib import Path
from urllib.parse import unquote

BASE = Path("/Users/dmpantiu/copernicus_mcp")
CATALOG = BASE / "marine_rag" / "out" / "catalog.json"
CDS_REFS = BASE / "meta_harvest" / "cds_references.json"
OUT = BASE / "publications" / "registry"
OUT.mkdir(parents=True, exist_ok=True)

# --- DOI handling -----------------------------------------------------------

# allow one <...> segment (old AMS/Wiley SICI DOIs like 10.1175/...(1989)006<0599:x>2.0.co;2)
DOI_RE = re.compile(
    r'10\.\d{4,9}/[^\s"\'<>\\]+(?:<\d[^\s<>]*>[^\s"\'<>\\]*)?', re.IGNORECASE)
YEAR_RE = re.compile(r'\b(19|20)\d{2}\b')
HEADING_RE = re.compile(r'^#{1,6}\s')
REF_HEADING_RE = re.compile(r'^#{1,6}\s.*(referen|bibliograph)', re.IGNORECASE)

TRAIL_CHARS = '.,;:!?"\'»›)]}>*_`|'


def clean_doi(raw: str):
    """Aggressively clean an OCR/markdown-noisy DOI match; return lowercase DOI or None."""
    d = raw.strip()
    # markdown / OCR artifacts
    d = d.replace('**', '').replace('\\', '')
    d = d.rstrip(' ')
    # markdown link syntax: [doi](url) -> cut at first square bracket
    d = re.split(r'[\[\]]', d, 1)[0]
    # decode percent-encoding (handles %3c, %253c double-encoded) to canonical form
    for _ in range(3):
        if '%' not in d:
            break
        dec = unquote(d)
        if dec == d:
            break
        d = dec
    # OCR noise chars (negation sign, soft hyphen) and glued HTML tags
    d = d.replace('¬', '').replace('­', '')
    d = re.split(r'<(?=[/a-zA-Z])', d, 1)[0]
    # aggregate/collection URL DOIs glued with '@' (e.g. 10.1002/x@10.1002/(issn)...)
    d = d.split('@', 1)[0]
    # strip trailing punctuation, but keep balanced closing parens
    while d and d[-1] in TRAIL_CHARS:
        if d[-1] == ')' and d.count('(') >= d.count(')'):
            break
        d = d[:-1]
    # cut at common junk that got glued on
    for sep in ('http', ',last', 'available', 'ISSN', 'ISBN'):
        i = d.lower().find(sep.lower(), 8)
        if i > 0:
            d = d[:i]
    # re-strip
    while d and d[-1] in TRAIL_CHARS:
        if d[-1] == ')' and d.count('(') >= d.count(')'):
            break
        d = d[:-1]
    d = d.lower()
    # UUID-suffix DOIs with glued trailing text -> truncate to the UUID
    m = re.match(r'(10\.\d{4,9}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', d)
    if m and len(d) > len(m.group(1)):
        d = m.group(1)
    # placeholder / template DOIs (e.g. 10.24381/XXXXXXXX)
    if re.search(r'x{6,}', d):
        return None
    # validate (printable ASCII incl. <> for SICI DOIs)
    if not re.fullmatch(r'10\.\d{4,9}/[!-~]{3,}', d):
        return None
    # angle brackets only allowed as one balanced <...> segment
    if d.count('<') != d.count('>') or d.count('<') > 1:
        return None
    # suffix must contain an alnum
    suffix = d.split('/', 1)[1]
    if not re.search(r'[a-z0-9]', suffix):
        return None
    if len(d) > 120:  # OCR runaway
        return None
    return d


def is_self_doi(doi: str, store: str) -> bool:
    """Catalogue self-DOIs: CMEMS uses 10.48670/moi|mds-*, CDS/ADS/EWDS use
    the ECMWF DataCite prefix 10.24381/*."""
    if store == "CMEMS":
        return doi.startswith('10.48670/moi-') or doi.startswith('10.48670/mds-')
    return doi.startswith('10.24381/')


# --- reference-section extraction (CMEMS markdown) --------------------------

def ref_section_lines(text: str):
    """Yield lines from all sections whose heading matches reference/bibliography."""
    lines = text.splitlines()
    in_ref = False
    for ln in lines:
        if HEADING_RE.match(ln):
            in_ref = bool(REF_HEADING_RE.match(ln))
            continue
        if in_ref:
            yield ln


def looks_like_citation(line: str) -> bool:
    s = line.strip()
    if len(s) <= 40:
        return False
    if not YEAR_RE.search(s):
        return False
    if s.startswith(('<table', '|', '![', '<tr', '<td', '#', '-', '*', '>', '&nbsp')):
        return False
    # skip obvious CDS boilerplate / license / attribution lines
    low = s.lower()
    if any(b in low for b in (
            'neither the european commission', 'responsible for any use',
            'in addition to the requirements', 'clear and visible attribution',
            'applicable license', 'cite the cds catalogue', 'contains modified')):
        return False
    return True


def line_has_doi(line: str) -> bool:
    low = line.lower()
    return bool(DOI_RE.search(line)) or 'doi.org' in low or 'doi:' in low


# --- aggregation containers -------------------------------------------------

class Agg:
    def __init__(self):
        self.doi_ids = defaultdict(set)       # doi -> set(id)
        self.doi_mentions = defaultdict(int)  # doi -> int
        self.doi_sources = defaultdict(set)   # doi -> set(source)
        self.id_store = {}                    # id -> store
        self.self_dois = defaultdict(set)     # id -> set(catalogue dois)
        self.no_doi_refs = []                 # list of dicts
        self.id_meta = {}                     # id -> (domains, regions)
        self.raw = 0
        self.invalid = 0

    def add_doi(self, doi, _id, store, source):
        self.doi_ids[doi].add(_id)
        self.doi_mentions[doi] += 1
        self.doi_sources[doi].add(source)
        self.id_store[_id] = store


def process_text(agg, _id, store, source, text, seen, id_key,
                 use_ref_section, join_linebreaks):
    if join_linebreaks:
        text = re.sub(r'(10\.\d{4,9}/[^\s"\'<>\\]*)-\s*\n\s*', r'\1', text)
        text = re.sub(r'(10\.\d{4,9})/\s*\n\s*', r'\1/', text)
    for m in DOI_RE.finditer(text):
        agg.raw += 1
        doi = clean_doi(m.group(0))
        if doi is None:
            agg.invalid += 1
            continue
        if is_self_doi(doi, store):
            agg.self_dois[_id].add(doi)
            agg.id_store[_id] = store
            continue
        agg.add_doi(doi, _id, store, source)

    # citation text lines (no DOI in line)
    line_iter = ref_section_lines(text) if use_ref_section else text.splitlines()
    for ln in line_iter:
        if not looks_like_citation(ln):
            continue
        if line_has_doi(ln):
            continue
        s = ' '.join(ln.split())
        key = s.lower()
        if key in seen:
            continue
        seen.add(key)
        agg.no_doi_refs.append({id_key: _id, "ref_text": s})


# --- main --------------------------------------------------------------------

def main():
    agg = Agg()
    catalog = json.loads(CATALOG.read_text())

    n_docs_read = n_docs_missing = 0
    for prod in catalog:
        pid = prod["product_id"]
        agg.id_meta[pid] = (prod.get("domains") or [], prod.get("regions") or [])
        seen = set()
        for doc in prod.get("docs", []):
            md_path = doc.get("md_path")
            if not md_path:
                continue
            p = BASE / md_path
            if not p.exists():
                n_docs_missing += 1
                continue
            n_docs_read += 1
            text = p.read_text(errors="replace")
            process_text(agg, pid, "CMEMS", "eqc_refs", text, seen,
                         "product_id", use_ref_section=True, join_linebreaks=True)

    # CDS / ADS / EWDS
    cds = json.loads(CDS_REFS.read_text())
    store_map = {"cds": "CDS", "ads": "ADS", "ewds": "EWDS"}
    n_cds_coll = n_cds_blocks = 0
    for store_key, colls in cds.items():
        store = store_map.get(store_key, store_key.upper())
        for cid, obj in colls.items():
            n_cds_coll += 1
            agg.id_meta.setdefault(cid, ([], []))
            seen = set()
            for ref in obj.get("references", []):
                n_cds_blocks += 1
                txt = ref.get("text") or ""
                process_text(agg, cid, store, "cds_refs", txt, seen,
                             "collection_id", use_ref_section=False,
                             join_linebreaks=False)

    # --- write unique_dois.jsonl ---
    with open(OUT / "unique_dois.jsonl", "w") as f:
        for doi in sorted(agg.doi_ids):
            ids = sorted(agg.doi_ids[doi])
            domains, regions = set(), set()
            for i in ids:
                d_, r_ = agg.id_meta.get(i, ([], []))
                domains.update(d_)
                regions.update(r_)
            rec = {
                "doi": doi,
                "linked_products": ids,
                "product_stores": {i: agg.id_store[i] for i in ids},
                "n_mentions": agg.doi_mentions[doi],
                "domains": sorted(domains),
                "regions": sorted(regions),
                "sources": sorted(agg.doi_sources[doi]),
            }
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")

    with open(OUT / "no_doi_refs.jsonl", "w") as f:
        for rec in agg.no_doi_refs:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")

    with open(OUT / "product_self_dois.json", "w") as f:
        json.dump({k: sorted(v) for k, v in sorted(agg.self_dois.items())},
                  f, indent=1)

    linked_ids = {i for ids in agg.doi_ids.values() for i in ids}
    by_store = defaultdict(int)
    for i in linked_ids:
        by_store[agg.id_store.get(i, "?")] += 1
    summary = {
        "cmems_docs_read": n_docs_read,
        "cmems_docs_missing": n_docs_missing,
        "cds_collections": n_cds_coll,
        "cds_ref_blocks": n_cds_blocks,
        "raw_doi_matches": agg.raw,
        "invalid_after_clean": agg.invalid,
        "unique_dois": len(agg.doi_ids),
        "linked_ids_total": len(linked_ids),
        "linked_ids_by_store": dict(by_store),
        "ids_with_self_doi": len(agg.self_dois),
        "no_doi_ref_lines": len(agg.no_doi_refs),
    }
    with open(OUT / "extract_summary.json", "w") as f:
        json.dump(summary, f, indent=1)
    print(json.dumps(summary, indent=1))


if __name__ == "__main__":
    sys.exit(main())