teamseven commited on
Commit
5397a53
·
verified ·
1 Parent(s): 862b067

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -247
app.py CHANGED
@@ -1,256 +1,64 @@
1
- import os
2
- import base64
3
- import tempfile
4
- import logging
5
-
6
  import gradio as gr
7
- import requests
8
-
9
- logging.basicConfig(
10
- level=logging.INFO,
11
- format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
12
- )
13
-
14
- logger = logging.getLogger("edge-tts-bridge")
15
-
16
- APP_TITLE = "Edge TTS Bridge"
17
-
18
- GO_TTS_URL = "http://127.0.0.1:8080/v1/synthesize"
19
-
20
- VOICES = {
21
- "Myanmar Female": "my-MM-NilarNeural",
22
- "Myanmar Male": "my-MM-ThihaNeural",
23
- }
24
-
25
-
26
- def synthesize(text: str, voice: str) -> str:
27
- """Generate audio through the Go Edge TTS server."""
28
-
29
- output_path = None
30
-
31
- try:
32
- logger.info(
33
- "TTS request started | voice=%s | characters=%d",
34
- voice,
35
- len(text),
36
- )
37
-
38
- response = requests.post(
39
- GO_TTS_URL,
40
- json={
41
- "text": text,
42
- "voice": voice,
43
- },
44
- timeout=120,
45
- )
46
-
47
- logger.info(
48
- "Go TTS response | status=%s | content_type=%s | bytes=%d",
49
- response.status_code,
50
- response.headers.get("content-type", ""),
51
- len(response.content),
52
- )
53
-
54
- if response.status_code != 200:
55
- raise RuntimeError(
56
- f"Go TTS HTTP {response.status_code}: "
57
- f"{response.text[:500]}"
58
- )
59
-
60
- content_type = response.headers.get(
61
- "content-type",
62
- "",
63
- ).lower()
64
-
65
- # Case 1: Server returns audio directly.
66
- if content_type.startswith("audio/"):
67
- audio_data = response.content
68
-
69
- # Case 2: Server returns JSON.
70
- else:
71
- try:
72
- result = response.json()
73
- except ValueError:
74
- raise RuntimeError(
75
- "Unexpected response from Go TTS: "
76
- f"{response.text[:500]}"
77
- )
78
-
79
- logger.info(
80
- "Go TTS JSON response: %s",
81
- str(result)[:1000],
82
- )
83
-
84
- if not isinstance(result, dict):
85
- raise RuntimeError(
86
- "Go TTS returned unexpected JSON format."
87
- )
88
-
89
- # Surface server-side errors.
90
- if result.get("error"):
91
- raise RuntimeError(
92
- str(result["error"])[:500]
93
- )
94
-
95
- # Common Base64 audio fields.
96
- audio_data = None
97
-
98
- for key in (
99
- "audio",
100
- "data",
101
- "audioContent",
102
- "audio_content",
103
- ):
104
- value = result.get(key)
105
-
106
- if isinstance(value, str) and value:
107
- try:
108
- if value.startswith("data:") and "," in value:
109
- value = value.split(",", 1)[1]
110
-
111
- audio_data = base64.b64decode(
112
- value,
113
- validate=True,
114
- )
115
-
116
- if audio_data:
117
- break
118
-
119
- except Exception:
120
- audio_data = None
121
-
122
- if not audio_data:
123
- raise RuntimeError(
124
- "Go TTS did not return recognizable audio. "
125
- "Response: "
126
- f"{str(result)[:500]}"
127
- )
128
-
129
- if len(audio_data) < 100:
130
- raise RuntimeError(
131
- "Audio response is too small: "
132
- f"{len(audio_data)} bytes."
133
- )
134
-
135
- with tempfile.NamedTemporaryFile(
136
- suffix=".mp3",
137
- delete=False,
138
- ) as temp:
139
- temp.write(audio_data)
140
- output_path = temp.name
141
-
142
- logger.info(
143
- "TTS succeeded | voice=%s | bytes=%d",
144
- voice,
145
- len(audio_data),
146
- )
147
-
148
- return output_path
149
-
150
- except Exception:
151
- if output_path and os.path.exists(output_path):
152
- try:
153
- os.remove(output_path)
154
- except OSError:
155
- pass
156
-
157
- logger.exception(
158
- "TTS synthesis failed | voice=%s",
159
- voice,
160
- )
161
- raise
162
-
163
-
164
- def generate_audio(text, voice_name):
165
- """Gradio interface handler."""
166
 
167
- text = (text or "").strip()
 
 
 
 
 
 
168
 
 
169
  if not text:
170
- raise gr.Error("Please enter text.")
171
-
172
- if len(text) > 3000:
173
- raise gr.Error(
174
- "Maximum 3000 characters per request."
175
- )
176
-
177
- if voice_name not in VOICES:
178
- raise gr.Error("Unsupported voice.")
179
-
180
- voice = VOICES[voice_name]
181
-
182
  try:
183
- return synthesize(text, voice)
184
-
185
- except Exception as exc:
186
- logger.exception(
187
- "TTS handler failed | type=%s",
188
- type(exc).__name__,
189
- )
190
-
191
- raise gr.Error(
192
- f"TTS failed ({type(exc).__name__}): "
193
- f"{str(exc)[:500]}"
194
- )
195
-
196
-
197
- with gr.Blocks(title=APP_TITLE) as demo:
198
- gr.Markdown(
199
- """
200
- # Edge TTS Bridge — Go Test
201
-
202
- Test Microsoft Edge TTS using the Go server.
203
- """
204
- )
205
-
206
  with gr.Row():
207
- text_input = gr.Textbox(
208
- label="Text",
209
- placeholder="မင်္ဂလာပါ၊ အသံစမ်းသပ်နေပါတယ်။",
210
- lines=4,
211
- max_lines=10,
212
- )
213
-
214
- voice_input = gr.Dropdown(
215
- choices=list(VOICES.keys()),
216
- value="Myanmar Female",
217
- label="Voice",
218
- )
219
-
220
- generate_button = gr.Button(
221
- "Generate Audio",
222
- variant="primary",
223
- )
224
-
225
- audio_output = gr.Audio(
226
- label="Generated Audio",
227
- type="filepath",
228
- )
229
-
230
- generate_button.click(
231
- fn=generate_audio,
232
- inputs=[
233
- text_input,
234
- voice_input,
235
- ],
236
- outputs=audio_output,
237
- api_name="generate",
238
- )
239
-
240
- gr.Markdown(
241
- """
242
- ## Test instructions
243
-
244
- 1. Enter a short Myanmar sentence.
245
- 2. Select a voice.
246
- 3. Click Generate Audio.
247
- 4. Check whether the MP3 is playable.
248
- """
249
  )
250
 
251
-
252
  if __name__ == "__main__":
253
- demo.queue(max_size=5).launch(
254
- server_name="0.0.0.0",
255
- server_port=7860,
256
- )
 
 
 
 
 
 
1
  import gradio as gr
2
+ import edge_tts
3
+ import asyncio
4
+ import tempfile
5
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # မြန်မာနဲ့ အင်္ဂလိပ် အသံတချို့ကို Default ထည့်ပေးထားပါတယ်
8
+ VOICES = [
9
+ "my-MM-NilarNeural",
10
+ "my-MM-ThihaNeural",
11
+ "en-US-AriaNeural",
12
+ "en-US-GuyNeural"
13
+ ]
14
 
15
+ async def generate_tts(text, voice, proxy):
16
  if not text:
17
+ return None, "ကျေးဇူးပြု၍ စာသားထည့်ပါ။"
18
+
 
 
 
 
 
 
 
 
 
 
19
  try:
20
+ # အသံဖိုင်သိမ်းရန် Temporary file ဖန်တီးခြင်း
21
+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
22
+ temp_file.close()
23
+
24
+ # Proxy ထည့်ထားရင် သုံးမယ်၊ မထည့်ထားရင် None အနေနဲ့ ပုံမှန်အတိုင်း အလုပ်လုပ်မယ်
25
+ proxy_url = proxy if proxy.strip() != "" else None
26
+
27
+ # edge_tts ကို proxy parameter ထည့်ပြီး ခေါ်ခြင်း
28
+ communicate = edge_tts.Communicate(text, voice, proxy=proxy_url)
29
+ await communicate.save(temp_file.name)
30
+
31
+ return temp_file.name, "အောင်မြင်ပါသည်။"
32
+ except Exception as e:
33
+ return None, f"Error: {str(e)}"
34
+
35
+ def tts_interface(text, voice, proxy):
36
+ return asyncio.run(generate_tts(text, voice, proxy))
37
+
38
+ # Gradio Web UI ဒီဇိုင်း
39
+ with gr.Blocks(title="Edge TTS with Proxy") as app:
40
+ gr.Markdown("## Hugging Face Space အတွက် Edge TTS (Proxy Support)")
41
+ gr.Markdown("Proxy ကို `http://ip:port` သို့မဟုတ် `http://user:pass@ip:port` ပုံစံဖြင့် ထည့်သွင်းအသုံးပြုနိုင်ပါသည်။")
42
+
43
  with gr.Row():
44
+ with gr.Column():
45
+ text_input = gr.Textbox(label="စာသားထည့်ပါ (Text)", lines=7, placeholder="မြန်မာ သို့မဟုတ် အင်္ဂလိပ်စာသား ထည့်ပါ...")
46
+ voice_dropdown = gr.Dropdown(choices=VOICES, value="my-MM-NilarNeural", label="အသံရွေးချယ်ပါ (Voice)")
47
+ proxy_input = gr.Textbox(
48
+ label="Proxy URL (Optional)",
49
+ placeholder="http://123.45.67.89:8080 (RunPod သို့မဟုတ် အခြား Proxy ကို ထည့်ပါ)"
50
+ )
51
+ submit_btn = gr.Button("အသံဖန်တီးမည် (Generate TTS)", variant="primary")
52
+
53
+ with gr.Column():
54
+ audio_output = gr.Audio(label="ထွက်ပေါ်လာသောအသံ (Output Audio)", type="filepath")
55
+ status_output = gr.Textbox(label="အခြေအနေ (Status)")
56
+
57
+ submit_btn.click(
58
+ fn=tts_interface,
59
+ inputs=[text_input, voice_dropdown, proxy_input],
60
+ outputs=[audio_output, status_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  )
62
 
 
63
  if __name__ == "__main__":
64
+ app.launch()