shukdevdatta123 commited on
Commit
4d9dba9
·
verified ·
1 Parent(s): 0199b96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -24
app.py CHANGED
@@ -7,9 +7,23 @@ import tempfile
7
  import shutil
8
  import re
9
 
10
- def translate_to_japanese(api_key, text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
- Translates English text to Japanese using OpenAI's API and provides pronunciation.
13
  """
14
  # Validate input
15
  if not api_key:
@@ -23,11 +37,11 @@ def translate_to_japanese(api_key, text):
23
  # Define the messages for the chat model
24
  messages_translation = [
25
  {"role": "system", "content": "You are a helpful translator."},
26
- {"role": "user", "content": f"Translate the following English text to Japanese:\n\n{text}"}
27
  ]
28
 
29
  try:
30
- # Call the OpenAI API to get the Japanese translation
31
  response_translation = openai.ChatCompletion.create(
32
  model="gpt-4o", # Use the correct endpoint for chat models
33
  messages=messages_translation,
@@ -35,13 +49,13 @@ def translate_to_japanese(api_key, text):
35
  temperature=0.5
36
  )
37
 
38
- # Extract the Japanese translation from the response
39
- japanese_translation = response_translation.choices[0].message['content'].strip()
40
 
41
- # Define the messages for the pronunciation (Romaji) request
42
  messages_pronunciation = [
43
- {"role": "system", "content": "You are a helpful assistant who provides the Romaji (Japanese pronunciation in Latin script) of Japanese text."},
44
- {"role": "user", "content": f"Provide the Romaji pronunciation for the following Japanese text:\n\n{japanese_translation}"}
45
  ]
46
 
47
  # Call the OpenAI API to get the pronunciation
@@ -52,10 +66,10 @@ def translate_to_japanese(api_key, text):
52
  temperature=0.5
53
  )
54
 
55
- # Extract the pronunciation (Romaji) from the response
56
  pronunciation = response_pronunciation.choices[0].message['content'].strip()
57
 
58
- return japanese_translation, pronunciation
59
 
60
  except openai.error.OpenAIError as e:
61
  return f"OpenAI API error: {str(e)}", None
@@ -65,20 +79,20 @@ def translate_to_japanese(api_key, text):
65
  # Function to clean pronunciation text
66
  def clean_pronunciation(pronunciation_text):
67
  # Remove introductory phrases like "Sure! The Romaji pronunciation..."
68
- pronunciation_cleaned = re.sub(r"^Sure! The Romaji pronunciation for the Japanese text.*?is[:]*", "", pronunciation_text).strip()
69
  return pronunciation_cleaned
70
 
71
  # Function to generate audio file from text using gTTS
72
- def generate_audio_from_text(text):
73
- tts = gTTS(text, lang='ja') # 'ja' for Japanese language
74
  # Save audio to a temporary file
75
  temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
76
  tts.save(temp_audio_file.name)
77
  return temp_audio_file.name
78
 
79
  # Streamlit UI
80
- st.title("English to Japanese Translator with Pronunciation")
81
- st.markdown("Translate English text into Japanese and get its pronunciation (Romaji) using OpenAI's API.")
82
 
83
  translateimg = Image.open("Untitled.png") # Ensure the file is in the correct directory
84
  st.image(translateimg, use_container_width=True) # Adjust the size as per preference
@@ -89,6 +103,12 @@ api_key = os.getenv("OPENAI_API_KEY")
89
  # Input field for the text
90
  english_text = st.text_area("Enter the English text to translate")
91
 
 
 
 
 
 
 
92
  # Button to trigger the translation
93
  if st.button("Translate"):
94
  if api_key and english_text:
@@ -101,23 +121,24 @@ if st.button("Translate"):
101
  progress_text.text("Translating text...")
102
  progress_bar.progress(33) # Update progress bar to 33%
103
 
104
- japanese_text, pronunciation = translate_to_japanese(api_key, english_text)
 
105
 
106
  # Step 2: Check if translation was successful
107
  if pronunciation:
108
- progress_text.text("Generating Romaji pronunciation...")
109
  progress_bar.progress(66) # Update progress bar to 66%
110
 
111
  # Clean pronunciation (remove unnecessary parts)
112
  cleaned_pronunciation = clean_pronunciation(pronunciation)
113
 
114
  st.markdown("### Translation Result:")
115
- st.write(f"**English Text:** {english_text}")
116
- st.write(f"**Japanese Output:** {japanese_text}")
117
  st.write(f"**Pronunciation:** {cleaned_pronunciation}")
118
 
119
  # Save the result in a text file
120
- result_text = f"English Text: {english_text}\n\nJapanese Translation: {japanese_text}\nPronunciation: {cleaned_pronunciation}"
121
 
122
  # Write to a text file
123
  with open("translation_result.txt", "w") as file:
@@ -136,7 +157,7 @@ if st.button("Translate"):
136
  progress_text.text("Generating pronunciation audio...")
137
  progress_bar.progress(100) # Update progress bar to 100%
138
 
139
- audio_file_path = generate_audio_from_text(cleaned_pronunciation)
140
 
141
  # Provide a button to play the pronunciation audio
142
  st.audio(audio_file_path, format="audio/mp3")
@@ -145,7 +166,7 @@ if st.button("Translate"):
145
  st.image(translateimg2, width=150) # Adjust the size as per preference
146
 
147
  else:
148
- st.error(japanese_text) # Display error message if API call fails
149
 
150
  except Exception as e:
151
  st.error(f"An error occurred: {str(e)}")
@@ -153,4 +174,4 @@ if st.button("Translate"):
153
  if not api_key:
154
  st.error("API key is missing. Please add it as a secret in Hugging Face Settings.")
155
  else:
156
- st.error("Please provide text to translate.")
 
7
  import shutil
8
  import re
9
 
10
+ # Language mapping for gTTS
11
+ LANGUAGE_MAP = {
12
+ "English": "en",
13
+ "Japanese": "ja",
14
+ "French": "fr",
15
+ "Spanish": "es",
16
+ "German": "de",
17
+ "Chinese": "zh",
18
+ "Italian": "it",
19
+ "Portuguese": "pt",
20
+ "Korean": "ko",
21
+ "Arabic": "ar"
22
+ }
23
+
24
+ def translate_text(api_key, text, target_language):
25
  """
26
+ Translates English text to the selected target language using OpenAI's API and provides pronunciation.
27
  """
28
  # Validate input
29
  if not api_key:
 
37
  # Define the messages for the chat model
38
  messages_translation = [
39
  {"role": "system", "content": "You are a helpful translator."},
40
+ {"role": "user", "content": f"Translate the following English text to {target_language}:\n\n{text}"}
41
  ]
42
 
43
  try:
44
+ # Call the OpenAI API to get the translation
45
  response_translation = openai.ChatCompletion.create(
46
  model="gpt-4o", # Use the correct endpoint for chat models
47
  messages=messages_translation,
 
49
  temperature=0.5
50
  )
51
 
52
+ # Extract the translation from the response
53
+ translation = response_translation.choices[0].message['content'].strip()
54
 
55
+ # Define the messages for the pronunciation request (Romaji or other phonetic systems)
56
  messages_pronunciation = [
57
+ {"role": "system", "content": "You are a helpful assistant who provides the pronunciation of the translated text."},
58
+ {"role": "user", "content": f"Provide the pronunciation for the following {target_language} text:\n\n{translation}"}
59
  ]
60
 
61
  # Call the OpenAI API to get the pronunciation
 
66
  temperature=0.5
67
  )
68
 
69
+ # Extract the pronunciation from the response
70
  pronunciation = response_pronunciation.choices[0].message['content'].strip()
71
 
72
+ return translation, pronunciation
73
 
74
  except openai.error.OpenAIError as e:
75
  return f"OpenAI API error: {str(e)}", None
 
79
  # Function to clean pronunciation text
80
  def clean_pronunciation(pronunciation_text):
81
  # Remove introductory phrases like "Sure! The Romaji pronunciation..."
82
+ pronunciation_cleaned = re.sub(r"^Sure! The pronunciation for the text.*?is[:]*", "", pronunciation_text).strip()
83
  return pronunciation_cleaned
84
 
85
  # Function to generate audio file from text using gTTS
86
+ def generate_audio_from_text(text, language_code):
87
+ tts = gTTS(text, lang=language_code) # Dynamically use the language code
88
  # Save audio to a temporary file
89
  temp_audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
90
  tts.save(temp_audio_file.name)
91
  return temp_audio_file.name
92
 
93
  # Streamlit UI
94
+ st.title("Multi-language Translator with Pronunciation")
95
+ st.markdown("Translate English text into various languages and get its pronunciation.")
96
 
97
  translateimg = Image.open("Untitled.png") # Ensure the file is in the correct directory
98
  st.image(translateimg, use_container_width=True) # Adjust the size as per preference
 
103
  # Input field for the text
104
  english_text = st.text_area("Enter the English text to translate")
105
 
106
+ # Dropdown menu for language selection
107
+ language_option = st.selectbox(
108
+ "Select Target Language",
109
+ ["English", "Japanese", "French", "Spanish", "German", "Chinese", "Italian", "Portuguese", "Korean", "Arabic"]
110
+ )
111
+
112
  # Button to trigger the translation
113
  if st.button("Translate"):
114
  if api_key and english_text:
 
121
  progress_text.text("Translating text...")
122
  progress_bar.progress(33) # Update progress bar to 33%
123
 
124
+ # Translate text and get pronunciation
125
+ translated_text, pronunciation = translate_text(api_key, english_text, language_option)
126
 
127
  # Step 2: Check if translation was successful
128
  if pronunciation:
129
+ progress_text.text("Generating pronunciation...")
130
  progress_bar.progress(66) # Update progress bar to 66%
131
 
132
  # Clean pronunciation (remove unnecessary parts)
133
  cleaned_pronunciation = clean_pronunciation(pronunciation)
134
 
135
  st.markdown("### Translation Result:")
136
+ st.write(f"**Original English Text:** {english_text}")
137
+ st.write(f"**Translated Text ({language_option}):** {translated_text}")
138
  st.write(f"**Pronunciation:** {cleaned_pronunciation}")
139
 
140
  # Save the result in a text file
141
+ result_text = f"Original English Text: {english_text}\n\nTranslated Text ({language_option}): {translated_text}\nPronunciation: {cleaned_pronunciation}"
142
 
143
  # Write to a text file
144
  with open("translation_result.txt", "w") as file:
 
157
  progress_text.text("Generating pronunciation audio...")
158
  progress_bar.progress(100) # Update progress bar to 100%
159
 
160
+ audio_file_path = generate_audio_from_text(cleaned_pronunciation, LANGUAGE_MAP[language_option])
161
 
162
  # Provide a button to play the pronunciation audio
163
  st.audio(audio_file_path, format="audio/mp3")
 
166
  st.image(translateimg2, width=150) # Adjust the size as per preference
167
 
168
  else:
169
+ st.error(translated_text) # Display error message if API call fails
170
 
171
  except Exception as e:
172
  st.error(f"An error occurred: {str(e)}")
 
174
  if not api_key:
175
  st.error("API key is missing. Please add it as a secret in Hugging Face Settings.")
176
  else:
177
+ st.error("Please provide text to translate.")