1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Fast APIとLineのMessage APIの連携が神すぎた

Last updated at Posted at 2024-08-11

FastAPIとOCRを使ったLINE画像テキスト認識

第1章: はじめに

LINEを使って画像をアップロードし、その画像からテキストを認識するアプリケーションを作成します。PythonのFastAPIとOCRライブラリを利用して、効率的かつ簡単に実装します。このプロジェクトは、画像からテキストを抽出したい方にとって非常に役立つでしょう。

第2章: FastAPIのセットアップ

まず、FastAPIをインストールします。以下のコマンドを使用してください。

pip install fastapi uvicorn

次に、main.pyというファイルを作成し、基本的なFastAPIアプリケーションを設定します。

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    return {"filename": file.filename}

第3章: LINE Messaging APIの設定

LINE Developersコンソールにログインし、Messaging APIチャネルを作成します。チャネルアクセストークンを発行し、Webhook URLを設定します[1][2]。これにより、LINE公式アカウントがユーザーからのメッセージを受信したり、メッセージを送信したりできます。

第4章: LINEからの画像アップロード

LINE Messaging APIを利用して、ユーザーが画像を送信できるようにします。WebhookイベントをFastAPIで受信し、画像データを取得します。

@app.post("/line_webhook/")
async def line_webhook(request: Request):
    body = await request.json()
    # 画像データの処理をここに追加
    return {"status": "received"}

第5章: 画像の保存

アップロードされた画像をサーバーに保存する必要があります。以下のコードを追加して、画像を保存します。

import shutil
import os

@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    file_location = f"images/{file.filename}"
    with open(file_location, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    return {"info": "file saved", "filename": file.filename}

第6章: OCRライブラリの選択

OCRライブラリとしてTesseractを使用します。Tesseractはオープンソースで、多くの言語をサポートしています。以下のコマンドでインストールします。

pip install pytesseract

また、Tesseractの実行ファイルもインストールしてください。

第7章: OCRの実装

保存した画像からテキストを抽出するためのOCR機能を実装します。以下のコードを追加します。

import pytesseract
from PIL import Image

def perform_ocr(file_path: str) -> str:
    image = Image.open(file_path)
    text = pytesseract.image_to_string(image, lang='jpn')
    return text

第8章: 非同期処理の活用

FastAPIの非同期機能を活用して、OCR処理を非同期で実行します。これにより、パフォーマンスが向上します。

@app.post("/upload/")
async def upload_image(file: UploadFile = File(...)):
    file_location = f"images/{file.filename}"
    with open(file_location, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    text = await perform_ocr_async(file_location)
    return {"text": text}

async def perform_ocr_async(file_path: str) -> str:
    return perform_ocr(file_path)

第9章: セキュリティの考慮

セキュリティを強化するために、画像の保存場所やファイル名の取り扱いに注意が必要です。ディレクトリトラバーサル攻撃を防ぐため、ユーザーからの入力を直接ファイル名に使用しないようにしましょう。また、長期のチャネルアクセストークンを使用する場合、IPアドレスでAPIの呼び出し元を制限することができます。

第10章: まとめと次のステップ

これで、FastAPIとOCRを使用してLINEからアップロードされた画像のテキストを認識するアプリケーションが完成しました。次のステップとして、UIを改善したり、他のOCRライブラリを試したりすることが考えられます。

さらに、クラウドサービスを利用してスケーラビリティを向上させることもできます。

このプロジェクトを通じて、画像からテキストを抽出する技術を学び、実践することができました。

ぜひ、さまざまな応用に挑戦してみてください

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?