Spaces:
Sleeping
Sleeping
Download src/decision_model/deployment.py from xstard/decision-model: direct link, hf CLI and curl.
- Browser
- Download file 5.88 kB
-
https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/deployment.py
- Command line
-
hf download hf://spaces/xstard/decision-model/src/decision_model/deployment.py
-
curl -L -o deployment.py https://huggingface.co/spaces/xstard/decision-model/resolve/main/src/decision_model/deployment.py
5.88 kB
| import json | |
| from pathlib import Path | |
| import zipfile | |
| from .artifacts import verify_bundle, sha256 | |
| from .settings import ROOT | |
| STATIC = ["README.md", "LICENSE", "app.py", "Dockerfile", ".dockerignore", ".gitignore", ".env.example", | |
| "pyproject.toml", "requirements.txt", "requirements-dev.txt"] | |
| PATTERNS = ["src/**/*.py", "tests/*.py", "docs/*.md", "scripts/*.py", "data/examples/*.jsonl", "configs/*.json"] | |
| def source_files(root=ROOT): | |
| root = Path(root).resolve() | |
| if any(not (root / name).is_file() for name in STATIC): | |
| raise ValueError("Пакет вихідного коду неповний.") | |
| files = [root / name for name in STATIC] | |
| for pattern in PATTERNS: | |
| files.extend(root.glob(pattern)) | |
| # The execution ledger contains local account/preflight state, not public source. | |
| files = [file for file in files if file.name.casefold() != 'progress.md'] | |
| for file in files: | |
| if not file.resolve().is_relative_to(root): | |
| raise ValueError("Публічний пакет не може містити посилання на файли поза проєктом.") | |
| return sorted({file.relative_to(root).as_posix() for file in files}) | |
| def package_source(root=ROOT): | |
| root = Path(root) | |
| files = source_files(root) | |
| directory = root / "dist" | |
| directory.mkdir(exist_ok=True) | |
| archive = directory / "decision-model-source.zip" | |
| with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as stream: | |
| for name in files: | |
| stream.write(root / name, arcname=name) | |
| return archive | |
| def validate_target(repo_id, owner): | |
| if repo_id != "xstard/decision-model" or owner != "xstard": | |
| raise ValueError("Публікація дозволена лише для xstard/decision-model з акаунта xstard.") | |
| def check_publishable(manifest, result, allow_experimental=False): | |
| if manifest.get('diagnostic_only') or manifest.get('head_layout','shared')!='shared': | |
| raise ValueError('Діагностичні окремі голови не є фінальною спільною головою підходу №4.') | |
| if manifest.get('model_version')=='decision-1.1.0' and result.get('improvement_verified') is not True: | |
| raise ValueError('Для оновлення v1.1 потрібне виміряне покращення обох задач на тому самому новому test: comparison.') | |
| if manifest.get('stage') != 'evaluated' or result.get('stage') != 'evaluated': | |
| raise ValueError('Перед публікацією потрібні завершене калібрування й оцінювання.') | |
| required = {'calibration_min_groups', 'test_min_groups', 'calibration_review', 'test_review', | |
| 'train_stratified_review', 'split_disjointness', 'demo_class_coverage'} | |
| checks = result.get('release_checks', {}) | |
| if result.get('evidence_complete') is not True or not required.issubset(checks) or any(checks[k] is not True for k in required): | |
| raise ValueError('Немає повних перевірених доказів: потрібні аудит, ≥100 cal/test груп і відсутність витоку. --allow-experimental цього не обходить.') | |
| if result.get('experimental', True) and not allow_experimental: | |
| raise ValueError('Пропущені цілі якості потребують явного --allow-experimental.') | |
| def deploy(repo_id, artifact_dir, allow_experimental=False): | |
| from huggingface_hub import HfApi | |
| artifact_dir = Path(artifact_dir) | |
| manifest = verify_bundle(artifact_dir) | |
| result = json.loads((artifact_dir / "metrics.json").read_text(encoding="utf-8")) | |
| check_publishable(manifest, result, allow_experimental) | |
| files = source_files() | |
| api = HfApi() | |
| identity = api.whoami() | |
| validate_target(repo_id, identity["name"]) | |
| if not identity.get("isPro"): | |
| raise ValueError("Не підтверджено право створювати Docker Space; платний план автоматично не купується.") | |
| api.create_repo(repo_id, repo_type="model", private=False, exist_ok=True) | |
| model_files = ["manifest.json", "head.safetensors", "calibration.json", "metrics.json", "README.md"] | |
| if manifest.get('encoder_delta'): | |
| model_files.append('encoder_delta.safetensors') | |
| if (artifact_dir / "reliability.png").exists(): | |
| model_files.append("reliability.png") | |
| commit = api.upload_folder(repo_id=repo_id, repo_type="model", folder_path=str(artifact_dir), | |
| allow_patterns=model_files, commit_message="Publish evaluated approach-4 decision model") | |
| revision = commit.oid | |
| api.create_repo(repo_id, repo_type="space", space_sdk="docker", private=False, exist_ok=True) | |
| runtime = api.get_space_runtime(repo_id) | |
| hardware = runtime.raw.get("hardware", {}).get("requested") | |
| if hardware not in {None, "cpu-basic"}: | |
| raise ValueError("Space має інше обладнання; платний ресурс автоматично не використовується.") | |
| api.add_space_variable(repo_id, "MODEL_REPO_ID", repo_id) | |
| api.add_space_variable(repo_id, "MODEL_REVISION", revision) | |
| api.upload_folder(repo_id=repo_id, repo_type="space", folder_path=str(ROOT), allow_patterns=files, | |
| commit_message="Implement encoder-only bilingual decision API and demo") | |
| report = {"space": f"https://huggingface.co/spaces/{repo_id}", "app": "https://xstard-decision-model.hf.space", | |
| "model": f"https://huggingface.co/{repo_id}", "model_revision": revision, | |
| "manifest_sha256": sha256(artifact_dir / "manifest.json"), "status": "uploaded; runtime verification pending"} | |
| (ROOT / "artifacts" / "deployment.json").write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| return report | |