shukdevdatta123 commited on
Commit
fadaf9f
·
verified ·
1 Parent(s): 77cdd75

Update app.py

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