File size: 57,451 Bytes
847b3d1
 
 
 
 
 
 
 
0cf32f4
 
 
 
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dad0cc
ba89a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71689dc
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca532e5
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca532e5
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fec06f4
 
847b3d1
 
 
 
 
 
 
d49a75f
6d85d09
ba5f696
0cf32f4
 
 
 
 
 
 
 
847b3d1
 
 
e19de70
847b3d1
 
1726600
664e148
847b3d1
 
 
 
 
 
 
 
24c7873
847b3d1
 
 
 
ba5f696
6040d25
27f8e79
847b3d1
 
 
 
 
 
fa349ab
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fff8d85
847b3d1
 
 
 
 
 
 
 
 
 
6040d25
847b3d1
 
 
 
 
 
 
6040d25
847b3d1
 
 
 
 
 
 
ebcd30d
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6040d25
847b3d1
 
 
 
 
 
 
6040d25
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a967fc
 
 
 
 
 
 
 
 
 
 
 
847b3d1
9a967fc
 
44ebf2d
9a967fc
 
 
 
 
 
 
 
 
847b3d1
9a967fc
847b3d1
 
 
9a967fc
 
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488d0ba
 
 
 
 
 
 
 
847b3d1
 
 
 
 
 
 
301a669
847b3d1
 
 
 
 
c6c1d03
847b3d1
39f1f8a
847b3d1
 
 
 
 
 
 
 
 
 
 
 
c6c1d03
af6efd0
847b3d1
 
 
7880330
12af871
847b3d1
 
 
4dfbfc6
847b3d1
c6c1d03
b8f4375
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6c1d03
847b3d1
 
 
 
 
 
 
 
 
fff8d85
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fff8d85
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6c1d03
 
 
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ace90
847b3d1
 
094e43d
30ace90
847b3d1
094e43d
30ace90
094e43d
30ace90
 
 
 
 
 
 
 
 
 
 
 
 
094e43d
 
ce01725
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fd946b
847b3d1
 
4fd946b
847b3d1
 
f2aeb95
847b3d1
f2aeb95
 
 
 
9ec26bf
f2aeb95
 
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
ce01725
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179537c
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
19a638a
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
ce01725
847b3d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179537c
847b3d1
 
 
 
 
 
 
 
 
 
9d3cb1a
edb41f1
 
9d3cb1a
edb41f1
9d3cb1a
edb41f1
9d3cb1a
 
 
847b3d1
d264c89
 
847b3d1
d264c89
 
 
 
 
6040d25
847b3d1
 
 
 
 
 
 
ca532e5
 
 
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
import gradio as gr
from gradio_client import Client
import os
import csv
import numpy as np
import scipy.io.wavfile as wavfile
import tempfile

# try:
#     client = Client(os.environ['src'])
# except:
#     client = Client("http://localhost:7860/") 

css = """
.gradio-container input::placeholder,
.gradio-container textarea::placeholder {
    color: #333333 !important;
}
code {
    background-color: #ffde9f;
    padding: 2px 4px;
    border-radius: 3px;
}
#settings-accordion summary {
    justify-content: center;
}
.examples-holder > .label {
    color: #b45309 !important;
    font-weight: 600;
}

.gr-checkbox label span,
.gr-check-radio label span,
[data-testid="checkbox"] label span,
.checkbox-container span {
    color: #ECF2F7 !important;
}
.gr-checkbox label span.selected,
.gr-check-radio label span.selected,
[data-testid="checkbox"].selected span {
    color: #FFD700 !important;
}

#advanced-accordion > button,
#advanced-accordion > button span,
#advanced-accordion > div > button,
#advanced-accordion > div > button span,
#advanced-accordion .label-wrap,
#advanced-accordion .label-wrap span,
#advanced-accordion > .open,
#advanced-accordion > .open span {
    color: #FFD700 !important;
}

.examples-table {
    border-collapse: collapse !important;
    width: 100% !important;
}

.examples-table tbody tr {
    background-color: #d4c896 !important;
    border-bottom: 2px solid #c4b886 !important;
}

.examples-table tbody tr:hover {
    background-color: #c9bd8b !important;
}

.examples-table tbody td {
    background-color: #d4c896 !important;
    padding: 12px 16px !important;
    color: #1a1a1a !important;
    font-weight: 500 !important;
    border: none !important;
}

.examples-table thead th {
    background-color: #bfb07a !important;
    color: #1a1a1a !important;
    font-weight: 600 !important;
    padding: 10px 16px !important;
}

.gallery,
.gr-examples,
.examples {
    background: transparent !important;
}

.gallery > div,
.gr-examples > div,
.examples > div {
    background: transparent !important;
}

.gallery button,
.gr-examples button,
.examples button,
.gr-sample-textbox,
button.sample {
    background-color: #d4c896 !important;
    border: 1px solid #c4b886 !important;
    color: #1a1a1a !important;
    font-weight: 500 !important;
    margin: 4px !important;
    padding: 10px 14px !important;
    border-radius: 6px !important;
    transition: background-color 0.2s ease !important;
}

.gallery button:hover,
.gr-examples button:hover,
.examples button:hover,
.gr-sample-textbox:hover,
button.sample:hover {
    background-color: #c9bd8b !important;
    border-color: #b4a876 !important;
}

#mono-examples-container .gallery button,
#mono-examples-container .gr-examples button,
#mono-examples-container .examples button,
#mono-examples-container button.sample {
    background-color: #d4c896 !important;
    border-color: #c4b886 !important;
}

#stereo-examples-container .gallery button,
#stereo-examples-container .gr-examples button,
#stereo-examples-container .examples button,
#stereo-examples-container button.sample {
    background-color: #c8d4a6 !important;
    border-color: #b8c496 !important;
}

#stereo-examples-container .gallery button:hover,
#stereo-examples-container .gr-examples button:hover,
#stereo-examples-container .examples button:hover,
#stereo-examples-container button.sample:hover {
    background-color: #bdc9a0 !important;
    border-color: #a8b486 !important;
}

.gr-examples table,
.examples table,
table.examples-table {
    width: 100% !important;
    border-collapse: collapse !important;
}

.gr-examples table tr,
.examples table tr {
    background-color: #d4c896 !important;
}

.gr-examples table tr:hover,
.examples table tr:hover {
    background-color: #c9bd8b !important;
}

.gr-examples table td,
.examples table td {
    background-color: inherit !important;
    padding: 12px 16px !important;
    color: #1a1a1a !important;
    font-weight: 500 !important;
    cursor: pointer !important;
}

.gr-examples .gr-samples-table,
.examples .gr-samples-table {
    background: transparent !important;
}

.gr-examples .gr-samples-table tr,
.examples .gr-samples-table tr {
    background-color: #d4c896 !important;
    margin-bottom: 4px !important;
}

.gr-examples > div > div,
.examples > div > div {
    background-color: #d4c896 !important;
    border-radius: 6px !important;
    margin: 4px !important;
    padding: 8px 12px !important;
}

.gr-examples > div > div:hover,
.examples > div > div:hover {
    background-color: #c9bd8b !important;
}

body {
    background: none !important;
}

body::before {
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    pointer-events: none;
    background: url('https://i.postimg.cc/1smD6GPf/gradio-theme-rin2.png') center center / cover no-repeat;
}

"""


def save_audio_to_temp(audio_data):
    if audio_data is None:
        return None
    sample_rate, audio_array = audio_data
    if isinstance(audio_array, list):
        audio_array = np.array(audio_array)
    if audio_array.dtype == np.float32 or audio_array.dtype == np.float64:
        audio_array = (audio_array * 32767).astype(np.int16)
    tmp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
    wavfile.write(tmp.name, sample_rate, audio_array)
    tmp.close()
    return tmp.name


def cleanup_temp(path):
    if path is not None:
        try:
            os.unlink(path)
        except:
            pass


def load_examples(csv_path):
    examples = []
    if not os.path.exists(csv_path):
        return examples
    try:
        with open(csv_path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f, delimiter=',', quotechar='"', doublequote=True)
            for row in reader:
                if len(row) >= 2:
                    audio_path = row[0].strip()
                    text = row[1].strip()
                    if text.startswith('"') and text.endswith('"'):
                        text = text[1:-1]
                    elif text.startswith("'") and text.endswith("'"):
                        text = text[1:-1]
                    if text.startswith('\u201c') and text.endswith('\u201d'):
                        text = text[1:-1]
                    if text.startswith('\u300c') and text.endswith('\u300d'):
                        text = text[1:-1]
                    
                    speaker_id = 1
                    if len(row) >= 3 and row[2].strip():
                        try:
                            speaker_id = int(row[2].strip())
                        except ValueError:
                            speaker_id = 1
                    
                    pregenerated_audio = None
                    if audio_path and audio_path.lower() != "none" and audio_path != "":
                        if not os.path.isabs(audio_path):
                            base_dir = os.path.dirname(csv_path)
                            audio_path = os.path.join(base_dir, audio_path)
                        if os.path.exists(audio_path):
                            pregenerated_audio = audio_path
                    examples.append([text, pregenerated_audio, speaker_id])
    except Exception as e:
        pass
    return examples


def run_generation_pipeline_client(
    raw_text,
    audio_prompt,
    use_stereo,
    speaker_id,
    cfg_scale,
    temperature,
    min_temp,
    max_temp,
    top_k,
    top_p,
    min_p,
    dry_multiplier,
    max_tokens,
    pan_idx,
    width_idx,
    seed,
):
    try:
        audio_path = save_audio_to_temp(audio_prompt)
        audio_for_api = None
        if audio_path is not None:
            audio_for_api = {"path": audio_path, "meta": {"_type": "gradio.FileData"}}

        result = client.predict(
            raw_text,
            audio_for_api,
            use_stereo,
            speaker_id,
            cfg_scale,
            temperature,
            min_temp,
            max_temp,
            top_k,
            top_p,
            min_p,
            dry_multiplier,
            max_tokens,
            pan_idx,
            width_idx,
            seed,
            "",
            api_name="/run_generation_pipeline"
        )

        cleanup_temp(audio_path)

        if result is None:
            return None, "Status: No response from server"

        if isinstance(result, (list, tuple)) and len(result) == 2:
            audio_result, status_msg = result
            if audio_result is not None:
                if isinstance(audio_result, str) and os.path.exists(audio_result):
                    sr, data = wavfile.read(audio_result)
                    return (sr, data), status_msg
                elif isinstance(audio_result, (list, tuple)) and len(audio_result) >= 2:
                    sr = audio_result[0]
                    data = audio_result[1]
                    if isinstance(data, list):
                        data = np.array(data)
                    return (sr, data), status_msg
            return None, status_msg

        return None, "Status: Unexpected response format from server"

    except Exception as e:
        cleanup_temp(audio_path if 'audio_path' in dir() else None)
        return None, f"Status: Connection error: {str(e)}"


def run_alchemy_pipeline_client(
    raw_text,
    ref_audio_1,
    ref_audio_2,
    mix_ratio,
    cfg_scale,
    speaker_cfg_scale,
    speaker_adaln_scale,
    temperature,
    min_temp,
    max_temp,
    temp_exponent,
    top_k,
    top_p,
    min_p,
    dry_multiplier,
    max_tokens,
    seed,
):
    try:
        ref1_path = save_audio_to_temp(ref_audio_1)
        ref2_path = save_audio_to_temp(ref_audio_2)

        ref1_for_api = None
        if ref1_path is not None:
            ref1_for_api = {"path": ref1_path, "meta": {"_type": "gradio.FileData"}}

        ref2_for_api = None
        if ref2_path is not None:
            ref2_for_api = {"path": ref2_path, "meta": {"_type": "gradio.FileData"}}

        result = client.predict(
            raw_text,
            ref1_for_api,
            ref2_for_api,
            mix_ratio,
            cfg_scale,
            speaker_cfg_scale,
            speaker_adaln_scale,
            temperature,
            min_temp,
            max_temp,
            temp_exponent,
            top_k,
            top_p,
            min_p,
            dry_multiplier,
            max_tokens,
            seed,
            "",
            api_name="/run_alchemy_pipeline"
        )

        cleanup_temp(ref1_path)
        cleanup_temp(ref2_path)

        if result is None:
            return None, "Status: No response from server"

        if isinstance(result, (list, tuple)) and len(result) == 2:
            audio_result, status_msg = result
            if audio_result is not None:
                if isinstance(audio_result, str) and os.path.exists(audio_result):
                    sr, data = wavfile.read(audio_result)
                    return (sr, data), status_msg
                elif isinstance(audio_result, (list, tuple)) and len(audio_result) >= 2:
                    sr = audio_result[0]
                    data = audio_result[1]
                    if isinstance(data, list):
                        data = np.array(data)
                    return (sr, data), status_msg
            return None, status_msg

        return None, "Status: Unexpected response format from server"

    except Exception as e:
        cleanup_temp(ref1_path if 'ref1_path' in dir() else None)
        cleanup_temp(ref2_path if 'ref2_path' in dir() else None)
        return None, f"Status: Connection error: {str(e)}"


examples_mono_csv_path = "samples/examples_mono.csv"
examples_stereo_csv_path = "samples/examples_stereo.csv"

example_list_mono = load_examples(examples_mono_csv_path)
example_list_stereo = load_examples(examples_stereo_csv_path)


with gr.Blocks(theme="Respair/Shiki@10.1.0", css=css) as demo:

    # gr.Markdown('<h1 style="text-align: center;">🪷 Takane - Mirei 「美嶺」 </h1>')
    # gr.HTML('<h1 style="text-align: center;">🪷 Takane - Mirei 「美嶺」 </h1>')
    # gr.HTML('<h1 style="text-align: center; font-size: 24px;">🪷 Takane - Mirei 「美嶺」 </h1>')
    # gr.Markdown(
    # """
    # <div style="text-align: left;">
    # 美嶺はゼロショットモデルではなく、話者ID付きで学習しているため、音声プロンプトとの話者類似性はどのみち低めになります。<br>
    # </div>
    # """
    # )

    gr.Markdown(
    """
    <div style="text-align: left;">
    Demo is closed until further notice; thank you for using it. Feel free to check the pre-generated samples at the <code>Examples</code> tab. <br>
    </div>
    """
    )

    with gr.Tabs():

        with gr.TabItem("Speech Generation"):
            with gr.Row():
                with gr.Column(scale=2):
                    text_input = gr.Textbox(
                        label="Text here",
                        lines=5,
                        max_length=125,
                        placeholder="ここでテキストを入力してください...\n\n"
                    )

                    use_stereo_checkbox = gr.Checkbox(
                        label="🎧 Use Stereo Mode",
                        value=False,
                        info="⚠️ ステレオ生成は現在無効になっています。"
                    )

                    with gr.Row(equal_height=False):
                        with gr.Accordion("----------------------------------⭐ 🛠️ ⭐", open=False):

                            audio_prompt_input = gr.Audio(
                                label="Audio Prompt (Optional — Please set Speaker ID to 1)",
                                sources=["upload", "microphone"],
                                type="numpy"
                            )

                            speaker_id_slider = gr.Slider(
                                label="Speaker ID",
                                minimum=1,
                                maximum=2000,
                                value=1,
                                step=1
                            )

                            gr.Markdown('<h3 style="color: #FFD700;">Common Parameters</h3>')

                            cfg_scale_slider = gr.Slider(
                                label="CFG Scale",
                                minimum=1.0,
                                maximum=3.0,
                                value=1.15,
                                step=0.05
                            )

                            temperature_slider = gr.Slider(
                                label="Temperature (Min/Max Temp の両方が 0 に設定されている場合のみ有効です)",
                                minimum=0.0,
                                maximum=2.0,
                                value=1.0,
                                step=0.05
                            )

                            min_temp_slider = gr.Slider(
                                label="Min Temperature (0 = off; ignored in stereo mode)",
                                minimum=0.0,
                                maximum=2.0,
                                value=0.25,
                                step=0.05
                            )

                            max_temp_slider = gr.Slider(
                                label="Max Temperature (0 = off; ignored in stereo mode)",
                                minimum=0.0,
                                maximum=2.0,
                                value=1.0,
                                step=0.05
                            )

                            top_k_slider = gr.Slider(
                                label="Top K (0 = off)",
                                minimum=0,
                                maximum=200,
                                value=0,
                                step=1
                            )

                            top_p_slider = gr.Slider(
                                label="Top P",
                                minimum=0.0,
                                maximum=1.0,
                                value=1.0,
                                step=0.01
                            )

                            min_p_slider = gr.Slider(
                                label="Min P (0 = off)",
                                minimum=0.0,
                                maximum=1.0,
                                value=0.0,
                                step=0.01
                            )

                            max_tokens_slider = gr.Slider(
                                label="Max Tokens",
                                minimum=100,
                                maximum=1500,
                                value=768,
                                step=10
                            )

                            dry_multiplier_slider = gr.Slider(
                                label="DRY Multiplier (0 = off)",
                                minimum=0.0,
                                maximum=2.0,
                                value=0.8,
                                step=0.1
                            )

                            seed_slider = gr.Slider(
                                label="Seed (-1 for random)",
                                minimum=-1,
                                maximum=2700000000,
                                value=-1,
                                step=1
                            )

                            gr.Markdown('<h3 style="color: #FFD700;">Stereo-Only Parameters</h3>')

                            pan_idx_slider = gr.Slider(
                                label="Pan (0=Left, 5=Center, 10=Right)",
                                minimum=0,
                                maximum=10,
                                value=2,
                                step=1
                            )

                            width_idx_slider = gr.Slider(
                                label="Stereo Width (0=Narrow, 10=Wide)",
                                minimum=0,
                                maximum=10,
                                value=5,
                                step=1
                            )

                        with gr.Column(scale=1):
                            generate_button = gr.Button("🎤 Generate", variant="primary", size="lg")

                with gr.Column(scale=1):
                    status_output = gr.Textbox(label="Status", interactive=False)
                    audio_output = gr.Audio(
                        label="Generated Speech",
                        interactive=False
                    )

            def on_stereo_toggle(use_stereo):
                if use_stereo:
                    temp, min_t, max_t, min_p_val = 1.0, 0.0, 0.0, 0.05
                    if len(example_list_stereo) >= 2:
                        ex = example_list_stereo[1]
                        text = ex[0]
                        sid = ex[2]
                        path = ex[1]
                        if path and os.path.exists(path):
                            sr, data = wavfile.read(path)
                            return (gr.update(value=temp), gr.update(value=min_t), gr.update(value=max_t), gr.update(value=min_p_val),
                                    gr.update(value=text), gr.update(value=sid), (sr, data), "Status: Stereo example loaded / ステレオ例を読み込みました")
                    return (gr.update(value=temp), gr.update(value=min_t), gr.update(value=max_t), gr.update(value=min_p_val),
                            gr.update(), gr.update(), gr.update(), gr.update())
                else:
                    temp, min_t, max_t, min_p_val = 1.0, 0.25, 1.0, 0.0
                    if len(example_list_mono) >= 2:
                        ex = example_list_mono[-1]
                        text = ex[0]
                        sid = ex[2]
                        path = ex[1]
                        if path and os.path.exists(path):
                            sr, data = wavfile.read(path)
                            return (gr.update(value=temp), gr.update(value=min_t), gr.update(value=max_t), gr.update(value=min_p_val),
                                    gr.update(value=text), gr.update(value=sid), (sr, data), "Status: Mono example loaded / モノラル例を読み込みました")
                    return (gr.update(value=temp), gr.update(value=min_t), gr.update(value=max_t), gr.update(value=min_p_val),
                            gr.update(), gr.update(), gr.update(), gr.update())

                    
            use_stereo_checkbox.change(
                fn=on_stereo_toggle,
                inputs=[use_stereo_checkbox],
                outputs=[temperature_slider, min_temp_slider, max_temp_slider, min_p_slider,
                         text_input, speaker_id_slider, audio_output, status_output]
            )
            
            generate_button.click(
                fn=run_generation_pipeline_client,
                inputs=[
                    text_input,
                    audio_prompt_input,
                    use_stereo_checkbox,
                    speaker_id_slider,
                    cfg_scale_slider,
                    temperature_slider,
                    min_temp_slider,
                    max_temp_slider,
                    top_k_slider,
                    top_p_slider,
                    min_p_slider,
                    dry_multiplier_slider,
                    max_tokens_slider,
                    pan_idx_slider,
                    width_idx_slider,
                    seed_slider,
                ],
                outputs=[audio_output, status_output],
                concurrency_limit=4
            )

        with gr.TabItem("⚗️ Alchemy ⚗️"):

            # gr.HTML("""
            #         <div style="background-color: rgba(255, 255, 255, 0.025); padding: 20px; border-radius: 12px; backdrop-filter: blur(10px); box-shadow: 0 4px 6px rgba(0,0,0,0.5); margin-top: 8px;">
            #             <p style="color: #1a1a1a; font-weight: 500; line-height: 1.6; font-size: 14px; text-align: center; margin: 0;">
            #             Upload audio references and mix them to create new voices.
            #             Upload two references and adjust the mix ratio, or use a single reference.
            #             </p>
            #         </div>
            #         """)

            with gr.Row():
                with gr.Column(scale=2):
                    alch_text_input = gr.Textbox(
                        label="Synthesize",
                        lines=5,
                        placeholder="日本語のテキストを入力してください...\n\n",
                        value="睡眠は、心身の健康を保つために欠かせない大切な時間です。良質な睡眠をとることで、一日の疲れを癒やし、脳内の情報を整理することができます。寝る前にスマートフォンを控えたり、温かい飲み物を飲んでリラックスすることで、より深く眠れるようになります。明日も元気に過ごすために、今夜はゆっくりと体を休めましょうね。"
                    )

                    alch_mix_ratio = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.5,
                        step=0.05,
                        label="Mix Ratio",
                    )

                    with gr.Row():
                        with gr.Column():
                            gr.HTML("""
                            <div style="background-color: rgba(255, 255, 255, 0.55); padding: 8px 12px; border-radius: 8px; backdrop-filter: blur(10px); box-shadow: 0 2px 4px rgba(0,0,0,0.08); text-align: center; max-width: 180px; margin: 0 auto;">
                                <h3 style="color: #000000; margin: 0; font-size: 16px;">🔊 Reference 1</h3>
                            </div>
                            """)
                            alch_ref_audio_1 = gr.Audio(
                                label="Reference Audio 1",
                                sources=["upload", "microphone"],
                                type="numpy",
                                value="samples/sample_01.mp3"
                            )
                        with gr.Column():
                            gr.HTML("""
                            <div style="background-color: rgba(255, 255, 255, 0.525); padding: 8px 12px; border-radius: 8px; backdrop-filter: blur(10px); box-shadow: 0 2px 4px rgba(0,0,0,0.08); text-align: center; max-width: 250px; margin: 0 auto;">
                                <h3 style="color: #000000; margin: 0; font-size: 16px;">🔊 Reference 2 (Optional)</h3>
                            </div>
                            """)
                            alch_ref_audio_2 = gr.Audio(
                                label="Reference Audio 2 (Optional)",
                                sources=["upload", "microphone"],
                                type="numpy",
                                value="samples/sample_02.mp3"
                            )

                    with gr.Row(equal_height=False):
                        with gr.Accordion("----------------------------------⭐ 🛠️ ⭐", open=False):

                            gr.Markdown('<h3 style="color: #FFD700;">Style Parameters</h3>')

                            alch_cfg_scale = gr.Slider(
                                label="CFG Scale",
                                minimum=0.5,
                                maximum=3.0,
                                value=1.4,
                                step=0.05
                            )

                            alch_speaker_cfg_scale = gr.Slider(
                                label="Speaker CFG Scale (Legacy - just rely AdaLN scale)",
                                minimum=0.5,
                                maximum=3.0,
                                value=1.,
                                step=0.1
                            )

                            alch_speaker_adaln_scale = gr.Slider(
                                label="Speaker AdaLN Scale (値を上げると参照音声に近づきますが、不自然になる可能性があります)",
                                minimum=0.0,
                                maximum=3.0,
                                value=2.,
                                step=0.1
                            )

                            gr.Markdown('<h3 style="color: #FFD700;">Sampling Parameters</h3>')

                            alch_temperature = gr.Slider(
                                label="Temperature (Min/Max Temp の両方が 0 に設定されている場合のみ有効です)",
                                minimum=0.0,
                                maximum=2.0,
                                value=0.0,
                                step=0.05
                            )

                            alch_min_temp = gr.Slider(
                                label="Min Temperature (0 = off)",
                                minimum=0.0,
                                maximum=1.0,
                                value=0.1,
                                step=0.05
                            )

                            alch_max_temp = gr.Slider(
                                label="Max Temperature (0 = off)",
                                minimum=0.0,
                                maximum=2.0,
                                value=1.0,
                                step=0.1
                            )

                            alch_temp_exponent = gr.Slider(
                                label="Temperature Exponent",
                                minimum=0.5,
                                maximum=2.0,
                                value=1.0,
                                step=0.1
                            )

                            alch_top_k = gr.Slider(
                                label="Top K (0 = off)",
                                minimum=0,
                                maximum=200,
                                value=0,
                                step=5
                            )

                            alch_top_p = gr.Slider(
                                label="Top P",
                                minimum=0.0,
                                maximum=1.0,
                                value=1.0,
                                step=0.01
                            )

                            alch_min_p = gr.Slider(
                                label="Min P (0 = off)",
                                minimum=0.0,
                                maximum=1.0,
                                value=0.0,
                                step=0.01
                            )

                            alch_max_tokens = gr.Slider(
                                label="Max Tokens",
                                minimum=100,
                                maximum=1500,
                                value=1024,
                                step=10
                            )

                            alch_dry_multiplier = gr.Slider(
                                label="DRY Multiplier (0 = off)",
                                minimum=0.0,
                                maximum=2.0,
                                value=0.8,
                                step=0.1
                            )

                            alch_seed = gr.Slider(
                                label="Seed (-1 for random)",
                                minimum=-1,
                                maximum=2700000000,
                                value=42,
                                step=1
                            )

                        with gr.Column(scale=1):
                            alch_generate_button = gr.Button("⚗️ Generate", variant="primary", size="lg")

                with gr.Column(scale=1):
                    alch_status_output = gr.Textbox(label="Status", interactive=False)
                    alch_audio_output = gr.Audio(
                        label="Transmuted Speech",
                        interactive=False,
                        value="samples/audio_62.wav"
                        
                    )

            alch_generate_button.click(
                fn=run_alchemy_pipeline_client,
                inputs=[
                    alch_text_input,
                    alch_ref_audio_1,
                    alch_ref_audio_2,
                    alch_mix_ratio,
                    alch_cfg_scale,
                    alch_speaker_cfg_scale,
                    alch_speaker_adaln_scale,
                    alch_temperature,
                    alch_min_temp,
                    alch_max_temp,
                    alch_temp_exponent,
                    alch_top_k,
                    alch_top_p,
                    alch_min_p,
                    alch_dry_multiplier,
                    alch_max_tokens,
                    alch_seed,
                ],
                outputs=[alch_audio_output, alch_status_output],
                concurrency_limit=4
            )

        with gr.TabItem("Description Guided *NEW*"):
            gr.HTML("""
            <div style="background-color: rgba(255, 255, 255, 0.025); padding: 60px 30px; border-radius: 12px; backdrop-filter: blur(5px); max-width: 100%; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center;">
                <p style="color: #1a1a1a; font-weight: 600; line-height: 1.8; margin-bottom: 8px; font-size: 24px;">
                Try it here!
                </p>
                <p style="color: #555; font-weight: 400; line-height: 1.6; margin-bottom: 24px; font-size: 14px;">
                Create the voice you want by describing it with a prompt (gender, tone, characteristic, emotion etc.)
                </p>
                <a href="https://huggingface.co/spaces/Respair/Voice_Design" target="_blank" style="
                    display: inline-block;
                    background-color: #b45309;
                    color: white;
                    font-weight: 600;
                    font-size: 16px;
                    padding: 12px 28px;
                    border-radius: 8px;
                    text-decoration: none;
                    transition: background-color 0.2s ease;
                ">🎨 Open Voice Design Space</a>
                <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; margin-top: 30px; margin-bottom: 8px; font-size: 20px;">
                こちらで試せます!
                </p>
                <p style="color: #555; font-weight: 400; line-height: 1.6; font-size: 13px;">
                このモードでは、性別・口調・感情などをプロンプトで指示するだけで、好みの声を作成できます。
                </p>
            </div>
            """)
        with gr.TabItem("Examples"):
            gr.HTML("""
                    <div style="background-color: rgba(255, 255, 255, 0.025); padding: 20px; border-radius: 12px; backdrop-filter: blur(10px); box-shadow: 0 4px 6px rgba(0,0,0,0.5); margin-top: 8px;">
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.6; font-size: 14px; text-align: center; margin: 0;">
                        Click on any example below to load the text and hear the pre-generated audio. / 下の例をクリックすると、テキストが読み込まれ、生成済みの音声を聞くことができます。
                        </p>
                    </div>
                    """)
            
            
            example_text_holder = gr.Textbox(visible=False)

            def load_mono_example_fn(text):
                for ex in example_list_mono:
                    if ex[0] == text:
                        pregenerated_path = ex[1]
                        sid = ex[2]
                        if pregenerated_path and os.path.exists(pregenerated_path):
                            try:
                                sample_rate, audio_data = wavfile.read(pregenerated_path)
                                status = "Status: Mono example loaded / モノラル例を読み込みました"
                                return text, False, sid, (sample_rate, audio_data), status
                            except Exception as e:
                                return text, False, sid, None, f"Status: Error loading audio: {str(e)}"
                        else:
                            return text, False, sid, None, "Status: Mono example loaded (no pre-generated audio)"
                return text, False, 1, None, "Status: Mono example loaded"

            def load_stereo_example_fn(text):
                for ex in example_list_stereo:
                    if ex[0] == text:
                        pregenerated_path = ex[1]
                        sid = ex[2]
                        if pregenerated_path and os.path.exists(pregenerated_path):
                            try:
                                sample_rate, audio_data = wavfile.read(pregenerated_path)
                                status = "Status: Stereo example loaded / ステレオ例を読み込みました"
                                return text, True, sid, (sample_rate, audio_data), status
                            except Exception as e:
                                return text, True, sid, None, f"Status: Error loading audio: {str(e)}"
                        else:
                            return text, True, sid, None, "Status: Stereo example loaded (no pre-generated audio)"
                return text, True, 1, None, "Status: Stereo example loaded"

            with gr.Row():
                with gr.Column(scale=1, elem_id="mono-examples-container"):
                    
                    gr.HTML("""
                    <div style="background-color: rgba(255, 255, 255, 0.55); padding: 8px 12px; border-radius: 8px; backdrop-filter: blur(10px); box-shadow: 0 2px 4px rgba(0,0,0,0.08); text-align: center; max-width: 180px; margin: 0 auto;">
                        <h3 style="color: #000000; margin: 0; font-size: 16px;">🔊 Mono </h3>
                    </div>
                    """)
                    
                    if example_list_mono:
                        mono_example_texts = [[ex[0]] for ex in example_list_mono]
                        gr.Examples(
                            examples=mono_example_texts,
                            inputs=[example_text_holder],
                            outputs=[text_input, use_stereo_checkbox, speaker_id_slider, audio_output, status_output],
                            fn=load_mono_example_fn,
                            label="Click to load a mono example",
                            cache_examples=False,
                            run_on_click=True,
                            examples_per_page=15
                        )
                    else:
                        gr.Markdown("*No mono examples available*")

                with gr.Column(scale=1, elem_id="stereo-examples-container"):
                    
                    gr.HTML("""
                    <div style="background-color: rgba(255, 255, 255, 0.55); padding: 8px 12px; border-radius: 8px; backdrop-filter: blur(10px); box-shadow: 0 2px 4px rgba(0,0,0,0.08); text-align: center; max-width: 180px; margin: 0 auto;">
                        <h3 style="color: #000000; margin: 0; font-size: 16px;">🎧 Stereo </h3>
                    </div>
                    """)
                    
                    
                    if example_list_stereo:
                        stereo_example_texts = [[ex[0]] for ex in example_list_stereo]
                        gr.Examples(
                            examples=stereo_example_texts,
                            inputs=[example_text_holder],
                            outputs=[text_input, use_stereo_checkbox, speaker_id_slider, audio_output, status_output],
                            fn=load_stereo_example_fn,
                            label="Click to load a stereo example",
                            cache_examples=False,
                            run_on_click=True,
                            examples_per_page=15
                        )
                    else:
                        gr.Markdown("*No stereo examples available*")

        with gr.TabItem("Guide"):
                    gr.HTML('<h1 style="text-align: center;">🪷 Takane - Mirei 「美嶺」 </h1>')
                    with gr.Row():
                        with gr.Column(scale=1):
                            
                            gr.HTML("""
                    <div style="background-color: rgba(255, 255, 255, 0.525); padding: 30px; border-radius: 12px; backdrop-filter: blur(5px); max-width: 100%; box-shadow: 0 4px 6px rgba(0,0,0,0.5);">
                    <h2 style="color: #000000; margin-bottom: 20px; font-size: 28px;">日本語</h2>

                    <div style="background-color: rgba(255, 200, 200, 0.45); padding: 16px 20px; border-radius: 8px; border-left: 4px solid #cc4444; margin-bottom: 20px;">
                        <p style="color: #1a1a1a; font-weight: 600; line-height: 1.8; font-size: 14px; margin: 0;">
                        ⚠️ サーバー負荷を軽くするため、オリジナルのTakaneとは違い、このデモではハルシネーション対策などの安全策を省いています。
                        そのため、モデルの出力が崩れたり、デモが止まるリスクは通常より高いです。
                        たまにメンテしますが、あくまでWIPということでご了承ください。
                        </p>
                    </div>

                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; margin-bottom: 20px; font-size: 16px;">
                        Mirei「美嶺」 は、Takane の系譜に連なる最新モデルであり、高品質なアニメっぽい日本語音声生成のためにゼロから再構築・再設計されたモデルです。より大規模で高速、かつクリーンな音質を実現し、機能も増え、学習コストも大幅に抑えられています。
                        </p>

                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; margin-bottom: 20px; font-size: 16px;">
                        これは、現代の最高峰の技術を駆使し、究極の日本語音声合成モデルを開発するという私の目標に向けた、新たな一歩です。
                        </p>

                        <h3 style="color: #000000; margin-top: 30px; margin-bottom: 15px; font-size: 20px;">初代 Takane との比較:</h3>
                        <ul style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 15px;">
                            <li style="margin: 8px 0;">大幅な容量拡大: 500M → 1.2B (Mono) / 3B (Stereo) パラメータ</li>
                            <li style="margin: 8px 0;">より多くのデータでの学習</li>
                            <li style="margin: 8px 0;">実験的な制御可能 End-to-end Stereo 生成</li>
                            <li style="margin: 8px 0;">Promptable Description Guided (TBA)</li>
                            <li style="margin: 8px 0;">FiLM ベースの文字起こし不要なゼロショット・オーディオプロンプティング (Alchemy mode)</li>
                            <li style="margin: 8px 0;">この種のモデルとしては最も包括的なサンプリングツールキット</li>
                            <li style="margin: 8px 0;">アーティファクトを極限まで抑え、鮮明な音質を実現する新しい 44.1khz - 25hz コーデック</li>
                        </ul>

                        <hr style="border: none; border-top: 1px solid rgba(0,0,0,0.15); margin: 25px 0;">

                        <h3 style="color: #000000; margin-top: 20px; margin-bottom: 15px; font-size: 20px;">注意事項:</h3>
                        <ul style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                            <li style="margin: 8px 0;"><strong>Stereo</strong> は概念実証(PoC)段階です。Pan と Width で方向と深度を制御できますが、Width は現時点では近似的なものです。</li>
                            <li style="margin: 8px 0;"><strong>Speaker IDs</strong>: <code>speaker_id = 1</code> はランダムを意味します。多くの学習データ(特に Stereo)には話者タグがありません。未知の話者は分布外(OOD)になる可能性があるため品質にばらつきが出ますが、Stereo でも機能はします。</li>
                            <li style="margin: 8px 0;"><strong>データセットのバイアス / 制限</strong>: 左耳へのパンニング(<code>pan = 1–4</code>)や浅い深度(<code>&lt; 5</code>)のデータが過多です。Hover/rotation はここではサポートされていません。</li>
                            <li style="margin: 8px 0;"><strong>絵文字</strong>: サポートは最小限ですが、ASMR プロンプトの方向付けに役立ちます(例:😮‍💨 🌬️ 👂 🤭 🍭 💋)。NSFW の場合、テキスト(またはテキスト+絵文字)を主に使用してください。絵文字のみのプロンプトはあまりうまくいきません。</li>
                            <li style="margin: 8px 0;">絵文字は特定の音に必ずしも対応しているわけではないため、配置場所はそれほど重要ではありませんが、全体的な雰囲気(vibe)に影響を与えます。</li>
                            <li style="margin: 8px 0;"><strong>多数の設定項目</strong>: 基本的にはそのままで素晴らしい結果が得られますが、場合によっては調整が必要になることもあります。</li>
                            <li style="margin: 8px 0;"><strong><code>&lt;asmr&gt;</code> タグ</strong>: 任意ですが、出力が変化するため、有無の両方を試してみてください。</li>
                            <li style="margin: 8px 0;"><strong>NSFW</strong>: Mono の方が一般的に制御しやすいです(データ量が多いため)。入力テキストの先頭に <code>♡♡</code> を付けることを推奨します。</li>
                            <li style="margin: 8px 0;"><strong>Audio prompting</strong>: ベースモードでは、プロンプトは6秒以内かつ綺麗にトリミングされたものにしてください。Alchemy mode では、Prefill とは異なる手法を用いているため、この制約はそれほど重要ではありません。</li>
                            <li style="margin: 8px 0;"><strong>長さ制限</strong>: 最大出力は29.9秒です。このデモでは長時間の生成はサポートされていません。</li>
                            <li style="margin: 8px 0;"><strong>再生環境</strong>: 音場表現のしっかりしたヘッドホンの使用を推奨します。</li>
                            <li style="margin: 8px 0;"><strong>多様性の調整</strong>: バリエーションの激しい出力の場合、<code>Temperature</code> を <code>~0.8–1.0</code> に上げ、<code>DRY = 0</code> に設定してください。</li>
                            <li style="margin: 8px 0;"><code>DRY</code> をオフにすると、出力とテキストの相関が弱い場合にモデルが崩壊する可能性があります。</li>
                            <li style="margin: 8px 0;">Takane シリーズはアニメスタイルの出力に特化していますが、Mirei バリアントでは通常の日本語もよりサポートされています。</li>
                        </ul>

                        <h3 style="color: #000000; margin-top: 30px; margin-bottom: 15px; font-size: 20px;">Prefilling と RyuseiNet についての注記</h3>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        コーデックベースのモデルにおける Audio prompting のデフォルトモードは Prefilling です。これは、ボイスクリップからオーディオトークンを抽出し、その文字起こしと共に入力に結合する方法です。
                        問題点はコンテキストを消費してしまうことです。モデルは入力を、プロンプトの自然な続きとして扱うためです。
                        </p>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        例えば、モデルが主に30秒のチャンクで学習されている場合、リファレンス+出力の合計長は30秒未満である必要があります。また、安全のためにバッファを持たせることも推奨されます。例えば、出力が約20秒になる場合、オーディオプロンプトは5〜6秒程度に収めるべきです。
                        </p>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        RyuseiNet (Alchemy mode) では、この制限はありません。それに話者の類似性がより高く、入力テキストに対してより頑健です。ただし、参考のために両方の手法を残しています。
                        </p>

                        <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(0,0,0,0.1);">
                            <p style="color: #666; font-size: 14px; text-align: center;">
                        
                            </p>
                        </div>

                    </div>
                    """)
                        with gr.Column(scale=1):
                            gr.HTML("""
                    <div style="background-color: rgba(255, 255, 255, 0.525); padding: 30px; border-radius: 12px; backdrop-filter: blur(5px); max-width: 100%; box-shadow: 0 4px 6px rgba(0,0,0,0.5);">

                        <h2 style="color: #000000; margin-bottom: 20px; font-size: 28px;">English</h2>

                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; margin-bottom: 20px; font-size: 16px;">
                        Mirei (美嶺) is the continuation of my work from Takane, rebuilt and redesigned from the ground up for high-quality, anime-style Japanese voice generation. It's larger, faster, sounds cleaner, has more features, and is also much cheaper to train.
                        </p>

                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; margin-bottom: 20px; font-size: 16px;">
                        It is another step toward my goal of developing the ultimate Japanese speech and audio synthesis model, pushing as far as today's best technology can take.
                        </p>

                        <h3 style="color: #000000; margin-top: 30px; margin-bottom: 15px; font-size: 20px;">Compared to the base Takane, Mirei adds:</h3>
                        <ul style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 15px;">
                            <li style="margin: 8px 0;">Significantly larger capacity: 500M → 1.2B (mono) / 3B (stereo) parameters</li>
                            <li style="margin: 8px 0;">Trained on more data</li>
                            <li style="margin: 8px 0;">Experimental controllable end-to-end stereo generation</li>
                            <li style="margin: 8px 0;">Promptable Description Guided (TBA)</li>
                            <li style="margin: 8px 0;">FiLM-based, transcription-less zero-shot audio prompting (Alchemy mode)</li>
                            <li style="margin: 8px 0;">The most comprehensive sampling toolkit in any model of this kind</li>
                            <li style="margin: 8px 0;">A new 44.1khz - 25hz codec that sounds crisp with as few artifacts as possible</li>
                        </ul>

                        <hr style="border: none; border-top: 1px solid rgba(0,0,0,0.15); margin: 25px 0;">

                        <h3 style="color: #000000; margin-top: 20px; margin-bottom: 15px; font-size: 20px;">Notes:</h3>
                        <ul style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                            <li style="margin: 8px 0;"><strong>Stereo</strong> is a proof of concept. Use pan and width to control direction and depth, but width is approximate right now (until I come up with a better extraction algorithm).</li>
                            <li style="margin: 8px 0;"><strong>Speaker IDs</strong>: <code>speaker_id = 1</code> means random. Most training data (especially stereo) lacks speaker tags. Unseen speakers may be out-of-distribution, so quality can vary (stereo can still work).</li>
                            <li style="margin: 8px 0;"><strong>Dataset bias / limits</strong>: Left-ear panning (<code>pan = 1–4</code>) and shallower depth (<code>&lt; 5</code>) are overrepresented. Hover/rotation isn't supported here (but it is technically feasible).</li>
                            <li style="margin: 8px 0;"><strong>Emoji</strong> support is minimal but can help ground ASMR prompts (e.g., 😮‍💨 🌬️ 👂 🤭 🍭 💋). For NSFW, rely more on text (or text + emoji). Emoji-only prompts rarely work well.</li>
                            <li style="margin: 8px 0;">Emojis don't necessarily correlate with specific sounds, so their placement doesn't matter much; but they affect the overall vibe.</li>
                            <li style="margin: 8px 0;"><strong>Lots of knobs</strong>: You'll get great results most of the time, but the remaining cases may take some tuning.</li>
                            <li style="margin: 8px 0;"><strong><code>&lt;asmr&gt;</code> tag</strong>: Optional, but it does change the output — try with and without it.</li>
                            <li style="margin: 8px 0;"><strong>NSFW</strong>: Mono is generally easier to steer (more data). Prepending the input text with <code>♡♡</code> is recommended.</li>
                            <li style="margin: 8px 0;"><strong>Audio prompting</strong>: In base mode, keep prompts ≤ 6s, cleanly trimmed (no abrupt cuts). In Alchemy mode, this constraint doesn't matter as much (we use a different method than prefill).</li>
                            <li style="margin: 8px 0;"><strong>Length limit</strong>: Max output is 29.9s; long-form generation isn't supported in this demo.</li>
                            <li style="margin: 8px 0;"><strong>Playback</strong>: Headphones with a decent soundstage are recommended; otherwise spatial effects may feel weaker.</li>
                            <li style="margin: 8px 0;"><strong>Diversity tuning</strong>: For high-variance outputs (laughter, extreme emotions, aegi/chupa), raise <code>temperature</code> to <code>~0.8–1.0</code> and set <code>DRY = 0</code>.</li>
                            <li style="margin: 8px 0;">Turning off <code>DRY</code> can cause the model to collapse when the output is weakly correlated with the text.</li>
                            <li style="margin: 8px 0;">While the Takane model family is geared towards anime-style outputs, normal Japanese is also better supported with the Mirei variant (I have provided an example).</li>
                        </ul>

                        <h3 style="color: #000000; margin-top: 30px; margin-bottom: 15px; font-size: 20px;">A Note about Prefilling vs RyuseiNet</h3>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        The default mode for audio prompting in any codec-based model is prefilling — where you extract audio tokens from your voice clip and glue them together with the transcription as your input.
                        The problem is it eats up your context, because the model treats your input as if it is a natural continuation of your prompt.
                        </p>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        For example, if your model was trained on mostly 30-second chunks, the length of your reference + the output should be less than 30 seconds. It's also recommended to keep a safety buffer. For example, if your output will be roughly 20 seconds, your audio prompt should be around 5–6 seconds to be in the safe zone.
                        </p>
                        <p style="color: #1a1a1a; font-weight: 500; line-height: 1.8; font-size: 14px;">
                        For RyuseiNet (Alchemy mode), we don't have this limitation, it has a better speaker similarity and more robust to your input text. But I am keeping both methods for reference.
                        </p>

                        <div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(0,0,0,0.1);">
                            <p style="color: #666; font-size: 14px; text-align: center;">
                          
                            </p>
                        </div>

                    </div>
                    """)
                    gr.HTML("""
                    <div style="text-align: center; margin-top: 30px; padding: 20px; background-color: rgba(255, 255, 255, 0.35); border-radius: 10px; backdrop-filter: blur(5px);">
                        <p style="color: #1a1a1a; font-size: 17px; font-weight: 500;">
                            If you need help or have questions, feel free to contact me on
                            <a href="https://x.com/MystiqCaleid" target="_blank" style="color: #b45309; text-decoration: none; font-weight: 600;">X / Twitter</a>
                            or
                            <a href="https://discord.com/users/349236707167698944" target="_blank" style="color: #5865F2; text-decoration: none; font-weight: 600;">Discord (@soshyant)</a>
                        </p>
                    </div>
                    """)
    def load_default_example():
        if len(example_list_stereo) >= 2:
            return load_stereo_example_fn(example_list_stereo[1][0])
        return gr.update(), gr.update(), gr.update(), None, ""

    # def load_default_example():
    #     if len(example_list_mono) >= 2:
    #         return load_mono_example_fn(example_list_mono[-1][0])
    #     return gr.update(), gr.update(), gr.update(), None, ""
        
    demo.load(
        fn=load_default_example,
        inputs=None,
        outputs=[text_input, use_stereo_checkbox, speaker_id_slider, audio_output, status_output]
    )

if __name__ == "__main__":
    demo.queue(api_open=False, max_size=15).launch()