はじめに
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の一覧が表示されます.
右上の Try it out
をクリックして text
に適当な英文を入力します.
下の方に long time ago,
で始まるGPTの生成文が5つ表示されます.
おわりに
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