#!/usr/bin/env python3
"""Rebuild the reference-only rows of jialinyyzz/humanizer-data.
Those rows carry no text because the source license does not let us pass it on. Each row has
`upstream_dataset`, `upstream_id` and (often) `upstream_url`; this script fetches the original record
from its public source and checks it against `original_sha256`.
Usage:
pip install datasets requests pyarrow huggingface_hub
python scripts/rebuild_reference_only.py --config rewrite_sft --out rebuilt_sft.jsonl [--only MedRAG/pubmed] [--limit 100]
python scripts/rebuild_reference_only.py --input reference_only.jsonl --out rebuilt.jsonl # a local copy of the split
Output, one line per row: {id, upstream_dataset, upstream_id, how, text, sha256_match, error?}
Notes:
* You get the whole upstream record. The text we trained on is often an excerpt of it with whitespace,
hard line breaks, quoted replies and signatures tidied, so `sha256_match` is false for many rows even
when the record is the right one. `sha256_match` compares the lower-cased, whitespace-collapsed text.
* Row-index IDs ("[config:]split:N") are 0-based positions in the upstream Hugging Face dataset
(the `row_idx` of the datasets-server /rows API).
* Some sources must be downloaded by hand or need you to accept terms first (PERSUADE 2.0, the Enron
archive, Kaggle data, NUCLE, large corpora); the script reports what to do for those rows.
* Respect each source's license and terms. These rows are reference-only for a reason.
"""
import csv, gzip, html, io, json, os, re, sys, time, urllib.parse, urllib.request
UA = 'humanizer-data-rebuild/1.0'
ROWS_API = 'https://datasets-server.huggingface.co/rows'
HF_TOKEN = os.environ.get('HF_TOKEN')
def http(url, data=None, headers=None, tries=5):
h = {'User-Agent': UA}
if headers: h.update(headers)
for a in range(tries):
try:
with urllib.request.urlopen(urllib.request.Request(url, data=data, headers=h), timeout=120) as r:
return r.read()
except urllib.error.HTTPError as e:
if e.code == 404: raise
time.sleep(45 if e.code == 429 else 3 * (a + 1))
except Exception:
time.sleep(3 * (a + 1))
raise RuntimeError(f'fetch failed: {url}')
def hf_row(ds, cfg, split, idx, revision=None):
q = {'dataset': ds, 'config': cfg, 'split': split, 'offset': int(idx), 'length': 1}
hd = {'Authorization': f'Bearer {HF_TOKEN}'} if HF_TOKEN else None
j = json.loads(http(f'{ROWS_API}?{urllib.parse.urlencode(q)}', headers=hd))
rows = j.get('rows') or []
if not rows: raise LookupError(f'{ds} {cfg}/{split} row {idx} not found')
r = rows[0]
if r.get('truncated_cells'): # the rows API truncates very large cells
raise LookupError(f'{ds} row {idx}: cell truncated by the rows API; download the parquet file instead')
return r['row']
def parse_rowid(uid, default_cfg='default'):
p = uid.split(':')
if len(p) == 2: return default_cfg, p[0], int(p[1])
return p[0], p[1], int(p[2])
def hf_file(repo, path, revision='main'):
"""Download one file from a Hugging Face dataset repo (cached)."""
try:
from huggingface_hub import hf_hub_download
return open(hf_hub_download(repo, path, repo_type='dataset', revision=revision), 'rb').read()
except ImportError:
url = f'https://huggingface.co/datasets/{repo}/resolve/{urllib.parse.quote(revision, safe="")}/{path}'
return http(url)
# ---------------------------------------------------------------- per-source fetchers
def get_rowindex(ds, field, default_cfg='default', post=None):
def f(r):
cfg, split, i = parse_rowid(r['upstream_id'], default_cfg)
t = hf_row(ds, cfg, split, i)[field]
return post(t) if post else t
return f
def get_hn(r):
j = json.loads(http(f"https://hacker-news.firebaseio.com/v0/item/{r['upstream_id']}.json"))
return j.get('text')
_medrag = {}
def get_pubmed(r):
m = re.match(r'(pubmed\d+n\d+)_(\d+)$', r['upstream_id'])
if m:
fn, k = m.group(1), int(m.group(2))
if fn not in _medrag:
_medrag[fn] = hf_file('MedRAG/pubmed', f'chunk/{fn}.jsonl').decode().splitlines()
o = json.loads(_medrag[fn][k])
assert o['id'] == r['upstream_id'], 'MedRAG id mismatch'
return o['contents']
pmid = re.search(r'/(\d+)/?$', r.get('upstream_url') or '').group(1) # fallback: NCBI E-utilities (format differs from MedRAG)
return http(f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id={pmid}&rettype=abstract&retmode=text').decode()
def get_gutenberg2(r):
k = int(r['upstream_id'].split(':')[1])
return json.loads(hf_file('nbeerbower/gutenberg2-dpo', 'gb2_2024_11_16.json'))[k]['chosen']
_small = {}
def get_by_col(repo, path, col, field, kind):
"""Download a small file once and index it by a column."""
def f(r):
key = (repo, path)
if key not in _small:
b = hf_file(repo, path)
if kind == 'parquet':
import pyarrow.parquet as pq
rows = pq.read_table(io.BytesIO(b)).to_pylist()
else:
rows = list(csv.DictReader(io.StringIO(b.decode('utf-8'))))
_small[key] = {str(x[col]): x for x in rows}
return _small[key][r['upstream_id']][field]
return f
def get_peerread(r):
path, k = r['upstream_id'].split('#')
j = json.loads(http(f'https://raw.githubusercontent.com/allenai/PeerRead/master/data/{path}'))
return j['reviews'][int(k)]['comments']
_crs = {}
def get_crs(r):
if not _crs:
for row in csv.DictReader(io.StringIO(http('https://www.everycrsreport.com/reports.csv').decode('utf-8'))):
_crs[row['number']] = row
h = http('https://www.everycrsreport.com/' + _crs[r['upstream_id']]['latestHTML']).decode('utf-8', 'replace')
t = re.sub(r'(?i)
', '\n', h); t = re.sub(r'(?i)