aziizpra's picture
Update app.py
0da6189
from pydantic import BaseModel
from fastapi import FastAPI, status
from starlette.responses import JSONResponse
from MachineTranslation import MachineTranslation
from utils import PROVIDED_LANGUAGES
from fastapi.middleware.cors import CORSMiddleware
import time
class RequestBody(BaseModel):
text: str
from_lang: str
to_lang: str
app = FastAPI()
machine_translation = MachineTranslation("facebook/nllb-200-distilled-1.3B")
origins = ['*']
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/predict")
async def predict(data_request: RequestBody):
if not data_request.text:
return JSONResponse({
"errors": "Please fill text!"
}, status_code=status.HTTP_400_BAD_REQUEST)
if len(data_request.text) > 5000:
return JSONResponse({
"errors": "The Number of Characters Exceeds The Limit"
}, status_code=status.HTTP_400_BAD_REQUEST)
if data_request.from_lang not in PROVIDED_LANGUAGES or data_request.to_lang not in PROVIDED_LANGUAGES:
return JSONResponse({
"errors": "Language not found!"
}, status_code=status.HTTP_400_BAD_REQUEST)
try:
# waktu prediksi
time_before = time.perf_counter()
result = machine_translation.predict(data_request.text, data_request.from_lang, data_request.to_lang)
time_after = time.perf_counter()
return JSONResponse({
"result": result,
"inference_time": time_after - time_before
}, status_code=status.HTTP_200_OK)
except Exception:
return JSONResponse({
"errors": "Please contact your administrator"
}, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)