Download src/discerna/server.py from CrazyH0rse/Discerna-v1-475M: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/server.py
- Command line
-
hf download hf://CrazyH0rse/Discerna-v1-475M/src/discerna/server.py
-
curl -L -o server.py https://huggingface.co/CrazyH0rse/Discerna-v1-475M/resolve/main/src/discerna/server.py
1.64 kB
| """An HTTP server for a Discerna model: `POST /v1/decide` takes a request and returns its answers. | |
| discerna serve --model <owner>/Discerna-v1-475M # or a local model folder | |
| Errors: a request beyond the model's limits is HTTP 413 with "unsupported" in the body, an invalid | |
| body is 422, anything else is 500. | |
| """ | |
| from __future__ import annotations | |
| import threading | |
| from fastapi import FastAPI, HTTPException | |
| from discerna import __version__ | |
| from discerna.contract import DecisionRequest | |
| from discerna.engine import Discerna, Unsupported | |
| def create_app(model: Discerna) -> FastAPI: | |
| app = FastAPI(title="Discerna", version=__version__) | |
| lock = threading.Lock() # one forward pass at a time: torch models are not thread-safe | |
| def healthz() -> dict: | |
| return {"ok": True} | |
| def models() -> dict: | |
| return {"data": [{"id": model.name, "modalities": ["text", "image"] if model.accepts_images else ["text"], | |
| "device": str(model.device), "dtype": str(model.dtype).removeprefix("torch.")}]} | |
| def decide(request: DecisionRequest) -> dict: | |
| with lock: | |
| result = model.decide_batch([request])[0] | |
| if isinstance(result, Unsupported): | |
| raise HTTPException(status_code=413, detail={"error": "unsupported", "reason": str(result)}) | |
| if isinstance(result, Exception): | |
| raise HTTPException(status_code=500, detail={"error": type(result).__name__, "reason": str(result)}) | |
| return result.model_dump(mode="json", exclude_none=True) | |
| return app | |