#!/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 `` 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 (`{{`), ``, `]*)?)>(.*?)", re.S) BAD = re.compile(r"\{\{| 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:" 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()