File size: 2,461 Bytes
94e8fb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import random

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse

from src.api_models import (
    ResponseGuessWord, ResponseSemanticCalculation,
    RequestSemanticCalculation, ResponseMessage,
    SemanticCalculation
)
from src.setting import AVAILABLE_WORDS, CFG
from src.vector_db import VectorDatabaseHandler

router = APIRouter()

DEFAULT_RESPONSES = {
    500: {"description": "Internal Server Error", "model": ResponseMessage},
}


@router.get(
    "/v1/service/status",
    response_model=ResponseMessage,
    responses={**DEFAULT_RESPONSES},
    description="Description: The endpoint is used to check the service status.",
    tags=["Service Status"]
)
async def status() -> ResponseMessage:
    """Health endpoint."""
    return ResponseMessage(message="Success.")


@router.get(
    "/v1/service/get_guess_word",
    response_model=ResponseGuessWord,
    responses={**DEFAULT_RESPONSES},
    description="Description: The endpoint is used to get a random word from the list of available words.",
    tags=["Get Word"]
)
async def get_guess_word() -> ResponseGuessWord:
    try:
        guess_word = random.choices(AVAILABLE_WORDS, k=1)[0]
    except Exception as e:
        return JSONResponse(status_code=500, content={"message": str(e)})
    return ResponseGuessWord(word=guess_word)


@router.get(
    "/v1/service/semantic_calculation",
    response_model=ResponseSemanticCalculation,
    responses={**DEFAULT_RESPONSES},
    description="Description: The endpoint is used to calculate the semantic similarity between the guessed word \
    and the supposed word.",
    tags=["Semantic Analysis"]
)
async def semantic_calculation(
    request: RequestSemanticCalculation = Depends(RequestSemanticCalculation)
) -> ResponseGuessWord:
    supposed_word = request.supposed_word
    guessed_word = request.guessed_word

    if supposed_word not in AVAILABLE_WORDS:
        return ResponseSemanticCalculation(
            word_exist=False,
            metadata=None
        )

    vector_db = VectorDatabaseHandler(
        db_path=CFG.db.folder_path,
        table_name=CFG.db.table_name,
        metrics_cfg=CFG.db.metrics
    )

    try:
        result = vector_db(guessed_word, supposed_word)
    except Exception as e:
        return JSONResponse(status_code=500, content={"message": str(e)})
    return ResponseSemanticCalculation(
        word_exist=True,
        metadata=SemanticCalculation(**result)
    )