File size: 5,153 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
#!/usr/bin/env python3
"""
fetch_parse.py — fetch & text-extract the CDS/ADS/EWDS deep documentation
(Confluence wiki pages + PDFs + service webpages) so the non-marine stores get
the same deep-doc RAG depth as CMEMS marine.

Input : meta_harvest/deep_doc_plan.json   dataset_id -> [{title,url,kind}]
Output: deep_docs/parsed/<urlhash>.md     cleaned text per unique URL
        deep_docs/manifest.jsonl          one line per URL (checkpoint: resumable)

No VLM needed: Confluence/webpages via requests+bs4+markdownify, PDFs via PyMuPDF.
Env: SAMPLE_N=<n> to only process the first n URLs (smoke test).
"""
import json
import os
import re
import sys
import hashlib
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import requests
from bs4 import BeautifulSoup
from markdownify import markdownify as mdify
import fitz  # PyMuPDF

ROOT = Path(__file__).resolve().parent.parent
PLAN = ROOT / "meta_harvest" / "deep_doc_plan.json"
OUTDIR = ROOT / "deep_docs" / "parsed"
MANIFEST = ROOT / "deep_docs" / "manifest.jsonl"
UA = {"User-Agent": "Mozilla/5.0 (copernicus-rag deep-doc harvester; research use)"}


def log(*a):
    print(*a, file=sys.stderr, flush=True)


def uhash(url):
    return hashlib.md5(url.encode()).hexdigest()[:16]


def clean_md(md: str) -> str:
    md = re.sub(r"\n{3,}", "\n\n", md)
    md = re.sub(r"[ \t]+\n", "\n", md)
    # drop obvious confluence chrome lines
    drop = ("Skip to", "Configure Space tools", "Space shortcuts", "Copyright ©",
            "Powered by Atlassian", "Evaluate Confluence", "You are viewing")
    lines = [ln for ln in md.splitlines() if not any(d in ln for d in drop)]
    return "\n".join(lines).strip()


def parse_html(html: str) -> str:
    soup = BeautifulSoup(html, "html.parser")
    for t in soup(["script", "style", "nav", "header", "footer", "noscript", "form"]):
        t.decompose()
    node = (soup.select_one("#main-content") or soup.select_one(".wiki-content")
            or soup.select_one("div[role=main]") or soup.select_one("main")
            or soup.select_one("article") or soup.body or soup)
    md = mdify(str(node), heading_style="ATX", strip=["img"])
    return clean_md(md)


def parse_pdf(content: bytes) -> str:
    doc = fitz.open(stream=content, filetype="pdf")
    parts = [page.get_text("text") for page in doc]
    doc.close()
    return clean_md("\n\n".join(parts))


def fetch_one(url: str, kind: str) -> tuple[str, str]:
    """Return (markdown, status). status in {ok, empty, http_<code>, error}."""
    try:
        r = requests.get(url, headers=UA, timeout=40, allow_redirects=True)
        if r.status_code != 200:
            return "", f"http_{r.status_code}"
        ct = r.headers.get("content-type", "").lower()
        if kind == "pdf" or "application/pdf" in ct or url.lower().split("?")[0].endswith(".pdf"):
            md = parse_pdf(r.content)
        else:
            md = parse_html(r.text)
        return md, ("ok" if len(md) >= 200 else "empty")
    except Exception as e:
        return "", f"error:{type(e).__name__}"


def main():
    OUTDIR.mkdir(parents=True, exist_ok=True)
    plan = json.loads(PLAN.read_text())
    # unique url -> {title, kind, datasets:[]}
    urls: dict[str, dict] = {}
    for dsid, docs in plan.items():
        for d in docs:
            u = d["url"]
            e = urls.setdefault(u, {"title": d.get("title", ""), "kind": d.get("kind"), "datasets": []})
            e["datasets"].append(dsid)

    done = set()
    if MANIFEST.exists():
        for line in MANIFEST.read_text().splitlines():
            if line.strip():
                done.add(json.loads(line)["url"])
    todo = [u for u in urls if u not in done]
    sample = int(os.environ.get("SAMPLE_N", "0"))
    if sample:
        todo = todo[:sample]
    log(f"unique urls={len(urls)} done={len(done)} todo={len(todo)}"
        + (f" (SAMPLE {sample})" if sample else ""))

    workers = int(os.environ.get("WORKERS", "10"))
    lock = threading.Lock()
    counts = {"ok": 0, "done": 0}
    mf = open(MANIFEST, "a", encoding="utf-8")

    def work(url):
        meta = urls[url]
        md, status = fetch_one(url, meta["kind"])
        rec = {"url": url, "kind": meta["kind"], "title": meta["title"],
               "datasets": meta["datasets"], "status": status,
               "n_chars": len(md), "md_path": ""}
        if status == "ok":
            p = OUTDIR / f"{uhash(url)}.md"
            header = f"# {meta['title']}\n\n<!-- source: {url} -->\n\n"
            p.write_text(header + md, encoding="utf-8")
            rec["md_path"] = str(p.relative_to(ROOT))
        with lock:
            mf.write(json.dumps(rec, ensure_ascii=False) + "\n")
            mf.flush()
            counts["done"] += 1
            counts["ok"] += status == "ok"
            if counts["done"] % 40 == 0:
                log(f"  {counts['done']}/{len(todo)}  ok={counts['ok']}")

    with ThreadPoolExecutor(max_workers=workers) as ex:
        list(as_completed(ex.submit(work, u) for u in todo))
    mf.close()
    log(f"DONE todo={len(todo)} ok={counts['ok']}")


if __name__ == "__main__":
    main()