"""Enroll and replay private tuner profiles using a verified Mini download. Run as a fresh process. Model assets and profiles are written outside the download; enrollment reference audio is never saved in playback state. """ import sys sys.dont_write_bytecode = True import argparse import hashlib import importlib.util import json import os from pathlib import Path import re import subprocess STATE_SCHEMA = 'inflect-tuner-work-v1' PROFILE_SCHEMA = 'inflect-tuner-profile-pointer-v1' def digest(path): with Path(path).open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest() def verify_package(root): verifier = root / 'verify_release.py' if verifier.is_symlink() or not verifier.is_file(): raise ValueError('Missing package verifier') spec = importlib.util.spec_from_file_location('_inflect_public_verify', verifier) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) module.verify(root) data = json.loads((root / 'release-manifest.json').read_text(encoding='utf-8')) components = data.get('components') if not isinstance(components, list): raise ValueError('Missing package component inventory') expected = {'core': 'assembly-manifest.json', 'extras/tuner': 'candidate-manifest.json'} pins = {} for destination, name in expected.items(): rows = [row for row in components if isinstance(row, dict) and row.get('destination') == destination] if len(rows) != 1 or rows[0].get('manifest') != name: raise ValueError('Missing or duplicate component: ' + destination) value = rows[0].get('sha256') file_name = destination + '/' + name entry = data.get('files', {}).get(file_name, {}) if not isinstance(value, str) or not re.fullmatch('[0-9a-f]{64}', value) or entry.get('sha256') != value: raise ValueError('Component pin does not match release inventory') if digest(root / file_name) != value: raise ValueError('Component manifest hash mismatch') pins[destination] = value return pins def external(path, root, *, existing=False): path = Path(path).expanduser().absolute() if path.is_symlink() or path.resolve().is_relative_to(root): raise ValueError('Paths must be outside the downloaded package and not symlinks') if existing and not path.is_file(): raise ValueError('Expected an existing regular file: ' + str(path)) return path def invoke(root, script, arguments, *, offline=True): env = os.environ.copy() for name in ('PYTHONPATH', 'PYTHONHOME', 'PYTHONUSERBASE'): env.pop(name, None) env.update(PYTHONDONTWRITEBYTECODE='1', PYTHONNOUSERSITE='1', HF_HUB_DISABLE_TELEMETRY='1') if offline: env.update(HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1') result = subprocess.run([sys.executable, '-B', str(script), *map(str, arguments)], cwd=root, env=env, capture_output=True, text=True) if result.returncode: raise RuntimeError('Tuner step failed: ' + (result.stderr.strip()[-4000:] or result.stdout.strip()[-4000:])) try: value = json.loads(result.stdout.strip().splitlines()[-1]) except (ValueError, IndexError) as error: raise ValueError('Tuner step did not return JSON') from error if not isinstance(value, dict): raise ValueError('Tuner step returned invalid JSON') return value def new_json(path, value): with path.open('x', encoding='utf-8') as stream: json.dump(value, stream, indent=2, sort_keys=True, allow_nan=False) stream.write('\n') def verify_playback_origin(root, playback, state, pins): if playback.is_symlink() or not playback.is_dir(): raise ValueError('Playback assets must be a regular directory') sdk = json.loads((root / 'extras/tuner/candidate-manifest.json').read_text(encoding='utf-8')) profiles = sdk.get('core_profiles', {}) core_files = profiles.get(pins['core']) if not isinstance(core_files, dict): raise ValueError('Core is not a pinned tuner profile') expected = {'mini/' + name: entry['sha256'] for name, entry in core_files.items()} notice = 'playback/notices/' if state['device'] == 'cpu' else 'playback-cuda/notices/' for name, entry in sdk['files'].items(): if name.startswith(('playback/runtime/', notice)): expected[name.split('/', 1)[1]] = entry['sha256'] manifest_path = playback / 'manifest.json' if manifest_path.is_symlink() or not manifest_path.is_file() or digest(manifest_path) != state['playback_manifest_sha256']: raise ValueError('Playback manifest identity mismatch') manifest = json.loads(manifest_path.read_text(encoding='utf-8')) if (manifest.get('schema') != 'inflect-tuner-model-only-v2' or manifest.get('files') != expected or manifest.get('mini_sha256') != core_files['baseline/models/mini/weights.pt']['sha256']): raise ValueError('Playback manifest does not match verified package') for name in ('tuner_model_playback_20261110.py', 'tuner_model_manifest_20261110.py', 'tuner_audio_guard_20261110.py'): path = playback / 'runtime' / name if path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(playback.resolve()) or digest(path) != expected['runtime/' + name]: raise ValueError('Playback runtime does not match verified SDK') def enroll(root, pins, args): if not args.consent_confirmed: raise ValueError('Explicit consent confirmation is required') if args.download_public_assets: if not args.accept_third_party_licenses or args.inno_weights or args.ecapa_weights: raise ValueError('Downloads require license acknowledgement and no local checkpoint arguments') elif not (args.inno_weights and args.ecapa_weights): raise ValueError('Provide both local checkpoints or explicitly enable downloads') reference = external(args.reference, root, existing=True) descriptor = external(args.profile, root) work = external(args.work_dir, root) binary = descriptor.with_name(descriptor.name + '.pt') if work.exists() or descriptor.exists() or descriptor.is_symlink() or binary.exists() or binary.is_symlink(): raise ValueError('Work directory and profile outputs must be new') if not work.parent.is_dir() or not descriptor.parent.is_dir(): raise ValueError('Work and profile parent directories must exist') work.mkdir() sdk, core = root / 'extras/tuner', root / 'core' assets, playback = work / 'enrollment-assets', work / 'playback-assets' assembly = ['--candidate', sdk, '--candidate-manifest-sha256', pins['extras/tuner'], '--core-root', core, '--output', assets, '--device', args.device] if args.download_public_assets: assembly += ['--download-public-assets', '--accept-third-party-licenses'] else: assembly += ['--inno-weights', external(args.inno_weights, root, existing=True), '--ecapa-weights', external(args.ecapa_weights, root, existing=True)] staged = invoke(root, sdk / 'tuner_enrollment_assembly_20261110.py', assembly, offline=not args.download_public_assets) trained = invoke(root, sdk / 'enrollment-source/sdk/tuner_portable_20261110.py', ['enroll', '--asset-root', assets, '--manifest-sha256', staged['asset_manifest_sha256'], '--device', args.device, '--reference', reference, '--output', binary, '--enrollment-id', args.enrollment_id, '--consent-confirmed']) if digest(binary) != trained.get('profile_sha256'): raise ValueError('Profile hash mismatch') ready = invoke(root, sdk / 'tuner_playback_init_20261110.py', ['--sdk', sdk, '--sdk-manifest-sha256', pins['extras/tuner'], '--core-root', core, '--output', playback, '--device', args.device]) new_json(work / 'tuner-state.json', dict(schema=STATE_SCHEMA, sdk_sha256=pins['extras/tuner'], core_sha256=pins['core'], playback_manifest_sha256=ready['model_manifest_sha256'], device=args.device)) new_json(descriptor, dict(schema=PROFILE_SCHEMA, file=binary.name, sha256=trained['profile_sha256'])) print(json.dumps(dict(status='enrolled', profile=str(descriptor), profile_data=str(binary), profile_sha256=trained['profile_sha256'], work_dir=str(work), rejected_candidates=trained.get('rejected_candidates', []), quality_approved=False), allow_nan=False)) def say(root, pins, args): descriptor = external(args.profile, root, existing=True) work = external(args.work_dir, root) output = external(args.output, root) if work.is_symlink() or not work.is_dir() or output.exists() or output.is_symlink() or not output.parent.is_dir(): raise ValueError('Existing work directory and new output path are required') if output.resolve().is_relative_to(work.resolve()): raise ValueError('Output must be outside the verified work directory') state_file = work / 'tuner-state.json' if state_file.is_symlink() or not state_file.is_file() or state_file.stat().st_size > 16384: raise ValueError('Missing or invalid tuner state') state = json.loads(state_file.read_text(encoding='utf-8')) if not isinstance(state, dict) or set(state) != {'schema','sdk_sha256','core_sha256','playback_manifest_sha256','device'} or state['schema'] != STATE_SCHEMA or state['sdk_sha256'] != pins['extras/tuner'] or state['core_sha256'] != pins['core'] or state['device'] != args.device: raise ValueError('Tuner state does not match package and device') if descriptor.stat().st_size > 16384: raise ValueError('Profile descriptor too large') info = json.loads(descriptor.read_text(encoding='utf-8')) if not isinstance(info, dict) or set(info) != {'schema','file','sha256'} or info['schema'] != PROFILE_SCHEMA or info['file'] != descriptor.name + '.pt' or not isinstance(info['sha256'], str) or not re.fullmatch('[0-9a-f]{64}', info['sha256']): raise ValueError('Invalid profile descriptor') binary = external(descriptor.parent / info['file'], root, existing=True) if digest(binary) != info['sha256'] or not args.text.strip(): raise ValueError('Profile hash mismatch or empty text') playback = work / 'playback-assets' verify_playback_origin(root, playback, state, pins) result = invoke(root, playback / 'runtime/tuner_model_playback_20261110.py', ['synthesize', '--model-root', playback, '--manifest-sha256', state['playback_manifest_sha256'], '--profile', binary, '--profile-sha256', info['sha256'], '--text', args.text, '--output', output, '--device', args.device, '--deny-read', work / 'enrollment-assets']) if digest(output) != result.get('output_sha256') or not result.get('raw_audio_validated'): raise ValueError('Output identity or audio validation failure') print(json.dumps(dict(status='complete', output=str(output), output_sha256=result['output_sha256'], profile=result['profile'], quality_approved=False), allow_nan=False)) def main(argv=None, *, root=None): p = argparse.ArgumentParser(description=__doc__) sub = p.add_subparsers(dest='mode', required=True) add = sub.add_parser('enroll') for name in ('reference','profile','work-dir'): add.add_argument('--' + name, required=True) add.add_argument('--enrollment-id', default='user-reference') add.add_argument('--consent-confirmed', action='store_true') add.add_argument('--download-public-assets', action='store_true') add.add_argument('--accept-third-party-licenses', action='store_true') add.add_argument('--inno-weights') add.add_argument('--ecapa-weights') speak = sub.add_parser('say') for name in ('profile','work-dir','text','output'): speak.add_argument('--' + name, required=True) for parser in (add, speak): parser.add_argument('--device', choices=('cpu','cuda'), default='cpu') args = p.parse_args(argv) root = (Path(root) if root is not None else Path(__file__).resolve().parent).resolve(strict=True) pins = verify_package(root) if args.mode == 'enroll': enroll(root, pins, args) else: say(root, pins, args) if __name__ == '__main__': main()