-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
87 lines (71 loc) · 2.16 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
import os
import tempfile
from dotenv import load_dotenv
# from typing import Union
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from predict.predict import Model
from service.gcloud_storage import get_model
load_dotenv()
app = FastAPI()
def model():
model_path = get_model()
load_model = Model(model_path)
return load_model
@app.get("/")
async def read_root():
return JSONResponse(
content={"error": False, "message": "ML Prediction API is running!"},
status_code=200,
)
@app.post("/predict")
def predict(
video: UploadFile = File(media_type=["video/mp4", "video/x-m4v", "video/*"])
):
try:
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
tmp_file.write(video.file.read())
print(f"This is the temp file path: {tmp_file.name}")
tmp_file.close()
lm = model()
result = lm.process_video(tmp_file.name)
return JSONResponse(
content={
"error": False,
"message": "Prediction successful!",
"data": result,
},
status_code=200,
)
except Exception as e:
return JSONResponse(
content={"error": True, "message": "Prediction failed!", "data": str(e)},
status_code=500,
)
finally:
if os.path.exists(tmp_file.name):
os.remove(tmp_file.name)
@app.post("/init")
def init_model():
try:
get_model()
return JSONResponse(
content={
"error": False,
"message": "Model initialized!"},
status_code=200)
except Exception as e:
return JSONResponse(
content={
"error": True,
"message": "Model initialization failed!",
"data": str(e)},
status_code=500)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host=str(os.getenv("HOST")),
port=int(os.getenv("PORT")),
reload=True,
)