LoginSignup
4
6

More than 1 year has passed since last update.

FastAPIを用いてテキスト生成APIを作る

Last updated at Posted at 2022-10-18

はじめに

FastAPIを用いてGPTによる文生成APIを作る方法です.

手順

まず,main.pyに以下を記述します.

# 事前にライブラリをインストール
# pip install fastapi
# pip install "uvicorn[standard]"
# pip install transformers

from fastapi import FastAPI
from transformers import pipeline

app = FastAPI()
# GPT2の読み込み (初回はモデルのダウンロードに時間がかかります)
generator = pipeline('text-generation', model='gpt2')

@app.get("/gpt/{text}")
async def read_item(text: str):
    gen_text = generator(text, max_length=30, num_return_sequences=5)
    return {"generated_text": gen_text}

次に,ターミナルで次のコマンドを実行します.

uvicorn main:app --reload --host 0.0.0.0 --port 8000

自分のPCで立ち上げた場合は http://localhost:8000/docs,LAN内の他のサーバで立ち上げた場合は <立ち上げたサーバのIPアドレス>:8000/docs にアクセスすると,以下のようにAPIの一覧が表示されます.
image.png

右上の Try it out をクリックして text に適当な英文を入力します.
image.png

下の方に long time ago, で始まるGPTの生成文が5つ表示されます.
image.png

おわりに

huggingfaceのtransformersライブラリのおかげで非常に簡単な記述で作れました.他にも画像認識APIや翻訳APIなどに応用できます.

追記

画像認識APIはこんな感じで実装できます.

from fastapi import FastAPI, UploadFile
from transformers import pipeline
import shutil

clf = pipeline("image-classification")
app = FastAPI()

@app.post("/images/")
def get_uploadfile(upload_file: UploadFile):
    path = upload_file.filename
    # アップロードされたファイルを保存
    with open(path, 'wb+') as buffer:
        shutil.copyfileobj(upload_file.file, buffer)
    # 保存した画像ファイルを読み込んで画像認識
    clf_result = clf(path)
    return clf_result

猫の画像をダウンロードしてきて試したところ,ちゃんと予測できていました.
image.png

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6