-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtrans_api.py
executable file
·56 lines (44 loc) · 1.58 KB
/
trans_api.py
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
from fastapi import Query,Body,FastAPI
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from api.PYtranslator import google_translator
from api import constant
from langdetect import detect,DetectorFactory
import time
DetectorFactory.seed = 0
app=FastAPI(description='Tranlating API for Reduct Nepal')
class Text(BaseModel):
text:str
lang:str
class Config:
extra_schema={
'example':{
'text':'Hello world this is a test text to be translated',
'lang':'en'
}
}
@app.get('/codes',response_class=JSONResponse)
async def get_codes()-> str:
return constant.LANGUAGES
async def translate_munche(sentence:str,lang:str) -> dict:
result_lang = detect(sentence)
try:
if result_lang == lang:
return {"Detected language":result_lang,"translated_text":sentence}
else:
try:
translator = google_translator()
translated = await translator.translate(sentence,lang_src=str(result_lang),lang_tgt=str(lang))
final_output = {"Detected language":result_lang,"translated_text":translated}
return final_output
except Exception as e:
print(e)
except Exception as e:
print(e)
@app.post('/translate')
async def translate(text:Text):
start = time.time()
_tobe_translated = (text.dict())['text']
langugae = (text.dict())['lang']
final_output = await translate_munche(_tobe_translated,langugae)
return JSONResponse(final_output)