shukdevdatta123 commited on
Commit
c495445
·
verified ·
1 Parent(s): c802f74

Create ins2.txt

Browse files
Files changed (1) hide show
  1. ins2.txt +135 -0
ins2.txt ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import streamlit as st
4
+ from PIL import Image
5
+ from gtts import gTTS
6
+ 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:
16
+ return "Error: API key is missing."
17
+ if not text:
18
+ return "Error: Input text is empty."
19
+
20
+ # Set the OpenAI API key
21
+ openai.api_key = api_key
22
+
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,
34
+ max_tokens=300,
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
48
+ response_pronunciation = openai.ChatCompletion.create(
49
+ model="gpt-4o",
50
+ messages=messages_pronunciation,
51
+ max_tokens=300,
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
62
+ except Exception as e:
63
+ return f"An unexpected error occurred: {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
85
+
86
+ # Access the API key from Hugging Face Secrets
87
+ api_key = os.getenv("OPENAI_API_KEY")
88
+
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:
95
+ japanese_text, pronunciation = translate_to_japanese(api_key, english_text)
96
+ if pronunciation:
97
+ # Clean pronunciation (remove unnecessary parts)
98
+ cleaned_pronunciation = clean_pronunciation(pronunciation)
99
+
100
+ st.markdown("### Translation Result:")
101
+ st.write(f"**English Text:** {english_text}")
102
+ st.write(f"**Japanese Output:** {japanese_text}")
103
+ st.write(f"**Pronunciation:** {cleaned_pronunciation}")
104
+
105
+ # Save the result in a text file
106
+ result_text = f"English Text: {english_text}\n\nJapanese Translation: {japanese_text}\nPronunciation: {cleaned_pronunciation}"
107
+
108
+ # Write to a text file
109
+ with open("translation_result.txt", "w") as file:
110
+ file.write(result_text)
111
+
112
+ # Create a download button for the user to download the file
113
+ with open("translation_result.txt", "rb") as file:
114
+ st.download_button(
115
+ label="Download Translation Result",
116
+ data=file,
117
+ file_name="translation_result.txt",
118
+ mime="text/plain"
119
+ )
120
+
121
+ # Generate audio for pronunciation
122
+ audio_file_path = generate_audio_from_text(cleaned_pronunciation)
123
+
124
+ # Provide a button to play the pronunciation audio
125
+ st.audio(audio_file_path, format="audio/mp3")
126
+
127
+ translateimg2 = Image.open("v3.png") # Ensure the file is in the correct directory
128
+ st.image(translateimg2, width=150) # Adjust the size as per preference
129
+ else:
130
+ st.error(japanese_text) # Display error message if API call fails
131
+ else:
132
+ if not api_key:
133
+ st.error("API key is missing. Please add it as a secret in Hugging Face Settings.")
134
+ else:
135
+ st.error("Please provide text to translate.")