omokage 0.1.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.
- omokage/__init__.py +0 -0
- omokage/__main__.py +4 -0
- omokage/api/__init__.py +0 -0
- omokage/api/access.py +77 -0
- omokage/api/app.py +167 -0
- omokage/api/hosting.py +105 -0
- omokage/api/language.py +43 -0
- omokage/api/parameters.py +5 -0
- omokage/api/routers/__init__.py +0 -0
- omokage/api/routers/agent.py +186 -0
- omokage/api/routers/datasets.py +331 -0
- omokage/api/routers/experiments.py +105 -0
- omokage/api/routers/jobs.py +107 -0
- omokage/api/routers/library.py +148 -0
- omokage/api/routers/models.py +139 -0
- omokage/api/routers/operations.py +70 -0
- omokage/api/routers/outputs.py +176 -0
- omokage/api/routers/presets.py +29 -0
- omokage/api/routers/queue.py +229 -0
- omokage/api/routers/runs.py +268 -0
- omokage/api/routers/storage.py +113 -0
- omokage/api/routers/system.py +61 -0
- omokage/api/routers/tasks.py +212 -0
- omokage/api/routers/training.py +106 -0
- omokage/api/schema.py +284 -0
- omokage/api/security.py +24 -0
- omokage/api/sockets.py +64 -0
- omokage/cli/__init__.py +0 -0
- omokage/cli/app.py +87 -0
- omokage/cli/client.py +81 -0
- omokage/cli/commands/__init__.py +0 -0
- omokage/cli/commands/api.py +53 -0
- omokage/cli/commands/datasets.py +38 -0
- omokage/cli/commands/experiments.py +27 -0
- omokage/cli/commands/inspect.py +140 -0
- omokage/cli/commands/jobs.py +31 -0
- omokage/cli/commands/manage.py +21 -0
- omokage/cli/commands/models.py +140 -0
- omokage/cli/commands/server.py +30 -0
- omokage/cli/factory.py +82 -0
- omokage/core/__init__.py +0 -0
- omokage/core/database.py +80 -0
- omokage/core/datasets/__init__.py +0 -0
- omokage/core/datasets/service.py +283 -0
- omokage/core/datasets/storage.py +91 -0
- omokage/core/errors.py +17 -0
- omokage/core/events.py +208 -0
- omokage/core/i18n.py +38 -0
- omokage/core/inference/__init__.py +0 -0
- omokage/core/inference/batching.py +91 -0
- omokage/core/inference/refilter.py +46 -0
- omokage/core/inference/request.py +140 -0
- omokage/core/inference/service.py +465 -0
- omokage/core/inference/sidecar.py +53 -0
- omokage/core/jobs/__init__.py +0 -0
- omokage/core/jobs/models.py +68 -0
- omokage/core/jobs/scheduler.py +257 -0
- omokage/core/jobs/service.py +152 -0
- omokage/core/models/__init__.py +0 -0
- omokage/core/models/catalog.py +158 -0
- omokage/core/models/downloads.py +281 -0
- omokage/core/models/library.py +115 -0
- omokage/core/models/manifests/blip-large.json +42 -0
- omokage/core/models/manifests/blip2-flan-t5-xl-coco.json +52 -0
- omokage/core/models/manifests/blip2-flan-t5-xl.json +67 -0
- omokage/core/models/manifests/blip2-flan-t5-xxl.json +82 -0
- omokage/core/models/manifests/blip2-opt-2.7b-coco.json +57 -0
- omokage/core/models/manifests/blip2-opt-2.7b.json +72 -0
- omokage/core/models/manifests/blip2-opt-6.7b-coco.json +82 -0
- omokage/core/models/manifests/blip2-opt-6.7b.json +82 -0
- omokage/core/models/manifests/cl_tagger_1_01.json +17 -0
- omokage/core/models/manifests/git-large-coco.json +47 -0
- omokage/core/models/manifests/git-large-textcaps.json +47 -0
- omokage/core/models/manifests/joycaption-beta-one.json +72 -0
- omokage/core/models/manifests/llava-onevision-0.5b.json +72 -0
- omokage/core/models/manifests/qwen2.5-vl-7b.json +77 -0
- omokage/core/models/manifests/qwen3-vl-4b.json +67 -0
- omokage/core/models/manifests/sd-blip-large.json +42 -0
- omokage/core/models/manifests/sd-cl-optimized.json +17 -0
- omokage/core/models/manifests/sd-wd14-swinv2-v2-savedmodel.json +32 -0
- omokage/core/models/manifests/sd-wd14-swinv2-v2.json +17 -0
- omokage/core/models/manifests/smolvlm2-2.2b.json +77 -0
- omokage/core/models/manifests/toriigate-v0.4-2b.json +57 -0
- omokage/core/models/manifests/wd-convnext-v3.json +17 -0
- omokage/core/models/manifests/wd-eva02-large-tagger-v3.json +17 -0
- omokage/core/models/manifests/wd-swinv2-v3.json +17 -0
- omokage/core/models/manifests/wd-vit-large-tagger-v3.json +17 -0
- omokage/core/models/manifests/wd-vit-v3.json +17 -0
- omokage/core/models/manifests/wd14-convnext-v1-savedmodel.json +32 -0
- omokage/core/models/manifests/wd14-convnext-v1.json +17 -0
- omokage/core/models/manifests/wd14-convnext-v2-savedmodel.json +32 -0
- omokage/core/models/manifests/wd14-convnext-v2.json +17 -0
- omokage/core/models/manifests/wd14-convnextv2-v2.json +17 -0
- omokage/core/models/manifests/wd14-moat-v2.json +17 -0
- omokage/core/models/manifests/wd14-swinv2-v2.json +17 -0
- omokage/core/models/manifests/wd14-vit-v1-savedmodel.json +32 -0
- omokage/core/models/manifests/wd14-vit-v1.json +17 -0
- omokage/core/models/manifests/wd14-vit-v2.json +17 -0
- omokage/core/models/models.json +945 -0
- omokage/core/models/plugins.py +38 -0
- omokage/core/models/script_models.json +394 -0
- omokage/core/models/user_models.py +113 -0
- omokage/core/net/__init__.py +0 -0
- omokage/core/net/discovery.py +84 -0
- omokage/core/net/ports.py +122 -0
- omokage/core/notifications.py +27 -0
- omokage/core/settings/__init__.py +0 -0
- omokage/core/settings/models.py +82 -0
- omokage/core/settings/service.py +161 -0
- omokage/core/training/__init__.py +0 -0
- omokage/core/training/experiments.py +266 -0
- omokage/core/training/process.py +86 -0
- omokage/core/training/service.py +278 -0
- omokage/core/training/training_profiles.json +4 -0
- omokage/core/training/worker.py +209 -0
- omokage/core/version.py +22 -0
- omokage/core/zh-CN.json +278 -0
- omokage/embed.py +78 -0
- omokage/engines/__init__.py +0 -0
- omokage/engines/captions/__init__.py +0 -0
- omokage/engines/captions/chat.py +41 -0
- omokage/engines/captions/decoding.py +192 -0
- omokage/engines/captions/engine.py +205 -0
- omokage/engines/captions/language.py +205 -0
- omokage/engines/captions/layers.py +96 -0
- omokage/engines/captions/processor.py +183 -0
- omokage/engines/captions/sd.py +64 -0
- omokage/engines/captions/session.py +166 -0
- omokage/engines/captions/vlm.py +198 -0
- omokage/engines/captions/weights.py +91 -0
- omokage/engines/taggers/__init__.py +0 -0
- omokage/engines/taggers/engine.py +253 -0
- omokage/engines/taggers/onnx_blocks.py +137 -0
- omokage/engines/taggers/onnx_weights.py +73 -0
- omokage/engines/taggers/sd.py +162 -0
- omokage/engines/taggers/wd_vit.py +93 -0
- omokage/runtime/__init__.py +0 -0
- omokage/runtime/accel/__init__.py +0 -0
- omokage/runtime/accel/attention.py +120 -0
- omokage/runtime/accel/layer_graph.py +64 -0
- omokage/runtime/compute.py +247 -0
- omokage/runtime/cpu.py +75 -0
- omokage/runtime/diagnostics.py +85 -0
- omokage/runtime/engine.py +64 -0
- omokage/runtime/manager.py +354 -0
- omokage/runtime/memory/__init__.py +0 -0
- omokage/runtime/memory/filemap.py +87 -0
- omokage/runtime/memory/pinning.py +80 -0
- omokage/runtime/memory/placement.py +190 -0
- omokage/runtime/memory/rows.py +35 -0
- omokage/runtime/memory/transfer.py +105 -0
- omokage/runtime/readiness.py +81 -0
- omokage/runtime/remote.py +148 -0
- omokage/version.py +3 -0
- omokage/webui/__init__.py +1 -0
- omokage/webui/dist/assets/DatasetView-BzpfEFts.css +1 -0
- omokage/webui/dist/assets/DatasetView-LABDszNX.js +1 -0
- omokage/webui/dist/assets/DevComponentsView-34mXrFim.js +1 -0
- omokage/webui/dist/assets/DevComponentsView-CMqpQVye.css +1 -0
- omokage/webui/dist/assets/ExperimentView-Bj4rc2Xl.css +1 -0
- omokage/webui/dist/assets/ExperimentView-DphUVBz0.js +1 -0
- omokage/webui/dist/assets/FolderBrowser-BSX7EI7R.js +1 -0
- omokage/webui/dist/assets/FolderBrowser-MtEm6nf8.css +1 -0
- omokage/webui/dist/assets/HistoryView-Bo9_o3gn.css +1 -0
- omokage/webui/dist/assets/HistoryView-C6ZlV_Y2.js +3 -0
- omokage/webui/dist/assets/InspectView-CjmUNrDJ.css +1 -0
- omokage/webui/dist/assets/InspectView-DywK8f47.js +3 -0
- omokage/webui/dist/assets/ModelsView-DTIAbaEl.js +1 -0
- omokage/webui/dist/assets/ModelsView-DlDag3Qz.css +1 -0
- omokage/webui/dist/assets/NewExperimentDialog-DddF-11m.css +1 -0
- omokage/webui/dist/assets/NewExperimentDialog-DlqZ8qQo.js +1 -0
- omokage/webui/dist/assets/RefilterPanel-BiAg_j0W.css +1 -0
- omokage/webui/dist/assets/RefilterPanel-Bxigbzzf.js +3 -0
- omokage/webui/dist/assets/ServerPathDialog-BC4TL4GC.js +1 -0
- omokage/webui/dist/assets/SettingsView-D0Y9qqD8.js +3 -0
- omokage/webui/dist/assets/SettingsView-Dozg38MR.css +1 -0
- omokage/webui/dist/assets/TagList-B86e4x5n.css +1 -0
- omokage/webui/dist/assets/TagList-dmMer7s4.js +1 -0
- omokage/webui/dist/assets/TrainView-ODuBIs6N.js +1 -0
- omokage/webui/dist/assets/TrainView-lvlrjTMg.css +1 -0
- omokage/webui/dist/assets/client-C2zcEUVU.js +1 -0
- omokage/webui/dist/assets/datasets-Cw_Cz6C0.js +1 -0
- omokage/webui/dist/assets/experiments-olS53VFz.js +1 -0
- omokage/webui/dist/assets/favicon-Dl02K8Df.svg +1 -0
- omokage/webui/dist/assets/index-ClVx45ed.css +1 -0
- omokage/webui/dist/assets/index-D8ccXZ4X.js +654 -0
- omokage/webui/dist/assets/roboto-flex-cyrillic-ext-wght-normal-CVcCQn0y.woff2 +0 -0
- omokage/webui/dist/assets/roboto-flex-cyrillic-wght-normal-BJ-nQEdz.woff2 +0 -0
- omokage/webui/dist/assets/roboto-flex-greek-wght-normal-DeN4rzfy.woff2 +0 -0
- omokage/webui/dist/assets/roboto-flex-latin-ext-wght-normal-gysdOMcS.woff2 +0 -0
- omokage/webui/dist/assets/roboto-flex-latin-wght-normal-n-dP9qr2.woff2 +0 -0
- omokage/webui/dist/assets/roboto-flex-vietnamese-wght-normal-AVFfiTln.woff2 +0 -0
- omokage/webui/dist/assets/runtime-core.esm-bundler-BYQ3ovRE.js +1 -0
- omokage/webui/dist/index.html +30 -0
- omokage-0.1.0.dist-info/METADATA +215 -0
- omokage-0.1.0.dist-info/RECORD +202 -0
- omokage-0.1.0.dist-info/WHEEL +5 -0
- omokage-0.1.0.dist-info/entry_points.txt +2 -0
- omokage-0.1.0.dist-info/licenses/LICENSE +661 -0
- omokage-0.1.0.dist-info/licenses/licenses/Mizuoto-GPL-3.0.txt +674 -0
- omokage-0.1.0.dist-info/licenses/licenses/sd-scripts-Apache-2.0.txt +201 -0
- omokage-0.1.0.dist-info/top_level.txt +1 -0
omokage/__init__.py
ADDED
|
File without changes
|
omokage/__main__.py
ADDED
omokage/api/__init__.py
ADDED
|
File without changes
|
omokage/api/access.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import secrets
|
|
3
|
+
from base64 import b64decode
|
|
4
|
+
from binascii import Error
|
|
5
|
+
|
|
6
|
+
from fastapi import HTTPException, Request
|
|
7
|
+
from starlette.datastructures import Headers
|
|
8
|
+
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
9
|
+
|
|
10
|
+
from omokage.api.hosting import error
|
|
11
|
+
from omokage.api.security import request_token
|
|
12
|
+
from omokage.core.i18n import tr
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def authorized(headers: Headers | dict[str, str], secret: bytes, supplied: str = "") -> bool:
|
|
16
|
+
"""Whether a request is allowed: its bearer or basic credential, or ``supplied`` (the cookie, the query), matches."""
|
|
17
|
+
if not secret:
|
|
18
|
+
return True
|
|
19
|
+
header = headers.get("authorization", "")
|
|
20
|
+
scheme, _, token = header.partition(" ")
|
|
21
|
+
credential = supplied.encode()
|
|
22
|
+
if not supplied and scheme.lower() == "bearer":
|
|
23
|
+
credential = token.encode()
|
|
24
|
+
elif not supplied and scheme.lower() == "basic":
|
|
25
|
+
try:
|
|
26
|
+
credential = b64decode(token, validate=True).partition(b":")[2]
|
|
27
|
+
except Error:
|
|
28
|
+
pass
|
|
29
|
+
return secrets.compare_digest(secret, credential)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _headers(scope: Scope) -> dict[str, str]:
|
|
33
|
+
return {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AccessToken:
|
|
37
|
+
"""When a token is configured, every request must carry it; the UI shell and its assets load without, so the page can ask for one."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, app: ASGIApp, token: str, prefix: str = "") -> None:
|
|
40
|
+
self.app = app
|
|
41
|
+
self.secret = token.encode()
|
|
42
|
+
self.sio = "/socket.io"
|
|
43
|
+
base = "/" + prefix.strip("/") if prefix.strip("/") else ""
|
|
44
|
+
# The shell itself (and its assets) load without a token; the API they call needs one.
|
|
45
|
+
self.public = {f"{base}/", f"{base}/index.html"}
|
|
46
|
+
self.public_assets = f"{base}/assets/"
|
|
47
|
+
|
|
48
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
49
|
+
if scope["type"] == "http":
|
|
50
|
+
headers = _headers(scope)
|
|
51
|
+
path = scope.get("path", "")
|
|
52
|
+
if scope["method"] in ("GET", "HEAD") and (path in self.public or path.startswith(f"{self.public_assets}")):
|
|
53
|
+
await self.app(scope, receive, send)
|
|
54
|
+
return
|
|
55
|
+
if path.startswith(self.sio):
|
|
56
|
+
# The socket authenticates in its own connect handler (the auth payload or the cookie).
|
|
57
|
+
await self.app(scope, receive, send)
|
|
58
|
+
return
|
|
59
|
+
if not authorized(headers, self.secret, request_token(headers, scope.get("query_string", b"")) or ""):
|
|
60
|
+
response = error(401, tr("Unauthorized"))
|
|
61
|
+
# A page navigation must reach the shell and its token dialog, not the browser's own prompt.
|
|
62
|
+
wants_html = "text/html" in headers.get("accept", "")
|
|
63
|
+
if headers.get("x-requested-with") != "Omokage" and not wants_html:
|
|
64
|
+
response.headers["WWW-Authenticate"] = 'Basic realm="Omokage"'
|
|
65
|
+
await response(scope, receive, send)
|
|
66
|
+
return
|
|
67
|
+
await self.app(scope, receive, send)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def client_headers() -> dict[str, str]:
|
|
71
|
+
token = os.getenv("OMOKAGE_ACCESS_TOKEN")
|
|
72
|
+
return {"Authorization": "Bearer " + token} if token else {}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def local(request: Request) -> None:
|
|
76
|
+
if not request.client or request.client.host not in ("127.0.0.1", "::1", "localhost"):
|
|
77
|
+
raise HTTPException(403, tr("Local filesystem access requires a loopback connection"))
|
omokage/api/app.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
from collections.abc import AsyncGenerator
|
|
4
|
+
from contextlib import asynccontextmanager, suppress
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from fastapi import FastAPI
|
|
8
|
+
from starlette.exceptions import HTTPException
|
|
9
|
+
from starlette.responses import Response
|
|
10
|
+
from starlette.staticfiles import StaticFiles
|
|
11
|
+
from starlette.types import Scope
|
|
12
|
+
|
|
13
|
+
from omokage.api.access import AccessToken
|
|
14
|
+
from omokage.api.hosting import BrowserAccess, install_errors
|
|
15
|
+
from omokage.api.language import ApiLanguage
|
|
16
|
+
from omokage.api.routers.agent import hosts_router, monitor
|
|
17
|
+
from omokage.api.routers.agent import router as agent_router
|
|
18
|
+
from omokage.api.routers.datasets import router as datasets_router
|
|
19
|
+
from omokage.api.routers.experiments import router as experiments_router
|
|
20
|
+
from omokage.api.routers.jobs import router as jobs_router
|
|
21
|
+
from omokage.api.routers.library import router as library_router
|
|
22
|
+
from omokage.api.routers.operations import router as ops_router
|
|
23
|
+
from omokage.api.routers.outputs import router as outputs_router
|
|
24
|
+
from omokage.api.routers.presets import router as presets_router
|
|
25
|
+
from omokage.api.routers.queue import router as queue_router
|
|
26
|
+
from omokage.api.routers.storage import router as storage_router
|
|
27
|
+
from omokage.api.routers.system import router as system_router
|
|
28
|
+
from omokage.api.routers.tasks import router as tasks_router
|
|
29
|
+
from omokage.api.routers.training import router as training_router
|
|
30
|
+
from omokage.api.sockets import Notifications
|
|
31
|
+
from omokage.core.datasets.service import Datasets
|
|
32
|
+
from omokage.core.jobs.service import Jobs
|
|
33
|
+
from omokage.core.models.catalog import refresh_catalog
|
|
34
|
+
from omokage.core.training.experiments import Experiments
|
|
35
|
+
from omokage.core.training.service import Training
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def create_app(
|
|
39
|
+
data_dir: Path | None = None,
|
|
40
|
+
*,
|
|
41
|
+
token: str | None = None,
|
|
42
|
+
prefix: str = "",
|
|
43
|
+
hosts: set[str] | None = None,
|
|
44
|
+
agent_only: bool = False,
|
|
45
|
+
settings_path: Path | None = None,
|
|
46
|
+
overrides: dict | None = None,
|
|
47
|
+
) -> FastAPI:
|
|
48
|
+
@asynccontextmanager
|
|
49
|
+
async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
|
|
50
|
+
manager = app.state.service.manager
|
|
51
|
+
|
|
52
|
+
async def reap() -> None:
|
|
53
|
+
while True:
|
|
54
|
+
await asyncio.sleep(min(60, manager.idle_seconds) if manager.idle_seconds > 0 else 60)
|
|
55
|
+
await asyncio.to_thread(manager.unload, expired=True, default_idle=manager.idle_seconds if manager.idle_seconds > 0 else float("inf"))
|
|
56
|
+
|
|
57
|
+
from omokage.api.routers.agent import prune_blobs
|
|
58
|
+
|
|
59
|
+
await asyncio.to_thread(prune_blobs, app.state.service.path.parent / "agent-images")
|
|
60
|
+
|
|
61
|
+
async def reload_settings() -> None:
|
|
62
|
+
while True:
|
|
63
|
+
await asyncio.sleep(1)
|
|
64
|
+
if await asyncio.to_thread(app.state.service.config.reload):
|
|
65
|
+
scheduler = app.state.jobs.scheduler
|
|
66
|
+
with scheduler.lock:
|
|
67
|
+
scheduler.dispatch()
|
|
68
|
+
|
|
69
|
+
watcher = asyncio.create_task(reload_settings())
|
|
70
|
+
polling = asyncio.create_task(monitor(app))
|
|
71
|
+
task = asyncio.create_task(reap())
|
|
72
|
+
bridge = asyncio.create_task(notifications.stream())
|
|
73
|
+
try:
|
|
74
|
+
yield
|
|
75
|
+
finally:
|
|
76
|
+
watcher.cancel()
|
|
77
|
+
with suppress(asyncio.CancelledError):
|
|
78
|
+
await watcher
|
|
79
|
+
bridge.cancel()
|
|
80
|
+
with suppress(asyncio.CancelledError):
|
|
81
|
+
await bridge
|
|
82
|
+
await notifications.server.shutdown()
|
|
83
|
+
polling.cancel()
|
|
84
|
+
with suppress(asyncio.CancelledError):
|
|
85
|
+
await polling
|
|
86
|
+
if task:
|
|
87
|
+
task.cancel()
|
|
88
|
+
with suppress(asyncio.CancelledError):
|
|
89
|
+
await task
|
|
90
|
+
await asyncio.to_thread(app.state.training.close)
|
|
91
|
+
await asyncio.to_thread(app.state.jobs.close)
|
|
92
|
+
manager.unload()
|
|
93
|
+
manager.downloads.pool.shutdown(wait=True)
|
|
94
|
+
|
|
95
|
+
app = FastAPI(title="Omokage", lifespan=lifespan)
|
|
96
|
+
from omokage.api.routers.models import router as models_router
|
|
97
|
+
from omokage.api.routers.runs import router
|
|
98
|
+
from omokage.api.schema import document
|
|
99
|
+
from omokage.core.inference.service import InspectService
|
|
100
|
+
|
|
101
|
+
app.state.service = InspectService(data_dir, settings_path=settings_path, overrides=overrides)
|
|
102
|
+
token = token or os.getenv("OMOKAGE_ACCESS_TOKEN")
|
|
103
|
+
app.state.secret = (token or "").encode()
|
|
104
|
+
notifications = Notifications(app.state.service.config.events, app.state.secret)
|
|
105
|
+
if token:
|
|
106
|
+
app.add_middleware(AccessToken, token=token, prefix=prefix)
|
|
107
|
+
hosts = hosts if hosts is not None else set()
|
|
108
|
+
hosts.update(h.strip() for h in os.getenv("OMOKAGE_ALLOWED_HOSTS", "").split(",") if h.strip())
|
|
109
|
+
app.add_middleware(BrowserAccess, config=app.state.service.config, hosts=hosts)
|
|
110
|
+
install_errors(app)
|
|
111
|
+
app.add_middleware(ApiLanguage)
|
|
112
|
+
app.state.jobs = Jobs(app.state.service)
|
|
113
|
+
app.state.datasets = Datasets(app.state.service.path)
|
|
114
|
+
app.state.training = Training(app.state.datasets, app.state.service.manager, app.state.jobs.events)
|
|
115
|
+
app.state.experiments = Experiments(app.state.training)
|
|
116
|
+
app.state.host_status = {}
|
|
117
|
+
app.include_router(agent_router)
|
|
118
|
+
app.include_router(ops_router)
|
|
119
|
+
if not agent_only:
|
|
120
|
+
app.include_router(tasks_router)
|
|
121
|
+
app.include_router(experiments_router)
|
|
122
|
+
app.include_router(hosts_router)
|
|
123
|
+
app.include_router(datasets_router)
|
|
124
|
+
app.include_router(library_router)
|
|
125
|
+
app.include_router(jobs_router)
|
|
126
|
+
app.include_router(outputs_router)
|
|
127
|
+
app.include_router(presets_router)
|
|
128
|
+
app.include_router(queue_router)
|
|
129
|
+
app.include_router(training_router)
|
|
130
|
+
app.include_router(storage_router)
|
|
131
|
+
app.include_router(system_router)
|
|
132
|
+
app.include_router(router)
|
|
133
|
+
app.include_router(models_router)
|
|
134
|
+
app.get("/api/v1/models")(refresh_catalog)
|
|
135
|
+
app.mount("/socket.io", notifications.app, name="socket")
|
|
136
|
+
dist = Path(__file__).resolve().parents[1] / "webui" / "dist"
|
|
137
|
+
if dist.is_dir() and not agent_only:
|
|
138
|
+
app.mount("/", SPAStaticFiles(directory=dist, html=True), name="workbench")
|
|
139
|
+
document(app)
|
|
140
|
+
if prefix.strip("/"):
|
|
141
|
+
outer = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
|
142
|
+
outer.state = app.state
|
|
143
|
+
outer.mount("/" + prefix.strip("/"), app)
|
|
144
|
+
return outer
|
|
145
|
+
return app
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SPAStaticFiles(StaticFiles):
|
|
149
|
+
"""Hashed files under ``assets/`` are cached for a year; ``index.html`` is never cached, and a page
|
|
150
|
+
address that accepts HTML falls back to it (the workbench routes by hash)."""
|
|
151
|
+
|
|
152
|
+
async def get_response(self, path: str, scope: Scope) -> Response:
|
|
153
|
+
try:
|
|
154
|
+
response = await super().get_response(path, scope)
|
|
155
|
+
except HTTPException as e:
|
|
156
|
+
if e.status_code != 404 or not self._accepts_html(scope):
|
|
157
|
+
raise
|
|
158
|
+
response = await super().get_response("index.html", scope)
|
|
159
|
+
if path.startswith("assets/") and response.status_code == 200:
|
|
160
|
+
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
|
161
|
+
else:
|
|
162
|
+
response.headers["Cache-Control"] = "no-cache"
|
|
163
|
+
return response
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _accepts_html(scope: Scope) -> bool:
|
|
167
|
+
return any(key == b"accept" and b"text/html" in value for key, value in scope.get("headers", []))
|
omokage/api/hosting.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from urllib.parse import urlsplit
|
|
2
|
+
|
|
3
|
+
from fastapi import FastAPI, Request
|
|
4
|
+
from fastapi.encoders import jsonable_encoder
|
|
5
|
+
from fastapi.exceptions import RequestValidationError
|
|
6
|
+
from starlette.datastructures import Headers
|
|
7
|
+
from starlette.exceptions import HTTPException
|
|
8
|
+
from starlette.middleware.cors import CORSMiddleware
|
|
9
|
+
from starlette.responses import JSONResponse
|
|
10
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
11
|
+
|
|
12
|
+
from omokage.core.errors import DomainError, problem
|
|
13
|
+
from omokage.core.events import ClientStateChanged, DatasetsChanged, ExperimentsChanged, OutputsChanged, PresetsChanged, SettingsChanged
|
|
14
|
+
from omokage.core.i18n import tr
|
|
15
|
+
from omokage.core.jobs.scheduler import task_origin
|
|
16
|
+
from omokage.core.settings.service import Configuration
|
|
17
|
+
|
|
18
|
+
CHANGES = {
|
|
19
|
+
"presets": PresetsChanged,
|
|
20
|
+
"datasets": DatasetsChanged,
|
|
21
|
+
"projects": DatasetsChanged,
|
|
22
|
+
"outputs": OutputsChanged,
|
|
23
|
+
"experiments": ExperimentsChanged,
|
|
24
|
+
"client-state": ClientStateChanged,
|
|
25
|
+
"engines": SettingsChanged,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def error(status: int, message: str, detail: object = None, code: str = "") -> JSONResponse:
|
|
30
|
+
return JSONResponse(problem(status, message, detail, code), status_code=status)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def install_errors(app: FastAPI) -> None:
|
|
34
|
+
@app.exception_handler(DomainError)
|
|
35
|
+
async def domain_error(request: Request, exc: DomainError) -> JSONResponse:
|
|
36
|
+
return error(exc.status, str(exc), code=exc.code)
|
|
37
|
+
|
|
38
|
+
@app.exception_handler(HTTPException)
|
|
39
|
+
async def http_error(request: Request, exc: HTTPException) -> JSONResponse:
|
|
40
|
+
if isinstance(exc.__cause__, DomainError):
|
|
41
|
+
return await domain_error(request, exc.__cause__)
|
|
42
|
+
return error(exc.status_code, str(exc.detail), exc.detail)
|
|
43
|
+
|
|
44
|
+
@app.exception_handler(RequestValidationError)
|
|
45
|
+
async def validation(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
46
|
+
return error(422, str(exc), jsonable_encoder(exc.errors()), "invalid_request")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Origins(CORSMiddleware):
|
|
50
|
+
def __init__(self, app: ASGIApp, config: Configuration) -> None:
|
|
51
|
+
super().__init__(app, allow_methods=["*"], allow_headers=["*"], allow_credentials=True)
|
|
52
|
+
self.config = config
|
|
53
|
+
|
|
54
|
+
def is_allowed_origin(self, origin: str) -> bool:
|
|
55
|
+
return origin in self.config.value.allowed_origins
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class BrowserAccess:
|
|
59
|
+
def __init__(self, app: ASGIApp, config: Configuration, hosts: set[str]) -> None:
|
|
60
|
+
self.app, self.config, self.hosts = Origins(app, config), config, hosts
|
|
61
|
+
|
|
62
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
63
|
+
if scope["type"] not in ("http", "websocket"):
|
|
64
|
+
await self.app(scope, receive, send)
|
|
65
|
+
return
|
|
66
|
+
headers = Headers(scope=scope)
|
|
67
|
+
task_origin.set("web" if headers.get("x-requested-with") == "Omokage" else "cli" if headers.get("x-omokage-client") == "cli" else "api")
|
|
68
|
+
host = headers.get("host", "")
|
|
69
|
+
if self.hosts and urlsplit("//" + host).hostname not in self.hosts:
|
|
70
|
+
if scope["type"] == "websocket":
|
|
71
|
+
await send({"type": "websocket.close", "code": 1008})
|
|
72
|
+
return
|
|
73
|
+
await error(400, tr("Host not allowed"), code="bad_host")(scope, receive, send)
|
|
74
|
+
return
|
|
75
|
+
if scope.get("method") not in ("GET", "HEAD", "OPTIONS") or scope["path"].rstrip("/").endswith("/socket.io"):
|
|
76
|
+
scheme = {"ws": "http", "wss": "https"}.get(scope["scheme"], scope["scheme"])
|
|
77
|
+
origin = headers.get("origin")
|
|
78
|
+
if (origin and origin != f"{scheme}://{host}" and origin not in self.config.value.allowed_origins) or (not origin and headers.get("sec-fetch-site") == "cross-site"):
|
|
79
|
+
if scope["type"] == "websocket":
|
|
80
|
+
await send({"type": "websocket.close", "code": 1008})
|
|
81
|
+
return
|
|
82
|
+
await error(403, tr("Origin not allowed"), code="bad_origin")(scope, receive, send)
|
|
83
|
+
return
|
|
84
|
+
parts = scope["path"].partition("/api/v1/")[2].split("/")
|
|
85
|
+
domains = {
|
|
86
|
+
"presets": "presets",
|
|
87
|
+
"samples": "datasets",
|
|
88
|
+
"datasets": "datasets",
|
|
89
|
+
"projects": "projects",
|
|
90
|
+
"outputs": "outputs",
|
|
91
|
+
"engines": "engines",
|
|
92
|
+
"experiments": "experiments",
|
|
93
|
+
"client-state": "client-state",
|
|
94
|
+
}
|
|
95
|
+
if parts[0] in domains:
|
|
96
|
+
|
|
97
|
+
async def notify(message: Message) -> None:
|
|
98
|
+
if message["type"] == "http.response.start" and 200 <= message["status"] < 300:
|
|
99
|
+
change = CHANGES[domains[parts[0]]]
|
|
100
|
+
self.config.events.publish(change(keys=["engines"]) if change is SettingsChanged else change(path="/".join(parts)))
|
|
101
|
+
await send(message)
|
|
102
|
+
|
|
103
|
+
await self.app(scope, receive, notify)
|
|
104
|
+
return
|
|
105
|
+
await self.app(scope, receive, send)
|
omokage/api/language.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from starlette.datastructures import Headers, MutableHeaders
|
|
2
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
3
|
+
|
|
4
|
+
from omokage.core.i18n import current_locale, detect_locale
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def request_locale(header: str) -> str:
|
|
8
|
+
if not header:
|
|
9
|
+
return current_locale.get()
|
|
10
|
+
candidates = []
|
|
11
|
+
for entry in header.split(","):
|
|
12
|
+
tag, _, weight = entry.strip().partition(";")
|
|
13
|
+
try:
|
|
14
|
+
quality = float(weight.strip().removeprefix("q=")) if weight else 1
|
|
15
|
+
except ValueError:
|
|
16
|
+
continue
|
|
17
|
+
if 0 < quality <= 1:
|
|
18
|
+
candidates.append((quality, tag.strip()))
|
|
19
|
+
return detect_locale(max(candidates, key=lambda item: item[0])[1]) if candidates else "en"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ApiLanguage:
|
|
23
|
+
def __init__(self, app: ASGIApp) -> None:
|
|
24
|
+
self.app = app
|
|
25
|
+
|
|
26
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
27
|
+
if scope["type"] != "http" or not scope["path"].startswith("/api/"):
|
|
28
|
+
await self.app(scope, receive, send)
|
|
29
|
+
return
|
|
30
|
+
language = request_locale(Headers(scope=scope).get("accept-language", ""))
|
|
31
|
+
token = current_locale.set(language)
|
|
32
|
+
|
|
33
|
+
async def send_localized(message: Message) -> None:
|
|
34
|
+
if message["type"] == "http.response.start":
|
|
35
|
+
headers = MutableHeaders(scope=message)
|
|
36
|
+
headers["Content-Language"] = language
|
|
37
|
+
headers.add_vary_header("Accept-Language")
|
|
38
|
+
await send(message)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
await self.app(scope, receive, send_localized)
|
|
42
|
+
finally:
|
|
43
|
+
current_locale.reset(token)
|
|
File without changes
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from contextlib import AsyncExitStack
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import NamedTemporaryFile
|
|
8
|
+
from threading import Event
|
|
9
|
+
from time import time
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
|
|
14
|
+
|
|
15
|
+
from omokage.api.access import local
|
|
16
|
+
from omokage.api.routers.models import profile
|
|
17
|
+
from omokage.core.events import RemoteChanged
|
|
18
|
+
from omokage.core.i18n import tr
|
|
19
|
+
from omokage.core.inference.request import Backend, Options
|
|
20
|
+
from omokage.core.models.catalog import describe
|
|
21
|
+
from omokage.core.models.plugins import enabled, plugins
|
|
22
|
+
from omokage.runtime.compute import device_names
|
|
23
|
+
from omokage.runtime.engine import ENGINES
|
|
24
|
+
from omokage.runtime.readiness import model_readiness
|
|
25
|
+
from omokage.runtime.remote import AGENT_PROTOCOL, check_protocol, host_error, remote_call, remote_headers, remote_verify
|
|
26
|
+
|
|
27
|
+
router = APIRouter(prefix="/api/v1/agent")
|
|
28
|
+
hosts_router = APIRouter(prefix="/api/v1/remote")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def blob(request: Request, sha: str) -> Path:
|
|
32
|
+
if not re.fullmatch("[0-9a-f]{64}", sha):
|
|
33
|
+
raise HTTPException(422, tr("Invalid image digest"))
|
|
34
|
+
return request.app.state.service.path.parent / "agent-images" / sha
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@router.get("/info")
|
|
38
|
+
def info() -> dict:
|
|
39
|
+
"""What a host needs to route to this agent; readiness for one model comes from ``/readiness/{id}``.
|
|
40
|
+
|
|
41
|
+
Probes everything once (the monitor asks every few seconds), so it stays cheap: the readiness
|
|
42
|
+
check imports each engine's packages and queries the devices, which is why it lives per model.
|
|
43
|
+
"""
|
|
44
|
+
return {
|
|
45
|
+
"protocol": AGENT_PROTOCOL,
|
|
46
|
+
"engines": sorted(set(ENGINES) | set(plugins())),
|
|
47
|
+
"devices": device_names(),
|
|
48
|
+
"models": [m["id"] for m in describe() if m["installed"]],
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@router.get("/readiness/{model_id}")
|
|
53
|
+
def readiness(model_id: str, request: Request, backend: Backend = "auto") -> dict:
|
|
54
|
+
model = profile(model_id)
|
|
55
|
+
try:
|
|
56
|
+
enabled(model.parameters, request.app.state.service.config.value.engines.get(model.parameters, {}), model.template or model.id)
|
|
57
|
+
except ValueError as exc:
|
|
58
|
+
return {"ready": False, "state": "refused", "missing": [], "errors": {"policy": str(exc)}}
|
|
59
|
+
return model_readiness(model, backend) | {"installed": all((model.directory() / name).is_file() for name in model.files)}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@router.get("/heartbeat")
|
|
63
|
+
def heartbeat() -> dict:
|
|
64
|
+
return {"time": time(), "protocol": AGENT_PROTOCOL}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@router.post("/blobs/missing")
|
|
68
|
+
def missing(digests: list[str], request: Request) -> list[str]:
|
|
69
|
+
missing = []
|
|
70
|
+
now = time()
|
|
71
|
+
for key in dict.fromkeys(digests):
|
|
72
|
+
path = blob(request, key)
|
|
73
|
+
try:
|
|
74
|
+
stat = path.stat()
|
|
75
|
+
except FileNotFoundError:
|
|
76
|
+
missing.append(key)
|
|
77
|
+
continue
|
|
78
|
+
if now - stat.st_atime > 86400:
|
|
79
|
+
os.utime(path, ns=(int(now * 1e9), stat.st_mtime_ns))
|
|
80
|
+
return missing
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@router.put("/blobs/{sha}")
|
|
84
|
+
async def put_blob(sha: str, request: Request) -> dict:
|
|
85
|
+
path = blob(request, sha)
|
|
86
|
+
path.parent.mkdir(exist_ok=True)
|
|
87
|
+
digest = hashlib.sha256()
|
|
88
|
+
with NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
|
89
|
+
temp = Path(stream.name)
|
|
90
|
+
try:
|
|
91
|
+
async for chunk in request.stream():
|
|
92
|
+
stream.write(chunk)
|
|
93
|
+
digest.update(chunk)
|
|
94
|
+
if digest.hexdigest() != sha:
|
|
95
|
+
raise HTTPException(422, tr("Image checksum mismatch"))
|
|
96
|
+
stream.close()
|
|
97
|
+
temp.replace(path)
|
|
98
|
+
finally:
|
|
99
|
+
temp.unlink(missing_ok=True)
|
|
100
|
+
return {"sha256": sha}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@hosts_router.get("/hosts")
|
|
104
|
+
def hosts(request: Request, refresh: bool = False) -> dict:
|
|
105
|
+
status = request.app.state.host_status
|
|
106
|
+
for name, host in request.app.state.service.config.value.hosts.items():
|
|
107
|
+
if refresh or name not in status:
|
|
108
|
+
url = str(host.url).rstrip("/") + "/api/v1/agent/"
|
|
109
|
+
try:
|
|
110
|
+
with httpx.Client(verify=remote_verify(host.ca_file), headers=remote_headers(host.token_env), timeout=5) as client:
|
|
111
|
+
reply = client.get(url + "info", timeout=60)
|
|
112
|
+
reply.raise_for_status()
|
|
113
|
+
check_protocol(reply.json())
|
|
114
|
+
status[name] = {"online": True, "state": "online", **reply.json(), "last_seen": time()}
|
|
115
|
+
except (httpx.HTTPError, KeyError, OSError, ValueError) as exc:
|
|
116
|
+
status[name] = host_error(exc)
|
|
117
|
+
return {k: status[k] for k in request.app.state.service.config.value.hosts if k in status}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def monitor(app: FastAPI) -> None:
|
|
121
|
+
async with AsyncExitStack() as stack:
|
|
122
|
+
clients: dict[str | None, httpx.AsyncClient] = {}
|
|
123
|
+
while True:
|
|
124
|
+
for name, host in list(app.state.service.config.value.hosts.items()):
|
|
125
|
+
url = str(host.url).rstrip("/") + "/api/v1/agent/"
|
|
126
|
+
last = app.state.host_status.get(name, {})
|
|
127
|
+
try:
|
|
128
|
+
if host.ca_file not in clients:
|
|
129
|
+
clients[host.ca_file] = await stack.enter_async_context(httpx.AsyncClient(timeout=4, verify=remote_verify(host.ca_file)))
|
|
130
|
+
client = clients[host.ca_file]
|
|
131
|
+
headers = remote_headers(host.token_env)
|
|
132
|
+
reply = await client.get(url + "heartbeat", headers=headers)
|
|
133
|
+
reply.raise_for_status()
|
|
134
|
+
check_protocol(reply.json())
|
|
135
|
+
if not last.get("online") or last.get("url") != url:
|
|
136
|
+
reply = await client.get(url + "info", headers=headers, timeout=60)
|
|
137
|
+
reply.raise_for_status()
|
|
138
|
+
check_protocol(reply.json())
|
|
139
|
+
last = {"url": url, **reply.json()}
|
|
140
|
+
current = last | {"online": True, "state": "online", "last_seen": time()}
|
|
141
|
+
except (httpx.HTTPError, KeyError, OSError, ValueError) as exc:
|
|
142
|
+
current = host_error(exc) | {"last_seen": last.get("last_seen")}
|
|
143
|
+
app.state.host_status[name] = current
|
|
144
|
+
if current["online"] != last.get("online"):
|
|
145
|
+
app.state.service.config.events.publish(RemoteChanged(host=name, online=bool(current["online"])))
|
|
146
|
+
await asyncio.sleep(15)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def prune_blobs(directory: Path) -> None:
|
|
150
|
+
cutoff = time() - 30 * 86400
|
|
151
|
+
if directory.is_dir():
|
|
152
|
+
for path in directory.iterdir():
|
|
153
|
+
if path.is_file() and path.stat().st_atime < cutoff:
|
|
154
|
+
path.unlink(missing_ok=True)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@router.post("/load")
|
|
158
|
+
def load(body: Options, request: Request) -> dict:
|
|
159
|
+
model = profile(body.model)
|
|
160
|
+
service = request.app.state.service
|
|
161
|
+
enabled(model.parameters, service.config.value.engines.get(model.parameters, {}), model.template or model.id)
|
|
162
|
+
body.resolve()
|
|
163
|
+
device = service.manager.device(model, body)
|
|
164
|
+
with service.manager.lease(device, model.id, Event()) as slot:
|
|
165
|
+
if slot is None:
|
|
166
|
+
raise HTTPException(409, tr("Device is busy"))
|
|
167
|
+
engine = service.manager.load(slot, model, body, device)
|
|
168
|
+
return {"model": model.id, "device": device, "metadata": engine.metadata}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@hosts_router.post("/hosts/{name}/{action}", dependencies=[Depends(local)])
|
|
172
|
+
def control_host(name: str, action: Literal["load", "status", "unload", "release"], request: Request, options: Options) -> dict:
|
|
173
|
+
host = request.app.state.service.config.value.hosts.get(name)
|
|
174
|
+
if not host:
|
|
175
|
+
raise HTTPException(404, tr("Unknown remote host: {host}", host=name))
|
|
176
|
+
target = (str(host.url).rstrip("/"), host.token_env, host.ca_file)
|
|
177
|
+
method, path = {
|
|
178
|
+
"load": ("POST", "agent/load"),
|
|
179
|
+
"status": ("GET", "runtime"),
|
|
180
|
+
"unload": ("POST", "models/" + options.model + "/unload"),
|
|
181
|
+
"release": ("POST", "compute/" + options.device + "/release"),
|
|
182
|
+
}[action]
|
|
183
|
+
try:
|
|
184
|
+
return remote_call(target, method, path, options.model_dump() if action == "load" else None)
|
|
185
|
+
except (httpx.HTTPError, KeyError, OSError, ValueError) as exc:
|
|
186
|
+
raise HTTPException(502, str(exc)) from exc
|