スペルチェックAPI
🔥 Vibe プロンプト
「FastAPIスペルチェックAPIを構築:単語を入力、編集距離で上位5件の候補を返す。」
構築するもの
DP編集距離アルゴリズムを実運用可能なFastAPIサービスにパッケージ化します。APIは単語を受け取り、辞書から最も近い候補を返します。
実装
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI(title="スペルチェックAPI", version="1.0.0")
DICTIONARY = [
"coding", "vibe", "tutor", "python", "algorithm",
"react", "nextjs", "docker", "kubernetes", "typescript",
"javascript", "tailwind", "fastapi", "postgres", "redis"
]
class SpellRequest(BaseModel):
word: str
top_k: int = 5
class Suggestion(BaseModel):
word: str
distance: int
class SpellResponse(BaseModel):
original: str
suggestions: List[Suggestion]
@app.post("/spell-check", response_model=SpellResponse)
def spell_check(req: SpellRequest):
"""スペルチェック:最も近い単語を返す"""
scored = [(w, edit_distance(req.word, w)) for w in DICTIONARY]
scored.sort(key=lambda x: x[1])
top = scored[:req.top_k]
return SpellResponse(
original=req.word,
suggestions=[Suggestion(word=w, distance=d) for w, d in top]
)
@app.get("/dictionary")
def get_dictionary():
"""辞書の全単語を表示"""
return {"words": DICTIONARY, "count": len(DICTIONARY)}
@app.post("/dictionary/add")
def add_word(word_data: SpellRequest):
"""辞書に単語を追加"""
if word_data.word not in DICTIONARY:
DICTIONARY.append(word_data.word)
return {"message": f"'{word_data.word}'を追加", "count": len(DICTIONARY)}
return {"message": f"'{word_data.word}'は既に存在"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
API応答例
curl -X POST http://localhost:8000/spell-check \
-H "Content-Type: application/json" \
-d '{"word": "codng", "top_k": 3}'
# 応答:
# {
# "original": "codng",
# "suggestions": [
# {"word": "coding", "distance": 1},
# {"word": "docker", "distance": 4},
# {"word": "vibe", "distance": 5}
# ]
# }
拡張アイデア
| 機能 | 実装方法 | |------|---------| | 多言語対応 | 言語別の辞書を追加 | | 自動学習 | 未知の単語をフラグして後で確認 | | 音声一致 | Soundex/Metaphoneをフォールバックとして追加 | | 一括チェック | 単語配列を受け付ける | | 文脈認識 | n-gram言語モデルで候補をランク付け |
まとめ
| 項目 | 詳細 |
|------|------|
| アルゴリズム | Levenshtein DP (O(m×n)/比較) |
| APIフレームワーク | FastAPI + Pydanticバリデーション |
| 辞書 | メモリ内リスト(本番では50K+単語) |
| 最適化 | BK-treeやtrieで大規模辞書を高速化 |
| デプロイ | uvicorn spell_check:app --host 0.0.0.0 --port 8000 |
DPコース完了!🎉
- ✅ DP核心(再帰+表形式)
- ✅ 0/1ナップサック
- ✅ 最長共通部分列(LCS)
- ✅ 編集距離(Levenshtein)
- ✅ スペルチェックAPI
- ✅ 計算量分析(空間/時間最適化)