"""Preflight local tokenizer/VAD resources. No runtime downloader is permitted.""" import hashlib import json from pathlib import Path import time REQUIRED_NLTK = ( 'tokenizers/punkt_tab/english/abbrev_types.txt', 'tokenizers/punkt_tab/english/collocations.tab', 'tokenizers/punkt_tab/english/sent_starters.txt', 'tokenizers/punkt_tab/english/ortho_context.tab', 'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json', 'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json', 'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json', ) REQUIRED_VAD = ('hubconf.py', 'src/silero_vad/data/silero_vad.jit') class AssetError(ValueError): pass def validate_assets(nltk_root, vad_root, manifest_path): try: roots = {'nltk': Path(nltk_root).resolve(strict=True), 'vad': Path(vad_root).resolve(strict=True)} manifest_path = Path(manifest_path) if manifest_path.stat().st_size > 1048576: raise ValueError() manifest_bytes = manifest_path.read_bytes() manifest = json.loads(manifest_bytes) if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), dict): raise ValueError() files = manifest['files'] required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD} if manifest['schema'] != 1 or not required <= files.keys() or not 0 < len(files) <= 4096: raise ValueError() found = set() deadline = time.monotonic() + 30 total = 0 for kind, root in roots.items(): for path in root.rglob('*'): if time.monotonic() >= deadline: raise ValueError() if '.git' in path.parts or '__pycache__' in path.parts: continue if path.is_symlink(): raise ValueError() if not path.is_file(): continue name = kind + '/' + path.relative_to(root).as_posix() found.add(name) if len(found) > 4096 or name not in files: raise ValueError() total += path.stat().st_size if total > 536870912: raise ValueError() digest = hashlib.sha256() with path.open('rb') as source: while part := source.read(1048576): if time.monotonic() >= deadline: raise ValueError() digest.update(part) if digest.hexdigest() != files[name]: raise ValueError() if found != set(files): raise ValueError() return hashlib.sha256(manifest_bytes).hexdigest() except (ValueError, OSError, KeyError, TypeError): raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None def forbid_download(*args, **kwargs): raise AssetError('LOCAL_ENGINE_ASSET_DOWNLOAD_FORBIDDEN') def configure_nltk(nltk, root): nltk.data.path[:] = [str(Path(root).resolve())] nltk.download = forbid_download # Also block alternate public download entry points before upstream import. if hasattr(nltk, 'downloader'): nltk.downloader.download = forbid_download nltk.downloader.Downloader.download = forbid_download validate_nltk(nltk) def validate_nltk(nltk): try: nltk.data.find('tokenizers/punkt_tab/english/') nltk.data.find('taggers/averaged_perceptron_tagger_eng/') nltk.sent_tokenize('Local asset verification.') nltk.pos_tag(['verification'], lang='eng') except Exception: raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None def patch_pipeline_source(source): start = source.index('# Ensure that the necessary NLTK resources are available') end = source.index('# caching allows', start) return source[:start] + 'from services.local_s2s.assets import validate_nltk\nvalidate_nltk(nltk)\n\n' + source[end:] def main(): """Fingerprint an already-provisioned local bundle; never fetch resources.""" import argparse parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument('--nltk-root', type=Path, required=True) parser.add_argument('--vad-root', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() try: roots = {'nltk': args.nltk_root.resolve(strict=True), 'vad': args.vad_root.resolve(strict=True)} if args.output.exists() or any(root == args.output.resolve() or root in args.output.resolve().parents for root in roots.values()): raise ValueError() files, total = {}, 0 for kind, root in roots.items(): for path in root.rglob('*'): if '.git' in path.parts or '__pycache__' in path.parts: continue if path.is_symlink(): raise ValueError() if path.is_file(): total += path.stat().st_size if len(files) >= 4096 or total > 536870912: raise ValueError() with path.open('rb') as source: files[kind + '/' + path.relative_to(root).as_posix()] = hashlib.file_digest(source, 'sha256').hexdigest() required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD} if not required <= files.keys(): raise ValueError() with args.output.open('x', encoding='utf-8') as target: json.dump(dict(schema=1, files=files), target, indent=2, sort_keys=True) target.write('\n') digest = validate_assets(roots['nltk'], roots['vad'], args.output) except (ValueError, OSError): parser.exit(1, 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED\n') print(json.dumps(dict(manifest_sha256=digest, files=len(files)))) return 0 if __name__ == '__main__': raise SystemExit(main())