Files changed (1) hide show
  1. app.py +49 -96
app.py CHANGED
@@ -3,7 +3,47 @@ import edge_tts
3
  import asyncio
4
  import tempfile
5
  import os
 
 
 
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  async def get_voices():
8
  voices = await edge_tts.list_voices()
9
  return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
@@ -19,114 +59,27 @@ async def text_to_speech(text, voice, rate, pitch):
19
  pitch_str = f"{pitch:+d}Hz"
20
  communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
21
 
22
- # Save directly to mp3 file (Edge TTS actually outputs mp3 format)
23
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
24
  tmp_path = tmp_file.name
25
  await communicate.save(tmp_path)
26
 
27
  return tmp_path, None
28
 
29
- async def tts_interface(text, voice, rate, pitch):
30
- audio, warning = await text_to_speech(text, voice, rate, pitch)
31
- if warning:
32
- return audio, gr.Warning(warning)
33
- return audio, None
34
-
35
  async def create_demo():
36
  voices = await get_voices()
37
 
38
  with gr.Blocks(analytics_enabled=False) as demo:
39
- gr.Markdown("# 🎙️ Edge TTS Text-to-Speech")
40
-
41
- with gr.Row():
42
- with gr.Column(scale=1):
43
- gr.Markdown("## Text-to-Speech with Microsoft Edge TTS")
44
- gr.Markdown("""
45
- Convert text to speech using Microsoft Edge TTS.
46
- Adjust speech rate and pitch: 0 is default, positive values increase, negative values decrease.
47
- """)
48
-
49
- gr.HTML("""
50
- <div style="margin: 20px 0; padding: 15px; border: 1px solid #4CAF50; border-radius: 10px; background-color: #f1f8e9;">
51
- <p style="margin-top: 0;"><b>Looking for the new version with more features?</b></p>
52
- <p>The new version includes:</p>
53
- <ul>
54
- <li><b>SRT Subtitle Support</b>: Upload SRT files or input SRT format text</li>
55
- <li><b>File Upload</b>: Easily upload TXT or SRT files</li>
56
- <li><b>Smart Format Detection</b>: Detects plain text or SRT format</li>
57
- <li><b>MP3 Output</b>: Generate high-quality MP3 audio</li>
58
- </ul>
59
- <div style="text-align: center; margin-top: 15px;">
60
- <a href="https://text-to-speech.wingetgui.com/" target="_blank"
61
- style="display: inline-block;
62
- background: linear-gradient(45deg, #4CAF50, #8BC34A);
63
- color: white;
64
- padding: 12px 30px;
65
- text-decoration: none;
66
- border-radius: 30px;
67
- font-weight: bold;
68
- font-size: 16px;
69
- box-shadow: 0 4px 10px rgba(76, 175, 80, 0.3);
70
- transition: all 0.3s ease;">Try New Version ➔</a>
71
- </div>
72
- </div>
73
- """)
74
-
75
- with gr.Column(scale=1):
76
- gr.HTML("""
77
- <div style="height: 100%; background-color: #f0f8ff; padding: 15px; border-radius: 10px;">
78
- <h2 style="color: #1e90ff; margin-top: 0;">Turn Your Text Into Professional Videos!</h2>
79
- <ul style="list-style-type: none; padding-left: 0;">
80
- <li>✅ <b>40+ languages and 300+ voices supported</b></li>
81
- <li>✅ <b>Custom backgrounds, music, and visual effects</b></li>
82
- <li>✅ <b>Create engaging video content from simple text</b></li>
83
- <li>✅ <b>Perfect for educators, content creators, and marketers</b></li>
84
- </ul>
85
- <div style="text-align: center; margin-top: 20px;">
86
- <span style="font-size: 96px;">🎬</span>
87
- <div style="margin-top: 15px;">
88
- <a href="https://text2video.wingetgui.com/" target="_blank"
89
- style="display: inline-block;
90
- background: linear-gradient(45deg, #2196F3, #21CBF3);
91
- color: white;
92
- padding: 12px 30px;
93
- text-decoration: none;
94
- border-radius: 30px;
95
- font-weight: bold;
96
- font-size: 16px;
97
- box-shadow: 0 4px 10px rgba(33, 150, 243, 0.3);
98
- transition: all 0.3s ease;">Try Text-to-Video ➔</a>
99
- </div>
100
- </div>
101
- </div>
102
- """)
103
-
104
- with gr.Row():
105
- with gr.Column():
106
- text_input = gr.Textbox(label="Input Text", lines=5)
107
- voice_dropdown = gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value="")
108
- rate_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1)
109
- pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)
110
-
111
- generate_btn = gr.Button("Generate Speech", variant="primary")
112
-
113
- audio_output = gr.Audio(label="Generated Audio", type="filepath")
114
- warning_md = gr.Markdown(label="Warning", visible=False)
115
-
116
- generate_btn.click(
117
- fn=tts_interface,
118
- inputs=[text_input, voice_dropdown, rate_slider, pitch_slider],
119
- outputs=[audio_output, warning_md]
120
- )
121
-
122
- gr.Markdown("Experience the power of Edge TTS for text-to-speech conversion, and explore our advanced Text-to-Video Converter for even more creative possibilities!")
123
 
124
  return demo
125
 
126
- async def main():
127
- demo = await create_demo()
128
- demo.queue(default_concurrency_limit=50)
129
- demo.launch(show_api=False)
 
 
130
 
131
  if __name__ == "__main__":
132
- asyncio.run(main())
 
3
  import asyncio
4
  import tempfile
5
  import os
6
+ from fastapi import FastAPI, Request, HTTPException
7
+ from fastapi.responses import FileResponse, JSONResponse
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ import uvicorn
10
 
11
+ # --- FastAPI часть для API ---
12
+ app = FastAPI()
13
+
14
+ # Разрешаем CORS для всех доменов (можно ограничить только вашим сайтом)
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_methods=["POST", "GET"],
19
+ allow_headers=["*"],
20
+ )
21
+
22
+ @app.post("/api/tts")
23
+ async def api_tts(request: Request):
24
+ try:
25
+ data = await request.json()
26
+ text = data.get("text", "").strip()
27
+ voice = data.get("voice", "en-US-GuyNeural")
28
+ rate = data.get("rate", 0)
29
+ pitch = data.get("pitch", 0)
30
+
31
+ if not text:
32
+ raise HTTPException(status_code=400, detail="Text is required")
33
+
34
+ rate_str = f"{rate:+d}%"
35
+ pitch_str = f"{pitch:+d}Hz"
36
+
37
+ communicate = edge_tts.Communicate(text, voice, rate=rate_str, pitch=pitch_str)
38
+ output_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
39
+ await communicate.save(output_file)
40
+
41
+ return FileResponse(output_file, media_type="audio/mpeg")
42
+
43
+ except Exception as e:
44
+ raise HTTPException(status_code=500, detail=str(e))
45
+
46
+ # --- Gradio часть для интерфейса Spaces ---
47
  async def get_voices():
48
  voices = await edge_tts.list_voices()
49
  return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
 
59
  pitch_str = f"{pitch:+d}Hz"
60
  communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
61
 
 
62
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
63
  tmp_path = tmp_file.name
64
  await communicate.save(tmp_path)
65
 
66
  return tmp_path, None
67
 
 
 
 
 
 
 
68
  async def create_demo():
69
  voices = await get_voices()
70
 
71
  with gr.Blocks(analytics_enabled=False) as demo:
72
+ # ... (ваш текущий интерфейс Gradio без изменений) ...
73
+ # (оставьте всю разметку и логику как есть)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  return demo
76
 
77
+ # Запуск и совмещение FastAPI + Gradio
78
+ gradio_app = gr.mount_gradio_app(app, await create_demo(), path="/")
79
+
80
+ @gradio_app.get("/")
81
+ async def root():
82
+ return {"message": "Edge TTS API is running. Use /api/tts for API or / for Gradio UI."}
83
 
84
  if __name__ == "__main__":
85
+ uvicorn.run(gradio_app, host="0.0.0.0", port=7860)