-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathmain.py
151 lines (123 loc) · 4.1 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import logging
import os
import traceback
from typing import Type, Optional, Any
import uvicorn
from fastapi import Depends, FastAPI, File, UploadFile, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.status import HTTP_401_UNAUTHORIZED
from load import get_predictor_class
from models import Payload
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# globals
PREDICTOR: Optional[Any] = None
USERS_DB = {}
# auth
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def verify(token: str = Depends(oauth2_scheme)):
try:
if token == os.getenv('BUDGET_TOKEN'):
return token
raise Exception
except Exception as e:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials with error {}".format(
str(e)),
headers={"WWW-Authenticate": "Bearer"},
)
@app.on_event("startup")
async def startup_event():
global PREDICTOR
global USERS_DB
# Setting auth creds
USERS_DB = {
'username': os.environ['BUDGET_USERNAME'],
'password': os.environ['BUDGET_PWD'],
}
try:
PREDICTOR_CLASS_PATH = os.getenv('BUDGET_PREDICTOR_PATH')
assert PREDICTOR_CLASS_PATH is not None
ENV_PREDICTOR_ENTRYPOINT = os.getenv('BUDGET_PREDICTOR_ENTRYPOINT',
'Predictor')
# Load predictor
predictor_class: Type[Any] = get_predictor_class(
PREDICTOR_CLASS_PATH, ENV_PREDICTOR_ENTRYPOINT)
PREDICTOR = predictor_class()
PREDICTOR.load()
except Exception as e:
logging.debug(f"Predictor class could not be loaded with: {str(e)}")
traceback.print_exc()
@app.get("/")
def health_check():
return {"I'm": "Alive!"}
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
global USERS_DB
if form_data.username == USERS_DB['username'] \
and form_data.password == USERS_DB['password']:
return {
"access_token": os.getenv('BUDGET_TOKEN'),
"token_type": "bearer"
}
raise HTTPException(
status_code=401, detail="Incorrect username or password")
@app.post("/predict/")
async def predict(request: Request,
_: str = Depends(verify)) -> Response:
global PREDICTOR
if PREDICTOR is None:
raise HTTPException(
status_code=500,
detail="The predictor could not be loaded. Please check the logs "
"for more detail.",
)
return await PREDICTOR.predict(request)
@app.post("/predict_image/")
async def predict_image(request: UploadFile = File(...),
_: str = Depends(verify)) -> Response:
"""
https://fastapi.tiangolo.com/tutorial/request-files/
:param request:
:return:
"""
global PREDICTOR
if PREDICTOR is None:
raise HTTPException(
status_code=500,
detail="The predictor could not be loaded. Please check the logs "
"for more detail.",
)
return await PREDICTOR.predict(request)
@app.post("/predict_dict/")
async def predict_dict(request: Payload,
_: str = Depends(verify)) -> Response:
"""
Request is Payload type which has a dict.
:param request:
:return:
"""
global PREDICTOR
if PREDICTOR is None:
raise HTTPException(
status_code=500,
detail="The predictor could not be loaded. Please check the logs "
"for more detail.",
)
return await PREDICTOR.predict(request)
if __name__ == "__main__":
os.environ['BUDGET_USERNAME'] = 'username'
os.environ['BUDGET_PWD'] = 'password'
os.environ['BUDGET_TOKEN'] = 'token'
uvicorn.run(app, host="0.0.0.0", port=8000)