repleeka commited on
Commit
d266b49
·
verified ·
1 Parent(s): 96b4aac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -33
app.py CHANGED
@@ -1,61 +1,106 @@
1
- from transformers import pipeline
2
- from datasets import Dataset
3
  import streamlit as st
4
  import torch
 
 
5
 
6
- # Set the background color and layout with set_page_config
7
  st.set_page_config(
8
  page_title="English to Tawra Translator",
9
  page_icon=":repeat:",
10
  layout="wide",
11
  )
12
 
13
- # Streamlit app setup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  st.title(":repeat: English to Tawra Translator")
15
  st.markdown("Welcome to the English to Tawra Translator. :sparkles: Simply enter your text in English, and get the translation in Tawra instantly! :thumbsup:")
16
 
17
- # Text input
18
  if 'text_input' not in st.session_state:
19
  st.session_state.text_input = ""
20
- text_input = st.text_area("Enter English text to translate", height=150, value=st.session_state.text_input)
21
 
22
- # Define your model from Hugging Face
23
- model_directory = "repleeka/eng-taw-nmt"
24
 
25
- device = 0 if torch.cuda.is_available() else -1
26
- translation_pipeline = pipeline(
27
- task="translation",
28
- model="repleeka/eng-taw-nmt",
29
- tokenizer="repleeka/eng-taw-nmt",
30
- device=device
31
  )
32
 
33
- # Translate button
34
- if st.button("Translate", key="translate_button"):
35
- if text_input:
36
- with st.spinner("Translating... Please wait"):
37
- # Prepare data for translation
38
- sentences = [text_input]
39
- data = Dataset.from_dict({"text": sentences})
40
 
41
- # Apply translation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
 
 
 
 
 
 
 
43
  results = data.map(lambda x: {"translation": translation_pipeline(x["text"])})
44
- result = results[0]["translation"][0]['translation_text']
45
 
46
- # Capitalize the first letter of the result
47
- result = result.capitalize()
 
 
 
 
48
 
49
- # Display translation result with custom styling
 
50
  st.markdown("#### Translated text:")
51
- st.markdown(f'<h2 class="result-text">{result}</2>', unsafe_allow_html=True)
52
- # st.markdown(result)
53
 
54
  except Exception as e:
55
  st.error(f"Translation error: {e}")
 
 
56
  else:
57
- st.warning("Please enter text to translate.")
58
-
59
- # Clear input button
60
- if st.button("Clear Input"):
61
- st.session_state.text_input = ""
 
 
 
1
  import streamlit as st
2
  import torch
3
+ from transformers import pipeline
4
+ from datasets import Dataset
5
 
6
+ # 1. Page Config must be the first Streamlit command
7
  st.set_page_config(
8
  page_title="English to Tawra Translator",
9
  page_icon=":repeat:",
10
  layout="wide",
11
  )
12
 
13
+ # Custom CSS for the result text and general styling
14
+ st.markdown("""
15
+ <style>
16
+ .result-text {
17
+ color: #1E88E5;
18
+ background-color: #f0f2f6;
19
+ padding: 20px;
20
+ border-radius: 10px;
21
+ border-left: 5px solid #1E88E5;
22
+ }
23
+ </style>
24
+ """, unsafe_allow_html=True)
25
+
26
+ # 2. Optimization: Cache the model loading to prevent reloading on every interaction
27
+ @st.cache_resource
28
+ def load_translator():
29
+ model_id = "repleeka/eng-taw-nmt"
30
+ # Determine device: use GPU if available, else CPU
31
+ device = 0 if torch.cuda.is_available() else -1
32
+ return pipeline(
33
+ task="translation",
34
+ model=model_id,
35
+ tokenizer=model_id,
36
+ device=device
37
+ )
38
+
39
+ translation_pipeline = load_translator()
40
+
41
+ # 3. App UI Setup
42
  st.title(":repeat: English to Tawra Translator")
43
  st.markdown("Welcome to the English to Tawra Translator. :sparkles: Simply enter your text in English, and get the translation in Tawra instantly! :thumbsup:")
44
 
45
+ # 4. State Management for Input Clearing
46
  if 'text_input' not in st.session_state:
47
  st.session_state.text_input = ""
 
48
 
49
+ def clear_text():
50
+ st.session_state.text_input = ""
51
 
52
+ # Text area tied to session state
53
+ text_input = st.text_area(
54
+ "Enter English text to translate",
55
+ height=150,
56
+ value=st.session_state.text_input,
57
+ key="current_input" # Adding a key helps Streamlit track this specific widget
58
  )
59
 
60
+ # Update session state with current input so it persists until "Clear" is clicked
61
+ st.session_state.text_input = text_input
 
 
 
 
 
62
 
63
+ col1, col2 = st.columns([1, 10])
64
+
65
+ with col1:
66
+ translate_clicked = st.button("Translate", type="primary")
67
+
68
+ with col2:
69
+ # Use a callback or direct state update for clearing
70
+ if st.button("Clear Input"):
71
+ clear_text()
72
+ st.rerun() # Force rerun to clear the text area immediately
73
+
74
+ # 5. Translation Logic
75
+ if translate_clicked:
76
+ if text_input.strip():
77
+ with st.spinner("Translating... Please wait"):
78
  try:
79
+ # Prepare data using the Datasets library
80
+ sentences = [text_input]
81
+ data = Dataset.from_dict({"text": sentences})
82
+
83
+ # Apply translation
84
+ # Fix: Hugging Face translation pipelines usually return a list of dicts directly
85
+ # We use .map for batch processing consistency if you have many sentences
86
  results = data.map(lambda x: {"translation": translation_pipeline(x["text"])})
 
87
 
88
+ # Extract the translation text
89
+ # Accessing: Row 0 -> 'translation' column -> index 0 of results -> 'translation_text' key
90
+ raw_result = results[0]["translation"][0]['translation_text']
91
+
92
+ # Formatting
93
+ final_result = raw_result.strip().capitalize()
94
 
95
+ # Display result
96
+ st.markdown("---")
97
  st.markdown("#### Translated text:")
98
+ # Fixed the closing tag error in your HTML string (</h2> instead of </2>)
99
+ st.markdown(f'<div class="result-text"><h2>{final_result}</h2></div>', unsafe_allow_html=True)
100
 
101
  except Exception as e:
102
  st.error(f"Translation error: {e}")
103
+ # Optional: log error details for debugging
104
+ # st.exception(e)
105
  else:
106
+ st.warning("Please enter some text to translate.")