๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป Programming/Python

[python] FastAPI๋กœ ๋”ฅ๋Ÿฌ๋‹ ๋ชจ๋ธ API ๊ตฌ์ถ•ํ•˜๊ธฐ | ๋ฌธ์ž์—ด ํŒŒ์ผ๊ฒฝ๋กœ, Bytes ํƒ€์ž… ์ž…๋ ฅ๋ฐ›๊ธฐ

by ๋ญ…์ฆค 2023. 8. 3.
๋ฐ˜์‘ํ˜•

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)
๋ฐ˜์‘ํ˜•