dmpantiu's picture
Upload folder using huggingface_hub
0ec8fd6 verified
Raw
History Blame Contribute Delete
5.15 kB
#!/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()