SinglePredictionInput

Bases: BaseModel

Model for single prediction input.

Attributes:
  • produit_recu (int) –

    The quantity of the received product.

  • temps_livraison (int) –

    The delivery time.

Source code in api/utils.py
45
46
47
48
49
50
51
52
53
54
class SinglePredictionInput(BaseModel):
    """
    Model for single prediction input.

    Attributes:
        produit_recu (int): The quantity of the received product.
        temps_livraison (int): The delivery time.
    """
    produit_recu: int
    temps_livraison: int

SinglePredictionOutput

Bases: BaseModel

Model for single prediction output.

Attributes:
  • prediction (int) –

    The predicted value.

Source code in api/utils.py
57
58
59
60
61
62
63
64
class SinglePredictionOutput(BaseModel):
    """
    Model for single prediction output.

    Attributes:
        prediction (int): The predicted value.
    """
    prediction: int

generate_token(to_encode)

Generate a JWT token.

Parameters:
  • to_encode (str) –

    The string to encode in the token.

Returns:
  • str

    The generated JWT token.

Source code in api/utils.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def generate_token(to_encode):
    """
    Generate a JWT token.

    Args:
        to_encode (str): The string to encode in the token.

    Returns:
        str: The generated JWT token.
    """
    load_dotenv()
    SECRET_KEY = os.environ.get("SECRET_KEY")
    ALGORITHM = "HS256"
    to_encode_dict = {"sub": to_encode}
    encoded_jwt = jwt.encode(to_encode_dict, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

get_model(run_name)

Load a model from a pickle file.

Parameters:
  • run_name (str) –

    The name of the model run.

Returns:
  • The loaded model.

Source code in api/utils.py
87
88
89
90
91
92
93
94
95
96
97
98
99
def get_model(run_name):
    """
    Load a model from a pickle file.

    Args:
        run_name (str): The name of the model run.

    Returns:
        The loaded model.
    """
    with open(f"api/{run_name}.pkl", 'rb') as file:
        loaded_model = pickle.load(file)
    return loaded_model

has_access(credentials=Depends(HTTPBearer())) async

Validates the access token provided in the request headers.

Parameters:
  • credentials (HTTPAuthorizationCredentials, default: Depends(HTTPBearer()) ) –

    The bearer token credentials.

Returns:
  • bool

    True if the user has access, otherwise raises HTTPException.

Raises:
  • HTTPException

    If the token is invalid or the user is not authorized.

Source code in api/utils.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
async def has_access(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
    """
    Validates the access token provided in the request headers.

    Args:
        credentials (HTTPAuthorizationCredentials): The bearer token credentials.

    Returns:
        bool: True if the user has access, otherwise raises HTTPException.

    Raises:
        HTTPException: If the token is invalid or the user is not authorized.
    """
    token = credentials.credentials
    load_dotenv()
    SECRET_KEY = os.environ.get("SECRET_KEY")
    ALGORITHM = "HS256"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
    except JWTError:
        raise credentials_exception
    if username == "admin":
        return True
    else:
        raise credentials_exception

predict_single(loaded_model, order)

Make a prediction using the loaded model and the input order.

Parameters:
  • loaded_model

    The pre-trained model.

  • order (SinglePredictionInput) –

    The input data for making the prediction.

Returns:
  • int

    The predicted value.

Source code in api/utils.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def predict_single(loaded_model, order):
    """
    Make a prediction using the loaded model and the input order.

    Args:
        loaded_model: The pre-trained model.
        order (SinglePredictionInput): The input data for making the prediction.

    Returns:
        int: The predicted value.
    """
    data = {'produit_recu': [order.produit_recu],
            'temps_livraison': [order.temps_livraison]}
    df_to_predict = pd.DataFrame(data)

    prediction = loaded_model.predict(df_to_predict)

    return prediction[0]