S-Dreamer commited on
Commit
1afd40d
·
verified ·
1 Parent(s): 0bf89d3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from transformers import pipeline
4
+ from utils import preprocess_text, postprocess_translation, TextProcessor
5
+ from css import custom_css
6
+ from cultural_utils import get_cultural_context
7
+ import logging
8
+ import sys
9
+
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(levelname)s - %(message)s',
13
+ stream=sys.stdout
14
+ )
15
+ logger = logging.getLogger(__name__)
16
+
17
+ class TranslationService:
18
+ """Handles the translation pipeline and text processing."""
19
+
20
+ def __init__(self):
21
+ try:
22
+ logger.info("Loading translation pipeline...")
23
+ self.pipeline = pipeline(
24
+ "translation",
25
+ model="persiannlp/mt5-small-parsinlu-translation_en_fa",
26
+ device="cpu"
27
+ )
28
+ logger.info("Translation pipeline loaded successfully")
29
+ except Exception as e:
30
+ logger.error(f"Failed to load translation pipeline: {str(e)}")
31
+ raise
32
+
33
+ def translate(self, text: str, source_lang: str, target_lang: str) -> dict:
34
+ """Translate text between English and Farsi with cultural context."""
35
+ try:
36
+ if not text:
37
+ return {"translation": "", "cultural_context": {"idioms": []}}
38
+
39
+ # Validate input
40
+ is_valid, error_msg = TextProcessor.validate_input(text)
41
+ if not is_valid:
42
+ return {"translation": error_msg, "cultural_context": {"idioms": []}}
43
+
44
+ # Get cultural context before translation
45
+ src_lang = "en" if source_lang == "English" else "fa"
46
+ cultural_context = get_cultural_context(text, src_lang)
47
+
48
+ # Preprocess text
49
+ processed_text = preprocess_text(text)
50
+ logger.info(f"Translating text from {source_lang} to {target_lang}")
51
+
52
+ # Generate translation
53
+ result = self.pipeline(processed_text)
54
+
55
+ # Post-process and return result
56
+ translated_text = postprocess_translation(result[0]['translation_text'])
57
+ return {
58
+ "translation": translated_text,
59
+ "cultural_context": cultural_context
60
+ }
61
+
62
+ except Exception as e:
63
+ logger.error(f"Translation error: {str(e)}")
64
+ return {
65
+ "translation": "Translation error occurred. Please try again.",
66
+ "cultural_context": {"idioms": []}
67
+ }
68
+
69
+ class GradioInterface:
70
+ """Manages the Gradio web interface components."""
71
+
72
+ def __init__(self, translation_service):
73
+ self.translation_service = translation_service
74
+
75
+ def create(self):
76
+ """Create and configure the Gradio interface."""
77
+ with gr.Blocks(css=custom_css) as interface:
78
+ self._create_header()
79
+ source_lang, target_lang = self._create_language_controls()
80
+ self._create_translation_interface(source_lang, target_lang)
81
+ return interface
82
+
83
+ def _create_header(self):
84
+ """Create the interface header."""
85
+ gr.Markdown("""
86
+ # English-Farsi Translation
87
+ Culturally-sensitive translation between English and Farsi
88
+ """)
89
+
90
+ def _create_language_controls(self):
91
+ """Create language selection controls."""
92
+ with gr.Row():
93
+ source_lang = gr.Dropdown(
94
+ choices=["English", "Farsi"],
95
+ value="English",
96
+ label="Source Language"
97
+ )
98
+ target_lang = gr.Dropdown(
99
+ choices=["Farsi", "English"],
100
+ value="Farsi",
101
+ label="Target Language"
102
+ )
103
+
104
+ swap_btn = gr.Button("🔄 Swap Languages")
105
+ swap_btn.click(
106
+ fn=lambda s, t: (t, s),
107
+ inputs=[source_lang, target_lang],
108
+ outputs=[source_lang, target_lang]
109
+ )
110
+ return source_lang, target_lang
111
+
112
+ def _create_translation_interface(self, source_lang, target_lang):
113
+ """Create the translation input/output interface."""
114
+ with gr.Row():
115
+ with gr.Column():
116
+ input_text = gr.Textbox(
117
+ lines=5,
118
+ placeholder="Enter text to translate...",
119
+ label="Input Text"
120
+ )
121
+ with gr.Column():
122
+ output_text = gr.Textbox(
123
+ lines=5,
124
+ label="Translation",
125
+ rtl=True
126
+ )
127
+ cultural_notes = gr.Markdown(
128
+ label="Cultural Context",
129
+ value="Cultural context annotations will appear here..."
130
+ )
131
+
132
+ def format_cultural_context(result):
133
+ translation = result["translation"]
134
+ context = result["cultural_context"]
135
+
136
+ if not context["idioms"]:
137
+ return translation, "No cultural annotations found."
138
+
139
+ notes = "### Cultural Context Notes:\n"
140
+ for idiom, literal, explanation in context["idioms"]:
141
+ notes += f"- **{idiom}**\n"
142
+ notes += f" - Literal: {literal}\n"
143
+ notes += f" - Context: {explanation}\n\n"
144
+
145
+ return translation, notes
146
+
147
+ translate_btn = gr.Button("Translate", variant="primary")
148
+ def handle_translation(text, src_lang, tgt_lang):
149
+ result = self.translation_service.translate(text, src_lang, tgt_lang)
150
+ translation = result["translation"]
151
+ context = result["cultural_context"]
152
+
153
+ if not context["idioms"]:
154
+ return translation, "No cultural annotations found."
155
+
156
+ notes = "### Cultural Context Notes:\n"
157
+ for idiom, literal, explanation in context["idioms"]:
158
+ notes += f"- **{idiom}**\n"
159
+ notes += f" - Literal: {literal}\n"
160
+ notes += f" - Context: {explanation}\n\n"
161
+
162
+ return translation, notes
163
+
164
+ translate_btn.click(
165
+ fn=handle_translation,
166
+ inputs=[input_text, source_lang, target_lang],
167
+ outputs=[output_text, cultural_notes]
168
+ )
169
+
170
+ source_lang.change(
171
+ fn=lambda lang: gr.update(rtl=lang == "Farsi"),
172
+ inputs=[source_lang],
173
+ outputs=[input_text]
174
+ )
175
+
176
+ def main():
177
+ """Initialize and launch the translation application."""
178
+ try:
179
+ logger.info("Initializing translation service...")
180
+ translation_service = TranslationService()
181
+
182
+ logger.info("Creating Gradio interface...")
183
+ interface = GradioInterface(translation_service).create()
184
+
185
+ interface.launch(
186
+ server_name="0.0.0.0",
187
+ server_port=8000,
188
+ share=True,
189
+ debug=True,
190
+ show_error=True
191
+ )
192
+ logger.info("Gradio interface started successfully")
193
+ except Exception as e:
194
+ logger.error(f"Application startup failed: {str(e)}")
195
+ raise
196
+
197
+ if __name__ == "__main__":
198
+ main()
199
+