kamau1 commited on
Commit
1181f17
1 Parent(s): bb15705

Update modules/app.py

Browse files
Files changed (1) hide show
  1. modules/app.py +75 -4
modules/app.py CHANGED
@@ -10,12 +10,15 @@ from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import HTMLResponse
11
  import uvicorn
12
 
 
13
  import ctranslate2
14
  import sentencepiece as spm
15
  import fasttext
 
16
 
17
- import pytz
18
  from datetime import datetime
 
 
19
  import os
20
 
21
  app = FastAPI()
@@ -30,12 +33,14 @@ app.add_middleware(
30
  allow_headers=["*"],
31
  )
32
 
 
 
 
33
  fasttext.FastText.eprint = lambda x: None
34
 
35
  # User interface
36
  templates_folder = os.path.join(os.path.dirname(__file__), "templates")
37
-
38
-
39
  # Get time of request
40
 
41
  def get_time():
@@ -48,6 +53,29 @@ def get_time():
48
 
49
  full_date = f"{curr_day} | {curr_date} | {curr_time}"
50
  return full_date, curr_time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  # Load the model and tokenizer ..... only once!
53
  beam_size = 1 # change to a smaller value for faster inference
@@ -68,10 +96,14 @@ sp = spm.SentencePieceProcessor()
68
  sp.load(sp_model_full_path)
69
 
70
  # Import The Translator model
 
71
  print("\nimporting Translator model")
72
  ct_model_file = "sematrans-3.3B"
73
  ct_model_full_path = os.path.join(os.path.dirname(__file__), ct_model_file)
74
  translator = ctranslate2.Translator(ct_model_full_path, device)
 
 
 
75
 
76
  print('\nDone importing models\n')
77
 
@@ -126,6 +158,26 @@ def translate_enter(userinput: str, source_lang: str, target_lang: str):
126
  # Return the source language and the translated text
127
  return translations_desubword[0]
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
  @app.get("/", response_class=HTMLResponse)
131
  async def read_root(request: Request):
@@ -172,4 +224,23 @@ async def translate_enter_endpoint(request: Request):
172
  }
173
 
174
 
175
- print("\nAPI starting .......\n")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  from fastapi.responses import HTMLResponse
11
  import uvicorn
12
 
13
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
14
  import ctranslate2
15
  import sentencepiece as spm
16
  import fasttext
17
+ import torch
18
 
 
19
  from datetime import datetime
20
+ import pytz
21
+ import time
22
  import os
23
 
24
  app = FastAPI()
 
33
  allow_headers=["*"],
34
  )
35
 
36
+ # set this key as an environment variable
37
+ os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets['huggingface_token']
38
+
39
  fasttext.FastText.eprint = lambda x: None
40
 
41
  # User interface
42
  templates_folder = os.path.join(os.path.dirname(__file__), "templates")
43
+
 
44
  # Get time of request
45
 
46
  def get_time():
 
53
 
54
  full_date = f"{curr_day} | {curr_date} | {curr_time}"
55
  return full_date, curr_time
56
+
57
+
58
+ def load_models():
59
+ # build model and tokenizer
60
+ model_name_dict = {
61
+ #'nllb-distilled-600M': 'facebook/nllb-200-distilled-600M',
62
+ #'nllb-1.3B': 'facebook/nllb-200-1.3B',
63
+ #'nllb-distilled-1.3B': 'facebook/nllb-200-distilled-1.3B',
64
+ #'nllb-3.3B': 'facebook/nllb-200-3.3B',
65
+ 'nllb-moe-54b': 'facebook/nllb-moe-54b',
66
+ }
67
+
68
+ model_dict = {}
69
+
70
+ for call_name, real_name in model_name_dict.items():
71
+ print('\tLoading model: %s' % call_name)
72
+ model = AutoModelForSeq2SeqLM.from_pretrained(real_name)
73
+ tokenizer = AutoTokenizer.from_pretrained(real_name)
74
+ model_dict[call_name+'_model'] = model
75
+ model_dict[call_name+'_tokenizer'] = tokenizer
76
+
77
+ return model_dict
78
+
79
 
80
  # Load the model and tokenizer ..... only once!
81
  beam_size = 1 # change to a smaller value for faster inference
 
96
  sp.load(sp_model_full_path)
97
 
98
  # Import The Translator model
99
+ '''
100
  print("\nimporting Translator model")
101
  ct_model_file = "sematrans-3.3B"
102
  ct_model_full_path = os.path.join(os.path.dirname(__file__), ct_model_file)
103
  translator = ctranslate2.Translator(ct_model_full_path, device)
104
+ '''
105
+ print("\nimporting Translator model")
106
+ model_dict = load_models()
107
 
108
  print('\nDone importing models\n')
109
 
 
158
  # Return the source language and the translated text
159
  return translations_desubword[0]
160
 
161
+
162
+ def translate_faster(userinput3: str, source_lang3: str, target_lang3: str):
163
+ if len(model_dict) == 2:
164
+ model_name = 'nllb-moe-54b'
165
+
166
+ start_time = time.time()
167
+
168
+ model = model_dict[model_name + '_model']
169
+ tokenizer = model_dict[model_name + '_tokenizer']
170
+
171
+ translator = pipeline('translation', model=model, tokenizer=tokenizer, src_lang=source_lang3, tgt_lang=target_lang3)
172
+ output = translator(userinput3, max_length=400)
173
+ end_time = time.time()
174
+
175
+ output = output[0]['translation_text']
176
+ result = {'inference_time': end_time - start_time,
177
+ 'source': source,
178
+ 'target': target,
179
+ 'result': output}
180
+ return result
181
 
182
  @app.get("/", response_class=HTMLResponse)
183
  async def read_root(request: Request):
 
224
  }
225
 
226
 
227
+ @app.post("/translate_faster/")
228
+ async def translate_faster_endpoint(request: Request):
229
+ dataf = await request.json()
230
+ userinputf = datae.get("userinput")
231
+ source_langf = datae.get("source_lang")
232
+ target_langf = datae.get("target_lang")
233
+ ffull_date = get_time()[0]
234
+ print(f"\nrequest: {ffull_date}\nSource_language; {source_langf}, Target Language; {target_langf}, User Input: {userinputf}\n")
235
+
236
+ if not userinputf or not target_langf:
237
+ raise HTTPException(status_code=422, detail="'userinput' 'sourc_lang'and 'target_lang' are required.")
238
+
239
+ translated_text_f = translate_faster(userinputf, source_langf, target_langf)
240
+ fcurrent_time = get_time()[1]
241
+ print(f"\nresponse: {fcurrent_time}; ... Translated Text: {translated_text_f}\n\n")
242
+ return {
243
+ "translated_text": translated_text_f,
244
+ }
245
+
246
+ print("\nAPI started successfully 😁\n")