[python] FastAPI로 딥러닝 모델 API 구축하기 | 문자열 파일경로, Bytes 타입 입력받기

2023. 8. 3. 09:27·💻 Programming/Python
반응형

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)
반응형

'💻 Programming > Python' 카테고리의 다른 글

[pandas] DataFrame 설명 | 데이터 조작, 필터링, 시각화, 통계 분석  (0) 2023.11.16
[pandas] 2차원 리스트를 데이터프레임으로 변환하기 | pd.DataFrame  (0) 2023.11.16
[python] 구글 검색 이미지 크롤링/스크래핑하기  (0) 2023.08.15
curl 커맨드를 python, javascript 등의 언어로 변환 | curl 커맨드 api를 파이썬 코드로 변환할 때  (0) 2023.07.11
[python] 반복문 효과적으로 디버깅하기: try-except 블록  (0) 2022.12.15
'💻 Programming/Python' 카테고리의 다른 글
  • [pandas] 2차원 리스트를 데이터프레임으로 변환하기 | pd.DataFrame
  • [python] 구글 검색 이미지 크롤링/스크래핑하기
  • curl 커맨드를 python, javascript 등의 언어로 변환 | curl 커맨드 api를 파이썬 코드로 변환할 때
  • [python] 반복문 효과적으로 디버깅하기: try-except 블록
뭅즤
뭅즤
AI 기술 블로그
    반응형
  • 뭅즤
    moovzi’s Doodle
    뭅즤
  • 전체
    오늘
    어제
  • 공지사항

    • ✨ About Me
    • 분류 전체보기 (213)
      • 📖 Fundamentals (34)
        • Computer Vision (9)
        • 3D vision & Graphics (6)
        • AI & ML (16)
        • NLP (2)
        • etc. (1)
      • 🏛 Research (75)
        • Deep Learning (7)
        • Perception (19)
        • OCR (7)
        • Multi-modal (5)
        • Image•Video Generation (18)
        • 3D Vision (4)
        • Material • Texture Recognit.. (8)
        • Large-scale Model (7)
        • etc. (0)
      • 🛠️ Engineering (8)
        • Distributed Training & Infe.. (5)
        • AI & ML 인사이트 (3)
      • 💻 Programming (92)
        • Python (18)
        • Computer Vision (12)
        • LLM (4)
        • AI & ML (18)
        • Database (3)
        • Distributed Computing (6)
        • Apache Airflow (6)
        • Docker & Kubernetes (14)
        • 코딩 테스트 (4)
        • C++ (1)
        • etc. (6)
      • 💬 ETC (4)
        • 책 리뷰 (4)
  • 링크

    • 리틀리 프로필 (멘토링, 면접책,...)
    • 『나는 AI 엔지니어입니다』
    • Instagram
    • Brunch
    • Github
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뭅즤
[python] FastAPI로 딥러닝 모델 API 구축하기 | 문자열 파일경로, Bytes 타입 입력받기
상단으로

티스토리툴바