mathconv-corpus / scripts /wikipedia_tex.py
viktor-shcherb's picture
Publish version 1 of the corpus
93e3ef1 verified
Raw History Blame Contribute Delete
8.83 kB
#!/usr/bin/env python3
"""Collect a pool of TeX formulas from Wikipedia wikitext (CC BY-SA 4.0).
Usage: wikipedia_tex.py --work DIR --out FILE [--seed N] [--target N]
[--en-pages N] [--other-pages N]
Finds math-heavy articles with the MediaWiki search API (`list=search`,
field keywords per language: mathematics, physics, chemistry, statistics,
engineering, economics), downloads their current wikitext with
`prop=revisions&rvprop=content|ids` (20 pages per request, one request per
second) and extracts the content of `<math>` tags. Responses are cached in
`DIR/wikipedia` so that an interrupted run resumes.
Each site's licence is read from `meta=siteinfo&siprop=rightsinfo`; a site
whose rights are not CC BY-SA 4.0 is skipped. Formulas containing templates
(`{{`), `<nowiki>`, `<ref` or the `chem` attribute are skipped. The pool of
distinct TeX strings is reduced to `--target` formulas with a seeded
selection that first keeps formulas holding rare TeX commands (document
frequency below 25, rarest first, up to half of the target), then fills with
a random sample. At most 60 formulas are taken from any page before
selection.
Output FILE: one JSON object per line with `tex`, `context`, `lang`,
`title`, `revid`, `rights_url` and `page_count` (number of pages in which
this exact TeX occurs). A sidecar `FILE.pages.jsonl` lists the pages used.
"""
import argparse
import hashlib
import html
import json
import os
import random
import re
import sys
import urllib.parse
from collections import Counter, defaultdict
from datetime import date
import corpus_common as cc
TERMS = {
"en": ["mathematics theorem", "physics equation", "chemistry reaction", "statistics distribution",
"engineering control", "economics model"],
"de": ["Mathematik Satz", "Physik Gleichung", "Chemie Reaktion", "Statistik Verteilung",
"Ingenieurwesen Regelung", "Ökonomie Modell"],
"fr": ["mathématiques théorème", "physique équation", "chimie réaction", "statistique loi",
"ingénierie contrôle", "économie modèle"],
"es": ["matemáticas teorema", "física ecuación", "química reacción", "estadística distribución",
"ingeniería control", "economía modelo"],
"ru": ["математика теорема", "физика уравнение", "химия реакция", "статистика распределение",
"инженерия управление", "экономика модель"],
"ja": ["数学 定理", "物理学 方程式", "化学 反応", "統計学 分布", "工学 制御", "経済学 モデル"],
"zh": ["数学 定理", "物理 方程", "化学 反应", "统计 分布", "工程 控制", "经济 模型"],
"pt": ["matemática teorema", "física equação", "química reação", "estatística distribuição",
"engenharia controle", "economia modelo"],
}
MATH = re.compile(r"<math((?:\s[^>]*)?)>(.*?)</math\s*>", re.S)
BAD = re.compile(r"\{\{|<nowiki|<ref|<!--")
CMD = re.compile(r"\\([A-Za-z]+|.)")
FIELDS = ["mathematics", "physics", "chemistry", "statistics", "engineering", "economics"]
def cached(work, url):
os.makedirs(work, exist_ok=True)
p = os.path.join(work, hashlib.sha1(url.encode()).hexdigest() + ".json")
if os.path.exists(p):
return json.load(open(p, encoding="utf-8"))
d = json.loads(cc.polite_get(url, min_interval=2.0))
json.dump(d, open(p, "w", encoding="utf-8"))
return d
def api(lang, **params):
params["format"] = "json"
params["formatversion"] = "2"
return "https://%s.wikipedia.org/w/api.php?%s" % (lang, urllib.parse.urlencode(params))
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--work", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--target", type=int, default=20000)
ap.add_argument("--en-pages", type=int, default=100, help="search results per field for English")
ap.add_argument("--other-pages", type=int, default=40, help="search results per field, other languages")
a = ap.parse_args()
work = os.path.join(a.work, "wikipedia")
rng = random.Random(a.seed)
today = date.today().isoformat()
pool = {} # tex -> record
pages_used = []
for lang, terms in TERMS.items():
info = cached(work, api(lang, action="query", meta="siteinfo", siprop="rightsinfo"))
rights = info["query"]["rightsinfo"]
if "by-sa/4.0" not in rights["url"]:
cc.log("skip", lang, "rights", rights)
continue
titles = []
npages = a.en_pages if lang == "en" else a.other_pages
for term in terms:
got = 0
off = 0
while got < npages:
lim = min(50, npages - got)
d = cached(work, api(lang, action="query", list="search", srsearch=term + ' insource:"<math"',
srnamespace="0", srlimit=lim, sroffset=off))
hits = d["query"]["search"]
titles += [h["title"] for h in hits]
got += len(hits)
off += len(hits)
if len(hits) < lim:
break
titles = sorted(set(titles))
for i in range(0, len(titles), 20):
batch = titles[i:i + 20]
d = cached(work, api(lang, action="query", prop="revisions", rvprop="content|ids", rvslots="main",
titles="|".join(batch)))
for p in d["query"]["pages"]:
if "revisions" not in p:
continue
rev = p["revisions"][0]
text = rev["slots"]["main"]["content"]
forms = []
for attrs, body in MATH.findall(text):
body = body.strip()
if not body or BAD.search(body) or re.search(r"\bchem\b", attrs):
continue
ctx = "display" if re.search(r'display\s*=\s*["\']?block', attrs) else "inline"
forms.append((body, ctx))
forms = list(dict.fromkeys(forms))
if len(forms) < 5:
continue
if len(forms) > 60:
forms = rng.sample(forms, 60)
pages_used.append(dict(
lang=lang, title=p["title"], revid=rev["revid"],
origin="https://%s.wikipedia.org/w/index.php?title=%s&oldid=%d" % (
lang, urllib.parse.quote(p["title"].replace(" ", "_")), rev["revid"]),
history_url="https://%s.wikipedia.org/w/index.php?title=%s&action=history" % (
lang, urllib.parse.quote(p["title"].replace(" ", "_"))),
licence="CC-BY-SA-4.0", licence_url=rights["url"], rights_text=rights["text"],
retrieved=today, formulas=len(forms)))
for body, ctx in forms:
r = pool.get(body)
if r is None:
pool[body] = dict(tex=body, context=ctx, lang=lang, title=p["title"],
revid=rev["revid"], rights_url=rights["url"], page_count=1)
else:
r["page_count"] += 1
cc.log(lang, "titles", len(titles), "pool", len(pool))
# Seeded selection keeping rare commands.
items = sorted(pool.values(), key=lambda r: r["tex"])
cmds = [set(CMD.findall(r["tex"])) for r in items]
df = Counter(c for s in cmds for c in s)
rare = [i for i, s in enumerate(cmds) if any(df[c] < 25 for c in s)]
rare.sort(key=lambda i: (min(df[c] for c in cmds[i]), items[i]["tex"]))
chosen = []
if len(items) <= a.target:
chosen = list(range(len(items)))
else:
covered = set()
for i in rare:
if len(chosen) >= a.target // 2:
break
new = {c for c in cmds[i] if df[c] < 25} - covered
if new or rng.random() < 0.3:
chosen.append(i)
covered |= new
cs = set(chosen)
rest = [i for i in range(len(items)) if i not in cs]
chosen += rng.sample(rest, a.target - len(chosen))
chosen.sort()
with open(a.out, "w", encoding="utf-8") as f:
for i in chosen:
f.write(json.dumps(items[i], ensure_ascii=False) + "\n")
with open(a.out + ".pages.jsonl", "w", encoding="utf-8") as f:
for p in pages_used:
f.write(json.dumps(p, ensure_ascii=False) + "\n")
cc.log("pool distinct", len(pool), "selected", len(chosen), "pages", len(pages_used),
"distinct commands", len(df))
if __name__ == "__main__":
main()