#!/usr/bin/env python3 """Extract the MathML formulas of the first corpus file. Reads (read-only): - JATS_DIR/page_*.xml: OAI-PMH pages of JATS article XML from Copernicus Publications (CC BY 4.0). Records are identified by their OAI identifier; a record seen on a second page is skipped, and records without article content (OAI "error" records) are skipped. - CRAWL_DIR/*.json: crawled web pages, one JSON object per page with the fields `host`, `url` and `html`; the `html` field is scanned. Writes: - OUT_DIR/formulas.jsonl: one distinct MathML string per line - OUT_DIR/extraction_stats.json: counts for the census MathML elements are located as text spans ( .. ), so the `mathml` field is the exact source string. The licence of the crawled pages is decided afterwards, per page; see carry_v0.py. Usage: extract_local_mathml.py --jats-dir DIR --crawl-dir DIR --out DIR """ import argparse import glob import hashlib import html import json import os import re import sys JATS_DIR = CRAWL_DIR = OUT_DIR = None # set from the arguments in main() MATH_OPEN = re.compile(r"<(?:[A-Za-z][\w.-]*:)?math(?=[\s>/])", re.I) MATH_CLOSE = re.compile(r"", re.I) ESCAPED_MATH = re.compile(r"<(?:[A-Za-z][\w.-]*:)?math(?=[\s&>/]|>)", re.I) RECORD = re.compile(r"(.*?)", re.S) IDENT = re.compile(r"([^<]*)") DOI = re.compile(r'([^<]*)<') WRAPPER = re.compile(r"<(inline|disp)-formula\b.*?", re.S) ROOT_ATTRS = re.compile(r"<[^>]*>") ATTR = re.compile(r"""([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""") ANNOTATION = re.compile(r"<(?:\w+:)?annotation\b([^>]*)>(.*?)", re.S | re.I) SCRIPT_TEXT = re.compile(r"<(script|textarea|style)\b[^>]*>.*?", re.S | re.I) def find_spans(text): """Return (start, end, unterminated_count) of every .. span.""" spans, unterminated, pos = [], 0, 0 while True: m = MATH_OPEN.search(text, pos) if not m: return spans, unterminated c = MATH_CLOSE.search(text, m.end()) if not c: unterminated += 1 pos = m.end() continue spans.append((m.start(), c.end())) pos = c.end() def attrs_of_root(s): tag = ROOT_ATTRS.match(s).group(0) return {k.lower(): html.unescape(v.strip("\"'")) for k, v in ATTR.findall(tag)} def carried_tex(s, root): for m in ANNOTATION.finditer(s): enc = dict((k.lower(), v.strip("\"'")) for k, v in ATTR.findall(m.group(1))).get("encoding", "") if "tex" in enc.lower(): return html.unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip() alt = root.get("alttext") return alt if alt else None def context_of(root, wrapper=None): if wrapper: return "inline" if wrapper == "inline" else "display" d = root.get("display", "").lower() return {"inline": "inline", "block": "display"}.get(d, "unknown") class Corpus: def __init__(self): self.rows = {} self.found = {"copernicus-jats": 0, "crawl-focus": 0} self.cross_source = 0 def add(self, s, source, licence, origin, ctx, tex): self.found[source] += 1 row = self.rows.get(s) if row is None: self.rows[s] = {"id": hashlib.sha1(s.encode("utf-8")).hexdigest()[:16], "mathml": s, "source": source, "licence": licence, "origin": origin, "context": ctx, "carried_tex": tex, "count": 1, "source_counts": {source: 1}} else: row["count"] += 1 row["source_counts"][source] = row["source_counts"].get(source, 0) + 1 if len(row["source_counts"]) > 1: row["licence"] = "unknown" # the stricter licence applies def read_jats(corpus, stats): seen, pages, identical = {}, [], True for path in sorted(glob.glob(os.path.join(JATS_DIR, "page_*.xml"))): with open(path, encoding="utf-8") as f: text = f.read() ids = [] for rec in RECORD.finditer(text): body = rec.group(1) ident = IDENT.search(body).group(1) ids.append(ident) if ident in seen: seen[ident]["dup_on_pages"].append(os.path.basename(path)) continue seen[ident] = {"page": os.path.basename(path), "dup_on_pages": [], "has_article": "
0 for v in seen.values()) stats["jats_records_repeated_on_later_pages"] = sum(len(v["dup_on_pages"]) for v in seen.values()) stats["jats_same_record_ids"] = len({p["id_set_hash"] for p in pages}) == 1 def read_crawl(corpus, stats): files = [] for path in sorted(glob.glob(os.path.join(CRAWL_DIR, "*.json"))): with open(path, encoding="utf-8") as f: d = json.load(f) text = d["html"] spans, unterminated = find_spans(text) scripts = [(m.start(), m.end()) for m in SCRIPT_TEXT.finditer(text)] in_script = 0 for a, b in spans: s = text[a:b] if any(sa < a < sb for sa, sb in scripts): in_script += 1 root = attrs_of_root(s) corpus.add(s, "crawl-focus", "unknown", d["host"], context_of(root), carried_tex(s, root)) files.append({"file": os.path.basename(path), "host": d["host"], "real_elements": len(spans), "unterminated": unterminated, "escaped_occurrences": len(ESCAPED_MATH.findall(text)), "inside_script_or_textarea": in_script}) stats["crawl_files"] = files def main(): global JATS_DIR, CRAWL_DIR, OUT_DIR ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--jats-dir", required=True) ap.add_argument("--crawl-dir", required=True) ap.add_argument("--out", required=True) args = ap.parse_args() JATS_DIR, CRAWL_DIR, OUT_DIR = args.jats_dir, args.crawl_dir, args.out os.makedirs(OUT_DIR, exist_ok=True) corpus = Corpus() stats = {"jats_unterminated": 0} read_jats(corpus, stats) read_crawl(corpus, stats) stats["found"] = corpus.found stats["distinct"] = len(corpus.rows) stats["cross_source_duplicates"] = sum(len(r["source_counts"]) > 1 for r in corpus.rows.values()) with open(os.path.join(OUT_DIR, "formulas.jsonl"), "w", encoding="utf-8") as f: for row in corpus.rows.values(): f.write(json.dumps(row, ensure_ascii=False) + "\n") with open(os.path.join(OUT_DIR, "extraction_stats.json"), "w", encoding="utf-8") as f: json.dump(stats, f, indent=1) print(json.dumps({k: v for k, v in stats.items() if k not in ("crawl_files",)}, indent=1)) for c in stats["crawl_files"]: print(c) if __name__ == "__main__": sys.exit(main())