Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,3 +1,171 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''
|
2 |
+
Created By Lewis Kamau Kimaru
|
3 |
+
Sema translator api backend
|
4 |
+
January 2024
|
5 |
+
Docker deployment
|
6 |
+
'''
|
7 |
|
8 |
+
from fastapi import FastAPI, HTTPException, Request
|
9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
10 |
+
from fastapi.responses import HTMLResponse
|
11 |
+
import gradio as gr
|
12 |
+
import ctranslate2
|
13 |
+
import sentencepiece as spm
|
14 |
+
import fasttext
|
15 |
+
import uvicorn
|
16 |
+
import pytz
|
17 |
+
from datetime import datetime
|
18 |
+
import os
|
19 |
+
|
20 |
+
app = FastAPI()
|
21 |
+
|
22 |
+
fasttext.FastText.eprint = lambda x: None
|
23 |
+
|
24 |
+
# Get time of request
|
25 |
+
|
26 |
+
def get_time():
|
27 |
+
nairobi_timezone = pytz.timezone('Africa/Nairobi')
|
28 |
+
current_time_nairobi = datetime.now(nairobi_timezone)
|
29 |
+
|
30 |
+
curr_day = current_time_nairobi.strftime('%A')
|
31 |
+
curr_date = current_time_nairobi.strftime('%Y-%m-%d')
|
32 |
+
curr_time = current_time_nairobi.strftime('%H:%M:%S')
|
33 |
+
|
34 |
+
full_date = f"{curr_day} | {curr_date} | {curr_time}"
|
35 |
+
return full_date, curr_time
|
36 |
+
|
37 |
+
# Load the model and tokenizer ..... only once!
|
38 |
+
beam_size = 1 # change to a smaller value for faster inference
|
39 |
+
device = "cpu" # or "cuda"
|
40 |
+
|
41 |
+
# Language Prediction model
|
42 |
+
print("\nimporting Language Prediction model")
|
43 |
+
lang_model_file = "lid218e.bin"
|
44 |
+
lang_model_full_path = os.path.join(os.path.dirname(__file__), lang_model_file)
|
45 |
+
lang_model = fasttext.load_model(lang_model_full_path)
|
46 |
+
|
47 |
+
|
48 |
+
# Load the source SentencePiece model
|
49 |
+
print("\nimporting SentencePiece model")
|
50 |
+
sp_model_file = "spm.model"
|
51 |
+
sp_model_full_path = os.path.join(os.path.dirname(__file__), sp_model_file)
|
52 |
+
sp = spm.SentencePieceProcessor()
|
53 |
+
sp.load(sp_model_full_path)
|
54 |
+
|
55 |
+
# Import The Translator model
|
56 |
+
print("\nimporting Translator model")
|
57 |
+
ct_model_file = "sematrans-3.3B"
|
58 |
+
ct_model_full_path = os.path.join(os.path.dirname(__file__), ct_model_file)
|
59 |
+
translator = ctranslate2.Translator(ct_model_full_path, device)
|
60 |
+
|
61 |
+
print('\nDone importing models\n')
|
62 |
+
|
63 |
+
|
64 |
+
def translate_detect(userinput: str, target_lang: str):
|
65 |
+
source_sents = [userinput]
|
66 |
+
source_sents = [sent.strip() for sent in source_sents]
|
67 |
+
target_prefix = [[target_lang]] * len(source_sents)
|
68 |
+
|
69 |
+
# Predict the source language
|
70 |
+
predictions = lang_model.predict(source_sents[0], k=1)
|
71 |
+
source_lang = predictions[0][0].replace('__label__', '')
|
72 |
+
|
73 |
+
# Subword the source sentences
|
74 |
+
source_sents_subworded = sp.encode(source_sents, out_type=str)
|
75 |
+
source_sents_subworded = [[source_lang] + sent + ["</s>"] for sent in source_sents_subworded]
|
76 |
+
|
77 |
+
# Translate the source sentences
|
78 |
+
translations = translator.translate_batch(
|
79 |
+
source_sents_subworded,
|
80 |
+
batch_type="tokens",
|
81 |
+
max_batch_size=2024,
|
82 |
+
beam_size=beam_size,
|
83 |
+
target_prefix=target_prefix,
|
84 |
+
)
|
85 |
+
translations = [translation[0]['tokens'] for translation in translations]
|
86 |
+
|
87 |
+
# Desubword the target sentences
|
88 |
+
translations_desubword = sp.decode(translations)
|
89 |
+
translations_desubword = [sent[len(target_lang):] for sent in translations_desubword]
|
90 |
+
|
91 |
+
# Return the source language and the translated text
|
92 |
+
return source_lang, translations_desubword
|
93 |
+
|
94 |
+
def translate_enter(userinput: str, source_lang: str, target_lang: str):
|
95 |
+
source_sents = [userinput]
|
96 |
+
source_sents = [sent.strip() for sent in source_sents]
|
97 |
+
target_prefix = [[target_lang]] * len(source_sents)
|
98 |
+
|
99 |
+
# Subword the source sentences
|
100 |
+
source_sents_subworded = sp.encode(source_sents, out_type=str)
|
101 |
+
source_sents_subworded = [[source_lang] + sent + ["</s>"] for sent in source_sents_subworded]
|
102 |
+
|
103 |
+
# Translate the source sentences
|
104 |
+
translations = translator.translate_batch(source_sents_subworded, batch_type="tokens", max_batch_size=2024, beam_size=beam_size, target_prefix=target_prefix)
|
105 |
+
translations = [translation[0]['tokens'] for translation in translations]
|
106 |
+
|
107 |
+
# Desubword the target sentences
|
108 |
+
translations_desubword = sp.decode(translations)
|
109 |
+
translations_desubword = [sent[len(target_lang):] for sent in translations_desubword]
|
110 |
+
|
111 |
+
# Return the source language and the translated text
|
112 |
+
return translations_desubword[0]
|
113 |
+
|
114 |
+
|
115 |
+
@app.get("/")
|
116 |
+
async def read_root():
|
117 |
+
gradio_interface = """
|
118 |
+
<html>
|
119 |
+
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0">
|
120 |
+
<head>
|
121 |
+
<title>Sema</title>
|
122 |
+
</head>
|
123 |
+
<frameset>
|
124 |
+
<frame src=https://kamau1-semaapi-frontend.hf.space/?embedded=true'>
|
125 |
+
</frameset>
|
126 |
+
</html>
|
127 |
+
"""
|
128 |
+
return HTMLResponse(content=gradio_interface)
|
129 |
+
|
130 |
+
|
131 |
+
@app.post("/translate_detect/")
|
132 |
+
async def translate_detect_endpoint(request: Request):
|
133 |
+
datad = await request.json()
|
134 |
+
userinputd = datad.get("userinput")
|
135 |
+
target_langd = datad.get("target_lang")
|
136 |
+
dfull_date = get_time()[0]
|
137 |
+
print(f"\nrequest: {dfull_date}\nTarget Language; {target_langd}, User Input: {userinputd}\n")
|
138 |
+
|
139 |
+
if not userinputd or not target_langd:
|
140 |
+
raise HTTPException(status_code=422, detail="Both 'userinput' and 'target_lang' are required.")
|
141 |
+
|
142 |
+
source_langd, translated_text_d = translate_detect(userinputd, target_langd)
|
143 |
+
dcurrent_time = get_time()[1]
|
144 |
+
print(f"\nresponse: {dcurrent_time}; ... Source_language: {source_langd}, Translated Text: {translated_text_d}\n\n")
|
145 |
+
return {
|
146 |
+
"source_language": source_langd,
|
147 |
+
"translated_text": translated_text_d[0],
|
148 |
+
}
|
149 |
+
|
150 |
+
|
151 |
+
@app.post("/translate_enter/")
|
152 |
+
async def translate_enter_endpoint(request: Request):
|
153 |
+
datae = await request.json()
|
154 |
+
userinpute = datae.get("userinput")
|
155 |
+
source_lange = datae.get("source_lang")
|
156 |
+
target_lange = datae.get("target_lang")
|
157 |
+
efull_date = get_time()[0]
|
158 |
+
print(f"\nrequest: {efull_date}\nSource_language; {source_lange}, Target Language; {target_lange}, User Input: {userinpute}\n")
|
159 |
+
|
160 |
+
if not userinpute or not target_lange:
|
161 |
+
raise HTTPException(status_code=422, detail="'userinput' 'sourc_lang'and 'target_lang' are required.")
|
162 |
+
|
163 |
+
translated_text_e = translate_enter(userinpute, source_lange, target_lange)
|
164 |
+
ecurrent_time = get_time()[1]
|
165 |
+
print(f"\nresponse: {ecurrent_time}; ... Translated Text: {translated_text_e}\n\n")
|
166 |
+
return {
|
167 |
+
"translated_text": translated_text_e,
|
168 |
+
}
|
169 |
+
|
170 |
+
|
171 |
+
print("\nAPI starting .......\n")
|