Download tools/sequence_insertions.py from maxwellinked/time-lapse-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 18.3 kB
-
https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/refs%2Fpr%2F113/tools/sequence_insertions.py
- Command line
-
hf download hf://datasets/maxwellinked/time-lapse-artifacts@refs/pr/113/tools/sequence_insertions.py
-
curl -L -o sequence_insertions.py https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts/resolve/refs%2Fpr%2F113/tools/sequence_insertions.py
18.3 kB
| #!/usr/bin/env python3 | |
| """Validate the two explicitly registered sequence insertion supplements. | |
| Strict validation binds media and metadata to a captured immutable Hub inventory. | |
| Prepublication validation is explicitly unbound and cannot authorize publication. | |
| The ordinary dated fragment validator and its RecNN contract remain unchanged. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import re | |
| from pathlib import Path, PurePosixPath | |
| REGISTRY_PATH = 'Standard_Time_Lapses/Provenance/Sequence_Insertions/registry.json' | |
| MANIFEST_PATH = 'Standard_Time_Lapses/Provenance/Sequence_Insertions/2026-10-29-F/sequence.json' | |
| F_LABEL = '2026-10-25.0938.BallpointPen.Ink.Paper.9x12' | |
| NINE_BY_TWELVE_MANIFEST_PATH = 'Standard_Time_Lapses/Provenance/Sequence_Insertions/2026-10-30-9x12/sequence.json' | |
| NINE_BY_TWELVE_LABEL = '2026-10-27.0100.Pencil.Graphite.FountainPen.Ink.Paper.9x12' | |
| # Exact path/label pairs only: this is not a generic insertion mechanism. | |
| SEQUENCE_CONTRACTS = { | |
| (MANIFEST_PATH, F_LABEL): (('03a', '03b'), '2026-10-25', '09:38'), | |
| (NINE_BY_TWELVE_MANIFEST_PATH, NINE_BY_TWELVE_LABEL): (('03a',), '2026-10-27', '01:00'), | |
| } | |
| PREDECESSOR_PATH = 'Standard_Time_Lapses/Provenance/2026-10-29/fragment_sequence_relationships.csv' | |
| PREDECESSOR_SHA256 = 'd930bd171220403df10247cb3c05cb7ad431689c7bfcd0e4ec7e3c11ec9f232d' | |
| PREDECESSOR_REVISION = '4f563085afacfc454496ac2d61606614268b2cb8' | |
| EVIDENCE = {'membership': 'owner-confirmed', 'order': 'visual-inference-with-device-metadata-corroboration', 'gapless_capture': 'not-established'} | |
| HASH_RE = re.compile(r'^[0-9a-f]{64}$') | |
| REVISION_RE = re.compile(r'^[0-9a-f]{40}$') | |
| RECORD_RE = re.compile(r'^tla-[0-9a-f]{16}$') | |
| LETTERED_RE = re.compile(r'\.Rec\d+[a-zA-Z]+\.mp4$') | |
| MEMBER_KEYS = {'record_id', 'file_path', 'sha256', 'hub_xet_hash', 'size_bytes', 'sequence_position'} | |
| MANIFEST_KEYS = {'schema_version', 'fragment_set_label', 'source_hub_revision', 'predecessor', 'additions', 'members', 'sequence_completeness', 'evidence', 'notes'} | |
| def matches(pattern, value): | |
| return isinstance(value, str) and pattern.fullmatch(value) is not None | |
| def positive_int(value): | |
| return type(value) is int and value > 0 | |
| def read_json(path): | |
| return json.loads(path.read_text(encoding='utf-8-sig')) | |
| def read_csv(path): | |
| with path.open(encoding='utf-8-sig', newline='') as handle: | |
| reader = csv.DictReader(handle) | |
| if not reader.fieldnames: | |
| raise ValueError('CSV header is missing') | |
| return list(reader) | |
| def safe_path(root, value): | |
| if not isinstance(value, str) or not value or '\\' in value: | |
| raise ValueError('invalid repository path') | |
| relative = PurePosixPath(value) | |
| if relative.is_absolute() or any(p in ('..', '.') for p in relative.parts) or ':' in value: | |
| raise ValueError('unsafe repository path') | |
| path = root.joinpath(*relative.parts).resolve() | |
| if not path.is_relative_to(root.resolve()): | |
| raise ValueError('repository path escapes root') | |
| return path | |
| def unique_index(rows, field, errors, label): | |
| result = {} | |
| if not isinstance(rows, list): | |
| errors.append(f'{label}: expected a list') | |
| return result | |
| for row in rows: | |
| if not isinstance(row, dict) or not isinstance(row.get(field), str) or not row[field]: | |
| errors.append(f'{label}: invalid {field}') | |
| continue | |
| value = row[field] | |
| if value in result: | |
| errors.append(f'{label}: duplicate {field}: {value}') | |
| result[value] = row | |
| return result | |
| def validate_insertions(root: Path, metadata: Path, *, inventory=None, | |
| prepublication=False, bind_inventory=True): | |
| """Return errors and validated sequences; never return partial membership. | |
| bind_inventory=False is for the metadata loader's local structural check. | |
| It still requires real remote identities; only prepublication=True permits | |
| a null source revision and null Xet identities for the declared additions. | |
| """ | |
| errors = [] | |
| sequences = [] | |
| level = ('prepublication_unbound' if prepublication else | |
| 'pinned_repository_inventory' if bind_inventory else 'structural_and_metadata_only') | |
| result = {'verification_level': level, 'inventory_binding_checked': False, | |
| 'sequences': sequences, 'errors': errors} | |
| try: | |
| registry = read_json(root / REGISTRY_PATH) | |
| metadata_rows = read_csv(metadata) | |
| by_id = unique_index(metadata_rows, 'record_id', errors, 'metadata') | |
| unique_index(metadata_rows, 'file_name', errors, 'metadata') | |
| if (not isinstance(registry, dict) or set(registry) != {'schema_version', 'sequences'} | |
| or type(registry.get('schema_version')) is not int or registry['schema_version'] != 1 | |
| or not isinstance(registry.get('sequences'), list) or not registry['sequences']): | |
| raise ValueError('registry must contain schema_version 1 and a nonempty sequences list') | |
| if bind_inventory and not prepublication and not isinstance(inventory, dict): | |
| errors.append('strict validation requires an actual pinned repository inventory') | |
| inventory_bundle = None | |
| current_inventory = None | |
| if (bind_inventory and not prepublication and isinstance(inventory, dict) | |
| and ('inventories' in inventory or 'current_inventory' in inventory)): | |
| inventory_bundle = {} | |
| entries = inventory.get('inventories') | |
| current_inventory = inventory.get('current_inventory') | |
| if (set(inventory) != {'current_inventory', 'inventories'} | |
| or not isinstance(entries, list) or not entries): | |
| errors.append('inventory bundle requires current_inventory and a nonempty inventories list') | |
| if (not isinstance(current_inventory, dict) | |
| or not matches(REVISION_RE, current_inventory.get('sha'))): | |
| errors.append('current_inventory requires an immutable revision') | |
| current_inventory = None | |
| if isinstance(entries, list): | |
| for source in entries: | |
| if not isinstance(source, dict) or set(source) != {'inventory', 'metadata_path'}: | |
| errors.append('source entry requires inventory and metadata_path'); continue | |
| receipt, snapshot = source['inventory'], source['metadata_path'] | |
| if not isinstance(receipt, dict) or not matches(REVISION_RE, receipt.get('sha')): | |
| errors.append('source inventory requires an immutable revision'); continue | |
| if not isinstance(snapshot, str) or not Path(snapshot).is_absolute(): | |
| errors.append('source metadata_path must be an explicit absolute local path'); continue | |
| pin = receipt['sha'] | |
| if pin in inventory_bundle: | |
| errors.append('inventory bundle contains duplicate revisions'); continue | |
| inventory_bundle[pin] = (receipt, Path(snapshot)) | |
| seen_labels, seen_paths, registered_ids = set(), set(), set() | |
| for entry in registry['sequences']: | |
| if not isinstance(entry, dict) or set(entry) != {'manifest_path', 'sha256'}: | |
| errors.append('invalid registry entry'); continue | |
| path = safe_path(root, entry['manifest_path']) | |
| if entry['manifest_path'] not in {path for path, _ in SEQUENCE_CONTRACTS}: | |
| errors.append('unregistered insertion manifest path'); continue | |
| if entry['manifest_path'] in seen_paths: | |
| errors.append('duplicate active insertion version'); continue | |
| seen_paths.add(entry['manifest_path']) | |
| raw = path.read_bytes() | |
| if not matches(HASH_RE, entry['sha256']) or hashlib.sha256(raw).hexdigest() != entry['sha256']: | |
| errors.append('registry manifest SHA-256 mismatch'); continue | |
| manifest = json.loads(raw) | |
| if not isinstance(manifest, dict) or set(manifest) != MANIFEST_KEYS: | |
| errors.append('invalid sequence manifest fields'); continue | |
| if type(manifest['schema_version']) is not int or manifest['schema_version'] != 1: | |
| errors.append('invalid sequence schema_version') | |
| label = manifest['fragment_set_label'] | |
| if (entry['manifest_path'], label) not in SEQUENCE_CONTRACTS: | |
| errors.append('unregistered fragment_set_label'); continue | |
| suffixes, finish_date, finish_time = SEQUENCE_CONTRACTS[(entry['manifest_path'], label)] | |
| addition_count = len(suffixes) | |
| if label in seen_labels: | |
| errors.append('duplicate active sequence for fragment_set_label'); continue | |
| seen_labels.add(label) | |
| if manifest['sequence_completeness'] != 'unknown' or manifest['evidence'] != EVIDENCE: | |
| errors.append('insertion evidence/completeness contract differs') | |
| if not isinstance(manifest['notes'], str) or not manifest['notes'].strip(): | |
| errors.append('sequence notes must be nonblank') | |
| revision = manifest['source_hub_revision'] | |
| if not matches(REVISION_RE, revision) and not (prepublication and revision is None): | |
| errors.append('source_hub_revision must be an immutable commit') | |
| expected_predecessor = {'path': PREDECESSOR_PATH, 'sha256': PREDECESSOR_SHA256, | |
| 'source_hub_revision': PREDECESSOR_REVISION} | |
| if manifest['predecessor'] != expected_predecessor: | |
| errors.append('predecessor differs from the immutable registered F receipt' if label == F_LABEL else 'predecessor differs from the immutable registered 9x12 receipt') | |
| predecessor = root / PREDECESSOR_PATH | |
| if hashlib.sha256(predecessor.read_bytes()).hexdigest() != PREDECESSOR_SHA256: | |
| errors.append('historical predecessor bytes changed'); continue | |
| old = [row for row in read_csv(predecessor) if row['object_role'] == 'canonical_fragment' and row['fragment_set_label'] == label] | |
| old.sort(key=lambda row: int(row['sequence_position'])) | |
| old_ids = [row['record_id'] for row in old] | |
| additions = manifest['additions'] | |
| if (not isinstance(additions, list) or len(additions) != addition_count | |
| or not all(matches(RECORD_RE, item) for item in additions) | |
| or len(set(additions)) != addition_count or any(item in old_ids for item in additions)): | |
| errors.append('additions must declare exactly two new unique record IDs' if label == F_LABEL else 'additions must declare exactly one new unique record ID'); continue | |
| members = manifest['members'] | |
| members_by_id = unique_index(members, 'record_id', errors, 'members') | |
| if not isinstance(members, list) or any(not isinstance(m, dict) for m in members): | |
| errors.append('members must be objects'); continue | |
| for field in ('file_path', 'sha256'): | |
| unique_index(members, field, errors, 'members') | |
| bound_xet = [m.get('hub_xet_hash') for m in members if isinstance(m.get('hub_xet_hash'), str)] | |
| if len(bound_xet) != len(set(bound_xet)): | |
| errors.append('members contain duplicate Xet identities') | |
| expected_ids = old_ids[:3] + additions + old_ids[3:] | |
| if [m.get('record_id') for m in members] != expected_ids: | |
| errors.append('members must preserve all nine predecessor objects in order and insert only Rec03a/Rec03b after Rec03' if label == F_LABEL else 'members must preserve all seven predecessor objects in order and insert only Rec03a after Rec03') | |
| for old_member in old: | |
| member = members_by_id.get(old_member['record_id'], {}) | |
| for field in MEMBER_KEYS - {'sequence_position'}: | |
| expected = int(old_member[field]) if field == 'size_bytes' else old_member[field] | |
| if member.get(field) != expected: | |
| errors.append(f"{old_member['record_id']}: predecessor {field} changed or missing") | |
| for record_id, suffix in zip(additions, suffixes): | |
| if members_by_id.get(record_id, {}).get('file_path') != f'Standard_Time_Lapses/{label}.Rec{suffix}.mp4': | |
| errors.append('unregistered insertion suffix or path') | |
| for position, member in enumerate(members, 1): | |
| record_id = member.get('record_id') | |
| if set(member) != MEMBER_KEYS: | |
| errors.append('invalid member field contract') | |
| if not matches(RECORD_RE, record_id): | |
| errors.append('invalid member record_id'); continue | |
| if type(member.get('sequence_position')) is not int or member['sequence_position'] != position: | |
| errors.append(f'{record_id}: sequence_position differs from explicit order') | |
| if not positive_int(member.get('size_bytes')) or not matches(HASH_RE, member.get('sha256')): | |
| errors.append(f'{record_id}: invalid size or SHA-256') | |
| pending = prepublication and record_id in additions and member.get('hub_xet_hash') is None | |
| if not pending and not matches(HASH_RE, member.get('hub_xet_hash')): | |
| errors.append(f'{record_id}: invalid or unbound Xet identity') | |
| row = by_id.get(record_id, {}) | |
| expected_metadata = {'file_name': member.get('file_path'), 'hub_xet_hash': '' if pending else member.get('hub_xet_hash'), | |
| 'size_bytes': str(member.get('size_bytes')), 'date': finish_date, 'time': finish_time, | |
| 'work_id': '', 'acquisition_protocol_version': 'standard-2026-08-27'} | |
| for field, expected in expected_metadata.items(): | |
| if field not in row or row[field] != expected: | |
| errors.append(f'{record_id}: metadata {field} differs from registered sequence') | |
| registered_ids.update(additions) | |
| if bind_inventory and not prepublication and isinstance(inventory, dict): | |
| if inventory_bundle is None: | |
| validate_inventory(inventory, revision, metadata, members, errors) | |
| result['inventory_binding_checked'] = True | |
| else: | |
| source = inventory_bundle.get(revision) | |
| if source is None: | |
| errors.append('inventory bundle missing declared source_hub_revision') | |
| else: | |
| receipt, snapshot = source | |
| validate_inventory(receipt, revision, snapshot, members, errors) | |
| if current_inventory is not None: | |
| validate_inventory(current_inventory, current_inventory['sha'], metadata, members, errors) | |
| if source is not None and current_inventory is not None: | |
| result['inventory_binding_checked'] = True | |
| sequences.append(manifest) | |
| for row in metadata_rows: | |
| if LETTERED_RE.search(row.get('file_name', '')) and row.get('record_id') not in registered_ids: | |
| errors.append(f"{row.get('record_id')}: unregistered lettered Rec suffix") | |
| except (OSError, ValueError, TypeError, KeyError, UnicodeError) as exc: | |
| errors.append(f'unable to validate sequence insertions: {exc}') | |
| if errors: | |
| result['sequences'] = [] | |
| return result | |
| def validate_inventory(inventory, revision, metadata, members, errors): | |
| if inventory.get('sha') != revision: | |
| errors.append('inventory commit differs from source_hub_revision') | |
| files = inventory.get('validationFiles') | |
| receipt = files.get('metadata.csv') if isinstance(files, dict) else None | |
| data = metadata.read_bytes() | |
| if (not isinstance(receipt, dict) or receipt.get('repoCommit') != revision | |
| or receipt.get('sha256') != hashlib.sha256(data).hexdigest() | |
| or type(receipt.get('size')) is not int or receipt['size'] != len(data)): | |
| errors.append('metadata.csv is not bound to exact pinned repository bytes') | |
| siblings = unique_index(inventory.get('siblings'), 'rfilename', errors, 'inventory') | |
| for member in members: | |
| remote = siblings.get(member.get('file_path'), {}) | |
| lfs = remote.get('lfs') | |
| if not isinstance(lfs, dict): | |
| lfs = {} | |
| if (type(remote.get('size')) is not int or remote['size'] != member.get('size_bytes') | |
| or lfs.get('sha256') != member.get('sha256') | |
| or remote.get('xetHash') != member.get('hub_xet_hash') | |
| or remote.get('repoCommit') != revision): | |
| errors.append(f"{member.get('record_id')}: pinned repository media identity differs or is absent") | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--root', type=Path, default=Path('.')) | |
| parser.add_argument('--metadata', type=Path, required=True) | |
| parser.add_argument('--repo-inventory-json', type=Path) | |
| parser.add_argument('--prepublication', action='store_true', help='local-only preparation; never publishable validation') | |
| args = parser.parse_args() | |
| try: | |
| inventory = read_json(args.repo_inventory_json) if args.repo_inventory_json else None | |
| result = validate_insertions(args.root, args.metadata, inventory=inventory, prepublication=args.prepublication) | |
| except (OSError, ValueError, UnicodeError) as exc: | |
| result = {'errors': [f'unable to read inventory: {exc}'], 'sequences': []} | |
| print(json.dumps(result, indent=2)) | |
| raise SystemExit(bool(result['errors'])) | |
| if __name__ == '__main__': | |
| main() | |