"""Build the corpus and the ground truth table. Text: English Wikipedia extracts, CC BY-SA 4.0, revision ids recorded in corpus-sources.json so the exact text is identifiable. Project Gutenberg was the first choice and refused automated fetches with 503 from two addresses. Owner labels are assigned round robin over paragraph order, so owner is statistically independent of content. That independence is load bearing. If owners were topical, the embedding could encode owner and a filtered query might look clean because the nearest neighbours happen to carry the right owner. Round robin over one topical pool means every query retrieves paragraphs from several owners, which is what lets the unfiltered positive control pass, and makes the filter the only thing that can be doing the work. Ground truth is the owner assigned here, keyed by id. The harness joins on id and never reads an owner back out of a search result. """ import hashlib import json import os import re import sys import urllib.parse import urllib.request OUT = os.path.dirname(os.path.abspath(__file__)) API = 'https://en.wikipedia.org/w/api.php' OWNERS = ['acme', 'borealis', 'cardoso', 'dalmar'] TARGET = 240 TITLES = [ 'Bill of lading', 'Charterparty', 'Demurrage', 'Laytime', 'Freight rate', 'Container ship', 'Port of Rotterdam', 'Maritime transport', 'Cargo', 'Marine insurance', 'Panama Canal', 'Suez Canal', 'Bulk carrier', 'Oil tanker', 'Ship registration', 'Flag of convenience', 'Dry dock', 'Harbor pilot', 'Stevedore', 'Intermodal container', 'Shipbroker', 'Classification society', 'International Maritime Organization', 'Port state control', 'Load line', 'Draft (hull)', 'Ballast water', 'Shipping agency', 'Bunker fuel', 'Seaworthiness', ] def fetch_extracts(): """One article per request, cached to raw/ so a rerun never refetches. Wikipedia rate limited at 429 on an unthrottled loop, so each request waits and backs off. The cache also means the exact text used is kept on disk and published, not refetched later into something different. """ import time raw_dir = os.path.join(OUT, 'raw') os.makedirs(raw_dir, exist_ok=True) docs, sources = [], [] for title in TITLES: cache = os.path.join(raw_dir, re.sub(r'[^a-z0-9]+', '-', title.lower()) + '.json') if os.path.exists(cache): page = json.load(open(cache, encoding='utf-8')) else: q = {'action': 'query', 'prop': 'extracts|revisions', 'explaintext': '1', 'rvprop': 'ids', 'format': 'json', 'formatversion': '2', 'titles': title} url = API + '?' + urllib.parse.urlencode(q) req = urllib.request.Request(url, headers={'User-Agent': 'research-bench'}) page = None for attempt in range(5): try: with urllib.request.urlopen(req, timeout=60) as r: data = json.load(r) pages = data.get('query', {}).get('pages', []) page = pages[0] if pages else None break except urllib.error.HTTPError as e: if e.code != 429 or attempt == 4: raise time.sleep(5 * (attempt + 1)) if page is None: continue json.dump(page, open(cache, 'w', encoding='utf-8')) time.sleep(1.5) if 'extract' not in page: continue rev = (page.get('revisions') or [{}])[0].get('revid') sources.append({'title': page['title'], 'revid': rev, 'license': 'CC BY-SA 4.0', 'url': 'https://en.wikipedia.org/?curid=%s' % page.get('pageid')}) docs.append((page['title'], page['extract'])) return docs, sources def paragraphs(pages): out = [] for title, text in pages: for p in re.split(r'\n+', text): p = ' '.join(p.split()) if 180 <= len(p) <= 1400 and not p.startswith('=='): out.append((title, p)) return out def main(): pages, sources = fetch_extracts() paras = paragraphs(pages) if len(paras) < TARGET: sys.exit('only %d usable paragraphs, need %d' % (len(paras), TARGET)) # interleave by source article so no owner is dominated by one article paras.sort(key=lambda tp: (tp[1][:40])) paras = paras[:TARGET] docs = [] for n, (title, text) in enumerate(paras): docs.append({ 'id': 'doc-%04d' % n, 'owner': OWNERS[n % len(OWNERS)], 'article': title, 'text': text, 'sha256': hashlib.sha256(text.encode()).hexdigest()[:16], }) sizes = {o: sum(1 for d in docs if d['owner'] == o) for o in OWNERS} assert len(set(sizes.values())) == 1, 'unbalanced owners: %s' % sizes # owner must not be guessable from the source article import collections for o in OWNERS: arts = collections.Counter(d['article'] for d in docs if d['owner'] == o) top = arts.most_common(1)[0][1] / sizes[o] assert top < 0.35, 'owner %s is %.0f%% one article' % (o, 100 * top) json.dump(docs, open(os.path.join(OUT, 'corpus.json'), 'w'), indent=1) json.dump({d['id']: d['owner'] for d in docs}, open(os.path.join(OUT, 'ground-truth.json'), 'w'), indent=1) json.dump(sources, open(os.path.join(OUT, 'corpus-sources.json'), 'w'), indent=1) print('corpus: %d documents, %d owners, %d each' % (len(docs), len(OWNERS), sizes[OWNERS[0]])) print('articles: %d, all CC BY-SA 4.0 with revision ids recorded' % len(sources)) print('no owner is more than 35%% one article') if __name__ == '__main__': main()