#!/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(('
', ' ')):
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())