aboutsummaryrefslogtreecommitdiff
path: root/app/tests/test_tts.py
blob: cf67c6c5e0570f9d141f84ca12513ebe54f69c1a (plain)
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
"""Tests for the TTS client wrappers (language handling and payloads)."""

import io
import json
import tempfile
import time
import urllib.error
import unittest
import wave
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import MagicMock, patch

from converter import config
from converter import converter as converter_mod
from converter.clients import (
    AUDIOCPP_DEFAULT_FAMILY_PROFILE,
    AUDIOCPP_FAMILY_PROFILES,
    AUDIOCPP_LANG_OMIT,
    AUDIOCPP_TASK_TTS,
    AUDIOCPP_TASK_VDES,
    AUDIOCPP_VOICE_CLONE,
    AUDIOCPP_VOICE_DESIGN,
    AUDIOCPP_VOICE_SPEAKER,
    BACKEND_AUDIOCPP,
    BACKEND_FASTER,
    BACKEND_QWEN,
    LANGUAGE_CHOICES,
    LANGUAGE_ISO_CODES,
    MODEL_SIZE,
    SAMPLE_RATE,
    TTS_LANGUAGES,
    VOICE_MODE_CLONE,
    VOICE_MODE_CUSTOM,
    VOICE_MODE_DESIGN,
    VOICE_MODES,
    AudioCppTTSClient,
    FasterTTSClient,
    QwenTTSClient,
    audiocpp_entry_voice_capability,
    normalize_language,
)
from converter.converter import AudiobookConverter

# Chunks folder handed to clients whose tests never write chunk files.
_DUMMY_CHUNKS = Path(tempfile.gettempdir()) / "audiobook_tts_test_chunks"


class NormalizeLanguageTests(unittest.TestCase):
    def test_display_names_case_insensitive(self):
        self.assertEqual(normalize_language("english"), "English")
        self.assertEqual(normalize_language("ENGLISH"), "English")
        self.assertEqual(normalize_language(" Japanese "), "Japanese")

    def test_auto_accepted(self):
        self.assertEqual(normalize_language("auto"), "Auto")
        self.assertEqual(normalize_language("Auto"), "Auto")

    def test_iso_aliases(self):
        self.assertEqual(normalize_language("en"), "English")
        self.assertEqual(normalize_language("ja"), "Japanese")
        self.assertEqual(normalize_language("zh"), "Chinese")
        self.assertEqual(normalize_language("ko"), "Korean")
        self.assertEqual(normalize_language("de"), "German")
        self.assertEqual(normalize_language("fr"), "French")
        self.assertEqual(normalize_language("ru"), "Russian")
        self.assertEqual(normalize_language("pt"), "Portuguese")
        self.assertEqual(normalize_language("es"), "Spanish")
        self.assertEqual(normalize_language("it"), "Italian")
        self.assertEqual(normalize_language("ar"), "Arabic")
        self.assertEqual(normalize_language("hi"), "Hindi")
        self.assertEqual(normalize_language("vi"), "Vietnamese")

    def test_audio_cpp_menu_languages_accepted(self):
        # audio.cpp's WebUI menus add Arabic, Hindi and Vietnamese; the
        # MagpieTTS Arabic regional variants collapse to plain Arabic.
        self.assertEqual(normalize_language("arabic"), "Arabic")
        self.assertEqual(normalize_language("Hindi"), "Hindi")
        self.assertEqual(normalize_language("vietnamese"), "Vietnamese")
        for variant in ("ar-AE", "ar-MSA", "ar-SA"):
            self.assertEqual(normalize_language(variant), "Arabic")

    def test_language_choices_are_valid_display_names(self):
        # The TUI's static picker lists a permutation of TTS_LANGUAGES
        # (common languages first), so every entry normalizes.
        self.assertEqual(sorted(LANGUAGE_CHOICES), sorted(TTS_LANGUAGES))
        for name in LANGUAGE_CHOICES:
            self.assertEqual(normalize_language(name), name)

    def test_all_supported_languages_round_trip(self):
        for name in TTS_LANGUAGES:
            self.assertEqual(normalize_language(name.lower()), name)

    def test_unknown_language_rejected_with_guidance(self):
        with self.assertRaises(ValueError) as ctx:
            normalize_language("klingon")
        message = str(ctx.exception)
        self.assertIn("klingon", message)
        self.assertIn("English", message)

    def test_none_and_empty_rejected(self):
        with self.assertRaises(ValueError):
            normalize_language(None)
        with self.assertRaises(ValueError):
            normalize_language("   ")


class QwenTTSClientLanguageTests(unittest.TestCase):
    """Language validation and defaults, without touching the network."""

    def _make_client(self, **kwargs):
        with patch.object(QwenTTSClient, "_connect"):
            return QwenTTSClient(_DUMMY_CHUNKS, **kwargs)

    def test_default_follows_config_for_each_mode(self):
        custom = self._make_client(voice_mode=VOICE_MODE_CUSTOM)
        self.assertEqual(custom.language, config.LANGUAGE)
        clone = self._make_client(voice_mode=VOICE_MODE_CLONE,
                                  voice_clone_ref_audio="ref.wav")
        self.assertEqual(clone.language, config.LANGUAGE)

    def test_explicit_language_normalized(self):
        client = self._make_client(voice_mode=VOICE_MODE_CUSTOM, language="ja")
        self.assertEqual(client.language, "Japanese")

    def test_invalid_language_fails_before_connect(self):
        with patch.object(QwenTTSClient, "_connect") as mock_connect:
            with self.assertRaises(ValueError):
                QwenTTSClient(_DUMMY_CHUNKS, language="klingon")
        mock_connect.assert_not_called()

    def test_api_url_override_stored(self):
        client = self._make_client(voice_mode=VOICE_MODE_CUSTOM,
                                   api_url="http://10.0.0.5:7860")
        self.assertEqual(client.api_url, "http://10.0.0.5:7860")

    def test_api_url_override_used_by_connect(self):
        with patch.object(QwenTTSClient, "_init_client") as mk_init:
            client = QwenTTSClient.__new__(QwenTTSClient)
            client.voice_mode = VOICE_MODE_CUSTOM
            client.api_url = "http://10.0.0.5:7860"
            client._connect()
        mk_init.assert_called_once_with("http://10.0.0.5:7860", clone=False)


class SeedResolutionTests(unittest.TestCase):
    """CONSTANT_SEED: one seed per run, reused for every request, so the
    voice stays consistent across chunk boundaries (the servers
    re-sample the voice when the seed changes between generations)."""

    def _make_client(self, **kwargs):
        with patch.object(QwenTTSClient, "_connect"):
            return QwenTTSClient(_DUMMY_CHUNKS, **kwargs)

    def test_constant_seed_draws_one_nonnegative_seed(self):
        with patch.object(config, "CONSTANT_SEED", True), \
                patch.object(config, "SEED", -1):
            client = self._make_client(voice_mode=VOICE_MODE_CUSTOM)
        self.assertGreaterEqual(client._seed, 0)

    def test_explicit_seed_wins_over_constant_seed(self):
        with patch.object(config, "CONSTANT_SEED", True), \
                patch.object(config, "SEED", 42):
            client = self._make_client(voice_mode=VOICE_MODE_CUSTOM)
        self.assertEqual(client._seed, 42)

    def test_without_constant_seed_minus_one_is_forwarded(self):
        with patch.object(config, "CONSTANT_SEED", False), \
                patch.object(config, "SEED", -1):
            client = self._make_client(voice_mode=VOICE_MODE_CUSTOM)
        self.assertEqual(client._seed, -1)

    def test_resolved_seed_is_reused_across_requests(self):
        api_info = {
            "named_endpoints": {
                "/run_custom_voice": {
                    "parameters": [{"parameter_name": "seed"}]
                }
            }
        }
        client = QwenTTSClient.__new__(QwenTTSClient)
        client.voice_mode = VOICE_MODE_CUSTOM
        client.language = "English"
        client._seed = 1234
        client.api_info = api_info
        client.client = MagicMock()
        client._generate_custom_voice("first text")
        client._generate_custom_voice("second text")
        seeds = [call.kwargs["seed"]
                 for call in client.client.predict.call_args_list]
        self.assertEqual(seeds, [1234, 1234])


class PayloadLanguageTests(unittest.TestCase):
    """The language must reach the API payload in every endpoint variant."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        self.ref_audio = Path(self._tmp.name) / "reference.wav"
        self.ref_audio.write_bytes(b"x")

    def tearDown(self):
        self._tmp.cleanup()

    def _custom_client(self, language, endpoint, api_info=None):
        client = QwenTTSClient.__new__(QwenTTSClient)
        client.voice_mode = VOICE_MODE_CUSTOM
        client.language = language
        client._seed = config.SEED
        client.api_info = api_info if api_info is not None else {
            "named_endpoints": {endpoint: {}}
        }
        client.client = MagicMock()
        return client

    def _clone_client(self, language, endpoint, api_info=None, ref_text="hello"):
        client = QwenTTSClient.__new__(QwenTTSClient)
        client.voice_mode = VOICE_MODE_CLONE
        client.language = language
        client._seed = config.SEED
        client.voice_clone_ref_audio = str(self.ref_audio)
        client.voice_clone_ref_text = ref_text
        client.clone_api_info = api_info if api_info is not None else {
            "named_endpoints": {endpoint: {}}
        }
        client.clone_client = MagicMock()
        client._ref_audio_filedata = {"dummy": "payload"}
        return client

    def test_custom_voice_run_instruct_uses_language(self):
        client = self._custom_client("Japanese", "/run_instruct")
        client._generate_custom_voice("text")
        kwargs = client.client.predict.call_args.kwargs
        self.assertEqual(kwargs["lang_disp"], "Japanese")

    def test_custom_voice_alt_endpoint_uses_language(self):
        client = self._custom_client("French", "/run_custom_voice")
        client._generate_custom_voice("text")
        kwargs = client.client.predict.call_args.kwargs
        self.assertEqual(kwargs["language"], "French")

    def test_voice_clone_run_voice_clone_uses_language(self):
        client = self._clone_client("Japanese", "/run_voice_clone")
        client._generate_voice_clone("text")
        kwargs = client.clone_client.predict.call_args.kwargs
        self.assertEqual(kwargs["lang_disp"], "Japanese")

    def test_voice_clone_alt_endpoint_uses_language(self):
        client = self._clone_client("Korean", "/generate_voice_clone")
        client._generate_voice_clone("text")
        kwargs = client.clone_client.predict.call_args.kwargs
        self.assertEqual(kwargs["language"], "Korean")

    def test_voice_clone_alt_endpoint_includes_optional_params(self):
        api_info = {
            "named_endpoints": {
                "/generate_voice_clone": {
                    "parameters": [
                        {"parameter_name": "model_size"},
                        {"parameter_name": "seed"},
                    ]
                }
            }
        }
        client = self._clone_client("English", "/generate_voice_clone", api_info=api_info)
        client._generate_voice_clone("text")
        kwargs = client.clone_client.predict.call_args.kwargs
        self.assertEqual(kwargs["model_size"], MODEL_SIZE)
        self.assertEqual(kwargs["seed"], config.SEED)


class FasterTTSClientHealthTests(unittest.TestCase):
    """Connection behavior of the faster-qwen3-tts client."""

    def _health_response(self, model_loaded=True):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = json.dumps(
            {"status": "ok", "model_loaded": model_loaded}).encode("utf-8")
        return response

    def test_unreachable_server_raises_with_readme_pointer(self):
        import urllib.error
        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=urllib.error.URLError("Connection refused")):
            with self.assertRaises(RuntimeError) as ctx:
                FasterTTSClient(_DUMMY_CHUNKS)
        message = str(ctx.exception)
        self.assertIn("not reachable", message)
        self.assertIn("README", message)

    def test_model_not_loaded_raises(self):
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._health_response(model_loaded=False)):
            with self.assertRaises(RuntimeError) as ctx:
                FasterTTSClient(_DUMMY_CHUNKS)
        self.assertIn("not loaded", str(ctx.exception))

    def test_healthy_server_defaults_from_config(self):
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._health_response()):
            client = FasterTTSClient(_DUMMY_CHUNKS)
        self.assertEqual(client.voice, config.FASTER_VOICE)
        self.assertEqual(client.api_url, config.FASTER_API_URL.rstrip("/"))

    def test_explicit_voice_and_url_override_config(self):
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._health_response()):
            client = FasterTTSClient(_DUMMY_CHUNKS,
                                     voice="narrator", api_url="http://10.0.0.5:9000/")
        self.assertEqual(client.voice, "narrator")
        self.assertEqual(client.api_url, "http://10.0.0.5:9000")


class FasterTTSClientGenerateTests(unittest.TestCase):
    """Chunk generation: sub-chunking, WAV output, retries, bookkeeping."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        self._sleep = patch("converter.clients.base.time.sleep")
        self._sleep.start()

    def tearDown(self):
        self._sleep.stop()
        self._tmp.cleanup()

    def _make_client(self):
        client = FasterTTSClient.__new__(FasterTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.voice = "default"
        client.api_url = "http://127.0.0.1:8000"
        return client

    def _read_wav(self, path):
        with wave.open(str(path), "rb") as wav_file:
            return (wav_file.getnchannels(), wav_file.getsampwidth(),
                    wav_file.getframerate(), wav_file.readframes(wav_file.getnframes()))

    def test_generate_chunk_writes_valid_wav(self):
        client = self._make_client()
        pcm = b"\x01\x00" * 100
        with patch.object(client, "_request_pcm", return_value=pcm):
            result = client.generate_chunk("Hello world.", 1)
        self.assertIsNotNone(result)
        path = Path(result)
        self.assertEqual(path.name, "chunk_0001.wav")
        channels, sampwidth, framerate, frames = self._read_wav(path)
        self.assertEqual(channels, 1)
        self.assertEqual(sampwidth, 2)
        self.assertEqual(framerate, SAMPLE_RATE)
        self.assertEqual(frames, pcm)

    def test_long_text_is_subchunked_and_concatenated_in_order(self):
        client = self._make_client()
        sentences = [" ".join(f"word{i}" for i in range(6)) + "." for _ in range(3)]
        text = " ".join(sentences)
        pcm_parts = [b"\x01\x00" * 10, b"\x02\x00" * 20, b"\x03\x00" * 30]
        with patch.object(config, "CHUNK_SIZE", 10), \
                patch.object(client, "_request_pcm", side_effect=pcm_parts) as mock_pcm:
            result = client.generate_chunk(text, 1)
        self.assertEqual(mock_pcm.call_count, 3)
        _, _, _, frames = self._read_wav(Path(result))
        self.assertEqual(frames, b"".join(pcm_parts))

    def test_subchunk_size_follows_config_chunk_size(self):
        client = self._make_client()
        text = " ".join(f"word{i}" for i in range(8))
        pcm = b"\x01\x00" * 10
        with patch.object(config, "CHUNK_SIZE", 4), \
                patch.object(client, "_request_pcm", return_value=pcm) as mock_pcm:
            result = client.generate_chunk(text, 1)
        # The sub-chunk split follows config.CHUNK_SIZE, so the whole
        # (8-word) text needs two 4-word requests here.
        self.assertEqual(mock_pcm.call_count, 2)
        self.assertIsNotNone(result)

    def test_stale_chunk_files_are_removed(self):
        stale = Path(self._tmp.name) / "chunk_0001.mp3"
        stale.write_bytes(b"old")
        client = self._make_client()
        with patch.object(client, "_request_pcm", return_value=b"\x01\x00"):
            client.generate_chunk("Hello.", 1)
        remaining = sorted(path.name for path in Path(self._tmp.name).glob("chunk_0001.*"))
        self.assertEqual(remaining, ["chunk_0001.wav"])

    def test_transient_failure_fails_the_chunk_attempt(self):
        # Retrying is the chunk-level policy's job
        # (process_chunk_with_retry); one generate_chunk call makes one
        # request attempt per sub-chunk.
        client = self._make_client()
        pcm = b"\x01\x00" * 10
        with patch.object(client, "_request_pcm",
                          side_effect=[RuntimeError("boom"), pcm]) as mock_pcm:
            result = client.generate_chunk("Hello.", 1)
        self.assertIsNone(result)
        self.assertEqual(mock_pcm.call_count, 1)

    def test_empty_pcm_response_fails_the_chunk(self):
        client = self._make_client()

        def _response(body):
            response = MagicMock()
            response.__enter__.return_value = response
            response.read.return_value = body
            return response

        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=[_response(b"")]) as mock_urlopen:
            result = client.generate_chunk("Hello.", 1)
        self.assertIsNone(result)
        self.assertEqual(mock_urlopen.call_count, 1)

    def test_subchunk_request_failure_fails_the_chunk(self):
        client = self._make_client()
        with patch.object(client, "_request_pcm",
                          side_effect=RuntimeError("down")) as mock_pcm:
            result = client.generate_chunk("Hello.", 1)
        self.assertIsNone(result)
        self.assertEqual(mock_pcm.call_count, 1)

    def test_empty_text_fails_the_chunk(self):
        client = self._make_client()
        with patch.object(client, "_request_pcm") as mock_pcm:
            result = client.generate_chunk("   ", 1)
        self.assertIsNone(result)
        mock_pcm.assert_not_called()

    def test_request_payload_includes_voice_text_and_format(self):
        client = self._make_client()
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = b"\x01\x00" * 10
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=response) as mock_urlopen:
            pcm = client._request_pcm("Hello world.")
        self.assertEqual(pcm, b"\x01\x00" * 10)
        request = mock_urlopen.call_args[0][0]
        self.assertEqual(request.full_url, "http://127.0.0.1:8000/v1/audio/speech")
        payload = json.loads(request.data.decode("utf-8"))
        self.assertEqual(payload["input"], "Hello world.")
        self.assertEqual(payload["voice"], "default")
        self.assertEqual(payload["response_format"], "pcm")

    def test_full_length_pcm_passes(self):
        client = self._make_client()
        text = " ".join(f"word{i}" for i in range(12))
        # 12 words -> expected 4.8s, half is 2.4s -> 2.5s of audio passes.
        pcm = b"\x01\x00" * int(2.5 * SAMPLE_RATE)
        with patch.object(client, "_request_pcm", return_value=pcm):
            result = client.generate_chunk(text, 1)
        self.assertIsNotNone(result)


class QwenTTSClientGenerateTests(unittest.TestCase):
    """Qwen chunk generation: sub-request splitting and concatenation."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()

    def tearDown(self):
        self._tmp.cleanup()

    def _make_client(self):
        client = QwenTTSClient.__new__(QwenTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.voice_mode = VOICE_MODE_CUSTOM
        return client

    @staticmethod
    def _write_wav(path: Path, frames: bytes) -> Path:
        with wave.open(str(path), "wb") as wav_file:
            wav_file.setnchannels(1)
            wav_file.setsampwidth(2)
            wav_file.setframerate(SAMPLE_RATE)
            wav_file.writeframes(frames)
        return path

    def _read_wav_frames(self, path: Path) -> bytes:
        with wave.open(str(path), "rb") as wav_file:
            return wav_file.readframes(wav_file.getnframes())

    def test_single_request_copies_audio(self):
        client = self._make_client()
        source = self._write_wav(Path(self._tmp.name) / "server.wav", b"\x01\x00" * 50)
        with patch.object(client, "_generate_custom_voice",
                          return_value=(str(source),)) as mock_generate:
            result = client.generate_chunk("Hello world.", 1)
        mock_generate.assert_called_once_with("Hello world.")
        path = Path(result)
        self.assertEqual(path.name, "chunk_0001.wav")
        self.assertEqual(self._read_wav_frames(path), b"\x01\x00" * 50)

    def test_oversized_input_is_split_and_concatenated_in_order(self):
        client = self._make_client()
        first = self._write_wav(Path(self._tmp.name) / "one.wav", b"\x01\x00" * 10)
        second = self._write_wav(Path(self._tmp.name) / "two.wav", b"\x02\x00" * 20)
        text = " ".join(f"word{i}" for i in range(12))
        with patch.object(config, "CHUNK_SIZE", 5), \
                patch.object(client, "_generate_custom_voice",
                             side_effect=[(str(first),), (str(second),),
                                          (str(first),)]) as mock_generate:
            result = client.generate_chunk(text, 1)
        self.assertEqual(mock_generate.call_count, 3)
        path = Path(result)
        self.assertEqual(path.name, "chunk_0001.wav")
        self.assertEqual(self._read_wav_frames(path),
                         b"\x01\x00" * 10 + b"\x02\x00" * 20 + b"\x01\x00" * 10)
        for call in mock_generate.call_args_list:
            self.assertLessEqual(len(call[0][0].split()), 5)

    def test_empty_text_fails_the_chunk(self):
        client = self._make_client()
        with patch.object(client, "_generate_custom_voice") as mock_generate:
            result = client.generate_chunk("   ", 1)
        self.assertIsNone(result)
        mock_generate.assert_not_called()


class QwenTTSClientVoiceDesignTests(unittest.TestCase):
    """Qwen VoiceDesign mode: instructions and the /run_voice_design call."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()

    def tearDown(self):
        self._tmp.cleanup()

    def _client(self, instructions=None):
        client = QwenTTSClient.__new__(QwenTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.voice_mode = VOICE_MODE_DESIGN
        client.language = config.LANGUAGE
        client.instructions = (instructions if instructions is not None
                               else config.INSTRUCT).strip()
        client.api_info = {"named_endpoints": {"/run_voice_design": {
            "parameters": [
                {"parameter_name": "text"},
                {"parameter_name": "lang_disp"},
                {"parameter_name": "design"},
            ]}}}
        return client

    def _fake_output(self) -> str:
        out = Path(self._tmp.name) / "server_out.wav"
        out.write_bytes(b"\x01\x00")
        return str(out)

    def test_voice_mode_design_is_valid(self):
        self.assertIn(VOICE_MODE_DESIGN, VOICE_MODES)

    def test_generate_payload_and_return(self):
        client = self._client(instructions="A warm narrator")
        fake = MagicMock(return_value=(self._fake_output(),))
        with patch.object(client, "_generate_voice_design", fake):
            result = client._generate_sub_request(
                "Hello there.", self._tmp.name, 1, 1, 1)
        fake.assert_called_once_with("Hello there.")
        self.assertEqual(Path(result).name, "part_01.wav")

    def test_payload_uses_design_field_language_and_instruction(self):
        client = self._client(instructions="A warm narrator")
        captured = {}

        def fake_predict(**payload):
            captured.update(payload)
            return (self._fake_output(),)

        client.client = MagicMock()
        client.client.predict.side_effect = fake_predict
        result = client._generate_voice_design("Hi.")
        self.assertEqual(captured["text"], "Hi.")
        self.assertEqual(captured["lang_disp"], config.LANGUAGE)
        self.assertEqual(captured["design"], "A warm narrator")
        self.assertNotIn("seed", captured)  # not accepted by this endpoint
        self.assertEqual(result, (self._fake_output(),))

    def test_payload_defaults_instructions_to_config(self):
        client = self._client(instructions=None)
        self.assertEqual(client.instructions,
                         (config.INSTRUCT or "").strip())

    def test_unknown_api_falls_back_to_the_requested_name(self):
        client = self._client()
        client.api_info = {"named_endpoints": {}}
        client.client = MagicMock()
        client.client.predict.return_value = (self._fake_output(),)
        client._generate_voice_design("Hi.")
        _, kwargs = client.client.predict.call_args
        self.assertEqual(kwargs["api_name"], "/run_voice_design")



class AudioCppTTSClientHealthTests(unittest.TestCase):
    """Connection behavior of the audio.cpp client."""

    def setUp(self):
        # The default AUDIOCPP_MODEL_ID is empty (auto-select); these tests
        # exercise a configured single-model CustomVoice server, so pin a
        # concrete id whose "customvoice" substring marks it speaker-capable.
        patcher = patch.object(
            config, "AUDIOCPP_MODEL_ID", "Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF")
        patcher.start()
        self.addCleanup(patcher.stop)

    @staticmethod
    def _json_response(payload):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = json.dumps(payload).encode("utf-8")
        return response

    def _get_responses(self, health=None, models=None, voices=None):
        """Side effect dispatching GET responses by URL."""
        def _dispatch(request, **_kwargs):
            url = request if isinstance(request, str) else request.full_url
            if url.endswith("/health"):
                return self._json_response(health if health is not None
                                           else {"status": "ok"})
            if url.endswith("/v1/models"):
                return self._json_response(models if models is not None else
                                           {"data": [{"id": config.AUDIOCPP_MODEL_ID,
                                                      "family": "qwen3_tts"}]})
            if "/v1/audio/voices" in url:
                if voices is Exception:
                    raise Exception("voices endpoint down")
                return self._json_response(voices if voices is not None
                                           else {"voices": ["narrator"]})
            raise AssertionError(f"unexpected URL: {url}")
        return _dispatch

    def _client(self, voice=None, language=None, model_id=None, **kwargs):
        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=self._get_responses(**kwargs)):
            return AudioCppTTSClient(_DUMMY_CHUNKS, voice=voice,
                                     language=language, model_id=model_id)

    def test_unreachable_server_raises_with_readme_pointer(self):
        import urllib.error
        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=urllib.error.URLError("Connection refused")):
            with self.assertRaises(RuntimeError) as ctx:
                AudioCppTTSClient(_DUMMY_CHUNKS)
        message = str(ctx.exception)
        self.assertIn("not reachable", message)
        self.assertIn("README", message)

    def test_unhealthy_status_raises(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(health={"status": "starting"})
        self.assertIn("starting", str(ctx.exception))

    def test_unknown_model_id_raises_with_configured_ids(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(models={"data": [{"id": "pocket-tts"}, {"id": "other"}]})
        message = str(ctx.exception)
        self.assertIn(config.AUDIOCPP_MODEL_ID, message)
        self.assertIn("pocket-tts", message)
        self.assertIn("other", message)

    def test_healthy_server_speaker_mode_defaults(self):
        client = self._client()
        self.assertEqual(client.api_url, config.AUDIOCPP_API_URL.rstrip("/"))
        self.assertEqual(client.model_id, config.AUDIOCPP_MODEL_ID)
        self.assertEqual(client.language, config.LANGUAGE)
        self.assertEqual(client.voice, "Vivian")
        self.assertFalse(client.preset_mode)
        self.assertTrue(client.speaker_mode)

    def test_speaker_mode_uses_configured_speaker(self):
        with patch.object(config, "SPEAKER", "uncle_fu"):
            client = self._client()
        self.assertEqual(client.voice, "Uncle Fu")
        self.assertTrue(client.speaker_mode)

    def test_voice_speaker_name_selects_speaker_mode(self):
        # --voice naming a built-in CustomVoice speaker selects speaker
        # mode; the name is normalized to its wire (display) form and no
        # preset validation runs.
        client = self._client(voice="Uncle_Fu")
        self.assertEqual(client.voice, "Uncle Fu")
        self.assertFalse(client.preset_mode)
        self.assertTrue(client.speaker_mode)

    def test_voice_speaker_name_on_clone_entry_is_a_preset(self):
        # --voice on a clone-only (Base) entry is a server-side preset,
        # not a built-in speaker, so the name is validated against the
        # server's voice library.
        with self.assertRaises(RuntimeError) as ctx:
            self._client(voice="Ryan", model_id="Qwen3-TTS-12Hz-1.7B-Base-GGUF",
                         models={"data": [
                             {"id": "Qwen3-TTS-12Hz-1.7B-Base-GGUF",
                              "family": "qwen3_tts"}]})
        message = str(ctx.exception)
        self.assertIn("'Ryan'", message)
        self.assertIn("--voice", message)

    def test_voice_speaker_name_does_not_reroute_to_clone_model(self):
        # A built-in speaker name on a CustomVoice primary selects speaker
        # mode without the AUDIOCPP_CLONE_MODEL_ID reroute.
        with patch.object(config, "AUDIOCPP_MODEL_ID",
                          "Qwen3-TTS-CustomVoice"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"):
            client = self._client(
                voice="Ryan",
                models={"data": [{"id": "Qwen3-TTS-CustomVoice",
                                  "family": "qwen3_tts"},
                                 {"id": "qwen3-tts-clone",
                                  "family": "qwen3_tts"}]})
        self.assertEqual(client.model_id, "Qwen3-TTS-CustomVoice")
        self.assertTrue(client.speaker_mode)
        self.assertFalse(client.preset_mode)

    def test_no_voice_on_base_entry_raises_instead_of_silent_speaker(self):
        # The Base model has no built-in speakers: without --voice the run
        # fails fast instead of silently sending a speaker name that the
        # model ignores.
        with self.assertRaises(RuntimeError) as ctx:
            self._client(model_id="Qwen3-TTS-12Hz-1.7B-Base-GGUF",
                         models={"data": [
                             {"id": "Qwen3-TTS-12Hz-1.7B-Base-GGUF",
                              "family": "qwen3_tts"}]})
        message = str(ctx.exception)
        self.assertIn("Base-GGUF", message)
        self.assertIn("--voice", message)

    def test_preset_mode_uses_requested_voice(self):
        client = self._client(voice="narrator")
        self.assertEqual(client.voice, "narrator")
        self.assertTrue(client.preset_mode)

    def test_preset_mode_validates_voice_against_server_list(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(voice="ghost", voices={"voices": ["narrator", "obama"]})
        message = str(ctx.exception)
        self.assertIn("ghost", message)
        self.assertIn("narrator", message)
        self.assertIn("obama", message)

    def test_preset_mode_skips_validation_when_voices_endpoint_fails(self):
        client = self._client(voice="narrator", voices=Exception)
        self.assertEqual(client.voice, "narrator")

    def test_invalid_language_fails_before_connect(self):
        with patch("converter.clients.faster.urllib.request.urlopen") as mock_urlopen:
            with self.assertRaises(ValueError):
                AudioCppTTSClient(_DUMMY_CHUNKS, language="klingon")
        mock_urlopen.assert_not_called()

    def test_explicit_language_normalized(self):
        client = self._client(language="ja")
        self.assertEqual(client.language, "Japanese")

    def test_seed_resolved_once_per_run(self):
        with patch.object(config, "CONSTANT_SEED", True), \
                patch.object(config, "SEED", -1):
            client = self._client()
        self.assertGreaterEqual(client._seed, 0)

    def test_preset_mode_routes_to_clone_model_when_configured(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"):
            client = self._client(
                voice="narrator",
                models={"data": [{"id": "qwen3-tts"}, {"id": "qwen3-tts-clone"}]})
        self.assertEqual(client.model_id, "qwen3-tts-clone")

    def test_preset_mode_falls_back_when_clone_model_not_on_server(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"), \
                self.assertLogs("converter.clients.audiocpp", level="WARNING") as logs:
            client = self._client(
                voice="narrator",
                models={"data": [{"id": "qwen3-tts", "family": "qwen3_tts"},
                                 {"id": "pocket-tts"}]})
        self.assertEqual(client.model_id, "qwen3-tts")
        self.assertTrue(any("qwen3-tts-clone" in line for line in logs.output))

    def test_empty_model_id_auto_picks_single_server_entry(self):
        # A multi-model server used without editing config.py: an empty
        # --model resolves to the only hosted entry automatically.
        client = self._client(
            voice="narrator", model_id="",
            models={"data": [{"id": "higgs", "family": "higgs_audio_tts"}]},
            voices={"voices": ["narrator"]})
        self.assertEqual(client.model_id, "higgs")

    def test_empty_model_id_with_multiple_entries_requires_explicit_choice(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(
                voice="narrator", model_id="",
                models={"data": [{"id": "higgs"}, {"id": "voxcpm2"}]},
                voices={"voices": ["narrator"]})
        message = str(ctx.exception)
        self.assertIn("--model", message)
        self.assertIn("higgs", message)
        self.assertIn("voxcpm2", message)

    def test_model_id_override_reaches_request(self):
        # --model overrides AUDIOCPP_MODEL_ID for the run.
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen"):
            client = self._client(
                voice="narrator", model_id="higgs",
                models={"data": [{"id": "higgs", "family": "higgs_audio_tts"}]},
                voices={"voices": ["narrator"]})
        self.assertEqual(client.model_id, "higgs")

    def test_clone_model_id_ignored_for_speaker_mode(self):
        # Speaker mode (no --voice on a CustomVoice entry) never reroutes to
        # AUDIOCPP_CLONE_MODEL_ID — that reroute is a preset-mode concern.
        with patch.object(config, "AUDIOCPP_MODEL_ID",
                          "Qwen3-TTS-CustomVoice"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"):
            client = self._client(
                models={"data": [{"id": "Qwen3-TTS-CustomVoice",
                                  "family": "qwen3_tts"},
                                 {"id": "qwen3-tts-clone",
                                  "family": "qwen3_tts"}]})
        self.assertEqual(client.model_id, "Qwen3-TTS-CustomVoice")

    def test_clone_model_id_equal_to_primary_is_noop(self):
        with patch.object(config, "AUDIOCPP_CLONE_MODEL_ID",
                          config.AUDIOCPP_MODEL_ID):
            client = self._client(voice="narrator")
        self.assertEqual(client.model_id, config.AUDIOCPP_MODEL_ID)

    def test_preset_mode_with_clone_only_server_uses_clone_model(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"):
            client = self._client(
                voice="narrator",
                models={"data": [{"id": "qwen3-tts-clone"}]})
        self.assertEqual(client.model_id, "qwen3-tts-clone")

    def test_speaker_mode_with_clone_only_server_suggests_voice(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"):
            with self.assertRaises(RuntimeError) as ctx:
                self._client(models={"data": [{"id": "qwen3-tts-clone"}]})
        message = str(ctx.exception)
        self.assertIn("qwen3-tts", message)
        self.assertIn("--voice", message)

    def test_preset_mode_with_no_matching_model_lists_both_ids(self):
        # Neither the primary nor the clone id is on the server, so the
        # family is unknown and no degradation warning is logged — the
        # requirement error lists both configured ids instead.
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"), \
                self.assertNoLogs("converter.clients.audiocpp", level="WARNING"):
            with self.assertRaises(RuntimeError) as ctx:
                self._client(voice="narrator",
                             models={"data": [{"id": "pocket-tts"}]})
        message = str(ctx.exception)
        self.assertIn("qwen3-tts", message)
        self.assertIn("qwen3-tts-clone", message)
        self.assertIn("pocket-tts", message)


class AudioCppTaskDetectionTests(unittest.TestCase):
    """Task auto-detection (tts/clon/vdes) and voice design validation."""

    def setUp(self):
        # Pin a CustomVoice id so the default (no-voice) path is speaker
        # mode; individual tests override family/task to exercise other paths.
        patcher = patch.object(
            config, "AUDIOCPP_MODEL_ID", "Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF")
        patcher.start()
        self.addCleanup(patcher.stop)

    @staticmethod
    def _json_response(payload):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = json.dumps(payload).encode("utf-8")
        return response

    def _client(self, voice=None, instructions=None, request_options=None,
                models=None):
        if models is None:
            models = {"data": [{"id": config.AUDIOCPP_MODEL_ID,
                                "family": "qwen3_tts"}]}

        def _dispatch(request, **_kwargs):
            url = request if isinstance(request, str) else request.full_url
            if url.endswith("/health"):
                return self._json_response({"status": "ok"})
            if url.endswith("/v1/models"):
                return self._json_response(models)
            if "/v1/audio/voices" in url:
                return self._json_response({"voices": ["narrator"]})
            raise AssertionError(f"unexpected URL: {url}")

        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=_dispatch):
            return AudioCppTTSClient(_DUMMY_CHUNKS, voice=voice,
                                     instructions=instructions,
                                     request_options=request_options)

    def test_missing_task_falls_back_to_tts(self):
        # Servers that predate the task field hosted plain TTS models.
        client = self._client(models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts"}]})
        self.assertEqual(client.task, AUDIOCPP_TASK_TTS)
        self.assertFalse(client.design_mode)

    def test_task_detected_from_models_endpoint(self):
        client = self._client(models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
             "task": "vdes"}]},
            instructions="A warm adult narrator")
        self.assertEqual(client.task, AUDIOCPP_TASK_VDES)
        self.assertTrue(client.design_mode)

    def test_clon_task_entry_connects_in_preset_mode(self):
        client = self._client(voice="narrator", models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID, "family": "chatterbox",
             "task": "clon"}]})
        self.assertEqual(client.task, "clon")
        self.assertFalse(client.design_mode)
        self.assertTrue(client.preset_mode)

    def test_unsupported_task_rejected_with_available_entries(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_asr",
                 "task": "asr"},
                {"id": "tts-1", "family": "qwen3_tts", "task": "tts"}]},
                instructions="unused")
        message = str(ctx.exception)
        self.assertIn("'asr'", message)
        self.assertIn("--model", message)
        self.assertIn("tts-1", message)

    def test_vdes_without_instructions_requires_description(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "vdes"}]})
        message = str(ctx.exception)
        self.assertIn("voice design", message)
        self.assertIn("--instructions", message)

    def test_vdes_with_voice_rejected(self):
        with self.assertRaises(RuntimeError) as ctx:
            self._client(voice="narrator", models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "vdes"}]},
                instructions="A warm adult narrator")
        self.assertIn("--voice", str(ctx.exception))
        self.assertIn("--instructions", str(ctx.exception))

    def test_vdes_with_instructions_connects_in_design_mode(self):
        buf = io.StringIO()
        with redirect_stdout(buf):
            client = self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "vdes"}]},
                instructions="A warm adult narrator")
        self.assertTrue(client.design_mode)
        self.assertEqual(client.instructions, "A warm adult narrator")
        out = buf.getvalue()
        self.assertIn("voice design", out)
        self.assertIn("A warm adult narrator", out)

    def test_instructions_without_voice_on_generic_family_connects(self):
        # Families without built-in speakers can get their voice from the
        # instruction alone (e.g. OmniVoice voice design).
        buf = io.StringIO()
        with redirect_stdout(buf):
            client = self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "omnivoice",
                 "task": "tts"}]},
                instructions="female, young adult, moderate pitch")
        self.assertFalse(client.design_mode)
        self.assertTrue(client.instruction_voice)
        self.assertIn("instruction voice", buf.getvalue())

    def test_instructions_with_builtin_speaker_family_stays_speaker_mode(self):
        buf = io.StringIO()
        with redirect_stdout(buf):
            client = self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "tts"}]},
                instructions="Very happy.")
        self.assertFalse(client.design_mode)
        self.assertFalse(client.instruction_voice)
        self.assertIn("speaker 'Vivian'", buf.getvalue())

    def test_config_instructions_used_when_flag_omitted(self):
        with patch.object(config, "AUDIOCPP_INSTRUCTIONS",
                          "A calm elderly storyteller"):
            client = self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "vdes"}]})
        self.assertEqual(client.instructions, "A calm elderly storyteller")

    def test_explicit_instructions_override_config_default(self):
        with patch.object(config, "AUDIOCPP_INSTRUCTIONS", "from config"):
            client = self._client(models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "qwen3_tts",
                 "task": "vdes"}]},
                instructions="from flag")
        self.assertEqual(client.instructions, "from flag")


class AudioCppFamilyDetectionTests(unittest.TestCase):
    """Family auto-detection and per-family adaptations."""

    def setUp(self):
        patcher = patch.object(config, "AUDIOCPP_MODEL_ID", "qwen")
        patcher.start()
        self.addCleanup(patcher.stop)

    @staticmethod
    def _json_response(payload):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = json.dumps(payload).encode("utf-8")
        return response

    def _client(self, voice="narrator", models=None):
        def _dispatch(request, **_kwargs):
            url = request if isinstance(request, str) else request.full_url
            if url.endswith("/health"):
                return self._json_response({"status": "ok"})
            if url.endswith("/v1/models"):
                return self._json_response(models)
            if "/v1/audio/voices" in url:
                return self._json_response({"voices": [voice] if voice else []})
            raise AssertionError(f"unexpected URL: {url}")

        with patch("converter.clients.faster.urllib.request.urlopen",
                   side_effect=_dispatch):
            return AudioCppTTSClient(_DUMMY_CHUNKS, voice=voice)

    def test_family_detected_from_models_endpoint(self):
        client = self._client(models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID, "family": "higgs_audio_tts"}]})
        self.assertEqual(client.family, "higgs_audio_tts")
        self.assertIs(client.profile, AUDIOCPP_DEFAULT_FAMILY_PROFILE)

    def test_missing_family_uses_generic_profile(self):
        # A missing family is unknown (not guessed as qwen3_tts): it falls
        # through to the generic clone-only profile.
        client = self._client(models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID}]})
        self.assertEqual(client.family, "")
        self.assertIs(client.profile, AUDIOCPP_DEFAULT_FAMILY_PROFILE)

    def test_unknown_family_uses_generic_profile(self):
        client = self._client(models={"data": [
            {"id": config.AUDIOCPP_MODEL_ID, "family": "future_tts"}]})
        self.assertEqual(client.family, "future_tts")
        self.assertIs(client.profile, AUDIOCPP_DEFAULT_FAMILY_PROFILE)
        self.assertEqual(client.profile.language_style, AUDIOCPP_LANG_OMIT)

    def test_speaker_mode_rejected_for_clone_only_family(self):
        client = None
        try:
            client = self._client(voice=None, models={"data": [
                {"id": config.AUDIOCPP_MODEL_ID, "family": "voxcpm2"}]})
        except RuntimeError as exc:
            message = str(exc)
            self.assertIn("voxcpm2", message)
            self.assertIn("--voice", message)
            self.assertIn("no built-in speakers", message)
        self.assertIsNone(client)

    def test_speaker_mode_allowed_for_customvoice_entry(self):
        # A Qwen3-TTS entry whose id names CustomVoice is speaker-capable;
        # no --voice is needed.
        with patch.object(config, "AUDIOCPP_MODEL_ID",
                          "Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF"):
            client = self._client(voice=None, models={"data": [
                {"id": "Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF",
                 "family": "qwen3_tts"}]})
        self.assertEqual(client.family, "qwen3_tts")

    def test_speaker_mode_rejected_for_qwen_base_entry(self):
        # A Qwen3-TTS entry whose id names Base (not CustomVoice) is
        # clone-only, even though its family has built-in speakers on other
        # entries: without --voice it fails fast.
        client = None
        try:
            client = self._client(voice=None, models={"data": [
                {"id": "Qwen3-TTS-12Hz-1.7B-Base-GGUF",
                 "family": "qwen3_tts"}]})
        except RuntimeError as exc:
            message = str(exc)
            self.assertIn("Base-GGUF", message)
            self.assertIn("--voice", message)
        self.assertIsNone(client)

    def test_clone_model_id_of_different_family_is_ignored(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "higgs"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen-clone"), \
                self.assertLogs("converter.clients.audiocpp", level="WARNING") as logs:
            client = self._client(models={"data": [
                {"id": "higgs", "family": "higgs_audio_tts"},
                {"id": "qwen-clone", "family": "qwen3_tts"}]})
        self.assertEqual(client.model_id, "higgs")
        self.assertTrue(any("different family" in line.lower() or
                            "hosts family" in line.lower()
                            for line in logs.output))

    def test_clone_model_id_missing_on_non_qwen_server_is_debug_only(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "higgs"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen-clone"), \
                self.assertNoLogs("converter.clients.audiocpp", level="WARNING"):
            client = self._client(models={"data": [
                {"id": "higgs", "family": "higgs_audio_tts"}]})
        self.assertEqual(client.model_id, "higgs")

    def test_clone_model_id_missing_on_qwen_server_still_warns(self):
        with patch.object(config, "AUDIOCPP_MODEL_ID", "qwen3-tts"), \
                patch.object(config, "AUDIOCPP_CLONE_MODEL_ID", "qwen3-tts-clone"), \
                self.assertLogs("converter.clients.audiocpp", level="WARNING") as logs:
            client = self._client(models={"data": [
                {"id": "qwen3-tts", "family": "qwen3_tts"},
                {"id": "pocket-tts", "family": "pocket_tts"}]})
        self.assertEqual(client.model_id, "qwen3-tts")
        self.assertTrue(any("qwen3-tts-clone" in line for line in logs.output))

    def test_iso_language_code_helper(self):
        self.assertEqual(LANGUAGE_ISO_CODES["English"], "en")
        self.assertIsNone(LANGUAGE_ISO_CODES.get("Auto"))

    def test_iso_codes_cover_the_audio_cpp_menu_languages(self):
        self.assertEqual(LANGUAGE_ISO_CODES["Arabic"], "ar")
        self.assertEqual(LANGUAGE_ISO_CODES["Hindi"], "hi")
        self.assertEqual(LANGUAGE_ISO_CODES["Vietnamese"], "vi")


class AudiocppEntryVoiceCapabilityTests(unittest.TestCase):
    """The per-entry voice capability resolver (speaker/clone/design)."""

    def _cap(self, family="", task="tts", model_id=""):
        return audiocpp_entry_voice_capability(family, task, model_id)

    def test_vdes_task_is_design(self):
        self.assertEqual(self._cap("qwen3_tts", "vdes",
                                   "Qwen3-TTS-VoiceDesign-GGUF"),
                         AUDIOCPP_VOICE_DESIGN)

    def test_qwen_customvoice_entry_is_speaker(self):
        self.assertEqual(self._cap("qwen3_tts", "tts",
                                   "Qwen3-TTS-12Hz-1.7B-CustomVoice-GGUF"),
                         AUDIOCPP_VOICE_SPEAKER)

    def test_qwen_base_entry_is_clone(self):
        self.assertEqual(self._cap("qwen3_tts", "tts",
                                   "Qwen3-TTS-12Hz-1.7B-Base-GGUF"),
                         AUDIOCPP_VOICE_CLONE)

    def test_qwen_unidentified_entry_is_clone(self):
        self.assertEqual(self._cap("qwen3_tts", "tts", "qwen"),
                         AUDIOCPP_VOICE_CLONE)

    def test_other_families_are_clone(self):
        self.assertEqual(self._cap("higgs_audio_tts", "tts", "higgs"),
                         AUDIOCPP_VOICE_CLONE)

    def test_missing_family_is_clone(self):
        self.assertEqual(self._cap("", "tts", "legacy"),
                         AUDIOCPP_VOICE_CLONE)

    def test_customvoice_match_is_case_insensitive(self):
        self.assertEqual(self._cap("qwen3_tts", "tts",
                                   "Qwen3-TTS-12Hz-1.7B-CUSTOMVOICE-GGUF"),
                         AUDIOCPP_VOICE_SPEAKER)

    def test_customvoice_id_in_other_family_is_not_speaker(self):
        # The "customvoice" substring only marks a speaker for the qwen3_tts
        # family; another family with a lookalike id stays clone-only.
        self.assertEqual(self._cap("future_tts", "tts",
                                   "Qwen3-TTS-CustomVoice"),
                         AUDIOCPP_VOICE_CLONE)


class AudioCppTTSClientRequestTests(unittest.TestCase):
    """The /v1/audio/speech payload and response validation."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()
        self._sleep = patch("converter.clients.base.time.sleep")
        self._sleep.start()

    def tearDown(self):
        self._sleep.stop()
        self._tmp.cleanup()

    def _make_client(self, preset_mode=False, voice="Vivian", language="English", seed=-1,
                     family="qwen3_tts", task="tts",
                     instructions=None, request_options=None):
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.api_url = "http://127.0.0.1:8080"
        client.model_id = config.AUDIOCPP_MODEL_ID
        client.preset_mode = preset_mode
        client.voice = voice
        client.language = language
        client._seed = seed
        client.family = family
        client.task = task
        client.profile = AUDIOCPP_FAMILY_PROFILES.get(
            family, AUDIOCPP_DEFAULT_FAMILY_PROFILE)
        client.instructions = instructions or ""
        client.request_options = dict(request_options or {})
        client.design_mode = task == AUDIOCPP_TASK_VDES
        # Mirrors the connect-time rule: an instruction-defined voice on a
        # clone-capable entry with no --voice (design mode takes precedence).
        capability = audiocpp_entry_voice_capability(
            family, task, client.model_id)
        client.instruction_voice = (
            not preset_mode and not client.design_mode
            and capability == AUDIOCPP_VOICE_CLONE
            and bool(client.instructions))
        return client

    @staticmethod
    def _wav_bytes(frames=b"\x01\x00" * 10, rate=SAMPLE_RATE):
        buffer = io.BytesIO()
        with wave.open(buffer, "wb") as wav_file:
            wav_file.setnchannels(1)
            wav_file.setsampwidth(2)
            wav_file.setframerate(rate)
            wav_file.writeframes(frames)
        return buffer.getvalue()

    def _post_response(self, body):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = body
        return response

    def test_payload_includes_model_input_voice_language_and_seed(self):
        client = self._make_client(preset_mode=True, voice="narrator",
                                   language="Japanese", seed=1234)
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello world.")
        request = mock_urlopen.call_args[0][0]
        self.assertEqual(request.full_url,
                         "http://127.0.0.1:8080/v1/audio/speech")
        payload = json.loads(request.data.decode("utf-8"))
        self.assertEqual(payload["model"], config.AUDIOCPP_MODEL_ID)
        self.assertEqual(payload["input"], "Hello world.")
        self.assertEqual(payload["voice"], "narrator")
        self.assertEqual(payload["language"], "Japanese")
        self.assertEqual(payload["seed"], 1234)
        self.assertNotIn("instructions", payload)

    def test_negative_seed_omitted_from_payload(self):
        client = self._make_client(preset_mode=True, voice="narrator", seed=-1)
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello world.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("seed", payload)

    def test_request_timeout_is_the_configured_api_timeout(self):
        client = self._make_client()
        long_text = " ".join(f"word{i}" for i in range(1500))
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav(long_text)
        timeout = mock_urlopen.call_args[1]["timeout"]
        self.assertEqual(timeout, config.API_TIMEOUT)

    def test_speaker_mode_sends_instruct(self):
        client = self._make_client(preset_mode=False)
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["instructions"], config.INSTRUCT)

    def test_explicit_instructions_replace_config_instruct(self):
        # --instructions overrides the INSTRUCT default in speaker mode.
        client = self._make_client(preset_mode=False,
                                   instructions="Read whisper quiet.")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["instructions"], "Read whisper quiet.")

    def test_preset_mode_sends_instructions_alongside_voice(self):
        # Clone + style control: both the server-side voice and the
        # instruction reach the model.
        client = self._make_client(preset_mode=True, voice="narrator",
                                   instructions="Calm and steady.")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["voice"], "narrator")
        self.assertEqual(payload["instructions"], "Calm and steady.")

    def test_design_mode_payload_omits_voice_and_sends_instructions(self):
        client = self._make_client(task="vdes",
                                   instructions="A warm adult narrator")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("voice", payload)
        self.assertEqual(payload["instructions"], "A warm adult narrator")

    def test_design_mode_language_follows_family_profile(self):
        # The VoiceDesign package is family qwen3_tts, whose language field
        # takes Qwen display names like the other variants.
        client = self._make_client(task="vdes", language="Japanese",
                                   instructions="A warm adult narrator")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["language"], "Japanese")

    def test_instruction_voice_payload_omits_voice(self):
        # Instruction-defined voice on a family without built-in speakers:
        # no speaker name is invented, the instruction carries the voice.
        client = self._make_client(family="omnivoice",
                                   instructions="female, young adult")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("voice", payload)
        self.assertNotIn("language", payload)  # generic profile: omitted
        self.assertEqual(payload["instructions"], "female, young adult")

    def test_request_options_forwarded_in_payload(self):
        client = self._make_client(preset_mode=True, voice="narrator",
                                   request_options={"emotion": "neutral",
                                                    "speed": "1.1"})
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["options"], {"emotion": "neutral",
                                              "speed": "1.1"})

    def test_empty_request_options_omit_options_field(self):
        client = self._make_client(preset_mode=True, voice="narrator")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("options", payload)

    def test_generic_family_omits_language_and_instructions(self):
        # Clone-only families (higgs_audio_tts, voxcpm2, ...) detect the
        # language themselves and take no style instruction.
        client = self._make_client(preset_mode=False, family="higgs_audio_tts")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("language", payload)
        self.assertNotIn("instructions", payload)

    def test_iso_family_sends_language_code(self):
        client = self._make_client(preset_mode=True, voice="narrator",
                                   language="Japanese", family="index_tts2")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["language"], "ja")

    def test_iso_family_auto_omits_language(self):
        client = self._make_client(preset_mode=True, voice="narrator",
                                   language="Auto", family="index_tts2")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertNotIn("language", payload)

    def test_qwen_language_display_name_still_sent(self):
        client = self._make_client(preset_mode=True, voice="narrator",
                                   language="Japanese", family="qwen3_tts")
        with patch("converter.clients.faster.urllib.request.urlopen",
                   return_value=self._post_response(self._wav_bytes())) as mock_urlopen:
            client._request_wav("Hello.")
        payload = json.loads(mock_urlopen.call_args[0][0].data.decode("utf-8"))
        self.assertEqual(payload["language"], "Japanese")

    def test_non_wav_response_rejected(self):
        client = self._make_client()
        for body in (b"", b"RIFFxxxx", b"MP3DATA-MP3DATA", b"RIFF\x00\x00\x00\x00mpeg"):
            with patch("converter.clients.faster.urllib.request.urlopen",
                       return_value=self._post_response(body)):
                with self.assertRaises(RuntimeError):
                    client._request_wav("Hello.")

    def test_http_error_body_surfaced(self):
        import urllib.error
        client = self._make_client()
        error = urllib.error.HTTPError(
            "http://127.0.0.1:8080/v1/audio/speech", 500,
            "Server Error", {}, io.BytesIO(b'{"error":"bad voice"}'))
        with patch("converter.clients.faster.urllib.request.urlopen", side_effect=error):
            with self.assertRaises(RuntimeError) as ctx:
                client._request_wav("Hello.")
        self.assertIn("500", str(ctx.exception))
        self.assertIn("bad voice", str(ctx.exception))

    def test_transient_failure_fails_the_chunk_attempt(self):
        # Retrying is the chunk-level policy's job
        # (process_chunk_with_retry); one generate_chunk call makes one
        # request attempt per sub-chunk.
        client = self._make_client()
        wav = self._wav_bytes()
        with patch.object(client, "_request_wav",
                          side_effect=[RuntimeError("boom"), wav]) as mock_request:
            result = client.generate_chunk("Hello.", 1)
        self.assertIsNone(result)
        self.assertEqual(mock_request.call_count, 1)

    def test_request_failure_fails_the_chunk(self):
        client = self._make_client()
        with patch.object(client, "_request_wav",
                          side_effect=RuntimeError("down")) as mock_request:
            result = client.generate_chunk("Hello.", 1)
        self.assertIsNone(result)
        self.assertEqual(mock_request.call_count, 1)

    def test_empty_text_fails_the_chunk(self):
        client = self._make_client()
        with patch.object(client, "_request_wav") as mock_request:
            result = client.generate_chunk("   ", 1)
        self.assertIsNone(result)
        mock_request.assert_not_called()

    def test_generate_chunk_writes_valid_wav(self):
        client = self._make_client()
        frames = b"\x01\x00" * 100
        with patch.object(client, "_request_wav", return_value=self._wav_bytes(frames)):
            result = client.generate_chunk("Hello world.", 1)
        self.assertIsNotNone(result)
        path = Path(result)
        self.assertEqual(path.name, "chunk_0001.wav")
        with wave.open(str(path), "rb") as wav_file:
            self.assertEqual(wav_file.getnchannels(), 1)
            self.assertEqual(wav_file.getsampwidth(), 2)
            self.assertEqual(wav_file.getframerate(), SAMPLE_RATE)
            self.assertEqual(wav_file.readframes(wav_file.getnframes()), frames)

    def test_long_text_is_subchunked_and_concatenated_in_order(self):
        client = self._make_client()
        sentences = [" ".join(f"word{i}" for i in range(6)) + "." for _ in range(3)]
        text = " ".join(sentences)
        parts = [self._wav_bytes(b"\x01\x00" * 10),
                 self._wav_bytes(b"\x02\x00" * 20),
                 self._wav_bytes(b"\x03\x00" * 30)]
        with patch.object(config, "CHUNK_SIZE", 10), \
                patch.object(client, "_request_wav", side_effect=parts) as mock_request:
            result = client.generate_chunk(text, 1)
        self.assertEqual(mock_request.call_count, 3)
        with wave.open(str(Path(result)), "rb") as wav_file:
            self.assertEqual(wav_file.readframes(wav_file.getnframes()),
                             b"\x01\x00" * 10 + b"\x02\x00" * 20 + b"\x03\x00" * 30)

    def test_stale_chunk_files_are_removed(self):
        stale = Path(self._tmp.name) / "chunk_0001.mp3"
        stale.write_bytes(b"old")
        client = self._make_client()
        with patch.object(client, "_request_wav", return_value=self._wav_bytes()):
            client.generate_chunk("Hello.", 1)
        remaining = sorted(path.name for path in Path(self._tmp.name).glob("chunk_0001.*"))
        self.assertEqual(remaining, ["chunk_0001.wav"])


class AudioCppHeartbeatTests(unittest.TestCase):
    """The heartbeat reports chunk progress while a request generates."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()

    def tearDown(self):
        self._tmp.cleanup()

    def _client(self):
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.api_url = "http://127.0.0.1:8080"
        client.model_id = config.AUDIOCPP_MODEL_ID
        client.preset_mode = False
        client.voice = "Vivian"
        client.language = "English"
        client._seed = -1
        client.family = "qwen3_tts"
        client.profile = AUDIOCPP_DEFAULT_FAMILY_PROFILE
        return client

    @staticmethod
    def _wav_bytes():
        buffer = io.BytesIO()
        with wave.open(buffer, "wb") as wav_file:
            wav_file.setnchannels(1)
            wav_file.setsampwidth(2)
            wav_file.setframerate(SAMPLE_RATE)
            wav_file.writeframes(b"\x01\x00" * 10)
        return buffer.getvalue()

    def _run(self):
        client = self._client()

        def slow_request(*_args, **_kwargs):
            time.sleep(0.12)
            return self._wav_bytes()

        buf = io.StringIO()
        with patch.object(config, "HEARTBEAT_INTERVAL_SECONDS", 0.03), \
                patch.object(client, "_request_wav",
                             side_effect=slow_request), \
                redirect_stdout(buf):
            result = client.generate_chunk("Hello.", 1)
        self.assertTrue(result)
        return buf.getvalue()

    def test_heartbeat_reports_chunk_progress(self):
        out = self._run()
        self.assertIn("Chunk 1 still generating", out)


class AudioCppTTSClientTruncationTests(unittest.TestCase):
    """Audio far shorter than its text implies fails the request."""

    def setUp(self):
        self._tmp = tempfile.TemporaryDirectory()

    def tearDown(self):
        self._tmp.cleanup()

    def _make_client(self):
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.chunks_dir = Path(self._tmp.name)
        client.api_url = "http://127.0.0.1:8080"
        client.model_id = config.AUDIOCPP_MODEL_ID
        client.preset_mode = True
        client.voice = "narrator"
        client.language = "English"
        client._seed = -1
        client.family = "qwen3_tts"
        client.profile = AUDIOCPP_FAMILY_PROFILES["qwen3_tts"]
        return client

    @staticmethod
    def _wav_bytes(frames):
        buffer = io.BytesIO()
        with wave.open(buffer, "wb") as wav_file:
            wav_file.setnchannels(1)
            wav_file.setsampwidth(2)
            wav_file.setframerate(SAMPLE_RATE)
            wav_file.writeframes(frames)
        return buffer.getvalue()

    def test_full_length_wav_passes(self):
        client = self._make_client()
        text = " ".join(f"word{i}" for i in range(12))
        # 12 words -> expected 4.8s, half is 2.4s -> 2.5s of audio passes.
        wav = self._wav_bytes(b"\x01\x00" * int(2.5 * SAMPLE_RATE))
        with patch.object(client, "_request_wav", return_value=wav):
            result = client.generate_chunk(text, 1)
        self.assertIsNotNone(result)


class AudioCppUnloadModelsTests(unittest.TestCase):
    """Before generating, the client asks the server to drop loaded models."""

    @staticmethod
    def _client():
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.api_url = "http://127.0.0.1:8080"
        return client

    @staticmethod
    def _response(body):
        response = MagicMock()
        response.__enter__.return_value = response
        response.read.return_value = body
        return response

    def test_posts_to_unload_all_models(self):
        client = self._client()
        with patch("converter.clients.audiocpp.urllib.request.urlopen",
                   return_value=self._response(b'{"unloaded": ["qwen"]}')) as mock_urlopen:
            client._unload_server_models()
        request = mock_urlopen.call_args[0][0]
        self.assertEqual(request.full_url,
                         "http://127.0.0.1:8080/v1/tasks/unload_all_models")
        self.assertEqual(request.method, "POST")
        self.assertEqual(request.data, b"")

    def test_reports_unloaded_ids(self):
        client = self._client()
        buf = io.StringIO()
        with patch("converter.clients.audiocpp.urllib.request.urlopen",
                   return_value=self._response(b'{"unloaded": ["a", "b"]}')), \
                redirect_stdout(buf):
            client._unload_server_models()
        self.assertIn("Unloaded 2 model(s)", buf.getvalue())
        self.assertIn("a, b", buf.getvalue())

    def test_no_loaded_models_is_silent(self):
        client = self._client()
        buf = io.StringIO()
        with patch("converter.clients.audiocpp.urllib.request.urlopen",
                   return_value=self._response(b'{"unloaded": []}')), \
                redirect_stdout(buf):
            client._unload_server_models()
        self.assertEqual(buf.getvalue(), "")

    def test_http_error_warns_and_continues(self):
        client = self._client()
        buf = io.StringIO()
        with patch("converter.clients.audiocpp.urllib.request.urlopen",
                   side_effect=urllib.error.HTTPError(
                       "http://127.0.0.1:8080/v1/tasks/unload_all_models",
                       404, "Not Found", None, io.BytesIO())), \
                redirect_stdout(buf):
            client._unload_server_models()
        out = buf.getvalue()
        self.assertIn("[WARNING]", out)
        self.assertIn("404", out)

    def test_connection_error_warns_and_continues(self):
        client = self._client()
        buf = io.StringIO()
        with patch("converter.clients.audiocpp.urllib.request.urlopen",
                   side_effect=urllib.error.URLError("refused")), \
                redirect_stdout(buf):
            client._unload_server_models()
        self.assertIn("[WARNING]", buf.getvalue())

    def test_connect_unloads_before_returning(self):
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.api_url = "http://127.0.0.1:8080"
        client.model_id = config.AUDIOCPP_MODEL_ID
        client.preset_mode = True
        client.voice = "narrator"
        client.language = "English"
        client._seed = -1
        client.family = "qwen3_tts"
        client.task = AUDIOCPP_TASK_TTS
        client.profile = AUDIOCPP_FAMILY_PROFILES["qwen3_tts"]
        client.design_mode = False
        client.instruction_voice = False
        client.speaker_mode = False
        client.instructions = ""
        with patch.object(client, "_check_health"), \
                patch.object(client, "_list_models",
                             return_value=[{"id": client.model_id,
                                            "family": "qwen3_tts",
                                            "task": "tts"}]), \
                patch.object(client, "_auto_pick_model_id"), \
                patch.object(client, "_select_model"), \
                patch.object(client, "_require_model_id"), \
                patch.object(client, "_resolve_family"), \
                patch.object(client, "_resolve_task"), \
                patch.object(client, "_check_voice"), \
                patch.object(client, "_unload_server_models") as mock_unload:
            client._connect()
        mock_unload.assert_called_once()

    def test_connect_skips_unload_when_disabled(self):
        client = AudioCppTTSClient.__new__(AudioCppTTSClient)
        client.api_url = "http://127.0.0.1:8080"
        client.model_id = config.AUDIOCPP_MODEL_ID
        client.preset_mode = True
        client.voice = "narrator"
        client.language = "English"
        client._seed = -1
        client.family = "qwen3_tts"
        client.task = AUDIOCPP_TASK_TTS
        client.profile = AUDIOCPP_FAMILY_PROFILES["qwen3_tts"]
        client.design_mode = False
        client.instruction_voice = False
        client.speaker_mode = False
        client.instructions = ""
        with patch.object(client, "_check_health"), \
                patch.object(client, "_list_models",
                             return_value=[{"id": client.model_id,
                                            "family": "qwen3_tts",
                                            "task": "tts"}]), \
                patch.object(client, "_auto_pick_model_id"), \
                patch.object(client, "_select_model"), \
                patch.object(client, "_require_model_id"), \
                patch.object(client, "_resolve_family"), \
                patch.object(client, "_resolve_task"), \
                patch.object(client, "_check_voice"), \
                patch.object(config, "AUDIOCPP_UNLOAD_MODELS", False), \
                patch.object(client, "_unload_server_models") as mock_unload:
            client._connect()
        mock_unload.assert_not_called()


class BackendWiringTests(unittest.TestCase):
    """AudiobookConverter wiring for the --backend selector."""

    def test_faster_backend_uses_faster_client_without_reference(self):
        with patch("converter.converter.FasterTTSClient") as mock_faster, \
                patch("converter.converter.QwenTTSClient") as mock_qwen, \
                patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                               backend=BACKEND_FASTER, voice="narrator")
        mock_faster.assert_called_once_with(chunks_dir=converter_mod.CHUNKS_FOLDER,
                                            voice="narrator", api_url=None,
                                            quiet=False)
        mock_qwen.assert_not_called()
        mock_audiocpp.assert_not_called()

    def test_audiocpp_backend_with_voice_uses_audiocpp_client(self):
        with patch("converter.converter.FasterTTSClient") as mock_faster, \
                patch("converter.converter.QwenTTSClient") as mock_qwen, \
                patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                               backend=BACKEND_AUDIOCPP, voice="narrator",
                               language="ja")
        mock_audiocpp.assert_called_once_with(chunks_dir=converter_mod.CHUNKS_FOLDER,
                                              voice="narrator", language="Japanese",
                                              model_id=None,
                                              instructions=None,
                                              request_options={},
                                              api_url=None, quiet=False)
        mock_faster.assert_not_called()
        mock_qwen.assert_not_called()

    def test_audiocpp_backend_without_voice_uses_audiocpp_client(self):
        with patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CUSTOM,
                               backend=BACKEND_AUDIOCPP)
        mock_audiocpp.assert_called_once_with(chunks_dir=converter_mod.CHUNKS_FOLDER,
                                              voice=None, language=config.LANGUAGE,
                                              model_id=None,
                                              instructions=None,
                                              request_options={},
                                              api_url=None, quiet=False)

    def test_audiocpp_backend_model_id_is_wired_through(self):
        with patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                               backend=BACKEND_AUDIOCPP, voice="narrator",
                               model_id="higgs")
        mock_audiocpp.assert_called_once_with(
            chunks_dir=converter_mod.CHUNKS_FOLDER,
            voice="narrator", language=config.LANGUAGE,
            model_id="higgs", instructions=None,
            request_options={}, api_url=None, quiet=False)

    def test_audiocpp_backend_instructions_and_options_are_wired_through(self):
        with patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CUSTOM,
                               backend=BACKEND_AUDIOCPP,
                               instructions="A warm adult narrator",
                               request_options={"emotion": "neutral",
                                                "speed": "1.1"})
        mock_audiocpp.assert_called_once_with(
            chunks_dir=converter_mod.CHUNKS_FOLDER,
            voice=None, language=config.LANGUAGE,
            model_id=None,
            instructions="A warm adult narrator",
            request_options={"emotion": "neutral", "speed": "1.1"},
            api_url=None, quiet=False)

    def test_qwen_backend_uses_qwen_client(self):
        with patch("converter.converter.FasterTTSClient") as mock_faster, \
                patch("converter.converter.QwenTTSClient") as mock_qwen, \
                patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CUSTOM,
                               backend=BACKEND_QWEN)
        mock_qwen.assert_called_once()
        mock_faster.assert_not_called()
        mock_audiocpp.assert_not_called()

    def test_qwen_clone_mode_still_requires_reference(self):
        with patch("converter.converter.QwenTTSClient"):
            with self.assertRaises(ValueError):
                AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                                   backend=BACKEND_QWEN)

    def test_qwen_design_mode_without_instructions_rejected(self):
        # A VoiceDesign run needs a description; an empty instructions
        # value (not even the config default) is refused up front.
        with patch("converter.converter.QwenTTSClient"):
            with self.assertRaises(ValueError):
                AudiobookConverter(voice_mode=VOICE_MODE_DESIGN,
                                   backend=BACKEND_QWEN, instructions="   ")

    def test_qwen_design_mode_threads_instructions_to_the_client(self):
        with patch("converter.converter.QwenTTSClient") as mock_qwen:
            AudiobookConverter(voice_mode=VOICE_MODE_DESIGN,
                               backend=BACKEND_QWEN,
                               instructions="A warm adult female narrator")
        _, kwargs = mock_qwen.call_args
        self.assertEqual(kwargs["instructions"],
                         "A warm adult female narrator")

    def test_qwen_design_narrator_tag_uses_designed(self):
        self.assertEqual(AudiobookConverter.compute_narrator_tag(
            BACKEND_QWEN, None, VOICE_MODE_DESIGN, None,
            "A warm adult female narrator"), "designed")

    def test_api_url_override_reaches_each_client(self):
        # A remote conversion threads api_url through to the selected client.
        with patch("converter.converter.AudioCppTTSClient") as mock_audiocpp:
            AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                               backend=BACKEND_AUDIOCPP, voice="narrator",
                               api_url="http://10.0.0.5:8080")
        mock_audiocpp.assert_called_once_with(
            chunks_dir=converter_mod.CHUNKS_FOLDER,
            voice="narrator", language=config.LANGUAGE, model_id=None,
            instructions=None, request_options={},
            api_url="http://10.0.0.5:8080", quiet=False)
        with patch("converter.converter.FasterTTSClient") as mock_faster:
            AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                               backend=BACKEND_FASTER, voice="narrator",
                               api_url="http://10.0.0.5:8000")
        mock_faster.assert_called_once_with(chunks_dir=converter_mod.CHUNKS_FOLDER,
                                            voice="narrator",
                                            api_url="http://10.0.0.5:8000",
                                            quiet=False)
        with patch("converter.converter.QwenTTSClient") as mock_qwen:
            AudiobookConverter(voice_mode=VOICE_MODE_CUSTOM,
                               backend=BACKEND_QWEN,
                               api_url="http://10.0.0.5:7860")
        mock_qwen.assert_called_once_with(
            chunks_dir=converter_mod.CHUNKS_FOLDER,
            voice_mode=VOICE_MODE_CUSTOM, voice_clone_ref_audio=None,
            voice_clone_ref_text=None, skip_transcription=False,
            language=config.LANGUAGE, instructions=None,
            api_url="http://10.0.0.5:7860", quiet=False)

    def test_audiocpp_clone_mode_does_not_require_reference(self):
        # Cloning is server-side for the audiocpp backend, so the
        # clone-mode voice can be selected without local reference audio.
        with patch("converter.converter.AudioCppTTSClient"):
            converter = AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                                           backend=BACKEND_AUDIOCPP,
                                           voice="narrator")
        self.assertIsNone(converter.voice_clone_ref_audio)

    def test_chapter_chunks_audiocpp_splits(self):
        converter = self._audiocpp_converter(voice="narrator")
        text = " ".join(f"word{i}" for i in range(50))
        with patch.object(config, "CHUNK_SIZE", 10):
            chunks = converter._chapter_chunks(text)
        self.assertGreater(len(chunks), 1)
        self.assertTrue(all(len(chunk.split()) <= 10 for chunk in chunks))

    def test_chapter_chunks_qwen_always_splits(self):
        with patch("converter.converter.QwenTTSClient"):
            converter = AudiobookConverter(voice_mode=VOICE_MODE_CUSTOM,
                                           backend=BACKEND_QWEN)
        text = " ".join(f"word{i}" for i in range(50))
        with patch.object(config, "CHUNK_SIZE", 10):
            chunks = converter._chapter_chunks(text)
        self.assertGreater(len(chunks), 1)

    def test_faster_backend_still_validates_other_settings(self):
        with patch("converter.converter.FasterTTSClient"):
            with self.assertRaises(ValueError):
                AudiobookConverter(backend=BACKEND_FASTER, speed=0)
            with self.assertRaises(ValueError):
                AudiobookConverter(backend=BACKEND_FASTER, language="klingon")

    def test_audiocpp_backend_still_validates_other_settings(self):
        with patch("converter.converter.AudioCppTTSClient"):
            with self.assertRaises(ValueError):
                AudiobookConverter(backend=BACKEND_AUDIOCPP, speed=0)
            with self.assertRaises(ValueError):
                AudiobookConverter(backend=BACKEND_AUDIOCPP, language="klingon")

    def _faster_converter(self, voice=None):
        with patch("converter.converter.FasterTTSClient"):
            return AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                                      backend=BACKEND_FASTER, voice=voice)

    def _audiocpp_converter(self, voice=None):
        with patch("converter.converter.AudioCppTTSClient"):
            return AudiobookConverter(
                voice_mode=VOICE_MODE_CLONE if voice else VOICE_MODE_CUSTOM,
                backend=BACKEND_AUDIOCPP, voice=voice)

    def test_narrator_tag_uses_faster_voice_name(self):
        converter = self._faster_converter(voice="male_richard_poe")
        self.assertEqual(converter._narrator_tag(), "male_richard_poe")

    def test_narrator_tag_falls_back_to_config_voice(self):
        converter = self._faster_converter()
        self.assertEqual(converter._narrator_tag(), config.FASTER_VOICE)

    def test_narrator_tag_audiocpp_uses_voice_name(self):
        converter = self._audiocpp_converter(voice="female_narrator")
        self.assertEqual(converter._narrator_tag(), "female_narrator")

    def test_narrator_tag_audiocpp_falls_back_to_speaker(self):
        converter = self._audiocpp_converter()
        self.assertEqual(converter._narrator_tag(), "Vivian")

    def test_banner_and_narrator_work_without_reference_audio(self):
        converter = self._faster_converter(voice="male_richard_poe")
        converter._print_banner()  # must not raise (regression: Path(None))
        self.assertIsNone(converter.voice_clone_ref_audio)

    def test_audiocpp_banner_prints_without_reference_audio(self):
        converter = self._audiocpp_converter(voice="narrator")
        converter._print_banner()  # must not raise
        converter = self._audiocpp_converter()
        converter._print_banner()

    def test_audiocpp_banner_prints_model_family(self):
        from contextlib import redirect_stdout
        converter = self._audiocpp_converter(voice="narrator")
        converter.tts.family = "higgs_audio_tts"
        buffer = io.StringIO()
        with redirect_stdout(buffer):
            converter._print_banner()
        self.assertIn("higgs_audio_tts", buffer.getvalue())

    def test_non_faster_narrator_tag_unchanged(self):
        with tempfile.TemporaryDirectory() as tmp:
            ref = Path(tmp) / "ref.wav"
            ref.write_bytes(b"x")
            with patch("converter.converter.QwenTTSClient"):
                converter = AudiobookConverter(voice_mode=VOICE_MODE_CLONE,
                                               voice_clone_ref_audio=str(ref),
                                               backend=BACKEND_QWEN)
        self.assertEqual(converter._narrator_tag(), "ref")


if __name__ == "__main__":
    unittest.main()