tempest_fastapi_sdk.vision¶
Inferência de visão computacional (extra [vision]): schemas, mappers e o serviço sobre o ort-vision-sdk.
vision
¶
Computer-vision inference integration (optional [vision] extra).
Wraps ort-vision-sdk <https://pypi.org/project/ort-vision-sdk/>_ — the
ONNX Runtime classification / detection / segmentation library — with the
FastAPI-facing layer it lacks: Pydantic response schemas and the mappers
that turn a result object into them.
The task classes (Classifier / Detector / Segmenter) are re-exported
lazily — accessing one imports ort-vision-sdk and raises a clear
ImportError (pointing at the [vision] extra) when it is missing.
The schemas and mappers carry no such dependency, so importing this module
is always safe.
from tempest_fastapi_sdk.utils import read_upload_capped
from tempest_fastapi_sdk.vision import Detector, to_detection_schemas
detector = Detector("yolov8n.onnx", labels="coco")
@router.post("/detect")
async def detect(file: UploadFile) -> list[DetectionSchema]:
data = await read_upload_capped(file, max_bytes=20 * 1024 * 1024)
results = (await detector.async_predict(data))[0]
return to_detection_schemas(results)
A hand-written route like this one still decodes whatever canvas the image
header declares; :func:make_vision_router also refuses images over
DEFAULT_MAX_IMAGE_PIXELS before decoding them.
DEFAULT_MAX_IMAGE_PIXELS
module-attribute
¶
Largest width * height :func:make_vision_router decodes (50 MP).
The byte ceiling does not bound memory for images: a PNG of flat colour
compresses by orders of magnitude. Measured with Pillow 13.0.0 and
ort-vision-sdk 0.12.0, a blank 9400 x 9400 PNG of 10 804 bytes decodes
into a 265 080 000-byte RGB array, without tripping Pillow's own
decompression-bomb warning (88.36 MP sits under its 89.48 MP threshold).
The dimensions are read from the header, before any pixel is decoded. 50 MP
covers a 50-megapixel phone photo (8160 x 6120); the models resize to a few
hundred pixels anyway.
DEFAULT_MAX_IMAGE_UPLOAD_BYTES
module-attribute
¶
Largest image upload :func:make_vision_router accepts, in bytes (20 MiB).
The whole upload is held in memory while it is decoded, so the ceiling is enforced while reading, not after.
AsyncVisionTask
¶
Bases: Protocol
Async vision task contract accepted by :func:make_vision_router.
Satisfied by ort-vision-sdk task objects (Classifier, Detector,
Segmenter) as well as custom or test doubles exposing
async_predict.
async_predict
¶
Run inference on encoded image bytes and return one or more results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
bytes
|
Encoded image bytes read from the upload. |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[Sequence[ResultT]]
|
Awaitable[Sequence[ResultT]]: Sequence whose first element is |
Awaitable[Sequence[ResultT]]
|
mapped into the HTTP response schema. |
BoundingBoxSchema
¶
Bases: BaseSchema
An axis-aligned box in pixel coordinates (top-left origin).
Attributes:
| Name | Type | Description |
|---|---|---|
x1 |
float
|
Left edge. |
y1 |
float
|
Top edge. |
x2 |
float
|
Right edge. |
y2 |
float
|
Bottom edge. |
ClassificationSchema
¶
Bases: BaseSchema
A classification result: the top label plus the ranked scores.
Attributes:
| Name | Type | Description |
|---|---|---|
class_id |
int
|
Top-1 class index. |
class_name |
str
|
Top-1 label. |
confidence |
float
|
Top-1 score in |
probabilities |
list[ClassProbabilitySchema]
|
The ranked scores (top-k), highest first. |
ClassProbabilitySchema
¶
Bases: BaseSchema
One class score from a classifier's ranked output.
Attributes:
| Name | Type | Description |
|---|---|---|
class_id |
int
|
Integer class index. |
class_name |
str
|
Human-readable label. |
probability |
float
|
Score in |
DetectClassifySchema
¶
Bases: BaseSchema
A detected object plus the second-stage classification of its crop.
The two stages have unrelated label spaces: a detector that finds
sheep may feed a classifier that answers famacha_3, and the two
share no class ids. That is why the classifier's verdict is nested
rather than flattened onto this object — class_id here is always
the detector's, and classification.class_id is always the
classifier's.
Attributes:
| Name | Type | Description |
|---|---|---|
class_id |
int
|
Detector class index. |
class_name |
str
|
Detector label. |
confidence |
float
|
Detection score in |
box |
BoundingBoxSchema
|
Object bounding box. |
classification |
ClassificationSchema | None
|
The classifier's
verdict on this object's crop, or |
DetectionSchema
¶
Bases: BaseSchema
A single detected object.
Attributes:
| Name | Type | Description |
|---|---|---|
class_id |
int
|
Integer class index. |
class_name |
str
|
Human-readable label. |
confidence |
float
|
Detection score in |
box |
BoundingBoxSchema
|
Object bounding box. |
SegmentationSchema
¶
Bases: BaseSchema
A single segmented instance (box + label; mask data omitted).
The raw mask is intentionally not serialized — returning a per-pixel
array in JSON is rarely what an API wants. Read it from the original
SegmentationResult.mask when you need the pixels.
Attributes:
| Name | Type | Description |
|---|---|---|
class_id |
int
|
Integer class index. |
class_name |
str
|
Human-readable label. |
confidence |
float
|
Instance score in |
box |
BoundingBoxSchema
|
Instance bounding box. |
to_classification_schema
¶
to_classification_schema(results: ClassificationResults) -> ClassificationSchema
Map a classifier result to a single :class:ClassificationSchema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
ClassificationResults
|
One element of
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
ClassificationSchema |
ClassificationSchema
|
The top-1 label plus the ranked scores. |
to_detect_classify_schemas
¶
to_detect_classify_schemas(
results: DetectClassifyResults,
) -> list[DetectClassifySchema]
Map a fused detect-classify result to a list of schemas.
Each detection carries its own second-stage verdict, so this returns
one entry per detected object with classification filled in.
DetectionResult.classification is a ClassificationResult — the
singular type, whose fields are class_id / class_name /
confidence. The plural ClassificationResults that
:func:to_classification_schema reads spells the same three
cls / name / conf, which is why the two mappers do not share
a helper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
DetectClassifyResults
|
One element of
|
required |
Returns:
| Type | Description |
|---|---|
list[DetectClassifySchema]
|
list[DetectClassifySchema]: One entry per detected object ( |
list[DetectClassifySchema]
|
when nothing was detected). |
to_detection_schemas
¶
to_detection_schemas(results: DetectionResults) -> list[DetectionSchema]
Map a detector result to a list of :class:DetectionSchema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
DetectionResults
|
One element of |
required |
Returns:
| Type | Description |
|---|---|
list[DetectionSchema]
|
list[DetectionSchema]: One entry per detected object ( |
list[DetectionSchema]
|
nothing was detected). |
to_segmentation_schemas
¶
to_segmentation_schemas(results: SegmentationResults) -> list[SegmentationSchema]
Map a segmenter result to a list of :class:SegmentationSchema.
Mask pixels are omitted (see :class:SegmentationSchema); only the
box + label of each instance are returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
SegmentationResults
|
One element of
|
required |
Returns:
| Type | Description |
|---|---|
list[SegmentationSchema]
|
list[SegmentationSchema]: One entry per segmented instance. |
make_vision_router
¶
make_vision_router(
*,
classifier: AsyncVisionTask[ClassificationResults] | None = None,
detector: AsyncVisionTask[DetectionResults] | None = None,
segmenter: AsyncVisionTask[SegmentationResults] | None = None,
prefix: str = "/api/vision",
tags: Sequence[str] | None = None,
max_upload_bytes: int = DEFAULT_MAX_IMAGE_UPLOAD_BYTES,
max_image_pixels: int | None = DEFAULT_MAX_IMAGE_PIXELS,
docs_locale: str | None = None,
) -> APIRouter
Build a router exposing only the injected vision tasks.
Every route reads the upload with
:func:~tempest_fastapi_sdk.utils.upload.read_upload_capped, checks the
declared pixel count from the image header, decodes the pixels in a
worker thread to refuse a truncated file, and only then runs the
model. An oversized upload answers 413 (UPLOAD_TOO_LARGE); a
canvas over max_image_pixels, bytes that are not an image, or a
truncated image answer 422, and so does an ImageLoadError
raised by ort-vision-sdk while decoding, which used to escape as a
500.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
classifier
|
AsyncVisionTask[ClassificationResults] | None
|
A loaded
|
None
|
detector
|
AsyncVisionTask[DetectionResults] | None
|
A loaded
|
None
|
segmenter
|
AsyncVisionTask[SegmentationResults] | None
|
A loaded
|
None
|
prefix
|
str
|
Route prefix. |
'/api/vision'
|
tags
|
Sequence[str] | None
|
OpenAPI tags (defaults to |
None
|
max_upload_bytes
|
int
|
Largest upload, in bytes. Defaults to
:data: |
DEFAULT_MAX_IMAGE_UPLOAD_BYTES
|
max_image_pixels
|
int | None
|
Largest |
DEFAULT_MAX_IMAGE_PIXELS
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When no task object is injected. |
ImportError
|
When |