SmartDataAlex commited on
Commit
b8e2033
·
verified ·
1 Parent(s): ca58521

Upload 6 files

Browse files
.github/workflows/ci-deploy.yml ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test, backup, deploy and verify
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ concurrency:
12
+ group: vectorization-hf-space
13
+ cancel-in-progress: false
14
+
15
+ jobs:
16
+ unit-tests:
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v4
20
+ - uses: actions/setup-python@v5
21
+ with:
22
+ python-version: '3.11'
23
+ cache: pip
24
+ - name: Install CPU-only dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ python -m pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cpu
28
+ python -m pip install -r requirements-dev.txt
29
+ - name: Test validation and authorization
30
+ run: pytest -q tests/test_app.py --junitxml=unit-results.xml
31
+ - uses: actions/upload-artifact@v4
32
+ if: always()
33
+ with:
34
+ name: unit-test-results
35
+ path: unit-results.xml
36
+ retention-days: 90
37
+
38
+ backup-and-deploy:
39
+ needs: unit-tests
40
+ if: github.ref == 'refs/heads/main' && vars.HF_DEPLOY_ENABLED == 'true'
41
+ runs-on: ubuntu-latest
42
+ timeout-minutes: 70
43
+ env:
44
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
45
+ API_TEST_KEY: ${{ secrets.API_TEST_KEY }}
46
+ SPACE_URL: https://smartdataalex-jupyter.hf.space
47
+ EXPECTED_SHA: ${{ github.sha }}
48
+ steps:
49
+ - uses: actions/checkout@v4
50
+ - uses: actions/setup-python@v5
51
+ with:
52
+ python-version: '3.11'
53
+ - run: python -m pip install 'huggingface-hub==0.30.2' 'httpx==0.28.1'
54
+ - name: Verify deployment credentials exist
55
+ run: |
56
+ test -n "$HF_TOKEN" || { echo 'Missing HF_TOKEN GitHub secret'; exit 1; }
57
+ test -n "$API_TEST_KEY" || { echo 'Missing API_TEST_KEY GitHub secret'; exit 1; }
58
+ - name: Backup existing Space before any modification
59
+ run: python scripts/backup_space.py
60
+ - name: Upload original Space snapshot
61
+ uses: actions/upload-artifact@v4
62
+ with:
63
+ name: space-backup-${{ github.run_id }}
64
+ path: ${{ runner.temp }}/hf-space-backup/
65
+ retention-days: 90
66
+ if-no-files-found: error
67
+ - name: Set release identifier
68
+ run: echo "$GITHUB_SHA" > VERSION
69
+ - name: Deploy backed-up revision to Hugging Face Docker Space
70
+ run: python scripts/deploy_space.py
71
+ - name: Smoke-test actual published API (must match this commit)
72
+ run: python scripts/smoke_live.py
73
+ - name: Upload deployment test results
74
+ if: always()
75
+ uses: actions/upload-artifact@v4
76
+ with:
77
+ name: live-api-results-${{ github.run_id }}
78
+ path: smoke-result.json
79
+ if-no-files-found: ignore
80
+ retention-days: 90
scripts/backup_space.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-closed predeployment backup of the existing Hugging Face Space."""
2
+
3
+ import json
4
+ import os
5
+ import tarfile
6
+ from pathlib import Path
7
+
8
+ from huggingface_hub import HfApi, snapshot_download
9
+
10
+ SPACE = "SmartDataAlex/Jupyter"
11
+ ROOT = Path(os.environ.get("RUNNER_TEMP", "/tmp")) / "hf-space-backup"
12
+ TOKEN = os.environ.get("HF_TOKEN")
13
+ if not TOKEN:
14
+ raise RuntimeError("HF_TOKEN is required to read and back up the existing Space")
15
+
16
+ api = HfApi(token=TOKEN)
17
+ info = api.repo_info(repo_id=SPACE, repo_type="space")
18
+ revision = info.sha
19
+ if not revision:
20
+ raise RuntimeError("Cannot determine the current Space revision; refusing to deploy")
21
+
22
+ ROOT.mkdir(parents=True, exist_ok=True)
23
+ snapshot_path = Path(snapshot_download(
24
+ repo_id=SPACE,
25
+ repo_type="space",
26
+ revision=revision,
27
+ token=TOKEN,
28
+ local_dir=ROOT / "snapshot",
29
+ ))
30
+ files = [p for p in snapshot_path.rglob("*") if p.is_file() and ".cache" not in p.parts]
31
+ if not files:
32
+ raise RuntimeError("Space snapshot is empty; refusing to overwrite it")
33
+ archive = ROOT / f"SmartDataAlex-Jupyter-{revision}.tar.gz"
34
+ with tarfile.open(archive, "w:gz") as output:
35
+ for path in files:
36
+ output.add(path, arcname=path.relative_to(snapshot_path))
37
+ (ROOT / "backup-manifest.json").write_text(json.dumps({
38
+ "space": SPACE, "revision": revision, "files": len(files), "archive": archive.name
39
+ }, indent=2), encoding="utf-8")
40
+ print(f"Space backed up: revision={revision}, files={len(files)}, archive={archive}")
scripts/deploy_space.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Atomically replace Space content only if its predeployment backup is current."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ from huggingface_hub import HfApi
10
+
11
+ SPACE = "SmartDataAlex/Jupyter"
12
+ ROOT = Path(os.environ.get("RUNNER_TEMP", "/tmp")) / "hf-space-backup"
13
+ TOKEN = os.environ.get("HF_TOKEN")
14
+
15
+
16
+ def main() -> None:
17
+ if not TOKEN:
18
+ raise RuntimeError("Missing HF_TOKEN")
19
+ manifest_path = ROOT / "backup-manifest.json"
20
+ if not manifest_path.is_file():
21
+ raise RuntimeError("No completed backup manifest; refusing to deploy")
22
+ backup = json.loads(manifest_path.read_text(encoding="utf-8"))
23
+ revision = backup.get("revision")
24
+ if backup.get("space") != SPACE or not revision:
25
+ raise RuntimeError("Backup is for a different Space or lacks a revision")
26
+ archive = ROOT / backup.get("archive", "")
27
+ if not archive.is_file() or archive.stat().st_size == 0:
28
+ raise RuntimeError("Backup archive missing; refusing to deploy")
29
+
30
+ api = HfApi(token=TOKEN)
31
+ current = api.repo_info(repo_id=SPACE, repo_type="space").sha
32
+ if current != revision:
33
+ raise RuntimeError("Space changed after backup; refusing to overwrite newer content")
34
+
35
+ # Upload_folder handles deletions and additions within the same commit.
36
+ # parent_commit prevents accidentally overwriting a concurrent Space update.
37
+ result = api.upload_folder(
38
+ repo_id=SPACE,
39
+ repo_type="space",
40
+ folder_path=".",
41
+ allow_patterns=[
42
+ "README.md", "Dockerfile", ".dockerignore", "VERSION",
43
+ "requirements.txt", "app/**", "scripts/download_model.py",
44
+ ],
45
+ delete_patterns="*",
46
+ parent_commit=revision,
47
+ commit_message=f"Deploy vectorization service from GitHub {os.environ.get('GITHUB_SHA', 'unknown')}",
48
+ )
49
+ print(f"Deployed {SPACE}: {result.commit_url}")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ main()
scripts/download_model.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache an immutable, minimal E5 model snapshot in the Docker image."""
2
+
3
+ import os
4
+
5
+ from huggingface_hub import snapshot_download
6
+
7
+ snapshot_download(
8
+ repo_id="intfloat/multilingual-e5-small",
9
+ revision="fd1525a9fd15316a2d503bf26ab031a61d056e98",
10
+ local_dir=os.getenv("E5_MODEL_DIR", "/opt/models/multilingual-e5-small"),
11
+ allow_patterns=[
12
+ "config.json",
13
+ "model.safetensors",
14
+ "sentencepiece.bpe.model",
15
+ "special_tokens_map.json",
16
+ "tokenizer.json",
17
+ "tokenizer_config.json",
18
+ ],
19
+ )
scripts/restore_space.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit/manual rollback of a previously backed-up Hugging Face Space.
2
+
3
+ Use only with a trusted backup archive produced by backup_space.py.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import os
10
+ import tarfile
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+ from huggingface_hub import HfApi
15
+
16
+ SPACE = "SmartDataAlex/Jupyter"
17
+
18
+
19
+ def main() -> None:
20
+ parser = argparse.ArgumentParser(description="Restore existing Space files from a backup archive")
21
+ parser.add_argument("archive", type=Path)
22
+ parser.add_argument("--confirm-space", required=True, help=f"Must be exactly {SPACE}")
23
+ args = parser.parse_args()
24
+ if args.confirm_space != SPACE:
25
+ raise SystemExit(f"Refusing to restore: --confirm-space must equal {SPACE}")
26
+ token = os.getenv("HF_TOKEN")
27
+ if not token:
28
+ raise SystemExit("HF_TOKEN environment variable is required")
29
+ if not args.archive.is_file():
30
+ raise SystemExit("Backup archive not found")
31
+
32
+ with tempfile.TemporaryDirectory(prefix="space-rollback-") as temp:
33
+ dest = Path(temp)
34
+ with tarfile.open(args.archive, "r:gz") as backup:
35
+ members = backup.getmembers()
36
+ if not members or len(members) > 10000:
37
+ raise SystemExit("Invalid backup archive")
38
+ for member in members:
39
+ if (not member.isfile() or member.name.startswith("/")
40
+ or ".." in Path(member.name).parts):
41
+ raise SystemExit("Unsafe or unsupported backup entry")
42
+ backup.extractall(path=dest, filter="data")
43
+
44
+ HfApi(token=token).upload_folder(
45
+ repo_id=SPACE,
46
+ repo_type="space",
47
+ folder_path=str(dest),
48
+ delete_patterns="*",
49
+ commit_message=f"Restore Space from backup {args.archive.name}",
50
+ )
51
+ print(f"Restored {SPACE} from {args.archive.name}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
scripts/smoke_live.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the deployed HTTPS service, not local code. Store JSON report for AI review."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ import sys
9
+ import time
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ import httpx
14
+
15
+ SPACE_URL = os.getenv("SPACE_URL", "https://smartdataalex-jupyter.hf.space").rstrip("/")
16
+ KEY = os.environ.get("API_TEST_KEY", "")
17
+ EXPECTED_SHA = os.environ.get("EXPECTED_SHA", "")
18
+ MAX_WAIT_SECONDS = int(os.getenv("LIVE_WAIT_SECONDS", "2400"))
19
+ REPORT = Path(os.getenv("SMOKE_REPORT", "smoke-result.json"))
20
+ TESTS = []
21
+
22
+
23
+ def check(name: str, condition: bool, details: str = "") -> None:
24
+ TESTS.append({"name": name, "passed": bool(condition), "details": details})
25
+ if not condition:
26
+ raise AssertionError(f"{name} failed: {details}")
27
+
28
+
29
+ def cosine(a: list[float], b: list[float]) -> float:
30
+ dot = sum(x * y for x, y in zip(a, b))
31
+ na = math.sqrt(sum(x * x for x in a))
32
+ nb = math.sqrt(sum(y * y for y in b))
33
+ return dot / (na * nb)
34
+
35
+
36
+ def run() -> None:
37
+ if not KEY:
38
+ raise ValueError("API_TEST_KEY is required for real authenticated tests")
39
+ headers = {"X-API-Key": KEY}
40
+ with httpx.Client(timeout=90.0) as client:
41
+ deadline = time.monotonic() + MAX_WAIT_SECONDS
42
+ while time.monotonic() < deadline:
43
+ try:
44
+ health = client.get(f"{SPACE_URL}/health", timeout=20)
45
+ if health.status_code == 200 and health.json().get("status") == "ok":
46
+ version = health.json().get("version", "")
47
+ if not EXPECTED_SHA or version == EXPECTED_SHA:
48
+ break
49
+ except (httpx.HTTPError, ValueError):
50
+ pass
51
+ time.sleep(15)
52
+ else:
53
+ raise TimeoutError("Live service did not reach the expected release version")
54
+ check("public_health", health.status_code == 200)
55
+ check("expected_deployment", not EXPECTED_SHA or health.json().get("version") == EXPECTED_SHA)
56
+
57
+ unauthorized = client.post(f"{SPACE_URL}/embed", json={"text": "hello", "type": "query"})
58
+ check("missing_key_rejected", unauthorized.status_code == 401, str(unauthorized.status_code))
59
+ forbidden = client.post(f"{SPACE_URL}/embed", json={"text": "hello", "type": "query"}, headers={"X-API-Key": "wrong-key"})
60
+ check("wrong_key_rejected", forbidden.status_code == 401, str(forbidden.status_code))
61
+ check("model_metadata_protected", client.get(f"{SPACE_URL}/model").status_code == 401)
62
+
63
+ model_response = client.get(f"{SPACE_URL}/model", headers=headers)
64
+ check("model_metadata_authorized", model_response.status_code == 200)
65
+ info = model_response.json()
66
+ check("model_and_dimensions", info.get("embedding_model") == "intfloat/multilingual-e5-small" and info.get("dimensions") == 384)
67
+ check("no_extra_normalization", info.get("normalization") == "none")
68
+
69
+ def embed(text: str, kind: str = "query") -> dict:
70
+ response = client.post(f"{SPACE_URL}/embed", headers=headers, json={"text": text, "type": kind})
71
+ check(f"embed_{len(TESTS)}", response.status_code == 200, str(response.status_code))
72
+ return response.json()
73
+
74
+ sample = embed("How to find similar documents?")
75
+ sample_again = embed("How to find similar documents?")
76
+ check("response_echo", sample.get("text") == "How to find similar documents?" and sample.get("type") == "query")
77
+ check("token_count", isinstance(sample.get("tokens_count"), int) and sample["tokens_count"] > 0)
78
+ vector = sample["embedding"]
79
+ check("dimension_consistent", len(vector) == sample.get("dimensions") == 384)
80
+ check("vector_numeric", all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in vector))
81
+ check("reproducibility", max(abs(a - b) for a, b in zip(vector, sample_again["embedding"])) < 1e-5)
82
+ check("passage_mode", embed("A short sentence.", "passage")["type"] == "passage")
83
+ check("unicode", embed("Проверка текста на русском языке")["dimensions"] == 384)
84
+
85
+ related = embed("How to search for similar documents?")
86
+ unrelated = embed("The strawberry cake is delicious.")
87
+ related_score = cosine(vector, related["embedding"])
88
+ unrelated_score = cosine(vector, unrelated["embedding"])
89
+ check("semantic_sanity", related_score > unrelated_score, f"related={related_score:.4f} unrelated={unrelated_score:.4f}")
90
+
91
+ for invalid in [{"text": "", "type": "query"}, {"text": "ok", "type": "invalid"}, {"type": "query"}]:
92
+ response = client.post(f"{SPACE_URL}/embed", headers=headers, json=invalid)
93
+ check("invalid_input_rejected", response.status_code == 422, str(response.status_code))
94
+
95
+
96
+ if __name__ == "__main__":
97
+ started = datetime.now(timezone.utc).isoformat()
98
+ error = None
99
+ try:
100
+ run()
101
+ except Exception as exc:
102
+ error = f"{type(exc).__name__}: {exc}"
103
+ report = {
104
+ "started_at": started, "space_url": SPACE_URL, "expected_sha": EXPECTED_SHA or None,
105
+ "passed": error is None, "error": error, "checks": TESTS,
106
+ }
107
+ REPORT.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
108
+ print(json.dumps(report, ensure_ascii=False, indent=2))
109
+ sys.exit(1 if error is not None else 0)