ntam0001 commited on
Commit
acb75f7
1 Parent(s): 1c05bef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import MarianMTModel, MarianTokenizer
3
+
4
+ # Define a function that loads a model and tokenizer based on the chosen language
5
+ def load_model(lang_pair):
6
+ if lang_pair == "English to French":
7
+ model_name = 'Helsinki-NLP/opus-mt-en-fr'
8
+ elif lang_pair == "Kinyarwanda to English":
9
+ model_name = 'Helsinki-NLP/opus-mt-rw-en'
10
+ else:
11
+ raise ValueError("Unsupported language pair")
12
+
13
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
14
+ model = MarianMTModel.from_pretrained(model_name)
15
+ return model, tokenizer
16
+
17
+ # Function to translate text based on selected language
18
+ def translate(lang_pair, text):
19
+ model, tokenizer = load_model(lang_pair)
20
+
21
+ # Tokenize the text using the __call__ method
22
+ model_inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
23
+
24
+ # Perform the translation
25
+ gen = model.generate(**model_inputs)
26
+
27
+ # Decode the generated tokens to string
28
+ translation = tokenizer.batch_decode(gen, skip_special_tokens=True)
29
+ return translation[0]
30
+
31
+ # Create a Gradio interface with a dropdown menu for language selection
32
+ iface = gr.Interface(
33
+ fn=translate,
34
+ inputs=[
35
+ gr.Dropdown(choices=["English to French", "Kinyarwanda to English"], label="Select Language"),
36
+ gr.Textbox(lines=2, placeholder="Enter Message...")
37
+ ],
38
+ outputs=gr.Textbox()
39
+ )
40
+
41
+ # Launch the interface
42
+ iface.launch(debug=True,inline=False)