207 lines
15 KiB
Python
207 lines
15 KiB
Python
"""Normalize pinned DBLP publication metadata into audited edition files."""
|
||
import argparse
|
||
from collections import Counter,OrderedDict
|
||
from contextlib import closing
|
||
import fcntl
|
||
import hashlib
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
import shutil
|
||
import sqlite3
|
||
import tempfile
|
||
from urllib.parse import parse_qs,unquote,urlsplit
|
||
|
||
from paper_atlas.config import DEFAULT_REGISTRY
|
||
from paper_atlas.collectors.dblp import XML_SHA,DTD_MD5,RELEASE,records
|
||
from paper_atlas.collectors.dblp_scope import scope
|
||
from paper_atlas.collectors.dblp_predecessors import missing_candidate_families
|
||
from paper_atlas.db.submissions import timestamp
|
||
from paper_atlas.io.snapshots import digest_file
|
||
from paper_atlas.io.publication_ids import mlsys_id
|
||
|
||
AS_OF='2026-11-01T00:00:00.000Z'
|
||
MATERIAL_PART=r'(?:title(?: page)?|preface|foreword|editorial|front\s?matter|back\s?matter|(?:table of )?contents|(?:author |subject )?index|contributors|(?:conference |program |organizing |steering )?committee|conference organization|reviewers)'
|
||
FRONTMATTER=re.compile(MATERIAL_PART+r'(?:\s*[,;&]\s*'+MATERIAL_PART+r')*[.!:]?',re.I)
|
||
HEADINGS=re.compile(r'(?:(?:IJCAI|AAAI)(?:[- ]\d{2,4})? |(?:19|20)\d{2} )?(?:conference )?(?:organization|organizers and sponsors|sponsorship|sponsors|(?:non-PC )?reviewers|awards and distinguished papers|keynote and invited speakers|area chairs and program committee|tutorials|panel session|invited talks|workshops|workshop summaries|special track on continuous planning)[.!:]?',re.I)
|
||
|
||
|
||
def material_reason(title,authors,key,year,track):
|
||
if FRONTMATTER.fullmatch(title):return 'frontmatter'
|
||
if re.search(r"\bchairs['’]? welcome(?:\s*&\s*organization listing)?[.!:]?$",title,re.I):return 'frontmatter'
|
||
if not authors:
|
||
if HEADINGS.fullmatch(title) or re.fullmatch(r'(?:past IJCAI conferences|events colocated with IJCAI-\d{2}|welcome message from the conference chairs|welcome to (?:ICDM|IJCAI|AAAI) \d{4})[.!:]?',title,re.I):return 'proceedings_heading'
|
||
# These anonymous synthetic entries name whole workshop events, rather
|
||
# than identifiable papers. Hold them without discarding the raw source.
|
||
if year==2019 and track=='companion' and re.fullmatch(r'conf/www/X19[a-z]?',key):return 'unverified_proceedings_material'
|
||
return None
|
||
|
||
|
||
def identifiers(fields):
|
||
dois=set();arxiv=set();forums=set();mlsys=set()
|
||
for link in fields.get('ee',[]):
|
||
if own_mlsys := mlsys_id(link):
|
||
mlsys.add(own_mlsys)
|
||
parsed=urlsplit(link);path=unquote(parsed.path)
|
||
doi=None
|
||
if parsed.netloc in ('doi.org','dx.doi.org','doi.ieeecomputersociety.org'):doi=path.lstrip('/')
|
||
elif parsed.netloc=='link.springer.com' and path.startswith('/chapter/'):doi=path.removeprefix('/chapter/')
|
||
elif parsed.netloc=='dl.acm.org':
|
||
match=re.match(r'/doi/(?:abs/|full/|pdf/)?(10\..+)',path)
|
||
if match:doi=match[1]
|
||
if doi and re.fullmatch(r'10\.\d{4,9}/\S+',doi):dois.add(doi.lower())
|
||
if parsed.netloc in ('arxiv.org','www.arxiv.org'):
|
||
match=re.fullmatch(r'/(?:abs|pdf)/((?:\d{4}\.\d{4,5}|[a-zA-Z.-]+/\d{7})(?:v\d+)?)(?:\.pdf)?',path)
|
||
if match:arxiv.add(re.sub(r'v\d+$','',match[1]))
|
||
if parsed.netloc=='openreview.net' and parsed.path in ('/forum','/pdf'):
|
||
values=parse_qs(parsed.query).get('id',[])
|
||
if len(values)==1 and re.fullmatch(r'[A-Za-z0-9_-]+',values[0]) and not re.match(r'20\d{2}-Oral-',values[0]):forums.add(values[0])
|
||
for doi in dois:
|
||
match=re.fullmatch(r'10\.48550/arxiv\.((?:\d{4}\.\d{4,5}|[a-z.-]+/\d{7})(?:v\d+)?)',doi)
|
||
if match:arxiv.add(re.sub(r'v\d+$','',match[1]))
|
||
publications={doi for doi in dois if not doi.startswith('10.48550/arxiv.')}
|
||
own={}
|
||
groups=(('doi',publications),('arxiv',arxiv),('openreview',forums),('publication_mlsys',mlsys))
|
||
for scheme,values in groups:
|
||
if len(values)==1:own[scheme]=next(iter(values))
|
||
ambiguous={scheme:sorted(values) for scheme,values in groups if len(values)>1}
|
||
return own,ambiguous
|
||
|
||
|
||
def normalize_row(row,volumes,targets,include_workshops=False,through_year=2026):
|
||
if row['record_type']!='inproceedings':return None,'not_a_paper'
|
||
fields=row['fields'];refs=fields.get('crossref',[])
|
||
if len(refs)!=1:return None,'ambiguous_or_missing_crossref'
|
||
edition,reason=scope(row,volumes.get(refs[0]),through_year)
|
||
if not edition:return None,reason
|
||
if not ({edition['venue']}|set(edition['venue_aliases']))&targets:return None,'outside_requested_venues'
|
||
if edition['track']=='workshop' and not include_workshops:return None,'separate_workshop'
|
||
titles=fields.get('title',[])
|
||
if len(titles)!=1 or not titles[0].strip():return None,'missing_or_multiple_titles'
|
||
title=' '.join(titles[0].split())
|
||
authors=[re.sub(r'\s+\d{4}$','',name).strip() for name in fields.get('author',[]) if name.strip()]
|
||
reason=material_reason(title,authors,row['key'],edition['year'],edition['track'])
|
||
if reason:return None,reason
|
||
own,ambiguous=identifiers(fields)
|
||
metadata={'snapshot_sha256':XML_SHA,'snapshot_release':RELEASE,'observation_date_precision':'day',
|
||
'proceedings_key':refs[0],'proceedings_title':edition['proceedings_title'],'bibliographic_year':edition['bibliographic_year'],
|
||
'edition_year_basis':edition['edition_year_basis'],
|
||
'scope_rule':edition['rule'],'author_names_raw':fields.get('author',[]),'publtype':row.get('publtype'),
|
||
'bibliography':{key:value for key,value in fields.items() if key in ('booktitle','year','ee','url','pages','volume','number','publisher','series','isbn')},
|
||
'ambiguous_identifiers':ambiguous,'publication_evidence':'inproceedings bibliography; not an original decision note'}
|
||
if edition.get('historical_predecessor_evidence'):
|
||
metadata['historical_predecessor_evidence'] = edition['historical_predecessor_evidence']
|
||
if edition.get('joint_edition_evidence'):
|
||
metadata['joint_edition_evidence'] = edition['joint_edition_evidence']
|
||
if edition.get('track_scope_note'):
|
||
metadata['track_scope_note']=edition['track_scope_note']
|
||
if edition.get('track_scope_evidence_url'):
|
||
metadata['track_scope_evidence_url']=edition['track_scope_evidence_url']
|
||
flagged=bool(re.search(r'\b(?:withdrawn|retracted)\b',row.get('publtype') or '',re.I))
|
||
result={'source':'dblp','external_id':row['key'],'url':'https://dblp.org/rec/'+row['key']+'.html',
|
||
'title':title,'abstract':None,'authors':authors,'identifiers':own,
|
||
**{key:edition[key] for key in ('venue','venue_aliases','year','track')},
|
||
'status':'unknown' if flagged else 'accepted','observed_at':AS_OF,
|
||
'raw_decision':'listed in pinned DBLP inproceedings bibliography','metadata':metadata,
|
||
'tags':[{'namespace':'dblp:booktitle','value':fields['booktitle'][0]}]}
|
||
if flagged:result['decision_events']=[]
|
||
return result,None
|
||
|
||
|
||
def collect(catalogue,out,venues=None,candidates=None,archive=None,dtd=None,include_workshops=False,through_year=2026):
|
||
if bool(candidates)==bool(archive):raise ValueError('Choose exactly one candidates file or original archive')
|
||
catalogue=Path(catalogue);manifest=json.loads(catalogue.with_name('dblp-ai-candidates.manifest.json').read_text())
|
||
if manifest['snapshot_sha256']!=XML_SHA:raise ValueError('Unsupported snapshot identity')
|
||
if candidates:
|
||
if digest_file(Path(candidates))['sha256']!=manifest['candidate_sha256']:raise ValueError('Candidate checksum mismatch')
|
||
else:
|
||
if not dtd or digest_file(Path(dtd))['md5']!=DTD_MD5:raise ValueError('DTD checksum mismatch')
|
||
if digest_file(Path(archive))['sha256']!=XML_SHA:raise ValueError('Archive checksum mismatch')
|
||
with closing(sqlite3.connect(catalogue.resolve().as_uri()+'?mode=ro',uri=True)) as c:
|
||
volumes={key:json.loads(payload) for key,payload in c.execute('SELECT key,metadata_json FROM proceedings')}
|
||
if len(volumes)!=manifest['record_types']['proceedings']:raise ValueError('Catalogue inventory mismatch')
|
||
allowed={row['acronym'].casefold():row['acronym'] for row in json.loads(DEFAULT_REGISTRY.read_text())['venues']}
|
||
if venues and set(name.casefold() for name in venues)-allowed.keys():raise ValueError('Unknown registry venue')
|
||
targets={allowed[name.casefold()] for name in venues} if venues else set(allowed.values())
|
||
if candidates:
|
||
families = manifest.get('candidate_family_counts', {})
|
||
missing = [venue for venue, family in [('MM', 'mm'), ('MLSys', 'mlsys')]
|
||
if venue in targets and not families.get(family)]
|
||
missing += ['ICAPS/'+family for family in missing_candidate_families(targets, families, through_year)]
|
||
if missing:
|
||
raise ValueError('Candidate file omits requested families ' + ', '.join(missing) + '; use the original --archive')
|
||
out=Path(out);out.mkdir(parents=True,exist_ok=True)
|
||
with (out/'dblp.normalize.lock').open('a') as lock:
|
||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||
return _collect_rows(volumes,out,targets,candidates,archive,dtd,include_workshops,through_year,manifest)
|
||
|
||
|
||
def _collect_rows(volumes,out,targets,candidates,archive,dtd,include_workshops,through_year,source_manifest):
|
||
counts=Counter();excluded=Counter();examples={};groups={};seen=set();handles=OrderedDict();scanned=0
|
||
def rows():
|
||
if candidates:
|
||
with Path(candidates).open() as stream:
|
||
for line in stream:yield json.loads(line)
|
||
else:yield from records(archive,Path(dtd).read_bytes())
|
||
if shutil.disk_usage(out).free<8*1024**3:raise RuntimeError('Less than 8 GiB free before normalization')
|
||
with tempfile.TemporaryDirectory(prefix='.dblp-normalize-',dir=out) as temporary:
|
||
stage=Path(temporary)
|
||
try:
|
||
for row in rows():
|
||
scanned+=1
|
||
record,reason=normalize_row(row,volumes,targets,include_workshops,through_year)
|
||
if record is None:
|
||
excluded[reason]+=1
|
||
label=reason+'|'+'/'.join(row.get('key','').split('/')[:2])+'|'+';'.join(row['fields'].get('booktitle',[]))
|
||
if label not in examples:examples[label]={'count':0,'example_key':row.get('key')}
|
||
examples[label]['count']+=1
|
||
else:
|
||
key=record['external_id']
|
||
if key in seen:raise ValueError('Repeated DBLP publication key')
|
||
seen.add(key);group=(record['venue'],record['year'],record['track'])
|
||
filename='dblp-'+re.sub(r'[^a-z0-9]+','-',group[0].casefold())+'-'+str(group[1])+'-'+group[2]+'.jsonl'
|
||
if group not in groups:groups[group]={'filename':filename,'count':0,'unknown':0,'ambiguous_identifiers':0}
|
||
info=groups[group];info['count']+=1;info['unknown']+=record['status']=='unknown';info['ambiguous_identifiers']+=bool(record['metadata']['ambiguous_identifiers'])
|
||
if group not in handles:
|
||
if len(handles)>=32:handles.popitem(last=False)[1].close()
|
||
handles[group]=(stage/filename).open('a')
|
||
handles.move_to_end(group);handles[group].write(json.dumps(record,ensure_ascii=False)+'\n');counts[record['venue']]+=1
|
||
if scanned%50000==0:
|
||
if shutil.disk_usage(out).free<8*1024**3:raise RuntimeError('Less than 8 GiB free during normalization')
|
||
print(json.dumps({'source':'dblp','scanned':scanned,'normalized':sum(counts.values())}),flush=True)
|
||
finally:
|
||
for handle in handles.values():handle.close()
|
||
expected=source_manifest['candidate_records'] if candidates else sum(source_manifest['record_types'].values())
|
||
if scanned!=expected:raise ValueError('Input count differs from verified catalogue')
|
||
if not seen:raise ValueError('No target publications were verified')
|
||
files=[]
|
||
for (venue,year,track),info in sorted(groups.items()):
|
||
path=out/info['filename'];checksum=digest_file(stage/info['filename'])['sha256']
|
||
item={'source':'dblp','parser_version':1,'venue':venue,'year':year,'track':track,'count':info['count'],
|
||
'missing_abstract_count':info['count'],'unknown_status_count':info['unknown'],'ambiguous_identifier_count':info['ambiguous_identifiers'],
|
||
'list_url':RELEASE,'status':'partial','file':str(path),'file_sha256':checksum,'snapshot_sha256':XML_SHA,
|
||
'abstract_note':'DBLP provides no abstract; canonical abstracts must come from independently linked sources.'}
|
||
(stage/info['filename']).replace(path)
|
||
meta=path.with_suffix('.manifest.json');part=meta.with_suffix('.part');part.write_text(json.dumps(item,indent=2));part.replace(meta);files.append(item)
|
||
result={'source':'dblp','finished_at':timestamp(),'snapshot_sha256':XML_SHA,'input_mode':'candidates' if candidates else 'original_archive',
|
||
'requested_venues':sorted(targets),'include_workshops':include_workshops,'through_year':through_year,'scanned_records':scanned,
|
||
'normalized_records':len(seen),'records_by_venue':dict(counts),'excluded_by_reason':dict(excluded),'scope_review':examples,'files':files,
|
||
'input_candidate_sha256':source_manifest['candidate_sha256'] if candidates else None,
|
||
'note':'Classification covers requested recognizable bibliography entries, not an independent proof of complete venue histories. Unknown scopes remain in scope_review.'}
|
||
target=out/'dblp-normalization.json';part=target.with_suffix('.part');part.write_text(json.dumps(result,ensure_ascii=False,indent=2));part.replace(target)
|
||
queue={'files':[item['file'] for item in files],'file_sha256':{item['file']:item['file_sha256'] for item in files}}
|
||
target=out/'dblp-import-queue.json';part=target.with_suffix('.part');part.write_text(json.dumps(queue,indent=2));part.replace(target)
|
||
print(json.dumps({key:result[key] for key in ('scanned_records','normalized_records','records_by_venue','excluded_by_reason')}),flush=True)
|
||
return result
|
||
|
||
|
||
def main(argv=None,*,prog=None):
|
||
parser=argparse.ArgumentParser(prog=prog);parser.add_argument('--catalogue',required=True);parser.add_argument('--out',required=True)
|
||
inputs=parser.add_mutually_exclusive_group(required=True);inputs.add_argument('--candidates');inputs.add_argument('--archive')
|
||
parser.add_argument('--dtd');parser.add_argument('--venue',action='append');parser.add_argument('--include-workshops',action='store_true')
|
||
parser.add_argument('--through-year',type=int,default=2026);args=parser.parse_args(argv)
|
||
collect(args.catalogue,args.out,args.venue,args.candidates,args.archive,args.dtd,args.include_workshops,args.through_year)
|
||
|
||
|
||
if __name__=='__main__':main()
|