mjsp commited on
Commit
45bcbb5
·
1 Parent(s): c6d6c95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -28
app.py CHANGED
@@ -1,32 +1,26 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- from transformers import AutoTokenizer, TFAutoModelForSeq2SeqLM
4
 
5
- path = 'tf_model/'
6
- model_checkpoint = "Helsinki-NLP/opus-mt-en-hi"
7
- tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
8
- model = TFAutoModelForSeq2SeqLM.from_pretrained(path)
 
9
 
10
- title = 'Text Translation(English to Hindi)'
11
- def process_input(text):
12
- # Tokenize the input text using the tokenizer and convert to NumPy arrays
13
- tokenized = tokenizer([text], return_tensors='np')
14
- # Generate output sequences using the pre-trained model
15
- out = model.generate(**tokenized, max_length=128)
16
- # Switch the tokenizer to target mode
17
- with tokenizer.as_target_tokenizer():
18
- # Decode the generated output sequence, skipping special tokens
19
- result = tokenizer.decode(out[0], skip_special_tokens=True)
20
- return result
21
 
22
- # Example input text for the GUI
23
- examples = ['If you have the time, come along with me.', 'I can come if you want.', 'Tom was at home alone.', 'Wow!','How rude of you!',"What's in your hand?"]
24
 
25
- # Create a Gradio Interface for the model
26
- model_gui = gr.Interface(
27
- process_input, # Function for processing input and generating output
28
- gr.Textbox(lines=3, label="English"), # Textbox for entering English text
29
- gr.Textbox(lines=3, label="Hindi"), # Textbox for displaying translated Hindi text
30
- title=title, # Set the title of the GUI
31
- examples=examples # Provide example input text for the GUI
32
- )
 
 
 
 
 
1
+ from transformers import MarianMTModel, MarianTokenizer
 
 
2
 
3
+ def translate_text(input_text, source_lang="en", target_lang="hi"):
4
+ # Load pre-trained model and tokenizer for MarianMT
5
+ model_name = f'Helsinki-NLP/opus-mt-{source_lang}-{target_lang}'
6
+ model = MarianMTModel.from_pretrained(model_name)
7
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
8
 
9
+ # Tokenize the input text
10
+ input_ids = tokenizer.encode(input_text, return_tensors="pt")
 
 
 
 
 
 
 
 
 
11
 
12
+ # Generate translation
13
+ translation_ids = model.generate(input_ids)
14
 
15
+ # Decode the translated text
16
+ translated_text = tokenizer.decode(translation_ids[0], skip_special_tokens=True)
17
+
18
+ return translated_text
19
+
20
+ if __name__ == "__main__":
21
+ # Example usage
22
+ input_text = "Hello, how are you?"
23
+ translated_text = translate_text(input_text)
24
+
25
+ print(f"Input Text: {input_text}")
26
+ print(f"Translated Text: {translated_text}")