danhtran2mind commited on
Commit
8dabd6b
·
verified ·
1 Parent(s): c5e0beb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -0
app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ from translator import Translator
4
+ from utils import tokenizer_utils
5
+ from utils.preprocessing import input_processing, output_processing
6
+ from models.transformer import Transformer
7
+ from models.encoder import Encoder
8
+ from models.decoder import Decoder
9
+ from models.layers import EncoderLayer, DecoderLayer, MultiHeadAttention, point_wise_feed_forward_network
10
+ from models.utils import masked_loss, masked_accuracy
11
+
12
+ def load_model_and_tokenizers(model_path="saved_models/en_vi_translation.keras"):
13
+ """
14
+ Load the pre-trained model and tokenizers.
15
+
16
+ Args:
17
+ model_path (str): Path to the pre-trained model file.
18
+
19
+ Returns:
20
+ model: Loaded TensorFlow model.
21
+ en_tokenizer: English tokenizer.
22
+ vi_tokenizer: Vietnamese tokenizer.
23
+ """
24
+ # Define custom objects for the model
25
+ custom_objects = {
26
+ "Transformer": Transformer,
27
+ "Encoder": Encoder,
28
+ "Decoder": Decoder,
29
+ "EncoderLayer": EncoderLayer,
30
+ "DecoderLayer": DecoderLayer,
31
+ "MultiHeadAttention": MultiHeadAttention,
32
+ "point_wise_feed_forward_network": point_wise_feed_forward_network,
33
+ "masked_loss": masked_loss,
34
+ "masked_accuracy": masked_accuracy,
35
+ }
36
+
37
+ # Load the model
38
+ try:
39
+ model = tf.keras.models.load_model(model_path, custom_objects=custom_objects)
40
+ print("Model loaded successfully.")
41
+ except Exception as e:
42
+ raise Exception(f"Failed to load model: {str(e)}")
43
+
44
+ # Load tokenizers
45
+ try:
46
+ en_tokenizer, vi_tokenizer = tokenizer_utils.load_tokenizers()
47
+ print("Tokenizers loaded successfully.")
48
+ except Exception as e:
49
+ raise Exception(f"Failed to load tokenizers: {str(e)}")
50
+
51
+ return model, en_tokenizer, vi_tokenizer
52
+
53
+ def translate_sentence(sentence, model, en_tokenizer, vi_tokenizer):
54
+ """
55
+ Translate a single English sentence to Vietnamese.
56
+
57
+ Args:
58
+ sentence (str): English sentence to translate.
59
+ model: Pre-trained translation model.
60
+ en_tokenizer: English tokenizer.
61
+ vi_tokenizer: Vietnamese tokenizer.
62
+
63
+ Returns:
64
+ str: Translated Vietnamese sentence.
65
+ """
66
+ if not sentence.strip():
67
+ return "Please provide a valid sentence."
68
+
69
+ # Initialize translator
70
+ translator = Translator(en_tokenizer, vi_tokenizer, model)
71
+
72
+ # Process and translate
73
+ processed_sentence = input_processing(sentence)
74
+ translated_text = translator(processed_sentence)
75
+ translated_text = output_processing(translated_text)
76
+
77
+ return translated_text
78
+
79
+ # Load model and tokenizers once at startup
80
+ try:
81
+ model, en_tokenizer, vi_tokenizer = load_model_and_tokenizers()
82
+ except Exception as e:
83
+ raise Exception(f"Initialization failed: {str(e)}")
84
+
85
+ # Define Gradio interface
86
+ def gradio_translate(sentence):
87
+ """
88
+ Gradio-compatible translation function.
89
+
90
+ Args:
91
+ sentence (str): Input English sentence.
92
+
93
+ Returns:
94
+ str: Translated Vietnamese sentence.
95
+ """
96
+ return translate_sentence(sentence, model, en_tokenizer, vi_tokenizer)
97
+
98
+ # Create Gradio interface
99
+ iface = gr.Interface(
100
+ fn=gradio_translate,
101
+ inputs=gr.Textbox(
102
+ label="Enter English Sentence",
103
+ placeholder="Type an English sentence to translate to Vietnamese...",
104
+ lines=2
105
+ ),
106
+ outputs=gr.Textbox(
107
+ label="Translated Vietnamese Sentence"
108
+ ),
109
+ title="English to Vietnamese Translator",
110
+ description=(
111
+ "Enter an English sentence to translate it to Vietnamese using a pre-trained Transformer model. "
112
+ "Example: 'Hello, world!'"
113
+ ),
114
+ examples=[
115
+ [
116
+ "For at least six centuries, residents along a lake in the mountains of central Japan "
117
+ "have marked the depth of winter by celebrating the return of a natural phenomenon "
118
+ "once revered as the trail of a wandering god."
119
+ ],
120
+ ["Hello, world!"],
121
+ ["The sun is shining."]
122
+ ]
123
+ )
124
+
125
+ # Launch the app
126
+ if __name__ == "__main__":
127
+ iface.launch()