File size: 8,518 Bytes
63f1d6d
 
 
 
9d562d5
b8dff41
92f766b
 
 
 
b8dff41
 
65c0339
b8dff41
65c0339
b8dff41
 
92f766b
b8dff41
 
8c1a544
b8dff41
92f766b
b8dff41
 
8c1a544
92f766b
b8dff41
92f766b
b8dff41
65c0339
b8dff41
65c0339
b8dff41
 
 
 
 
 
 
 
 
92f766b
b8dff41
92f766b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d645fd7
92f766b
 
 
 
 
 
 
 
 
d645fd7
92f766b
 
 
 
 
 
 
 
 
 
 
 
 
 
63f1d6d
92f766b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import gradio as gr
import edge_tts
import asyncio
import tempfile
import re
import emoji
from flask import Flask, request, jsonify, render_template_string

app = Flask(__name__)

# Функция для очистки текста от нежелательных символов и эмодзи
def clean_text(text):
    # Удаление указанных символов
    text = re.sub(r'[*_~><]', '', text)
    # Удаление эмодзи
    text = emoji.replace_emoji(text, replace='')
    return text

# Get all available voices
async def get_voices():
    voices = await edge_tts.list_voices()
    return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}

# Text-to-speech function
async def text_to_speech(text, voice, rate, pitch):
    if not text.strip():
        return None, "Пожалуйста, введите текст для озвучки."
    if not voice:
        return None, "Пожалуйста, выберите голос."
    
    # Очистка текста
    text = clean_text(text)
    
    voice_short_name = voice.split(" - ")[0]
    rate_str = f"{rate:+d}%"
    pitch_str = f"{pitch:+d}Hz"
    communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)
    with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
        tmp_path = tmp_file.name
        try:
            await communicate.save(tmp_path)
        except Exception as e:
            return None, f"Произошла ошибка при конвертации текста в речь: {str(e)}"
    return tmp_path, None

# HTML шаблон
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Озвучка с музыкальной атмосферой</title>
    <style>
        body {
            background-color: white;
            color: #FF6347; /* Томатный оранжевый */
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }

        header {
            background-color: #FF6347;
            color: white;
            padding: 10px 20px;
            text-align: center;
        }

        .container {
            padding: 20px;
        }

        .audio-control {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background-color: white;
            border: 1px solid #FF6347;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        button {
            background-color: #FF6347;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }

        button:hover {
            background-color: #FF4500; /* Темный томатный оранжевый */
        }
    </style>
</head>
<body>
    <header>
        <h1>Озвучка с музыкальной атмосферой</h1>
    </header>
    <div class="container">
        <textarea id="text-input" rows="5" placeholder="Введите текст для озвучки"></textarea>
        <br>
        <select id="voice-select">
            <!-- Опции будут заполнены через JavaScript -->
        </select>
        <br>
        <label for="rate-slider">Скорость озвучки:</label>
        <input type="range" id="rate-slider" min="-50" max="50" value="0" step="1">
        <br>
        <label for="pitch-slider">Тон озвучки:</label>
        <input type="range" id="pitch-slider" min="-20" max="20" value="0" step="1">
        <br>
        <button onclick="generateAudio()">Озвучить</button>
        <br>
        <audio id="audio-player" controls style="display:none;"></audio>
    </div>
    <div class="audio-control">
        <label for="atmosphere-select">Атмосфера:</label>
        <select id="atmosphere-select">
            <option value="dynamic">Динамичная</option>
            <option value="calm">Спокойная</option>
        </select>
        <br>
        <button onclick="toggleMusic()">Выключить музыку</button>
        <audio id="background-music" loop></audio>
    </div>
    <script>
        let voices = [];
        let currentMusic = null;

        document.addEventListener('DOMContentLoaded', () => {
            fetch('/get_voices')
                .then(response => response.json())
                .then(data => {
                    voices = data;
                    const voiceSelect = document.getElementById('voice-select');
                    Object.keys(voices).forEach(key => {
                        const option = document.createElement('option');
                        option.value = voices[key];
                        option.textContent = key;
                        voiceSelect.appendChild(option);
                    });
                });

            const atmosphereSelect = document.getElementById('atmosphere-select');
            atmosphereSelect.addEventListener('change', () => {
                changeMusic(atmosphereSelect.value);
            });

            changeMusic(atmosphereSelect.value); // Устанавливаем музыку по умолчанию
        });

        function generateAudio() {
            const text = document.getElementById('text-input').value;
            const voice = document.getElementById('voice-select').value;
            const rate = document.getElementById('rate-slider').value;
            const pitch = document.getElementById('pitch-slider').value;

            if (!text.trim()) {
                alert('Пожалуйста, введите текст для озвучки.');
                return;
            }
            if (!voice) {
                alert('Пожалуйста, выберите голос.');
                return;
            }

            fetch('/tts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ text, voice, rate, pitch })
            })
            .then(response => response.json())
            .then(data => {
                if (data.warning) {
                    alert(data.warning);
                } else {
                    const audioPlayer = document.getElementById('audio-player');
                    audioPlayer.src = data.audio;
                    audioPlayer.style.display = 'block';
                    audioPlayer.play();
                    audioPlayer.addEventListener('ended', () => {
                        document.getElementById('background-music').play();
                    });
                }
            });
        }

        function changeMusic(atmosphere) {
            const backgroundMusic = document.getElementById('background-music');
            backgroundMusic.src = `/music/${atmosphere}.mp3`;
            backgroundMusic.play();
            currentMusic = atmosphere;
        }

        function toggleMusic() {
            const backgroundMusic = document.getElementById('background-music');
            if (backgroundMusic.paused) {
                backgroundMusic.play();
                document.querySelector('.audio-control button').textContent = 'Выключить музыку';
            } else {
                backgroundMusic.pause();
                document.querySelector('.audio-control button').textContent = 'Включить музыку';
            }
        }
    </script>
</body>
</html>
"""

@app.route('/get_voices', methods=['GET'])
async def get_voices_route():
    voices = await get_voices()
    return jsonify(voices)

@app.route('/tts', methods=['POST'])
async def tts_route():
    data = request.get_json()
    text = data.get('text', '')
    voice = data.get('voice', '')
    rate = data.get('rate', 0)
    pitch = data.get('pitch', 0)
    
    audio, warning = await text_to_speech(text, voice, rate, pitch)
    if warning:
        return jsonify({'warning': warning})
    else:
        return jsonify({'audio': audio})

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/music/<path:path>')
def serve_music(path):
    return app.send_static_file(f'music/{path}')

if __name__ == "__main__":
    app.run(debug=True)