
【保存版】OCR APIを作ってRapidAPIで販売するまで
はじめに
「画像からテキストを抽出したい」
名刺、レシート、書類……画像からテキストを抜き出したい場面は多いです。
今回は、Claude Vision を使って画像からテキストを抽出するAPIを作り、RapidAPIで販売するまでを書きます。
完成したもの
OCR API として公開しました。
画像からテキストを抽出
日本語・英語対応
表はMarkdown形式で構造化
無料枠 100リクエスト/月
技術スタック
| 用途 | 技術 |
|---|---|
| 言語 | Python 3.12 |
| フレームワーク | FastAPI |
| OCR | Claude Vision (Anthropic) |
| デプロイ | Render |
| 販売 | RapidAPI |
実装
画像のBase64エンコード
import base64
import io
from PIL import Image
def image_to_base64(image_bytes):
img = Image.open(io.BytesIO(image_bytes))
if max(img.size) > 1568:
ratio = 1568 / max(img.size)
new_size = (int(img.size[0] * ratio), int(img.size[1] * ratio))
img = img.resize(new_size)
buf = io.BytesIO()
img.save(buf, format="PNG")
return base64.b64encode(buf.getvalue()).decode()Claude VisionでOCR
python
from anthropic import Anthropic
client = Anthropic(api_key=settings.anthropic_api_key)
def extract_text_from_image(image_bytes, language="auto"):
b64 = image_to_base64(image_bytes)
msg = client.messages.create(
model="claude-haiku-4-5",
max_tokens=2048,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
{"type": "text", "text": "画像内のすべてのテキストを抽出してください。"},
],
}],
)
return msg.content[0].textAPIエンドポイント
python
@app.post("/v1/ocr")
async def ocr(
file: UploadFile = File(...),
language: str = Form("auto"),
):
image_bytes = await file.read()
text = extract_text_from_image(image_bytes, language)
return {"text": text}デプロイ
RenderにDockerでデプロイ。
RapidAPI出品
料金プラン:
プラン 月額 リクエスト数
Basic $0 100
Pro $9.99 5,000
Ultra $29.99 25,000
Mega $99.99 100,000
まとめ
FastAPI + Claude Vision で、個人でも高精度なOCR APIが作れます。
これで6つのAPIを公開しました。
引き続き、新しいAPIを作っていきます。