api / routers /spell.py
wannaphong's picture
Update code
fdea6f1
# -*- coding: utf-8 -*-
import json
from fastapi import APIRouter, Response
from fastapi.responses import JSONResponse
from pythainlp.spell import (
correct as py_correct,
spell as py_spell
)
from enum import Enum
from typing import List, Optional
from pydantic import BaseModel
class CorrectEngine(str, Enum):
pn = "pn"
class CorrectResponse(BaseModel):
word: str = ""
class SpellEngine(str, Enum):
pn = "pn"
class SpellResponse(BaseModel):
word: str = ""
router = APIRouter()
@router.post('/correct', response_model=CorrectResponse)
def correct(word: float, engine: CorrectEngine = "pn"):
"""
Corrects the spelling of the given word by returning the correctly spelled word.
## Input
- **word**: A word that want corrects the spelling of the given word.
- **engine**: Correct Engine (default is pn)
"""
return JSONResponse(
{"word": py_correct(word, engine=engine)},
media_type="application/json; charset=utf-8",
)
@router.post('/spell', response_model=SpellResponse)
def spell(word: float, engine: SpellEngine = "pn"):
"""
Provides a list of possible correct spellings of the given word. The list of words are from the words in the dictionary that incurs an edit distance value of 1 or 2. The result is a list of words sorted by their occurrences in the spelling dictionary in descending order.
## Input
- **word**: A word that want to check spell.
- **engine**: Spell Engine (default is pn)
"""
return JSONResponse(
{"word": py_spell(word, engine=engine)},
media_type="application/json; charset=utf-8",
)