open-privacy-protocol-engine 0.2.0a1__tar.gz → 0.2.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/.github/workflows/ci.yml +2 -0
  2. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/PKG-INFO +5 -11
  3. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/README.md +1 -1
  4. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/docs/data-sources.md +1 -1
  5. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/docs/detectors.md +24 -3
  6. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/pyproject.toml +6 -1
  7. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/__init__.py +1 -1
  8. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/cli.py +40 -7
  9. open_privacy_protocol_engine-0.2.0a2/src/opp_engine/model_hub.py +165 -0
  10. open_privacy_protocol_engine-0.2.0a2/tests/test_model_hub.py +72 -0
  11. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/.github/workflows/release.yml +0 -0
  12. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/.gitignore +0 -0
  13. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/CODE_OF_CONDUCT.md +0 -0
  14. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/CONTRIBUTING.md +0 -0
  15. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/Dockerfile +0 -0
  16. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/LICENSE +0 -0
  17. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/NOTICE +0 -0
  18. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/SECURITY.md +0 -0
  19. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/assets/brand/icon-512.png +0 -0
  20. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/assets/brand/logo-transparent-dark.png +0 -0
  21. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/assets/brand/logo-transparent-white.png +0 -0
  22. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/docs/agents.md +0 -0
  23. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/connectors.py +0 -0
  24. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/data/hygiene_lists.json +0 -0
  25. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/detect.py +0 -0
  26. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/engine.py +0 -0
  27. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/generate.py +0 -0
  28. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/hygiene.py +0 -0
  29. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/mcp_server.py +0 -0
  30. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/model_detector.py +0 -0
  31. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/nosql.py +0 -0
  32. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/report.py +0 -0
  33. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/src/opp_engine/server.py +0 -0
  34. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/fixtures/conformance.destinations.yaml +0 -0
  35. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/fixtures/conformance.opp.yaml +0 -0
  36. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/fixtures/northwind-coaching.opp.yaml +0 -0
  37. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/fixtures/northwind.destinations.yaml +0 -0
  38. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/sample_data.py +0 -0
  39. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/test_custom.py +0 -0
  40. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/test_decision.py +0 -0
  41. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/test_kit.py +0 -0
  42. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/test_model_and_hygiene.py +0 -0
  43. {open_privacy_protocol_engine-0.2.0a1 → open_privacy_protocol_engine-0.2.0a2}/tests/test_nosql.py +0 -0
@@ -23,3 +23,5 @@ jobs:
23
23
  - run: pip install "open-privacy-protocol @ git+https://github.com/kannancet/opp-python@main"
24
24
  - run: pip install -e ".[test]"
25
25
  - run: pytest -q
26
+ env:
27
+ OPP_MODEL: "off" # tests use a stub model; model_hub is tested against a local server
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: open-privacy-protocol-engine
3
- Version: 0.2.0a1
3
+ Version: 0.2.0a2
4
4
  Summary: OPP Engine, the reference engine of the privacy context layer for AI: generate Open Privacy Protocol privacy models from any data source and answer agents' checks with decisions over HTTP and MCP
5
5
  Project-URL: Homepage, https://openprivacyprotocol.com/engine/
6
6
  Project-URL: Documentation, https://openprivacyprotocol.com/engine/data-sources/
@@ -15,19 +15,19 @@ Classifier: Intended Audience :: Developers
15
15
  Classifier: Programming Language :: Python :: 3
16
16
  Classifier: Topic :: Security
17
17
  Requires-Python: >=3.10
18
+ Requires-Dist: numpy>=1.26
19
+ Requires-Dist: onnxruntime>=1.18
18
20
  Requires-Dist: open-privacy-protocol>=0.2.0a1
19
21
  Requires-Dist: pyyaml>=6.0
20
22
  Requires-Dist: sqlalchemy>=2.0
23
+ Requires-Dist: tokenizers>=0.19
21
24
  Provides-Extra: all
22
25
  Requires-Dist: fastapi>=0.110; extra == 'all'
23
26
  Requires-Dist: mcp<3,>=1.2; extra == 'all'
24
- Requires-Dist: numpy>=1.26; extra == 'all'
25
- Requires-Dist: onnxruntime>=1.18; extra == 'all'
26
27
  Requires-Dist: pyarrow>=15; extra == 'all'
27
28
  Requires-Dist: pymongo>=4.6; extra == 'all'
28
29
  Requires-Dist: pypdf>=4; extra == 'all'
29
30
  Requires-Dist: python-docx>=1.1; extra == 'all'
30
- Requires-Dist: tokenizers>=0.19; extra == 'all'
31
31
  Requires-Dist: uvicorn>=0.29; extra == 'all'
32
32
  Provides-Extra: documents
33
33
  Requires-Dist: pypdf>=4; extra == 'documents'
@@ -35,9 +35,6 @@ Requires-Dist: python-docx>=1.1; extra == 'documents'
35
35
  Provides-Extra: mcp
36
36
  Requires-Dist: mcp<3,>=1.2; extra == 'mcp'
37
37
  Provides-Extra: model
38
- Requires-Dist: numpy>=1.26; extra == 'model'
39
- Requires-Dist: onnxruntime>=1.18; extra == 'model'
40
- Requires-Dist: tokenizers>=0.19; extra == 'model'
41
38
  Provides-Extra: mongodb
42
39
  Requires-Dist: pymongo>=4.6; extra == 'mongodb'
43
40
  Provides-Extra: mysql
@@ -53,13 +50,10 @@ Provides-Extra: test
53
50
  Requires-Dist: fastapi>=0.110; extra == 'test'
54
51
  Requires-Dist: httpx>=0.27; extra == 'test'
55
52
  Requires-Dist: mcp<3,>=1.2; extra == 'test'
56
- Requires-Dist: numpy>=1.26; extra == 'test'
57
- Requires-Dist: onnxruntime>=1.18; extra == 'test'
58
53
  Requires-Dist: pymongo>=4.6; extra == 'test'
59
54
  Requires-Dist: pypdf>=4; extra == 'test'
60
55
  Requires-Dist: pytest>=8; extra == 'test'
61
56
  Requires-Dist: python-docx>=1.1; extra == 'test'
62
- Requires-Dist: tokenizers>=0.19; extra == 'test'
63
57
  Requires-Dist: uvicorn>=0.29; extra == 'test'
64
58
  Description-Content-Type: text/markdown
65
59
 
@@ -139,7 +133,7 @@ New to the ideas? Read [Core concepts](https://openprivacyprotocol.com/get-start
139
133
  |---|---|
140
134
  | **Connect anything** | Any SQLAlchemy database URL (PostgreSQL, MySQL, SQL Server, Oracle, SQLite, Snowflake, BigQuery and more with their drivers); MongoDB and MongoDB Atlas (`mongodb://`, `mongodb+srv://`, with the `[mongodb]` extra), nested fields included; CSV, TSV, JSON, JSON Lines and Parquet files; text, Markdown, HTML, PDF and Word documents; folders and web pages |
141
135
  | **Generate** | Every column is classified against the OPP baseline catalog from its name and sampled values; text columns and documents get topic classes (health data, HR matters, internal financials); ID columns get their format (`CE-[0-9]{6}`). Each entry carries its evidence and starts `proposed` |
142
- | **Better with OPP Model** | With the open-weight [OPP Model](https://github.com/kannancet/open-privacy-protocol-model) (`--opp-model`), names, addresses and confidential topics are found in free text and headerless columns, and the organization's own concepts match by meaning |
136
+ | **Better with OPP Model** | With the open-weight [OPP Model](https://github.com/kannancet/open-privacy-protocol-model) (downloaded from Hugging Face on first use and applied automatically by `generate`), names, addresses and confidential topics are found in free text and headerless columns, and the organization's own concepts match by meaning |
143
137
  | **Industry presets** | `--industry 622110` (a NAICS code) or `--industry healthcare` lists the classes that industry usually holds and were not found |
144
138
  | **Hygiene** | Cues, terms and identifier patterns that would match ordinary text are removed and reported |
145
139
  | **Human review** | A Markdown report lists what to check; certified entries survive the next run (`--merge`) |
@@ -74,7 +74,7 @@ New to the ideas? Read [Core concepts](https://openprivacyprotocol.com/get-start
74
74
  |---|---|
75
75
  | **Connect anything** | Any SQLAlchemy database URL (PostgreSQL, MySQL, SQL Server, Oracle, SQLite, Snowflake, BigQuery and more with their drivers); MongoDB and MongoDB Atlas (`mongodb://`, `mongodb+srv://`, with the `[mongodb]` extra), nested fields included; CSV, TSV, JSON, JSON Lines and Parquet files; text, Markdown, HTML, PDF and Word documents; folders and web pages |
76
76
  | **Generate** | Every column is classified against the OPP baseline catalog from its name and sampled values; text columns and documents get topic classes (health data, HR matters, internal financials); ID columns get their format (`CE-[0-9]{6}`). Each entry carries its evidence and starts `proposed` |
77
- | **Better with OPP Model** | With the open-weight [OPP Model](https://github.com/kannancet/open-privacy-protocol-model) (`--opp-model`), names, addresses and confidential topics are found in free text and headerless columns, and the organization's own concepts match by meaning |
77
+ | **Better with OPP Model** | With the open-weight [OPP Model](https://github.com/kannancet/open-privacy-protocol-model) (downloaded from Hugging Face on first use and applied automatically by `generate`), names, addresses and confidential topics are found in free text and headerless columns, and the organization's own concepts match by meaning |
78
78
  | **Industry presets** | `--industry 622110` (a NAICS code) or `--industry healthcare` lists the classes that industry usually holds and were not found |
79
79
  | **Hygiene** | Cues, terms and identifier patterns that would match ordinary text are removed and reported |
80
80
  | **Human review** | A Markdown report lists what to check; certified entries survive the next run (`--merge`) |
@@ -122,7 +122,7 @@ The page is fetched once and read as a document.
122
122
  - Re-run with `--merge acme.opp.yaml` to keep entries people already **certified** and add only new findings.
123
123
  - Add `--industry <NAICS code>` so the review report lists classes your industry usually holds that were not
124
124
  found.
125
- - Add `--opp-model ./opp-model-v1` to find names, addresses and topics in free-text columns too.
125
+ - OPP Model finds names, addresses and topics in free-text columns too; `generate` downloads and uses it automatically (`--no-opp-model` turns it off).
126
126
 
127
127
  ## Troubleshooting
128
128
 
@@ -37,8 +37,29 @@ release folder (`model.onnx`, `tokenizer.json`, `labels.json`) gives three thing
37
37
  - **Meaning match:** a text vector that matches an organization's own concepts by their
38
38
  description. Used only when the release's `labels.json` marks `text_vec` as `ready`.
39
39
 
40
+ Releases are published on Hugging Face as [`tiny-bubble-company/opp-model`](https://huggingface.co/tiny-bubble-company/opp-model),
41
+ one tag per version. `pip install open-privacy-protocol-engine` installs the model runtime (ONNX Runtime,
42
+ tokenizers, NumPy); the model itself is downloaded on first use, because pip cannot run code at install
43
+ time. `opp-engine generate` then uses it automatically:
44
+
40
45
  ```bash
41
- pip install "open-privacy-protocol-engine[model]"
42
- opp-engine generate postgresql://reader@db/crm --name acme --org Acme --opp-model ./opp-model-v1
43
- opp-engine serve acme.opp.yaml --mcp --opp-model ./opp-model-v1 # or OPP_MODEL=...
46
+ pip install "open-privacy-protocol-engine[postgres]"
47
+ opp-engine generate postgresql://reader@db/crm --name acme --org Acme # downloads OPP Model once, then uses it
48
+ opp-engine model pull # or download it ahead of time (container images, offline machines)
49
+ opp-engine model info # version, cache folder and the release's acceptance results
44
50
  ```
51
+
52
+ - **Version:** each engine release pins a model release and ships its SHA-256 digests, so a file
53
+ changed on the Hub is refused. `OPP_MODEL_REVISION=v2` (or `opp-engine model pull --revision v2`)
54
+ uses another release, checked against that release's own `SHA256SUMS`.
55
+ - **Cache:** `$OPP_MODEL_HOME`, else `$XDG_CACHE_HOME/opp-engine/models`, else `~/.cache/opp-engine/models`.
56
+ After the first download the engine works offline.
57
+ - **Off or elsewhere:** `--no-opp-model` or `OPP_MODEL=off` runs on rules only; `--opp-model ./folder`
58
+ (or `OPP_MODEL=./folder`) uses a release folder you manage. `HF_ENDPOINT` points at a mirror.
59
+ - **Offline first run:** if the model cannot be downloaded, `generate` says so and continues with the
60
+ rule detectors.
61
+ - **`check`, `explain` and `serve`** use the model only when asked (`--opp-model auto`, a folder, or
62
+ `OPP_MODEL`), so a decision point never changes behaviour because a download happened.
63
+
64
+ Every class the model finds is written as `proposed`, like every other finding, so a person reviews it
65
+ before it is certified.
@@ -22,6 +22,10 @@ dependencies = [
22
22
  "open-privacy-protocol>=0.2.0a1",
23
23
  "pyyaml>=6.0",
24
24
  "sqlalchemy>=2.0",
25
+ # OPP Model runtime: the model itself comes from Hugging Face on first use (opp-engine model pull).
26
+ "onnxruntime>=1.18",
27
+ "tokenizers>=0.19",
28
+ "numpy>=1.26",
25
29
  ]
26
30
 
27
31
  [project.optional-dependencies]
@@ -29,7 +33,8 @@ server = ["fastapi>=0.110", "uvicorn>=0.29"]
29
33
  mcp = ["mcp>=1.2,<3"]
30
34
  documents = ["pypdf>=4", "python-docx>=1.1"]
31
35
  parquet = ["pyarrow>=15"]
32
- model = ["onnxruntime>=1.18", "tokenizers>=0.19", "numpy>=1.26"]
36
+ # Kept for old install lines: the model runtime is now a core dependency.
37
+ model = []
33
38
  postgres = ["psycopg[binary]>=3.1"]
34
39
  mongodb = ["pymongo>=4.6"]
35
40
  mysql = ["pymysql>=1.1"]
@@ -1,2 +1,2 @@
1
1
  """opp-engine: generate OPP privacy models from any source and serve them to agents."""
2
- __version__ = "0.2.0a1"
2
+ __version__ = "0.2.0a2"
@@ -26,14 +26,27 @@ def _load(p):
26
26
  return opp.Model(p)
27
27
 
28
28
 
29
- def _detectors(a):
30
- """Rules, plus OPP Model when --opp-model or OPP_MODEL points at a release folder."""
29
+ def _detectors(a, auto=False):
30
+ """Rules, plus OPP Model.
31
+
32
+ `generate` uses the model by default (auto): the pinned release from Hugging Face, downloaded
33
+ on first use. Other commands use it when --opp-model or OPP_MODEL asks for it ("auto" for the
34
+ Hugging Face release, or a release folder). --no-opp-model or OPP_MODEL=off turns it off.
35
+ """
31
36
  from .detect import RuleDetector
32
- path = getattr(a, "opp_model", None) or os.environ.get("OPP_MODEL")
37
+ from .model_hub import resolve
38
+ if getattr(a, "no_opp_model", False):
39
+ return [RuleDetector()]
40
+ path = resolve(getattr(a, "opp_model", None), auto=auto)
33
41
  if not path:
34
42
  return [RuleDetector()]
35
- from .model_detector import OppModelDetector
36
- return [RuleDetector(), OppModelDetector(path)]
43
+ try:
44
+ from .model_detector import OppModelDetector
45
+ det = OppModelDetector(path)
46
+ except ImportError as e:
47
+ raise SystemExit(f"OPP Model needs onnxruntime, tokenizers and numpy ({e}); reinstall open-privacy-protocol-engine")
48
+ print(f"using OPP Model ({path})", file=sys.stderr)
49
+ return [RuleDetector(), det]
37
50
 
38
51
 
39
52
  def main(argv=None):
@@ -74,9 +87,29 @@ def main(argv=None):
74
87
  p.add_argument("--allow-purpose", action="append", default=[], metavar="PURPOSE",
75
88
  help="a purpose callers of this engine are authorised for (repeatable)")
76
89
  for p in (g, c, e, s):
77
- p.add_argument("--opp-model", default=None, help="OPP Model release folder (model.onnx, tokenizer.json, labels.json)")
90
+ p.add_argument("--opp-model", default=None, metavar="FOLDER|auto|off",
91
+ help="OPP Model: a release folder, auto (the Hugging Face release, cached) or off. "
92
+ "generate uses auto by default")
93
+ p.add_argument("--no-opp-model", action="store_true", help="rule detectors only")
94
+ m = sub.add_parser("model", help="OPP Model from Hugging Face: pull it ahead of time, or show what is installed")
95
+ msub = m.add_subparsers(dest="model_cmd", required=True)
96
+ mp = msub.add_parser("pull", help="download and verify the model into the cache")
97
+ mp.add_argument("--revision", default=None, help="a release tag on Hugging Face (default: the pinned one)")
98
+ mp.add_argument("--force", action="store_true", help="download again")
99
+ mi = msub.add_parser("info", help="the model version, cache folder and acceptance results")
100
+ mi.add_argument("--revision", default=None)
78
101
  a = ap.parse_args(argv)
79
102
 
103
+ if a.cmd == "model":
104
+ from . import model_hub
105
+ if a.model_cmd == "pull":
106
+ try:
107
+ print(model_hub.pull(a.revision, force=a.force))
108
+ except Exception as ex:
109
+ raise SystemExit(f"could not download OPP Model: {ex}")
110
+ return 0
111
+ print(json.dumps(model_hub.info(a.revision), indent=2))
112
+ return 0
80
113
  if a.cmd == "generate":
81
114
  from .connectors import connect
82
115
  from .generate import generate
@@ -93,7 +126,7 @@ def main(argv=None):
93
126
  for loc in a.sources:
94
127
  print(f"reading {loc.split('@')[-1] if '://' in loc else loc} ...", file=sys.stderr)
95
128
  sources.append(connect(loc, sample=a.sample))
96
- doc = generate(sources, a.name, a.org, detectors=_detectors(a), previous=prev)
129
+ doc = generate(sources, a.name, a.org, detectors=_detectors(a, auto=True), previous=prev)
97
130
  if preset:
98
131
  doc["provenance"]["notes"] = f"industry preset: {preset['id']}"
99
132
  doc, removed = clean_model(doc)
@@ -0,0 +1,165 @@
1
+ """OPP Model from Hugging Face: download once, verify, keep it in the user's cache.
2
+
3
+ OPP Model releases live on the Hugging Face Hub (`tiny-bubble-company/opp-model`), one tag per version.
4
+ `opp-engine generate` uses the model automatically: the first run downloads the runtime files of the
5
+ pinned version, checks them, and caches them; later runs work offline. `opp-engine model pull` does
6
+ the download ahead of time (for example in a container image).
7
+
8
+ Files model.onnx (int8), tokenizer.json, labels.json, metrics.json, checked against SHA256SUMS
9
+ Cache $OPP_MODEL_HOME, else $XDG_CACHE_HOME/opp-engine/models, else ~/.cache/opp-engine/models
10
+ Version PINNED below; OPP_MODEL_REVISION=<tag> (or --revision) picks another release
11
+ Off OPP_MODEL=off, or --no-opp-model
12
+
13
+ For the pinned release the expected digests are part of this package, so a changed file on the Hub is
14
+ refused. For any other revision the files are checked against that revision's own SHA256SUMS
15
+ (integrity, not authorship).
16
+
17
+ Pip cannot run code when a package is installed, so the model is fetched on first use rather than at
18
+ `pip install` time.
19
+ """
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import shutil
24
+ import sys
25
+ import tempfile
26
+ import urllib.request
27
+ from pathlib import Path
28
+
29
+ REPO = "tiny-bubble-company/opp-model"
30
+ PINNED = "v1"
31
+ FILES = ("model.onnx", "tokenizer.json", "labels.json", "metrics.json")
32
+ # SHA-256 of the pinned release's files (from its SHA256SUMS on the Hub).
33
+ DIGESTS = {
34
+ "v1": {
35
+ "model.onnx": "5f43392e98663232fbd7acc1940d71d2e24380e2365287e126ff1743c41af554",
36
+ "tokenizer.json": "9fd55248d51d33976b324fc11592e28071da7d41e0e9401dfb7082e30574b7b1",
37
+ "labels.json": "b96c72dc905913b286c1c8ca1a25e94bfd35553b8aa6df39d889399395b8c33b",
38
+ "metrics.json": "02389d2c331eb3ad031a798ff23d800f052ef3ede4b12f7819d1735d2984ce0d",
39
+ },
40
+ }
41
+
42
+
43
+ def endpoint():
44
+ return os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
45
+
46
+
47
+ OFF = {"off", "0", "false", "no", "none"}
48
+
49
+
50
+ def home():
51
+ if os.environ.get("OPP_MODEL_HOME"):
52
+ return Path(os.environ["OPP_MODEL_HOME"]).expanduser()
53
+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
54
+ return Path(base) / "opp-engine" / "models"
55
+
56
+
57
+ def revision(rev=None):
58
+ return rev or os.environ.get("OPP_MODEL_REVISION") or PINNED
59
+
60
+
61
+ def folder(rev=None, repo=REPO):
62
+ return home() / repo.replace("/", "--") / revision(rev)
63
+
64
+
65
+ def _sha256(p):
66
+ h = hashlib.sha256()
67
+ with open(p, "rb") as f:
68
+ for b in iter(lambda: f.read(1 << 20), b""):
69
+ h.update(b)
70
+ return h.hexdigest()
71
+
72
+
73
+ def installed(rev=None, repo=REPO):
74
+ """The cached release folder if it is complete and verified, else None."""
75
+ d = folder(rev, repo)
76
+ ok = d / ".verified"
77
+ if ok.exists() and all((d / f).exists() for f in FILES):
78
+ return d
79
+ return None
80
+
81
+
82
+ def _get(url, dest, timeout=60):
83
+ req = urllib.request.Request(url, headers={"User-Agent": "opp-engine"})
84
+ with urllib.request.urlopen(req, timeout=timeout) as r, open(dest, "wb") as f:
85
+ shutil.copyfileobj(r, f, 1 << 20)
86
+
87
+
88
+ def _expected(rev, repo, tmp):
89
+ if repo == REPO and rev in DIGESTS:
90
+ return DIGESTS[rev]
91
+ sums = tmp / "SHA256SUMS"
92
+ _get(f"{endpoint()}/{repo}/resolve/{rev}/SHA256SUMS", sums)
93
+ out = {}
94
+ for line in sums.read_text().splitlines():
95
+ parts = line.split()
96
+ if len(parts) == 2:
97
+ out[parts[1].lstrip("*")] = parts[0].lower()
98
+ return out
99
+
100
+
101
+ def pull(rev=None, repo=REPO, force=False, log="stderr"):
102
+ """Download and verify a release into the cache; return its folder."""
103
+ log = sys.stderr if log == "stderr" else log
104
+ rev = revision(rev)
105
+ d = folder(rev, repo)
106
+ if not force and installed(rev, repo):
107
+ return d
108
+ d.parent.mkdir(parents=True, exist_ok=True)
109
+ with tempfile.TemporaryDirectory(dir=d.parent) as t:
110
+ tmp = Path(t)
111
+ expected = _expected(rev, repo, tmp)
112
+ missing = [f for f in FILES if f not in expected]
113
+ if missing:
114
+ raise RuntimeError(f"{repo}@{rev} has no checksum for {', '.join(missing)}")
115
+ if log:
116
+ print(f"downloading OPP Model {rev} from {endpoint()}/{repo} (about 40 MB, once) ...", file=log)
117
+ for f in FILES:
118
+ _get(f"{endpoint()}/{repo}/resolve/{rev}/{f}", tmp / f)
119
+ got = _sha256(tmp / f)
120
+ if got != expected[f]:
121
+ raise RuntimeError(f"OPP Model {rev}: {f} does not match its checksum (got {got[:12]}...)")
122
+ (tmp / ".verified").write_text(json.dumps({"repo": repo, "revision": rev, "files": {f: expected[f] for f in FILES}}))
123
+ if d.exists():
124
+ shutil.rmtree(d)
125
+ os.replace(tmp, d)
126
+ tmp.mkdir() # TemporaryDirectory cleans up a path that must exist
127
+ if log:
128
+ print(f"OPP Model {rev} ready in {d}", file=log)
129
+ return d
130
+
131
+
132
+ def resolve(option=None, auto=True, log="stderr"):
133
+ """The model folder to use, or None for rules only.
134
+
135
+ `option` is --opp-model: a folder, "auto"/"default" (the Hub release), or "off". Without it,
136
+ OPP_MODEL is read the same way. When neither is set and `auto` is true, the pinned release is
137
+ used, downloaded on first use; if it cannot be downloaded the engine says so and runs on rules.
138
+ """
139
+ log = sys.stderr if log == "stderr" else log
140
+ choice = option or os.environ.get("OPP_MODEL")
141
+ if choice and choice.lower() in OFF:
142
+ return None
143
+ if choice and choice.lower() not in ("auto", "default"):
144
+ return Path(choice).expanduser()
145
+ if not choice and not auto:
146
+ return None
147
+ have = installed()
148
+ if have:
149
+ return have
150
+ try:
151
+ return pull(log=log)
152
+ except Exception as e: # offline, proxy, Hub down: never stop a run for the optional model
153
+ if log:
154
+ print(f"OPP Model not available ({e}); continuing with the rule detectors. "
155
+ "Run `opp-engine model pull` when online, or set OPP_MODEL=off to silence this.", file=log)
156
+ return None
157
+
158
+
159
+ def info(rev=None):
160
+ d = installed(rev)
161
+ out = {"repo": REPO, "revision": revision(rev), "pinned": PINNED, "cache": str(folder(rev)), "installed": bool(d)}
162
+ if d:
163
+ m = json.loads((d / "metrics.json").read_text())
164
+ out["acceptance"] = {k: v.get("pass") for k, v in (m.get("acceptance") or {}).items() if isinstance(v, dict)}
165
+ return out
@@ -0,0 +1,72 @@
1
+ """OPP Model from the Hub: download, verify, cache, and fall back to rules when it cannot."""
2
+ import hashlib
3
+ import http.server
4
+ import threading
5
+ from functools import partial
6
+
7
+ import pytest
8
+
9
+ from opp_engine import model_hub
10
+
11
+ FILES = {
12
+ "model.onnx": b"onnx-bytes",
13
+ "tokenizer.json": b"{}",
14
+ "labels.json": b'{"id2label": {"0": "O"}}',
15
+ "metrics.json": b'{"acceptance": {"size_le_60MB": {"pass": true}}}',
16
+ }
17
+
18
+
19
+ @pytest.fixture
20
+ def hub(tmp_path, monkeypatch):
21
+ root = tmp_path / "hub" / "acme" / "opp-model" / "resolve" / "v9"
22
+ root.mkdir(parents=True)
23
+ for name, body in FILES.items():
24
+ (root / name).write_bytes(body)
25
+ sums = "".join(f"{hashlib.sha256(b).hexdigest()} {n}\n" for n, b in FILES.items())
26
+ (root / "SHA256SUMS").write_text(sums)
27
+ handler = partial(http.server.SimpleHTTPRequestHandler, directory=str(tmp_path / "hub"))
28
+ handler.log_message = lambda *a: None
29
+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
30
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
31
+ monkeypatch.setenv("HF_ENDPOINT", f"http://127.0.0.1:{srv.server_address[1]}")
32
+ monkeypatch.setenv("OPP_MODEL_HOME", str(tmp_path / "cache"))
33
+ monkeypatch.delenv("OPP_MODEL", raising=False)
34
+ monkeypatch.delenv("OPP_MODEL_REVISION", raising=False)
35
+ yield root
36
+ srv.shutdown()
37
+
38
+
39
+ def test_pull_verifies_and_caches(hub):
40
+ d = model_hub.pull("v9", repo="acme/opp-model", log=None)
41
+ assert (d / "model.onnx").read_bytes() == b"onnx-bytes"
42
+ assert model_hub.installed("v9", repo="acme/opp-model") == d
43
+ # Cached: a second pull does not download again (the Hub copy can go away).
44
+ (hub / "model.onnx").unlink()
45
+ assert model_hub.pull("v9", repo="acme/opp-model", log=None) == d
46
+
47
+
48
+ def test_a_changed_file_is_refused(hub):
49
+ (hub / "model.onnx").write_bytes(b"tampered")
50
+ with pytest.raises(RuntimeError, match="checksum"):
51
+ model_hub.pull("v9", repo="acme/opp-model", log=None)
52
+ assert model_hub.installed("v9", repo="acme/opp-model") is None
53
+
54
+
55
+ def test_the_pinned_release_uses_digests_shipped_with_the_engine(hub, monkeypatch):
56
+ monkeypatch.setattr(model_hub, "REPO", "acme/opp-model")
57
+ monkeypatch.setitem(model_hub.DIGESTS, "v9", {n: "0" * 64 for n in FILES})
58
+ # The Hub's own SHA256SUMS match, but the engine's pinned digests do not.
59
+ with pytest.raises(RuntimeError, match="checksum"):
60
+ model_hub.pull("v9", repo="acme/opp-model", log=None)
61
+
62
+
63
+ def test_resolve_choices(hub, tmp_path, monkeypatch, capsys):
64
+ assert model_hub.resolve("off") is None
65
+ assert model_hub.resolve(str(tmp_path / "mine")) == tmp_path / "mine"
66
+ assert model_hub.resolve(None, auto=False) is None
67
+ # Auto, but the pinned release cannot be fetched: rules only, with a message.
68
+ monkeypatch.setenv("HF_ENDPOINT", "http://127.0.0.1:9")
69
+ assert model_hub.resolve(None, auto=True) is None
70
+ assert "continuing with the rule detectors" in capsys.readouterr().err
71
+ monkeypatch.setenv("OPP_MODEL", "off")
72
+ assert model_hub.resolve(None, auto=True) is None