| |
| """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_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() |
| |
| d = d.replace('**', '').replace('\\', '') |
| d = d.rstrip(' ') |
| |
| d = re.split(r'[\[\]]', d, 1)[0] |
| |
| for _ in range(3): |
| if '%' not in d: |
| break |
| dec = unquote(d) |
| if dec == d: |
| break |
| d = dec |
| |
| d = d.replace('¬', '').replace('', '') |
| d = re.split(r'<(?=[/a-zA-Z])', d, 1)[0] |
| |
| d = d.split('@', 1)[0] |
| |
| while d and d[-1] in TRAIL_CHARS: |
| if d[-1] == ')' and d.count('(') >= d.count(')'): |
| break |
| d = d[:-1] |
| |
| for sep in ('http', ',last', 'available', 'ISSN', 'ISBN'): |
| i = d.lower().find(sep.lower(), 8) |
| if i > 0: |
| d = d[:i] |
| |
| while d and d[-1] in TRAIL_CHARS: |
| if d[-1] == ')' and d.count('(') >= d.count(')'): |
| break |
| d = d[:-1] |
| d = d.lower() |
| |
| 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) |
| |
| if re.search(r'x{6,}', d): |
| return None |
| |
| if not re.fullmatch(r'10\.\d{4,9}/[!-~]{3,}', d): |
| return None |
| |
| if d.count('<') != d.count('>') or d.count('<') > 1: |
| return None |
| |
| suffix = d.split('/', 1)[1] |
| if not re.search(r'[a-z0-9]', suffix): |
| return None |
| if len(d) > 120: |
| 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/') |
|
|
|
|
| |
|
|
| 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', '#', '-', '*', '>', ' ')): |
| return False |
| |
| 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 |
|
|
|
|
| |
|
|
| class Agg: |
| def __init__(self): |
| self.doi_ids = defaultdict(set) |
| self.doi_mentions = defaultdict(int) |
| self.doi_sources = defaultdict(set) |
| self.id_store = {} |
| self.self_dois = defaultdict(set) |
| self.no_doi_refs = [] |
| self.id_meta = {} |
| 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) |
|
|
| |
| 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}) |
|
|
|
|
| |
|
|
| 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 = 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) |
|
|
| |
| 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()) |
|
|