|
| 1 | +from fastapi import APIRouter, Query, HTTPException |
| 2 | +from pythainlp import word_vector |
| 3 | +from enum import Enum |
| 4 | +from typing import List, Optional |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +router = APIRouter() |
| 8 | + |
| 9 | + |
| 10 | +class MostSimilarCosmulWord(BaseModel): |
| 11 | + word: str |
| 12 | + score: float |
| 13 | + |
| 14 | + |
| 15 | +class DoesntMatchResponse(BaseModel): |
| 16 | + doesnt_match: str = "" |
| 17 | + |
| 18 | + |
| 19 | +class MostSimilarCosmulResponse(BaseModel): |
| 20 | + most_similar_cosmul: List[MostSimilarCosmulWord] = [] |
| 21 | + |
| 22 | + |
| 23 | +class SentenceVectorizerResponse(BaseModel): |
| 24 | + sentence_vectorizer: List[List[float]] = [] |
| 25 | + |
| 26 | + |
| 27 | +class SimilarityResponse(BaseModel): |
| 28 | + similarity: float = -1 |
| 29 | + |
| 30 | + |
| 31 | +@router.get('/doesnt-match', response_model=DoesntMatchResponse) |
| 32 | +def doesnt_match(words: List[str] = Query(None)): |
| 33 | + try: |
| 34 | + return {"doesnt_match": word_vector.doesnt_match(words)} |
| 35 | + except Exception as e: |
| 36 | + raise HTTPException(status_code=500, detail=str(e).replace("\"", "")) |
| 37 | + |
| 38 | + |
| 39 | +@router.get('/most-similar-cosmul', response_model=MostSimilarCosmulResponse) |
| 40 | +def most_similar_cosmul(listPositive: List[str] = Query([]), listNegative: List[str] = Query([])): |
| 41 | + try: |
| 42 | + words = word_vector.most_similar_cosmul(listPositive, listNegative) |
| 43 | + res = [{"word": word, "score": score} for word, score in words] |
| 44 | + return {"most_similar_cosmul": res} |
| 45 | + except Exception as e: |
| 46 | + raise HTTPException(status_code=500, detail=str(e).replace("\"", "")) |
| 47 | + |
| 48 | + |
| 49 | +@router.get('/sentence-vectorizer', response_model=SentenceVectorizerResponse) |
| 50 | +def sentence_vectorizer(q: str = ""): |
| 51 | + try: |
| 52 | + vector = word_vector.sentence_vectorizer(q, use_mean=True).tolist() |
| 53 | + return {"sentence_vectorizer": vector} |
| 54 | + except Exception as e: |
| 55 | + raise HTTPException(status_code=500, detail=str(e).replace("\"", "")) |
| 56 | + |
| 57 | + |
| 58 | +@router.get('/similarity', response_model=SimilarityResponse) |
| 59 | +def similarity(word1: str = "", word2: str = ""): |
| 60 | + try: |
| 61 | + return {"similarity": word_vector.similarity(word1, word2)} |
| 62 | + except Exception as e: |
| 63 | + raise HTTPException(status_code=500, detail=str(e).replace("\"", "")) |
0 commit comments