bukosabino / bukosabino/scoring-handler

Use of automatic data validation (based on Pydantic)

Open
#1 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
HTML
Stars
1
Forks
0
PR merge metrics
No merged PRs in 30d

Description

In order to use one of the most important features of `FastAPI`, I would like to use `Pydantic` to define some data schemas for input data and output data.

Draft code on a `schemas.py` file (probably on [utils repository](https://github.com/bukosabino/scoring-handler-utils)):

```python
from pydantic import BaseModel, Field

class IrisFeatures(BaseModel):
sepal_length: float = Field(
..., ge=0, description="sepal length in cm"
)
sepal_width: float = Field(
..., ge=0, description="sepal width in cm"
)
petal_length: float = Field(
..., ge=0, description="petal length in cm"
)
petal_width: float = Field(
..., ge=0, description="petal width in cm"
)

class IrisTarget(BaseModel):
type: int = Field(
...,
ge=0,
le=2,
description="type of iris plant: 0 -> setosa; 1 -> versicolour; 2 -> virginica",
)
```

So, we would have automatic data validation that can detect any invalid data type at the runtime and returns the reason for bad inputs to the user in the JSON format. Also, `FastAPI` provides automatic serialization/deserialization.

Draft code on `async/app/main.py`:

```python
@app.post("/api/v1/ml/async/predict", response_model=IrisTarget)
async def predict(input_data: IrisFeatures):
"""Asynchronous prediction"""
input_data = [*input_data.dict().values()]
input_data = np.array(input_data).reshape(1, -1)
prediction = await ML_MODEL.predict(input_data)
output = IrisTarget(type=prediction)
return output
```

Some examples of input/outputs:

input:
```
{
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}
```

output:
```
200
{
"type": 0
}
```

input:
```
{
"sepal_length": -5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}
```

output:
```
422 | Error: Unprocessable Entity
{
"detail": [
{
"loc": [
"body",
"sepal_length"
],
"msg": "ensure this value is greater than or equal to 0",
"type": "value_error.number.not_ge",
"ctx": {
"limit_value": 0
}
}
]
}
```

input:
```
{
"invent_key": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2
}
```

output:
```
422 | Error: Unprocessable Entity
{
"detail": [
{
"loc": [
"body",
"sepal_length"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.