anisgtboi commited on
Commit
10fe3cf
Β·
verified Β·
1 Parent(s): ec21afd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -105
app.py CHANGED
@@ -1,121 +1,80 @@
1
- # app.py
2
  import os
3
- import traceback
4
  import gradio as gr
 
5
 
6
- # Try import transformers; if missing the app will show a clear error message in logs.
7
- try:
8
- from transformers import pipeline
9
- import os
10
-
11
  auth_token = os.getenv("HF_API_TOKEN")
12
 
13
- translator = pipeline(
14
- "translation",
15
- model="Helsinki-NLP/opus-mt-en-bn", # or your chosen model
16
- token=auth_token
17
- )
18
 
19
- def safe_load_pipeline(model_name):
20
- """Load a translation pipeline lazily and return a tuple (success, message)."""
21
- global _loaded
22
- if pipeline is None:
23
- return False, "transformers not available - check requirements.txt"
24
- if model_name in _loaded:
25
- return True, f"model already loaded: {model_name}"
26
- try:
27
- # device=-1 ensures CPU usage; set max_length moderately
28
- p = pipeline("translation", model=model_name, device=-1, max_length=512)
29
- _loaded[model_name] = p
30
- return True, f"Loaded {model_name}"
31
- except Exception as e:
32
- # log the full stack to Space logs so you can copy it
33
- print("Exception while loading model:", model_name)
34
- traceback.print_exc()
35
- return False, f"Failed to load {model_name}: {str(e)}"
36
 
37
- def translate_text(text: str, direction: str):
38
- """
39
- Main translation function used by the Gradio UI.
40
- returns: translation, status, debug_info
41
- """
42
- if not text or not text.strip():
43
- return "", "⚠️ Enter text to translate", ""
44
- try:
45
- model_name = MODEL_EN_TO_BN if direction == "English β†’ Bengali" else MODEL_BN_TO_EN
46
 
47
- # Try local lazy-load first
48
- ok, msg = safe_load_pipeline(model_name)
49
- if not ok:
50
- # If local load fails, provide immediate dummy fallback so buttons respond
51
- print("Local model load failed:", msg)
52
- return text, f"⚠️ Local model load failed: {msg}. Showing fallback (identity) translation.", "Fallback used: returning input as output."
53
 
54
- # Use the loaded pipeline
55
- translator = _loaded.get(model_name)
56
- result = translator(text, max_length=512)
57
- # result is often list of dicts
58
- if isinstance(result, list) and len(result) > 0:
59
- r0 = result[0]
60
- if isinstance(r0, dict):
61
- translated = r0.get("translation_text") or r0.get("generated_text") or str(r0)
62
- else:
63
- translated = str(r0)
 
64
  else:
65
- translated = str(result)
66
- status = f"βœ… Translated using {model_name}"
67
- analysis = f"Input words: {len(text.split())}; Output words: {len(translated.split())}"
68
- return translated, status, analysis
69
-
70
  except Exception as e:
71
- # If anything crashes, show a simple fallback so UI remains responsive
72
- tb = traceback.format_exc()
73
- print("Translation exception:", tb)
74
- return "", f"❌ Error during translation: {str(e)}", tb
75
 
76
- # --- Small, responsive CSS for mobile: keep layout simple ---
77
- custom_css = """
78
- /* Make UI mobile-friendly and readable */
79
- .gradio-container { padding: 12px !important; max-width: 900px; margin: auto; font-family: 'Times New Roman', serif; }
80
- .gradio-row { gap: 8px !important; }
81
- textarea, input[type="text"] { font-size: 18px !important; }
82
- .gr-button { font-size: 18px !important; padding: 12px 18px !important; }
83
- """
84
 
85
- # --- Build Gradio UI with Blocks for responsive layout ---
86
- with gr.Blocks(css=custom_css, title="English ↔ Bengali β€” Fast Translator") as demo:
87
- gr.Markdown("## English ↔ Bengali β€” Fast Translator\nUsing small OPUS-MT models (CPU friendly). The app lazy-loads models so Space won't crash. If a model fails to load the app will return a fallback so buttons still work.")
88
- with gr.Row():
89
- direction = gr.Radio(label="Direction", choices=["English β†’ Bengali", "Bengali β†’ English"], value="English β†’ Bengali")
90
- swap_btn = gr.Button("Swap")
91
-
92
- input_text = gr.Textbox(label="Input text", placeholder="Type a sentence here (English or Bengali)...", lines=4)
93
- translate_btn = gr.Button("Translate", variant="primary")
94
- with gr.Row():
95
- out_translation = gr.Textbox(label="Translation", lines=4)
96
- with gr.Row():
97
- out_status = gr.Textbox(label="Status / Tips", lines=1)
98
- out_analysis = gr.Textbox(label="Analysis / Debug", lines=3)
99
 
100
- # swap behavior
101
- def do_swap(cur):
102
- return "Bengali β†’ English" if cur == "English β†’ Bengali" else "English β†’ Bengali"
103
- swap_btn.click(do_swap, inputs=direction, outputs=direction)
104
-
105
- # main click hook
106
- translate_btn.click(translate_text, inputs=[input_text, direction], outputs=[out_translation, out_status, out_analysis])
107
-
108
- # example quick buttons
109
  with gr.Row():
110
- ex1 = gr.Button("Hello, how are you?")
111
- ex2 = gr.Button("Ami bhalo achi")
112
- ex3 = gr.Button("Where is the market?")
113
-
114
- ex1.click(lambda: "Hello, how are you?", outputs=input_text)
115
- ex2.click(lambda: "Ami bhalo achi", outputs=input_text)
116
- ex3.click(lambda: "Where is the market?", outputs=input_text)
117
-
118
- # Launch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  if __name__ == "__main__":
120
- # debug=True prints logs to the container console
121
- demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), debug=True)
 
 
1
  import os
 
2
  import gradio as gr
3
+ from transformers import pipeline
4
 
5
+ # === Load Hugging Face token (only needed if Space is private) ===
 
 
 
 
6
  auth_token = os.getenv("HF_API_TOKEN")
7
 
8
+ # === Choose your model (pick one that works best for you) ===
9
+ MODEL_NAME = "Helsinki-NLP/opus-mt-en-bn" # English β†’ Bengali
10
+ # MODEL_NAME = "shhossain/opus-mt-en-to-bn" # Alternate
11
+ # MODEL_NAME = "facebook/nllb-200-distilled-600M" # Multi-language
 
12
 
13
+ # === Load translation pipeline ===
14
+ try:
15
+ translator = pipeline(
16
+ "translation",
17
+ model=MODEL_NAME,
18
+ token=auth_token # Works for private Spaces
19
+ )
20
+ except Exception as e:
21
+ translator = None
22
+ print("❌ Error loading model:", e)
 
 
 
 
 
 
 
23
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # === Define translation function ===
26
+ def translate_text(text, direction):
27
+ if not translator:
28
+ return "⚠️ Model not loaded. Check HF_API_TOKEN for private Spaces."
 
 
29
 
30
+ try:
31
+ if direction == "English β†’ Bengali":
32
+ result = translator(text, src="en", tgt="bn")
33
+ elif direction == "Bengali β†’ English":
34
+ # For reverse, swap model if needed
35
+ rev_translator = pipeline(
36
+ "translation",
37
+ model="Helsinki-NLP/opus-mt-bn-en",
38
+ token=auth_token
39
+ )
40
+ result = rev_translator(text)
41
  else:
42
+ return "⚠️ Unknown direction."
43
+ return result[0]['translation_text']
 
 
 
44
  except Exception as e:
45
+ return f"⚠️ Translation failed: {str(e)}"
 
 
 
46
 
 
 
 
 
 
 
 
 
47
 
48
+ # === Gradio UI ===
49
+ with gr.Blocks(title="Private English ↔ Bengali Translator") as demo:
50
+ gr.Markdown("## 🌐 English ↔ Bengali Translator (Private Space Ready)")
 
 
 
 
 
 
 
 
 
 
 
51
 
 
 
 
 
 
 
 
 
 
52
  with gr.Row():
53
+ with gr.Column():
54
+ input_text = gr.Textbox(
55
+ label="Enter text",
56
+ placeholder="Type here...",
57
+ lines=5
58
+ )
59
+ direction = gr.Radio(
60
+ ["English β†’ Bengali", "Bengali β†’ English"],
61
+ value="English β†’ Bengali",
62
+ label="Select Translation Direction"
63
+ )
64
+ translate_btn = gr.Button("Translate", variant="primary")
65
+
66
+ with gr.Column():
67
+ output_text = gr.Textbox(
68
+ label="Translation Result",
69
+ lines=5
70
+ )
71
+
72
+ translate_btn.click(
73
+ fn=translate_text,
74
+ inputs=[input_text, direction],
75
+ outputs=[output_text]
76
+ )
77
+
78
+ # === Launch app ===
79
  if __name__ == "__main__":
80
+ demo.launch()