Datasets:
Download code/evaluation-code/ent400-a06a1576/np/catalog_sync.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/np/catalog_sync.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/np/catalog_sync.py
-
curl -L -o catalog_sync.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/np/catalog_sync.py
5.85 kB
| """目录机械字段的同步与漂移检查:catalog.json 里的 link_type、bindings.subject 由核心重算(核心是权威)。 | |
| 只执行本地核心代码(core_lib、catalog_reader),输入一次读入、读时核对未被改动。 | |
| `python3 -B -m np sync-catalog --catalog spec/questions [--check]`;--check 由 make spec-check 跑。 | |
| """ | |
| import hashlib | |
| from pathlib import Path | |
| import sys | |
| import types | |
| import uuid | |
| def sync_catalog(directory, *, check=False): | |
| """Rebuild the catalog's mechanical fields from core declarations.""" | |
| import copy | |
| import json | |
| root, data, _, _ = capture(directory) | |
| core, namespace = authoritative_core(root, data) | |
| try: | |
| catalog = json.loads(data[root / 'catalog.json']) | |
| rows = [row for form in catalog['forms'] for row in form['versions']] | |
| ids = [row['id'] for row in rows] | |
| active = set(core.catalog_reader.active_ids()) | |
| missing, extra = active - core.versions.keys(), core.versions.keys() - active | |
| if len(ids) != len(set(ids)) or missing or extra: | |
| raise ValueError(f'catalog coverage mismatch: duplicates={len(ids) - len(set(ids))}, ' | |
| f'missing core={sorted(missing)}, extra core={sorted(extra)}') | |
| changed, covered = [], set() | |
| for form in catalog['forms']: | |
| for row in form['versions']: | |
| if row['id'] not in active: | |
| continue | |
| covered.add(row['id']) | |
| before = copy.deepcopy(row) | |
| fields = core.catalog_mechanics(core.versions[row['id']]) | |
| link = fields['link_type']['value'] | |
| if link is None: | |
| row.pop('link_type', None) | |
| else: | |
| row['link_type'] = link | |
| if 'subject' in fields: | |
| row.setdefault('bindings', {})['subject'] = fields['subject']['value'] | |
| elif 'bindings' in row: | |
| row['bindings'].pop('subject', None) | |
| if row != before: | |
| changed.append(row['id']) | |
| if check and changed: | |
| raise ValueError('generated catalog fields drifted: ' + ', '.join(changed)) | |
| if changed and not check: | |
| (root / 'catalog.json').write_text(json.dumps(catalog, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| return dict(changed=changed, checked=len(covered)) | |
| finally: | |
| for name in list(sys.modules): | |
| if name == namespace or name.startswith(namespace + '.'): | |
| del sys.modules[name] | |
| def capture(directory): | |
| root = Path(directory).resolve(strict=True) | |
| for name in ('catalog.json', 'methods.json', 'policy.json', 'core/core_lib.py', 'core/catalog_reader.py'): | |
| if not (root / name).is_file(): | |
| raise ValueError('authoritative Core/CatalogReader input missing: ' + name) | |
| paths = [root / 'catalog.json', root / 'methods.json', root / 'policy.json', | |
| root / 'forms_build.py', | |
| *sorted((root / 'forms-src').glob('*.json')), | |
| *sorted((root / 'core').glob('*.py'))] | |
| data, manifest, stamps = {}, {}, {} | |
| for path in paths: | |
| before = path.stat() | |
| value = path.read_bytes() | |
| after = path.stat() | |
| stamp = (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) | |
| if stamp != (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns): | |
| raise ValueError('input changed during capture: ' + str(path)) | |
| data[path] = value | |
| manifest[path.relative_to(root).as_posix()] = dict(bytes=len(value), sha256=hashlib.sha256(value).hexdigest()) | |
| stamps[path] = stamp | |
| return root, data, manifest, stamps | |
| def authoritative_core(root, data): | |
| """Private module namespace, with a memoized *I/O* boundary, no alternate parser. | |
| A local Path subclass lets both authoritative readers reuse captured bytes. | |
| No global pathlib/json patch, and no writes to the supplied core checkout. | |
| """ | |
| namespace = '_np_compile_' + uuid.uuid4().hex | |
| package = types.ModuleType(namespace) | |
| package.__path__ = [str(root / 'core')] | |
| sys.modules[namespace] = package | |
| class InputPath(type(Path())): | |
| def read_text(self, encoding=None, errors=None, **kwargs): | |
| resolved = Path(self).resolve() | |
| if resolved not in data: | |
| raise ValueError('uncaptured core input: ' + str(self)) | |
| return data[resolved].decode(encoding or 'utf-8', errors or 'strict') | |
| # Execute captured bytes so provenance binds the code actually executed. | |
| def module(name, directory='core'): | |
| full = namespace + '.' + name | |
| result = types.ModuleType(full) | |
| result.__file__ = str(root / directory / (name + '.py')) | |
| result.__package__ = namespace | |
| sys.modules[full] = result | |
| exec(compile(data[Path(result.__file__)], result.__file__, 'exec'), result.__dict__) | |
| result.Path = InputPath | |
| return result | |
| old = sys.dont_write_bytecode | |
| try: | |
| sys.dont_write_bytecode = True | |
| forms = module('forms_build', '') | |
| module('catalog_reader') | |
| lib = module('core_lib') | |
| lib.load_forms = forms.load | |
| lib.dump_form = forms.dump | |
| # query_context is imported lazily by Core; preload its captured version. | |
| if root / 'core/query_context.py' in data: | |
| module('query_context') | |
| core = lib.Core(master=root / 'methods.json', catalog=root / 'catalog.json', locale='en') | |
| except BaseException: | |
| for name in list(sys.modules): | |
| if name == namespace or name.startswith(namespace + '.'): | |
| del sys.modules[name] | |
| raise | |
| finally: | |
| sys.dont_write_bytecode = old | |
| return core, namespace | |