tanjinadnanabir commited on
Commit
28b2181
Β·
verified Β·
1 Parent(s): 3324961

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -0
app.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+ import gradio as gr
4
+ from gtts import gTTS
5
+ import tempfile
6
+ import re
7
+ # import requests
8
+
9
+ # Translation function
10
+
11
+ def translate_to_japanese(api_key, text): # openai api key
12
+
13
+ if not api_key:
14
+ return "Error: API key is missing.", None
15
+ if not text:
16
+ return "Error: Input text is empty.", None
17
+
18
+ openai.api_key = api_key
19
+
20
+ # translation
21
+
22
+ messages_translation = [
23
+ {"role": "system", "content": "You are a helpful translator."},
24
+ {"role": "user", "content": f"Translate the following English text to Japanese:\n\n{text}"} #prompt template
25
+ ]
26
+
27
+ try:
28
+ response_translation = openai.ChatCompletion.create(
29
+ model="gpt-4o",
30
+ messages=messages_translation,
31
+ max_tokens=300,
32
+ temperature=0.5
33
+ )
34
+
35
+ translated_text=response_translation.choices[0].message['content'].strip()
36
+
37
+ messages_pronunciation = [
38
+ {"role": "system", "content": "You are a helpful assistant who provides only the phonetic pronunciation (Romaji) of Japanese text, in square brackets."},
39
+ {"role": "user", "content": f"Provide only the Romaji pronunciation (phonetic) for this Japanese text:\n\n{translated_text}"} #prompt template
40
+ ]
41
+
42
+ # pronounciation
43
+
44
+ response_pronunciation = openai.ChatCompletion.create(
45
+ model="gpt-4o",
46
+ messages=messages_pronunciation,
47
+ max_tokens=150,
48
+ temperature=0.5
49
+ )
50
+
51
+ pronunciation=response_pronunciation.choices[0].message['content'].strip() ### the pron of ___ is konichuwa
52
+
53
+ return translated_text, pronunciation
54
+
55
+ except openai.error.OpenAIError as e:
56
+ return f"OpenAI API error: {str(e)}", None
57
+ except Exception as e:
58
+ return f"Unexpected error: {str(e)}", None
59
+
60
+ # clean pronounciation
61
+
62
+ def clean_pronunciation(pronunciation_text):
63
+
64
+ pronunciation_cleaned=re.sub(r"(?i)(the pronunciation.*?is[::]*|\n|\"|\')", "", pronunciation_text).strip()
65
+
66
+ # Keep only the text inside [ ] if present
67
+
68
+ match = re.search(r"\[.*?\]", pronunciation_cleaned)
69
+
70
+ if match:
71
+ pronunciation_cleaned = match.group(0)
72
+
73
+ return pronunciation_cleaned # the balah blah ignore [dsadasdasd] response: [dsadasdasd]
74
+
75
+ # audio generation function
76
+
77
+ def generate_audio_from_text(text):
78
+
79
+ tts=gTTS(text, lang="ja")
80
+ temp_audio_file=tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") #.wav
81
+ tts.save(temp_audio_file.name)
82
+
83
+ return temp_audio_file.name
84
+
85
+ # ---------------------- MAIN FUNCTION ----------------------
86
+
87
+ def process_translation(api_key, english_text):
88
+
89
+ if not api_key:
90
+ return "Missing API Key", "", "", None, None
91
+ if not english_text:
92
+ return "Please enter English text.", "", "", None, None
93
+
94
+ translated_text, pronunciation = translate_to_japanese(api_key, english_text)
95
+
96
+ if not pronunciation:
97
+ return translated_text, "", "", None, None
98
+
99
+ cleaned_pronunciation = clean_pronunciation(pronunciation) ### konichuwa
100
+
101
+ # Create result text file
102
+
103
+ result_text = f"English Text: {english_text}\n\nJapanese Translation: {translated_text}\nPronunciation: {cleaned_pronunciation}" ## hello ___ konichuwa
104
+
105
+ result_file = tempfile.NamedTemporaryFile(delete=False, suffix=".txt")
106
+
107
+ with open(result_file.name, "w", encoding="utf-8") as f:
108
+ f.write(result_text)
109
+
110
+ # Generate pronunciation audio
111
+
112
+ audio_path = generate_audio_from_text(cleaned_pronunciation)
113
+
114
+ return "", translated_text, cleaned_pronunciation, result_file.name, audio_path
115
+
116
+
117
+ ### UI design
118
+
119
+ with gr.Blocks(theme=gr.themes.Ocean()) as app:
120
+ gr.Markdown("# πŸ‡―πŸ‡΅ English β†’ Japanese Translator with Pronunciation")
121
+ gr.Markdown("Translate English text into **Japanese**, get **Romaji pronunciation**, and listen to it!")
122
+ api_key = gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password", placeholder="Enter your OpenAI API key")
123
+ english_text = gr.Textbox(label="πŸ“ Enter English Text", lines=4, placeholder="Type something in English...")
124
+ translate_button = gr.Button("Translate to Japanese πŸš€")
125
+ translation_output = gr.Textbox(label="πŸ“˜ Japanese Translation")
126
+ pronunciation_output = gr.Textbox(label="πŸ”€ Pronunciation (Romaji)")
127
+ audio_output=gr.Audio(label="πŸ”Š Listen to Pronunciation", type="filepath")
128
+ file_output = gr.File(label="⬇️ Download Translation Result")
129
+
130
+ translate_button.click(
131
+ fn=process_translation,
132
+ inputs=[api_key, english_text],
133
+ outputs=[gr.Label(), translation_output, pronunciation_output, file_output, audio_output]
134
+ )
135
+
136
+ app.launch()