๋ฐ์ํ
FastAPI๋ฅผ ์ด์ฉํ API ์์ฑ
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, Depends, File, Request
import uvicorn
app = FastAPI()
class InputData(BaseModel):
data: str
@app.on_event("startup")
async def load_ai_model():
global model
model = My_Model()
print("AI Model Loaded")
async def parse_body(request: Request):
data: bytes = await request.body()
return data
@app.post("/model_inference_str_input/")
def AI_model_inference(input: InputData):
output = model(input.data)
return output
@app.post("/model_inference_bytes_input/")
def AI_model_inference_2(image_bytes: bytes = Depends(parse_body)):
output = model(image_bytes)
return output
if __name__ == "__main__":
uvicorn.run(app, host="localhost", port=8000)
API๋ฅผ ๋ง๋ค ๋ ์ ๋ ฅ์ผ๋ก ํ์ผ ๊ฒฝ๋ก(๋ฌธ์์ด)๋ฅผ ๋ฐ๊ณ ์ถ์ ์๋ ์๊ณ Bytes ํฌ๋งท์ ๋ณ์๋ฅผ ๋ฐ๊ณ ์ถ์ ์๋ ์๋ค.
- load_ai_model : 'on_event' ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ์ฌ ์๋ฒ๊ฐ ์์๋ ๋ ํธ์ถํ์ฌ AI ๋ชจ๋ธ์ ๋ฏธ๋ฆฌ ๋ถ๋ฌ์จ๋ค
- AI_model_inference : ํ์ผ ๊ฒฝ๋ก(๋ฌธ์์ด)์ ์ ๋ ฅ๋ฐ๋ ํจ์
- AI_model_inference_2 : Bytes ๋ณ์๋ฅผ ์ ๋ ฅ๋ฐ๋ ํจ์
uvicorn.run()์ ์ฌ์ฉํ์ฌ ์๋ฒ๋ฅผ ์คํํ๋ฉฐ, ์ด๋ฅผ ์คํํ๋ฉด API๊ฐ http://localhost:8000 ์ฃผ์์์ ์คํ๋๋ค.
์ด์ ์๋ฒ๋ฅผ ์คํํ๊ณ http://localhost:8000/docs๋ก ์ด๋ํ์ฌ ์๋ ์์ฑ๋ API ๋ฌธ์์์ ๋ ์๋ํฌ์ธํธ์ ๋ํ ์์ธ ์ ๋ณด๋ฅผ ํ์ธํ ์ ์๋ค. ๋ํ API ๋ฌธ์๋ฅผ ํตํด ์ ๋ ฅ ๋ฐ์ดํฐ์ ํ์๊ณผ ์์ฒญ ๋ฐฉ๋ฒ์ ํ์ธํ๊ณ ํ ์คํธํ ์ ์๋ค.
ํ์ผ ๊ฒฝ๋ก(๋ฌธ์์ด)๋ฅผ ์ ๋ ฅํ๋ API ํธ์ถ
import requests
import numpy as np
url = 'http://localhost:8000/model_inference_str_input/'
input_image_path = 'image.jpg'
response = requests.post(url, json={'data': input_image_path})
if response.status_code == 200:
result = response.json()
print(result)
else:
print("API ํธ์ถ ์คํจ:", response.text)
Bytes ๋ณ์๋ฅผ ์ ๋ ฅํ๋ API ํธ์ถ
import requests
import numpy as np
url = 'http://localhost:8000/model_inference_bytes_input/'
input_image_path = 'image.jpg'
# ์ด๋ฏธ์ง ํ์ผ์ ๋ฐ์ดํธ ํํ๋ก ์ฝ์ด์ต๋๋ค.
with open(input_image_path, "rb") as image_file:
image_bytes = image_file.read()
response = requests.post(url, data = image_bytes)
if response.status_code == 200:
result = response.json()
print(result)
else:
print("API ํธ์ถ ์คํจ:", response.text)
๋ฐ์ํ