main.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from typing import Optional
  2. from pydantic import BaseModel
  3. import numpy as np
  4. from fastapi import FastAPI
  5. import tensorflow as tf
  6. from tensorflow.keras.applications import InceptionV3
  7. from tensorflow.keras.applications.inception_v3 import preprocess_input, decode_predictions
  8. from tensorflow.keras.preprocessing import image
  9. IMG_SIZE = 299
  10. PREDICTION_MODEL = InceptionV3(weights='imagenet')
  11. def warm_up():
  12. img_path = f'./app/test.png'
  13. img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  14. x = image.img_to_array(img)
  15. x = np.expand_dims(x, axis=0)
  16. x = preprocess_input(x)
  17. PREDICTION_MODEL.predict(x)
  18. # Warm up model
  19. warm_up()
  20. app = FastAPI()
  21. class TagImagePayload(BaseModel):
  22. thumbnail_path: str
  23. @app.post("/tagImage")
  24. async def post_root(payload: TagImagePayload):
  25. imagePath = payload.thumbnail_path
  26. if imagePath[0] == '.':
  27. imagePath = imagePath[2:]
  28. img_path = f'./app/{imagePath}'
  29. img = image.load_img(img_path, target_size=(IMG_SIZE, IMG_SIZE))
  30. x = image.img_to_array(img)
  31. x = np.expand_dims(x, axis=0)
  32. x = preprocess_input(x)
  33. preds = PREDICTION_MODEL.predict(x)
  34. result = decode_predictions(preds, top=3)[0]
  35. payload = []
  36. for _, value, _ in result:
  37. payload.append(value)
  38. return payload