File size: 26,218 Bytes
ed290ee
 
 
5df9ee2
ed290ee
 
 
96bf80c
ab257e2
ed290ee
ab257e2
ed290ee
 
 
1daf416
1b73690
ed290ee
96bf80c
 
 
ed290ee
 
 
 
 
 
 
 
 
ab257e2
 
 
 
ed290ee
 
 
 
 
 
 
 
774840a
ed290ee
 
ab257e2
ed290ee
 
 
 
 
 
 
 
 
ab257e2
 
 
ed290ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab257e2
 
 
 
ed290ee
 
 
ab257e2
ed290ee
 
 
 
 
 
 
ab257e2
 
 
 
 
 
 
 
ed290ee
 
da07fc5
1b73690
 
 
 
 
 
af2d743
1b73690
fbf03ad
 
 
 
 
 
 
1b73690
 
 
ab257e2
 
1b73690
 
1daf416
ed290ee
 
 
 
 
ab257e2
ed290ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1daf416
ed290ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab257e2
 
ed290ee
 
 
 
ab257e2
ed290ee
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed290ee
ab257e2
 
 
 
 
ed290ee
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
 
 
 
f40111a
ab257e2
 
 
 
 
ed290ee
ab257e2
ed290ee
ab257e2
 
 
 
 
 
 
f40111a
 
ab257e2
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
f40111a
ab257e2
f40111a
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f40111a
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed290ee
 
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed290ee
 
ab257e2
 
 
 
da07fc5
ab257e2
 
 
 
 
 
 
da07fc5
 
ed290ee
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed290ee
ab257e2
ed290ee
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed290ee
 
 
ab257e2
 
ed290ee
 
 
 
 
 
ab257e2
 
ed290ee
 
ab257e2
 
 
 
 
 
 
 
ed290ee
ab257e2
 
 
1b73690
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
ed290ee
ab257e2
 
 
 
 
 
 
 
 
 
ed290ee
ab257e2
 
 
 
 
 
 
ed290ee
ab257e2
 
ed290ee
1b73690
 
 
 
ab257e2
 
 
 
 
 
 
 
 
 
 
 
1b73690
 
ed290ee
ab257e2
 
 
 
 
 
ed290ee
 
 
ab257e2
 
 
ed290ee
 
 
 
 
 
 
 
 
 
 
 
 
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
#!/usr/bin/env python3
"""
ZipVoice Gradio Web Interface for HuggingFace Spaces
Updated for Gradio 5.47.0 compatibility
"""

import os
import sys
import json
import tempfile

import gradio as gr
import torch
from pathlib import Path
import spaces
import whisper

# Add current directory to Python path for local zipvoice package
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Import ZipVoice components
from zipvoice.models.zipvoice import ZipVoice
from zipvoice.models.zipvoice_distill import ZipVoiceDistill
from zipvoice.tokenizer.tokenizer import EmiliaTokenizer
from zipvoice.utils.checkpoint import load_checkpoint
from zipvoice.utils.feature import VocosFbank
from zipvoice.bin.infer_zipvoice import generate_sentence
from lhotse.utils import fix_random_seed


# Global caches for lazy loading
_models_cache: dict[str, dict[str, object]] = {}
_tokenizer_cache: EmiliaTokenizer | None = None
_vocoder_cache = None
_feature_extractor_cache = None


def load_models_and_components(model_name: str):
    """Load and cache models, tokenizer, vocoder, and feature extractor."""
    global _models_cache, _tokenizer_cache, _vocoder_cache, _feature_extractor_cache

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    if model_name not in _models_cache:
        print(f"Loading {model_name} model…")

        model_dir_map = {
            "zipvoice": "zipvoice",
            "zipvoice_distill": "zipvoice_distill",
        }

        huggingface_repo = "k2-fsa/ZipVoice"
        from huggingface_hub import hf_hub_download

        model_ckpt = hf_hub_download(huggingface_repo, filename=f"{model_dir_map[model_name]}/model.pt")
        model_config_path = hf_hub_download(huggingface_repo, filename=f"{model_dir_map[model_name]}/model.json")
        token_file = hf_hub_download(huggingface_repo, filename=f"{model_dir_map[model_name]}/tokens.txt")

        if _tokenizer_cache is None:
            _tokenizer_cache = EmiliaTokenizer(token_file=token_file)
        tokenizer = _tokenizer_cache
        tokenizer_config = {"vocab_size": tokenizer.vocab_size, "pad_id": tokenizer.pad_id}

        with open(model_config_path, "r") as f:
            model_config = json.load(f)

        if model_name == "zipvoice":
            model = ZipVoice(**model_config["model"], **tokenizer_config)
        else:
            model = ZipVoiceDistill(**model_config["model"], **tokenizer_config)

        load_checkpoint(filename=model_ckpt, model=model, strict=True)
        model = model.to(device)
        model.eval()

        _models_cache[model_name] = {
            "model": model,
            "sampling_rate": model_config["feature"]["sampling_rate"],
        }

    if _vocoder_cache is None:
        from vocos import Vocos

        _vocoder_cache = Vocos.from_pretrained("charactr/vocos-mel-24khz")
        _vocoder_cache = _vocoder_cache.to(device)
        _vocoder_cache.eval()

    if _feature_extractor_cache is None:
        _feature_extractor_cache = VocosFbank()

    entry = _models_cache[model_name]
    return (
        entry["model"],
        _tokenizer_cache,
        _vocoder_cache,
        _feature_extractor_cache,
        entry["sampling_rate"],
    )


@spaces.GPU
def transcribe_audio_whisper(audio_file):
    """Transcribe audio file using Whisper."""
    if audio_file is None:
        return "Error: Please upload an audio file first."

    try:
        model = whisper.load_model("small")

        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
            temp_audio_path = temp_audio.name
            with open(temp_audio_path, "wb") as f:
                f.write(audio_file)

        result = model.transcribe(temp_audio_path)
        os.unlink(temp_audio_path)

        return result["text"].strip()

    except Exception as exc:  # pylint: disable=broad-except
        return f"Error during transcription: {exc}"


@spaces.GPU
def synthesize_speech_gradio(
    text: str,
    prompt_audio_file,
    prompt_text: str,
    model_name: str,
    speed: float,
):
    """Synthesize speech using ZipVoice for Gradio interface."""
    if not text.strip():
        return None, "Error: Please enter text to synthesize."

    if prompt_audio_file is None:
        return None, "Error: Please upload a prompt audio file."

    if not prompt_text.strip():
        return None, "Error: Please enter the transcription of the prompt audio."

    try:
        fix_random_seed(666)

        model, tokenizer, vocoder, feature_extractor, sampling_rate = load_models_and_components(model_name)
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
            temp_audio_path = temp_audio.name
            with open(temp_audio_path, "wb") as f:
                f.write(prompt_audio_file)

        with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_output:
            output_path = temp_output.name

        print(f"Synthesizing: '{text}' using {model_name}")
        print(f"Prompt: {prompt_text}")
        print(f"Speed: {speed}")

        with torch.inference_mode():
            metrics = generate_sentence(
                save_path=output_path,
                prompt_text=prompt_text,
                prompt_wav=temp_audio_path,
                text=text,
                model=model,
                vocoder=vocoder,
                tokenizer=tokenizer,
                feature_extractor=feature_extractor,
                device=device,
                num_step=16 if model_name == "zipvoice" else 8,
                guidance_scale=1.0 if model_name == "zipvoice" else 3.0,
                speed=speed,
                t_shift=0.5,
                target_rms=0.1,
                feat_scale=0.1,
                sampling_rate=sampling_rate,
                max_duration=100,
                remove_long_sil=False,
            )

        with open(output_path, "rb") as f:
            audio_data = f.read()

        os.unlink(temp_audio_path)
        os.unlink(output_path)

        success_msg = f"Synthesis completed! Duration: {metrics['wav_seconds']:.2f}s, RTF: {metrics['rtf']:.2f}"
        return audio_data, success_msg

    except Exception as exc:  # pylint: disable=broad-except
        error_msg = f"Error during synthesis: {exc}"
        print(error_msg)
        return None, error_msg
def create_gradio_interface():
    """Create the Gradio web interface."""
    gpu_available = torch.cuda.is_available()

    css = """
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --accent-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        --warning-gradient: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        --surface: #ffffff;
        --surface-muted: #f8fafc;
        --surface-soft: #f1f5f9;
        --text-strong: #0f172a;
        --text: #1f2937;
        --text-muted: #64748b;
        --border: #e2e8f0;
        --shadow-sm: 0 1px 3px rgba(15, 23, 42, 0.08);
        --shadow-md: 0 8px 24px rgba(15, 23, 42, 0.08);
        --radius-sm: 8px;
        --radius-md: 14px;
        --radius-lg: 20px;
    }

    body {
        background: var(--surface-muted);
    }

    .gradio-container {
        max-width: 1180px;
        margin: 0 auto;
        padding: 0 24px 48px;
        font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        color: var(--text-strong);
    }

    .header-section {
        background: var(--surface);
        border-radius: var(--radius-lg);
        padding: 2.4rem;
        margin: 2.5rem 0 2rem;
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border);
    }

    .logo-section {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .logo-icon {
        font-size: 3rem;
        background: var(--primary-gradient);
        -webkit-background-clip: text;
        color: transparent;
    }

    .title {
        font-size: 2.6rem;
        font-weight: 800;
        background: var(--primary-gradient);
        -webkit-background-clip: text;
        color: transparent;
        margin: 0;
        letter-spacing: -0.03em;
    }

    .subtitle {
        margin: 0.35rem 0 0;
        font-size: 1.05rem;
        color: var(--text-muted);
        font-weight: 500;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.55rem 1.2rem;
        border-radius: 999px;
        font-size: 0.85rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        color: #fff;
        box-shadow: var(--shadow-sm);
    }

    .status-badge.gpu {
        background: var(--success-gradient);
    }

    .status-badge.cpu {
        background: var(--warning-gradient);
    }

    .steps-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }

    .step-chip {
        background: var(--surface);
        border-radius: var(--radius-md);
        padding: 1rem 1.2rem;
        display: flex;
        flex-direction: column;
        gap: 0.35rem;
        box-shadow: var(--shadow-sm);
        border: 1px solid var(--border);
    }

    .step-chip span {
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.12em;
        color: var(--text-muted);
    }

    .step-chip strong {
        font-size: 0.95rem;
        color: var(--text-strong);
    }

    .layout-grid {
        display: grid;
        grid-template-columns: minmax(0, 3fr) minmax(0, 2fr);
        gap: 2rem;
        align-items: start;
        margin-bottom: 2.5rem;
    }

    .input-card,
    .output-card {
        background: var(--surface);
        border-radius: var(--radius-lg);
        padding: 1.8rem;
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border);
        display: flex;
        flex-direction: column;
        gap: 1.25rem;
    }

    .section-title {
        font-size: 1.2rem;
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 0.6rem;
        color: var(--text-strong);
    }

    .section-subtitle {
        font-size: 0.95rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.1em;
        color: var(--text-muted);
    }

    .helper-text {
        font-size: 0.85rem;
        color: var(--text-muted);
        margin-top: -0.35rem;
    }

    .file-drop {
        border: 2px dashed var(--border) !important;
        border-radius: var(--radius-md) !important;
        background: var(--surface-soft) !important;
        transition: all 0.25s ease;
        padding: 1rem;
    }

    .file-drop:hover {
        border-color: #667eea !important;
        background: rgba(102, 126, 234, 0.08) !important;
    }

    .button-row {
        display: flex;
        gap: 0.6rem;
        flex-wrap: wrap;
    }

    .btn-primary {
        background: var(--primary-gradient) !important;
        color: #fff !important;
        border: none !important;
        border-radius: var(--radius-md) !important;
        font-weight: 600 !important;
        letter-spacing: 0.05em;
        padding: 0.9rem 1.6rem !important;
        box-shadow: var(--shadow-md);
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .btn-secondary {
        background: var(--surface-soft) !important;
        color: var(--text-strong) !important;
        border-radius: var(--radius-md) !important;
        border: 1px solid var(--border) !important;
        font-weight: 600 !important;
        padding: 0.75rem 1.4rem !important;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .btn-danger {
        background: var(--warning-gradient) !important;
        color: #fff !important;
        border-radius: var(--radius-md) !important;
        border: none !important;
        font-weight: 600 !important;
        padding: 0.75rem 1.2rem !important;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .btn-primary:hover,
    .btn-secondary:hover,
    .btn-danger:hover {
        transform: translateY(-1px);
        box-shadow: var(--shadow-md);
    }

    .divider {
        height: 1px;
        width: 100%;
        background: var(--border);
        margin: 0.5rem 0 0.75rem;
    }

    .text-area textarea,
    .text-input textarea,
    .text-input input {
        background: var(--surface-soft);
        border: 1.5px solid var(--border);
        border-radius: var(--radius-md);
        transition: border-color 0.25s ease, box-shadow 0.25s ease;
        font-size: 1rem;
    }

    .text-area textarea:focus,
    .text-input textarea:focus,
    .text-input input:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
        background: var(--surface);
    }

    .advanced-settings {
        border-radius: var(--radius-md);
        background: var(--surface-soft);
        border: 1px solid var(--border);
        box-shadow: var(--shadow-sm);
    }

    .status-box {
        background: var(--surface-soft);
        border: 1px solid rgba(102, 126, 234, 0.25);
        border-radius: var(--radius-md);
        padding: 1rem;
        font-size: 0.95rem;
        color: #334155;
        box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.05);
        min-height: 82px;
    }

    .status-box pre {
        white-space: pre-wrap;
    }

    .progress-indicator {
        display: none;
    }

    .progress-indicator.active {
        display: flex;
        align-items: center;
        gap: 0.85rem;
        background: rgba(102, 126, 234, 0.1);
        border: 1px solid rgba(102, 126, 234, 0.25);
        border-radius: var(--radius-md);
        padding: 0.85rem 1.1rem;
        color: #4c51bf;
        font-weight: 600;
    }

    .progress-indicator .spinner {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        border: 3px solid rgba(102, 126, 234, 0.25);
        border-top-color: #6366f1;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    .audio-player {
        background: var(--surface-soft);
        border-radius: var(--radius-md);
        border: 1px solid var(--border);
        padding: 1rem;
    }

    .audio-player button.download {
        background: var(--primary-gradient) !important;
        color: #fff !important;
        border-radius: var(--radius-sm) !important;
        border: none !important;
        font-weight: 600 !important;
        margin-top: 0.75rem;
        box-shadow: var(--shadow-sm);
    }

    .examples-deck {
        background: var(--surface);
        border-radius: var(--radius-lg);
        padding: 1.6rem;
        box-shadow: var(--shadow-md);
        border: 1px solid var(--border);
    }

    .examples-deck .section-title {
        margin-bottom: 1rem;
    }

    .footer {
        text-align: center;
        margin-top: 2.5rem;
        padding: 1.5rem;
        background: var(--surface);
        border-radius: var(--radius-lg);
        border: 1px solid var(--border);
        box-shadow: var(--shadow-sm);
        color: var(--text-muted);
        font-size: 0.9rem;
    }

    .footer-links {
        margin-top: 0.75rem;
        display: flex;
        justify-content: center;
        gap: 1.75rem;
    }

    .footer-link {
        color: var(--text-muted);
        text-decoration: none;
        font-weight: 600;
    }

    .footer-link:hover {
        color: #6366f1;
    }

    @media (max-width: 1024px) {
        .layout-grid {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 768px) {
        .gradio-container {
            padding: 0 16px 32px;
        }

        .header-section {
            padding: 1.8rem;
        }

        .logo-section {
            flex-direction: column;
            text-align: center;
            gap: 0.6rem;
        }

        .title {
            font-size: 2.1rem;
        }

        .steps-row {
            grid-template-columns: 1fr;
        }

        .button-row {
            flex-direction: column;
        }
    }

    @media (prefers-color-scheme: dark) {
        :root {
            --surface: #1f2937;
            --surface-muted: #0f172a;
            --surface-soft: #273549;
            --text-strong: #f8fafc;
            --text: #e2e8f0;
            --text-muted: #94a3b8;
            --border: #324155;
        }

        .status-box {
            border-color: rgba(99, 102, 241, 0.45);
            color: #cbd5f5;
        }

        .progress-indicator.active {
            background: rgba(99, 102, 241, 0.2);
            border-color: rgba(99, 102, 241, 0.4);
            color: #cbd5f5;
        }
    }
    """

    with gr.Blocks(title="ZipVoice — Zero-Shot TTS", css=css, theme=gr.themes.Soft()) as interface:

        with gr.Column(elem_classes="header-section"):
            with gr.Row():
                with gr.Column(scale=3):
                    gr.HTML("""
                        <div class='logo-section'>
                            <div class='logo-icon'>🎵</div>
                            <div>
                                <h1 class='title'>ZipVoice</h1>
                                <p class='subtitle'>Zero-shot text-to-speech with instant voice cloning</p>
                            </div>
                        </div>
                    """)
                with gr.Column(scale=1, min_width=160):
                    if gpu_available:
                        gr.HTML("<div class='status-badge gpu'>⚡ GPU Ready</div>")
                    else:
                        gr.HTML("<div class='status-badge cpu'>💻 CPU Mode</div>")

        gr.HTML("""
            <div class='steps-row'>
                <div class='step-chip'>
                    <span>Step 1 / 步驟一</span>
                    <strong>Drop your reference voice (1–3 s) / 拖放 1–3 秒的參考語音</strong>
                </div>
                <div class='step-chip'>
                    <span>Step 2 / 步驟二</span>
                    <strong>Transcribe the prompt or let ZipVoice auto-transcribe / 手動或自動生成轉寫</strong>
                </div>
                <div class='step-chip'>
                    <span>Step 3 / 步驟三</span>
                    <strong>Write the target text and generate / 輸入目標文本並開始合成</strong>
                </div>
            </div>
        """)

        with gr.Row(elem_classes="layout-grid"):
            with gr.Column(elem_classes="input-card"):
                gr.HTML("<div class='section-title'>🎤 Voice Prompt / 參考語音</div>")
                prompt_audio = gr.File(
                    label="Drop or select an audio file / 拖放或選擇音頻文件",
                    file_types=["audio"],
                    type="binary",
                    elem_classes="file-drop"
                )

                with gr.Row(elem_classes="button-row"):
                    transcribe_btn = gr.Button(
                        "🎧 Auto Transcribe / 自動轉寫",
                        variant="secondary",
                        size="sm",
                        elem_classes="btn-secondary"
                    )
                    clear_prompt = gr.Button(
                        "🧹 Reset / 重置",
                        size="sm",
                        elem_classes="btn-danger"
                    )

                gr.HTML("<p class='helper-text'>Tip: use a clear 1–3 second sample for best results. 提示:請使用 1–3 秒的清晰語音,以獲得最佳效果。</p>")

                gr.HTML("<div class='section-subtitle'>📝 Prompt transcription / 提示文本</div>")
                prompt_text = gr.Textbox(
                    placeholder="Type the exact words from the prompt audio or run auto-transcribe… / 輸入參考語音的原文或使用自動轉寫",
                    lines=3,
                    elem_classes="text-area"
                )

                gr.HTML("<div class='divider'></div>")

                gr.HTML("<div class='section-title'>✍️ Text to Synthesize / 合成文本</div>")
                text_input = gr.Textbox(
                    placeholder="Enter the text you want to speak (English, Chinese, etc.) / 輸入需要朗讀的文本(支援英文、中文等)",
                    lines=5,
                    value="Hello, this is a ZipVoice demo showing instant zero-shot voice cloning.",
                    elem_classes="text-area"
                )

                with gr.Row(elem_classes="button-row"):
                    generate_btn = gr.Button(
                        "🎵 Generate Voice / 開始合成",
                        variant="primary",
                        size="lg",
                        elem_classes="btn-primary"
                    )

                with gr.Accordion("Advanced settings / 高級設定", open=False, elem_classes="advanced-settings"):
                    model_dropdown = gr.Dropdown(
                        choices=["zipvoice", "zipvoice_distill"],
                        value="zipvoice",
                        label="Model / 模型",
                        info="zipvoice = highest fidelity · zipvoice_distill = faster generation / zipvoice = 最高音質 · zipvoice_distill = 更快生成"
                    )
                    speed_slider = gr.Slider(
                        minimum=0.5,
                        maximum=2.0,
                        value=1.0,
                        step=0.1,
                        label="Speaking speed / 語速",
                        info="0.5 = slower · 1.0 = natural · 2.0 = faster / 0.5 = 慢速 · 1.0 = 自然 · 2.0 = 快速"
                    )

            with gr.Column(elem_classes="output-card"):
                gr.HTML("<div class='section-title'>🔊 Result & Status / 輸出與狀態</div>")
                progress_bar = gr.HTML(value="", elem_classes="progress-indicator")
                output_audio = gr.Audio(
                    label="Playback / 播放",
                    type="filepath",
                    elem_classes="audio-player",
                    show_download_button=True
                )
                status_text = gr.Markdown(
                    value="Ready to synthesize. Please upload a prompt and click generate! / 準備就緒:請上傳參考語音並開始合成。",
                    elem_classes="status-box"
                )

        with gr.Column(elem_classes="examples-deck"):
            gr.HTML("<div class='section-title'>⚡ Quick Examples / 快速範例</div>")
            gr.Examples(
                examples=[
                    ["Hello everyone, welcome to ZipVoice.", "jfk.wav", "ask not what your country can do for you, ask what you can do for your country", "zipvoice", 1.0],
                    ["請在會議開始時靜音您的麥克風。", "jfk.wav", "ask not what your country can do for you, ask what you can do for your country", "zipvoice", 1.0],
                    ["Innovation starts with listening carefully to your users.", "jfk.wav", "ask not what your country can do for you, ask what you can do for your country", "zipvoice_distill", 1.2],
                ],
                inputs=[text_input, prompt_audio, prompt_text, model_dropdown, speed_slider],
                examples_per_page=3,
                label="Try a scenario in one click / 一鍵體驗範例"
            )

        gr.HTML("""
            <div class='footer'>
                <p>Created with ❤️ by the ZipVoice team on Gradio / 由 ZipVoice 團隊基於 Gradio 構建</p>
                <div class='footer-links'>
                    <a href='https://github.com/k2-fsa/ZipVoice' class='footer-link' target='_blank'>Source code / 原始碼</a>
                    <a href='https://huggingface.co/k2-fsa' class='footer-link' target='_blank'>HuggingFace models / HuggingFace 模型</a>
                    <a href='https://gradio.app' class='footer-link' target='_blank'>Gradio framework / Gradio 框架</a>
                </div>
            </div>
        """)

        def show_progress():
            return """
                <div class='progress-indicator active'>
                    <div class='spinner'></div>
                    <span>Generating audio… 音頻合成中…</span>
                </div>
            """

        def hide_progress():
            return ""

        transcribe_btn.click(
            fn=transcribe_audio_whisper,
            inputs=[prompt_audio],
            outputs=[prompt_text]
        ).then(
            fn=lambda: "✅ Transcription ready. Review it before synthesis. / 自動轉寫完成,請確認後繼續。",
            outputs=[status_text]
        )

        clear_prompt.click(
            fn=lambda: (None, "", "🔄 Prompt cleared. Please upload a new sample. / 提示已清空,請重新上傳樣本。"),
            inputs=None,
            outputs=[prompt_audio, prompt_text, status_text]
        ).then(
            fn=lambda: "",
            outputs=[progress_bar]
        )

        generate_btn.click(
            fn=show_progress,
            outputs=[progress_bar]
        ).then(
            fn=lambda: "🎵 Generating now… this may take a few seconds. / 正在合成,請稍候。",
            outputs=[status_text]
        ).then(
            fn=synthesize_speech_gradio,
            inputs=[text_input, prompt_audio, prompt_text, model_dropdown, speed_slider],
            outputs=[output_audio, status_text]
        ).then(
            fn=hide_progress,
            outputs=[progress_bar]
        )

    return interface


if __name__ == "__main__":
    # Create and launch the interface
    interface = create_gradio_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=int(os.environ.get("PORT", 7860)),
        show_error=True
    )