Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

main.py 1.1 KB

You have to be logged in to leave a comment. Sign In
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
  1. import asyncio
  2. from io import BytesIO
  3. from pathlib import Path
  4. import numpy as np
  5. from fastai.vision.all import PILImage, load_learner
  6. from fastapi import FastAPI, File
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from PIL import Image
  9. from src.eval_utils import resize_and_crop_center
  10. MODEL_PICKEL_PATH = Path('models/model_pickle_fastai.pkl').absolute()
  11. app = FastAPI()
  12. app.add_middleware(
  13. CORSMiddleware,
  14. allow_origins=["*"],
  15. allow_credentials=True,
  16. allow_methods=["*"],
  17. allow_headers=["*"],
  18. )
  19. async def setup_learner():
  20. learn = load_learner(MODEL_PICKEL_PATH)
  21. learn.dls.device = 'cpu'
  22. return learn
  23. @app.on_event("startup")
  24. async def startup_event():
  25. global learn
  26. tasks = [asyncio.ensure_future(setup_learner())]
  27. learn = (await asyncio.gather(*tasks))[0]
  28. @app.post("/analyze")
  29. async def analyze(image: bytes = File(...)):
  30. img = Image.open(BytesIO(image))
  31. img_cropped = resize_and_crop_center(img)
  32. img_cropped = PILImage(img_cropped)
  33. pred, *_ = learn.predict(img_cropped)
  34. pred = np.array(pred)
  35. resp = {'pred': pred.tolist()}
  36. return resp
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...