edugraph-bench / scripts /fetch_sources.py
christian-bick's picture
Initial development seed: 27 tasks with source provenance and proposed labels
12d8f1a verified
Raw History Blame Contribute Delete
1.44 kB
"""Fetch only the pinned, approved originals and verify their SHA-256 hashes."""
from pathlib import Path
from urllib.request import Request, urlopen
import hashlib
import json
ROOT = Path(__file__).resolve().parents[1]
def main():
sources = {s['source_id']: s for s in json.loads((ROOT / 'sources/registry.json').read_text(encoding='utf-8'))['sources']}
for doc in json.loads((ROOT / 'sources/documents.json').read_text(encoding='utf-8'))['documents']:
if sources[doc['source_id']]['status'] != 'approved':
raise ValueError('Source must be approved before fetching: ' + doc['document_id'])
dest = (ROOT / doc['path']).resolve()
if not dest.is_relative_to(ROOT):
raise ValueError('Destination escapes repository')
if dest.exists():
data = dest.read_bytes()
else:
with urlopen(Request(doc['download_url'], headers={'User-Agent': 'EduGraphBench/0.1'}), timeout=60) as response:
data = response.read(100_000_001)
if len(data) > 100_000_000 or not data.startswith(b'%PDF') or hashlib.sha256(data).hexdigest() != doc['sha256']:
raise ValueError('Source changed or failed verification: ' + doc['document_id'])
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists():
dest.write_bytes(data)
print('Verified', doc['document_id'])
if __name__ == '__main__':
main()