Files
paper-atlas/paper_atlas/collectors/public_openreview.py
2026-11-06 22:39:55 +08:00

253 lines
13 KiB
Python

"""Collect explicit public negative labels without inferring unobserved decisions.
PaperCopilot is a curated mirror, not the conference's signed decision feed.
Only metadata is retained; source profiles, reviews and PDFs are never cached.
"""
import argparse
from collections import Counter, defaultdict
import fcntl
import hashlib
import io
import json
from pathlib import Path
import re
import shutil
import tempfile
import urllib.request
from paper_atlas.config import DEFAULT_REGISTRY
from paper_atlas.db.submissions import timestamp
SOURCE = 'papercopilot_openreview'
REVISION = '41ee277825d685bd78e88e48b69da6aead9a69bb'
AS_OF = '2026-10-31T01:25:52.000Z'
REPOSITORY = 'https://github.com/papercopilot/openreview'
RAW_ROOT = 'https://raw.githubusercontent.com/papercopilot/openreview/' + REVISION + '/'
TREE_URL = 'https://api.github.com/repos/papercopilot/openreview/git/trees/' + REVISION + '?recursive=1'
NEGATIVE = {'reject': 'rejected', 'rejected': 'rejected',
'desk reject': 'desk_rejected', 'desk rejected': 'desk_rejected',
'withdrawn': 'withdrawn', 'withdrawal': 'withdrawn'}
TRACKS = {'main': 'main', 'Position': 'position',
'Datasets & Benchmarks': 'datasets_benchmarks'}
WORKSHOP_REJECT_LABELS = {"aim-fm workshop @ neurips'24 reject",
'coginterp @ neurips 2025 reject'}
def download(url, limit):
request = urllib.request.Request(url, headers={'User-Agent': 'PaperAtlas/0.1 (public scholarly metadata)'})
with urllib.request.urlopen(request, timeout=90) as response:
if response.status != 200:
raise ValueError('Expected a complete HTTP 200 response')
result = response.read(limit + 1)
if len(result) > limit:
raise ValueError('Public metadata exceeds byte limit')
return result
def negative_status(raw):
"""A closed mapping: pending, absent, low-score and retracted are not Reject."""
if not isinstance(raw, str):
raise ValueError('Status must be text')
key = ' '.join(raw.casefold().split())
if key in NEGATIVE:
return NEGATIVE[key]
if re.fullmatch(r'(?:icml|neurips) 20\d{2} (?:conference|workshop [a-z0-9 -]+) withdrawn submission', key):
return 'withdrawn'
if key in WORKSHOP_REJECT_LABELS:
return 'rejected'
return None
def normalize(row, family, year, provenance, include_workshops=False):
"""Return a normalized assertion or a reason requiring separate review."""
raw_status = row.get('status', '')
status = negative_status(raw_status)
if status is None:
if re.search(r'\bretract\w*\b', raw_status, re.I):
return None, 'retracted'
if re.search(r'\b(?:reject\w*|withdraw\w*|desk)\b', raw_status, re.I):
return None, 'unmapped_negative_label'
return None, 'not_explicit_negative'
forum = row.get('id')
if not isinstance(forum, str) or not re.fullmatch(r'[A-Za-z0-9_-]{8,32}', forum) or re.match(r'20\d{2}-Oral-', forum):
raise ValueError('Invalid public submission forum ID')
track = row.get('track')
if not isinstance(track, str):
raise ValueError('Track must be explicit text')
normalized_track = TRACKS.get(track)
if normalized_track is None:
if re.fullmatch(r'workshop_[a-z0-9_]+', track) and include_workshops:
normalized_track = track
else:
return None, 'separate_workshop' if track.startswith('workshop') else 'unmapped_track'
prefixed = re.match(r'^(ICML|NeurIPS) (20\d{2}) ', raw_status)
if prefixed and (prefixed[1].casefold() != ('neurips' if family == 'nips' else family) or int(prefixed[2]) != year):
raise ValueError('Status label conflicts with source conference year')
allowed = {v['acronym'].casefold(): v['acronym'] for v in json.loads(DEFAULT_REGISTRY.read_text())['venues']}
venue = allowed.get({'nips': 'neurips', 'acmmm': 'mm'}.get(family, family))
if venue is None:
return None, 'unmapped_venue'
title = row.get('title')
abstract = row.get('abstract')
if not isinstance(title, str) or not title.strip():
raise ValueError('Public submission lacks a title')
if abstract is not None and not isinstance(abstract, str):
raise ValueError('Abstract must be text or null')
author_text = row.get('author') or ''
if not isinstance(author_text, str):
raise ValueError('Unexpected public author format')
authors = [a.strip() for a in author_text.split(';') if a.strip() and '@' not in a
and not re.fullmatch(r'anonymous(?: authors?)?', a.strip(), re.I)]
tags = []
for field in ('keywords', 'primary_area'):
value = row.get(field)
if value is None:
continue
terms = value if isinstance(value, list) else re.split(r'[,;]', value) if field == 'keywords' and isinstance(value, str) else [value]
tags.extend({'namespace': SOURCE + ':' + field, 'value': term.strip()}
for term in terms if isinstance(term, str) and term.strip())
evidence = provenance['source_file'] + '#L' + str(provenance['source_line'])
return {'source': SOURCE, 'external_id': f'{family}/{year}/{forum}',
'url': 'https://openreview.net/forum?id=' + forum,
'title': ' '.join(title.split()), 'abstract': abstract.strip() if abstract else None,
'authors': authors, 'identifiers': {'openreview': forum},
'submission_identifiers': [{'scheme': 'openreview', 'value': forum}],
'venue': venue, 'year': year, 'track': normalized_track,
'status': status, 'raw_decision': raw_status, 'evidence_url': evidence,
'observed_at': AS_OF, 'tags': tags,
'metadata': {**provenance, 'raw_track': track, 'raw_status': raw_status,
'evidence_kind': 'curated_public_status_assertion',
'original_decision_signature_verified': False,
'source_snapshot_upper_bound': AS_OF}}, None
def held_metadata(row, reason, provenance):
# Retractions and unresolved track scopes remain visible without becoming
# invented Reject/Withdrawn events in a schema that cannot represent them.
return {key: row.get(key) for key in ('id', 'title', 'abstract', 'track', 'status')} | {
'reason': reason, 'provenance': provenance}
def collect(out, families=None, years=None, include_workshops=False, fetcher=None):
fetcher = fetcher or download
out = Path(out)
out.mkdir(parents=True, exist_ok=True)
with (out / 'collect.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if (out / 'public-openreview-inventory.json').exists():
raise ValueError('Completed inventory exists; select a new output directory')
if shutil.disk_usage(out).free < 8 * 1024**3:
raise RuntimeError('Less than 8 GiB free before collection')
tree = json.loads(fetcher(TREE_URL, 8 * 1024**2))
if tree.get('truncated') is not False or tree.get('sha') != REVISION:
raise ValueError('Incomplete or unpinned public source tree')
selected = []
for item in tree['tree']:
match = re.fullmatch(r'venues/([a-z0-9]+)/\1((?:19|20)\d{2})\.jsonl', item['path'])
if item['type'] != 'blob' or not match:
continue
family, year = match[1], int(match[2])
if year > 2026 or (families is None and family == 'iclr'):
continue
if families is not None and family not in families or years is not None and year not in years:
continue
selected.append((item, family, year))
if not selected:
raise ValueError('No pinned source files match the request')
if families and set(families) - {family for _, family, _ in selected}:
raise ValueError('Requested venue has no selected source file')
if years and set(years) - {year for _, _, year in selected}:
raise ValueError('Requested year has no selected source file')
return _collect_files(out, selected, include_workshops, fetcher)
def _collect_files(out, selected, include_workshops, fetcher):
summaries = []
groups = defaultdict(list)
global_forums = {}
with tempfile.TemporaryDirectory(prefix='.public-openreview-', dir=out) as temporary:
stage = Path(temporary)
held_path = stage / 'held-records.jsonl'
with held_path.open('w') as held:
for item, family, year in sorted(selected, key=lambda entry: entry[0]['path']):
size = item['size']
if not isinstance(size, int) or not 0 < size <= 96 * 1024**2:
raise ValueError('Unexpected metadata file size')
data = fetcher(RAW_ROOT + item['path'], size)
blob = hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
if len(data) != size or blob != item['sha']:
raise ValueError('Pinned source blob checksum mismatch')
matrix = Counter()
reasons = Counter()
seen = set()
rows = 0
for number, line in enumerate(io.BytesIO(data), 1):
if len(line) > 4 * 1024**2:
raise ValueError('Oversized metadata row')
row = json.loads(line)
forum = row.get('id')
if not isinstance(forum, str) or forum in seen:
raise ValueError('Missing or duplicate source forum ID')
seen.add(forum)
edition = (family, year, row.get('track'))
if forum in global_forums and global_forums[forum] != edition:
raise ValueError('One forum appears in multiple source editions or tracks')
global_forums[forum] = edition
rows += 1
matrix[(row.get('track'), row.get('status'))] += 1
provenance = {'source_revision': REVISION, 'source_blob_sha1': blob,
'source_file': RAW_ROOT + item['path'], 'source_line': number}
record, reason = normalize(row, family, year, provenance, include_workshops)
if record is None:
reasons[reason] += 1
if reason != 'not_explicit_negative':
held.write(json.dumps(held_metadata(row, reason, provenance), ensure_ascii=False) + '\n')
else:
groups[(family, year, record['track'])].append(record)
summary = {'path': item['path'], 'input_bytes': size, 'git_blob_sha1': blob,
'rows': rows, 'excluded_or_held': dict(reasons),
'status_matrix': [{'track': t, 'status': s, 'count': n} for (t, s), n in matrix.items()]}
summaries.append(summary)
print(json.dumps({key: summary[key] for key in ('path', 'rows', 'excluded_or_held')}), flush=True)
files = []
for (family, year, track), records in sorted(groups.items()):
name = f'public-openreview-{family}-{year}-{track}.jsonl'
path = stage / name
path.write_text(''.join(json.dumps(row, ensure_ascii=False) + '\n' for row in records))
manifest = {'source': SOURCE, 'parser_version': 1, 'venue': records[0]['venue'],
'year': year, 'track': track, 'count': len(records), 'status': 'partial',
'file': str(out / name), 'file_sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'list_url': REPOSITORY + '/tree/' + REVISION, 'source_revision': REVISION,
'missing_abstract_count': sum(not row['abstract'] for row in records),
'evidence_kind': 'curated_public_status_assertion',
'note': 'Public subset only; no population coverage or original decision-signature claim.'}
path.with_suffix('.manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
files.append(manifest)
result = {'source': SOURCE, 'revision': REVISION, 'finished_at': timestamp(),
'input_rows': sum(item['rows'] for item in summaries), 'source_files': summaries,
'normalized_records': sum(item['count'] for item in files), 'files': files,
'include_workshops': include_workshops, 'held_file': str(out / held_path.name),
'held_file_sha256': hashlib.sha256(held_path.read_bytes()).hexdigest(),
'note': 'Zero explicit negative records in this mirror does not prove no public rejections exist.'}
inventory = stage / 'public-openreview-inventory.json'
inventory.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
# Publish only after every selected source has passed its pinned hash.
for path in sorted(stage.iterdir(), key=lambda path: path == inventory):
path.replace(out / path.name)
return result
def main(argv=None, *, prog=None):
parser = argparse.ArgumentParser(prog=prog)
parser.add_argument('--out', required=True)
parser.add_argument('--family', action='append', help='Source family, e.g. icml, nips, emnlp')
parser.add_argument('--year', type=int, action='append')
parser.add_argument('--include-workshops', action='store_true')
args = parser.parse_args(argv)
collect(args.out, args.family, args.year, args.include_workshops)
if __name__ == '__main__':
main()