"""Reconstruct CES CoEdIT inputs locally from the official upstream distribution. Requires huggingface_hub and pyarrow. Downloading requires an explicit flag; users must establish that their intended use complies with upstream terms. The output directory must be separate from the public artifact tree. """ import argparse import hashlib import json from pathlib import Path def sha256(data): return hashlib.sha256(data).hexdigest() def read_jsonl(path): with path.open(encoding='utf-8') as stream: return [json.loads(line) for line in stream if line.strip()] def strip_instruction(text): prefix, separator, rest = text.partition(': ') return rest if separator and len(prefix.split()) <= 8 else text def load_sources(folder, specification): sources = {} for split, expected in specification['upstream_files'].items(): path = folder / f'{split}.jsonl' if sha256(path.read_bytes()) != expected['sha256']: raise ValueError(f'Upstream file hash mismatch: {path}') for row in read_jsonl(path): key = (split, str(row['_id'])) if key in sources: raise ValueError(f'Duplicate upstream ID: {key}') sources[key] = (strip_instruction(row['src']), row['tgt']) return sources def source_for(reference, sources): pair = sources[(reference['split'], reference['id'])] text = pair[reference['field']] if sha256(text.encode()) != reference['sha256']: raise ValueError(f'Source text mismatch: {reference["split"]}/{reference["id"]}') return text def materialize(parts, source): chunks = [] for part in parts: if set(part) == {'slice'}: start, end = part['slice'] if not 0 <= start <= end <= len(source): raise ValueError('Invalid source slice') chunks.append(source[start:end]) elif set(part) == {'literal'}: chunks.append(part['literal']) else: raise ValueError('Unknown edit payload format') return ''.join(chunks) def write_jsonl(path, rows): path.parent.mkdir(parents=True, exist_ok=True) with path.open('w', encoding='utf-8') as stream: for row in rows: stream.write(json.dumps(row, ensure_ascii=False, separators=(',', ':')) + '\n') def reconstruct(recipe_dir, upstream_dir, output): import pyarrow as pa import pyarrow.parquet as pq spec = json.loads((recipe_dir / 'specification.json').read_text()) sources = load_sources(upstream_dir, spec) counts = {} for item in spec['manifests']: rows = [] for recipe in read_jsonl(recipe_dir / item['recipe']): row = dict(recipe['metadata']) for field, reference in recipe['text_references'].items(): row[field] = source_for(reference, sources) rows.append(row) destination = output / item['output'] write_jsonl(destination, rows) counts[item['output']] = len(rows) for item in spec['clean_shards']: rows = [] for recipe in read_jsonl(recipe_dir / item['recipe']): row = dict(recipe['metadata']) for field, reference in recipe['text_references'].items(): row[field] = source_for(reference, sources) rows.append(row) destination = output / item['output'] destination.parent.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(rows), destination, compression='zstd') counts[item['output']] = len(rows) rows = [] for recipe in read_jsonl(recipe_dir / 'corruptions.jsonl'): source = source_for(recipe['source'], sources) corrupted = materialize(recipe['corrupted_parts'], source) if sha256(corrupted.encode()) != recipe['corrupted_sha256']: raise ValueError('Reconstructed corruption hash mismatch') row = dict(recipe['metadata']) row['source_text'] = source row['corrupted_text'] = corrupted for direction, text in [('forward', source), ('inverse', corrupted)]: edits = [] for encoded in recipe[f'{direction}_edits']: edit = dict(encoded) if 'content_parts' in edit: edit['content'] = materialize(edit.pop('content_parts'), text) edits.append(edit) row[f'{direction}_edits_json'] = json.dumps(edits) rows.append(row) relative = 'data/posttraining/ces/v1/gec-corruptions/approved-corruptions.parquet' destination = output / relative destination.parent.mkdir(parents=True, exist_ok=True) pq.write_table(pa.Table.from_pylist(rows), destination, compression='zstd') counts[relative] = len(rows) (output / 'RECONSTRUCTION.json').write_text(json.dumps({ 'upstream_revision': spec['upstream_revision'], 'rows': counts, 'scope': 'Text, row order and training edit programs verified; Parquet bytes and API traces are not reproduced.', }, indent=2) + '\n') return counts def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--upstream-dir', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--download', action='store_true', help='Fetch the pinned official CoEdIT files') args = parser.parse_args() recipes = Path(__file__).resolve().parent output = args.output.resolve() public_root = recipes.parent if output == public_root or public_root in output.parents or output in public_root.parents: parser.error('Reconstruct outside the public artifact tree to avoid accidental re-upload.') if output.exists() and any(output.iterdir()): parser.error('Choose an empty output directory; existing inputs will not be overwritten.') spec = json.loads((recipes / 'specification.json').read_text()) upstream = args.upstream_dir.resolve() if upstream == public_root or public_root in upstream.parents: parser.error('Keep downloaded upstream files outside the public artifact tree.') if args.download: from huggingface_hub import hf_hub_download for filename in ('train.jsonl', 'validation.jsonl'): hf_hub_download(spec['upstream_repository'], filename, repo_type='dataset', revision=spec['upstream_revision'], local_dir=args.upstream_dir) counts = reconstruct(recipes, args.upstream_dir, output) print(json.dumps(counts, indent=2)) if __name__ == '__main__': main()