flouds-onnx 2.0.0__py3-none-any.whl

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.
@@ -0,0 +1,102 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ """
6
+ flouds-onnx
7
+ ~~~~~~~~~~
8
+ Ollama-style ONNX model store and runtime.
9
+
10
+ Quick start:
11
+ from flouds_onnx import create_model
12
+
13
+ model = create_model("sentence-transformers/all-MiniLM-L6-v2")
14
+ outputs = model.run(None, {"input_ids": ids, "attention_mask": mask})
15
+ """
16
+ from typing import Any, List
17
+
18
+ from flouds_onnx.api.client import FloudsOnnxClient, get_default_client
19
+ from flouds_onnx.config.export_options import ExportOptions
20
+ from flouds_onnx.config.model_config import ModelConfig
21
+ from flouds_onnx.config.settings import FloudsOnnxSettings
22
+ from flouds_onnx.exceptions import (
23
+ ExporterNotInstalledError,
24
+ ExportError,
25
+ ExportInProgressError,
26
+ FloudsOnnxError,
27
+ InvalidModelReferenceError,
28
+ ManifestError,
29
+ ModelLoadError,
30
+ ModelNameConflictError,
31
+ ModelNotFoundError,
32
+ OptimumNotInstalledError,
33
+ RemoteCodeRequiredError,
34
+ RevisionMismatchError,
35
+ StrategyError,
36
+ TokenizerError,
37
+ )
38
+ from flouds_onnx.runtime.loader import LoadedModel
39
+ from flouds_onnx.runtime.strategy import SessionStrategy
40
+ from flouds_onnx.store.manifest import ModelManifest
41
+
42
+ __version__ = "2.0.0"
43
+ __all__ = [
44
+ # Primary API
45
+ "create_model",
46
+ "load_model",
47
+ "pull",
48
+ "list_models",
49
+ "remove_model",
50
+ # Client / settings
51
+ "FloudsOnnxClient",
52
+ "FloudsOnnxSettings",
53
+ "get_default_client",
54
+ # Types
55
+ "ModelConfig",
56
+ "ExportOptions",
57
+ "LoadedModel",
58
+ "SessionStrategy",
59
+ # Exceptions
60
+ "FloudsOnnxError",
61
+ "ModelNotFoundError",
62
+ "InvalidModelReferenceError",
63
+ "ModelNameConflictError",
64
+ "ModelLoadError",
65
+ "TokenizerError",
66
+ "ExportError",
67
+ "ExporterNotInstalledError",
68
+ "ExportInProgressError",
69
+ "RemoteCodeRequiredError",
70
+ "RevisionMismatchError",
71
+ "OptimumNotInstalledError",
72
+ "ManifestError",
73
+ "StrategyError",
74
+ ]
75
+
76
+
77
+ # ── Top-level convenience functions (delegate to default client singleton) ────
78
+
79
+
80
+ def create_model(model_name: str, model_for: str = "fe", **kwargs: Any) -> LoadedModel:
81
+ """Pull (auto-export if missing) + load session. Primary entry-point."""
82
+ return get_default_client().create_model(model_name, model_for, **kwargs)
83
+
84
+
85
+ def load_model(model_name: str, model_for: str = "fe") -> LoadedModel:
86
+ """Load a model already on disk (no auto-pull)."""
87
+ return get_default_client().load_model(model_name, model_for)
88
+
89
+
90
+ def pull(model_name: str, model_for: str = "fe", **kwargs: Any) -> ModelManifest:
91
+ """Export model to disk only (no session load)."""
92
+ return get_default_client().pull(model_name, model_for, **kwargs)
93
+
94
+
95
+ def list_models() -> List[ModelManifest]:
96
+ """Return manifests for all locally stored models."""
97
+ return get_default_client().list()
98
+
99
+
100
+ def remove_model(model_name: str, model_for: str = "fe") -> bool:
101
+ """Delete model from disk and evict from session pool."""
102
+ return get_default_client().remove(model_name, model_for)
@@ -0,0 +1,7 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ from flouds_onnx.api.client import FloudsOnnxClient, get_default_client
6
+
7
+ __all__ = ["FloudsOnnxClient", "get_default_client"]
@@ -0,0 +1,92 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ from __future__ import annotations
6
+
7
+ import threading
8
+ from typing import Any, List, Optional
9
+
10
+ from flouds_onnx.config.export_options import ExportOptions
11
+ from flouds_onnx.config.model_config import ModelConfig
12
+ from flouds_onnx.config.settings import FloudsOnnxSettings
13
+ from flouds_onnx.runtime.loader import LoadedModel, ModelLoader
14
+ from flouds_onnx.store.manifest import ModelManifest
15
+
16
+
17
+ class FloudsOnnxClient:
18
+ """Friendly facade over ModelLoader."""
19
+
20
+ def __init__(self, settings: Optional[FloudsOnnxSettings] = None) -> None:
21
+ self._loader = ModelLoader(settings)
22
+
23
+ def pull(
24
+ self,
25
+ model_name: str,
26
+ model_for: str = "fe",
27
+ task: Optional[str] = None,
28
+ force: bool = False,
29
+ config: Optional[ModelConfig] = None,
30
+ options: Optional[ExportOptions] = None,
31
+ **option_kwargs: Any,
32
+ ) -> ModelManifest:
33
+ """Export a model into the local store if it is not there already.
34
+
35
+ Export options can be given as an ``ExportOptions`` object, as keyword
36
+ arguments named after its fields (``optimize``, ``opset_version``, ``library``,
37
+ ``normalize_embeddings``, ``trust_remote_code``, ``hf_token``, ...), or both.
38
+ """
39
+ return self._loader.pull(model_name, model_for, task=task, force=force, config=config, options=options, **option_kwargs)
40
+
41
+ def list(self) -> List[ModelManifest]:
42
+ return self._loader.list()
43
+
44
+ def get_manifest(self, model_name: str, model_for: str = "fe") -> Optional[ModelManifest]:
45
+ """Manifest of a model in the local store, or None if it is not there."""
46
+ return self._loader.get_manifest(model_name, model_for)
47
+
48
+ def remove(self, model_name: str, model_for: str = "fe") -> bool:
49
+ return self._loader.remove(model_name, model_for)
50
+
51
+ def create_model(
52
+ self,
53
+ model_name: str,
54
+ model_for: str = "fe",
55
+ task: Optional[str] = None,
56
+ force_pull: bool = False,
57
+ config: Optional[ModelConfig] = None,
58
+ **kwargs: Any,
59
+ ) -> LoadedModel:
60
+ return self._loader.create_model(model_name, model_for, task=task, force_pull=force_pull, config=config, **kwargs)
61
+
62
+ def load_model(self, model_name: str, model_for: str = "fe") -> LoadedModel:
63
+ return self._loader.load_model(model_name, model_for)
64
+
65
+ def reload(self, model_name: str, model_for: str = "fe") -> LoadedModel:
66
+ return self._loader.reload(model_name, model_for)
67
+
68
+ def unload(self, model_name: str, model_for: str = "fe") -> bool:
69
+ return self._loader.unload(model_name, model_for)
70
+
71
+ def is_loaded(self, model_name: str, model_for: str = "fe") -> bool:
72
+ return self._loader.is_loaded(model_name, model_for)
73
+
74
+ def cache_stats(self) -> dict[str, Any]:
75
+ return self._loader.cache_stats()
76
+
77
+ @property
78
+ def settings(self) -> FloudsOnnxSettings:
79
+ return self._loader._settings
80
+
81
+
82
+ _default_client: Optional[FloudsOnnxClient] = None
83
+ _default_client_lock = threading.Lock()
84
+
85
+
86
+ def get_default_client() -> FloudsOnnxClient:
87
+ global _default_client
88
+ if _default_client is None:
89
+ with _default_client_lock:
90
+ if _default_client is None:
91
+ _default_client = FloudsOnnxClient(FloudsOnnxSettings.from_env())
92
+ return _default_client
@@ -0,0 +1,30 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ """
6
+ flouds_onnx.api.dependencies
7
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8
+ FastAPI dependencies. Imported only by the server, after FastAPI is known to be
9
+ installed; the rules themselves live in ``flouds_onnx.api.security``, which has no
10
+ FastAPI import.
11
+ """
12
+ from fastapi import HTTPException, Request
13
+
14
+ from flouds_onnx.api.security import check_access
15
+
16
+
17
+ async def require_access(request: Request) -> None:
18
+ """Applied to every route except /health. See ``flouds_onnx.api.security``."""
19
+ state = request.app.state
20
+ status, reason = check_access(
21
+ token=getattr(state, "api_token", None),
22
+ allowed_origins=getattr(state, "allowed_origins", frozenset()),
23
+ authorization=request.headers.get("authorization", ""),
24
+ origin=request.headers.get("origin", ""),
25
+ host_header=request.headers.get("host", ""),
26
+ client_host=request.client.host if request.client else None,
27
+ )
28
+ if status != 200:
29
+ headers = {"WWW-Authenticate": "Bearer"} if status == 401 else None
30
+ raise HTTPException(status_code=status, detail=reason, headers=headers)
@@ -0,0 +1,4 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
@@ -0,0 +1,51 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from typing import Any
9
+
10
+
11
+ def store_status(models_root: str) -> tuple[bool, str]:
12
+ """Whether the model store can be used, and why not if it cannot.
13
+
14
+ A store directory that does not exist yet is fine: it is created by the first
15
+ pull. One that exists but cannot be read or listed is not.
16
+ """
17
+ if not os.path.exists(models_root):
18
+ return True, "not created yet"
19
+ if not os.path.isdir(models_root):
20
+ return False, "store path is not a directory"
21
+ try:
22
+ os.listdir(models_root)
23
+ except OSError as exc:
24
+ return False, f"store is not readable: {type(exc).__name__}"
25
+ return True, "ok"
26
+
27
+
28
+ try:
29
+ from fastapi import APIRouter
30
+ from fastapi.responses import JSONResponse
31
+
32
+ router: Any = APIRouter(tags=["health"])
33
+
34
+ @router.get("/health")
35
+ async def health() -> dict[str, str]:
36
+ """Liveness: the process is up. Does not touch the model store."""
37
+ from flouds_onnx import __version__
38
+
39
+ return {"status": "ok", "service": "flouds-onnx", "version": __version__}
40
+
41
+ @router.get("/health/ready")
42
+ async def ready() -> Any:
43
+ """Readiness: the model store is usable. Returns 503 when it is not."""
44
+ from flouds_onnx.api.client import get_default_client
45
+
46
+ ok, reason = store_status(str(get_default_client().settings.models_root))
47
+ body = {"status": "ready" if ok else "not_ready", "store": reason}
48
+ return body if ok else JSONResponse(status_code=503, content=body)
49
+
50
+ except ImportError:
51
+ router = None
@@ -0,0 +1,154 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ import os
9
+ from typing import Annotated, Any, Callable
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+ try:
14
+ from fastapi import APIRouter, HTTPException, Query
15
+ from pydantic import BaseModel as _BM
16
+ from pydantic import ConfigDict
17
+ from starlette.concurrency import run_in_threadpool
18
+
19
+ from flouds_onnx.api.client import get_default_client
20
+ from flouds_onnx.config.export_options import ExportOptions, SafeExportOptions
21
+ from flouds_onnx.exceptions import (
22
+ ExporterNotInstalledError,
23
+ ExportInProgressError,
24
+ FloudsOnnxError,
25
+ InvalidModelReferenceError,
26
+ ModelNameConflictError,
27
+ ModelNotFoundError,
28
+ OptimumNotInstalledError,
29
+ RemoteCodeRequiredError,
30
+ RevisionMismatchError,
31
+ )
32
+
33
+ router = APIRouter(tags=["models"])
34
+
35
+ def _http_error(exc: FloudsOnnxError) -> HTTPException:
36
+ """Translate a library error into an HTTP response.
37
+
38
+ Errors the caller can act on keep their message. Anything else is logged in
39
+ full and reported without detail, because the underlying text contains
40
+ filesystem paths and third-party error output.
41
+ """
42
+ if isinstance(exc, InvalidModelReferenceError):
43
+ return HTTPException(status_code=400, detail=str(exc))
44
+ if isinstance(exc, ModelNotFoundError):
45
+ return HTTPException(status_code=404, detail=exc.args[0] if exc.args else "Model not found")
46
+ if isinstance(exc, RemoteCodeRequiredError):
47
+ # trust_remote_code cannot be set over HTTP, so say how it can be done.
48
+ return HTTPException(
49
+ status_code=422,
50
+ detail=f"{exc.args[0]}. The server never enables it; pull this model with the Python API or the CLI.",
51
+ )
52
+ if isinstance(exc, (ExportInProgressError, ModelNameConflictError, RevisionMismatchError)):
53
+ return HTTPException(status_code=409, detail=str(exc))
54
+ if isinstance(exc, (ExporterNotInstalledError, OptimumNotInstalledError)):
55
+ return HTTPException(status_code=501, detail=exc.args[0] if exc.args else "A required optional package is not installed")
56
+ log.error("flouds-onnx server: %s: %s", type(exc).__name__, exc)
57
+ return HTTPException(status_code=500, detail=f"{type(exc).__name__}: the operation failed. See the server log for details.")
58
+
59
+ async def _run(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
60
+ """Run blocking store or runtime work in a worker thread.
61
+
62
+ Exports take minutes and model loads take seconds. Run on the event loop they
63
+ would stall every other request, including /health.
64
+ """
65
+ try:
66
+ return await run_in_threadpool(func, *args, **kwargs)
67
+ except FloudsOnnxError as exc:
68
+ raise _http_error(exc) from exc
69
+
70
+ class PullRequest(SafeExportOptions):
71
+ """Request body for pull and create: the model, plus the export options that are
72
+ safe to accept over HTTP.
73
+
74
+ ``trust_remote_code`` and ``hf_token`` are deliberately not part of
75
+ ``SafeExportOptions``. The first runs Python from the model repository on this
76
+ server; the second would put a credential in request bodies and logs. Use the
77
+ CLI or the Python API for models that need remote code; the server takes its
78
+ Hugging Face token from HUGGINGFACE_HUB_TOKEN in its own environment.
79
+ """
80
+
81
+ # Unknown fields are rejected rather than ignored, so a caller who sends an
82
+ # option this API does not offer is told so.
83
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
84
+
85
+ model_name: str
86
+ model_for: str = "fe"
87
+ force: bool = False
88
+
89
+ class LoadRequest(_BM):
90
+ model_config = ConfigDict(extra="forbid", protected_namespaces=())
91
+
92
+ model_name: str
93
+ model_for: str = "fe"
94
+
95
+ def _export_options(req: PullRequest) -> ExportOptions:
96
+ safe = req.model_dump(exclude={"model_name", "model_for", "force"})
97
+ return ExportOptions(**safe, trust_remote_code=False, hf_token=os.environ.get("HUGGINGFACE_HUB_TOKEN") or None)
98
+
99
+ @router.get("/models")
100
+ async def list_models() -> list[dict[str, Any]]:
101
+ manifests = await _run(get_default_client().list)
102
+ return [m.model_dump(mode="json") for m in manifests]
103
+
104
+ @router.get("/models/{name:path}")
105
+ async def get_model(name: str, model_for: Annotated[str, Query()] = "fe") -> dict[str, Any]:
106
+ manifest = await _run(get_default_client().get_manifest, name, model_for)
107
+ if manifest is None:
108
+ raise HTTPException(status_code=404, detail=f"Model '{name}' not found")
109
+ return manifest.model_dump(mode="json")
110
+
111
+ @router.post("/models/pull")
112
+ async def pull_model(req: PullRequest) -> dict[str, Any]:
113
+ manifest = await _run(get_default_client().pull, req.model_name, req.model_for, force=req.force, **_export_options(req).as_kwargs())
114
+ return manifest.model_dump(mode="json")
115
+
116
+ @router.post("/models/create")
117
+ async def create_model(req: PullRequest) -> dict[str, Any]:
118
+ loaded = await _run(
119
+ get_default_client().create_model, req.model_name, req.model_for, force_pull=req.force, **_export_options(req).as_kwargs()
120
+ )
121
+ return {
122
+ "model_name": loaded.model_name,
123
+ "model_for": loaded.model_for,
124
+ "strategy": loaded.session_strategy.value,
125
+ "is_seq2seq": loaded.is_seq2seq,
126
+ "status": "created",
127
+ }
128
+
129
+ @router.post("/models/load")
130
+ async def load_model(req: LoadRequest) -> dict[str, str]:
131
+ loaded = await _run(get_default_client().load_model, req.model_name, req.model_for)
132
+ return {"model_name": loaded.model_name, "model_for": loaded.model_for, "strategy": loaded.session_strategy.value, "status": "loaded"}
133
+
134
+ @router.post("/models/reload")
135
+ async def reload_model(req: LoadRequest) -> dict[str, str]:
136
+ loaded = await _run(get_default_client().reload, req.model_name, req.model_for)
137
+ return {"model_name": loaded.model_name, "strategy": loaded.session_strategy.value, "status": "reloaded"}
138
+
139
+ @router.post("/models/unload")
140
+ async def unload_model(req: LoadRequest) -> dict[str, Any]:
141
+ evicted = await _run(get_default_client().unload, req.model_name, req.model_for)
142
+ return {"model_name": req.model_name, "evicted": evicted}
143
+
144
+ @router.delete("/models/{name:path}")
145
+ async def remove_model(name: str, model_for: Annotated[str, Query()] = "fe") -> dict[str, Any]:
146
+ removed = await _run(get_default_client().remove, name, model_for)
147
+ return {"model_name": name, "removed": removed}
148
+
149
+ @router.get("/stats")
150
+ async def stats() -> dict[str, Any]:
151
+ return await _run(get_default_client().cache_stats)
152
+
153
+ except ImportError:
154
+ router = None
@@ -0,0 +1,92 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ """
6
+ flouds_onnx.api.security
7
+ ~~~~~~~~~~~~~~~~~~~~~~~~
8
+ Access control for the optional HTTP server.
9
+
10
+ The server can download and export models, load them into memory and delete them from
11
+ disk, so every route except ``/health`` is protected. There are two modes:
12
+
13
+ Token mode: ``FLOUDS_ONNX_API_TOKEN`` is set.
14
+ Every request must send ``Authorization: Bearer <token>``. This is the only mode
15
+ in which the server may listen on a non-loopback address.
16
+
17
+ Local mode: no token is set.
18
+ Only requests from this machine are served: the connection must come from a
19
+ loopback address and the ``Host`` header must name a loopback host. The second
20
+ check stops DNS-rebinding, where a web page makes the browser reach
21
+ ``127.0.0.1`` under the page's own host name.
22
+
23
+ In both modes a request that carries an ``Origin`` header (that is, one made by a web
24
+ page) is refused unless the origin is the server itself or is listed in
25
+ ``FLOUDS_ONNX_ALLOWED_ORIGINS``. Without that, any page open in a browser on the same
26
+ machine could drive a server running in local mode.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import hmac
31
+ import ipaddress
32
+ import os
33
+ from typing import FrozenSet, Optional
34
+ from urllib.parse import urlsplit
35
+
36
+ API_TOKEN_ENV = "FLOUDS_ONNX_API_TOKEN" # nosec B105 - the name of a variable, not a secret
37
+ ALLOWED_ORIGINS_ENV = "FLOUDS_ONNX_ALLOWED_ORIGINS"
38
+
39
+ _LOOPBACK_NAMES = frozenset({"localhost"})
40
+
41
+
42
+ def configured_token() -> Optional[str]:
43
+ token = (os.environ.get(API_TOKEN_ENV) or "").strip()
44
+ return token or None
45
+
46
+
47
+ def configured_origins() -> FrozenSet[str]:
48
+ raw = os.environ.get(ALLOWED_ORIGINS_ENV) or ""
49
+ return frozenset(item.strip().rstrip("/").lower() for item in raw.split(",") if item.strip())
50
+
51
+
52
+ def is_loopback_host(host: Optional[str]) -> bool:
53
+ """True for localhost, 127.0.0.0/8 and ::1. Accepts 'host', 'host:port' and '[::1]:port'."""
54
+ if not host:
55
+ return False
56
+ value = host.strip().lower()
57
+ if value.startswith("["): # [::1]:19720
58
+ value = value[1:].split("]", 1)[0]
59
+ elif value.count(":") == 1: # name:port or 127.0.0.1:port
60
+ value = value.split(":", 1)[0]
61
+ if value in _LOOPBACK_NAMES:
62
+ return True
63
+ try:
64
+ return ipaddress.ip_address(value).is_loopback
65
+ except ValueError:
66
+ return False
67
+
68
+
69
+ def _origin_allowed(origin: str, host_header: str, allowed: FrozenSet[str]) -> bool:
70
+ normalised = origin.strip().rstrip("/").lower()
71
+ if normalised in allowed:
72
+ return True
73
+ # Same origin: the page was served by this server (for example the API docs page).
74
+ return urlsplit(normalised).netloc == host_header.strip().lower() and bool(host_header.strip())
75
+
76
+
77
+ def check_access(
78
+ *, token: Optional[str], allowed_origins: FrozenSet[str], authorization: str, origin: str, host_header: str, client_host: Optional[str]
79
+ ) -> tuple[int, str]:
80
+ """Decide whether a request may proceed. Returns (status, reason); status 200 means yes."""
81
+ if origin and not _origin_allowed(origin, host_header, allowed_origins):
82
+ return 403, "Requests from this web origin are not allowed."
83
+
84
+ if token:
85
+ scheme, _, supplied = authorization.partition(" ")
86
+ if scheme.lower() != "bearer" or not hmac.compare_digest(supplied.strip().encode("utf-8"), token.encode("utf-8")):
87
+ return 401, "A valid bearer token is required."
88
+ return 200, ""
89
+
90
+ if not is_loopback_host(client_host) or not is_loopback_host(host_header):
91
+ return 403, f"This server has no API token configured and only accepts local requests. Set {API_TOKEN_ENV} to allow remote access."
92
+ return 200, ""
@@ -0,0 +1,62 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ from typing import Any, Iterable, Optional
9
+
10
+ from flouds_onnx.exceptions import ServerConfigurationError, ServerNotInstalledError
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def create_app(api_token: Optional[str] = None, allowed_origins: Optional[Iterable[str]] = None) -> Any:
16
+ """Build the FastAPI application.
17
+
18
+ *api_token* and *allowed_origins* default to the ``FLOUDS_ONNX_API_TOKEN`` and
19
+ ``FLOUDS_ONNX_ALLOWED_ORIGINS`` environment variables. Without a token the server
20
+ only answers requests from this machine; see ``flouds_onnx.api.security``.
21
+ """
22
+ try:
23
+ from fastapi import Depends, FastAPI, Request
24
+ from fastapi.responses import JSONResponse
25
+ except ImportError as exc:
26
+ raise ServerNotInstalledError() from exc
27
+ from flouds_onnx import __version__
28
+ from flouds_onnx.api import security
29
+ from flouds_onnx.api.dependencies import require_access
30
+ from flouds_onnx.api.routers import health, models
31
+ from flouds_onnx.exceptions import InvalidModelReferenceError
32
+
33
+ app = FastAPI(title="flouds-onnx", description="ONNX model store and runtime REST API", version=__version__)
34
+ app.state.api_token = api_token.strip() if isinstance(api_token, str) and api_token.strip() else security.configured_token()
35
+ app.state.allowed_origins = (
36
+ frozenset(origin.strip().rstrip("/").lower() for origin in allowed_origins) if allowed_origins is not None else security.configured_origins()
37
+ )
38
+ if not app.state.api_token:
39
+ log.warning("flouds-onnx server: no API token configured; only requests from this machine will be served.")
40
+
41
+ @app.exception_handler(InvalidModelReferenceError)
42
+ async def _invalid_model_reference(_request: Request, exc: InvalidModelReferenceError) -> JSONResponse:
43
+ # Raised before any file is touched; report it as a bad request on every route.
44
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
45
+
46
+ app.include_router(health.router)
47
+ app.include_router(models.router, prefix="/api/v1", dependencies=[Depends(require_access)])
48
+ return app
49
+
50
+
51
+ def run_server(host: str = "127.0.0.1", port: int = 19720, reload: bool = False) -> None:
52
+ try:
53
+ import uvicorn
54
+ except ImportError as exc:
55
+ raise ServerNotInstalledError() from exc
56
+ from flouds_onnx.api import security
57
+
58
+ # The server can export, load and delete models. Listening beyond this machine
59
+ # without a token would hand that to anyone who can reach the port.
60
+ if not security.is_loopback_host(host) and not security.configured_token():
61
+ raise ServerConfigurationError(f"Refusing to listen on '{host}' without an API token. Set {security.API_TOKEN_ENV}, or use --host 127.0.0.1.")
62
+ uvicorn.run("flouds_onnx.api.server:create_app", factory=True, host=host, port=port, reload=reload)
@@ -0,0 +1,4 @@
1
+ # =============================================================================
2
+ # Copyright (c) 2026 Goutam Malakar. All rights reserved.
3
+ # Licensed under the Apache License, Version 2.0.
4
+ # =============================================================================