mathconv-corpus / scripts /extract_local_mathml.py
viktor-shcherb's picture
Publish version 1 of the corpus
93e3ef1 verified
Raw History Blame Contribute Delete
8.11 kB
#!/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 (<math ...> .. </math>), 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"</(?:[A-Za-z][\w.-]*:)?math\s*>", re.I)
ESCAPED_MATH = re.compile(r"&lt;(?:[A-Za-z][\w.-]*:)?math(?=[\s&>/]|&gt;)", re.I)
RECORD = re.compile(r"<record>(.*?)</record>", re.S)
IDENT = re.compile(r"<identifier>([^<]*)</identifier>")
DOI = re.compile(r'<article-id pub-id-type="doi">([^<]*)<')
WRAPPER = re.compile(r"<(inline|disp)-formula\b.*?</\1-formula>", re.S)
ROOT_ATTRS = re.compile(r"<[^>]*>")
ATTR = re.compile(r"""([^\s=/>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""")
ANNOTATION = re.compile(r"<(?:\w+:)?annotation\b([^>]*)>(.*?)</(?:\w+:)?annotation\s*>", re.S | re.I)
SCRIPT_TEXT = re.compile(r"<(script|textarea|style)\b[^>]*>.*?</\1\s*>", re.S | re.I)
def find_spans(text):
"""Return (start, end, unterminated_count) of every <math>..</math> 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": "<article " in body, "formulas": 0}
if "<article " not in body:
continue
doi = DOI.search(body)
origin = doi.group(1) if doi else ident
wrappers = [(w.start(), w.end(), w.group(1)) for w in WRAPPER.finditer(body)]
spans, unterminated = find_spans(body)
stats["jats_unterminated"] += unterminated
for a, b in spans:
s = body[a:b]
kind = next((k for ws, we, k in wrappers if ws < a < we), None)
root = attrs_of_root(s)
corpus.add(s, "copernicus-jats", "CC-BY-4.0", origin,
context_of(root, kind), carried_tex(s, root))
seen[ident]["formulas"] += 1
pages.append({"file": os.path.basename(path), "records": len(ids),
"id_set_hash": hashlib.sha1("\n".join(sorted(ids)).encode()).hexdigest()})
stats["jats_pages"] = pages
stats["jats_records_unique"] = len(seen)
stats["jats_records_with_article"] = sum(v["has_article"] for v in seen.values())
stats["jats_articles_with_formulas"] = sum(v["formulas"] > 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())