| 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) |
| ) |
|
|