File size: 3,460 Bytes
8a29a6a
 
 
 
8e1e76f
8a29a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e76f
 
 
 
 
 
 
 
 
 
 
 
8a29a6a
 
 
 
 
 
 
 
8e1e76f
 
8a29a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab7523d
 
8a29a6a
 
 
 
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
import gradio as gr
from supertonic import TTS
import tempfile
import os
import numpy as np  # <-- Добавляем numpy

# Initialize TTS
try:
    tts = TTS(auto_download=True)
except Exception as e:
    print(f"Error initializing TTS: {e}")

VOICES = ["M1", "M2", "M3", "M4", "M5", "F1", "F2", "F3", "F4", "F5"]

LANGUAGES = {
    "English": "en", "Korean": "ko", "Japanese": "ja", "Arabic": "ar",
    "Bulgarian": "bg", "Czech": "cs", "Danish": "da", "German": "de",
    "Greek": "el", "Spanish": "es", "Estonian": "et", "Finnish": "fi",
    "French": "fr", "Hindi": "hi", "Croatian": "hr", "Hungarian": "hu",
    "Indonesian": "id", "Italian": "it", "Lithuanian": "lt", "Latvian": "lv",
    "Dutch": "nl", "Polish": "pl", "Portuguese": "pt", "Romanian": "ro",
    "Russian": "ru", "Slovak": "sk", "Slovenian": "sl", "Swedish": "sv",
    "Turkish": "tr", "Ukrainian": "uk", "Vietnamese": "vi"
}

def generate_speech(text, voice, language_name):
    if not text.strip():
        raise gr.Error("Please enter some text.")
        
    try:
        lang_code = LANGUAGES[language_name]
        style = tts.get_voice_style(voice_name=voice)
        wav, duration = tts.synthesize(text, voice_style=style, lang=lang_code)
        
        # ==========================================
        # ИСПРАВЛЕНИЕ ОШИБКИ С DURATION
        # Превращаем в numpy массив, делаем плоским (flatten) 
        # и суммируем (на случай, если там массив из нескольких чанков)
        # ==========================================
        duration_array = np.asarray(duration).flatten()
        if duration_array.size > 0:
            readable_duration = float(duration_array.sum())
        else:
            readable_duration = 0.0
            
        # Создаем уникальный временный файл
        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
            output_path = tmp.name
            
        tts.save_audio(wav, output_path)
        
        return output_path, f"Generation Successful! \nDuration: {readable_duration:.2f}s"
    
    except Exception as e:
        import traceback
        traceback.print_exc() # Выведет точную ошибку в логи HF Spaces
        raise gr.Error(f"Generation failed: {str(e)}")

with gr.Blocks(theme='soft', title="Supertonic 3 TTS") as demo:
    gr.Markdown("# 🎙️ Supertonic 3: Multilingual TTS API")
    
    with gr.Row():
        with gr.Column(scale=1):
            input_text = gr.Textbox(label="Input Text", lines=4, value="Привет, как дела?")
            with gr.Row():
                voice_opt = gr.Dropdown(choices=VOICES, value="M2", label="Voice Style")
                lang_opt = gr.Dropdown(choices=sorted(list(LANGUAGES.keys())), value="Russian", label="Language")
            btn = gr.Button("Synthesize Speech", variant="primary")
            
        with gr.Column(scale=1):
            audio_output = gr.Audio(label="Synthesized Audio", type="filepath")
            status_box = gr.Textbox(label="Status", interactive=False)

    btn.click(
        fn=generate_speech, 
        inputs=[input_text, voice_opt, lang_opt], 
        outputs=[audio_output, status_box],
        api_name="generate"  # <--- ДОБАВЬ ЭТУ СТРОЧКУ
    )

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)