File size: 12,913 Bytes
62e3411
 
7037048
 
62e3411
 
7037048
 
 
62e3411
7037048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff78c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca1362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7037048
 
 
 
 
 
 
aca1362
 
 
 
 
 
 
 
 
 
 
7037048
 
 
 
 
 
 
 
93872e8
7037048
 
 
 
 
 
93872e8
7037048
 
9ff78c7
aca1362
 
7037048
 
 
 
93872e8
7037048
 
 
 
 
 
9ff78c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93872e8
7037048
93872e8
7037048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62e3411
 
 
7037048
4956922
 
3275e74
93872e8
3275e74
93872e8
3275e74
 
93872e8
4956922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b3d1f6
4956922
 
 
 
 
 
 
 
 
 
62e3411
93872e8
4956922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f37b04
4956922
 
 
 
 
 
 
7037048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62e3411
7037048
62e3411
 
 
 
 
 
 
 
7037048
4821af3
93872e8
4956922
3275e74
 
 
 
4956922
 
aca1362
3275e74
 
 
 
 
aca1362
3275e74
 
 
 
 
aca1362
3275e74
aca1362
3275e74
 
 
 
aca1362
3275e74
 
 
 
 
aca1362
62e3411
 
 
 
aca1362
 
62e3411
 
4956922
aca1362
7f37b04
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env python3
"""
Piper TTS Gradio Demo for Hugging Face Spaces
Supports Japanese and English text-to-speech using ONNX models
"""

import json
import logging

import gradio as gr
import numpy as np
import onnxruntime
from app_imports import ESPEAK_AVAILABLE, PYOPENJTALK_AVAILABLE

# Download models if not present
from download_models import download_models


# Ensure models are downloaded
download_models()


# Import optional dependencies
if PYOPENJTALK_AVAILABLE:
    import pyopenjtalk
if ESPEAK_AVAILABLE:
    from espeak_phonemizer import Phonemizer


# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Model configurations
MODELS = {
    "Japanese (Medium)": {
        "path": "models/ja_JP-test-medium.onnx",
        "config": "models/ja_JP-test-medium.onnx.json",
        "language": "ja",
    },
    "English (Test)": {
        "path": "models/test_voice.onnx",
        "config": "models/test_voice.onnx.json",
        "language": "en",
    },
}

# Basic English word to IPA mapping for common words
# This is a simplified fallback when espeak-ng is not available
ENGLISH_IPA_MAP = {
    "hello": "hɛloʊ",
    "world": "wɜrld",
    "this": "ðɪs",
    "is": "ɪz",
    "a": "ə",
    "test": "tɛst",
    "text": "tɛkst",
    "to": "tu",
    "speech": "spitʃ",
    "demo": "dɛmoʊ",
    "welcome": "wɛlkəm",
    "piper": "paɪpər",
    "tts": "titiɛs",
    "enjoy": "ɛndʒɔɪ",
    "high": "haɪ",
    "quality": "kwɑləti",
    "synthesis": "sɪnθəsɪs",
    "the": "ðə",
    "and": "ænd",
    "for": "fɔr",
    "with": "wɪð",
    "you": "ju",
    "can": "kæn",
    "it": "ɪt",
    "that": "ðæt",
    "have": "hæv",
    "from": "frʌm",
    "or": "ɔr",
    "which": "wɪtʃ",
    "one": "wʌn",
    "would": "wʊd",
    "all": "ɔl",
    "will": "wɪl",
    "there": "ðɛr",
    "say": "seɪ",
    "who": "hu",
    "make": "meɪk",
    "when": "wɛn",
    "time": "taɪm",
    "if": "ɪf",
    "no": "noʊ",
    "way": "weɪ",
    "has": "hæz",
    "yes": "jɛs",
    "good": "gʊd",
    "very": "vɛri",
}

# Japanese multi-character phoneme to Unicode PUA mapping
# This mapping must match the C++ implementation and training data
PHONEME_TO_PUA = {
    # Long vowels
    "a:": "\ue000",
    "i:": "\ue001",
    "u:": "\ue002",
    "e:": "\ue003",
    "o:": "\ue004",
    # Special consonants
    "cl": "\ue005",  # Geminate/glottal stop
    # Palatalized consonants
    "ky": "\ue006",
    "kw": "\ue007",
    "gy": "\ue008",
    "gw": "\ue009",
    "ty": "\ue00a",
    "dy": "\ue00b",
    "py": "\ue00c",
    "by": "\ue00d",
    # Affricates and special sounds
    "ch": "\ue00e",
    "ts": "\ue00f",
    "sh": "\ue010",
    "zy": "\ue011",
    "hy": "\ue012",
    # Palatalized nasals/liquids
    "ny": "\ue013",
    "my": "\ue014",
    "ry": "\ue015",
}


def load_model_config(config_path: str) -> dict:
    """Load model configuration from JSON file"""
    with open(config_path, encoding="utf-8") as f:
        return json.load(f)


def map_phonemes(phonemes: list[str]) -> list[str]:
    """Map multi-character phonemes to Unicode PUA characters"""
    result = []
    for phoneme in phonemes:
        if phoneme in PHONEME_TO_PUA:
            result.append(PHONEME_TO_PUA[phoneme])
        else:
            result.append(phoneme)
    return result


def text_to_phonemes(text: str, language: str) -> list[str]:
    """Convert text to phoneme strings based on language"""

    if language == "ja":
        if PYOPENJTALK_AVAILABLE:
            # Get phonemes from OpenJTalk
            labels = pyopenjtalk.extract_fullcontext(text)
            phonemes = []

            for label in labels:
                # Extract phoneme from label
                if "-" in label and "+" in label:
                    phoneme = label.split("-")[1].split("+")[0]
                    if phoneme not in ["sil", "pau"]:
                        phonemes.append(phoneme)

            # Add sentence markers
            phonemes = ["^"] + phonemes + ["$"]

            # Convert multi-character phonemes to Unicode PUA
            phonemes = map_phonemes(phonemes)
        else:
            logger.warning("pyopenjtalk not available, using fallback")
            # Simple fallback - just use dummy phonemes
            phonemes = ["^"] + list("aiueo") * 5 + ["$"]

    elif ESPEAK_AVAILABLE:  # English
        phonemizer = Phonemizer("en-us")
        phoneme_str = phonemizer.phonemize(text)
        # Convert phoneme string to list
        phonemes = ["^"] + list(phoneme_str.replace(" ", "")) + ["$"]
    else:
        logger.warning("espeak_phonemizer not available, using IPA fallback")
        # IPA-based fallback for better English pronunciation
        words = text.lower().split()
        phonemes = ["^"]

        for i, word in enumerate(words):
            # Add space between words
            if i > 0:
                phonemes.append(" ")

            # Remove punctuation from word
            clean_word = "".join(c for c in word if c.isalpha())

            if clean_word in ENGLISH_IPA_MAP:
                # Use IPA mapping if available
                ipa = ENGLISH_IPA_MAP[clean_word]
                phonemes.extend(list(ipa))
            else:
                # Fall back to character-by-character for unknown words
                phonemes.extend(list(clean_word))

        phonemes.append("$")

    return phonemes


def phonemes_to_ids(phonemes: list[str], config: dict) -> list[int]:
    """Convert phonemes to model input IDs"""
    phoneme_id_map = config.get("phoneme_id_map", {})

    ids = []
    for phoneme in phonemes:
        if phoneme in phoneme_id_map:
            ids.extend(phoneme_id_map[phoneme])
        else:
            # Use pad token for unknown phonemes
            ids.append(0)

    return ids


def synthesize_speech(
    text: str,
    model_name: str,
    speaker_id: int = 0,
    length_scale: float = 1.0,
    noise_scale: float = 0.667,
    noise_w: float = 0.8,
) -> tuple[int, np.ndarray]:
    """Generate speech from text using selected model"""

    if not text.strip():
        raise gr.Error("Please enter some text")

    if model_name not in MODELS:
        raise gr.Error("Invalid model selected")

    model_info = MODELS[model_name]
    config = load_model_config(model_info["config"])

    # Convert text to phoneme IDs
    phonemes = text_to_phonemes(text, model_info["language"])
    phoneme_ids = phonemes_to_ids(phonemes, config)

    if not phoneme_ids:
        raise gr.Error("Failed to convert text to phonemes")

    # Load ONNX model
    sess_options = onnxruntime.SessionOptions()
    sess_options.inter_op_num_threads = 1
    sess_options.intra_op_num_threads = 1

    try:
        model = onnxruntime.InferenceSession(
            model_info["path"],
            sess_options=sess_options,
            providers=["CPUExecutionProvider"],
        )
    except Exception as e:
        logger.error(f"Failed to load model: {e}")
        raise gr.Error(f"Failed to load model: {str(e)}") from e

    # Prepare inputs
    text_array = np.expand_dims(np.array(phoneme_ids, dtype=np.int64), 0)
    text_lengths = np.array([text_array.shape[1]], dtype=np.int64)
    scales = np.array([noise_scale, length_scale, noise_w], dtype=np.float32)

    # Handle speaker ID for multi-speaker models
    sid = None
    if config.get("num_speakers", 1) > 1:
        sid = np.array([speaker_id], dtype=np.int64)

    # Run inference
    try:
        inputs = {
            "input": text_array,
            "input_lengths": text_lengths,
            "scales": scales,
        }

        if sid is not None:
            inputs["sid"] = sid

        audio = model.run(None, inputs)[0]

        # Remove batch and channel dimensions
        audio = audio.squeeze()

        # Convert to int16
        audio = np.clip(audio * 32767, -32768, 32767).astype(np.int16)

        sample_rate = config.get("audio", {}).get("sample_rate", 22050)

        return sample_rate, audio

    except Exception as e:
        logger.error(f"Inference failed: {e}")
        raise gr.Error(f"Failed to generate speech: {str(e)}") from e


def create_interface():
    """Create Gradio interface"""
    with gr.Blocks(title="Piper TTS Demo") as interface:
        gr.Markdown("""
            # 🎙️ Piper TTS Demo

            High-quality text-to-speech synthesis supporting Japanese and English.

            This demo uses ONNX models for fast CPU inference.
            """)

        with gr.Row():
            with gr.Column(scale=2):
                model_dropdown = gr.Dropdown(
                    choices=list(MODELS.keys()),
                    label="Select Model",
                    value=list(MODELS.keys())[0],
                )

                text_input = gr.Textbox(
                    label="Text to synthesize",
                    placeholder="Enter text here...",
                    lines=3,
                )

                # Advanced Settings without Accordion (flattened)
                gr.Markdown("### Advanced Settings")

                speaker_id = gr.Number(
                    label="Speaker ID (for multi-speaker models)",
                    value=0,
                    precision=0,
                    minimum=0,
                    maximum=10,
                )

                length_scale = gr.Slider(
                    label="Speed (Lower = faster speech)",
                    minimum=0.5,
                    maximum=2.0,
                    value=1.0,
                    step=0.1,
                )

                noise_scale = gr.Slider(
                    label="Expressiveness",
                    minimum=0.0,
                    maximum=1.0,
                    value=0.667,
                    step=0.01,
                )

                noise_w = gr.Slider(
                    label="Phoneme Duration Variance",
                    minimum=0.0,
                    maximum=1.0,
                    value=0.8,
                    step=0.01,
                )

            synthesize_btn = gr.Button("Generate Speech", variant="primary")

        with gr.Column(scale=2):
            audio_output = gr.Audio(
                label="Generated Speech",
                type="numpy",
                autoplay=True,
            )

            gr.Markdown("""
                ### Tips:
                - Japanese model expects hiragana/kanji text
                - English model works with standard text
                - Adjust speed for faster/slower speech
                - Higher expressiveness = more natural variation
                """)

        # Examples
        gr.Examples(
            examples=[
                ["こんにちは、世界!今日はいい天気ですね。", "Japanese (Medium)"],
                [
                    "おはようございます。本日の会議は午後3時から始まります。",
                    "Japanese (Medium)",
                ],
                ["Hello world! This is a text to speech demo.", "English (Test)"],
                [
                    "Welcome to Piper TTS. Enjoy high quality speech synthesis.",
                    "English (Test)",
                ],
            ],
            inputs=[text_input, model_dropdown],
        )

        # Event handlers
        synthesize_btn.click(
            fn=synthesize_speech,
            inputs=[
                text_input,
                model_dropdown,
                speaker_id,
                length_scale,
                noise_scale,
                noise_w,
            ],
            outputs=audio_output,
        )

    return interface


def create_minimal_interface():
    """Create a minimal fallback interface if main interface fails"""
    with gr.Blocks(title="Piper TTS Demo") as interface:
        gr.Markdown("# 🎙️ Piper TTS Demo")

        text_input = gr.Textbox(
            label="Text to synthesize",
            placeholder="Enter text here...",
            lines=3,
        )

        model_dropdown = gr.Dropdown(
            choices=list(MODELS.keys()),
            label="Select Model",
            value=list(MODELS.keys())[0],
        )

        synthesize_btn = gr.Button("Generate Speech", variant="primary")

        audio_output = gr.Audio(
            label="Generated Speech",
            type="numpy",
        )

        synthesize_btn.click(
            fn=lambda text, model: synthesize_speech(text, model, 0, 1.0, 0.667, 0.8),
            inputs=[text_input, model_dropdown],
            outputs=audio_output,
        )

    return interface


# Create and launch the app
# Move interface creation inside main block to avoid context issues
interface = None

if __name__ == "__main__":
    # Create and launch interface
    interface = create_interface()
    # Launch with minimal configuration for Hugging Face Spaces
    interface.launch()