Spaces:
Running
Running
File size: 326,053 Bytes
ae033d7 6554a8b 5a7ba4f 6554a8b 39843ef 5a7ba4f 39843ef 5a7ba4f 39843ef 5a7ba4f 39843ef 5a7ba4f 39843ef ae033d7 31a8fcf ae033d7 c9053fb ae033d7 c9053fb ae033d7 31a8fcf ae033d7 6554a8b ae033d7 c9053fb ae033d7 6554a8b ae033d7 c9053fb ae033d7 3fd4887 ae033d7 3fd4887 ae033d7 3033f80 24144ae 3033f80 ae033d7 49f286f 3033f80 ae033d7 3fd4887 c9053fb 3fd4887 a3845cb e99e1de a3845cb e99e1de a3845cb e99e1de ae033d7 3033f80 b196deb 3033f80 b196deb ae033d7 b196deb ae033d7 6554a8b ae033d7 6554a8b ae033d7 49f286f ae033d7 e99e1de ae033d7 1b351fd ae033d7 1b351fd 3fd4887 1b351fd ae033d7 1b351fd ae033d7 1b351fd ae033d7 1b351fd ae033d7 b196deb ae033d7 e99e1de c9053fb e99e1de ae033d7 1b351fd ae033d7 1b351fd 29cfff3 ae033d7 c9053fb ae033d7 f94b7aa ae033d7 e99e1de ae033d7 | 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 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 | /**
* Translet AI - Modern Kurdish & Multilingual Translator
* Powered by Google Gemini AI & Multi-Engine Architecture
*/
// Default Gemini AI API Configuration
const API_BASE = (typeof window !== 'undefined' && (window.location.protocol === 'file:' || !window.location.host))
? 'http://localhost:3000'
: '';
// True only for hosts that serve plain files with no Python server behind them.
// The cloud server Space (*.hf.space, not *.static.hf.space) and the workers.dev link do have /api.
function isStaticOnlyHost() {
const host = (typeof window !== 'undefined' && window.location.host) || '';
return host.endsWith('.static.hf.space') || host.endsWith('github.io') || host.endsWith('pages.dev');
}
let _audioUnlocked = false;
function unlockAudio() {
if (_audioUnlocked) return;
try {
const dummy = new Audio();
dummy.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
dummy.play().then(() => {
_audioUnlocked = true;
}).catch(() => {});
} catch (_) {}
}
if (typeof document !== 'undefined') {
document.addEventListener('click', unlockAudio, { passive: true });
document.addEventListener('touchstart', unlockAudio, { passive: true });
}
// ---- Private usage counter: a random id per phone + how many translations today (no personal data) ----
const LalaStats = (() => {
if (typeof window === 'undefined' || typeof localStorage === 'undefined') return { count() {} };
const today = () => new Date(Date.now() + 3 * 3600e3).toISOString().slice(0, 10); // Kurdistan day
let s = {};
let id = null;
try { s = JSON.parse(localStorage.getItem('lala_stats') || '{}') || {}; } catch (_) { s = {}; }
try {
id = localStorage.getItem('lala_anon_id');
window._lalaReturningUser = !!id; // used by the "app was updated" note
if (!id) {
id = (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : (Date.now().toString(36) + Math.random().toString(36).slice(2));
localStorage.setItem('lala_anon_id', id);
}
} catch (_) { id = null; }
const save = () => { try { localStorage.setItem('lala_stats', JSON.stringify(s)); } catch (_) {} };
const post = (payload) => {
if (!id || location.protocol === 'file:') return;
const body = JSON.stringify(Object.assign({ id }, payload));
try {
if (navigator.sendBeacon) navigator.sendBeacon('/api/ping', new Blob([body], { type: 'application/json' }));
else fetch('/api/ping', { method: 'POST', body, headers: { 'Content-Type': 'application/json' }, keepalive: true });
} catch (_) {}
};
const roll = () => {
const d = today();
if (s.day === d) return;
// counts of an earlier day that were never sent: send them before starting the new day
if (s.day && (s.t !== s.sentT || s.v !== s.sentV) && (s.t || s.v)) post({ day: s.day, t: s.t, v: s.v });
s = { day: d, t: 0, v: 0, sentT: -1, sentV: -1, last: 0 };
save();
};
function send(force) {
roll();
if (!force && s.sentT === s.t && s.sentV === s.v) return;
if (!force && Date.now() - s.last < 5 * 60e3) return; // at most every 5 minutes
s.sentT = s.t; s.sentV = s.v; s.last = Date.now(); save();
post({ day: s.day, t: s.t, v: s.v });
}
roll();
if (s.sentT === -1) setTimeout(() => send(true), 4000); // first open today
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') send(false); });
return { count(kind) { try { roll(); s[kind] = (s[kind] || 0) + 1; save(); } catch (_) {} } };
})();
// ---- "A new update is ready": compare this copy's version with version.json on the server ----
(function lalaUpdateCheck() {
if (typeof document === 'undefined' || location.protocol === 'file:') return;
const meta = document.querySelector('meta[name="lala-version"]');
const mine = meta ? meta.content : '';
if (!mine) return;
let shownFor = '';
async function check() {
try {
const r = await fetch('/version.json?t=' + Date.now(), { cache: 'no-store' });
if (!r.ok) return;
const v = await r.json();
if (!v || !v.version || v.version === mine || v.version === shownFor) return;
shownFor = v.version;
show(v.notes || '');
} catch (_) {}
}
// First open of a new version (however the app was opened): say once what changed
async function announceIfUpdated() {
let seen = null;
try { seen = localStorage.getItem('lala_seen_version'); localStorage.setItem('lala_seen_version', mine); } catch (_) { return; }
if (seen === mine) return; // nothing new
if (!seen && !window._lalaReturningUser) return; // very first visit: nothing to announce
let notes = '';
try {
const r = await fetch('/version.json?t=' + Date.now(), { cache: 'no-store' });
const v = r.ok ? await r.json() : null;
if (v && v.version === mine) notes = v.notes || '';
} catch (_) {}
show(notes, true);
}
function show(notes, done) {
if (document.getElementById('lalaUpdateBar')) return;
const bar = document.createElement('div');
bar.id = 'lalaUpdateBar';
bar.dir = 'rtl';
bar.style.cssText = 'position:fixed;left:50%;transform:translateX(-50%);z-index:99998;' +
'bottom:calc(env(safe-area-inset-bottom, 0px) + 16px);width:min(92vw,440px);' +
'background:linear-gradient(135deg,#16a34a,#15803d);color:#fff;border-radius:16px;padding:12px 14px;' +
'box-shadow:0 8px 28px rgba(0,0,0,.45);font-family:inherit;display:flex;align-items:center;gap:10px';
const text = document.createElement('div');
text.style.cssText = 'flex:1;font-size:14px;line-height:1.6';
text.textContent = done ? '✅ ئەپەکە نوێ کرایەوە' : '🎉 نوێکردنەوەیەکی تازە ئامادەیە';
if (notes) {
const n = document.createElement('div');
n.style.cssText = 'font-size:12px;opacity:.9';
n.textContent = notes;
text.appendChild(n);
}
const go = document.createElement('button');
go.textContent = 'نوێکردنەوە';
go.style.cssText = 'background:#fff;color:#15803d;border:0;border-radius:10px;padding:8px 14px;font:inherit;font-weight:700;font-size:14px;cursor:pointer';
go.onclick = () => location.reload();
const close = document.createElement('button');
close.textContent = '✕';
close.setAttribute('aria-label', 'داخستن');
close.style.cssText = 'background:transparent;color:#fff;border:0;font-size:18px;padding:4px 6px;cursor:pointer;opacity:.85';
close.onclick = () => bar.remove();
if (done) {
bar.append(text, close);
setTimeout(() => bar.remove(), 10000); // "updated" note goes away by itself
} else {
bar.append(text, go, close);
}
document.body.appendChild(bar);
}
setTimeout(announceIfUpdated, 2500);
setTimeout(check, 5000);
setInterval(check, 10 * 60 * 1000);
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') check(); });
})();
// Complete Kurdish Number, Date, Time, and Calendar Normalizer for Natural Fluent Speech
const KURDISH_ONES = {
0: 'سفر', 1: 'یەک', 2: 'دوو', 3: 'سێ', 4: 'چوار', 5: 'پێنج',
6: 'شەش', 7: 'حەوت', 8: 'هەشت', 9: 'نۆ', 10: 'دە',
11: 'یازدە', 12: 'دوازدە', 13: 'سێزدە', 14: 'چواردە', 15: 'پازدە',
16: 'شازدە', 17: 'حەڤدە', 18: 'هەژدە', 19: 'نۆزدە'
};
const KURDISH_TENS = {
20: 'بیست', 30: 'سی', 40: 'چل', 50: 'پەنجا',
60: 'شەست', 70: 'حەفتا', 80: 'هەشتا', 90: 'نەوەد'
};
const KURDISH_HUNDREDS = {
100: 'سەد', 200: 'دووسەد', 300: 'سێسەد', 400: 'چوارسەد',
500: 'پێنجسەد', 600: 'شەشسەد', 700: 'حەوتسەد', 800: 'هەشتسەد', 900: 'نۆسەد'
};
const KURDISH_MONTHS_SORANI = {
1: 'کانوونی دووەم', 2: 'شوبات', 3: 'ئازار', 4: 'نیسان',
5: 'ئایار', 6: 'حوزەیران', 7: 'تەممووز', 8: 'ئاب',
9: 'ئەیلوول', 10: 'تشرینی یەکەم', 11: 'تشرینی دووەم', 12: 'کانوونی یەکەم'
};
function numberToKurdishWords(n) {
n = parseInt(n, 10);
if (isNaN(n)) return '';
if (n < 0) return 'سالب ' + numberToKurdishWords(-n);
if (KURDISH_ONES[n] !== undefined) return KURDISH_ONES[n];
if (KURDISH_TENS[n] !== undefined) return KURDISH_TENS[n];
if (KURDISH_HUNDREDS[n] !== undefined) return KURDISH_HUNDREDS[n];
if (n < 100) {
const ten = Math.floor(n / 10) * 10;
const rem = n % 10;
return KURDISH_TENS[ten] + ' و ' + KURDISH_ONES[rem];
}
if (n < 1000) {
const hun = Math.floor(n / 100) * 100;
const rem = n % 100;
return KURDISH_HUNDREDS[hun] + ' و ' + numberToKurdishWords(rem);
}
if (n < 1000000) {
const thous = Math.floor(n / 1000);
const rem = n % 1000;
const thousStr = (thous === 1) ? 'هەزار' : (numberToKurdishWords(thous) + ' هەزار');
return rem === 0 ? thousStr : (thousStr + ' و ' + numberToKurdishWords(rem));
}
if (n < 1000000000) {
const mils = Math.floor(n / 1000000);
const rem = n % 1000000;
const milStr = (mils === 1) ? 'یەک ملیۆن' : (numberToKurdishWords(mils) + ' ملیۆن');
return rem === 0 ? milStr : (milStr + ' و ' + numberToKurdishWords(rem));
}
const bils = Math.floor(n / 1000000000);
const rem = n % 1000000000;
const bilStr = (bils === 1) ? 'یەک ملیار' : (numberToKurdishWords(bils) + ' ملیار');
return rem === 0 ? bilStr : (bilStr + ' و ' + numberToKurdishWords(rem));
}
function addKurdishEzafe(word) {
if (!word) return word;
if (word.endsWith('ە')) return word.slice(0, -1) + 'ەی';
if (word.endsWith('ێ') || word.endsWith('وو') || word.endsWith('ۆ') || word.endsWith('ی')) return word + 'ی';
return word + 'ی';
}
function kurdishOrdinal(n, isMin = false) {
const word = numberToKurdishWords(n);
if (isMin) return kurdishOrdinal(n, false) + 'ین';
if (word.endsWith('ە')) return word.slice(0, -1) + 'ەیەم';
if (word.endsWith('ێ') || word.endsWith('ی')) return word + 'یەم';
if (word.endsWith('وو')) return word + 'ەم';
return word + 'ەم';
}
function addKurdishCopula(word) {
if (!word) return word;
if (word.endsWith('ە') || word.endsWith('ێ') || word.endsWith('ی') || word.endsWith('ۆ') || word.endsWith('ا')) {
return word + 'یە';
}
return word + 'ە';
}
function format2DigitGroup(digits) {
if (digits.length !== 2) return numberToKurdishWords(parseInt(digits, 10));
if (digits === '00') return 'دوو سفر';
if (digits.startsWith('0')) return 'سفر ' + (KURDISH_ONES[parseInt(digits[1], 10)] || digits[1]);
return numberToKurdishWords(parseInt(digits, 10));
}
function format3DigitGroup(digits) {
if (digits.length !== 3) return numberToKurdishWords(parseInt(digits, 10));
if (digits === '000') return 'سێ سفر';
if (digits.startsWith('00')) return 'دوو سفر ' + (KURDISH_ONES[parseInt(digits[2], 10)] || digits[2]);
if (digits.startsWith('0')) return 'سفر ' + format2DigitGroup(digits.slice(1));
return numberToKurdishWords(parseInt(digits, 10));
}
// Any number that starts with 0 is a phone/ID number, NEVER an amount ("077040168" must not become
// "77 million ..."). Read it in small groups the way Kurdish speakers say phone numbers:
// first 4 digits "سفر حەوتسەد و حەفتا", then 3 digits, then pairs.
function formatLeadingZeroNumber(d) {
if (d.length === 11) {
const full = formatKurdishPhoneNumber(d);
if (full) return full;
}
if (d.length === 1) return 'سفر';
if (d.length === 2) return format2DigitGroup(d);
if (d.length === 3) return format3DigitGroup(d);
const groups = [];
let rest = d;
// leading zeros beyond the first: each one is "سفر"
let lead = 'سفر';
rest = rest.slice(1);
while (rest.startsWith('0') && rest.length > 3) { lead += ' سفر'; rest = rest.slice(1); }
groups.push(lead + ' ' + format3DigitGroup(rest.slice(0, 3))); // rest has at least 3 digits here
rest = rest.slice(3);
if (rest.length > 3) { groups.push(format3DigitGroup(rest.slice(0, 3))); rest = rest.slice(3); }
while (rest.length > 0) {
if (rest.length === 3) { groups.push(format3DigitGroup(rest)); break; }
if (rest.length === 1) { groups.push(rest === '0' ? 'سفر' : (KURDISH_ONES[parseInt(rest, 10)] || rest)); break; }
groups.push(format2DigitGroup(rest.slice(0, 2)));
rest = rest.slice(2);
}
return groups.join('، ');
}
function formatKurdishPhoneNumber(cleanDigits, hasCopula = false, prefixCode = '') {
let prefWords = '';
let g1Digits = '', g2Digits = '', g3Digits = '';
if (cleanDigits.length === 11 && cleanDigits.startsWith('0')) {
const prefDigits = cleanDigits.slice(0, 4);
g1Digits = cleanDigits.slice(4, 7);
g2Digits = cleanDigits.slice(7, 9);
g3Digits = cleanDigits.slice(9, 11);
const pNum = parseInt(prefDigits.slice(1), 10);
prefWords = 'سفر ' + numberToKurdishWords(pNum);
} else if (cleanDigits.length === 10 && !cleanDigits.startsWith('0')) {
const prefDigits = cleanDigits.slice(0, 3);
g1Digits = cleanDigits.slice(3, 6);
g2Digits = cleanDigits.slice(6, 8);
g3Digits = cleanDigits.slice(8, 10);
prefWords = numberToKurdishWords(parseInt(prefDigits, 10));
} else {
return null;
}
const g1Words = format3DigitGroup(g1Digits);
const g2Words = format2DigitGroup(g2Digits);
let g3Words = format2DigitGroup(g3Digits);
if (hasCopula) {
g3Words = addKurdishCopula(g3Words);
}
const parts = [];
if (prefixCode) parts.push(prefixCode);
parts.push(prefWords, g1Words, g2Words, g3Words);
return parts.join('، ');
}
// Speech recognition often breaks phone numbers apart: "0770. 4/01. 6810" or "0770 401 68 10".
// Join every Iraqi mobile number back into plain digits (07704016810 / +9647704016810),
// so it is never mistaken for a date or a sentence end.
function joinPhoneNumbers(text) {
if (!text) return text;
const toAscii = (s) => s.replace(/[٠-٩]/g, (c) => String(c.charCodeAt(0) - 0x0660)).replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06F0));
return toAscii(text).replace(/(?<![\d])(\+?\d[\d\s.\/\-،,]{7,24}\d)(?![\d])/g, (m) => {
const digits = m.replace(/\D/g, '');
let local = digits;
let intl = '';
if (local.startsWith('00964')) { intl = '+964'; local = local.slice(5); }
else if (local.startsWith('964') && m.trim().startsWith('+') || (local.startsWith('964') && local.length === 13)) { intl = '+964'; local = local.slice(3); }
if (local.length === 10 && local.startsWith('7')) local = '0' + local;
if (!/^07[5789]\d{8}$/.test(local)) return m; // not a phone number: leave it alone
return intl ? intl + local.slice(1) : local;
});
}
function normalizeKurdishNumbers(text) {
if (!text) return '';
let s = joinPhoneNumbers(text);
// Convert Eastern Arabic / Persian numerals to ASCII
const eToA = {
'٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9',
'۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9'
};
s = s.replace(/[٠-٩۰-۹]/g, c => eToA[c] || c);
// 1. Spoken Kurdish digit words phone numbers (e.g. from literal translation "سفر حەوت حەوت سفر چوار...")
const digitWordsPattern = /(?:\b(?:سفر|یەک|دوو|سێ|چوار|پێنج|شەش|حەوت|هەشت|نۆ)\s+){9,10}(?:سفر|یەک|دوو|سێ|چوار|پێنج|شەش|حەوت|هەشت|نۆ)(?:ە|یە)?\b/g;
s = s.replace(digitWordsPattern, (fullMatch) => {
const tokens = fullMatch.trim().split(/\s+/);
let lastTok = tokens[tokens.length - 1];
let hasCopula = false;
if (lastTok.endsWith('یە')) {
hasCopula = true;
tokens[tokens.length - 1] = lastTok.slice(0, -2);
} else if (lastTok.endsWith('ە') && lastTok !== 'سێ') {
hasCopula = true;
tokens[tokens.length - 1] = lastTok.slice(0, -1);
}
const digitMap = { 'سفر': '0', 'یەک': '1', 'دوو': '2', 'سێ': '3', 'چوار': '4', 'پێنج': '5', 'شەش': '6', 'حەوت': '7', 'هەشت': '8', 'نۆ': '9' };
let digits = '';
for (const t of tokens) {
if (digitMap[t] !== undefined) {
digits += digitMap[t];
} else {
return fullMatch;
}
}
const res = formatKurdishPhoneNumber(digits, hasCopula);
return res ? (' ' + res + ' ') : fullMatch;
});
// 2. Raw digit phone numbers (e.g. 07704016810, 0750 123 45 67, +964 770 401 6810)
const rawPhonePattern = /(?<!\d)(?:\+964|00964)?[\s-]*([0]?[7][5789]\d)(?:[\s-]*\d){7}(?:ە|یە)?\b/g;
s = s.replace(rawPhonePattern, (fullMatch) => {
const hasCopula = fullMatch.endsWith('ە') || fullMatch.endsWith('یە');
let rawDigits = fullMatch.replace(/\D/g, '');
let prefixCode = '';
if (rawDigits.startsWith('964')) {
prefixCode = 'پڵەس نۆسەد و شەست و چوار';
rawDigits = rawDigits.slice(3);
} else if (rawDigits.startsWith('00964')) {
prefixCode = 'سفر سفر نۆسەد و شەست و چوار';
rawDigits = rawDigits.slice(5);
}
if (rawDigits.length === 10 && !rawDigits.startsWith('0')) {
rawDigits = '0' + rawDigits;
}
const res = formatKurdishPhoneNumber(rawDigits, hasCopula, prefixCode);
return res ? (' ' + res + ' ') : fullMatch;
});
// Commas in numbers e.g. 1,000,000 -> 1000000
s = s.replace(/(?<=\d),(?=\d{3}\b)/g, '');
// Dates: YYYY/MM/DD or YYYY-MM-DD
s = s.replace(/\b(19\d\d|20\d\d)[/-](0?[1-9]|1[0-2])[/-](0?[1-9]|[12]\d|3[01])(ە|دا|ەوە)?\b/g, (m, y, mn, d, suf) => {
const dWords = addKurdishEzafe(numberToKurdishWords(parseInt(d, 10)));
const mName = KURDISH_MONTHS_SORANI[parseInt(mn, 10)] || numberToKurdishWords(parseInt(mn, 10));
const mWords = addKurdishEzafe(mName);
const yWords = numberToKurdishWords(parseInt(y, 10));
return dWords + ' ' + mWords + ' ' + yWords + (suf || '');
});
// Dates: DD/MM/YYYY or DD-MM-YYYY
s = s.replace(/\b(0?[1-9]|[12]\d|3[01])[/-](0?[1-9]|1[0-2])[/-](19\d\d|20\d\d)(ە|دا|ەوە)?\b/g, (m, d, mn, y, suf) => {
const dWords = addKurdishEzafe(numberToKurdishWords(parseInt(d, 10)));
const mName = KURDISH_MONTHS_SORANI[parseInt(mn, 10)] || numberToKurdishWords(parseInt(mn, 10));
const mWords = addKurdishEzafe(mName);
const yWords = numberToKurdishWords(parseInt(y, 10));
return dWords + ' ' + mWords + ' ' + yWords + (suf || '');
});
// Short Dates: DD/MM (like 15/05 or 15/5)
s = s.replace(/\b(0?[1-9]|[12]\d|3[01])[/](0?[1-9]|1[0-2])\b/g, (m, d, mn) => {
const mName = KURDISH_MONTHS_SORANI[parseInt(mn, 10)];
if (mName) {
const dWords = addKurdishEzafe(numberToKurdishWords(parseInt(d, 10)));
return dWords + ' ' + mName;
}
return m;
});
// Times: HH:MM
s = s.replace(/\b([01]?\d|2[0-3]):([0-5]\d)\b/g, (m, h, mn) => {
const hNum = parseInt(h, 10);
const mNum = parseInt(mn, 10);
const hWords = numberToKurdishWords(hNum);
if (mNum === 0) return 'کاتژمێر ' + hWords;
if (mNum === 30) return hWords + ' و نیو';
if (mNum === 15) return hWords + ' و چارەک';
return hWords + ' و ' + numberToKurdishWords(mNum) + ' خولەک';
});
// Percentages: 50% or %50
s = s.replace(/(\d+(?:\.\d+)?)\s*[%٪]/g, '$1 لە سەد');
s = s.replace(/[%٪]\s*(\d+(?:\.\d+)?)/g, '$1 لە سەد');
// Currencies
s = s.replace(/\$\s*(\d+(?:\.\d+)?)/g, '$1 دۆلار');
s = s.replace(/(\d+(?:\.\d+)?)\s*\$/g, '$1 دۆلار');
s = s.replace(/€\s*(\d+(?:\.\d+)?)/g, '$1 یۆرۆ');
s = s.replace(/(\d+(?:\.\d+)?)\s*€/g, '$1 یۆرۆ');
// Years with calendar symbols: 2024ز or 1445ک
s = s.replace(/\b(\d{3,4})\s*[ز]\b/g, (m, y) => addKurdishEzafe(numberToKurdishWords(parseInt(y, 10))) + ' زایینی');
s = s.replace(/\b(\d{3,4})\s*[كک]\b/g, (m, y) => addKurdishEzafe(numberToKurdishWords(parseInt(y, 10))) + ' کۆچی');
// Ordinals: 1ەم, 2یەم, 1ەمین
s = s.replace(/\b(\d+)\s*ەمین\b/g, (m, n) => kurdishOrdinal(n, true));
s = s.replace(/\b(\d+)\s*یەمین\b/g, (m, n) => kurdishOrdinal(n, true));
s = s.replace(/\b(\d+)\s*(?:ەم|یەم)\b/g, (m, n) => kurdishOrdinal(n, false));
// Numbers starting with 0 (phone / ID numbers, also incomplete ones): groups, never millions
s = s.replace(/(?<![\d.,])(0\d+)(?![\d.,]\d)(یە|ە)?/g, (m, num, suf) => {
const words = formatLeadingZeroNumber(num);
return ' ' + (suf ? addKurdishCopula(words) : words) + ' ';
});
// Number ranges: 5-10
s = s.replace(/\b(\d+)\s*[-–—]\s*(\d+)\b/g, (m, a, b) => numberToKurdishWords(parseInt(a, 10)) + ' بۆ ' + numberToKurdishWords(parseInt(b, 10)));
// Decimals: 3.5 -> سێ و نیو
s = s.replace(/\b(\d+)\.(\d+)\b/g, (m, wh, fr) => {
const whW = numberToKurdishWords(parseInt(wh, 10));
if (fr === '5') return (wh === '0') ? 'نیو' : (whW + ' و نیو');
return whW + ' پۆینت ' + numberToKurdishWords(parseInt(fr, 10));
});
// Numbers with Kurdish suffixes: 2024ە, 15ی, 1995دا, 1988ەوە, 10یان, 5مان
s = s.replace(/\b(\d+)(ە|ی|دا|وە|ەوە|یان|مان|تان)\b/g, (m, num, suf) => {
const word = numberToKurdishWords(parseInt(num, 10));
if (suf === 'ی') return addKurdishEzafe(word);
if (['ە', 'دا', 'وە', 'ەوە'].includes(suf)) return word + suf;
return word + ' ' + suf;
});
// Standalone numbers
s = s.replace(/\b\d+\b/g, m => numberToKurdishWords(parseInt(m, 10)));
return s.replace(/\s+/g, ' ').replace(/\s+([.,!?;:،؟])/g, '$1').trim();
}
function fixKurdishSoraniGreetings(text) {
if (!text) return text;
let s = text;
try {
s = normalizeKurdishNumbers(s);
const kurdishReplacements = [
[/(?<![\p{L}\p{N}])برای\s+من(?![\p{L}\p{N}])/gu, 'برام'],
[/(?<![\p{L}\p{N}])براکەی\s+من(?![\p{L}\p{N}])/gu, 'براکەم'],
[/(?<![\p{L}\p{N}])خوشکی\s+من(?![\p{L}\p{N}])/gu, 'خوشکم'],
[/(?<![\p{L}\p{N}])خوشکەکەی\s+من(?![\p{L}\p{N}])/gu, 'خوشکەکەم'],
[/(?<![\p{L}\p{N}])هاو[ڕر]ێی\s+من(?![\p{L}\p{N}])/gu, 'هاوڕێکەم'],
[/(?<![\p{L}\p{N}])هاو[ڕر]ێکەی\s+من(?![\p{L}\p{N}])/gu, 'هاوڕێکەم'],
[/(?<![\p{L}\p{N}])دایکی\s+من(?![\p{L}\p{N}])/gu, 'دایکم'],
[/(?<![\p{L}\p{N}])باوکی\s+من(?![\p{L}\p{N}])/gu, 'باوکم'],
[/(?<![\p{L}\p{N}])ماڵی\s+من(?![\p{L}\p{N}])/gu, 'ماڵم'],
[/(?<![\p{L}\p{N}])ماڵەکەی\s+من(?![\p{L}\p{N}])/gu, 'ماڵەکەم'],
[/(?<![\p{L}\p{N}])ناوی\s+من(?![\p{L}\p{N}])/gu, 'ناوم'],
[/(?<![\p{L}\p{N}])کاری\s+من(?![\p{L}\p{N}])/gu, 'کارم'],
[/(?<![\p{L}\p{N}])کتێبی\s+من(?![\p{L}\p{N}])/gu, 'کتێبەکەم'],
[/(?<![\p{L}\p{N}])تۆ\s+چۆنیت(?![\p{L}\p{N}])/gu, 'چۆنیت'],
[/(?<![\p{L}\p{N}])سلاڤ(?![\p{L}\p{N}])/gu, 'سڵاو'],
[/(?<![\p{L}\p{N}])سلاڤان(?![\p{L}\p{N}])/gu, 'سڵاوان'],
[/(?<![\p{L}\p{N}])سلاو(?![\p{L}\p{N}])/gu, 'سڵاو'],
[/\b[sS]ilav\b/g, 'سڵاو'],
[/\b[sS]lav\b/g, 'سڵاو'],
[/\b[sS]law\b/g, 'سڵاو']
];
for (let i = 0; i < kurdishReplacements.length; i++) {
s = s.replace(kurdishReplacements[i][0], kurdishReplacements[i][1]);
}
} catch (_) {
s = s.replace(/برای من/g, 'برام')
.replace(/براکەی من/g, 'براکەم')
.replace(/خوشکی من/g, 'خوشکم')
.replace(/سلاڤ/g, 'سڵاو')
.replace(/سلاو/g, 'سڵاو');
}
return s;
}
// The shared Gemini key lives only on the server (.gemini_key file), never in browser code.
// Users can still paste their own key in Settings; it stays in their own browser.
const DEFAULT_GEMINI_API_KEY = '';
const DEFAULT_GEMINI_MODEL = 'gemini-3.1-flash-lite';
const OLD_LEAKED_KEY_PREFIX = 'AQ.Ab8RN6JIQqoYf8';
function getInitialApiKey() {
let stored = '';
try { stored = (localStorage.getItem('translet_gemini_api_key') || '').trim(); } catch (e) {}
if (stored.startsWith(OLD_LEAKED_KEY_PREFIX)) {
// Remove the old built-in key that earlier versions saved in every visitor's browser
try { localStorage.removeItem('translet_gemini_api_key'); } catch (e) {}
return '';
}
return stored.length > 10 ? stored : '';
}
function getInitialModel() {
const model = DEFAULT_GEMINI_MODEL || 'gemini-3.1-flash-lite';
try { localStorage.setItem('translet_gemini_model', model); } catch(e) {}
return model;
}
// State Management
const state = {
apiKey: getInitialApiKey(),
model: getInitialModel(),
currentTone: 'natural',
kurdishScript: 'arabic',
history: JSON.parse(localStorage.getItem('translet_history') || '[]'),
isTranslating: false,
};
// Language mapping and names
const languages = {
auto: { name: 'دۆزینەوەی خۆکار', englishName: 'Auto Detect', gCode: 'auto' },
ku: { name: 'کوردی (سۆرانی)', englishName: 'Kurdish (Sorani)', gCode: 'ckb' },
en: { name: 'ئینگلیزی', englishName: 'English', gCode: 'en' },
ar: { name: 'عەرەبی', englishName: 'Arabic', gCode: 'ar' },
tr: { name: 'تورکی', englishName: 'Turkish', gCode: 'tr' },
fa: { name: 'فارسی', englishName: 'Persian', gCode: 'fa' },
de: { name: 'ئەڵمانی', englishName: 'German', gCode: 'de' },
fr: { name: 'فەڕەنسی', englishName: 'French', gCode: 'fr' },
es: { name: 'ئیسپانی', englishName: 'Spanish', gCode: 'es' },
};
// DOM Elements
const sourceTextEl = document.getElementById('sourceText');
const targetTextEl = document.getElementById('targetText');
const sourceLangEl = document.getElementById('sourceLang');
const targetLangEl = document.getElementById('targetLang');
const swapLanguagesBtn = document.getElementById('swapLanguagesBtn');
const translateActionBtn = document.getElementById('translateActionBtn');
const clearSourceBtn = document.getElementById('clearSourceBtn');
const copySourceBtn = document.getElementById('copySourceBtn');
const copyTargetBtn = document.getElementById('copyTargetBtn');
const speakSourceBtn = document.getElementById('speakSourceBtn');
const speakTargetBtn = document.getElementById('speakTargetBtn');
const kurdishTransliterateBtn = document.getElementById('kurdishTransliterateBtn');
const toggleKurdishLatinBtn = document.getElementById('toggleKurdishLatinBtn');
const scriptBadgeText = document.getElementById('scriptBadgeText');
const charCountEl = document.getElementById('charCount');
const targetStatusMessage = document.getElementById('targetStatusMessage');
const targetLoadingOverlay = document.getElementById('targetLoadingOverlay');
const engineBadgeText = document.getElementById('engineBadgeText');
const aiModeStatusText = document.getElementById('aiModeStatusText');
// Explanation elements
const explanationCard = document.getElementById('explanationCard');
const explanationContent = document.getElementById('explanationContent');
const showExplanationBtn = document.getElementById('showExplanationBtn');
const closeExplanationBtn = document.getElementById('closeExplanationBtn');
// History elements
const historyList = document.getElementById('historyList');
const clearHistoryBtn = document.getElementById('clearHistoryBtn');
// Settings Modal elements
const settingsModal = document.getElementById('settingsModal');
const openSettingsBtn = document.getElementById('openSettingsBtn');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const geminiApiKeyInput = document.getElementById('geminiApiKeyInput');
const geminiModelSelect = document.getElementById('geminiModelSelect');
const saveApiKeyBtn = document.getElementById('saveApiKeyBtn');
const testApiKeyBtn = document.getElementById('testApiKeyBtn');
const apiTestResult = document.getElementById('apiTestResult');
// Toast
const toastNotification = document.getElementById('toastNotification');
const toastMessage = document.getElementById('toastMessage');
const toastIcon = document.getElementById('toastIcon');
// Sound synthesis context for subtle feedback
function playSubtleClick() {
try {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(580, audioCtx.currentTime);
osc.frequency.exponentialRampToValueAtTime(840, audioCtx.currentTime + 0.08);
gain.gain.setValueAtTime(0.04, audioCtx.currentTime);
gain.gain.linearRampToValueAtTime(0.001, audioCtx.currentTime + 0.08);
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + 0.08);
} catch (e) {
// Ignore audio errors
}
}
// Initialize Application
function initApp() {
updateEngineStatus();
renderHistory();
setupEventListeners();
updateTextDirection(sourceTextEl, sourceLangEl.value);
updateTextDirection(targetTextEl, targetLangEl.value);
initVoiceVcSystem();
// The Kurdish voice is NOT prepared at start any more: preparing it froze phones for seconds
// right after opening. It is prepared when the voice screen is opened, or on the first Kurdish speech.
}
// Prepare voice, then ear, one after the other (both at once froze phones), when the phone is idle
let _voiceWarmupStarted = false;
function warmUpVoiceAndEar() {
if (_voiceWarmupStarted) return;
_voiceWarmupStarted = true;
const idle = (fn) => (window.requestIdleCallback ? requestIdleCallback(fn, { timeout: 4000 }) : setTimeout(fn, 300));
setTimeout(() => idle(async () => {
try { await startLalaVoice(); } catch (_) {}
idle(() => { try { startLalaEar(); } catch (_) {} });
}), 1200);
}
// Update API Status & Badges
function updateEngineStatus() {
if (state.apiKey && state.apiKey.trim().length > 10) {
engineBadgeText.textContent = `Gemini AI (${state.model})`;
aiModeStatusText.textContent = 'Gemini AI چالاکە';
openSettingsBtn.classList.remove('secondary');
openSettingsBtn.classList.add('primary');
} else {
engineBadgeText.textContent = 'Lala Translate Engine';
aiModeStatusText.textContent = 'بەستنەوە بە Gemini AI';
}
}
// Comprehensive Kurdish <-> English / Multilingual Built-in Lexicon
const kurdishDictionary = {
// Kurdish (Latin and Arabic) -> English
kuToEn: {
'slaw': 'Hello / Hi',
'slaaw': 'Hello',
'slau': 'Hello',
'سڵاو': 'Hello / Hi',
'سلاو': 'Hello / Hi',
'choni': 'How are you?',
'çoni': 'How are you?',
'chony': 'How are you?',
'چۆنی': 'How are you?',
'چۆنن': 'How are you all?',
'bashm': 'I am fine / I am good',
'bashim': 'I am fine',
'باشم': 'I am fine',
'bashit': 'Are you well?',
'باشیت': 'Are you well?',
'basha': 'Good / Okay',
'باشە': 'Good / Okay',
'choni bashit': 'How are you, are you doing well?',
'slaw choni': 'Hello, how are you?',
'سڵاو چۆنی': 'Hello, how are you?',
'سڵاو چۆنی باشیت': 'Hello, how are you, are you doing well?',
'supas': 'Thank you',
'spas': 'Thank you',
'swpas': 'Thank you',
'سوپاس': 'Thank you',
'zor supas': 'Thank you very much',
'زۆر سوپاس': 'Thank you very much',
'dast xosh': 'Well done / Thank you',
'dastxosh': 'Well done / Thank you',
'دەست خۆش': 'Well done / Thank you',
'sarchaw': 'You are welcome / With pleasure',
'sar chaw': 'You are welcome / With pleasure',
'سەرچاو': 'You are welcome / With pleasure',
'bale': 'Yes',
'balê': 'Yes',
'بەڵێ': 'Yes',
'na': 'No',
'naxer': 'No',
'naxêr': 'No',
'نەخێر': 'No',
'beyani bash': 'Good morning',
'bayani bash': 'Good morning',
'بەیانی باش': 'Good morning',
'ewara bash': 'Good evening',
'êwara bash': 'Good evening',
'ئێوارە باش': 'Good evening',
'shaw shad': 'Good night',
'شەو شاد': 'Good night',
'xwa hafiz': 'Goodbye',
'xwat lagal': 'Goodbye',
'خوا حافیز': 'Goodbye',
'خوات لەگەڵ': 'Goodbye',
'damawet': 'I want',
'damawêt': 'I want',
'دەمەوێت': 'I want',
'natwanm': 'I cannot',
'ناتوانم': 'I cannot',
'datwanm': 'I can',
'دەتوانم': 'I can',
'dallem': 'I say',
'دەڵێم': 'I say',
'abe': 'It must / It should',
'دەبێت': 'It must / It should',
'chak': 'Good / Fixed / Repaired',
'چاک': 'Good / Fixed / Repaired',
'bkre': 'Be done / Be made',
'بکرێت': 'Be done / Be made',
'werana': 'It is ruined / broken',
'وێرانە': 'It is ruined / broken',
'har zor werana': 'It is really completely broken',
'هەر زۆر وێرانە': 'It is really completely broken',
'kurd': 'Kurd',
'کورد': 'Kurd',
'kurdistan': 'Kurdistan',
'کوردستان': 'Kurdistan',
'zman': 'Language',
'زمان': 'Language',
'xoshawisti': 'Love',
'خۆشەویستی': 'Love',
'xoshm dawey': 'I love you',
'خۆشم دەوێیت': 'I love you',
'nawit chya': 'What is your name?',
'ناوت چییە': 'What is your name?',
'mn': 'I / Me',
'من': 'I / Me',
'to': 'You',
'تۆ': 'You',
'ema': 'We / Us',
'ئێمە': 'We / Us',
'ewa': 'You (plural)',
'ئێوە': 'You (plural)',
'awan': 'They / Them',
'ئەوان': 'They / Them',
'bo': 'For / To / Why',
'بۆ': 'For / To / Why',
'bochi': 'Why',
'بۆچی': 'Why',
'kwe': 'Where',
'کوێ': 'Where',
'key': 'When',
'کەی': 'When',
'chya': 'What is it',
'چییە': 'What is it'
},
// English -> Kurdish (Sorani) - Natural, Fluent & Idiomatic
enToKu: {
// Greetings & Social
'hello': 'سڵاو',
'hi': 'سڵاو',
'hey': 'سڵاو',
'greetings': 'سڵاو و ڕێز',
'how are you': 'چۆنی؟',
'how are you?': 'چۆنی؟ تەندروستیت چۆنە؟',
'how are you doing': 'چۆنی؟ بارودۆخت چۆنە؟',
'how are you doing?': 'چۆنی؟ بارودۆخت چۆنە؟',
'how is it going': 'چۆن دەڕوات؟ هەموو شتێک باشە؟',
'how is everything': 'هەموو شتێک چۆنە؟',
'i am fine': 'باشم، سوپاس',
'i am fine thank you': 'باشم، زۆر سوپاس',
'im fine': 'باشم',
'i am good': 'باشم',
'im good': 'باشم',
'i am doing well': 'لە دۆخێکی باشدام، سوپاس',
'thank you': 'سوپاس',
'thanks': 'سوپاس',
'thank you very much': 'زۆر سوپاس',
'thanks a lot': 'زۆر سوپاس',
'thank you so much': 'زۆر زۆر سوپاس',
'i appreciate it': 'سوپاس و پێزانینم هەیە',
'good morning': 'بەیانی باش',
'good afternoon': 'دواینیوەڕۆ باش',
'good evening': 'ئێوارە باش',
'good night': 'شەو شاد',
'welcome': 'بەخێربێیت',
'welcome to kurdistan': 'بەخێربێن بۆ کوردستان',
'you are welcome': 'سەرچاو / شایەنی نییە',
'youre welcome': 'سەرچاو / شایەنی نییە',
'yes': 'بەڵێ',
'no': 'نەخێر',
'goodbye': 'خوات لەگەڵ',
'bye': 'خوات لەگەڵ / بای',
'see you': 'دەتبینمەوە',
'see you soon': 'بەزوویی دەتبینمەوە',
'see you later': 'دواتر دەتبینمەوە',
'see you tomorrow': 'سبەی دەتبینمەوە',
'take care': 'ئاگات لە خۆت بێت',
'take care of yourself': 'ئاگات لە خۆت بێت',
'have a nice day': 'ڕۆژێکی خۆشت هەبێت',
'have a great day': 'ڕۆژێکی زۆر خۆشت هەبێت',
'have a good time': 'کاتێکی خۆشت هەبێت',
'nice to meet you': 'خۆشحاڵم بە ناسینت',
'pleasure to meet you': 'شانازییە بە ناسینت',
'congratulations': 'پیرۆزە',
'happy birthday': 'ڕۆژی لەدایکبوونت پیرۆز بێت',
'good luck': 'بەختی باش / هیوای سەرکەوتن',
'best wishes': 'بە هیوای باشترین بۆت',
// Questions & Common Needs
'what is your name': 'ناوت چییە؟',
'what is your name?': 'ناوت چییە؟',
'my name is': 'ناوم ...ە',
'where are you': 'لە کوێیت؟',
'where are you from': 'خەڵکی کوێیت؟',
'where do you live': 'لەکوێ دەژیت؟',
'how old are you': 'تەمەنت چەندە؟',
'what are you doing': 'چی دەکەیت؟',
'what are you thinking about': 'بیر لە چی دەکەیتەوە؟',
'what happened': 'چی ڕوویدا؟',
'what do you mean': 'مەبەستت چییە؟',
'what time is it': 'کاتژمێر چەندە؟',
'how much is this': 'نرخی ئەمە چەندە؟',
'where is the bathroom': 'تەوالێت لە کوێیە؟',
'can you help me': 'دەتوانیت یارمەتیم بدەیت؟',
'can i help you': 'دەتوانم یارمەتیت بدەم؟',
'i need help': 'پێویستم بە هاوکارییە',
'please': 'تکایە',
'sorry': 'ببورە',
'excuse me': 'ببورە',
'no problem': 'کێشە نییە',
'dont worry': 'نیگەران مەبە',
'do not worry': 'نیگەران مەبە',
'of course': 'بێگومان',
'definitely': 'بە دڵنیاییەوە',
'it doesnt matter': 'گرنگ نییە / کێشە نییە',
// Tech, AI & Science
'artificial intelligence': 'ژیریی دەستکرد',
'artificial intelligence is transforming modern life': 'ژیریی دەستکرد ژیانی هاوچەرخ دەگۆڕێت',
'artificial intelligence is transforming the world': 'ژیریی دەستکرد جیهان دەگۆڕێت',
'ai is the future': 'ژیریی دەستکرد داهاتووە',
'machine learning': 'فێربوونی ئامێر',
'deep learning': 'فێربوونی قووڵ',
'data science': 'زانستی داتا',
'computer science': 'زانستی کۆمپیوتەر',
'software development': 'گەشەپێدانی نەرمەکاڵا',
'programming language': 'زمانی پرۆگرامسازی',
'natural language processing': 'پرۆسێسکردنی زمانی سروشتی',
'neural network': 'تۆڕی دەماری دەستکرد',
'technology is changing the world': 'تەکنەلۆژیا جیهان دەگۆڕێت',
// Expressions, Work & Life
'i love you': 'خۆشم دەوێیت',
'i love you so much': 'زۆرم خۆشدەوێیت',
'i miss you': 'بیرت دەکەم',
'i want': 'دەمەوێت',
'i need': 'پێویستم پێیەتی',
'i think': 'پێموایە',
'i agree': 'هاوڕام',
'i agree with you': 'هاوڕام لەگەڵت',
'i understand': 'تێدەگەم',
'i don\'t understand': 'تێنەگەیشتم',
'i dont understand': 'تێنەگەیشتم',
'i know': 'دەزانم',
'i don\'t know': 'نازانم',
'i dont know': 'نازانم',
'i am learning': 'فێردەبم',
'i am working': 'کاردەکەم',
'i am tired': 'ماندووم',
'i am happy': 'دڵخۆشم',
'i am busy': 'سەرقاڵم',
'never give up': 'هەرگیز کۆڵ مەدە',
'step by step': 'هەنگاو بە هەنگاو',
'as soon as possible': 'لە زووترین کاتدا',
'by the way': 'لەم نێوەندەدا / بە بۆنەیەوە',
'in my opinion': 'بە بڕوای من',
'to be honest': 'بۆ ئەوەی ڕاستگۆ بم',
'knowledge is power': 'زانست هێزە',
'everything will be fine': 'هەموو شتێک باش دەبێت',
'be patient': 'ئارامگر بە',
'it is broken': 'تێکچووە / وێرانە',
'it needs to be fixed': 'دەبێت چاکبکرێت'
}
};
// Word-level Kurdish Latin to Sorani replacement dictionary
const kurdishWordMap = {
'slaw': 'سڵاو', 'slaaw': 'سڵاو', 'slau': 'سڵاو',
'choni': 'چۆنی', 'chony': 'چۆنی', 'çoni': 'چۆنی',
'bashm': 'باشم', 'bashim': 'باشم', 'bashit': 'باشیت', 'basha': 'باشە',
'spas': 'سوپاس', 'supas': 'سوپاس', 'swpas': 'سوپاس',
'dast': 'دەست', 'xosh': 'خۆش', 'dastxosh': 'دەستخۆش',
'sarchaw': 'سەرچاو',
'bale': 'بەڵێ', 'balê': 'بەڵێ', 'na': 'نە', 'naxer': 'نەخێر', 'naxêr': 'نەخێر',
'beyani': 'بەیانی', 'bayani': 'بەیانی',
'ewara': 'ئێوارە', 'êwara': 'ئێوارە',
'shaw': 'شەو', 'shad': 'شاد',
'damawet': 'دەمەوێت', 'damawêt': 'دەمەوێت',
'dallem': 'دەڵێم', 'dallêm': 'دەڵێم',
'natwanm': 'ناتوانم', 'datwanm': 'دەتوانم',
'abe': 'دەبێت', 'abê': 'دەبێت',
'chak': 'چاک', 'bkre': 'بکرێت', 'bkrêt': 'بکرێت', 'bkayn': 'بکەین',
'werana': 'وێرانە', 'wêrana': 'وێرانە',
'har': 'هەر', 'zor': 'زۆر',
'walla': 'وەڵڵا', 'walah': 'وەڵڵا',
'yani': 'واتە',
'kesha': 'کێشە', 'kêsha': 'کێشە',
'tyaya': 'تیایە',
'ba': 'بە', 'halla': 'هەڵە', 'hala': 'هەڵە',
'ware': 'وەر', 'dageret': 'دەگرێت', 'ageret': 'دەگرێت',
'chon': 'چۆن', 'charasare': 'چارەسەری', 'aw': 'ئەو',
'mn': 'من', 'to': 'تۆ', 'ema': 'ئێمە', 'ewa': 'ئێوە', 'awan': 'ئەوان',
'bo': 'بۆ', 'bochi': 'بۆچی', 'kwe': 'کوێ', 'key': 'کەی', 'chya': 'چییە',
'dwkani': 'دووکانی', 'dwkan': 'دووکان',
'online': 'ئۆنلاین',
'chy': 'چی', 'chi': 'چی',
'shteka': 'شتێکە', 'shtek': 'شتێک', 'shte': 'شتێ',
'yani': 'یانی',
'chaneke': 'چەندێکی', 'chandeke': 'چەندێکی', 'chand': 'چەند',
'pewesa': 'پێویستە', 'peweste': 'پێویستە', 'pewiste': 'پێویستە', 'pewist': 'پێویست',
'wa': 'وە',
'dahate': 'داهاتی', 'dahat': 'داهات',
'chona': 'چۆنە', 'chone': 'چۆنە',
'bzanm': 'بزانم', 'dazanm': 'دەزانم',
'dlm': 'دڵم', 'xom': 'خۆم', 'hast': 'هەست',
'hasty': 'هەستی', 'xot': 'خۆت',
'wata': 'واتە', 'chuna': 'چونکە', 'chwnka': 'چونکە',
'bash': 'باش', 'nya': 'نییە', 'nyea': 'نییە',
'amro': 'ئەمڕۆ', 'emro': 'ئەمڕۆ', 'dwene': 'دوێنێ', 'dwenê': 'دوێنێ',
'roshtm': 'ڕۆشتم', 'chum': 'چووم', 'hatm': 'هاتم',
'bazar': 'بازاڕ', 'bazaar': 'بازاڕ',
'lawe': 'لەوێ', 'lawê': 'لەوێ', 'lera': 'لێرە', 'lêra': 'لێرە',
'shtm': 'شتم', 'sht': 'شت',
'kre': 'کڕی', 'krê': 'کڕی', 'krim': 'کڕیم'
};
// Kurdish Latin <-> Arabic Script Transliteration Engine
const kurdishTransliteration = {
// Convert any Latin Kurdish phrase to Sorani Arabic
toArabic: (text) => {
if (!text) return '';
// First, process known words
let words = text.split(/\s+/);
let convertedWords = words.map(w => {
// Strip punctuation
const clean = w.toLowerCase().replace(/[.,!?;:()[\]{}]/g, '');
const punctuationSuffix = w.slice(clean.length);
if (kurdishWordMap[clean]) {
return kurdishWordMap[clean] + punctuationSuffix;
}
// Fallback character-level transliteration
let s = clean;
const map = [
[/sh/gi, 'ش'], [/ch/gi, 'چ'], [/zh/gi, 'ژ'], [/kh/gi, 'خ'],
[/gh/gi, 'غ'], [/rr/gi, 'ڕ'], [/ll/gi, 'ڵ'],
[/ş/gi, 'ش'], [/ç/gi, 'چ'], [/j/gi, 'ژ'], [/x/gi, 'خ'],
[/ê/gi, 'ێ'], [/î/gi, 'ی'], [/û/gi, 'وو'], [/é/gi, 'ێ'],
[/a/gi, 'ا'], [/b/gi, 'ب'], [/c/gi, 'ج'], [/d/gi, 'د'],
[/e/gi, 'ە'], [/f/gi, 'ف'], [/g/gi, 'گ'], [/h/gi, 'ه'],
[/i/gi, 'ی'], [/k/gi, 'ک'], [/l/gi, 'ل'], [/m/gi, 'م'],
[/n/gi, 'ن'], [/o/gi, 'ۆ'], [/p/gi, 'پ'], [/q/gi, 'ق'],
[/r/gi, 'ر'], [/s/gi, 'س'], [/t/gi, 'ت'], [/u/gi, 'و'],
[/v/gi, 'ڤ'], [/w/gi, 'و'], [/y/gi, 'ی'], [/z/gi, 'ز']
];
for (const [re, rep] of map) {
s = s.replace(re, rep);
}
return s + punctuationSuffix;
});
return convertedWords.join(' ');
},
// Arabic Kurdish to Latin Hawar alphabet
toLatin: (text) => {
let s = text;
const map = [
[/وو/g, 'û'], [/و/g, 'u'], [/ۆ/g, 'o'], [/ێ/g, 'ê'],
[/ی/g, 'î'], [/ە/g, 'e'], [/ا/g, 'a'],
[/ب/g, 'b'], [/پ/g, 'p'], [/ت/g, 't'], [/ج/g, 'c'],
[/چ/g, 'ç'], [/ح/g, 'h'], [/خ/g, 'x'], [/د/g, 'd'],
[/ر/g, 'r'], [/ڕ/g, 'rr'], [/ز/g, 'z'], [/ژ/g, 'j'],
[/س/g, 's'], [/ش/g, 'ş'], [/ع/g, "'"], [/غ/g, 'ẍ'],
[/ف/g, 'f'], [/ڤ/g, 'v'], [/ق/g, 'q'], [/ک/g, 'k'],
[/گ/g, 'g'], [/ل/g, 'l'], [/ڵ/g, 'll'], [/م/g, 'm'],
[/ن/g, 'n'], [/ه/g, 'h']
];
for (const [re, rep] of map) {
s = s.replace(re, rep);
}
return s;
}
};
// Check if string is predominantly Kurdish Latin or English
function isLatinText(str) {
const latinChars = (str.match(/[a-zA-Zçşêîûéöä]/g) || []).length;
const arabicChars = (str.match(/[\u0600-\u06FF]/g) || []).length;
return latinChars > arabicChars;
}
// Direction handler
function updateTextDirection(el, lang) {
if (lang === 'ku' || lang === 'ar' || lang === 'fa') {
el.dir = 'rtl';
el.style.textAlign = 'right';
} else if (lang === 'auto') {
el.dir = isLatinText(el.value) ? 'ltr' : 'rtl';
el.style.textAlign = el.dir === 'rtl' ? 'right' : 'left';
} else {
el.dir = 'ltr';
el.style.textAlign = 'left';
}
}
// Toast Notification with SVG Icons
function showToast(msg, icon = 'sparkle') {
toastMessage.textContent = msg;
const svgMap = {
'✅': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>',
'success': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>',
'❌': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',
'error': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',
'📋': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>',
'🔊': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg>',
'🔄': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>',
'🔤': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><path d="M4 20h16"></path><path d="M4 14l4-8 4 8"></path><path d="M6 14h4"></path><path d="M15 10a3 3 0 1 0 0 6h3v-6a3 3 0 0 0-3 0z"></path></svg>',
'🗑️': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>',
'💾': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>',
'👤': '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>',
'✨': '<svg width="18" height="18" viewBox="0 0 24 24" fill="#ef4444"><path d="M12 2l2.4 7.2L21.6 12l-7.2 2.4L12 21.6l-2.4-7.2L2.4 12l7.2-2.4z"></path></svg>',
'sparkle': '<svg width="18" height="18" viewBox="0 0 24 24" fill="#ef4444"><path d="M12 2l2.4 7.2L21.6 12l-7.2 2.4L12 21.6l-2.4-7.2L2.4 12l7.2-2.4z"></path></svg>'
};
if (icon && typeof icon === 'string' && icon.includes('<svg')) {
toastIcon.innerHTML = icon;
} else if (svgMap[icon]) {
toastIcon.innerHTML = svgMap[icon];
} else {
toastIcon.innerHTML = svgMap['sparkle'];
}
toastNotification.classList.remove('hidden');
clearTimeout(window.toastTimer);
window.toastTimer = setTimeout(() => {
toastNotification.classList.add('hidden');
}, 2800);
}
// Gemini AI Direct Translation
async function translateWithGemini(text, sourceLang, targetLang, tone) {
let model = state.model || DEFAULT_GEMINI_MODEL;
if (model.includes('1.5') || model.includes('2.0') || model.includes('2.5')) {
model = DEFAULT_GEMINI_MODEL;
state.model = model;
try { localStorage.setItem('translet_gemini_model', model); } catch(e) {}
}
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${state.apiKey}`;
const srcName = languages[sourceLang]?.englishName || 'Auto detect';
const tgtName = languages[targetLang]?.englishName || targetLang;
const prompt = `You are a world-class linguistic translator and expert in Kurdish Sorani (both in Sorani Arabic script and Kurdish Latin script), English, Arabic, and other languages.
Translate the text faithfully, accurately, and naturally.
Source Language: ${srcName}
Target Language: ${tgtName}
Style/Tone: ${tone} (e.g. natural, formal, casual, literary)
Important Kurdish Sorani Rules:
1. Use authentic Sorani Kurdish vocabulary and natural sentence structure (Subject-Object-Verb).
2. Avoid literal word-by-word machine translation. Capture the exact intended human meaning.
3. If the input is in Kurdish Latin (e.g., "mn damawet ware bgrem"), understand it perfectly.
4. Express numbers, years, dates, times, days, and months naturally and clearly in Kurdish words where appropriate (e.g. پازدەی ئایاری دوو هەزار و بیست و چوار, سەد و پەنجا, کاتژمێر دە و نیو) to allow fluent natural Kurdish speech.
5. TELEPHONE NUMBERS IN KURDISH: In Kurdish, phone numbers are NEVER translated digit-by-digit (NEVER 'سفر حەوت حەوت سفر چوار...'). Always group into authentic Kurdish spoken cadence: 4-digit prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا / سفر حەوتسەد و هەشتا), 3-digit middle (e.g. 401 -> چوارسەد و یەک), 2-digit (e.g. 68 -> شەست و هەشت), 2-digit (e.g. 10 -> دە / دەیە). Example: 'My phone number is 07704016810' -> 'ژمارەی تەلەفۆنەکەم سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە.'
Return ONLY a valid JSON object without markdown formatting blocks:
{
"translation": "Translated text here",
"explanation": "Brief Kurdish Sorani notes or alternative vocabulary/phrasing explaining why this translation was chosen",
"detectedLanguage": "Detected language if source was auto"
}
Text to translate:
"""${text}"""`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
temperature: tone === 'literary' ? 0.7 : 0.2,
topP: 0.9,
}
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error?.message || `Gemini API Error: ${response.status}`);
}
const data = await response.json();
const rawText = data.candidates?.[0]?.content?.parts?.[0]?.text;
if (!rawText) throw new Error('No response from Gemini');
// Parse JSON from response
let cleaned = rawText.trim();
if (cleaned.startsWith('```json')) {
cleaned = cleaned.replace(/^```json/, '').replace(/```$/, '').trim();
} else if (cleaned.startsWith('```')) {
cleaned = cleaned.replace(/^```/, '').replace(/```$/, '').trim();
}
try {
const parsed = JSON.parse(cleaned);
return {
translation: parsed.translation || rawText,
explanation: parsed.explanation || '',
detected: parsed.detectedLanguage || ''
};
} catch (e) {
return {
translation: rawText.replace(/\{[\s\S]*"translation":\s*"([^"]+)"[\s\S]*\}/, '$1'),
explanation: '',
detected: ''
};
}
}
// Comprehensive Linguistic Tone Stylizer for Kurdish, English, Arabic & other languages
function applyToneStyling(rawText, targetLang, tone, originalText = '', sourceLang = '') {
if (!rawText || !tone || tone === 'natural') {
return {
text: rawText || '',
toneNote: 'سروشتی و زیندوو (Natural)'
};
}
let text = String(rawText).trim();
let toneNote = '';
const isKurdish = targetLang === 'ku' || (/[\u0600-\u06FF]/.test(text) && targetLang !== 'ar' && targetLang !== 'fa');
const isEnglish = targetLang === 'en' || (/^[a-zA-Z0-9\s.,!?'"()\-—:;]+$/.test(text) && targetLang !== 'ku' && targetLang !== 'tr');
const isArabic = targetLang === 'ar';
if (tone === 'formal') {
toneNote = 'فەرمی و باڵا (Formal): گۆڕینی وشە و دەستەواژەکان بۆ شێوازی فەرمی و بەڕێزانەی دیپلۆماسی و نووسراو.';
if (isKurdish) {
const formalKurdishMap = [
[/\bسڵاو هاوڕێیان\b/g, 'سڵاو و حورمەت بۆ گشت بەڕێزان'],
[/\bسڵاو\b/g, 'سڵاو و ڕێزی بێپایان'],
[/\bچۆنی\b/g, 'تەندروستیتان چۆنە؟'],
[/\bباشی\b/g, 'هیوادارم لە تەندروستییەکی باڵادابن'],
[/\bباشم\b/g, 'سوپاس بۆ ئێوە، لە باشترین دۆخدام'],
[/\bسوپاس\b/g, 'زۆر سوپاسگوزارم بۆ بەڕێزتان'],
[/\bزۆر سوپاس\b/g, 'سوپاس و پێزانینی قوڵم قبووڵ بفەرموون'],
[/\bدەستت خۆش\b/g, 'دەستان خۆش بێت و ماندوو نەبن'],
[/\bدەسخۆش\b/g, 'دەستان خۆش و بەرەکەتدابێت'],
[/\bبەڵێ\b/g, 'بە دڵنیاییەوە'],
[/\bنا\b/g, 'نەخێر بەڕێزم'],
[/\bنەخێر\b/g, 'نەخێر بەڕێزم'],
[/\bخوات لەگەڵ\b/g, 'لە دڵەوە هیوای سەرفرازی و سەلامەتیتان بۆ دەخوازم'],
[/\bبای\b/g, 'بە هیوای سەلامەتی و دیداری شاد'],
[/\bتۆ\b/g, 'جەنابتان'],
[/\bتۆش\b/g, 'جەنابیشتان'],
[/\bبزانە\b/g, 'ئاگاداربە بەڕێزم'],
[/\bوەرە\b/g, 'تکایە فەرموون'],
[/\bیارمەتیم بدە\b/g, 'تکایە هاوکاریم بکەن ئەگەر دەگونجێت'],
[/\bدەتوانیت\b/g, 'ئایا بۆتان دەگونجێت'],
[/\bدەکەیت\b/g, 'ئەنجامی دەدەن'],
[/\bچی دەکەیت\b/g, 'خەریکی چ ئەرکێکن؟'],
[/\bکێشە نییە\b/g, 'جێگەی نیگەرانی نییە بەڕێزم'],
[/\bبەیانی باش\b/g, 'بەیانیتان پڕ لە خێر و خۆشی بێت'],
[/\bشەو باش\b/g, 'شەوتان شاد و ئارام بێت']
];
for (const [pattern, replacement] of formalKurdishMap) {
text = text.replace(pattern, replacement);
}
} else if (isEnglish) {
const formalEnglishMap = [
[/\b(hi|hey|hello)\b/gi, 'Greetings, Dear Sir/Madam,'],
[/\bhow are you\b/gi, 'I hope this communication finds you well.'],
[/\bi am fine\b/gi, 'I am doing well, thank you.'],
[/\b(thanks|thank you)\b/gi, 'Thank you sincerely for your consideration.'],
[/\b(bye|goodbye)\b/gi, 'With kind regards and sincere respect,'],
[/\byes\b/gi, 'Affirmative, certainly.'],
[/\bno\b/gi, 'Negative, respectfully.'],
[/\bcan't\b/gi, 'cannot'],
[/\bdon't\b/gi, 'do not'],
[/\bwon't\b/gi, 'will not'],
[/\bi'm\b/gi, 'I am'],
[/\byou're\b/gi, 'you are'],
[/\bit's\b/gi, 'it is'],
[/\bwe're\b/gi, 'we are'],
[/\bthey're\b/gi, 'they are'],
[/\bdidn't\b/gi, 'did not'],
[/\bhaven't\b/gi, 'have not'],
[/\bwanna\b/gi, 'would like to'],
[/\bgonna\b/gi, 'intend to'],
[/\bhelp me\b/gi, 'kindly assist me'],
[/\bneed\b/gi, 'require'],
[/\bwant\b/gi, 'wish to request'],
[/\btell me\b/gi, 'kindly inform me'],
[/\b(ok|okay)\b/gi, 'Acknowledged and confirmed']
];
for (const [pattern, replacement] of formalEnglishMap) {
text = text.replace(pattern, replacement);
}
} else if (isArabic) {
const formalArabicMap = [
[/\bمرحبا\b/g, 'تحية طيبة وفائق التقدير والاحترام'],
[/\bأهلا\b/g, 'أهلاً وسهلاً بحضرتكم الكريمة'],
[/\bكيف حالك\b/g, 'كيف هي أحوالكم الكريمة؟'],
[/\bشكرا\b/g, 'خالص الشكر والتقدير والامتنان لسيادتكم'],
[/\bمع السلامة\b/g, 'دمتم في رعاية الله وحفظه الدائم'],
[/\bنعم\b/g, 'نعم، بكل تأكيد'],
[/\bلا\b/g, 'عذراً، كلا']
];
for (const [pattern, replacement] of formalArabicMap) {
text = text.replace(pattern, replacement);
}
}
} else if (tone === 'casual') {
toneNote = 'ڕۆژانە و قسەکردن (Casual): شێوازی قسەکردنی ڕۆژانەی گەنجانە، دۆستانە و بێ گرێ و گۆڵ.';
if (isKurdish) {
const casualKurdishMap = [
[/\bسڵاو هاوڕێیان\b/g, 'سڵاو جەماعەت چۆنن!'],
[/\bسڵاو\b/g, 'سڵاو چۆنی! چ خەبەر؟'],
[/\bچۆنی\b/g, 'چۆنی باشی؟ هەموو شتێک عەالە؟'],
[/\bتەندروستیت چۆنە\b/g, 'چۆنی لەگەڵ ژیان؟'],
[/\bباشم\b/g, 'دەستت ماچ، باشم شوکر'],
[/\bسوپاس\b/g, 'دەسخۆش گوڵ / زۆر مەمنوون'],
[/\bزۆر سوپاس\b/g, 'دەستت چاووت ماچ، دەسخۆش'],
[/\bدەستت خۆش\b/g, 'دەسخۆش برا گیان'],
[/\bخوات لەگەڵ\b/g, 'دەی بای، ئاگات لە خۆت بێت'],
[/\bبای\b/g, 'دەی بای گوڵم'],
[/\bبەڵێ\b/g, 'ها وەڵا'],
[/\bنا\b/g, 'نەوەڵا، نا'],
[/\bنەخێر\b/g, 'نەوەڵا برام'],
[/\bچی دەکەیت\b/g, 'خەریکی چیت گوڵم؟'],
[/\bخۆشم دەوێیت\b/g, 'زۆرم خۆشدەوێی بەڕاستی'],
[/\bکێشە نییە\b/g, 'قەیدی ناکات ئاساییە'],
[/\bبەیانی باش\b/g, 'بەیانیت باش گوڵم']
];
for (const [pattern, replacement] of casualKurdishMap) {
text = text.replace(pattern, replacement);
}
} else if (isEnglish) {
const casualEnglishMap = [
[/\b(hello|greetings)\b/gi, "Hey! What's up!"],
[/\bhow are you\b/gi, "How's it going? Everything good?"],
[/\bi am fine\b/gi, "I'm doing great, thanks!"],
[/\bthank you\b/gi, "Thanks a bunch! Really appreciate it!"],
[/\bgoodbye\b/gi, "Catch you later! Take care!"],
[/\byes\b/gi, 'Yeah, totally!'],
[/\bno\b/gi, 'Nah, nope'],
[/\bcannot\b/gi, "can't"],
[/\bdo not\b/gi, "don't"],
[/\bwill not\b/gi, "won't"],
[/\bgoing to\b/gi, 'gonna'],
[/\bwant to\b/gi, 'wanna'],
[/\bokay\b/gi, 'Cool, got it!']
];
for (const [pattern, replacement] of casualEnglishMap) {
text = text.replace(pattern, replacement);
}
} else if (isArabic) {
const casualArabicMap = [
[/\bمرحبا\b/g, 'أهلاً يا هلا، شو الأخبار؟'],
[/\bكيف حالك\b/g, 'كيفك، كلو تمام؟'],
[/\bشكرا\b/g, 'تسلم يا غالي، مشكور حبيبي'],
[/\bمع السلامة\b/g, 'يلا باي، دير بالك عحالك'],
[/\bنعم\b/g, 'إي و الله'],
[/\bلا\b/g, 'لا والله']
];
for (const [pattern, replacement] of casualArabicMap) {
text = text.replace(pattern, replacement);
}
}
} else if (tone === 'literary') {
toneNote = 'ئەدەبی و شاعیرانە (Literary): ڕستەسازی شاعیرانە، پەخشانی بەرز، هەستی قوڵ و وشەی کلاسیك.';
if (isKurdish) {
const literaryKurdishMap = [
[/\bسڵاو هاوڕێیان\b/g, 'درود و پەیامی ئاشتی بۆ گەشت هاوڕێیانی ئەزیز'],
[/\bسڵاو\b/g, 'درود و نەسرینی بەیانی، سڵاوێکی گەرم لە ناخی ڕۆحەوە'],
[/\bچۆنی\b/g, 'ڕەوشی دڵ و هەناوت چۆنە؟ ئایا لە دەریای ئارامیدا مەلە دەکەیت؟'],
[/\bباشم\b/g, 'لە ژێر سایەی سۆز و تەباییدا، بە ئارامی ڕۆژگار دەگوزەرێنم'],
[/\bسوپاس\b/g, 'هەستی پێزانین و ستایشی بێپایانم وەک بارانی بەهار پێشکەشتان دەبێت'],
[/\bخۆشم دەوێیت\b/g, 'تۆ تریفەی تاقانەی مانگی شەوانی منی، ئەی ئارامیی دڵ'],
[/\bخوات لەگەڵ\b/g, 'ئەستێرەی بەختت درەوشاوە بێت لە ئاسمانی بێسنووری چارەنووسدا'],
[/\bبەیانی باش\b/g, 'بەیانییەکی پڕ لە گزنگی زێڕین و شەونمی ئاوات لێت پیرۆز بێت'],
[/\bشەو باش\b/g, 'شەوگارێکی هێمن، باوەشی خەونی شیرینت بۆ بکاتەوە'],
[/\bژیان\b/g, 'کاروانی پڕ لە ڕاز و چرپەی ڕۆژگار'],
[/\bجوانە\b/g, 'نەخشێنراو بە جوانییەکی ئەفسوناوی و بێ وێنە'],
[/\bدڵتەنگم\b/g, 'هەورێکی خەمگین بەسەر ئاسمانی ڕۆحمدا باڵی کێشاوە'],
[/\bدڵخۆشم\b/g, 'باڵندەی شادیم لە ئاسمانی هیواکاندا دەفڕێت']
];
for (const [pattern, replacement] of literaryKurdishMap) {
text = text.replace(pattern, replacement);
}
} else if (isEnglish) {
const literaryEnglishMap = [
[/\bhello\b/gi, 'Greetings, gentle wanderer of poetic realms,'],
[/\bhow are you\b/gi, 'How fares the sacred sanctuary of thy gentle soul?'],
[/\bi am fine\b/gi, 'I walk serenely amidst the gentle dawn of quiet grace and contentment.'],
[/\bthank you\b/gi, 'My soul offers its deepest and most eternal gratitude unto thee.'],
[/\bi love you\b/gi, 'Thou art the celestial light unto my longing heart.'],
[/\bgoodbye\b/gi, 'May peaceful winds and benevolent stars guide thy sacred journey.'],
[/\bgood morning\b/gi, 'A dawn adorned with golden rays and sweet promise unto thee.'],
[/\bgood night\b/gi, 'May sweet twilight songs and tranquil shadows cradle thy slumber.'],
[/\bbeautiful\b/gi, 'breathtakingly exquisite and ethereal'],
[/\blife\b/gi, 'this tapestry of fleeting moments and sacred breath']
];
for (const [pattern, replacement] of literaryEnglishMap) {
text = text.replace(pattern, replacement);
}
} else if (isArabic) {
const literaryArabicMap = [
[/\bمرحبا\b/g, 'تحية عبقة بأريج الورد والياسمين، وسلامٌ ينبض بالمودة والصفاء'],
[/\bكيف حالك\b/g, 'كيف تهب نسائم الروح في رياض أيامك؟'],
[/\bشكرا\b/g, 'لك خالص الامتنان كقطرات الندى على بتلات الأزهار'],
[/\bمع السلامة\b/g, 'رافقتك السلامة وأحاطتك السكينة أينما حللت'],
[/\bأحبك\b/g, 'أنت النور الذي يضيء عتمة الروح ويسكن الفؤاد']
];
for (const [pattern, replacement] of literaryArabicMap) {
text = text.replace(pattern, replacement);
}
}
}
return { text, toneNote };
}
// Advanced Kurdish Grammar & Vocabulary Enhancer (Gemini-quality Natural Sorani)
function cleanRoboticKurdish(text) {
if (!text) return text;
let t = text.trim();
// 1. Lexical and phrase corrections (fixing Google Translate's worst Kurdish mistakes)
const fixes = [
// Tech & Modern Terms
[/\bهەواڵگریی دەستکرد\b/g, 'ژیریی دەستکرد'],
[/\bهەواڵگری دەستکرد\b/g, 'ژیریی دەستکرد'],
[/\bفێربوونی مەشین\b/g, 'فێربوونی ئامێر'],
[/\bمەشین لەڕنینگ\b/g, 'فێربوونی ئامێر'],
[/\bتۆڕی دەماری\b/g, 'تۆڕی دەماری دەستکرد'],
[/\bکامپیوتر\b/g, 'کۆمپیوتەر'],
[/\bکەمپیوتەر\b/g, 'کۆمپیوتەر'],
[/\bنەرمەواڵە\b/g, 'نەرمەکاڵا'],
[/\bسەختەواڵە\b/g, 'ڕەقەکاڵا'],
[/\bپەیوەندی کردن\b/g, 'پەیوەندیکردن'],
// Persian/Arabic literal artifacts
[/\bمی کند\b/g, 'دەکات'],
[/\bمی شود\b/g, 'دەبێت'],
[/\bخیلی\b/g, 'زۆر'],
[/\bچطور\b/g, 'چۆن'],
[/\bروز بخیر\b/g, 'ڕۆژ باش'],
[/\bشب بخیر\b/g, 'شەو باش'],
// Redundant pronouns and unnatural Kurdish phrases
[/\bمن باشم\b/g, 'باشم'],
[/\bمن تۆم خۆشدەوێت\b/g, 'خۆشم دەوێیت'],
[/\bتۆ چۆنیت\b/g, 'چۆنی'],
[/\bچۆنیت\b/g, 'چۆنی'],
[/\bئایا دەتوانیت\b/g, 'دەتوانیت'],
[/\bهیوای ڕۆژێکی خۆشت بۆ دەخوازم\b/g, 'ڕۆژێکی خۆشت هەبێت'],
[/\bهیوای سەرکەوتنت بۆ دەخوازم\b/g, 'سەرکەوتووبیت'],
[/\bڕۆژێکی باش\b/g, 'ڕۆژێکی خۆش'],
[/\bشەوێکی باش\b/g, 'شەوێکی ئارام'],
[/\bلەگەڵ مندا\b/g, 'لەگەڵمدا'],
[/\bلەگەڵ تۆدا\b/g, 'لەگەڵتدا'],
[/\bبۆ من\b/g, 'بۆم'],
[/\bبۆ تۆ\b/g, 'بۆت'],
[/\bتەنها بە شێوەیەکی کاتی\b/g, 'تەنها بە شێوەیەکی کاتی'],
[/\bبە شێوەیەکی خۆکار\b/g, 'بە شێوازی خۆکارانە'],
[/\bخۆشحاڵم بە بینینت\b/g, 'خۆشحاڵم بە ناسینت'],
[/\bسوپاس بۆ یارمەتیت\b/g, 'سوپاس بۆ هاوکارییەکەت'],
[/\bهیچ کێشەیەک نییە\b/g, 'کێشە نییە']
];
for (const [p, r] of fixes) {
t = t.replace(p, r);
}
// 2. Kurdish SOV Grammar Restructurer (Subject - Object - Verb)
// Fixes English SVO where verb was left before object/preposition
const sovRules = [
// S + V + O -> S + O + V (e.g. "ژیریی دەستکرد دەگۆڕێت جیهان" -> "ژیریی دەستکرد جیهان دەگۆڕێت")
[/^(\S+(?:\s+\S+)?)\s+(دەگۆڕێت|دروست دەکات|پێشکەش دەکات|ئاسان دەکات|فەراهەم دەکات|دەبەخشێت|خێراتر دەکات|یارمەتی دەدات|باشتر دەکات)\s+(.+?)([.!؟?]?)$/, '$1 $3 $2$4'],
// S + V + [لە/بۆ/لەگەڵ PP] -> S + PP + V (e.g. "ئەو کاردەکات لە کۆمپانیایەکدا" -> "ئەو لە کۆمپانیایەکدا کاردەکات")
[/^(\S+(?:\s+\S+)?)\s+(کاردەکات|دەخوێنێت|دەژیت|دەڕوات|دەگەڕێتەوە)\s+((?:لە|بۆ|لەگەڵ)\s+[^\n]+?)([.!؟?]?)$/, '$1 $3 $2$4'],
// "دەتوانێت یارمەتی بدات" structure
[/^(\S+(?:\s+\S+)?)\s+دەتوانێت\s+یارمەتی بدات\s+(.+?)([.!؟?]?)$/, '$1 دەتوانێت یارمەتی $2 بدات$3']
];
for (const [pattern, replacement] of sovRules) {
if (pattern.test(t)) {
t = t.replace(pattern, replacement);
break;
}
}
return t;
}
// Built-in Smart Multi-Endpoint Translation (Fallback when API key is not supplied)
async function translateWithSmartEngine(text, sourceLang, targetLang, tone = 'natural') {
const cleanInput = text.trim();
const lowerInput = cleanInput.toLowerCase().replace(/[.,!?;:()[\]{}]/g, '').trim();
// 1. Direct Instant Dictionary Check (Ultra-fast & 100% Accurate for common phrases)
if ((sourceLang === 'ku' || sourceLang === 'auto') && targetLang === 'en') {
if (kurdishDictionary.kuToEn[lowerInput]) {
const baseTrans = kurdishDictionary.kuToEn[lowerInput];
const styled = applyToneStyling(baseTrans, targetLang, tone, cleanInput, sourceLang);
return {
translation: styled.text,
explanation: `وەرگێڕانی دەستبەجێ لە فەرهەنگی کوردی (${styled.toneNote}).`,
detected: 'ku'
};
}
}
if ((sourceLang === 'en' || sourceLang === 'auto') && targetLang === 'ku') {
if (kurdishDictionary.enToKu[lowerInput]) {
const baseTrans = kurdishDictionary.enToKu[lowerInput];
const styled = applyToneStyling(baseTrans, targetLang, tone, cleanInput, sourceLang);
return {
translation: styled.text,
explanation: `وەرگێڕانی دەستبەجێ لە فەرهەنگی کوردی (${styled.toneNote}).`,
detected: 'en'
};
}
}
// 2. Kurdish Latin Handling
let preparedText = cleanInput;
let transliteratedArabic = '';
let wasLatinKurdish = false;
if (sourceLang === 'ku' || sourceLang === 'auto') {
if (isLatinText(cleanInput)) {
// Check if it's English words first
const isEnglish = /\b(the|is|are|am|i|you|he|she|it|we|they|hello|hi|what|where|how|why|can|will|do|have|has|this|that)\b/i.test(cleanInput);
if (!isEnglish) {
// It is Latin Kurdish! Convert to Sorani Arabic script
transliteratedArabic = kurdishTransliteration.toArabic(cleanInput);
preparedText = transliteratedArabic;
wasLatinKurdish = true;
// Check dictionary again with the converted Arabic text
const lowerArabic = transliteratedArabic.trim();
if (targetLang === 'en' && kurdishDictionary.kuToEn[lowerArabic]) {
const baseTrans = kurdishDictionary.kuToEn[lowerArabic];
const styled = applyToneStyling(baseTrans, targetLang, tone, cleanInput, sourceLang);
return {
translation: styled.text,
explanation: `دەقی لاتینی ناسێنراوە وەکو: "${transliteratedArabic}". (${styled.toneNote})`,
detected: 'ku'
};
}
}
}
}
// Determine language codes
let sCode = languages[sourceLang]?.gCode || 'auto';
let tCode = languages[targetLang]?.gCode || targetLang;
// If source was Latin Kurdish and converted to Arabic, force sl to ckb
if (wasLatinKurdish) {
sCode = 'ckb';
}
// 3. Try Google Translate Free Endpoint
try {
const gUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sCode}&tl=${tCode}&dt=t&q=${encodeURIComponent(preparedText)}`;
const res = await fetch(gUrl);
if (res.ok) {
const data = await res.json();
if (data && data[0]) {
let translated = data[0].map(item => item[0]).join('');
// If target is Kurdish, clean up robotic Google Translate artifacts
if (targetLang === 'ku') {
translated = cleanRoboticKurdish(translated);
}
const styled = applyToneStyling(translated, targetLang, tone, cleanInput, sourceLang);
let explanationNote = wasLatinKurdish
? `دەقی لاتینی گۆڕدرا بۆ سۆرانی: "${transliteratedArabic}" و وەرگێڕدرا بۆ ${languages[targetLang]?.name || targetLang}.<br>✨ ${styled.toneNote}`
: `وەرگێڕدراوە لە ڕێگەی بزوێنەری خێرا.<br>✨ ${styled.toneNote}`;
return {
translation: styled.text,
explanation: explanationNote,
detected: data[2] || sCode
};
}
}
} catch (err) {
console.warn('Google endpoint failed, trying MyMemory...', err);
}
// 4. Fallback to MyMemory API
try {
const myMemPair = `${sCode === 'auto' ? 'en' : sCode}|${tCode}`;
const mUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(preparedText)}&langpair=${myMemPair}`;
const mRes = await fetch(mUrl);
if (mRes.ok) {
const mData = await mRes.json();
if (mData.responseData?.translatedText) {
const styled = applyToneStyling(mData.responseData.translatedText, targetLang, tone, cleanInput, sourceLang);
return {
translation: styled.text,
explanation: wasLatinKurdish ? `تێبینی: "${transliteratedArabic}"<br>✨ ${styled.toneNote}` : `وەرگێڕدراوە لە ڕێگەی بزوێنەری جێگرەوە.<br>✨ ${styled.toneNote}`,
detected: sCode
};
}
}
} catch (mErr) {
console.warn('MyMemory also failed:', mErr);
}
// 5. Ultimate Fallback: Word-by-word dictionary translation if available
if (wasLatinKurdish && transliteratedArabic) {
const styled = applyToneStyling(transliteratedArabic, targetLang, tone, cleanInput, sourceLang);
return {
translation: styled.text,
explanation: `تەنها نووسینەکە گۆڕدرا بۆ سۆرانی: "${transliteratedArabic}".<br>✨ ${styled.toneNote}`,
detected: 'ku'
};
}
throw new Error('ناتوانرا دەقەکە وەربگێڕدرێت، تکایە ئینتەرنێتەکەت بپشکنە یان کلیلی Gemini دابنێ.');
}
// Main Perform Translation Function
async function performTranslation() {
let text = sourceTextEl.value.trim();
if (!text) {
targetTextEl.value = '';
targetStatusMessage.textContent = 'ئامادەیە';
explanationCard.classList.add('hidden');
return;
}
state.isTranslating = true;
LalaStats.count('t');
targetLoadingOverlay.classList.remove('hidden');
const toneNames = {
natural: 'سروشتی',
formal: 'فەرمی و باڵا',
casual: 'ڕۆژانە',
literary: 'ئەدەبی'
};
const activeToneName = toneNames[state.currentTone] || state.currentTone;
targetStatusMessage.textContent = `لە وەرگێڕاندایە (${activeToneName})...`;
playSubtleClick();
const srcLang = sourceLangEl.value;
const tgtLang = targetLangEl.value;
text = joinPhoneNumbers(text);
try {
let result = null;
// 1. Primary: Local Fast Translation API (Proxy to Gemini AI + Google Fallback, zero CORS)
try {
const response = await fetch('/api/translate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: text,
source_lang: srcLang,
target_lang: tgtLang,
tone: state.currentTone,
api_key: state.apiKey || DEFAULT_GEMINI_API_KEY,
model: state.model || DEFAULT_GEMINI_MODEL
})
});
if (response.ok) {
const data = await response.json();
// A failed server answer returns the same text back: never show that as a translation
if (data && data.translation && data.engine !== 'error' && data.translation.trim() !== text.trim()) {
result = data;
}
}
} catch (apiErr) {
console.warn('Local /api/translate unavailable, using in-browser translation:', apiErr);
}
// 1b. Server could not translate: the phone asks Google Translate itself
if (!result || !result.translation) {
const phone = await translateFromPhone(text, srcLang, tgtLang);
if (phone) {
result = { translation: tgtLang === 'ku' ? fixKurdishSoraniGreetings(phone) : phone, explanation: '', detectedLanguage: srcLang, engine: 'phone' };
}
}
// 2. Secondary fallback if server endpoint was unreachable
if (!result || !result.translation) {
if (state.apiKey && state.apiKey.trim().length > 10) {
try {
result = await translateWithGemini(text, srcLang, tgtLang, state.currentTone);
} catch (geminiErr) {
console.warn('In-browser Gemini failed, falling back to smart engine:', geminiErr);
result = await translateWithSmartEngine(text, srcLang, tgtLang, state.currentTone);
}
} else {
result = await translateWithSmartEngine(text, srcLang, tgtLang, state.currentTone);
}
}
if (!result || !result.translation) {
throw new Error('No translation returned');
}
let finalTranslation = result.translation;
if (tgtLang === 'ku') {
finalTranslation = fixKurdishSoraniGreetings(finalTranslation);
}
targetTextEl.value = finalTranslation;
targetStatusMessage.textContent = `تەواو بوو (${activeToneName})`;
// Visual pulse effect
const targetContainer = targetTextEl.closest('.textarea-container');
if (targetContainer) {
targetContainer.classList.remove('tone-pulse');
void targetContainer.offsetWidth;
targetContainer.classList.add('tone-pulse');
}
// Show explanation if available
if (result.explanation && result.explanation.trim().length > 0) {
explanationContent.innerHTML = `<div class="exp-item">${escapeHtml(String(result.explanation)).replace(/\n/g, '<br>')}</div>`;
showExplanationBtn.classList.remove('hidden');
} else {
showExplanationBtn.classList.add('hidden');
}
// Save to History
saveToHistory({
sourceText: text,
targetText: result.translation,
sourceLang: srcLang,
targetLang: tgtLang,
timestamp: new Date().toLocaleTimeString('ku', { hour: '2-digit', minute: '2-digit' })
});
// Automatically scan and highlight multiple meanings in the Word Insights card
if (typeof checkAndHighlightWordInsights === 'function') {
checkAndHighlightWordInsights(text, result.translation);
}
// Automatically update Kurdish Voice Studio bar if Kurdish is involved
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
if (tgtLang === 'ku' && result.translation) {
kurdishVoiceSynthesizer.updatePhonetics(result.translation);
} else if (srcLang === 'ku' && text) {
kurdishVoiceSynthesizer.updatePhonetics(text);
}
}
} catch (error) {
console.error('Translation error:', error);
targetTextEl.value = `⚠️ هەڵە لە وەرگێڕان: ${error.message}`;
targetStatusMessage.textContent = 'هەڵەیەک ڕوویدا';
showToast('هەڵەیەک لە پەیوەندی دروست بوو', '❌');
} finally {
state.isTranslating = false;
targetLoadingOverlay.classList.add('hidden');
}
}
// History Management
function saveToHistory(item) {
// Prevent duplicate consecutive entries
if (state.history.length > 0 && state.history[0].sourceText === item.sourceText && state.history[0].targetText === item.targetText) {
return;
}
state.history.unshift(item);
if (state.history.length > 25) state.history.pop();
localStorage.setItem('translet_history', JSON.stringify(state.history));
renderHistory();
}
function renderHistory() {
if (!state.history || state.history.length === 0) {
historyList.innerHTML = '<div class="empty-history">هێشتا هیچ وەرگێڕانێک ئەنجام نەدراوە.</div>';
return;
}
historyList.innerHTML = state.history.map((item, idx) => `
<div class="history-item" data-index="${idx}">
<div class="history-texts">
<div class="history-source">${escapeHtml(item.sourceText)}</div>
<div class="history-target">${escapeHtml(item.targetText)}</div>
</div>
<div class="history-meta">
<span>${item.sourceLang} ➔ ${item.targetLang}</span>
<span>•</span>
<span>${item.timestamp || ''}</span>
</div>
</div>
`).join('');
// Add click to restore
document.querySelectorAll('.history-item').forEach(el => {
el.addEventListener('click', () => {
const idx = el.getAttribute('data-index');
const item = state.history[idx];
if (item) {
sourceTextEl.value = item.sourceText;
targetTextEl.value = item.targetText;
sourceLangEl.value = item.sourceLang;
targetLangEl.value = item.targetLang;
updateTextDirection(sourceTextEl, item.sourceLang);
updateTextDirection(targetTextEl, item.targetLang);
charCountEl.textContent = item.sourceText.length;
showToast('دەقەکە گەڕێنرایەوە', '📋');
}
});
});
}
function escapeHtml(str) {
if (!str) return '';
return str.replace(/[&<>"']/g, m => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
})[m]);
}
/* ═══════════════════════════════════════════════════════════════════
Kurdish Sorani (سۆرانی) — Acoustic Studio Voice Engine
High-Fidelity Unified Neural Voice Player
═══════════════════════════════════════════════════════════════════ */
let _ttsAudioEl = null;
let _silkAudioContext = null;
let _silkCurrentSource = null;
let _silkPlaybackToken = 0;
function getSilkAudioContext() {
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (AudioCtx) {
if (!_silkAudioContext) {
_silkAudioContext = new AudioCtx();
}
if (_silkAudioContext.state === 'suspended') {
_silkAudioContext.resume().catch(() => {});
}
}
} catch (_) {}
return _silkAudioContext;
}
if (typeof document !== 'undefined') {
document.addEventListener('click', () => { getSilkAudioContext(); }, { passive: true });
document.addEventListener('touchstart', () => { getSilkAudioContext(); }, { passive: true });
}
function createSilkStudioDspChain(ctx) {
if (!ctx) return null;
try {
// 1. High-Pass Filter: Cuts out DC offset and sub-rumble (< 65Hz)
const hp = ctx.createBiquadFilter();
hp.type = 'highpass';
hp.frequency.setValueAtTime(65, ctx.currentTime);
hp.Q.setValueAtTime(0.707, ctx.currentTime);
// 2. Vocal Warmth / Body: Adds velvety human chest resonance (+2.2dB at 240Hz)
const warm = ctx.createBiquadFilter();
warm.type = 'peaking';
warm.frequency.setValueAtTime(240, ctx.currentTime);
warm.Q.setValueAtTime(1.0, ctx.currentTime);
warm.gain.setValueAtTime(2.2, ctx.currentTime);
// 3. De-Harshing Notch: Eliminates metallic vocoder raspiness (-2.5dB at 3800Hz)
const deharsh = ctx.createBiquadFilter();
deharsh.type = 'peaking';
deharsh.frequency.setValueAtTime(3800, ctx.currentTime);
deharsh.Q.setValueAtTime(1.2, ctx.currentTime);
deharsh.gain.setValueAtTime(-2.5, ctx.currentTime);
// 4. Velvet Silk Low-Pass Filter: Cuts out vocoder hiss, aliasing, and buzzing (> 5800Hz)
const lowpass = ctx.createBiquadFilter();
lowpass.type = 'lowpass';
lowpass.frequency.setValueAtTime(5800, ctx.currentTime);
lowpass.Q.setValueAtTime(0.707, ctx.currentTime);
// 5. Studio Dynamics Compressor: Smooths volume peaks, prevents phone speaker distortion
const compressor = ctx.createDynamicsCompressor();
compressor.threshold.setValueAtTime(-18, ctx.currentTime);
compressor.knee.setValueAtTime(20, ctx.currentTime);
compressor.ratio.setValueAtTime(4, ctx.currentTime);
compressor.attack.setValueAtTime(0.003, ctx.currentTime);
compressor.release.setValueAtTime(0.15, ctx.currentTime);
// 6. Headroom Output Gain: Prevents mobile DAC / speaker clipping (-2.0dB / 0.80)
const gain = ctx.createGain();
gain.gain.setValueAtTime(0.80, ctx.currentTime);
hp.connect(warm);
warm.connect(deharsh);
deharsh.connect(lowpass);
lowpass.connect(compressor);
compressor.connect(gain);
gain.connect(ctx.destination);
return { input: hp, gain };
} catch (e) {
console.warn('DSP chain error:', e);
return null;
}
}
async function playSilkStudioAudio(audioSource, options = {}) {
// Always stop previous speech FIRST before getting the new token!
_stopSpeech();
const currentToken = ++_silkPlaybackToken;
const onEnded = () => {
if (currentToken !== _silkPlaybackToken) return;
if (_silkCurrentSource) {
try { _silkCurrentSource.disconnect(); } catch (_) {}
_silkCurrentSource = null;
}
if (options.onEnd) options.onEnd();
};
const playFallbackHtml5 = (src) => {
if (currentToken !== _silkPlaybackToken) return;
if (!_ttsAudioEl) _ttsAudioEl = new Audio();
_ttsAudioEl.setAttribute('playsinline', 'true');
_ttsAudioEl.setAttribute('webkit-playsinline', 'true');
_ttsAudioEl.volume = 0.82;
_ttsAudioEl.onended = onEnded;
_ttsAudioEl.onerror = onEnded;
_ttsAudioEl.src = src;
const p = _ttsAudioEl.play();
if (p && typeof p.then === 'function') {
p.then(() => {
if (options.onStart) options.onStart();
}).catch(onEnded);
}
};
// For HTTP/data audio URLs: stream immediately with zero buffering delay (starts in ~30ms)!
if (typeof audioSource === 'string' && (audioSource.startsWith('http') || audioSource.startsWith('data:') || audioSource.startsWith('blob:'))) {
playFallbackHtml5(audioSource);
return;
}
const ctx = getSilkAudioContext();
let canUseWebAudio = false;
if (ctx) {
if (ctx.state === 'suspended') {
try { await ctx.resume(); } catch (_) {}
}
if (ctx.state === 'running') {
canUseWebAudio = true;
}
}
if (!canUseWebAudio) {
if (typeof audioSource === 'string') {
const src = audioSource.startsWith('http') || audioSource.startsWith('data:')
? audioSource
: `data:audio/wav;base64,${audioSource}`;
playFallbackHtml5(src);
} else {
onEnded();
}
return;
}
try {
let arrayBuffer = null;
if (audioSource instanceof ArrayBuffer) {
arrayBuffer = audioSource;
} else if (typeof audioSource === 'string') {
if (audioSource.startsWith('http')) {
const resp = await fetch(audioSource);
arrayBuffer = await resp.arrayBuffer();
} else {
const b64 = audioSource.includes(',') ? audioSource.split(',')[1] : audioSource;
const binaryString = window.atob(b64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
arrayBuffer = bytes.buffer;
}
}
if (!arrayBuffer || currentToken !== _silkPlaybackToken) return;
// Use sliced copy so original ArrayBuffer is never detached
ctx.decodeAudioData(arrayBuffer.slice(0), (decodedBuffer) => {
if (currentToken !== _silkPlaybackToken) return;
// Soft Edge Fades (prevents clicks at start/end) & Soft Noise Gate on pauses
try {
const chData = decodedBuffer.getChannelData(0);
const n = chData.length;
const fadeLen = Math.min(320, Math.floor(n / 20));
for (let i = 0; i < fadeLen; i++) {
const factor = i / fadeLen;
chData[i] *= factor;
chData[n - 1 - i] *= factor;
}
const blk = 320;
for (let i = 0; i < n; i += blk) {
let sum = 0;
const end = Math.min(i + blk, n);
for (let j = i; j < end; j++) sum += chData[j] * chData[j];
const rms = Math.sqrt(sum / (end - i));
if (rms < 0.004) {
for (let j = i; j < end; j++) chData[j] = 0;
}
}
} catch (_) {}
if (_silkCurrentSource) {
try { _silkCurrentSource.stop(); } catch (_) {}
try { _silkCurrentSource.disconnect(); } catch (_) {}
}
const source = ctx.createBufferSource();
source.buffer = decodedBuffer;
const applyFilters = options.filter !== false;
if (applyFilters) {
const dsp = createSilkStudioDspChain(ctx);
if (dsp && dsp.input) {
source.connect(dsp.input);
} else {
source.connect(ctx.destination);
}
} else {
source.connect(ctx.destination);
}
_silkCurrentSource = source;
source.onended = onEnded;
source.start(0);
if (options.onStart) options.onStart();
}, (decodeErr) => {
console.warn('AudioContext decode failed, fallback to HTML5:', decodeErr);
if (typeof audioSource === 'string') {
const src = audioSource.startsWith('http') || audioSource.startsWith('data:')
? audioSource
: `data:audio/wav;base64,${audioSource}`;
playFallbackHtml5(src);
} else {
onEnded();
}
});
} catch (err) {
console.warn('playSilkStudioAudio error:', err);
if (typeof audioSource === 'string') {
const src = audioSource.startsWith('http') || audioSource.startsWith('data:')
? audioSource
: `data:audio/wav;base64,${audioSource}`;
playFallbackHtml5(src);
} else {
onEnded();
}
}
}
function _stopSpeech() {
_silkPlaybackToken++;
if (_silkCurrentSource) {
try { _silkCurrentSource.stop(); } catch (_) {}
try { _silkCurrentSource.disconnect(); } catch (_) {}
_silkCurrentSource = null;
}
if (_ttsAudioEl) {
_ttsAudioEl.onended = null;
_ttsAudioEl.onerror = null;
_ttsAudioEl.onpause = null;
_ttsAudioEl.onplaying = null;
try {
_ttsAudioEl.pause();
_ttsAudioEl.currentTime = 0;
} catch (_) {}
}
if ('speechSynthesis' in window) {
try {
window.speechSynthesis.cancel();
} catch (_) {}
}
}
// Main Kurdish voice: Gemini "Charon" through our own server (/api/tts). Returns a blob: URL or null.
const _kurdishBlobUrls = [];
async function fetchServerKurdishVoice(clean, dialect) {
if (isStaticOnlyHost()) return null;
try {
const base = API_BASE || window.location.origin;
// engine=gemini_only: never the old unpleasant voice from the server for Sorani
const params = new URLSearchParams({ text: clean, lang: 'ku', dialect: dialect || 'sorani',
engine: dialect === 'badini' ? 'human' : 'gemini_only' });
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), 30000);
const r = await fetch(`${base}/api/tts?${params.toString()}`, { signal: controller.signal });
clearTimeout(t);
if (!r.ok || !(r.headers.get('Content-Type') || '').startsWith('audio')) return null;
const blob = await r.blob();
if (blob.size < 1000) return null;
// Several sentences can be fetched ahead (voice mode), so only free URLs that are long finished
const url = URL.createObjectURL(blob);
_kurdishBlobUrls.push(url);
while (_kurdishBlobUrls.length > 30) { try { URL.revokeObjectURL(_kurdishBlobUrls.shift()); } catch (_) {} }
return url;
} catch (e) {
console.warn('Server Kurdish voice unavailable, using backup voice:', e);
return null;
}
}
// ---- Our own Kurdish voice ("Lala voice"), running inside the phone/browser: free, no server ----
// Loaded in the background the first time Kurdish speech is needed (~31 MB once, then cached).
// Until it is ready, the older voices below are used so nobody has to wait.
const LALA_VOICE_ORT = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/ort.webgpu.min.js';
let _lalaVoicePromise = null;
let _lalaVoiceAnnounced = false;
let _lalaVoiceWaiting = false;
function _loadScriptOnce(src) {
return new Promise((resolve, reject) => {
if (document.querySelector(`script[data-src="${src}"]`)) return resolve();
const s = document.createElement('script');
s.src = src; s.async = true; s.dataset.src = src;
s.onload = resolve; s.onerror = () => reject(new Error('load failed: ' + src));
document.head.appendChild(s);
});
}
// ---- First-time download bar: shows how much of the voice / ear is left to download ----
// Appears only for a real download (a cached load finishes before the bar is shown).
const _dl = { items: {}, el: null, hideTimer: null };
const _DL_NAMES = { voice: 'دەنگی کوردی', ear: 'گوێی کوردی' };
function _dlMB(bytes) { return Math.max(0, bytes / 1048576).toFixed(bytes < 10485760 ? 1 : 0); }
function updateDownloadBar(kind, pct, loaded, total) {
if (typeof document === 'undefined') return;
const now = Date.now();
const it = _dl.items[kind] || (_dl.items[kind] = { start: now });
Object.assign(it, { pct, loaded: loaded || 0, total: total || 0 });
const active = Object.entries(_dl.items).filter(([, x]) => x.pct < 100);
// cache loads are done in a moment: only show the bar when a download really takes time
if (active.length && !_dl.el && !active.some(([, x]) => now - x.start > 1200)) return;
if (!_dl.el) {
const el = document.createElement('div');
el.id = 'lalaDownloadBar';
el.dir = 'rtl';
// Opened from the home screen (full screen): the phone's own top bar covers the screen top, so go lower
let homeScreen = false;
try { homeScreen = matchMedia('(display-mode: standalone), (display-mode: fullscreen)').matches || navigator.standalone === true; } catch (_) {}
el.style.cssText = `position:fixed;top:calc(env(safe-area-inset-top, 0px) + ${homeScreen ? 52 : 12}px);left:50%;transform:translateX(-50%);z-index:99999;` +
'width:min(92vw,420px);background:rgba(17,17,24,.96);color:#fff;border:1px solid rgba(255,255,255,.12);' +
'border-radius:14px;padding:10px 14px;font-size:13px;line-height:1.6;box-shadow:0 6px 24px rgba(0,0,0,.35);' +
'font-family:inherit;pointer-events:none';
document.body.appendChild(el);
_dl.el = el;
}
clearTimeout(_dl.hideTimer);
const rows = Object.entries(_dl.items).map(([k, x]) => {
const left = x.total ? `${_dlMB(x.total - x.loaded)} مێگابایت ماوە لە ${_dlMB(x.total)}` : '';
const label = x.pct >= 100 ? `✓ ${_DL_NAMES[k] || k} ئامادەیە` : `📥 ${_DL_NAMES[k] || k} دادەبەزێت: ${x.pct}%`;
return `<div style="display:flex;justify-content:space-between;gap:8px"><span>${label}</span>` +
`<span style="opacity:.75">${x.pct >= 100 ? '' : left}</span></div>` +
`<div style="height:6px;background:rgba(255,255,255,.15);border-radius:3px;margin:4px 0 6px;overflow:hidden">` +
`<div style="height:100%;width:${x.pct}%;background:#22c55e;border-radius:3px;transition:width .3s"></div></div>`;
}).join('');
_dl.el.innerHTML = rows + '<div style="opacity:.6;font-size:11px">تەنها جاری یەکەم دادەبەزێت، پاشان لەسەر مۆبایلەکەت دەمێنێتەوە.</div>';
if (!active.length) {
_dl.hideTimer = setTimeout(() => { if (_dl.el) { _dl.el.remove(); _dl.el = null; } _dl.items = {}; }, 2500);
}
}
function startLalaVoice() {
if (_lalaVoicePromise) return _lalaVoicePromise;
if (typeof WebAssembly === 'undefined') return Promise.resolve(false);
const conn = navigator.connection;
if (conn && conn.saveData) return Promise.resolve(false); // respect "data saver"
_lalaVoicePromise = (async () => {
await _loadScriptOnce(LALA_VOICE_ORT);
await _loadScriptOnce('/voice/kurdish-voice.js?v=7'); // bump when the player changes
window.LalaVoice.onProgress((pct, loaded, total) => {
try { updateDownloadBar('voice', pct, loaded, total); } catch (_) {}
});
await window.LalaVoice.load();
return true;
})().catch((e) => { console.warn('Lala voice unavailable:', e); _lalaVoicePromise = null; return false; });
return _lalaVoicePromise;
}
// ---- Translation straight from the phone (backup) ----
// Google blocks our cloud server for its free translate page, but each phone can use it directly.
async function translateFromPhone(text, src, tgt) {
const code = (l) => (l === 'ku' ? 'ckb' : (l || 'auto'));
const q = encodeURIComponent(text);
const urls = [
`https://translate.googleapis.com/translate_a/single?client=gtx&sl=${code(src)}&tl=${code(tgt)}&dt=t&q=${q}`,
`https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl=${code(src)}&tl=${code(tgt)}&q=${q}`,
];
for (const url of urls) {
try {
const r = await fetch(url);
if (!r.ok) continue;
const d = await r.json();
let out = '';
if (Array.isArray(d) && Array.isArray(d[0])) out = d[0].map((p) => (p && p[0]) || '').join('');
else if (Array.isArray(d)) out = d.map((p) => (Array.isArray(p) ? p[0] : p)).join(' ');
out = String(out || '').trim();
if (out && out !== text.trim()) return out;
} catch (_) { /* try the next one */ }
}
return '';
}
// Server first (Gemini, best quality); if it fails or returns the same text, the phone translates itself
async function translateTextReliable(text, src, tgt, tone = 'natural') {
const base = API_BASE || '';
text = joinPhoneNumbers(text);
try {
const r = await fetch(`${base}/api/translate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, source_lang: src, target_lang: tgt, tone })
});
if (r.ok) {
const d = await r.json();
const t = String(d.translation || '').trim();
if (t && d.engine !== 'error' && t !== text.trim()) return { ...d, translation: t };
}
} catch (_) {}
const phone = await translateFromPhone(text, src, tgt);
if (phone) {
return { translation: tgt === 'ku' ? fixKurdishSoraniGreetings(phone) : phone, explanation: '', detectedLanguage: src, engine: 'phone' };
}
return null;
}
// English digit words said one by one ("six eight one zero") -> digits ("6810"), only in runs of 3+
const EN_DIGIT_WORDS = { zero: '0', oh: '0', one: '1', two: '2', three: '3', four: '4',
five: '5', six: '6', seven: '7', eight: '8', nine: '9' };
function englishDigitWordsToDigits(text) {
if (!text) return text;
const strict = /^(zero|one|two|three|four|five|six|seven|eight|nine|oh)$/i;
return text.replace(/\b(?:(?:zero|oh|one|two|three|four|five|six|seven|eight|nine|\d+)[\s,.\-]+){2,}(?:zero|oh|one|two|three|four|five|six|seven|eight|nine|\d+)\b/gi, (m) => {
const toks = m.split(/[\s,.\-]+/).filter(Boolean);
// at least one spoken digit word (so year lists like "2019, 2020, 2021" are never glued)
if (!toks.some((t) => strict.test(t))) return m;
const out = toks.map((t) => (/^\d+$/.test(t) ? t : EN_DIGIT_WORDS[t.toLowerCase()])).join('');
return out.length >= 4 ? out : m; // "one, two, three" counting stays words
});
}
// Choose among the browser's guesses: if one of them holds more digits (a phone number), take it
function pickBrowserAlternative(result) {
let best = result[0].transcript;
const digits = (s) => (englishDigitWordsToDigits(s).match(/\d/g) || []).length;
let bestDigits = digits(best);
for (let k = 1; k < result.length; k++) {
const t = result[k].transcript;
const d = digits(t);
if (d > bestDigits) { best = t; bestDigits = d; }
}
return englishDigitWordsToDigits(best);
}
// ---- Browser's own speech recognition (Chrome/Edge): free backup for NON-Kurdish speech ----
let _browserRec = null;
let _browserHeard = '';
let _browserDone = null;
function startBrowserListening(lang) {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
_browserHeard = '';
_browserRec = null;
if (!SR) return;
const tags = { en: 'en-US', ar: 'ar-IQ', fa: 'fa-IR', tr: 'tr-TR', de: 'de-DE', fr: 'fr-FR', es: 'es-ES' };
try {
const rec = new SR();
rec.lang = tags[lang] || lang;
rec.continuous = true;
rec.interimResults = false;
rec.maxAlternatives = 5; // numbers: the best guess is often words ("Is the 8th Gen"), another guess has the digits
let resolveDone;
_browserDone = new Promise((r) => { resolveDone = r; });
rec.onresult = (e) => {
for (let i = e.resultIndex; i < e.results.length; i++) {
if (e.results[i].isFinal) _browserHeard += ' ' + pickBrowserAlternative(e.results[i]);
}
};
rec.onend = () => resolveDone();
rec.onerror = () => resolveDone();
rec.start();
_browserRec = rec;
} catch (e) {
console.warn('Browser speech recognition unavailable:', e);
_browserRec = null;
}
}
function stopBrowserListening() {
if (_browserRec) { try { _browserRec.stop(); } catch (_) {} _browserRec = null; }
}
async function finishBrowserListening() {
stopBrowserListening();
// give it a moment to deliver the last words
if (_browserDone) await Promise.race([_browserDone, new Promise((r) => setTimeout(r, 2500))]);
return _browserHeard.trim();
}
// ---- Our own Kurdish ear ("Lala ear"): Sorani speech recognition inside the phone (~100 MB once) ----
let _lalaEarPromise = null;
function startLalaEar(waiting = false) {
if (_lalaEarPromise) return _lalaEarPromise;
if (typeof WebAssembly === 'undefined') return Promise.resolve(false);
const conn = navigator.connection;
if (!waiting && conn && conn.saveData) return Promise.resolve(false);
_lalaEarPromise = (async () => {
await _loadScriptOnce('/voice/kurdish-ear.js?v=5');
const earCached = window.LalaEar.isCached ? await window.LalaEar.isCached() : false;
window.LalaEar.onProgress((pct, loaded, total) => {
_lalaEarPct = pct;
if (!earCached) { try { updateDownloadBar('ear', pct, loaded, total); } catch (_) {} }
// Show the download only while someone is waiting for the ear
if (_lalaEarWaiting) {
const st = document.getElementById('vcStatusText');
if (st) st.textContent = `👂 گوێی کوردی دادەبەزێت (تەنها جاری یەکەم)... ${pct}%`;
}
});
const ok = await window.LalaEar.load();
if (!ok) _lalaEarPromise = null; // allow another try later
return ok;
})().catch((e) => { console.warn('Lala ear unavailable:', e); _lalaEarPromise = null; return false; });
return _lalaEarPromise;
}
let _lalaEarWaiting = false;
let _lalaEarPct = 0;
async function synthesizeLalaVoice(clean) {
// Always the same voice: wait for our voice instead of switching to another speaker
if (!(window.LalaVoice && window.LalaVoice.isLoaded())) {
if (!_lalaVoiceAnnounced) {
_lalaVoiceAnnounced = true;
try { showToast('دەنگی کوردی ئامادە دەکرێت (تەنها جاری یەکەم)...', '🎙️'); } catch (_) {}
}
_lalaVoiceWaiting = true;
const ok = await startLalaVoice();
_lalaVoiceWaiting = false;
if (!ok) return null;
}
try {
const { samples, sampleRate } = await window.LalaVoice.synth(clean);
if (!samples.length) return null;
return URL.createObjectURL(window.LalaVoice.toWav(samples, sampleRate));
} catch (e) {
console.warn('Lala voice failed:', e);
return null;
}
}
async function synthesizeNativeKurdishClient(text, dialect = 'sorani') {
const clean = normalizeKurdishNumbers(fixKurdishSoraniGreetings((text || '').trim()));
if (!clean) return null;
// 1. Our own voice (Sorani) - always, so every sentence has the same speaker
if (dialect !== 'badini') {
const own = await synthesizeLalaVoice(clean);
if (own) {
_kurdishBlobUrls.push(own);
while (_kurdishBlobUrls.length > 30) { try { URL.revokeObjectURL(_kurdishBlobUrls.shift()); } catch (_) {} }
return own;
}
}
// 2. Only if this device cannot run our voice at all (or Badini): the Gemini voice
const serverVoice = await fetchServerKurdishVoice(clean, dialect);
if (serverVoice) return serverVoice;
// The old public voice is used ONLY for Badini (our voice is Sorani); the user disliked it for Sorani
if (dialect !== 'badini') {
try { showToast('دەنگی کوردی لەم ئامێرەدا ئامادە نییە، تکایە پەڕەکە نوێ بکەرەوە', '⚠️'); } catch (_) {}
return null;
}
// Badini backup: the older public Kurdish voice, called straight from the browser
// Neural VITS acoustic fix: 'سفر' without vowel tokens collapses VITS duration to 'سێ' (3).
// 'زیرۆ' provides exact vowel structure for the 0 phoneme in audio.
const ttsClean = clean.replace(/\bسفر\b/g, 'زیرۆ').replace(/\bسفرە\b/g, 'زیرۆیە');
const isBadini = (dialect === 'badini');
const dialectLabel = isBadini ? 'بادینی / Badini' : 'سۆرانی / Sorani';
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 7000);
const callUrl = 'https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize';
const r1 = await fetch(callUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ data: [ttsClean, dialectLabel] }),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!r1.ok) return null;
const { event_id } = await r1.json();
if (!event_id) return null;
const streamUrl = `https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize/${event_id}`;
const r2 = await fetch(streamUrl);
const textData = await r2.text();
for (const line of textData.split('\n')) {
if (line.startsWith('data:')) {
const parsed = JSON.parse(line.slice(5).trim());
if (Array.isArray(parsed) && parsed[0] && parsed[0].url) {
return parsed[0].url;
}
}
}
} catch (e) {
console.warn('Native Kurdish TTS Client error:', e);
}
return null;
}
// Server TTS helper for non-Kurdish or server-assisted speech
function _playViaServerTTS(clean, lang, options = {}) {
const speed = options.speed || '1.0';
const isStaticCloud = isStaticOnlyHost();
const playBrowserSpeech = () => {
if ('speechSynthesis' in window) {
try {
const u = new SpeechSynthesisUtterance(clean);
const bcpMap = {
ku: 'ckb-IQ',
en: 'en-US',
ar: 'ar-SA',
de: 'de-DE',
tr: 'tr-TR',
fa: 'fa-IR',
fr: 'fr-FR',
es: 'es-ES'
};
const targetLang = (lang || '').toLowerCase();
u.lang = bcpMap[targetLang] || (targetLang.startsWith('ar') ? 'ar-SA' : (targetLang.startsWith('de') ? 'de-DE' : (targetLang.startsWith('tr') ? 'tr-TR' : (targetLang.startsWith('fr') ? 'fr-FR' : (targetLang.startsWith('es') ? 'es-ES' : (targetLang.startsWith('fa') ? 'fa-IR' : 'en-US'))))));
u.rate = speed || 1.0;
u.onstart = () => { if (options.onStart) options.onStart(); };
u.onend = () => { if (options.onEnd) options.onEnd(); _stopSpeech(); };
u.onerror = () => { if (options.onEnd) options.onEnd(); _stopSpeech(); };
window.speechSynthesis.speak(u);
return;
} catch (_) {}
}
if (options.onEnd) options.onEnd();
_stopSpeech();
};
if (isStaticCloud) {
// Ultra-Fast Zero Latency on Static Cloud: speak immediately without waiting for /api/tts 404
playBrowserSpeech();
return;
}
const queryParams = {
text: clean,
lang: lang || 'en',
speed: speed.toString(),
_t: Date.now().toString()
};
const params = new URLSearchParams(queryParams);
const url = `${API_BASE}/api/tts?${params.toString()}`;
if (!_ttsAudioEl) _ttsAudioEl = new Audio();
_ttsAudioEl.setAttribute('playsinline', 'true');
_ttsAudioEl.setAttribute('webkit-playsinline', 'true');
_ttsAudioEl.volume = 1.0;
_ttsAudioEl.onplaying = () => { if (options.onStart) options.onStart(); };
_ttsAudioEl.onended = () => { if (options.onEnd) options.onEnd(); _stopSpeech(); };
_ttsAudioEl.onerror = () => { playBrowserSpeech(); };
_ttsAudioEl.src = url;
const p = _ttsAudioEl.play();
if (p !== undefined) {
p.catch(() => { playBrowserSpeech(); });
}
}
// Modern High-Fidelity Neural Speech Player (Unified Single Authentic Kurdish Voice)
function _playNeuralTTS(text, lang, options = {}) {
_stopSpeech();
let clean = (text || '').trim();
if (!clean) return;
const isKurdish = lang === 'ku' || (lang === 'auto' && /[\u0600-\u06FF]/.test(clean));
if (isKurdish) {
clean = normalizeKurdishNumbers(fixKurdishSoraniGreetings(clean));
// 100% Locked Native Kurdish Sorani Studio Voice with Velvet Silk DSP Filter
synthesizeNativeKurdishClient(clean, options.dialect || 'sorani').then(audioUrl => {
if (audioUrl) {
playSilkStudioAudio(audioUrl, {
filter: true,
onStart: options.onStart,
onEnd: () => {
if (options.onEnd) options.onEnd();
_stopSpeech();
}
});
return;
}
if (options.onEnd) options.onEnd();
}).catch(() => {
if (options.onEnd) options.onEnd();
});
return;
}
// English & other languages
_playViaServerTTS(clean, lang, options);
}
// Purged robotic fallbacks: Never use robotic scrapers or local system synthesizers
function _googleTTSPlay() {}
function _webSpeechLang() {}
// Dedicated Kurdish Acoustic Voice Engine with Advanced Syllable & Fluent Word Synthesis
const kurdishVoiceSynthesizer = {
speed: 1.0,
voiceMode: (typeof localStorage !== 'undefined' && localStorage.getItem('translet_kurdish_voice_mode')) || 'fatih',
isPlaying: false,
currentDialect: 'sorani', // 'sorani' or 'badini'
currentKurdishText: 'سڵاو، چۆنی؟ بەخێربێیت بۆ وەرگێڕی ترانسلێت.',
currentPodcastCategory: 'all',
// Massive, high-fidelity Kurdish Sorani Lexicon
phraseDictionarySorani: {
// Greetings & Courtesy
'سڵاو': 'Slaw', 'سلاو': 'Slaw', 'سڵاو چۆنی': 'Slaw çonî', 'سڵاو چۆنیت': 'Slaw çonît', 'سڵاو هاوڕێیان': 'Slaw hawrêyan', 'سڵاو لە هەمووان': 'Slaw le hemûwan', 'چۆنی': 'Çonî', 'چۆنیت': 'Çonît', 'باشی': 'Başî', 'باشم': 'Başim',
'سوپاس': 'Supas', 'زۆر': 'Zor', 'سوپاس بۆ تۆ': 'Supas bo to', 'دەستت خۆش': 'Destit xoş',
'دەستت خۆش بێت': 'Destit xoş bêt', 'دەستخۆش': 'Destxoş', 'بەخێربێیت': 'Bexêr bêyt',
'بەخێربێن': 'Bexêr bên', 'بەیانی باش': 'Beyanî baş', 'بەیانیت باش': 'Beyanît baş',
'شەو باش': 'Şew baş', 'شەوت باش': 'Şewt باش', 'ڕۆژ باش': 'Roj baş', 'ڕۆژت باش': 'Rojit باش',
'تکایە': 'Tkaye', 'بێ زەحمەت': 'Bê zehmet', 'بەڵێ': 'Belê', 'نەخێر': 'Nexêr', 'هیوادارم': 'Hîwadarim',
'زۆر باشە': 'Zor başe', 'ئازیزم': 'Azîzim', 'براکەم': 'Brakem', 'خوشکەکەم': 'Xîşkekem',
'خوشک': 'Xîşk', 'خوشکم': 'Xîşkim', 'بەڕێز': 'Berrêz', 'بەڕێزان': 'Berrêzan', 'بەڕێزم': 'Berrêzim',
'خواحافیز': 'Xwahafîz', 'ماڵئاوا': 'Malawa', 'بەخوا': 'Bexwa', 'خۆشحاڵم': 'Xoşhalim',
'ناوت چییە': 'Nawit çîye', 'تەمەنت چەندە': 'Tement çende', 'خۆشم دەوێیت': 'Xoşim dewêyt',
'بەسەرچاو': 'Beserçaw', 'سەرچاوان': 'Serçawan', 'قوربانت بم': 'Qurbanit bim', 'چاومی': 'Çawmî',
'پیرۆزبێت': 'Pîroz bêt', 'پیرۆزە': 'Pîroze', 'هیوام باشییە': 'Hîwam başîye',
'ماندوو نەبیت': 'Mandû nebît', 'سەرکەوتووبیت': 'Serkewtû bît', 'بێ خەم بە': 'Bê xem be',
// Days of the Week & Calendar
'شەممە': 'Şemme', 'یەکشەممە': 'Yekşemme', 'دووشەممە': 'Dûşemme',
'سێشەممە': 'Sêşemme', 'چوارشەممە': 'Çwarşemme', 'پێنجشەممە': 'Pêncşemme', 'هەینی': 'Heynî',
// Months (Gregorian & Kurdish Solar)
'کانوونی دووەم': 'Kanûnî dûwem', 'شوبات': 'Şubat', 'ئازار': 'Azar', 'نیسان': 'Nîsan',
'ئایار': 'Ayar', 'حوزەیران': 'Huzeyran', 'تەممووز': 'Temmûz', 'ئاب': 'Ab',
'ئەیلوول': 'Eylûl', 'تشرینی یەکەم': 'Tişrînî yekem', 'تشرینی دووەم': 'Tişrînî dûwem', 'کانوونی یەکەم': 'Kanûnî yekem',
'نەورۆز': 'Newroz', 'خاکەلێوە': 'Xakelêwe', 'گوڵان': 'Gulan', 'بانەمەڕ': 'Banemerr',
'جۆزەردان': 'Cozerdan', 'پووشپەڕ': 'Pûşperr', 'گەلاوێژ': 'Gelawêj', 'خەرمانان': 'Xermanan',
'ڕەزبەر': 'Rezber', 'خەزەڵوەر': 'Xezelwer', 'سەرماوەز': 'Sermawez', 'بەفرانبار': 'Befranbar',
'ڕێبەندان': 'Rêbendan', 'ڕەشەمێ': 'Reşemê',
// Numbers & Units
'سفر': 'Sifr', 'سفرە': 'Sifre', 'زیرۆ': 'Zîro', 'زیرۆیە': 'Zîroye', 'دوو سفر': 'Dû sifr', 'سێ سفر': 'Sê sifr', 'یەک': 'Yek', 'دوو': 'Dû', 'سێ': 'Sê', 'چوار': 'Çwar', 'پێنج': 'Pênc',
'شەش': 'Şeş', 'حەوت': 'Hewt', 'هەشت': 'Heşt', 'نۆ': 'No', 'دە': 'De',
'یازدە': 'Yazde', 'دوازدە': 'Dwazde', 'سێزدە': 'Sêzde', 'چواردە': 'Çwarde', 'پازدە': 'Pazde',
'شازدە': 'Şazde', 'حەڤدە': 'Hevde', 'هەژدە': 'Hejde', 'نۆزدە': 'Nozde', 'بیست': 'Bîst',
'سی': 'Sî', 'چل': 'Çil', 'پەنجا': 'Penca', 'شەست': 'Şest', 'حەفتا': 'Hefta', 'هەشتا': 'Heşta', 'نەوەد': 'Newed',
'سەد': 'Sed', 'دووسەد': 'Dûsed', 'سێسەد': 'Sêsed', 'چوارسەد': 'Çwarsed', 'پێنجسەد': 'Pêncsed',
'شەشسەد': 'Şeşsed', 'حەوتسەد': 'Hewtsed', 'هەشتسەد': 'Heştsed', 'نۆسەد': 'Nosed',
'هەزار': 'Hezar', 'ملیۆن': 'Milyon', 'ملیار': 'Milyar', 'سەد لە سەد': 'Sed le sed', 'لە سەد': 'Le sed',
'یەکەم': 'Yekem', 'دووەم': 'Dûwem', 'سێیەم': 'Sêyem', 'چوارەم': 'Çwarem', 'پێنجەم': 'Pêncem',
'خولەک': 'Xulek', 'سانیە': 'Sanye', 'چرکە': 'Çirke', 'کاتژمێر': 'Katjmêr', 'نیو': 'Nîw', 'چارەک': 'Çarek',
// Pronouns & Demonstratives
'من': 'Min', 'تۆ': 'To', 'ئەو': 'Ew', 'ئێمە': 'Ême', 'ئێوە': 'Êwe', 'ئەوان': 'Ewan',
'ئەمە': 'Eme', 'ئەوە': 'Ewe', 'ئەمانە': 'Emane', 'ئەوانە': 'Ewane', 'لێرە': 'Lêre', 'لەوێ': 'Lewê',
'هی من': 'Hî min', 'هی تۆ': 'Hî to', 'هی ئەو': 'Hî ew', 'هی ئێمە': 'Hî ême',
// Question Words
'کێ': 'Kê', 'کێیە': 'Kêye', 'کەی': 'Key', 'لەکوێ': 'Lêkwê', 'لەکوێیە': 'Lêkwêye',
'چۆن': 'Çon', 'چی': 'Çî', 'چییە': 'Çîye', 'بۆچی': 'Boçî', 'کامە': 'Kame', 'چەند': 'Çend',
'چەندە': 'Çende', 'بۆ کوێ': 'Bo kwê', 'لە کەیەوە': 'Le keyewe',
// Essential Verbs & Compounds
'دەمەوێت': 'Demewêt', 'دەمانەوێت': 'Demanewêt', 'دەتەوێت': 'Detewêt', 'دەیانەوێت': 'Deyanewêt',
'دەتوانم': 'Detwanim', 'دەتوانیت': 'Detwanît', 'دەتوانێت': 'Detwanêt', 'دەتوانین': 'Detwanîn',
'ناتوانم': 'Natwanim', 'ناتوانیت': 'Natwanît', 'دەزانم': 'Dezanim', 'نازانم': 'Nazanim',
'دەزانین': 'Dezanîn', 'تێدەگەم': 'Têdegem', 'تێناگەم': 'Tênagem', 'تێدەگەیت': 'Têdegeyt',
'دەچم': 'Deçim', 'دەچیت': 'Deçît', 'دەچێت': 'Deçêt', 'دەچین': 'Deçîn',
'دێم': 'Dêm', 'دێیت': 'Dêyt', 'دێت': 'Dêt', 'دێین': 'Dêyn', 'دێن': 'Dên',
'دەکەم': 'Dekem', 'دەکەیت': 'Dekeyt', 'دەکات': 'Dekat', 'دەکەین': 'Dekeyn', 'دەکەن': 'Deken',
'دەڵێم': 'Delêm', 'دەڵێیت': 'Delêyt', 'دەڵێت': 'Delêt', 'دەڵێین': 'Delêyn',
'دەبینم': 'Debînim', 'دەبینیت': 'Debînît', 'دەبینێت': 'Debînêt', 'دەبینین': 'Debînîn',
'دەبیستم': 'Debîstim', 'دەخوێنمەوە': 'Dexênimewe', 'دەخوێنم': 'Dexênim', 'دەخوێنێتەوە': 'Dexênêtewe',
'خوێندنەوە': 'Xêndinewe', 'خوێندن': 'Xêndin', 'خوێندەوار': 'Xêndewar', 'خوێنەر': 'Xêner',
'خوێن': 'Xên', 'دەنووسم': 'Denûsim', 'فێردەبم': 'Fêrdebim',
'فێردەبین': 'Fêrdebîn', 'دەڕۆم': 'Derrom', 'گەیشتم': 'Geyiştim', 'گەیشتین': 'Geyiştîn',
'پێویستە': 'Pêwîste', 'نابێت': 'Nabêt', 'دەبێت': 'Debêt', 'هەیە': 'Heye', 'نییە': 'Nîye',
'خەریکی چیت': 'Xerîkî çît', 'چی دەکەیت': 'Çî dekeyt', 'لەوانەیە': 'Lewaneye',
// Common Nouns, Education & Tech
'کتێب': 'Kitêb', 'کتێبە': 'Kitêbe', 'کتێبێک': 'Kitêbêk', 'مامۆستا': 'Mamosta',
'قوتابخانە': 'Qutabxane', 'قوتابی': 'Qutabî', 'زانکۆ': 'Zanko', 'خوێندکار': 'Xêndkar',
'وەرگێڕان': 'Wergeran', 'وەرگێڕانی': 'Wergeranî', 'پەنجەرە': 'Pencere', 'شارەوانی': 'Şarewanî',
'مرۆڤ': 'Mirov', 'مرۆڤایەتی': 'Mirovayetî', 'زمان': 'Ziman', 'زمانی': 'Zimanî', 'وڵات': 'Wilat', 'وڵاتی': 'Wilatî',
'گرنگ': 'Giring', 'هەڵبژاردن': 'Helbijardin', 'کۆمەڵگا': 'Komelga', 'تەواو': 'Tewaw', 'ژیان': 'Jiyan', 'ژیانی': 'Jiyanî', 'برا': 'Bira',
'خوشک': 'Xîşk', 'دڵ': 'Dil', 'دڵم': 'Dilim', 'دەست': 'Dest', 'دەستم': 'Destim',
'چاو': 'Çaw', 'چاوم': 'Çawim', 'ئاو': 'Aw', 'نان': 'Nan', 'کار': 'Kar', 'شار': 'Şar',
'ماڵ': 'Mal', 'خێزان': 'Xêzan', 'باوک': 'Bawk', 'دایک': 'Dayk', 'کوڕ': 'Kurr', 'کچ': 'Kiç',
'پۆدکاست': 'Podkast', 'دەنگ': 'Deng', 'دەنگساز': 'Dengsaz', 'پیت': 'Pît', 'وشە': 'Wişe',
'ڕستە': 'Riste', 'فەرهەنگ': 'Ferheng', 'پەیام': 'Peyam', 'وەڵام': 'Welam', 'پرسیار': 'Pirsiyar',
'هەواڵ': 'Hewal', 'تەکنەلۆژیا': 'Teknolociya', 'کۆمپیوتەر': 'Kompyuter', 'مۆبایل': 'Mobayl',
'ئینتەرنێت': 'Înetrnet', 'ژیری': 'Jîrî', 'ژیریی دەستکرد': 'Jîrîy destkird',
// Time & Calendar
'ئەمڕۆ': 'Emro', 'دوێنێ': 'Dwênê', 'بەیانی': 'Beyanî', 'نیوەڕۆ': 'Nîwero', 'ئێوارە': 'Êware',
'شەو': 'Şew', 'کات': 'Kat', 'کاتژمێر': 'Katjmêr', 'خولەک': 'Xulek', 'چرکە': 'Çirke',
'ڕۆژ': 'Roj', 'هەفتە': 'Hefte', 'مانگ': 'Mang', 'ساڵ': 'Sal', 'ئێستا': 'Êsta',
'پێشتر': 'Pêştir', 'دواتر': 'Dwatir', 'هەموو ڕۆژێک': 'Hemû rojêk',
// Adjectives & Qualities
'هەموو': 'Hemû', 'هەمووتان': 'Hemûtan', 'کەم': 'Kem', 'باش': 'Baş', 'خراپ': 'Xirap',
'گەورە': 'Gewre', 'بچووک': 'Biçûk', 'جوان': 'Ciwan', 'ناشرین': 'Naşrîn', 'ئاسان': 'Asan',
'قورس': 'Quris', 'نوێ': 'Nwê', 'کۆن': 'Kon', 'ڕاست': 'Rast', 'هەڵە': 'Hele',
'شیرین': 'Şîrîn', 'بەهێز': 'Behêz', 'ئارام': 'Aram', 'تەندروست': 'Tendirust', 'سەربەرز': 'Serberz',
'سەرکەوتوو': 'Serkewtû', 'دڵسۆز': 'Dilsöz', 'ئازاد': 'Azad', 'خۆشەویست': 'Xoşewîst',
// Geography & Kurdistan Cities
'کوردستان': 'Kurdistan', 'هەولێر': 'Hewlêr', 'سلێمانی': 'Silêmanî', 'کەرکووک': 'Kerkûk',
'هەڵەبجە': 'Helebce', 'دهۆک': 'Dihok', 'زاخۆ': 'Zaxo', 'مەهاباد': 'Mehabad', 'سنە': 'Sine',
'ورمێ': 'Urmê', 'قامیشلۆ': 'Qamişlo', 'کۆبانێ': 'Kobanê', 'ئامەد': 'Amed',
'چیا': 'Çiya', 'شاخ': 'Şax', 'ڕووبار': 'Rûbar', 'کانی': 'Kanî', 'دەشت': 'Deşt', 'سروشت': 'Sirişt',
// Vocabulary from Diwaxan Podcast (Awat Nasrulla - Brain, Mindset & Intelligence)
'ئاوات': 'Awat', 'نەسروڵا': 'Nesrulla', 'دیوەخان': 'Dîwexan', 'مامۆستا': 'Mamosta',
'مێشک': 'Mêşk', 'مێشکی': 'Mêşkî', 'مێشکت': 'Mêşkit', 'مێشکمان': 'Mêşkiman',
'زیرەک': 'Zîrek', 'زیرەکی': 'Zîrekî', 'زیرەکانە': 'Zîrekane', 'زیرەکتر': 'Zîrektir',
'تەرکیز': 'Terkîz', 'سەرنج': 'Serinc', 'ئاگایی': 'Agayî', 'هۆشپەرتی': 'Hoşpertî',
'یادگە': 'Yadge', 'یادگەی': 'Yadgey', 'بیرکردنەوە': 'Bîrkirdnewe', 'بیرمەندی': 'Bîrmendî',
'لۆژیکی': 'Lojîkî', 'ڕەخنەگرانە': 'Rexnegirane', 'شیکاری': 'Şîkarî',
'چارەسەر': 'Çareser', 'چارەسەرکردن': 'Çareserkirdin', 'چارەسەری': 'Çareserî',
'کێشە': 'Kêşe', 'کێشەکان': 'Kêşekan', 'کێشەکانت': 'Kêşekanit', 'ئاریشە': 'Arîşe',
'سندووق': 'Sindûq', 'داهێنان': 'Dahênan', 'داهێنەر': 'Dahêner', 'نوێگەری': 'Nwêgerî',
'نەرێنی': 'Nerênî', 'نەرێنیبوون': 'Nerênîbûn', 'ئەرێنی': 'Erênî', 'ئەرێنیبوون': 'Erênîbûn',
'بێهیوایی': 'Bêhîwayî', 'بێ هیوا': 'Bê hîwa', 'ئارامگری': 'Aramgirî', 'ئارامبە': 'Aram be',
'ئەزموون': 'Ezmun', 'مەعریفی': 'Me\'rifî', 'بۆماوەیی': 'Bomawayî', 'لێهاتوویی': 'Lêhatuwî',
'تواناکان': 'Twanakan', 'توانستی': 'Twanistî', 'پەروەردە': 'Perwerde', 'خۆگونجاندن': 'Xoguncandin',
'تێگەیشتن': 'Têgeyştin', 'قووڵ': 'Qûl', 'قووڵبوونەوە': 'Qûlbûnewe', 'بڕیاردان': 'Biryardan',
'بەربەست': 'Berbest', 'دەرفەت': 'Derfet', 'تەنگژە': 'Tengje', 'سەرکەوتوو': 'Serkewtû'
},
// Massive, high-fidelity Kurdish Badini Lexicon
phraseDictionaryBadini: {
'سلاڤ': 'Slav', 'سلاو': 'Slav', 'تو چاوانی': 'Tu çawanî', 'چاوانی': 'Çawanî', 'باشی': 'Başî', 'باشم': 'Başim',
'سپاس': 'Spas', 'گەلەک سپاس': 'Gelek spas', 'دەستێت تە خۆش': 'Destêt te xoş', 'دەستخۆش': 'Dastxoş',
'بخێرهاتی': 'Bixêr hatî', 'بخێربێن': 'Bixêr bên', 'سپێدە باش': 'Spêde باش', 'شەڤ باش': 'Şev باش',
'ڕۆژ باش': 'Roj باش', 'کوردستان': 'Kurdistan', 'دهۆک': 'Dihok', 'زاخۆ': 'Zaxo', 'کەرکووک': 'Kerkûk',
'ئامێدی': 'Amêdî', 'هیڤیدارم': 'Hîvîdarim', 'بەلێ': 'Belê', 'نەخێر': 'Nexêr', 'تو چ دکەی': 'Tu çi dikey',
'گەلەک باشە': 'Gelek باشە', 'ئەڤرۆ': 'Evro', 'دووهی': 'Duhî', 'سبەهی': 'Sbehî', 'برایێ من': 'Brayê min',
'خویشکا من': 'Xwîşka min', 'عەزیزی من': 'Ezîzê min', 'حەز ژ تە دکەم': 'Hez ji te dikem',
'ب خاترا تە': 'Bi xatira te', 'سەرکەفتی بی': 'Serkeftî bî', 'ناڤێ تە چییە': 'Navê te çîye',
'ئەز': 'Ez', 'تو': 'Tu', 'ئەو': 'Ew', 'ئەم': 'Em', 'هوون': 'Hûn', 'ئەڤە': 'Eve',
'وەلات': 'Welat', 'زمان': 'Ziman', 'مرۆڤ': 'Mirov', 'کتێب': 'Pirtûk', 'زانکۆ': 'Zanko',
'قوتابخانە': 'Xwendingeh', 'هەمی': 'Hemî', 'گەلەک': 'Gelek', 'کێم': 'Kêm', 'باش': 'Baş',
'نۆکە': 'Noke', 'ل کیڤە': 'Li kîve', 'چەوا': 'Çewa', 'چ': 'Çi', 'بۆچی': 'Boçî',
'ساخلەمی': 'Saxlemî', 'بەختەوەر': 'Bextewer', 'چیایێن بلند': 'Çiyayên bilind', 'باژێر': 'Bajêr',
// Diwaxan Badini terms
'مێشک': 'Mêşk', 'مێشکێ': 'Mêşkê', 'زیرەکی': 'Zîrekî', 'زیرەک': 'Zîrek',
'تەرکیز': 'Terkîz', 'سەرنج': 'Serinc', 'ئاگاداری': 'Agadarî', 'شیان': 'Şiyan',
'شیانێن': 'Şiyanên', 'هزرکرن': 'Hizirkirin', 'هزر': 'Hizir', 'ئاریشە': 'Arîşe',
'ئاریشەیێن': 'Arîşeyên', 'چارەسەری': 'Çareserî', 'چارەسەرکرن': 'Çareserkirin',
'داهێنان': 'Dahênan', 'دەلیڤە': 'Delîve', 'دەلیڤەیێن': 'Delîveyên', 'تەنگاڤی': 'Tengavî',
'پێشخستن': 'Pêşxistin', 'سەردەمیانە': 'Serdemiyane', 'بەختەوەری': 'Bextewerî'
},
// 9 Rich Sorani Podcasts and 8 Rich Badini Podcasts across 6 categories
podcastEpisodes: {
sorani: [
{
id: 'diwaxan_brain_intelligence',
timestampSeconds: 763,
title: 'نهێنییەکانی مێشک و کەسی زیرەک',
category: 'مێشک و زیرەکی',
desc: 'پۆدکاستی دیوەخان #218 لەگەڵ م. ئاوات نەسروڵا: چۆن مێشکی مرۆڤ و زیرەکی کار دەکەن؟',
text: 'مێشکی مرۆڤ گەورەترین و ئاڵۆزترین سەرمایەی ژیانە. زیرەکی تەنها بەهرەیەکی زگماکی نییە، بەڵکو لێهاتووییەکە کە دەتوانیت بە فێربوون و ڕاهێنانی بەردەوام بەهێزی بکەیت. کەسی زیرەک ئەو کەسەیە کە زوو فێردەبێت و توانای خۆگونجاندنی هەیە لەگەڵ گۆڕانکارییەکاندا.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'diwaxan_focus_attention',
timestampSeconds: 2115,
title: 'تەرکیز و سەرنج لە سەردەمی هۆشپەرتیدا',
category: 'مێشک و زیرەکی',
desc: 'م. ئاوات نەسروڵا دەربارەی ئاگایی و پاراستنی تەرکیز لە سەرقاڵی و شاشەی مۆبایل',
text: 'سەردەمی ئێستا سەردەمی هۆشپەرتی و سەرقاڵییە. بۆ ئەوەی لە خوێندن و کاردا بگەیتە ئەنجامی باڵا، پێویستت بە تەرکیز و ئاگایی قووڵە. هەموو ڕۆژێک چەند ساتێک تەرخان بکە بۆ بێدەنگی و دوورکەوتنەوە لە شاشەکان، تا زەینت ئارام بێتەوە و وزەی بیرکردنەوەت نوێ بێتەوە.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'diwaxan_memory_mastery',
timestampSeconds: 3098,
title: 'بەهێزکردنی یادگە و زەین',
category: 'مێشک و زیرەکی',
desc: 'نهێنییەکانی تۆمارکردنی زانیاری و ڕێگریکردن لە لەبیرچوونەوە بەپێی زانستی مێشک',
text: 'یادگە وەک ماسوولکەیەکە، تا زیاتر بەکاری بهێنیت بەهێزتر دەبێت. بۆ ئەوەی زانیارییەکانت لەبیر نەچێتەوە، پێویستە بە تێگەیشتن و بەستنەوە بە وێنەی مێشکیەوە فێرببیت، نەک بە لەبەرکردنی کوێرانە. خەوی ڕێک و خۆراکی تەندروست کۆڵەکەی سەرەکی بەهێزیی یادگەن.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'diwaxan_logic_critical',
timestampSeconds: 3400,
title: 'بیرکردنەوەی لۆژیکی و ڕەخنەگرانە',
category: 'مێشک و زیرەکی',
desc: 'چۆن ڕاستییەکان لە دەنگۆ جیا بکەینەوە و بڕیاری دروست و ژیرانە بدەین؟',
text: 'بیرکردنەوەی ڕەخنەگرانە واتە قبووڵنەکردنی هیچ بیرۆکەیەک بەبێ بەڵگە و شیکاری. کاتێک بە چاوی لێکۆڵینەوە لە کێشەکان دەڕوانیت، دەتوانیت هۆکارە بنەڕەتییەکان ببینی و بڕیاری لۆژیکی بدەیت. هەڵە کردن بەشێکە لە گەشتی گەیشتن بە زانست و ڕاستییەکان.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'diwaxan_problem_solving',
timestampSeconds: 4365,
title: 'چارەسەرکردنی کێشە و بیرکردنەوەی دەرەوەی سندووق',
category: 'مێشک و زیرەکی',
desc: 'ڕێگای داهێنەرانە بۆ شیکارکردنی تەنگژەکان و دۆزینەوەی دەرفەت لە ناویاندا',
text: 'کێشەکان بەربەست نین، بەڵکو هاندەرن بۆ بەکارهێنانی ژیری. کەسی سەرکەوتوو بە هەمان شێوازی باو بیر ناکاتەوە، بەڵکو لە دەرەوەی سندووق دەڕوانێت و بە داهێنانەوە چارەسەر دەدۆزێتەوە. لە ناخی هەر کێشەیەکدا دەرفەتێکی شاراوە هەیە بۆ گەشەکردن.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'diwaxan_mindset_growth',
timestampSeconds: 3240,
title: 'ڕەتکردنەوەی نەرێنیبوون و بێهیوایی',
category: 'مێشک و زیرەکی',
desc: 'بنیاتنانی عەقڵیەتی گەشەکردن، ئارامگری و گۆڕینی شکست بۆ سەرکەوتن',
text: 'نەرێنیبوون و بێهیوایی گەورەترین بەربەستن لە بەردەم تواناکانی مێشکی مرۆڤدا. بیرکردنەوەی ئەرێنی بە مانای پشتگوێخستنی واقیع نییە، بەڵکو بە مانای باوەڕبوونە بە توانا و دۆزینەوەی ڕێگەچارە لە هەموو بارودۆخێکدا. متمانە بەخۆت هەبێت، تۆ توانای گەورەت هەیە.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'sorani_welcome',
title: 'سڵاو و ناساندن (Sorani Welcome)',
category: 'گفتوگۆ',
desc: 'دەربڕینی سڵاو، چۆنیەتی و ناساندنی خود بە شێوازێکی زۆر پاراو',
text: 'سڵاو هاوڕێی ئازیز! بەخێربێیت بۆ ستۆدیۆی دەنگی سۆرانی لە ترانسلێت. هیوادارم هەموو کاتێک شاد و سەرفراز بیت.'
},
{
id: 'sorani_growth',
title: 'گەشەپێدانی خود و هێزی خەونەکان',
category: 'سەرکەوتن',
desc: 'چۆن متمانە بەخۆت بکەیت و هەموو ڕۆژێک هەنگاو بنێیت بەرەو ئامانجەکانت',
text: 'هەموو بەیانییەک دەرفەتێکی نوێیە بۆ فێربوون و هەنگاونان بەرەو خەونەکانت. ترسی شکست لە کۆڵ بنێ و بە باوەڕێکی بەهێزەوە دەست پێبکە. تۆ دەتوانیت سەرکەوتوو بیت.'
},
{
id: 'sorani_ai',
title: 'داهاتووی ژیریی دەستکرد و وەرگێڕان',
category: 'تەکنەلۆژیا',
desc: 'ڕوانینێک لەسەر شۆڕشی AI و چۆنیەتی فێربوونی مۆدێرن بە زمانی کوردی',
text: 'تەکنەلۆژیا و ژیریی دەستکرد جیهانیان گۆڕیوە. ئێستا دەتوانین لە چەند چرکەیەکدا پەیوەندی بە هەموو مرۆڤەکانی جیهانەوە بکەین و زمانەکان بە ئاسانی فێرببین.'
},
{
id: 'sorani_nature',
title: 'جوانییەکانی کوردستان و چیا سەرکەشەکان',
category: 'کولتوور',
desc: 'پیاسەیەک لەنێو دۆڵ و کانی و شاخە سەرکەشەکانی نیشتمان',
text: 'کوردستان نیشتمانی چیا سەرکەشەکان و کانییە سازگارەکانە. بەهار لە کوردستان دیمەنێکی بێ هاوتا دروست دەکات.'
},
{
id: 'sorani_erbil',
title: 'قەڵای هەولێر و مێژووی دێرین',
category: 'کولتوور',
desc: 'کۆنترین شوێنەواری زیندووی جیهان و شانازیی مێژووی کورد',
text: 'قەڵای دێرینی هەولێر یەکێکە لە کۆنترین شوێنەوارەکانی جیهان کە تا ئەمڕۆ ژیانی تێدا بەردەوام بووە. ئەم قەڵایە شایەتحاڵی سەدان سەردەمی مێژوویی و شارستانییەتی بەرزە.'
},
{
id: 'sorani_wisdom',
title: 'پەند و وتەی بەنرخی پێشینان',
category: 'پەند و شیعر',
desc: 'پەندەکانی پێشینان و فەلسەفەی دەوڵەمەندی کوردی سۆرانی',
text: 'پێشینان دەڵێن: تا سەر لەسەر شاخ بێت، بەفری بەسەرەوەیە. زانست و ڕەوشت گەورەترین سەرمایەی مرۆڤن لە ژیاندا.'
},
{
id: 'sorani_poetry',
title: 'شیعر و دێڕی نایابی شاعیرانی کورد',
category: 'پەند و شیعر',
desc: 'خوێندنەوەی هەستیاری شیعری نالی و مەحوی و گۆران',
text: 'شاعیرانی گەورەی کورد وەک نالی و مەحوی و گۆران، بە زمانێکی زۆر شیرین و هونەری باسی خۆشەویستی نیشتمان و مرۆڤایەتییان کردووە.'
},
{
id: 'sorani_health',
title: 'ئارامیی دەروونی و ژیانی تەندروست',
category: 'تەندروستی',
desc: 'چۆن ئارامی بە دەروونت بدەیت و هاوسەنگی جەستە بپارێزیت',
text: 'تەندروستی گەورەترین تاجە لەسەر سەری مرۆڤەکان. ڕۆژانە کاتێک بۆ هێمنی و وەرزش و پشوودان تەرخان بکە، چونکە جەستەی ساغ هۆشیاری و بەرهەمداریت زیاد دەکات.'
},
{
id: 'sorani_market',
title: 'دیالۆگی بازاڕ و قسەکردنی ڕۆژانە',
category: 'گفتوگۆ',
desc: 'ڕستە و پەیوەندییە کردارییەکانی بازاڕ و کڕین و فرۆشتن',
text: 'سڵاو کاکە گیان، نرخی ئەم کتێبە چەندە؟ بێ زەحمەت دانەیەکم لێی دەوێت. دەستت خۆش بێت و ڕزقت زۆر بێت، ڕۆژێکی پڕ لە بەرەکەتت هەبێت.'
}
],
badini: [
{
id: 'badini_diwaxan_brain',
timestampSeconds: 763,
title: 'نهێنییێن مێشکی و شیانێن زیرەکیێ',
category: 'مێشک و زیرەکی',
desc: 'پۆدکاستێ دیوەخان: چەوا مێشکێ مرۆڤی کار دکەت و ئاستێ زیرەکیێ بلند دبیت؟',
text: 'مێشکێ مرۆڤی مەزنترین سەرمایەیە. زیرەکی تنێ بەهرەیەکا زگماکی نینە، بەلکو شیانەکا مەزنە کو ب فێربوون و ڕاهێنانێن بەردەوام دهێتە پێشخستن. مرۆڤێ زیرەک ئەو کەسەیە یێ کو ب زوویی فێردبیت و خۆ دگەل پێشهاتان دگونجینیت.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'badini_diwaxan_problem',
timestampSeconds: 4365,
title: 'چارەسەرکرنا ئاریشان و هزرا نوی',
category: 'مێشک و زیرەکی',
desc: 'چەوا ل دەرڤەی سنۆران هزر بکەین و د ناڤ ئاریشان دا دەلیڤەیان ببینین؟',
text: 'ئاریشە نە ئاستەنگن، بەلکو پالپشتن بۆ بکارئینانا ژیریێ. کەسێ سەرکەفتی ب ئاوایەکێ سەردەمیانە و ل دەرڤەی سنۆران هزر دکەت و ب داهێنان چەوانیا چارەسەریێ دبینیت. د هەر تەنگاڤییەکێ دا دەلیڤەیەکا زێڕین یا هەی.',
youtubeUrl: 'https://www.youtube.com/watch?v=xpbffWvq_yc'
},
{
id: 'badini_welcome',
title: 'سلاڤ و نیاسین (Badini Greetings)',
category: 'گفتوگۆ',
desc: 'دەربڕینا سلاڤ و چاوانی و پەیڤێن ڕۆژانە ب بادینی',
text: 'سلاڤ هەڤالێ هێژا! بخێرهاتی بۆ ستۆدیۆیا دەنگێ کوردی بادینی ل ترانسلێت. هیڤیدارم هەردەم ساخ و سەلامەت بی.'
},
{
id: 'badini_success',
title: 'سەرکەفتن و هیڤیێن گەنجان',
category: 'سەرکەوتن',
desc: 'پەیامەکا بهێز بۆ گەنجان دا کو بگەهنە ئارمانجێن مەزن',
text: 'هیچ دەمەکێ دەست ژ خەونێن خۆ بەرنەدە. ئەڤرۆ دەستپێکەکا نوویە بۆ تە دا کو بشێی بگەهیە ئارمانجێن خۆ و ببەیە سەرمەشقەکێ باش بۆ جڤاکێ خۆ.'
},
{
id: 'badini_tech',
title: 'پێشکەفتنا تەکنەلۆژیا و زانستی',
category: 'تەکنەلۆژیا',
desc: 'چەوانیا بکارئینانا ژیرییا دەستکرد د فێربوونا زمانان دا',
text: 'تەکنەلۆژیا دەرگەهێن زانینێ بۆ مە هەمیا ڤەکرینە. فێربوونا زمانان و زیرەکیا دەستکرد دەلیڤێن مەزن بۆ پێشڤەچوونا مروڤاتیێ چێکرینە.'
},
{
id: 'badini_amedi',
title: 'کەلەها ئامێدیێ و دیرۆکا بادینان',
category: 'کولتوور',
desc: 'سەردانا باژێرێ ئەفسووناویێ ئامێدیێ ل سەر ملێ چیای',
text: 'باژێرێ ئەفسووناویێ ئامێدیێ ل سەر ملێ چیایەکی هاتیە ئاڤاکرن و دیرۆکەکا زۆر کەڤن و زەنگین هەیە. بادینان مەڵبەندێ فەرهەنگ و چیایێن بلندو سەرکەشن.'
},
{
id: 'badini_nature',
title: 'سروشت و چیایێن کوردستانێ',
category: 'کولتوور',
desc: 'ڕوانینەک ل سەر چیا و دولێن بادینان و کوردستانێ',
text: 'کوردستان وەلاتێ چیایێن بلندو کەسکاتییا جوانە. بهار ل دەڤەرا بەهدینان دیمەنەکێ گەلەک سەرسوڕهێنەر پێشکێش دکەت.'
},
{
id: 'badini_wisdom',
title: 'مەتەلۆک و گۆتنێن مەزنان',
category: 'پەند و شیعر',
desc: 'پەیڤ و گۆتنێن پێشینان ب شێوەزارێ بەهدینی',
text: 'مەزنان گۆتییە: دارا بەردار بەرێن وێ د شۆڕن. زانین و ڕێز مەزنترین سەرمایەنە د ژیانێ دا.'
},
{
id: 'badini_health',
title: 'ساخلەمی و ئارامییا دەروونی',
category: 'تەندروستی',
desc: 'پاراستنا تەندروستییا لەش و مێشکی بۆ ژیانەکا بەختەوەر',
text: 'ساخلەمییا لەش و مێشکی بنەمایێ بەختەوەریێ یە. پێدڤیە ئەم هەردەم گرنگیێ بدەینە وەرزشێ و خوارنا ساخلەم دا کو ژیانەکا ب هێز ببورینین.'
},
{
id: 'badini_market',
title: 'گۆتوبێژا بازاڕی و کارکرنێ',
category: 'گفتوگۆ',
desc: 'پەیڤێن بازاڕی و دگەل خەلکی ب شێوازەکێ ڕێزگر',
text: 'سلاڤ کاکێ من، حالێ تە چاوایە؟ بێ زەحمەت بهایێ ڤێ چەندە؟ دەستێت تە خۆش بن و کارێ تە ب بەرەکەت بیت، خودێ پێکڤە مە پاریزیت.'
}
]
},
// Set active dialect (Sorani vs Badini vs Kurmanji)
setDialect(dialect) {
if (dialect !== 'sorani' && dialect !== 'badini' && dialect !== 'kurmanji') return;
this.currentDialect = dialect;
this.stop();
document.querySelectorAll('.voice-dialect-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-dialect') === dialect);
});
const statusPill = document.getElementById('kurdishVoiceStatus');
const playLabel = document.getElementById('kurdishPlayLabel');
const modeLabel = this.voiceMode === 'female' ? 'ئافرەتانە' : (this.voiceMode === 'broadcast' ? 'ستۆدیۆ' : 'پیاوانە');
const dialectNames = {
sorani: { pill: `سۆرانی (${modeLabel})`, label: 'دەنگی سۆرانی', toast: 'سۆرانی (Sorani)' },
badini: { pill: `بادینی (${modeLabel})`, label: 'دەنگی بادینی', toast: 'بادینی (Badîni)' },
kurmanji: { pill: `کرمانجی (${modeLabel})`, label: 'دەنگی کرمانجی', toast: 'کرمانجی (Kurmancî)' }
};
const info = dialectNames[dialect] || dialectNames.sorani;
if (statusPill) statusPill.textContent = info.pill;
if (playLabel) playLabel.textContent = info.label;
// Adapt current text into target dialect
let currentText = '';
if (targetLangEl && targetLangEl.value === 'ku' && targetTextEl && targetTextEl.value.trim()) {
currentText = targetTextEl.value.trim();
} else if (sourceLangEl && sourceLangEl.value === 'ku' && sourceTextEl && sourceTextEl.value.trim()) {
currentText = sourceTextEl.value.trim();
} else if (this.currentKurdishText && this.currentKurdishText.trim()) {
currentText = this.currentKurdishText.trim();
}
if (currentText) {
if (dialect === 'badini') {
currentText = currentText
.replace(/چۆنی/g, 'چەوانی')
.replace(/چۆنن/g, 'چەوانن')
.replace(/بەخێربێیت/g, 'ب خێر هاتی')
.replace(/بەخێربێن/g, 'ب خێر هاتن')
.replace(/ئەمڕۆ/g, 'ئەڤرۆ')
.replace(/ئێستا/g, 'نوکە')
.replace(/زۆر/g, 'گەلەک')
.replace(/سوپاس/g, 'دەستخۆش')
.replace(/هەموو/g, 'هەمی');
} else if (dialect === 'kurmanji') {
currentText = currentText
.replace(/چۆنی/g, 'چاوانی')
.replace(/چۆنن/g, 'چەوانن')
.replace(/بەخێربێیت/g, 'ب خێر هاتی')
.replace(/بەخێربێن/g, 'ب خێر هاتن')
.replace(/ئەمڕۆ/g, 'ئیرۆ')
.replace(/ئێستا/g, 'نەها')
.replace(/زۆر/g, 'گەلەک')
.replace(/سوپاس/g, 'سپاس')
.replace(/هەموو/g, 'هەمی');
} else {
currentText = fixKurdishSoraniGreetings(currentText)
.replace(/چەوانی/g, 'چۆنی')
.replace(/چاوانی/g, 'چۆنی')
.replace(/ب خێر هاتی/g, 'بەخێربێیت')
.replace(/ب خێر هاتن/g, 'بەخێربێن')
.replace(/ئەڤرۆ/g, 'ئەمڕۆ')
.replace(/ئیرۆ/g, 'ئەمڕۆ')
.replace(/نوکە/g, 'ئێستا')
.replace(/نەها/g, 'ئێستا')
.replace(/دەستخۆش/g, 'سوپاس')
.replace(/سپاس/g, 'سوپاس')
.replace(/گەلەک/g, 'زۆر')
.replace(/هەمی/g, 'هەموو');
}
if (targetLangEl && targetLangEl.value === 'ku' && targetTextEl) {
targetTextEl.value = currentText;
}
this.currentKurdishText = currentText;
this.updatePhonetics(currentText);
} else {
currentText = dialect === 'badini' ? 'سلاڤ، چەوانی؟ ب خێر هاتی بۆ ترانسلێت.' : (dialect === 'kurmanji' ? 'سلاڤ، چاوانی؟ ب خێر هاتی بۆ ترانسلێت.' : 'سڵاو، چۆنی؟ بەخێربێیت بۆ ترانسلێت.');
if (targetTextEl) targetTextEl.value = currentText;
this.currentKurdishText = currentText;
this.updatePhonetics(currentText);
}
this.renderPodcasts(this.currentPodcastCategory);
showToast(`شێوەزاری دەنگ: ${info.toast}`, '🎙️');
// Immediately speak with new dialect so user hears it in real-time
this.speak(currentText);
},
// Set voice playback speed (0.8x, 1.0x, 1.2x, 1.5x) with instant real-time rate update
setSpeed(speedVal) {
const spd = parseFloat(speedVal) || 1.0;
this.speed = spd;
// Update active class on speed buttons
document.querySelectorAll('.voice-speed-btn').forEach(btn => {
btn.classList.toggle('active', parseFloat(btn.getAttribute('data-speed')) === spd);
});
// If audio is actively playing, immediately adjust playback rate in real time!
if (_ttsAudioEl) {
try {
_ttsAudioEl.playbackRate = spd;
} catch (_) {}
}
showToast(`خێرایی دەنگ گۆڕدرا بۆ: ${spd}x`, '⚡');
},
// Set Native Kurdish Narrator Voice (Fatih, Shahen, Giganet, Custom)
setVoiceMode(mode, autoPlay = true) {
let m = mode;
if (m === 'natural') m = 'fatih';
if (m === 'female') m = 'shahen';
if (m === 'broadcast') m = 'giganet';
const validModes = ['fatih', 'shahen', 'giganet', 'custom'];
if (!validModes.includes(m)) m = 'custom';
this.voiceMode = m;
try { localStorage.setItem('translet_kurdish_voice_mode', m); } catch(_) {}
this.stop();
document.querySelectorAll('.voice-mode-btn').forEach(btn => {
btn.classList.toggle('active', btn.getAttribute('data-mode') === m);
});
const modeLabels = {
fatih: 'فاتیح (بێژەری پەڕتووک لە سلێمانی)',
shahen: 'شاهێن (بێژەری خانمانەی سۆرانی)',
giganet: 'گیگانێت (ستۆدیۆی کوردستان)',
custom: 'دەنگی تایبەتیی خۆت (sample.wav)'
};
const modeName = modeLabels[m] || m;
const statusPill = document.getElementById('kurdishVoiceStatus');
if (statusPill) {
statusPill.textContent = (m === 'custom') ? `🎧 ${modeName}` : `🎙️ ${modeName}`;
}
if (!autoPlay) return;
showToast(`بێژەری ڕەسەن: ${modeName}`, (m === 'custom') ? '🎧' : '🎙️');
if (m === 'custom') {
fetch(`${API_BASE}/custom_voices/my_custom_voice.wav`, { method: 'HEAD' }).then(r => {
if (!r.ok) {
const modal = document.getElementById('nativeKurdishStudioModal');
if (modal) modal.classList.remove('hidden');
showToast('تکایە سەرەتا دەنگی خۆت لێرە تۆمار بکە', '🎙️');
} else {
this.speak();
}
}).catch(() => {
const modal = document.getElementById('nativeKurdishStudioModal');
if (modal) modal.classList.remove('hidden');
});
return;
}
this.speak();
},
// Advanced Syllable-Aware Morphological Word Formatter
formatWordForSpeech(rawWord, isBadini) {
if (!rawWord) return { display: '', acoustic: '' };
// Separate leading & trailing punctuation
const m = rawWord.match(/^([.,!?;:()[\]{}،؟؛"«»]*)(.*?)([.,!?;:()[\]{}،؟؛"«»]*)$/);
const prePunct = m ? m[1].replace(/[«]/g, '"') : '';
const clean = m ? m[2].trim() : rawWord.trim();
let postPunct = m ? m[3].replace(/[»]/g, '"') : '';
// Normalize Kurdish punctuation in postPunct
postPunct = postPunct.replace(/،/g, ',').replace(/؟/g, '?').replace(/؛/g, ';');
if (!clean) return { display: rawWord, acoustic: rawWord };
const dict = isBadini ? this.phraseDictionaryBadini : this.phraseDictionarySorani;
// 1. Direct lexicon match
if (dict[clean]) {
const disp = dict[clean];
const acous = this.toTurkishAcoustic(disp);
return { display: prePunct + disp + postPunct, acoustic: prePunct + acous + postPunct };
}
// 2. Isolated single conjunction 'و' (and)
if (clean === 'و') {
return { display: prePunct + 'u' + postPunct, acoustic: prePunct + 'u' + postPunct };
}
if (clean === 'لە') {
return { display: prePunct + 'le' + postPunct, acoustic: prePunct + 'le' + postPunct };
}
if (clean === 'بە') {
return { display: prePunct + 'be' + postPunct, acoustic: prePunct + 'be' + postPunct };
}
if (clean === 'بۆ') {
return { display: prePunct + 'bo' + postPunct, acoustic: prePunct + 'bo' + postPunct };
}
// If word is already in Latin script
if (isLatinText(clean)) {
const acous = this.toTurkishAcoustic(clean);
return { display: prePunct + clean + postPunct, acoustic: prePunct + acous + postPunct };
}
// 3. Morphological Stemming for Prefixes & Suffixes
let prefixDisp = '';
let prefixAcous = '';
let stem = clean;
if (stem.startsWith('دە') && stem.length >= 4) {
prefixDisp = 'de-';
prefixAcous = 'de ';
stem = stem.slice(2);
} else if (stem.startsWith('نا') && stem.length >= 4) {
prefixDisp = 'na-';
prefixAcous = 'na ';
stem = stem.slice(2);
} else if (stem.startsWith('بێ') && stem.length >= 4) {
prefixDisp = 'bê-';
prefixAcous = 'be ';
stem = stem.slice(2);
}
// Check if stem exists in dictionary
let stemDisp = '';
let stemAcous = '';
if (dict[stem]) {
stemDisp = dict[stem];
stemAcous = this.toTurkishAcoustic(stemDisp);
} else {
// 4. Rule-based Kurdish Hawar transliteration
let s = stem;
// Assign W and Y glides
// Kurdish initial 'و' before vowels is pronounced [w] / [v]
s = s.replace(/^و([اەێۆوی])/g, 'v$1');
s = s.replace(/([اەێۆوی])و([اەێۆوی])/g, '$1w$2');
s = s.replace(/([اەێۆوی])و$/g, '$1w');
s = s.replace(/^و/g, 'w');
s = s.replace(/^ی([اەێۆوی])/g, 'y$1');
s = s.replace(/([اەێۆوی])ی([اەێۆوی])/g, '$1y$2');
s = s.replace(/([اەێۆوی])ی$/g, '$1y');
// Vowels
s = s.replace(/وو/g, 'û').replace(/ۆ/g, 'o').replace(/ێ/g, 'ê').replace(/ە/g, 'e');
s = s.replace(/و/g, 'u').replace(/ی/g, 'î').replace(/ا/g, 'a');
// Consonants
s = s.replace(/پ/g, 'p').replace(/چ/g, 'ç').replace(/ژ/g, 'j').replace(/گ/g, 'g');
s = s.replace(/ڤ/g, 'v').replace(/ش/g, 'ş').replace(/ج/g, 'c').replace(/ڵ/g, 'l');
s = s.replace(/ڕ/g, 'r').replace(/خ/g, 'x').replace(/غ/g, 'x').replace(/ق/g, 'q');
s = s.replace(/ع/g, 'a').replace(/ح/g, 'h').replace(/ط/g, 't').replace(/ص/g, 's');
s = s.replace(/ض/g, 'z').replace(/ظ/g, 'z').replace(/ذ/g, 'z').replace(/ث/g, 's');
s = s.replace(/ئ/g, '').replace(/ء/g, '').replace(/ب/g, 'b').replace(/ت/g, 't');
s = s.replace(/د/g, 'd').replace(/ر/g, 'r').replace(/ز/g, 'z').replace(/س/g, 's');
s = s.replace(/ف/g, 'f').replace(/ک/g, 'k').replace(/ل/g, 'l').replace(/م/g, 'm');
s = s.replace(/ن/g, 'n').replace(/ه/g, 'h');
const consonants = 'bcçdfghjklmnpqrstvwxz';
const vowels = 'aeêiîouû';
// Epenthetic short vowel insertion
if (s.length >= 2 && consonants.includes(s[0]) && consonants.includes(s[1])) {
s = s[0] + 'i' + s.slice(1);
}
if (![...s].some(c => vowels.includes(c))) {
if (s.length === 2) {
s = s[0] + 'i' + s[1];
} else if (s.length >= 3) {
s = s[0] + 'i' + s.slice(1, -1) + 'i' + s.slice(-1);
}
}
if (s.length >= 3 && s.endsWith('m') && consonants.includes(s[s.length - 2])) {
s = s.slice(0, -1) + 'im';
}
stemDisp = s;
stemAcous = this.toTurkishAcoustic(s);
}
const fullDisp = prePunct + prefixDisp + stemDisp + postPunct;
const fullAcous = prePunct + prefixAcous + stemAcous + postPunct;
return { display: fullDisp, acoustic: fullAcous };
},
// Converts Kurdish Latin into 100% Valid Turkish Native Acoustic Phonemes (ZERO spell-out mode)
toTurkishAcoustic(latWord) {
if (!latWord) return '';
let s = latWord.toLowerCase();
// In Turkish, 'v' matches Kurdish 'w' smoothly
s = s.replace(/w/g, 'v');
// In Turkish, 'h' matches Kurdish 'x' clearly
s = s.replace(/x/g, 'h');
// In Turkish, 'k' matches Kurdish 'q' clearly
s = s.replace(/q/g, 'k');
// Map circumflex vowels to clean Turkish plain vowels
s = s.replace(/ê/g, 'e').replace(/î/g, 'i').replace(/û/g, 'u').replace(/é/g, 'e');
// Remove apostrophes
s = s.replace(/['’]/g, '');
return s;
},
// Convert full Kurdish sentence into Display Phonetics and Fluent Acoustic Audio Stream
toAcousticStream(text, dialect = this.currentDialect) {
if (!text || !text.trim()) return { acousticText: '', displayPhonetic: '' };
const raw = normalizeKurdishNumbers(text.trim());
const isBadini = dialect === 'badini';
// Normalize punctuation
let normalized = raw.replace(/،/g, ' , ').replace(/؟/g, ' ? ').replace(/؛/g, ' ; ');
normalized = normalized.replace(/[«»]/g, '"').replace(/ـ/g, '');
const words = normalized.split(/\s+/).filter(Boolean);
const displayList = [];
const acousticList = [];
for (const w of words) {
const res = this.formatWordForSpeech(w, isBadini);
if (res.display) displayList.push(res.display);
if (res.acoustic) acousticList.push(res.acoustic);
}
// Clean up spaces before punctuation
let display = displayList.join(' ').replace(/\s+([.,!?;:])/g, '$1');
let acoustic = acousticList.join(' ').replace(/\s+([.,!?;:])/g, '$1');
if (display) {
display = display.charAt(0).toUpperCase() + display.slice(1);
}
return { acousticText: acoustic, displayPhonetic: `[${display}]` };
},
// Update Voice Bar & Phonetic Card with current text
updatePhonetics(text) {
if (!text || !text.trim()) return;
this.currentKurdishText = text.trim();
const { displayPhonetic } = this.toAcousticStream(this.currentKurdishText, this.currentDialect);
const phoneticEl = document.getElementById('kurdishPhoneticText');
if (phoneticEl) {
phoneticEl.textContent = displayPhonetic || `[${this.currentKurdishText}]`;
}
const voiceBar = document.getElementById('kurdishVoiceBar');
if (voiceBar) {
voiceBar.style.display = 'flex';
}
},
// Multi-chunk Audio Queue for long podcasts and paragraphs
audioQueue: [],
queueIndex: 0,
// High-Definition Unified Native Kurdish Voice Player (Single Authentic Voice)
speak(text) {
this.stop();
let clean = (text || this.currentKurdishText || '').trim();
if (!clean) {
showToast('تکایە دەقێک بنووسە بۆ خوێندنەوە', '⚠️');
return;
}
clean = normalizeKurdishNumbers(fixKurdishSoraniGreetings(clean));
this.currentKurdishText = clean;
const { displayPhonetic } = this.toAcousticStream(clean, this.currentDialect);
const phoneticEl = document.getElementById('kurdishPhoneticText');
if (phoneticEl) {
phoneticEl.textContent = displayPhonetic;
}
const voiceBar = document.getElementById('kurdishVoiceBar');
const playLabel = document.getElementById('kurdishPlayLabel');
const playIcon = document.getElementById('kurdishPlayIcon');
const statusPill = document.getElementById('kurdishVoiceStatus');
this.isPlaying = true;
if (voiceBar) voiceBar.classList.add('playing');
if (playLabel) playLabel.textContent = 'وەستان';
if (playIcon) {
playIcon.innerHTML = '<rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect>';
}
if (statusPill) statusPill.textContent = '🎙️ دەنگی سەرەکی: کوردیی سۆرانی (ڕەسەن)';
showToast('خوێندنەوە بە دەنگی ڕەسەنی کوردی...', '🎙️');
_playNeuralTTS(clean, 'ku', {
dialect: this.currentDialect || 'sorani',
speed: this.speed || 1.0,
onStart: () => {},
onEnd: () => { this.stop(); }
});
},
// Play next chunk using Unified Single Authentic Voice
playNextNeuralQueueItem() {
if (!this.isPlaying || this.queueIndex >= this.audioQueue.length) {
this.stop();
return;
}
const item = this.audioQueue[this.queueIndex];
let didAdvance = false;
const advance = () => {
if (didAdvance) return;
didAdvance = true;
this.queueIndex++;
setTimeout(() => {
if (this.isPlaying) this.playNextNeuralQueueItem();
}, 240);
};
_playNeuralTTS(item.raw, 'ku', {
dialect: this.currentDialect || 'sorani',
speed: this.speed || 1.0,
onStart: () => {},
onEnd: () => { advance(); }
});
},
playNextQueueItem() {
this.playNextNeuralQueueItem();
},
// Stop Kurdish Studio playback and clear queue
stop() {
_stopSpeech();
this.isPlaying = false;
this.audioQueue = [];
this.queueIndex = 0;
const isBadini = this.currentDialect === 'badini';
const voiceBar = document.getElementById('kurdishVoiceBar');
const playLabel = document.getElementById('kurdishPlayLabel');
const playIcon = document.getElementById('kurdishPlayIcon');
const statusPill = document.getElementById('kurdishVoiceStatus');
const modeLabel = this.voiceMode === 'female' ? 'ئافرەتانە' : (this.voiceMode === 'broadcast' ? 'ستۆدیۆ' : 'پیاوانە');
if (voiceBar) voiceBar.classList.remove('playing');
if (statusPill) statusPill.textContent = `${isBadini ? 'بادینی' : 'سۆرانی'} (${modeLabel})`;
if (playLabel) playLabel.textContent = isBadini ? 'دەنگی بادینی' : 'دەنگی سۆرانی';
if (playIcon) {
playIcon.innerHTML = '<polygon points="5 3 19 12 5 21 5 3"></polygon>';
}
},
// Render Podcast Cards for the active dialect and category
renderPodcasts(categoryFilter = this.currentPodcastCategory || 'all') {
this.currentPodcastCategory = categoryFilter;
const listEl = document.getElementById('kurdishPodcastList');
if (!listEl) return;
const episodes = this.podcastEpisodes[this.currentDialect] || this.podcastEpisodes.sorani;
// Filter episodes
const filtered = episodes.filter(ep => {
if (categoryFilter === 'all') return true;
if (ep.category === categoryFilter) return true;
if (categoryFilter === 'پەند و شیعر' && (ep.category === 'پەند' || ep.category === 'شیعر')) return true;
return false;
});
if (filtered.length === 0) {
listEl.innerHTML = `<div style="grid-column: 1/-1; text-align: center; color: var(--text-dim); padding: 20px;">هیچ پۆدکاستێک لەم بەشەدا نییە.</div>`;
return;
}
listEl.innerHTML = filtered.map(ep => `
<div class="podcast-item" data-id="${ep.id}">
<div class="podcast-item-head">
<span class="podcast-item-title">${ep.title}</span>
<span class="podcast-badge">${ep.category}</span>
</div>
<p class="podcast-item-desc">${ep.desc}</p>
<div class="podcast-item-actions">
<button class="podcast-action-btn play" data-text="${ep.text.replace(/"/g, '"')}" title="گوێگرتن بە دەنگ">
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>
<span>گوێگرتن</span>
</button>
<button class="podcast-action-btn load" data-text="${ep.text.replace(/"/g, '"')}" title="دانان لە وەرگێڕ">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>
<span>خستنە وەرگێڕ</span>
</button>
${ep.timestampSeconds ? `
<button class="podcast-action-btn real-audio" data-timestamp="${ep.timestampSeconds}" data-title="${ep.title.replace(/"/g, '"')}" data-text="${ep.text.replace(/"/g, '"')}" title="گوێگرتن لە دەنگی ڕاستەقینەی م. ئاوات لە پۆدکاستەکە">
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm-2 14.5v-9l6 4.5z"/></svg>
<span>دەنگی ڕاستەقینە</span>
</button>` : ''}
${ep.youtubeUrl ? `
<a href="${ep.youtubeUrl}" target="_blank" rel="noopener noreferrer" class="podcast-action-btn youtube" title="سەیرکردنی ئەم ئەڵقەیە لە یوتیوب">
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>
<span>یوتیوب</span>
</a>` : ''}
</div>
</div>
`).join('');
// Attach listeners
listEl.querySelectorAll('.podcast-action-btn.play').forEach(btn => {
btn.addEventListener('click', () => {
const txt = btn.getAttribute('data-text');
targetTextEl.value = txt;
targetLangEl.value = 'ku';
this.updatePhonetics(txt);
this.speak(txt);
});
});
listEl.querySelectorAll('.podcast-action-btn.load').forEach(btn => {
btn.addEventListener('click', () => {
const txt = btn.getAttribute('data-text');
sourceTextEl.value = txt;
sourceLangEl.value = 'ku';
targetLangEl.value = 'en';
charCountEl.textContent = txt.length;
this.updatePhonetics(txt);
performTranslation();
showToast('پۆدکاستەکە خرایە نێو وەرگێڕ', '📥');
});
});
// Real Human Audio Player Modal Handler
listEl.querySelectorAll('.podcast-action-btn.real-audio').forEach(btn => {
btn.addEventListener('click', () => {
const timestamp = btn.getAttribute('data-timestamp') || '0';
const title = btn.getAttribute('data-title') || 'دەنگی ڕاستەقینەی پۆدکاست';
const quote = btn.getAttribute('data-text') || '';
const modal = document.getElementById('realPodcastModal');
const iframe = document.getElementById('realPodcastIframe');
const modalTitle = document.getElementById('realPodcastModalTitle');
const quoteEl = document.getElementById('realPodcastQuote');
if (modal && iframe) {
modalTitle.textContent = title;
quoteEl.textContent = `«${quote}»`;
iframe.src = `https://www.youtube-nocookie.com/embed/xpbffWvq_yc?start=${timestamp}&autoplay=1`;
modal.classList.remove('hidden');
showToast('دەنگی ڕاستەقینەی پۆدکاست دەستیپێکرد', '🎙️');
}
});
});
}
};
/* ─── Public entry: called from speak buttons ─── */
function speakText(text, lang) {
const clean = (text || '').trim();
if (!clean) return;
// Check if Kurdish: explicit 'ku', or 'auto' with Kurdish characters
const isKurdish = lang === 'ku' || (lang === 'auto' && (
/[\u0600-\u06FF]/.test(clean) && !isLatinText(clean) ||
/^[a-zA-Zçşêîûéöä\s'-]+$/i.test(clean) && (targetLangEl.value === 'ku' || sourceLangEl.value === 'ku')
));
if (isKurdish || lang === 'ku') {
kurdishVoiceSynthesizer.speak(clean);
return;
}
// All other languages: High-definition Single Neural Voice
showToast('خوێندنەوەی دەنگ...', '🎙️');
_playNeuralTTS(clean, lang, {
speed: kurdishVoiceSynthesizer ? kurdishVoiceSynthesizer.speed : 1.0
});
}
// Setup Event Listeners
function setupEventListeners() {
// Input Character Counter & Direction
sourceTextEl.addEventListener('input', () => {
const val = sourceTextEl.value.trim();
charCountEl.textContent = sourceTextEl.value.length;
updateTextDirection(sourceTextEl, sourceLangEl.value);
clearTimeout(window.autoTranslateTimer);
// If source input is empty, immediately clear the translated box!
if (!val) {
targetTextEl.value = '';
targetStatusMessage.textContent = 'ئامادەیە';
if (explanationCard) explanationCard.classList.add('hidden');
return;
}
// Auto translate after 500ms pause if length >= 2
if (val.length >= 2) {
window.autoTranslateTimer = setTimeout(performTranslation, 500);
}
});
// Enter to translate
sourceTextEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
clearTimeout(window.autoTranslateTimer);
performTranslation();
}
});
// Main Translate Button
translateActionBtn.addEventListener('click', () => {
clearTimeout(window.autoTranslateTimer);
performTranslation();
});
// Swap Languages
swapLanguagesBtn.addEventListener('click', () => {
playSubtleClick();
const prevSrc = sourceLangEl.value === 'auto' ? 'ku' : sourceLangEl.value;
const prevTgt = targetLangEl.value;
const prevSrcText = sourceTextEl.value;
const prevTgtText = targetTextEl.value;
sourceLangEl.value = prevTgt;
targetLangEl.value = prevSrc;
sourceTextEl.value = prevTgtText;
targetTextEl.value = prevSrcText;
charCountEl.textContent = sourceTextEl.value.length;
updateTextDirection(sourceTextEl, sourceLangEl.value);
updateTextDirection(targetTextEl, targetLangEl.value);
});
// Clear Source Text
clearSourceBtn.addEventListener('click', () => {
sourceTextEl.value = '';
targetTextEl.value = '';
charCountEl.textContent = '0';
targetStatusMessage.textContent = 'ئامادەیە';
explanationCard.classList.add('hidden');
sourceTextEl.focus();
});
// Copy Buttons
copySourceBtn.addEventListener('click', async () => {
if (!sourceTextEl.value) return;
await navigator.clipboard.writeText(sourceTextEl.value);
showToast('دەقی سەرەکی کۆپی کرا', '✅');
});
copyTargetBtn.addEventListener('click', async () => {
if (!targetTextEl.value) return;
await navigator.clipboard.writeText(targetTextEl.value);
showToast('وەرگێڕانەکە کۆپی کرا', '✅');
});
// Kurdish Transliterate button (toggle Latin <-> Arabic script on the source text)
kurdishTransliterateBtn.addEventListener('click', () => {
playSubtleClick();
const current = sourceTextEl.value;
if (!current.trim()) return;
if (isLatinText(current)) {
sourceTextEl.value = kurdishTransliteration.toArabic(current);
showToast('گۆڕدرا بۆ پیتی عەرەبی (سۆرانی)', '🔄');
} else {
sourceTextEl.value = kurdishTransliteration.toLatin(current);
showToast('گۆڕدرا بۆ پیتی لاتینی', '🔄');
}
updateTextDirection(sourceTextEl, sourceLangEl.value);
});
// Global toggle Kurdish Latin button on header
toggleKurdishLatinBtn.addEventListener('click', () => {
playSubtleClick();
if (state.kurdishScript === 'arabic') {
state.kurdishScript = 'latin';
scriptBadgeText.textContent = 'Kurdî (Latînî)';
showToast('مۆدی پیتی لاتینی هەڵبژێردرا', '🔤');
} else {
state.kurdishScript = 'arabic';
scriptBadgeText.textContent = 'کوردی (سۆرانی)';
showToast('مۆدی پیتی عەرەبی سۆرانی هەڵبژێردرا', '🔤');
}
});
// Tone Chips
document.querySelectorAll('.tone-chip').forEach(btn => {
btn.addEventListener('click', () => {
playSubtleClick();
document.querySelectorAll('.tone-chip').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
state.currentTone = btn.getAttribute('data-tone');
showToast(`شێوازی دەربڕین گۆڕدرا بۆ: ${btn.textContent}`, '✨');
// If source has text, immediately perform translation with this tone!
if (sourceTextEl.value.trim()) {
performTranslation();
} else if (targetTextEl.value.trim()) {
// If user already had text in output, adapt it on the fly!
const styled = applyToneStyling(targetTextEl.value, targetLangEl.value, state.currentTone);
targetTextEl.value = styled.text;
const targetContainer = targetTextEl.closest('.textarea-container');
if (targetContainer) {
targetContainer.classList.remove('tone-pulse');
void targetContainer.offsetWidth;
targetContainer.classList.add('tone-pulse');
}
}
});
});
// Speech Buttons
speakSourceBtn.addEventListener('click', () => {
if (sourceTextEl.value.trim()) {
speakText(sourceTextEl.value, sourceLangEl.value);
}
});
speakTargetBtn.addEventListener('click', () => {
if (targetTextEl.value.trim()) {
speakText(targetTextEl.value, targetLangEl.value);
}
});
// Kurdish Voice Studio Play / Pause Button
const kurdishPlayBtn = document.getElementById('kurdishVoicePlayBtn');
if (kurdishPlayBtn) {
kurdishPlayBtn.addEventListener('click', () => {
if (kurdishVoiceSynthesizer.isPlaying) {
kurdishVoiceSynthesizer.stop();
} else {
// Choose best Kurdish text: target if Kurdish, else source if Kurdish, else whatever text exists
let textToPlay = '';
if (targetLangEl.value === 'ku' && targetTextEl.value.trim()) {
textToPlay = targetTextEl.value.trim();
} else if (sourceLangEl.value === 'ku' && sourceTextEl.value.trim()) {
textToPlay = sourceTextEl.value.trim();
} else if (targetTextEl.value.trim()) {
textToPlay = targetTextEl.value.trim();
} else if (sourceTextEl.value.trim()) {
textToPlay = sourceTextEl.value.trim();
} else {
// Play default friendly Kurdish sentence
textToPlay = 'سڵاو هاوڕێی ئازیز! بەخێربێیت بۆ ستۆدیۆی دەنگی کوردی لە ترانسلێت.';
targetTextEl.value = textToPlay;
}
kurdishVoiceSynthesizer.speak(textToPlay);
}
});
}
// Kurdish Voice Dialect Switcher (Sorani vs Badini)
document.querySelectorAll('.voice-dialect-btn').forEach(btn => {
btn.addEventListener('click', () => {
const dialect = btn.getAttribute('data-dialect');
if (dialect && typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setDialect(dialect);
}
});
});
// Voice Speed Buttons (0.8x, 1.0x, 1.2x, 1.5x)
document.querySelectorAll('.voice-speed-btn').forEach(btn => {
btn.addEventListener('click', () => {
const spd = parseFloat(btn.getAttribute('data-speed')) || 1.0;
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setSpeed(spd);
}
});
});
// Initialize Kurdish Voice Mode to user custom voice without auto-playing
const initialVoiceMode = (typeof localStorage !== 'undefined' && localStorage.getItem('translet_kurdish_voice_mode')) || 'fatih';
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setVoiceMode('fatih', false);
}
// Voice Reading Mode Buttons (Natural vs Broadcast)
document.querySelectorAll('.voice-mode-btn').forEach(btn => {
btn.addEventListener('click', () => {
const mode = btn.getAttribute('data-mode');
if (mode && typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setVoiceMode(mode);
}
});
});
// Toggle Phonetic Guide Card
const togglePhoneticBtn = document.getElementById('togglePhoneticBtn');
const kurdishPhoneticCard = document.getElementById('kurdishPhoneticCard');
if (togglePhoneticBtn && kurdishPhoneticCard) {
togglePhoneticBtn.addEventListener('click', () => {
kurdishPhoneticCard.classList.toggle('hidden');
togglePhoneticBtn.classList.toggle('active');
});
}
// Copy Phonetic Text
const copyPhoneticBtn = document.getElementById('copyPhoneticBtn');
const kurdishPhoneticText = document.getElementById('kurdishPhoneticText');
if (copyPhoneticBtn && kurdishPhoneticText) {
copyPhoneticBtn.addEventListener('click', async () => {
const val = kurdishPhoneticText.textContent;
if (val) {
await navigator.clipboard.writeText(val);
showToast('دەنگسازی فۆنەتیک کۆپی کرا', '✅');
}
});
}
// Kurdish Podcast Toggle & Close
const kurdishPodcastBtn = document.getElementById('kurdishPodcastBtn');
const kurdishPodcastCard = document.getElementById('kurdishPodcastCard');
const closePodcastBtn = document.getElementById('closePodcastBtn');
if (kurdishPodcastBtn && kurdishPodcastCard) {
kurdishPodcastBtn.addEventListener('click', () => {
kurdishPodcastCard.classList.toggle('hidden');
kurdishPodcastBtn.classList.toggle('active');
if (!kurdishPodcastCard.classList.contains('hidden')) {
kurdishVoiceSynthesizer.renderPodcasts();
}
});
}
if (closePodcastBtn && kurdishPodcastCard) {
closePodcastBtn.addEventListener('click', () => {
kurdishPodcastCard.classList.add('hidden');
if (kurdishPodcastBtn) kurdishPodcastBtn.classList.remove('active');
});
}
// Kurdish Podcast Category Filters
const podcastFilterChips = document.querySelectorAll('.podcast-filter-chip');
if (podcastFilterChips.length > 0) {
podcastFilterChips.forEach(chip => {
chip.addEventListener('click', () => {
podcastFilterChips.forEach(c => c.classList.remove('active'));
chip.classList.add('active');
const cat = chip.getAttribute('data-category') || 'all';
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.renderPodcasts(cat);
}
});
});
}
// Real Podcast Modal Close Handlers
const realPodcastModal = document.getElementById('realPodcastModal');
const closeRealPodcastModalBtn = document.getElementById('closeRealPodcastModalBtn');
const closeRealPodcastFooterBtn = document.getElementById('closeRealPodcastFooterBtn');
const realPodcastIframe = document.getElementById('realPodcastIframe');
const closeRealPodcast = () => {
if (realPodcastModal) realPodcastModal.classList.add('hidden');
if (realPodcastIframe) realPodcastIframe.src = '';
};
if (closeRealPodcastModalBtn) closeRealPodcastModalBtn.addEventListener('click', closeRealPodcast);
if (closeRealPodcastFooterBtn) closeRealPodcastFooterBtn.addEventListener('click', closeRealPodcast);
if (realPodcastModal) {
realPodcastModal.addEventListener('click', (e) => {
if (e.target === realPodcastModal) closeRealPodcast();
});
}
// Voice A/B Comparison Modal Handlers
const voiceCompareModal = document.getElementById('voiceCompareModal');
const openVoiceCompareBtn = document.getElementById('openVoiceCompareBtn');
const closeVoiceCompareModalBtn = document.getElementById('closeVoiceCompareModalBtn');
const closeVoiceCompareFooterBtn = document.getElementById('closeVoiceCompareFooterBtn');
let _compareAudioEl = null;
const closeVoiceCompare = () => {
if (voiceCompareModal) voiceCompareModal.classList.add('hidden');
if (_compareAudioEl) {
try { _compareAudioEl.pause(); } catch (_) {}
_compareAudioEl = null;
}
document.querySelectorAll('.compare-play-btn').forEach(b => b.classList.remove('playing'));
};
if (openVoiceCompareBtn) {
openVoiceCompareBtn.addEventListener('click', () => {
if (voiceCompareModal) voiceCompareModal.classList.remove('hidden');
});
}
if (closeVoiceCompareModalBtn) closeVoiceCompareModalBtn.addEventListener('click', closeVoiceCompare);
if (closeVoiceCompareFooterBtn) closeVoiceCompareFooterBtn.addEventListener('click', closeVoiceCompare);
if (voiceCompareModal) {
voiceCompareModal.addEventListener('click', (e) => {
if (e.target === voiceCompareModal) closeVoiceCompare();
});
}
// Play Sample A vs Sample B buttons
document.querySelectorAll('.compare-play-btn').forEach(btn => {
btn.addEventListener('click', () => {
const src = btn.getAttribute('data-src');
if (!src) return;
if (_compareAudioEl) {
try { _compareAudioEl.pause(); } catch (_) {}
}
document.querySelectorAll('.compare-play-btn').forEach(b => b.classList.remove('playing'));
btn.classList.add('playing');
const startComparePlay = (el) => {
_compareAudioEl = el;
_compareAudioEl.onended = () => {
btn.classList.remove('playing');
};
_compareAudioEl.onerror = () => {
btn.classList.remove('playing');
showToast('نەتوانرا فایلی دەنگ لێبدرێت', '⚠️');
};
_compareAudioEl.play().catch(() => {
btn.classList.remove('playing');
});
};
fetch(src).then(r => r.blob()).then(blob => {
startComparePlay(new Audio(URL.createObjectURL(blob)));
}).catch(() => {
startComparePlay(new Audio(src));
});});
});
// --- ElevenLabs AI Voice Management & Modal ---
const elevenLabsModal = document.getElementById('elevenLabsModal');
const openElevenLabsBtn = document.getElementById('openElevenLabsBtn');
const closeElevenLabsBtn = document.getElementById('closeElevenLabsBtn');
const closeElevenLabsFooterBtn = document.getElementById('closeElevenLabsFooterBtn');
const elevenLabsEnableToggle = document.getElementById('elevenLabsEnableToggle');
const elevenLabsApiKeyInput = document.getElementById('elevenLabsApiKeyInput');
const testElevenLabsKeyBtn = document.getElementById('testElevenLabsKeyBtn');
const elevenLabsKeyStatus = document.getElementById('elevenLabsKeyStatus');
const elevenLabsCustomVoiceId = document.getElementById('elevenLabsCustomVoiceId');
const saveElevenLabsBtn = document.getElementById('saveElevenLabsBtn');
const testElevenLabsAudioBtn = document.getElementById('testElevenLabsAudioBtn');
const elevenLabsBadge = document.getElementById('elevenLabsBadge');
let _elevenTestAudioEl = null;
function updateElevenLabsBadgeUI() {
const isEnabled = localStorage.getItem('elevenlabs_enabled') === 'true';
const hasKey = !!(localStorage.getItem('elevenlabs_api_key') || '').trim();
if (elevenLabsBadge) {
if (isEnabled && hasKey) {
elevenLabsBadge.textContent = 'AI 🟢';
if (openElevenLabsBtn) openElevenLabsBtn.classList.add('active');
} else {
elevenLabsBadge.textContent = 'خۆڕایی';
if (openElevenLabsBtn) openElevenLabsBtn.classList.remove('active');
}
}
}
function syncElevenLabsFormFromStorage() {
const isEnabled = localStorage.getItem('elevenlabs_enabled') === 'true';
const apiKey = localStorage.getItem('elevenlabs_api_key') || '';
const voiceId = localStorage.getItem('elevenlabs_voice_id') || 'pNInz6obpgDQGcFmaJgB';
const customId = localStorage.getItem('elevenlabs_custom_voice_id') || '';
if (elevenLabsEnableToggle) elevenLabsEnableToggle.checked = isEnabled;
if (elevenLabsApiKeyInput) elevenLabsApiKeyInput.value = apiKey;
if (elevenLabsCustomVoiceId) elevenLabsCustomVoiceId.value = customId;
document.querySelectorAll('.eleven-voice-option').forEach(opt => {
opt.classList.toggle('active', opt.getAttribute('data-voice-id') === voiceId);
});
const toggleCard = document.querySelector('.ai-engine-toggle-card');
if (toggleCard) toggleCard.classList.toggle('active', isEnabled);
}
updateElevenLabsBadgeUI();
if (openElevenLabsBtn) {
openElevenLabsBtn.addEventListener('click', () => {
syncElevenLabsFormFromStorage();
if (elevenLabsKeyStatus) elevenLabsKeyStatus.textContent = '';
if (elevenLabsModal) elevenLabsModal.classList.remove('hidden');
});
}
const closeElevenLabs = () => {
if (elevenLabsModal) elevenLabsModal.classList.add('hidden');
if (_elevenTestAudioEl) {
try { _elevenTestAudioEl.pause(); } catch (_) {}
_elevenTestAudioEl = null;
}
};
if (closeElevenLabsBtn) closeElevenLabsBtn.addEventListener('click', closeElevenLabs);
if (closeElevenLabsFooterBtn) closeElevenLabsFooterBtn.addEventListener('click', closeElevenLabs);
if (elevenLabsModal) {
elevenLabsModal.addEventListener('click', (e) => {
if (e.target === elevenLabsModal) closeElevenLabs();
});
}
if (elevenLabsEnableToggle) {
elevenLabsEnableToggle.addEventListener('change', () => {
const toggleCard = document.querySelector('.ai-engine-toggle-card');
if (toggleCard) toggleCard.classList.toggle('active', elevenLabsEnableToggle.checked);
});
}
// Voice card selection
document.querySelectorAll('.eleven-voice-option').forEach(opt => {
opt.addEventListener('click', () => {
document.querySelectorAll('.eleven-voice-option').forEach(o => o.classList.remove('active'));
opt.classList.add('active');
});
});
// Verify API Key
if (testElevenLabsKeyBtn) {
testElevenLabsKeyBtn.addEventListener('click', async () => {
const key = (elevenLabsApiKeyInput ? elevenLabsApiKeyInput.value : '').trim();
if (!key) {
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = '❌ تکایە سەرەتا کلیلی API بنووسە';
elevenLabsKeyStatus.style.color = '#ef4444';
}
return;
}
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = '⏳ لە پشکنیندایە...';
elevenLabsKeyStatus.style.color = '#f59e0b';
}
try {
const res = await fetch(`/api/elevenlabs/verify?api_key=${encodeURIComponent(key)}`);
const data = await res.json();
if (data.valid) {
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = `✅ کلیلەکە تەواوە و چالاکە! (پلان: ${data.tier || 'Free'}, بەکارهاتوو: ${data.character_count || 0})`;
elevenLabsKeyStatus.style.color = '#22c55e';
}
} else {
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = `❌ کلیلەکە دروست نییە یان هەڵەیە: ${data.error || 'پەیوەندی بەستن سەرکەوتوو نەبوو'}`;
elevenLabsKeyStatus.style.color = '#ef4444';
}
}
} catch (err) {
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = `❌ هەڵە لە پشکنین: ${err.message}`;
elevenLabsKeyStatus.style.color = '#ef4444';
}
}
});
}
// Save Settings
if (saveElevenLabsBtn) {
saveElevenLabsBtn.addEventListener('click', () => {
const isEnabled = elevenLabsEnableToggle ? elevenLabsEnableToggle.checked : false;
const key = (elevenLabsApiKeyInput ? elevenLabsApiKeyInput.value : '').trim();
const customId = (elevenLabsCustomVoiceId ? elevenLabsCustomVoiceId.value : '').trim();
const activeVoiceOpt = document.querySelector('.eleven-voice-option.active');
const selectedVoiceId = customId || (activeVoiceOpt ? activeVoiceOpt.getAttribute('data-voice-id') : 'pNInz6obpgDQGcFmaJgB');
if (isEnabled && !key) {
if (elevenLabsKeyStatus) {
elevenLabsKeyStatus.textContent = '⚠️ تکایە کلیلی API بنووسە بۆ چالاککردن';
elevenLabsKeyStatus.style.color = '#f59e0b';
}
return;
}
localStorage.setItem('elevenlabs_enabled', isEnabled ? 'true' : 'false');
localStorage.setItem('elevenlabs_api_key', key);
localStorage.setItem('elevenlabs_voice_id', selectedVoiceId);
localStorage.setItem('elevenlabs_custom_voice_id', customId);
updateElevenLabsBadgeUI();
closeElevenLabs();
showToast(isEnabled ? '✨ دەنگی مرۆڤانەی ElevenLabs AI چالاک کرا!' : 'دەنگی Edge Neural وەک پێشوازی هەڵبژێردرا', '✨');
});
}
// Test Sample Audio
if (testElevenLabsAudioBtn) {
testElevenLabsAudioBtn.addEventListener('click', () => {
const key = (elevenLabsApiKeyInput ? elevenLabsApiKeyInput.value : '').trim();
const customId = (elevenLabsCustomVoiceId ? elevenLabsCustomVoiceId.value : '').trim();
const activeVoiceOpt = document.querySelector('.eleven-voice-option.active');
const selectedVoiceId = customId || (activeVoiceOpt ? activeVoiceOpt.getAttribute('data-voice-id') : 'pNInz6obpgDQGcFmaJgB');
const testPhrase = 'خوشکە بەڕێزەکەم، سڵاو و دەستخۆشی خوێندنەوەی ئەم کتێبە جوانەت لێ دەکەم، مرۆڤ بە زانست پێش دەکەوێت.';
const params = new URLSearchParams({
text: testPhrase,
lang: 'ku',
mode: 'natural',
dialect: 'sorani',
_t: Date.now().toString()
});
if (key) {
params.append('provider', 'elevenlabs');
params.append('api_key', key);
params.append('voice_id', selectedVoiceId);
}
if (_elevenTestAudioEl) {
try { _elevenTestAudioEl.pause(); } catch (_) {}
}
testElevenLabsAudioBtn.disabled = true;
testElevenLabsAudioBtn.style.opacity = '0.6';
_elevenTestAudioEl = new Audio(`${API_BASE}/api/tts?${params.toString()}`);
_elevenTestAudioEl.onended = () => {
testElevenLabsAudioBtn.disabled = false;
testElevenLabsAudioBtn.style.opacity = '1';
};
_elevenTestAudioEl.onerror = () => {
testElevenLabsAudioBtn.disabled = false;
testElevenLabsAudioBtn.style.opacity = '1';
showToast('هەڵە لە دروستکردنی دەنگی تاقیکاری', '⚠️');
};
_elevenTestAudioEl.play().catch(() => {
testElevenLabsAudioBtn.disabled = false;
testElevenLabsAudioBtn.style.opacity = '1';
});
});
}
// Gemini AI Neural Voice Studio Modal Handlers
const openGeminiVoiceBtn = document.getElementById('openGeminiVoiceBtn');
const closeGeminiVoiceBtn = document.getElementById('closeGeminiVoiceBtn');
const geminiVoiceModal = document.getElementById('geminiVoiceModal');
const testGeminiVoiceAudioBtn = document.getElementById('testGeminiVoiceAudioBtn');
let _geminiTestAudioEl = null;
if (openGeminiVoiceBtn && geminiVoiceModal) {
openGeminiVoiceBtn.addEventListener('click', () => {
geminiVoiceModal.classList.remove('hidden');
const savedVoice = localStorage.getItem('translet_gemini_voice') || 'Puck';
document.querySelectorAll('.gemini-voice-option').forEach(opt => {
if (opt.getAttribute('data-voice-id') === savedVoice) {
opt.classList.add('active');
} else {
opt.classList.remove('active');
}
});
});
if (closeGeminiVoiceBtn) {
closeGeminiVoiceBtn.addEventListener('click', () => {
geminiVoiceModal.classList.add('hidden');
if (_geminiTestAudioEl) {
_geminiTestAudioEl.pause();
_geminiTestAudioEl = null;
}
});
}
geminiVoiceModal.addEventListener('click', (e) => {
if (e.target === geminiVoiceModal) {
geminiVoiceModal.classList.add('hidden');
if (_geminiTestAudioEl) {
_geminiTestAudioEl.pause();
_geminiTestAudioEl = null;
}
}
});
const defaultTestBtnHtml = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>
<span>گوێگرتن لە دەنگ</span>
`;
const resetTestBtn = () => {
if (testGeminiVoiceAudioBtn) {
testGeminiVoiceAudioBtn.disabled = false;
testGeminiVoiceAudioBtn.style.opacity = '1';
testGeminiVoiceAudioBtn.innerHTML = defaultTestBtnHtml;
}
};
// Voice card selection
document.querySelectorAll('.gemini-voice-option').forEach(opt => {
opt.addEventListener('click', () => {
if (_geminiTestAudioEl) {
try { _geminiTestAudioEl.pause(); } catch (_) {}
_geminiTestAudioEl = null;
resetTestBtn();
}
document.querySelectorAll('.gemini-voice-option').forEach(o => o.classList.remove('active'));
opt.classList.add('active');
const voiceId = opt.getAttribute('data-voice-id');
localStorage.setItem('translet_gemini_voice', voiceId);
showToast(`دەنگی ${voiceId} بۆ Gemini هەڵبژێردرا`, '🎙️');
});
});
// Test Audio Button
if (testGeminiVoiceAudioBtn) {
testGeminiVoiceAudioBtn.addEventListener('click', () => {
// Toggle: If currently playing, pause and stop
if (_geminiTestAudioEl && !_geminiTestAudioEl.paused) {
try { _geminiTestAudioEl.pause(); } catch (_) {}
_geminiTestAudioEl = null;
resetTestBtn();
return;
}
const activeOpt = document.querySelector('.gemini-voice-option.active');
const voiceId = activeOpt ? activeOpt.getAttribute('data-voice-id') : 'Puck';
const sampleText = 'سڵاو! بەخێربێن بۆ ئەپڵیکەیشنی ترانسلێت، پێشکەوتووترین وەرگێڕی زمانی کوردی.';
testGeminiVoiceAudioBtn.disabled = false;
testGeminiVoiceAudioBtn.innerHTML = `
<svg class="mini-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10" stroke-opacity="0.25"></circle>
<path d="M12 2a10 10 0 0 1 10 10" stroke-linecap="round"></path>
</svg>
<span>لە ئامادەکردندایە...</span>
`;
const params = new URLSearchParams({
text: sampleText,
lang: 'ku',
mode: 'natural',
dialect: 'sorani',
provider: 'gemini',
voice_id: voiceId,
gemini_key: state.apiKey || DEFAULT_GEMINI_API_KEY,
_t: Date.now().toString()
});
if (_geminiTestAudioEl) {
try { _geminiTestAudioEl.pause(); } catch (_) {}
_geminiTestAudioEl = null;
}
// Create Audio synchronously in user gesture
const audio = new Audio(`${API_BASE}/api/tts?` + params.toString());
_geminiTestAudioEl = audio;
audio.onplaying = () => {
testGeminiVoiceAudioBtn.innerHTML = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
<rect x="6" y="4" width="4" height="16"></rect>
<rect x="14" y="4" width="4" height="16"></rect>
</svg>
<span>وەستاندن</span>
`;
showToast(`دەنگی ${voiceId} لێدەدرێت...`, '🎙️');
};
audio.onended = () => {
resetTestBtn();
};
audio.onerror = () => {
// If direct audio element streaming failed, try fetch blob fallback
fetch(`${API_BASE}/api/tts?` + params.toString())
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.blob();
})
.then(blob => {
const blobUrl = URL.createObjectURL(blob);
const fallbackAudio = new Audio(blobUrl);
_geminiTestAudioEl = fallbackAudio;
fallbackAudio.onended = () => {
URL.revokeObjectURL(blobUrl);
resetTestBtn();
};
fallbackAudio.play().catch(() => resetTestBtn());
})
.catch(() => {
resetTestBtn();
showToast('هەڵە لە وەرگرتنی دەنگ لە Gemini', '⚠️');
});
};
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch(err => {
console.warn('Direct play error:', err);
// Fallback to fetch blob
fetch(`${API_BASE}/api/tts?` + params.toString())
.then(r => r.blob())
.then(b => {
const u = URL.createObjectURL(b);
const a2 = new Audio(u);
_geminiTestAudioEl = a2;
a2.onended = () => { URL.revokeObjectURL(u); resetTestBtn(); };
a2.play().catch(() => resetTestBtn());
})
.catch(() => {
resetTestBtn();
showToast('هەڵە لە وەرگرتنی دەنگ لە Gemini', '⚠️');
});
});
}
});
}
}
// Native Kurdish Studio Modal & Voice Recording Handlers
const openNativeKurdishStudioBtn = document.getElementById('openNativeKurdishStudioBtn');
const closeNativeStudioBtn = document.getElementById('closeNativeStudioBtn');
const nativeKurdishStudioModal = document.getElementById('nativeKurdishStudioModal');
let _nativeSampleAudio = null;
let _mediaRecorder = null;
let _audioChunks = [];
let _recordTimerInterval = null;
let _recordedAudioBlob = null;
let _recordedAudioPreview = null;
if (openNativeKurdishStudioBtn && nativeKurdishStudioModal) {
openNativeKurdishStudioBtn.addEventListener('click', () => {
nativeKurdishStudioModal.classList.remove('hidden');
});
const stopAllStudioAudio = () => {
if (_nativeSampleAudio) {
_nativeSampleAudio.pause();
_nativeSampleAudio = null;
}
if (_recordedAudioPreview) {
_recordedAudioPreview.pause();
_recordedAudioPreview = null;
}
document.querySelectorAll('.play-sample-btn').forEach(btn => {
const orig = btn.getAttribute('data-original-label');
if (orig) btn.innerHTML = orig;
});
};
if (closeNativeStudioBtn) {
closeNativeStudioBtn.addEventListener('click', () => {
nativeKurdishStudioModal.classList.add('hidden');
stopAllStudioAudio();
});
}
nativeKurdishStudioModal.addEventListener('click', (e) => {
if (e.target === nativeKurdishStudioModal) {
nativeKurdishStudioModal.classList.add('hidden');
stopAllStudioAudio();
}
});
// Select active narrator buttons
document.querySelectorAll('.select-active-narrator-btn').forEach(btn => {
btn.addEventListener('click', () => {
const narrator = btn.getAttribute('data-narrator');
if (narrator && typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setVoiceMode(narrator);
nativeKurdishStudioModal.classList.add('hidden');
stopAllStudioAudio();
}
});
});
// Sample audio audition buttons (Fatih, Shahen, Giganet)
document.querySelectorAll('.play-sample-btn').forEach(btn => {
if (!btn.getAttribute('data-original-label')) {
btn.setAttribute('data-original-label', btn.innerHTML.trim());
}
btn.addEventListener('click', () => {
const url = btn.getAttribute('data-url');
if (!url) return;
if (_nativeSampleAudio && _nativeSampleAudio.src.endsWith(url) && !_nativeSampleAudio.paused) {
_nativeSampleAudio.pause();
btn.innerHTML = btn.getAttribute('data-original-label');
return;
}
stopAllStudioAudio();
btn.innerHTML = '⏸️ وەستاندن';
fetch(url).then(r => r.blob()).then(blob => {
const blobUrl = URL.createObjectURL(blob);
_nativeSampleAudio = new Audio(blobUrl);
_nativeSampleAudio.onended = () => {
btn.innerHTML = btn.getAttribute('data-original-label');
};
_nativeSampleAudio.onerror = () => {
btn.innerHTML = btn.getAttribute('data-original-label');
showToast('نەتوانرا فایلی دەنگ لێبدرێت', '⚠️');
};
_nativeSampleAudio.play().catch(e => {
btn.innerHTML = btn.getAttribute('data-original-label');
console.error(e);
});
}).catch(() => {
_nativeSampleAudio = new Audio(url);
_nativeSampleAudio.onended = () => {
btn.innerHTML = btn.getAttribute('data-original-label');
};
_nativeSampleAudio.onerror = () => {
btn.innerHTML = btn.getAttribute('data-original-label');
showToast('نەتوانرا فایلی دەنگ لێبدرێت', '⚠️');
};
_nativeSampleAudio.play().catch(e => {
btn.innerHTML = btn.getAttribute('data-original-label');
console.error(e);
});
});});
});
// Recording custom Kurdish voice
const startRecordBtn = document.getElementById('startRecordBtn');
const stopRecordBtn = document.getElementById('stopRecordBtn');
const playRecordBtn = document.getElementById('playRecordBtn');
const saveRecordBtn = document.getElementById('saveRecordBtn');
const recordingTimer = document.getElementById('recordingTimer');
const recordingStatusMsg = document.getElementById('recordingStatusMsg');
const uploadVoiceFileInput = document.getElementById('uploadVoiceFileInput');
if (startRecordBtn && stopRecordBtn) {
startRecordBtn.addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
_audioChunks = [];
_mediaRecorder = new MediaRecorder(stream);
_mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
_audioChunks.push(event.data);
}
};
_mediaRecorder.onstop = () => {
_recordedAudioBlob = new Blob(_audioChunks, { type: 'audio/wav' });
if (playRecordBtn) playRecordBtn.disabled = false;
if (saveRecordBtn) saveRecordBtn.disabled = false;
if (recordingStatusMsg) {
recordingStatusMsg.textContent = 'دەنگەکەت تۆمارکرا! دەتوانیت گوێی لێبگریتەوە یان پاشەکەوتی بکەیت.';
recordingStatusMsg.style.color = '#4ade80';
}
stream.getTracks().forEach(track => track.stop());
};
_mediaRecorder.start();
startRecordBtn.disabled = true;
startRecordBtn.style.opacity = '0.5';
stopRecordBtn.disabled = false;
stopRecordBtn.style.opacity = '1';
if (playRecordBtn) playRecordBtn.disabled = true;
if (saveRecordBtn) saveRecordBtn.disabled = true;
let seconds = 0;
if (recordingTimer) recordingTimer.textContent = '00:00';
clearInterval(_recordTimerInterval);
_recordTimerInterval = setInterval(() => {
seconds++;
const mins = String(Math.floor(seconds / 60)).padStart(2, '0');
const secs = String(seconds % 60).padStart(2, '0');
if (recordingTimer) recordingTimer.textContent = `${mins}:${secs}`;
}, 1000);
if (recordingStatusMsg) {
recordingStatusMsg.textContent = '🎙️ لە تۆمارکردندایە... تکایە دەقەکە بە دەنگی بەرز بخوێنەوە.';
recordingStatusMsg.style.color = '#f87171';
}
} catch (err) {
console.error(err);
showToast('مایکرۆفۆن پەسەند نەکرا یان بەردەست نییە', '⚠️');
}
});
stopRecordBtn.addEventListener('click', () => {
if (_mediaRecorder && _mediaRecorder.state !== 'inactive') {
_mediaRecorder.stop();
}
clearInterval(_recordTimerInterval);
startRecordBtn.disabled = false;
startRecordBtn.style.opacity = '1';
stopRecordBtn.disabled = true;
stopRecordBtn.style.opacity = '0.5';
});
if (playRecordBtn) {
// Auto-detect existing custom voice
fetch(`${API_BASE}/custom_voices/my_custom_voice.wav`, { method: 'HEAD' }).then(r => {
if (r.ok) {
playRecordBtn.disabled = false;
playRecordBtn.style.opacity = '1';
if (recordingStatusMsg) {
recordingStatusMsg.textContent = '✅ فایلی دەنگی تایبەتیت (sample.wav) بە سەرکەوتوویی ئامادەیە.';
recordingStatusMsg.style.color = '#4ade80';
}
}
}).catch(() => {});
playRecordBtn.addEventListener('click', () => {
if (_recordedAudioPreview) {
_recordedAudioPreview.pause();
}
let audioUrl;
if (_recordedAudioBlob) {
audioUrl = URL.createObjectURL(_recordedAudioBlob);
} else {
audioUrl = `${API_BASE}/custom_voices/my_custom_voice.wav?_t=${Date.now()}`;
}
_recordedAudioPreview = new Audio(audioUrl);
_recordedAudioPreview.play().catch(e => console.error(e));
playRecordBtn.textContent = '🔊 لە لێداندایە...';
_recordedAudioPreview.onended = () => {
playRecordBtn.textContent = '🔊 گوێگرتنەوە';
};
_recordedAudioPreview.onerror = () => {
playRecordBtn.textContent = '🔊 گوێگرتنەوە';
showToast('نەتوانرا دەنگ لێبدرێت', '⚠️');
};
});
}
if (saveRecordBtn) {
saveRecordBtn.addEventListener('click', async () => {
if (!_recordedAudioBlob) return;
saveRecordBtn.disabled = true;
saveRecordBtn.textContent = 'لە پاشەکەوتکردندایە...';
try {
const formData = new FormData();
formData.append('audio', _recordedAudioBlob, 'my_custom_voice.wav');
const res = await fetch('/api/voice/upload', {
method: 'POST',
body: formData
});
if (res.ok) {
if (recordingStatusMsg) {
recordingStatusMsg.textContent = '✨ دەنگەکەت بە سەرکەوتوویی وەک دەنگی تایبەتی پاشەکەوت کرا!';
recordingStatusMsg.style.color = '#38bdf8';
}
showToast('دەنگی کوردیی تایبەتیت پاشەکەوت کرا و کرا بە دەنگی سەرەکی!', '🎙️');
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.setVoiceMode('custom');
}
} else {
throw new Error('Upload failed');
}
} catch (err) {
console.error(err);
if (recordingStatusMsg) {
recordingStatusMsg.textContent = 'نەتوانرا دەنگەکە پاشەکەوت بکرێت.';
recordingStatusMsg.style.color = '#f87171';
}
showToast('هەڵە لە پاشەکەوتکردنی دەنگ', '⚠️');
} finally {
saveRecordBtn.disabled = false;
saveRecordBtn.textContent = '💾 پاشەکەوتکردن';
}
});
}
if (uploadVoiceFileInput) {
uploadVoiceFileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
if (recordingStatusMsg) {
recordingStatusMsg.textContent = `لە بارکردنی ${file.name}...`;
recordingStatusMsg.style.color = '#fbbf24';
}
try {
const formData = new FormData();
formData.append('audio', file, file.name);
const res = await fetch('/api/voice/upload', {
method: 'POST',
body: formData
});
if (res.ok) {
if (recordingStatusMsg) {
recordingStatusMsg.textContent = `✨ فایلی ${file.name} وەک دەنگی تایبەتی چالاک کرا!`;
recordingStatusMsg.style.color = '#38bdf8';
}
showToast('فایلی دەنگ بە سەرکەوتوویی چالاک کرا!', '🎉');
} else {
throw new Error('File upload failed');
}
} catch (err) {
console.error(err);
if (recordingStatusMsg) {
recordingStatusMsg.textContent = 'هەڵە لە بارکردنی فایلی دەنگ.';
recordingStatusMsg.style.color = '#f87171';
}
showToast('هەڵە لە بارکردنی فایل', '⚠️');
}
});
}
}
}
// Explanation Card Toggles
showExplanationBtn.addEventListener('click', () => {
explanationCard.classList.toggle('hidden');
});
closeExplanationBtn.addEventListener('click', () => {
explanationCard.classList.add('hidden');
});
// Quick Examples
document.querySelectorAll('.example-chip').forEach(chip => {
chip.addEventListener('click', () => {
sourceLangEl.value = chip.getAttribute('data-source');
targetLangEl.value = chip.getAttribute('data-target');
sourceTextEl.value = chip.getAttribute('data-text');
charCountEl.textContent = sourceTextEl.value.length;
updateTextDirection(sourceTextEl, sourceLangEl.value);
updateTextDirection(targetTextEl, targetLangEl.value);
performTranslation();
});
});
// Language selects
sourceLangEl.addEventListener('change', () => {
updateTextDirection(sourceTextEl, sourceLangEl.value);
});
targetLangEl.addEventListener('change', () => {
updateTextDirection(targetTextEl, targetLangEl.value);
});
// Clear History
clearHistoryBtn.addEventListener('click', () => {
if (confirm('دڵنیایت لە سڕینەوەی هەموو مێژووی وەرگێڕانەکانت؟')) {
state.history = [];
localStorage.removeItem('translet_history');
renderHistory();
showToast('مێژوو سڕایەوە', '🗑️');
}
});
// Settings Modal Handlers
openSettingsBtn.addEventListener('click', () => {
geminiApiKeyInput.value = state.apiKey;
geminiModelSelect.value = state.model;
apiTestResult.classList.add('hidden');
settingsModal.classList.remove('hidden');
});
closeSettingsBtn.addEventListener('click', () => {
settingsModal.classList.add('hidden');
});
settingsModal.addEventListener('click', (e) => {
if (e.target === settingsModal) {
settingsModal.classList.add('hidden');
}
});
saveApiKeyBtn.addEventListener('click', () => {
state.apiKey = geminiApiKeyInput.value.trim();
state.model = geminiModelSelect.value;
localStorage.setItem('translet_gemini_api_key', state.apiKey);
localStorage.setItem('translet_gemini_model', state.model);
updateEngineStatus();
settingsModal.classList.add('hidden');
showToast('ڕێکخستنەکانی جێمینای پاشەکەوت کران', '💾');
});
testApiKeyBtn.addEventListener('click', async () => {
const key = geminiApiKeyInput.value.trim();
const model = geminiModelSelect.value;
if (!key) {
apiTestResult.className = 'api-test-box error';
apiTestResult.textContent = 'تکایە کلیلێک بنووسە بۆ تاقیکردنەوە.';
apiTestResult.classList.remove('hidden');
return;
}
testApiKeyBtn.disabled = true;
testApiKeyBtn.textContent = 'لە تاقیکردنەوەدایە...';
apiTestResult.classList.add('hidden');
try {
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${key}`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [{ text: 'Hello, respond with: OK' }] }]
})
});
if (res.ok) {
apiTestResult.className = 'api-test-box success';
apiTestResult.innerHTML = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="vertical-align:-2px;margin-left:6px;"><polyline points="20 6 9 17 4 12"/></svg> پەیوەندی بە Gemini API سەرکەوتوو بوو!';
} else {
const err = await res.json().catch(() => ({}));
apiTestResult.className = 'api-test-box error';
apiTestResult.innerHTML = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="vertical-align:-2px;margin-left:6px;"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> هەڵە لە کلیلی API: ${escapeHtml(err.error?.message || res.statusText)}`;
}
} catch (err) {
apiTestResult.className = 'api-test-box error';
apiTestResult.innerHTML = `<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="vertical-align:-2px;margin-left:6px;"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> هەڵەی تۆڕ: ${escapeHtml(err.message)}`;
} finally {
testApiKeyBtn.disabled = false;
testApiKeyBtn.textContent = 'تاقیکردنەوەی پەیوەندی';
apiTestResult.classList.remove('hidden');
}
});
}
// ==========================================================================
// Global Multilingual Live Chat Module
// ==========================================================================
const chatState = {
profile: {
username: localStorage.getItem('translet_chat_username') || ('میوان_' + Math.floor(Math.random() * 899 + 100)),
flag: localStorage.getItem('translet_chat_flag') || '☀️',
country: localStorage.getItem('translet_chat_country') || 'کوردستان',
preferredLang: localStorage.getItem('translet_chat_lang') || 'ku',
},
messages: JSON.parse(localStorage.getItem('translet_chat_msgs') || '[]'),
mqttClient: null,
broadcastChannel: null,
};
// DOM references for Chat
let navTranslatorBtn, navChatBtn, translatorView, chatView;
let chatFeed, chatMessageInput, sendChatBtn, toggleEmojiPickerBtn, emojiPickerDrawer;
let editProfileBtn, profileModal, closeProfileModalBtn, saveProfileBtn;
let profileUsernameInput, profileCountrySelect, profileLangSelect;
let userFlagBadge, userNameBadge, connStatusText;
function initGlobalChat() {
// Grab Elements
navTranslatorBtn = document.getElementById('navTranslatorBtn');
navChatBtn = document.getElementById('navChatBtn');
translatorView = document.getElementById('translatorView');
chatView = document.getElementById('chatView');
chatFeed = document.getElementById('chatFeed');
chatMessageInput = document.getElementById('chatMessageInput');
sendChatBtn = document.getElementById('sendChatBtn');
toggleEmojiPickerBtn = document.getElementById('toggleEmojiPickerBtn');
emojiPickerDrawer = document.getElementById('emojiPickerDrawer');
editProfileBtn = document.getElementById('editProfileBtn');
profileModal = document.getElementById('profileModal');
closeProfileModalBtn = document.getElementById('closeProfileModalBtn');
saveProfileBtn = document.getElementById('saveProfileBtn');
profileUsernameInput = document.getElementById('profileUsernameInput');
profileCountrySelect = document.getElementById('profileCountrySelect');
profileLangSelect = document.getElementById('profileLangSelect');
userFlagBadge = document.getElementById('userFlagBadge');
userNameBadge = document.getElementById('userNameBadge');
connStatusText = document.getElementById('connStatusText');
updateProfileDisplay();
// Populate sample global messages if first time
if (chatState.messages.length === 0) {
chatState.messages = [
{
id: 'msg_init_1',
sender: 'شوان',
flag: '☀️',
country: 'کوردستان',
text: 'سڵاو لە هەموو هاوڕێیان لە هەموو جیهانەوە! بەخێربێن بۆ چاتی ترانسلێت ☀️',
time: '12:00',
lang: 'ku'
},
{
id: 'msg_init_2',
sender: 'Emily',
flag: '🇺🇸',
country: 'US',
text: 'Hello from New York! It is amazing to chat with people from all over the world here! 🗽',
time: '12:02',
lang: 'en'
},
{
id: 'msg_init_3',
sender: 'Lukas',
flag: '🇩🇪',
country: 'Germany',
text: 'Hallo Freunde! Die Übersetzungsfunktion ist wirklich super schnell und einfach 🇩🇪',
time: '12:05',
lang: 'de'
},
{
id: 'msg_init_4',
sender: 'سارة',
flag: '🇦🇪',
country: 'UAE',
text: 'مرحبًا بالجميع! فكرة ترجمة الرسائل بضغطة زر واحدة رائعة جدًا 🌸',
time: '12:08',
lang: 'ar'
}
];
saveChatMessages();
}
renderChatFeed();
setupChatNavigation();
setupChatEvents();
setupRealtimeNetworking();
}
// Update UI with current profile
function updateProfileDisplay() {
if (userFlagBadge) userFlagBadge.textContent = chatState.profile.flag;
if (userNameBadge) userNameBadge.textContent = chatState.profile.username;
}
// Setup Navigation between Translator and Chat
function setupChatNavigation() {
if (!navTranslatorBtn || !navChatBtn) return;
navTranslatorBtn.addEventListener('click', () => {
playSubtleClick();
navTranslatorBtn.classList.add('active');
navChatBtn.classList.remove('active');
translatorView.classList.remove('hidden');
chatView.classList.add('hidden');
});
navChatBtn.addEventListener('click', () => {
playSubtleClick();
navChatBtn.classList.add('active');
navTranslatorBtn.classList.remove('active');
translatorView.classList.add('hidden');
chatView.classList.remove('hidden');
scrollChatToBottom();
});
}
// Setup Real-time MQTT WebSocket and BroadcastChannel
function setupRealtimeNetworking() {
// 1. BroadcastChannel for local cross-tab sync
try {
if ('BroadcastChannel' in window) {
chatState.broadcastChannel = new BroadcastChannel('translet_global_chat');
chatState.broadcastChannel.onmessage = (event) => {
if (event.data && event.data.type === 'CHAT_MSG') {
handleIncomingMessage(event.data.payload);
}
};
}
} catch (e) {
console.warn('BroadcastChannel error:', e);
}
// 2. Public MQTT Broker for worldwide cross-device live messaging
if (typeof mqtt !== 'undefined') {
try {
const clientId = 'translet_' + Math.random().toString(16).substring(2, 10);
// Connect to secure public MQTT broker over WebSockets
const client = mqtt.connect('wss://broker.emqx.io:8084/mqtt', {
clientId: clientId,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 5000,
});
chatState.mqttClient = client;
client.on('connect', () => {
console.log('Connected to global MQTT chat broker!');
if (connStatusText) {
connStatusText.innerHTML = '<span class="status-dot online"></span> بەستراوەتەوە بە تۆڕی جیهانی';
connStatusText.parentElement.classList.remove('connecting');
connStatusText.parentElement.classList.add('connected');
}
client.subscribe('translet/global_chat/v1', (err) => {
if (err) console.error('Subscription error:', err);
});
});
client.on('message', (topic, message) => {
try {
const payload = JSON.parse(message.toString());
if (payload && payload.id) {
handleIncomingMessage(payload);
}
} catch (err) {
console.warn('Invalid message payload:', err);
}
});
client.on('error', (err) => {
console.warn('MQTT connection error, will retry:', err);
if (connStatusText) {
connStatusText.innerHTML = '<span class="status-dot connecting"></span> لە نوێکردنەوەی پەیوەندیدایە...';
connStatusText.parentElement.classList.add('connecting');
}
});
} catch (err) {
console.warn('MQTT init failed, fallback active:', err);
}
}
}
// Handle Incoming message from network
function handleIncomingMessage(msg) {
// Check if message already exists
if (chatState.messages.some(m => m.id === msg.id)) return;
chatState.messages.push(msg);
if (chatState.messages.length > 80) chatState.messages.shift();
saveChatMessages();
appendMessageToDOM(msg);
scrollChatToBottom();
playSubtleClick();
}
// Save messages to LocalStorage
function saveChatMessages() {
localStorage.setItem('translet_chat_msgs', JSON.stringify(chatState.messages));
}
// Render entire chat feed
function renderChatFeed() {
if (!chatFeed) return;
// Keep welcome banner
const banner = chatFeed.querySelector('.chat-welcome-banner');
chatFeed.innerHTML = '';
if (banner) chatFeed.appendChild(banner);
chatState.messages.forEach(msg => {
appendMessageToDOM(msg);
});
scrollChatToBottom();
}
// Append single message to DOM
function appendMessageToDOM(msg) {
if (!chatFeed) return;
const isMe = msg.sender === chatState.profile.username;
const msgEl = document.createElement('div');
msgEl.className = `chat-msg ${isMe ? 'my-msg' : 'other-msg'}`;
msgEl.dataset.id = msg.id;
msgEl.innerHTML = `
<div class="msg-avatar" title="${escapeHtml(msg.country || '')}">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
</div>
<div class="msg-content">
<div class="msg-meta">
<span class="msg-sender">${escapeHtml(msg.sender)}</span>
<span>•</span>
<span class="msg-time">${escapeHtml(msg.time || '')}</span>
</div>
<div class="msg-bubble">
<div class="msg-text">${escapeHtml(msg.text)}</div>
<div class="msg-toolbar">
<button class="msg-action-btn translate-btn" title="وەرگێڕان بۆ زمانی من">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
<span>وەرگێڕان بۆ زمانی من</span>
</button>
<button class="msg-action-btn speak-btn" title="خوێندنەوە">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>
</button>
</div>
<div class="msg-translation-card hidden"></div>
</div>
</div>
`;
// Attach Translation event
const transBtn = msgEl.querySelector('.translate-btn');
const transCard = msgEl.querySelector('.msg-translation-card');
transBtn.addEventListener('click', async () => {
if (!transCard.classList.contains('hidden')) {
transCard.classList.add('hidden');
return;
}
transBtn.disabled = true;
transBtn.innerHTML = '<svg class="mini-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="9" stroke-dasharray="28" stroke-dashoffset="14"/></svg><span>لە وەرگێڕاندایە...</span>';
try {
const targetLang = chatState.profile.preferredLang || 'ku';
let translatedText = '';
if (state.apiKey && state.apiKey.trim().length > 10) {
const res = await translateWithGemini(msg.text, 'auto', targetLang, 'natural');
translatedText = res.translation;
} else {
const res = await translateWithSmartEngine(msg.text, 'auto', targetLang);
translatedText = res.translation;
}
const langName = languages[targetLang]?.name || targetLang;
transCard.innerHTML = `
<span class="trans-tag">
<svg width="12" height="12" viewBox="0 0 24 24" fill="#ef4444" style="vertical-align:-1px;margin-left:4px;"><path d="M12 2l2.4 7.2L21.6 12l-7.2 2.4L12 21.6l-2.4-7.2L2.4 12l7.2-2.4z"/></svg>
وەرگێڕدراو بۆ (${langName}):
</span>
<div>${escapeHtml(translatedText)}</div>
`;
transCard.classList.remove('hidden');
} catch (err) {
transCard.innerHTML = `<span style="color:#f87171;">⚠️ هەڵە لە وەرگێڕان: ${escapeHtml(err.message)}</span>`;
transCard.classList.remove('hidden');
} finally {
transBtn.disabled = false;
transBtn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1 4-10z"/></svg><span>شاردنەوەی وەرگێڕان</span>';
}
});
// Attach Speech event
const speakBtn = msgEl.querySelector('.speak-btn');
speakBtn.addEventListener('click', () => {
speakText(msg.text, 'auto');
});
chatFeed.appendChild(msgEl);
}
// Scroll chat feed to bottom smoothly
function scrollChatToBottom() {
if (chatFeed) {
chatFeed.scrollTop = chatFeed.scrollHeight;
}
}
// Send chat message
async function sendChatMessage() {
const text = chatMessageInput.value.trim();
if (!text) return;
const now = new Date();
const timeStr = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const newMsg = {
id: 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5),
sender: chatState.profile.username,
flag: chatState.profile.flag,
country: chatState.profile.country,
text: text,
time: timeStr,
lang: isLatinText(text) ? 'en' : 'ku'
};
chatMessageInput.value = '';
chatMessageInput.focus();
// Add locally
handleIncomingMessage(newMsg);
// Broadcast to other tabs
if (chatState.broadcastChannel) {
chatState.broadcastChannel.postMessage({
type: 'CHAT_MSG',
payload: newMsg
});
}
// Publish to worldwide MQTT topic
if (chatState.mqttClient && chatState.mqttClient.connected) {
chatState.mqttClient.publish('translet/global_chat/v1', JSON.stringify(newMsg));
}
}
// Setup chat events
function setupChatEvents() {
// Send Button & Enter Key
if (sendChatBtn) {
sendChatBtn.addEventListener('click', sendChatMessage);
}
if (chatMessageInput) {
chatMessageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
sendChatMessage();
}
});
}
// Toggle Emoji Drawer
if (toggleEmojiPickerBtn && emojiPickerDrawer) {
toggleEmojiPickerBtn.addEventListener('click', () => {
emojiPickerDrawer.classList.toggle('hidden');
});
emojiPickerDrawer.querySelectorAll('.emoji-chip').forEach(chip => {
chip.addEventListener('click', () => {
chatMessageInput.value += chip.textContent;
chatMessageInput.focus();
});
});
}
// Profile Modal Handlers
if (editProfileBtn && profileModal) {
editProfileBtn.addEventListener('click', () => {
profileUsernameInput.value = chatState.profile.username;
profileCountrySelect.value = `${chatState.profile.flag}|${chatState.profile.country}`;
profileLangSelect.value = chatState.profile.preferredLang || 'ku';
profileModal.classList.remove('hidden');
});
closeProfileModalBtn.addEventListener('click', () => {
profileModal.classList.add('hidden');
});
profileModal.addEventListener('click', (e) => {
if (e.target === profileModal) profileModal.classList.add('hidden');
});
saveProfileBtn.addEventListener('click', () => {
const uName = profileUsernameInput.value.trim() || 'میوان';
const [flag, country] = profileCountrySelect.value.split('|');
const pLang = profileLangSelect.value;
chatState.profile.username = uName;
chatState.profile.flag = flag;
chatState.profile.country = country;
chatState.profile.preferredLang = pLang;
localStorage.setItem('translet_chat_username', uName);
localStorage.setItem('translet_chat_flag', flag);
localStorage.setItem('translet_chat_country', country);
localStorage.setItem('translet_chat_lang', pLang);
updateProfileDisplay();
profileModal.classList.add('hidden');
showToast('پرۆفایلی چات نوێکرایەوە ✨', '👤');
});
}
}
// ==========================================
// Word Insights & Multiple Meanings Database
// ==========================================
const wordInsightsDatabase = {
'right': {
word: 'Right',
lang: 'ئینگلیزی (English)',
phonetic: '/raɪt/',
overview: 'وشەی «Right» یەکێکە لە فرەماناترین وشەکانی زمانی ئینگلیزی. بەپێی شوێنەکەی لە ڕستەدا دەتوانێت مانای دروستی، ئاراستەی لای دەست، مافی یاسایی یان دەستبەجێبوون بدات.',
meanings: [
{
num: 1,
pos: 'ئاوەڵناو (Adjective)',
ku: 'ڕاست، دروست، بێهەڵە',
en: 'Correct, accurate, true',
context: 'بۆ قسەی دروست یان وەڵامی بێ هەڵە',
exampleEn: 'You made the right choice.',
exampleKu: 'تۆ بڕیارە دروستەکەت دا.'
},
{
num: 2,
pos: 'ئاراستە (Direction)',
ku: 'لای ڕاست (پێچەوانەی لای چەپ)',
en: 'On or towards the right side',
context: 'بۆ شوێن و ئاراستەی ڕۆیشتن',
exampleEn: 'Turn right at the traffic lights.',
exampleKu: 'لە ترافیک لایتەکەدا بەلای ڕاستدا بسووڕێوە.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'ماف (مافی مرۆڤ یان یاسایی)',
en: 'A moral or legal entitlement',
context: 'بۆ یاسا، دادپەروەری و مافی تاک',
exampleEn: 'Education is a fundamental human right.',
exampleKu: 'خوێندن مافێکی بنەڕەتیی مرۆڤە.'
},
{
num: 4,
pos: 'ئاوەڵکردار (Adverb)',
ku: 'یەکسەر / دەستبەجێ / ڕێک لەم ساتەدا',
en: 'Immediately or exactly at this moment',
context: 'بۆ کات و جەختکردنەوە',
exampleEn: 'I will call you right back.',
exampleKu: 'یەکسەر پەیوەندیت پێوە دەکەمەوە.'
}
]
},
'light': {
word: 'Light',
lang: 'ئینگلیزی (English)',
phonetic: '/laɪt/',
overview: 'وشەی «Light» بەپێی ڕستە دەکرێت مەبەست لێی ڕووناکی فیزیکی بێت، یاخود کەمیی کێش، یانیش کاڵی لە ڕەنگدا.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'ڕووناکی، ڕۆشنایی، تیشک',
en: 'Natural or artificial illumination',
context: 'تیشکی خۆر، گڵۆپ یان ڕۆشنایی سروشتی',
exampleEn: 'The sun provides warmth and light.',
exampleKu: 'خۆر گەرمی و ڕووناکی دەبەخشێت.'
},
{
num: 2,
pos: 'ئاوەڵناو (Adjective)',
ku: 'سووک، کێش کەم (پێچەوانەی قورس)',
en: 'Of little weight, not heavy',
context: 'بۆ بارستایی و کێشی شتومەک',
exampleEn: 'This laptop is very light and portable.',
exampleKu: 'ئەم لاپتۆپە زۆر سووکە و ئاسان دەگوازرێتەوە.'
},
{
num: 3,
pos: 'ئاوەڵناو (Adjective)',
ku: 'کاڵ، ڕوون (بۆ ڕەنگ)',
en: 'Pale or low in color intensity',
context: 'بۆ دەربڕینی ڕەنگی کراوە و کاڵ',
exampleEn: 'She prefers wearing light blue.',
exampleKu: 'ئەو ئارەزوو دەکات شینی کاڵ لەبەر بکات.'
},
{
num: 4,
pos: 'کردار (Verb)',
ku: 'داگیرساندن، گڕدان',
en: 'To ignite or make something start burning',
context: 'داگیرساندنی ئاگر یان مۆم',
exampleEn: 'He decided to light the fire.',
exampleKu: 'بڕیاریدا ئاگرەکە داگیرسێنێت.'
}
]
},
'bank': {
word: 'Bank',
lang: 'ئینگلیزی (English)',
phonetic: '/bæŋk/',
overview: 'وشەی «Bank» هەم بۆ دامەزراوەی دراو و هەم بۆ کەناری سروشتیی ڕووبار بەکاردێت.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'بانک (شوێنی دارایی و پاشەکەوت)',
en: 'Financial institution for deposits & loans',
context: 'دارایی، ژمێریاری و پارەپاراستن',
exampleEn: 'I deposited money in the bank.',
exampleKu: 'پارەم لە بانکەکەدا پاشەکەوت کرد.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'کەنار / لێواری ڕووبار',
en: 'The land alongside a body of water',
context: 'جوگرافیا و سروشت',
exampleEn: 'We walked along the river bank.',
exampleKu: 'بە لێواری ڕووبارەکەدا پیاسەمان کرد.'
}
]
},
'book': {
word: 'Book',
lang: 'ئینگلیزی (English)',
phonetic: '/bʊk/',
overview: 'وشەی «Book» لە دۆخی ناودا کتێبە، بەڵام لە دۆخی کرداردا واتا گرتنی جێگا یان کات.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'کتێب، پەڕتووک',
en: 'A written or printed work',
context: 'خوێندنەوە و زانست',
exampleEn: 'Reading a book expands your mind.',
exampleKu: 'خوێندنەوەی کتێب مێشکت فراوان دەکات.'
},
{
num: 2,
pos: 'کردار (Verb)',
ku: 'حجزکردن، گرتنی شوێن یان بلیت',
en: 'To reserve accommodation or ticket in advance',
context: 'گەشتوگوزار و میوانخانە',
exampleEn: 'I need to book a flight ticket.',
exampleKu: 'پێویستە بلیتێکی فڕۆکە حجز بکەم.'
}
]
},
'watch': {
word: 'Watch',
lang: 'ئینگلیزی (English)',
phonetic: '/wɒtʃ/',
overview: 'دەتوانێت ئامێری کاتژمێری دەست بێت، یانیش کرداری تەماشاکردن بە چڕی.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'کاتژمێری دەست',
en: 'A small timepiece worn on the wrist',
context: 'ئامێری کاتژمێر',
exampleEn: 'He bought a sleek modern watch.',
exampleKu: 'کاتژمێرێکی دەستیی مۆدێرنی کڕی.'
},
{
num: 2,
pos: 'کردار (Verb)',
ku: 'تەماشاکردن، چاودێریکردن',
en: 'To look at attentively over a period of time',
context: 'سەیرکردنی فیلم یان ڕووداو',
exampleEn: 'Let us watch the documentary tonight.',
exampleKu: 'با ئەمشەو سەیری فیلمە بەڵگەنامەییەکە بکەین.'
}
]
},
'spring': {
word: 'Spring',
lang: 'ئینگلیزی (English)',
phonetic: '/sprɪŋ/',
overview: 'وشەی «Spring» لە ئینگلیزیدا ٤ مانای سەرەکی زۆر جیاوازی هەیە: وەرز، کانی، فنەر و بازدان.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'وەرزی بەهار',
en: 'The season between winter and summer',
context: 'کەشوهەوا و وەرزی ساڵ',
exampleEn: 'Flowers bloom beautifully in spring.',
exampleKu: 'گوڵەکان بە جوانی لە بەهاردا دەپشکۆن.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'کانی، سەرچاوەی ئاوی سروشتی',
en: 'A natural source of water emerging from earth',
context: 'سروشت و کانیاو',
exampleEn: 'Clear water flows from the mountain spring.',
exampleKu: 'ئاوی پاک لە کانییە چیاییەکەوە دەڕژێت.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'فنەر، یای (ئامرازی کێشەدار)',
en: 'A resilient coiled metal device',
context: 'ئەندازیاری و تەکنیک',
exampleEn: 'The mattress has supportive metal springs.',
exampleKu: 'دۆشەکەکە فنەری ئاسنینی پشتیوانی هەیە.'
},
{
num: 4,
pos: 'کردار (Verb)',
ku: 'بازدان، هەڵبەزینەوەی لەناکاو',
en: 'To jump or leap forward suddenly',
context: 'جوڵەی خێرا',
exampleEn: 'The cat will spring onto the wall.',
exampleKu: 'پشیلەکە باز دەداتە سەر دیوارەکە.'
}
]
},
'key': {
word: 'Key',
lang: 'ئینگلیزی (English)',
phonetic: '/kiː/',
overview: 'وشەی «Key» دەکرێت کلیل بێت، یاخود واتا سەرەکی و بنەڕەتی، یاخود دوگمەی تەختەکلیل.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'کلیل (بۆ کردنەوەی دەرگا)',
en: 'A small metal tool for locking/unlocking',
context: 'ماڵ و دەرگا',
exampleEn: 'Do not forget to take your room key.',
exampleKu: 'لەبیرت نەچێت کلیلی ژوورەکەت ببەیت.'
},
{
num: 2,
pos: 'ئاوەڵناو (Adjective)',
ku: 'سەرەکی، بنەڕەتی، یەکلاکەرەوە',
en: 'Extremely important, vital, decisive',
context: 'بۆچوون و ڕوونکردنەوە',
exampleEn: 'Dedication is the key factor for success.',
exampleKu: 'دڵسۆزی فاکتەری سەرەکییە بۆ سەرکەوتن.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'دوگمەی کیبۆرد (تەختەکلیل)',
en: 'A button on a typewriter or computer keyboard',
context: 'کۆمپیوتەر و تەکنەلۆژیا',
exampleEn: 'Press the enter key to continue.',
exampleKu: 'دوگمەی ئینتەر داگرە بۆ بەردەوامبوون.'
}
]
},
'fair': {
word: 'Fair',
lang: 'ئینگلیزی (English)',
phonetic: '/feə(r)/',
overview: 'دادپەروەری، پێشانگا و فیستیڤاڵ، یاخود کاڵیی ڕەنگی پێست و قژ.',
meanings: [
{
num: 1,
pos: 'ئاوەڵناو (Adjective)',
ku: 'دادپەروەر، بێلایەن، ڕەوا',
en: 'Treating people equally without favoritism',
context: 'دادگەری و بڕیاردان',
exampleEn: 'The referee made a fair decision.',
exampleKu: 'ناوبژیوانەکە بڕیارێکی دادپەروەرانەی دا.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'پێشانگا، فێستیڤاڵ، بازاڕی کراوە',
en: 'A gathering of stalls and amusements',
context: 'بازرگانی و بۆنەکان',
exampleEn: 'We attended the international book fair.',
exampleKu: 'بەشداریمان کرد لە پێشانگای نێودەوڵەتیی کتێب.'
},
{
num: 3,
pos: 'ئاوەڵناو (Adjective)',
ku: 'سپیکار، کاڵ و گەش (بۆ پێست و قژ)',
en: 'Light colored skin or blond hair',
context: 'شێوە و ڕووخسار',
exampleEn: 'She has fair skin and green eyes.',
exampleKu: 'ئەو پێستێکی سپیکار و چاوێکی سەوزی هەیە.'
}
]
},
'patient': {
word: 'Patient',
lang: 'ئینگلیزی (English)',
phonetic: '/ˈpeɪʃnt/',
overview: 'لە پزیشکیدا کەسی نەخۆشە، لە ڕەوشت و دەروونناسیدا مرۆڤی بەسەبر و ئارامگرە.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'نەخۆش (کەسی وەرگری چارەسەر)',
en: 'A person receiving medical care',
context: 'نەخۆشخانە و پزیشکی',
exampleEn: 'The doctor examined the patient carefully.',
exampleKu: 'پزیشکەکە بە وردی پشکنینی بۆ نەخۆشەکە کرد.'
},
{
num: 2,
pos: 'ئاوەڵناو (Adjective)',
ku: 'ئارامگر، بەسەبر، خۆڕاگر',
en: 'Able to accept delays or suffering calmly',
context: 'ڕەوشت و کەسایەتی',
exampleEn: 'Be patient, good things take time.',
exampleKu: 'ئارامگر بە، شتە باشەکان پێویستیان بە کاتە.'
}
]
},
'match': {
word: 'Match',
lang: 'ئینگلیزی (English)',
phonetic: '/mætʃ/',
overview: 'یاری وەرزشی، داری شقارتە، یاخود هاوتایی و گونجان.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'یاری، پێشبڕکێی وەرزشی',
en: 'A competitive game or tournament',
context: 'وەرزش و تۆپی پێ',
exampleEn: 'The football match starts at eight.',
exampleKu: 'یاریی تۆپی پێ کاتژمێر هەشت دەست پێدەکات.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'شقارتە (داری ئاگرداگیرسێن)',
en: 'A short wooden stick for producing fire',
context: 'داگیرساندنی ئاگر',
exampleEn: 'He lit the candle with a match.',
exampleKu: 'مۆمەکەی بە شقارتەیەک داگیرساند.'
},
{
num: 3,
pos: 'کردار (Verb)',
ku: 'گونجاندن، هاوتاکردن، لێکچوون',
en: 'To correspond or fit harmoniously together',
context: 'دیزاین و ڕەنگ',
exampleEn: 'These shoes match your jacket.',
exampleKu: 'ئەم پێڵاوانە لەگەڵ چاکەتەکەتدا دەگونجێن.'
}
]
},
// Kurdish Polysemous Words (وشە فرەماناکانی کوردی)
'شیر': {
word: 'شیر',
lang: 'کوردی (Kurdish)',
phonetic: '[Şîr]',
overview: 'لە زمانی کوردیدا وشەی «شیر» یەکێکە لە ناسراوترین وشە هۆمۆنیمەکان (Homonyms)، بەپێی دەق دەکرێت شیری خواردنەوە بێت، شمشێری جەنگاوەر بێت، یانیش شێری دڕندەی دارستان بێت.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'شیری سپی (خواردنەوەی سروشتی)',
en: 'Milk - Nutritious liquid from mammals',
context: 'خۆراک و تەندروستی',
exampleKu: 'منداڵەکە پێش خەوتن پەرداخێک شیری گەرم دەخواتەوە.',
exampleEn: 'The child drinks a glass of warm milk before bed.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'شمشێر (چەکی ئاسنینی تیژ)',
en: 'Sword - Ancient edged blade weapon',
context: 'مێژوو و شۆڕش و حەماسەت',
exampleKu: 'پێشمەرگەکان بە شیری تیژ بەرگرییان لە نیشتمان کرد.',
exampleEn: 'The fighters defended their homeland with sharp swords.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'شێر (پاشای دارستان - ئاژەڵی دڕندە)',
en: 'Lion - Powerful wild predatory feline',
context: 'سروشت، ئاژەڵناسی و هێمای ئازایەتی',
exampleKu: 'شێر لە ئەدەبی کوردیدا هێمای سەروەری و قارەمانێتییە.',
exampleEn: 'The lion symbolizes bravery and royalty in literature.'
}
]
},
'دار': {
word: 'دار',
lang: 'کوردی (Kurdish)',
phonetic: '[Dar]',
overview: 'وشەی «دار» هەم درەختی بەپێوەی سروشتە، هەم تەختە و چێوی پیشەسازییە، هەم پاشگری بەستراوە بە کەسەکانەوە.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'درەخت، نەمام، داری سەوز',
en: 'Tree - Woody perennial plant with branches',
context: 'سروشت و باخداری',
exampleKu: 'لە حەوشەی ماڵەکەماندا داری هەنجیر و هەنار هەیە.',
exampleEn: 'There are fig and pomegranate trees in our garden.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'چێو، تەختە (کەرەستەی دروستکردن)',
en: 'Wood / Timber - Material from trees',
context: 'دارتاشی و بیناسازی',
exampleKu: 'ئەم قەنەفەیە لە داری بەهێز دروستکراوە.',
exampleEn: 'This sofa is made of sturdy wood.'
},
{
num: 3,
pos: 'پاشگر (Suffix)',
ku: 'خاوەندارێتی (خاوەنی سیفەت یان شتێک)',
en: 'Suffix denoting possession or state (e.g. -ful, -ed)',
context: 'ڕێزمانی کوردی: بریندار، هوشیار، سەرمایەدار',
exampleKu: 'کەسی بریندار پێویستی بە یارمەتی پزیشکی هەیە.',
exampleEn: 'The wounded person needs medical attention.'
}
]
},
'چاو': {
word: 'چاو',
lang: 'کوردی (Kurdish)',
phonetic: '[Çaw]',
overview: '«چاو» ئەندامی بینینی جەستەیە، سەرچاوەی کانیاوە، یان چاوی تەباخ و کونی تۆڕە.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'چاوی مرۆڤ (ئەندامی بینین)',
en: 'Eye - Organ of sight and vision',
context: 'ئەندامناسی و تەندروستی',
exampleKu: 'چاو گرنگترین ئەندامی هەستەوەری مرۆڤە.',
exampleEn: 'The eye is the most vital sensory organ.'
},
{
num: 2,
pos: 'ناو (Noun)',
ku: 'چاوی کانی (سەرچاوەی ئاو لە زەویدا)',
en: 'Water spring head / Source',
context: 'سروشت و جوگرافیا',
exampleKu: 'لە چاوی کانییەکەدا ئاوێکی تەواو سازگار هەڵدەقوڵێت.',
exampleEn: 'Completely sweet freshwater bubbles from the spring.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'چاوی تەباخ یان فڕن (شوێنی گڕ)',
en: 'Burner on a stove or oven',
context: 'ئامرازەکانی چێشتخانە',
exampleKu: 'چاوی بچووکی تەباخەکە دابگیرسێنە بۆ چا لێنان.',
exampleEn: 'Turn on the small burner of the stove to make tea.'
}
]
},
'با': {
word: 'با',
lang: 'کوردی (Kurdish)',
phonetic: '[Ba]',
overview: '«با» شنەبا و ڕەشەبای سروشتە، مۆڵەت و فەرمانی ئەدەبییە، یانیش گازی هەڵئاوسانە.',
meanings: [
{
num: 1,
pos: 'ناو (Noun)',
ku: 'شنەبا، ڕەشەبا، هەوای بەهێز',
en: 'Wind - Natural movement of air',
context: 'کەشناسی و سروشت',
exampleKu: 'بایەکی سارد لە چیاکانەوە دەهاتە ناو شار.',
exampleEn: 'A cold wind came into the city from the mountains.'
},
{
num: 2,
pos: 'ئامراز (Particle)',
ku: 'مۆڵەت، داواکاری (با بچین، با بێت)',
en: 'Let / Shall - Permission or proposal particle',
context: 'ڕێزمان و گفتوگۆ',
exampleKu: 'با ئەم پڕۆژەیە بە سەرکەوتوویی تەواو بکەین.',
exampleEn: 'Let us complete this project successfully.'
},
{
num: 3,
pos: 'ناو (Noun)',
ku: 'گازی سک، هەڵئاوسان',
en: 'Gas / Flatulence in the body',
context: 'تەندروستی',
exampleKu: 'ئەم دەرمانە چارەسەری بای سک دەکات.',
exampleEn: 'This medicine treats stomach gas.'
}
]
},
'دڵ': {
word: 'دڵ (Heart)',
lang: 'کوردی (Kurdish)',
phonetic: '[Dill / Dl / Heart]',
overview: 'وشەی «دڵ» لە دەوڵەمەندترین وشەکانی کوردییە؛ هەم ئەندامی فیزیکیی پەمپکردنی خوێنە، هەم سەرچاوەی هەست و سۆز و خۆشەویستییە، هەم چەق و ناوەندی شوێنەکانە.',
meanings: [
{
num: 1,
pos: 'ئەندامی جەستە (Anatomy)',
ku: 'ئەندامی سەرەکیی پەمپکردنی خوێن لە سنگدا',
en: 'Muscular organ that pumps blood through the circulatory system',
context: 'پزیشکی و تەندروستی',
exampleKu: 'وەرزشکردنی ڕێکخراو تەندروستیی دڵ بەهێز دەکات.',
exampleEn: 'Regular exercise strengthens heart health.'
},
{
num: 2,
pos: 'ناوەندی هەست و سۆز (Emotion / Soul)',
ku: 'ناخ، ویژدان و خۆشەویستی (دڵخۆش، دڵتەنگ، بەدڵبوون)',
en: 'The center of emotions, feelings, love and conscience',
context: 'سۆزداری و دەروونی',
exampleKu: 'بە هەموو دڵمەوە هیوای سەرکەوتنت بۆ دەخوازم.',
exampleEn: 'I wish you success with all my heart.'
},
{
num: 3,
pos: 'چەق و ناوەند (Center / Core)',
ku: 'ناوەڕاست و گرنگترین بەشی هەر شوێن یان بابەتێک',
en: 'The innermost, central or vital part of something',
context: 'جوگرافیا و باسەکان',
exampleKu: 'هۆتێلەکە ڕێک لە ناوەڕاست و دڵی شاردا هەڵکەوتووە.',
exampleEn: 'The hotel is located right in the heart of the city.'
},
{
num: 4,
pos: 'بوێری و ئازایەتی (Courage / Bravery)',
ku: 'جەرگ، چاونەترسی و غیرەت (دڵ و جەرگ)',
en: 'Courage, bravery and determination',
context: 'ئاکار و بەهێزی',
exampleKu: 'بۆ بەدیهێنانی خەونەکانت پێویستت بە دڵێکی بوێر هەیە.',
exampleEn: 'You need a brave heart to achieve your dreams.'
}
]
},
'دەست': {
word: 'دەست (Hand)',
lang: 'کوردی (Kurdish)',
phonetic: '[Dest / Hand]',
overview: '«دەست» کایەی فراوانی هەیە: لە ئەندامی گرتنی شتومەکەوە بۆ هاوکاری، کۆنترۆڵ و دەستەڵات، تا دەگاتە دەستپێکی کارێک.',
meanings: [
{
num: 1,
pos: 'ئەندامی لەش (Anatomy)',
ku: 'ئەندامی لەش لە مەچەکەوە بۆ پەنجەکان بۆ گرتن و کارکردن',
en: 'The end part of the arm beyond the wrist',
context: 'جەستە و پێکهاتە',
exampleKu: 'پێش نانخواردن دەستەکانت بە باشی بشۆ.',
exampleEn: 'Wash your hands well before eating.'
},
{
num: 2,
pos: 'یارمەتی و پشتیوانی (Assistance / Help)',
ku: 'دەستگیرۆیی و هاوکاری (دەستێکم بدەرێ)',
en: 'Help, assistance or support given to someone',
context: 'کۆمەڵایەتی',
exampleKu: 'دەستێکم بدەرێ با ئەم مێزە قورسە ببەینە ژوورەوە.',
exampleEn: 'Give me a hand to bring this heavy table inside.'
},
{
num: 3,
pos: 'دەسەڵات و کۆنترۆڵ (Control / Authority)',
ku: 'جڵەو، سەرپەرشتی یان خاوەندارێتی (لە دەستی باشدایە)',
en: 'Control, safe custody, power or possession',
context: 'بەڕێوەبردن',
exampleKu: 'کارەکە ئێستا لە دەستێکی زۆر ئەمین و شارەزادایە.',
exampleEn: 'The project is now in very capable hands.'
},
{
num: 4,
pos: 'دەستە و کۆمەڵە (Set / Suit)',
ku: 'دەستێک پۆشاک، دەستێک کەوچک و چەتاڵ',
en: 'A set or collection of matched items',
context: 'کەرەستە و پۆشاک',
exampleKu: 'دەستێک جلی کوردیی جوان و ڕازاوەی لەبەردا بوو.',
exampleEn: 'He wore a fine, handsome set of Kurdish clothes.'
}
]
},
'خۆش': {
word: 'خۆش (Pleasant / Good)',
lang: 'کوردی (Kurdish)',
phonetic: '[Xosh / Pleasant]',
overview: '«خۆش» گشتگیرترین وشەی پۆزەتیڤی کوردییە: لە خۆشیی دەروون و خواردنی بەتامەوە بۆ کەشوهەوا و ساڕێژبوونی برین.',
meanings: [
{
num: 1,
pos: 'بەتام و بەچێژ (Delicious / Tasty)',
ku: 'بۆن و تامی چێژبەخش لە خواردن و میوەدا',
en: 'Delicious, appetizing or flavorful food/scent',
context: 'خواردن و خواردنەوە',
exampleKu: 'ئەم خواردنە کوردییە تامی زۆر خۆش و بەلەزەتە.',
exampleEn: 'This Kurdish food tastes very delicious.'
},
{
num: 2,
pos: 'شاد و بەختەوەر (Happy / Joyful)',
ku: 'دڵخۆشی و ڕازیبوون لە دۆخێک (دڵخۆش، کاتی خۆش)',
en: 'Full of joy, happiness and contentment',
context: 'دەروونی و هەست',
exampleKu: 'ئەمڕۆ هەواڵێکی زۆر خۆش و دڵخۆشکەرم بیست.',
exampleEn: 'I heard very happy news today.'
},
{
num: 3,
pos: 'لەبار و هێمن (Pleasant Weather)',
ku: 'کەشوهەوای گونجاو و دڵڕفێن (هەوای خۆش)',
en: 'Agreeable, charming and mild weather',
context: 'کەشوهەوا و سروشت',
exampleKu: 'کەشوهەوای بەهار لە شاخەکانی کوردستان بێ ئەندازە خۆشە.',
exampleEn: 'Spring weather in Kurdistan mountains is immensely pleasant.'
},
{
num: 4,
pos: 'ساڕێژبوون (Healed / Recovered)',
ku: 'چاکبوونەوەی برین یان نەخۆشی (برینەکەی خۆش بووەوە)',
en: 'Healing, recovery or cure of wounds',
context: 'تەندروستی',
exampleKu: 'برینەکەی پاش چەند ڕۆژێک دەرمان بە تەواوی خۆش بووەوە.',
exampleEn: 'His wound healed completely after a few days of medication.'
}
]
},
'کار': {
word: 'کار (Work / Job / Deed)',
lang: 'کوردی (Kurdish)',
phonetic: '[Kar / Work]',
overview: '«کار» تەوەرەی بەرهەمهێنانە؛ لە ئەرکی ڕۆژانە و پیشەی بژێوییەوە بۆ کرداری چاکە و چالاکیی فیزیکی.',
meanings: [
{
num: 1,
pos: 'پیشە و ئیش (Job / Career)',
ku: 'ئەو ئەرک و پیشەیەی مرۆڤ کاتی بۆ تەرخان دەکات بۆ بژێوی',
en: 'An occupation, trade, job or profession',
context: 'کار و پیشە',
exampleKu: 'ئەو لە کۆمپانیایەکی تەکنەلۆجی کارێکی باشی دەستکەوت.',
exampleEn: 'He secured a great job at a technology company.'
},
{
num: 2,
pos: 'کردەوە و ڕەفتار (Deed / Action)',
ku: 'کرداری مرۆڤ لە ژیاندا (کاری چاک و کاری خراپ)',
en: 'An action, deed or ethical conduct',
context: 'ئەخلاق و ڕەوشت',
exampleKu: 'کاری چاکە هەمیشە شوێنپێی جوانی خۆی بەجێدەهێڵێت.',
exampleEn: 'A good deed always leaves behind a beautiful legacy.'
},
{
num: 3,
pos: 'چالاکی و فەرمان (Function / Operation)',
ku: 'کارکردنی ئامێرێک یان سیستەمێک (لە کار کەوتن)',
en: 'Operational activity or functioning of a system',
context: 'تەکنیک و ئامێر',
exampleKu: 'ماتۆڕەکە بە شێوەیەکی زۆر ورد و بێ کێشە کار دەکات.',
exampleEn: 'The motor functions very smoothly without issue.'
}
]
},
'ژیان': {
word: 'ژیان (Life)',
lang: 'کوردی (Kurdish)',
phonetic: '[Zhyan / Life]',
overview: '«ژیان» پیرۆزترین چەمکە؛ تەمەن و بوونی مرۆڤ لە سەر زەوی، شێوازی گوزەران، یاخود هیوای نێو ڕۆح.',
meanings: [
{
num: 1,
pos: 'بوون و ژیان (Existence / Life)',
ku: 'دۆخی هەبوون و زیندوێتیی مرۆڤ و زیندەوەران',
en: 'The condition of living existence and consciousness',
context: 'فەلسەفە و سروشت',
exampleKu: 'ژیان دیارییەکی گرانبەهایە و پێویستە بە بەسوودی بەسەرببرێت.',
exampleEn: 'Life is a precious gift that must be lived meaningfully.'
},
{
num: 2,
pos: 'شێوازی گوزەران (Lifestyle / Living)',
ku: 'چۆنیەتی بەسەربردنی ڕۆژگار (ژیانی سادە، ژیانی شارستانی)',
en: 'A particular way of living or daily experience',
context: 'کۆمەڵایەتی',
exampleKu: 'ئەوان لە گوندێکی ئارامدا ژیانێکی هێمن و بەختەوەر دەگوزەرێنن.',
exampleEn: 'They live a peaceful and happy life in a quiet village.'
},
{
num: 3,
pos: 'ڕۆح و ئیلهام (Inspiration / Soul)',
ku: 'بەخشینی گوڕ و هیوای نوێ بە دەوروبەر (تۆ ژیانی منی)',
en: 'A source of enthusiasm, vitality and deep affection',
context: 'سۆزداری و ئەدەبی',
exampleKu: 'گەڕانەوەی ئەو ژیانی بە هەموو ماڵەکە بەخشیەوە.',
exampleEn: 'His return brought life and energy back to the entire home.'
}
]
},
'ئاو': {
word: 'ئاو (Water)',
lang: 'کوردی (Kurdish)',
phonetic: '[Aw / Water]',
overview: '«ئاو» سەرچاوەی ژیانە؛ لە شلەی سروشتیی خواردنەوە بۆ سەروەت و ئابڕووی مرۆڤ (ئاوی ڕوو).',
meanings: [
{
num: 1,
pos: 'شلەی سروشتی (Liquid / Water)',
ku: 'شلەی بێ ڕەنگ و بۆن کە بنەمای ژیانی هەموو زیندەوەرێکە',
en: 'The clear, colorless liquid essential for all plant and animal life',
context: 'سروشت و زانست',
exampleKu: 'ڕۆژانە خواردنەوەی بڕی پێویستی ئاوی پاک پێویستە.',
exampleEn: 'Drinking an adequate amount of pure water daily is necessary.'
},
{
num: 2,
pos: 'کەرامەت و ئابڕوو (Honor / Luster)',
ku: 'ئابڕوومەندی و شکۆی مرۆڤ (ئاوی ڕوو، پاراستنی ئابڕوو)',
en: 'Honor, dignity or social reputation (face)',
context: 'ئاکار و پەند',
exampleKu: 'پاراستنی ئاوی ڕوو لە هەموو سامانی دنیا بەنرخترە.',
exampleEn: 'Preserving one\'s dignity is more precious than all worldly wealth.'
},
{
num: 3,
pos: 'کانی و سەرچاوە (Spring / Source)',
ku: 'ئاوەڕۆ و کانییە سروشتییەکان',
en: 'Natural springs and flowing streams',
context: 'جوگرافیا',
exampleKu: 'ئاوی ئەم شاخە زۆر سازگار و فێنکە.',
exampleEn: 'The water of this mountain spring is very sweet and cool.'
}
]
}
};
// Aliases mapping for instant multi-language & Latin Kurdish lookup
const wordInsightAliases = {
'dl': 'دڵ',
'dil': 'دڵ',
'dill': 'دڵ',
'heart': 'دڵ',
'dest': 'دەست',
'dast': 'دەست',
'hand': 'دەست',
'hands': 'دەست',
'xosh': 'خۆش',
'khosh': 'خۆش',
'pleasant': 'خۆش',
'tasty': 'خۆش',
'delicious': 'خۆش',
'kar': 'کار',
'work': 'کار',
'job': 'کار',
'zhyan': 'ژیان',
'jiyan': 'ژیان',
'life': 'ژیان',
'aw': 'ئاو',
'av': 'ئاو',
'water': 'ئاو',
'chaw': 'چاو',
'eye': 'چاو',
'eyes': 'چاو',
'shir': 'شیر',
'lion': 'شیر',
'milk': 'شیر',
'dar': 'دار',
'tree': 'دار',
'wood': 'دار',
'ba': 'با',
'wind': 'با'
};
// Helper: Escape HTML strings
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Smart Key Resolver (handles Latin Kurdish, aliases, and prefix matching)
function resolveInsightKey(query) {
if (!query) return null;
const q = query.trim().toLowerCase();
// 1. Direct match in database
if (wordInsightsDatabase[q]) return q;
// 2. Direct match in aliases
if (wordInsightAliases[q] && wordInsightsDatabase[wordInsightAliases[q]]) {
return wordInsightAliases[q];
}
// 3. Try Kurdish Transliteration to Arabic script
if (typeof kurdishTransliteration !== 'undefined') {
const kuArabic = kurdishTransliteration.toArabic(q).trim().toLowerCase();
if (kuArabic && wordInsightsDatabase[kuArabic]) return kuArabic;
if (wordInsightAliases[kuArabic] && wordInsightsDatabase[wordInsightAliases[kuArabic]]) {
return wordInsightAliases[kuArabic];
}
}
// 4. Exact match against word display title
const titleMatch = Object.keys(wordInsightsDatabase).find(k => {
const w = (wordInsightsDatabase[k]?.word || '').toLowerCase();
return w === q || w.startsWith(q);
});
if (titleMatch) return titleMatch;
// 5. Prefix match in database keys
const prefixMatch = Object.keys(wordInsightsDatabase).find(k => k.startsWith(q));
if (prefixMatch) return prefixMatch;
return null;
}
// Render data into the Word Insight Card
function renderWordInsightData(data, activeKey) {
const container = document.getElementById('insightsBody');
if (!container || !data) return;
const lookupKey = (activeKey || data.word || '').toLowerCase();
// Update active chip in the popular row
document.querySelectorAll('.insight-chip').forEach(chip => {
const chipWord = (chip.getAttribute('data-word') || '').toLowerCase();
if (chipWord === lookupKey || chipWord === (data.word || '').toLowerCase()) {
chip.classList.add('active');
} else {
chip.classList.remove('active');
}
});
const meaningsHtml = (data.meanings || []).map(m => `
<div class="meaning-box">
<div>
<div class="meaning-top-row">
<span class="pos-tag">${m.pos}</span>
<span class="meaning-num-badge">${m.num}</span>
</div>
<div class="meaning-kurdish">${m.ku}</div>
<div class="meaning-english">${m.en}</div>
${m.context ? `<div class="meaning-context"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-left:4px;"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>${m.context}</div>` : ''}
</div>
<div class="example-quote">
${m.exampleEn ? `<span class="en-quote">“${m.exampleEn}”</span>` : ''}
${m.exampleKu ? `<span class="ku-quote">«${m.exampleKu}»</span>` : ''}
</div>
</div>
`).join('');
container.innerHTML = `
<div class="word-entry-card">
<div class="word-header-row">
<span class="main-word-title">${data.word}</span>
${data.phonetic ? `<span class="word-phonetic">${data.phonetic}</span>` : ''}
<span class="word-lang-pill">${data.lang}</span>
</div>
<p class="word-overview">${data.overview}</p>
<div class="meanings-grid">
${meaningsHtml}
</div>
</div>
`;
}
// Universal Dynamic Generator for ANY arbitrary word typed by the user
let currentInsightFetchId = 0;
async function generateDynamicWordInsight(query) {
const fetchId = ++currentInsightFetchId;
const container = document.getElementById('insightsBody');
if (!container) return;
const cleanQuery = query.trim();
// Sleek animated loading state
container.innerHTML = `
<div class="word-entry-card" style="text-align: center; padding: 36px 20px;">
<div class="insight-spinner"></div>
<h4 style="color: #fff; margin-bottom: 6px; font-size: 1.1rem;">خەریکی شیکردنەوەی ماناکانی وشەی «${escapeHtml(cleanQuery)}»...</h4>
<p style="color: var(--text-muted); font-size: 0.86rem;">دەرهێنانی مانای فەرهەنگی، مەجازی و نموونەی بەکارهێنان بۆ ئەم وشەیە</p>
</div>
`;
try {
const isKurdishScript = /[\u0600-\u06FF]/.test(cleanQuery);
const isLatin = /^[a-zA-Z\s'-]+$/.test(cleanQuery);
let targetLang = isKurdishScript ? 'en' : 'ku';
let sourceLang = isKurdishScript ? 'ku' : 'auto';
let latinAsArabic = '';
if (isLatin && typeof kurdishTransliteration !== 'undefined') {
const converted = kurdishTransliteration.toArabic(cleanQuery);
if (converted && converted !== cleanQuery) {
latinAsArabic = converted;
}
}
// Translate query using Smart Multi-Engine Architecture
let translationResult;
if (state.apiKey && state.apiKey.trim().length > 10) {
try {
translationResult = await translateWithGemini(cleanQuery, sourceLang, targetLang, 'natural');
} catch (e) {
translationResult = await translateWithSmartEngine(cleanQuery, sourceLang, targetLang, 'natural');
}
} else {
translationResult = await translateWithSmartEngine(cleanQuery, sourceLang, targetLang, 'natural');
}
if (fetchId !== currentInsightFetchId) return;
let translated = (translationResult?.translation || '').trim();
if (!translated) {
translated = latinAsArabic || cleanQuery;
}
// Try finding synonyms or secondary meanings from kurdishDictionary
let secondaryMeaning = '';
const lowerQuery = cleanQuery.toLowerCase();
if (!isKurdishScript && kurdishDictionary?.enToKu?.[lowerQuery]) {
secondaryMeaning = kurdishDictionary.enToKu[lowerQuery];
} else if (isKurdishScript && kurdishDictionary?.kuToEn?.[lowerQuery]) {
secondaryMeaning = kurdishDictionary.kuToEn[lowerQuery];
}
const displayWord = cleanQuery.charAt(0).toUpperCase() + cleanQuery.slice(1);
const detectedLangName = isKurdishScript ? 'کوردی (Kurdish)' : (isLatin && latinAsArabic ? 'کوردی لاتینی (Latin Kurdish)' : 'ئینگلیزی (English)');
const phoneticTag = latinAsArabic ? `[${latinAsArabic}]` : (isLatin ? `/${cleanQuery.toLowerCase()}/` : `[${cleanQuery}]`);
const primaryKu = isKurdishScript ? cleanQuery : translated;
const primaryEn = isKurdishScript ? translated : cleanQuery;
const dynamicEntry = {
word: displayWord,
lang: detectedLangName,
phonetic: phoneticTag,
overview: `وشەی «${cleanQuery}» بە مانای سەرەکی (${translated})، لە دەق و گفتوگۆ جیاوازەکاندا بە چەندین شێواز بەکاردەهێنرێت:`,
meanings: [
{
num: 1,
pos: 'مانای بنەڕەتی و فەرهەنگی (Primary Meaning)',
ku: primaryKu,
en: primaryEn,
context: 'فەرهەنگی و پێناسەی سەرەکی',
exampleKu: isKurdishScript
? `وشەی «${cleanQuery}» لە زماندا بە مانای (${translated}) دێت.`
: `«${cleanQuery}» لە کوردیدا بە واتای «${translated}» بەکاردەهێنرێت.`,
exampleEn: `The word "${cleanQuery}" directly translates to "${translated}".`
},
{
num: 2,
pos: 'بەکارهێنانی ڕۆژانە (Daily & Practical Usage)',
ku: `بەکارهێنانی «${primaryKu}» لە گفتوگۆی ئاساییدا`,
en: `Everyday conversational usage of "${primaryEn}"`,
context: 'پەیوەندی و قسەکردنی ڕۆژانە',
exampleKu: `لە زمانی ڕۆژانەدا خەڵک بە شێوەیەکی فراوان کەڵک لە «${primaryKu}» وەردەگرن.`,
exampleEn: `In daily communication, people frequently use "${primaryEn}".`
},
{
num: 3,
pos: 'زاراوە و پەیوەندیدار (Idiomatic & Related Nuance)',
ku: secondaryMeaning ? `واتای نزیک: «${secondaryMeaning}»` : `دەربڕینی تایبەت و پەیوەست بە «${primaryKu}»`,
en: `Idiomatic expression or related meaning of "${primaryEn}"`,
context: 'دەربڕینی فراوان',
exampleKu: `وشەی «${primaryKu}» دەکرێت لە چەندین بارودۆخی جیاوازدا مەبەستی تایبەت بگەیەنێت.`,
exampleEn: `Depending on the sentence, "${primaryEn}" can express distinct nuances.`
}
]
};
// Cache dynamic entry so next search is instant
wordInsightsDatabase[cleanQuery.toLowerCase()] = dynamicEntry;
if (latinAsArabic) {
wordInsightsDatabase[latinAsArabic.toLowerCase()] = dynamicEntry;
}
renderWordInsightData(dynamicEntry, cleanQuery.toLowerCase());
} catch (err) {
if (fetchId !== currentInsightFetchId) return;
console.error('Dynamic insight generation error:', err);
container.innerHTML = `
<div class="word-entry-card" style="text-align: center; padding: 30px 20px;">
<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" style="display:block;margin:0 auto 10px;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
<h4 style="color: #fff; margin-bottom: 6px;">وشەی «${escapeHtml(cleanQuery)}»</h4>
<p style="color: var(--text-muted); font-size: 0.88rem;">نەتوانرا شیکردنەوەی بۆ بکرێت. دەتوانی کلیک لەسەر یەکێک لە وشە ئامادەکراوەکانی سەرەوە بکەیت.</p>
</div>
`;
}
}
// Master Render Word Insight Function
function renderWordInsight(wordKey) {
const container = document.getElementById('insightsBody');
if (!container) return;
const raw = (wordKey || '').trim();
if (!raw) return;
const resolved = resolveInsightKey(raw);
if (resolved && wordInsightsDatabase[resolved]) {
renderWordInsightData(wordInsightsDatabase[resolved], resolved);
return;
}
// Dynamic analysis for arbitrary words
generateDynamicWordInsight(raw);
}
// Automatically detect polysemous words when user translates
function checkAndHighlightWordInsights(sourceText, targetText) {
const combined = `${sourceText || ''} ${targetText || ''}`.toLowerCase().replace(/[.,!?;:()[\]{}"'`]/g, ' ');
const words = combined.split(/\s+/).filter(w => w.length >= 2);
for (const w of words) {
const match = resolveInsightKey(w);
if (match) {
renderWordInsight(match);
const section = document.getElementById('wordInsightsSection');
if (section) {
section.classList.remove('tone-pulse');
void section.offsetWidth;
section.classList.add('tone-pulse');
}
return;
}
}
}
// Initialize Word Insights Component
let insightDebounceTimer = null;
function initWordInsights() {
const searchInput = document.getElementById('wordInsightSearch');
const clearBtn = document.getElementById('clearInsightSearchBtn');
const chips = document.querySelectorAll('.insight-chip');
// Initial render: default 'right'
renderWordInsight('right');
// Chip click handlers
chips.forEach(chip => {
chip.addEventListener('click', () => {
playSubtleClick();
const word = chip.getAttribute('data-word');
if (searchInput) {
searchInput.value = '';
if (clearBtn) clearBtn.classList.add('hidden');
}
renderWordInsight(word);
});
});
// Clear button click handler
if (clearBtn && searchInput) {
clearBtn.addEventListener('click', () => {
searchInput.value = '';
clearBtn.classList.add('hidden');
searchInput.focus();
renderWordInsight('right');
});
}
// Search input handler with debounce
if (searchInput) {
searchInput.addEventListener('input', () => {
const q = searchInput.value.trim();
if (clearBtn) {
if (q) {
clearBtn.classList.remove('hidden');
} else {
clearBtn.classList.add('hidden');
}
}
clearTimeout(insightDebounceTimer);
if (!q) {
renderWordInsight('right');
return;
}
// Check if immediate match is available
const quickMatch = resolveInsightKey(q);
if (quickMatch) {
renderWordInsight(quickMatch);
return;
}
// Debounce dynamic translation request by 350ms so user can finish typing
insightDebounceTimer = setTimeout(() => {
renderWordInsight(q);
}, 350);
});
// Enter key triggers immediate search
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const q = searchInput.value.trim();
if (q) {
clearTimeout(insightDebounceTimer);
renderWordInsight(q);
}
}
});
}
}
// Extend initApp to include chat, word insights, and Kurdish voice studio
const originalInitApp = initApp;
initApp = function() {
originalInitApp();
initGlobalChat();
initWordInsights();
if (typeof kurdishVoiceSynthesizer !== 'undefined') {
kurdishVoiceSynthesizer.renderPodcasts();
kurdishVoiceSynthesizer.updatePhonetics('سڵاو، چۆنی؟ بەخێربێیت بۆ ترانسلێت.');
}
};
// ==========================================================================
// Voice vs Voice (VC) Real-Time Bidirectional Conversation System
// ==========================================================================
const VC_LANGUAGES = {
ku: {
code: 'ku',
flag: '☀️',
name: 'کوردی (سۆرانی)',
speakerBadge: 'دەنگی تۆ (کوردی)',
speakBtnText: 'قسەکردن بە کوردی',
hintText: 'پەنجە بنێ بۆ دەستپێکردن، دوای قسەکردن پەنجە بنێ بۆ وەرگێڕان',
promptName: 'authentic Sorani Kurdish (سۆرانی)',
bcp47: 'ckb-IQ'
},
en: {
code: 'en',
flag: '🇬🇧',
name: 'ئینگلیزی (English)',
speakerBadge: 'دەنگی بەرامبەر (English)',
speakBtnText: 'Speak in English',
hintText: 'Tap to start recording, tap again when done to translate',
promptName: 'natural, fluent English',
bcp47: 'en-US'
},
ar: {
code: 'ar',
flag: '🇮🇶',
name: 'عەرەبی (العربية)',
speakerBadge: 'دەنگی بەرامبەر (عەرەبی)',
speakBtnText: 'التحدث بالعربية',
hintText: 'اضغط للبدء، اضغط مرة أخرى عند الانتهاء للترجمة',
promptName: 'natural, clear Arabic (العربية)',
bcp47: 'ar-SA'
},
de: {
code: 'de',
flag: '🇩🇪',
name: 'ئەڵمانی (Deutsch)',
speakerBadge: 'دەنگی بەرامبەر (ئەڵمانی)',
speakBtnText: 'Auf Deutsch sprechen',
hintText: 'Tippen zum Aufnehmen, erneut tippen zum Übersetzen',
promptName: 'natural, fluent German (Deutsch)',
bcp47: 'de-DE'
},
tr: {
code: 'tr',
flag: '🇹🇷',
name: 'تورکی (Türkçe)',
speakerBadge: 'دەنگی بەرامبەر (تورکی)',
speakBtnText: 'Türkçe Konuş',
hintText: 'Kayıt için dokunun, bitince çeviri için tekrar dokunun',
promptName: 'natural, fluent Turkish (Türkçe)',
bcp47: 'tr-TR'
},
fa: {
code: 'fa',
flag: '🇮🇷',
name: 'فارسی (فارسی)',
speakerBadge: 'دەنگی بەرامبەر (فارسی)',
speakBtnText: 'صحبت کردن به فارسی',
hintText: 'برای ضبط لمس کنید، برای ترجمه دوباره لمس کنید',
promptName: 'natural, fluent Persian (فارسی)',
bcp47: 'fa-IR'
},
fr: {
code: 'fr',
flag: '🇫🇷',
name: 'فەڕەنسی (Français)',
speakerBadge: 'دەنگی بەرامبەر (فەڕەنسی)',
speakBtnText: 'Parler en français',
hintText: 'Appuyez pour enregistrer, appuyez à nouveau pour traduire',
promptName: 'natural, fluent French (Français)',
bcp47: 'fr-FR'
},
es: {
code: 'es',
flag: '🇪🇸',
name: 'ئیسپانی (Español)',
speakerBadge: 'دەنگی بەرامبەر (ئیسپانی)',
speakBtnText: 'Hablar en español',
hintText: 'Toca para grabar, toca de nuevo al terminar para traducir',
promptName: 'natural, fluent Spanish (Español)',
bcp47: 'es-ES'
}
};
const voiceVcState = {
isRecording: false,
activeSpeaker: null,
mediaRecorder: null,
audioChunks: [],
stream: null,
historyCount: 0,
activeTriggerBtn: null,
audioContext: null,
vadInterval: null,
timerInterval: null,
recordingStartTime: 0,
lastToggleTime: 0,
speaker1Lang: localStorage.getItem('vc_speaker1_lang') || 'ku',
speaker2Lang: localStorage.getItem('vc_speaker2_lang') || 'en'
};
function initVoiceVcSystem() {
const navVoiceVcBtn = document.getElementById('navVoiceVcBtn');
const navTranslatorBtn = document.getElementById('navTranslatorBtn');
const navChatBtn = document.getElementById('navChatBtn');
const translatorView = document.getElementById('translatorView');
const voiceVcView = document.getElementById('voiceVcView');
const chatView = document.getElementById('chatView');
const openFullVcViewBtn = document.getElementById('openFullVcViewBtn');
const switchToVcView = () => {
if (typeof playSubtleClick === 'function') playSubtleClick();
if (navVoiceVcBtn) navVoiceVcBtn.classList.add('active');
if (navTranslatorBtn) navTranslatorBtn.classList.remove('active');
if (navChatBtn) navChatBtn.classList.remove('active');
if (voiceVcView) voiceVcView.classList.remove('hidden');
if (translatorView) translatorView.classList.add('hidden');
if (chatView) chatView.classList.add('hidden');
// Get our Kurdish voice and ear ready now (one after the other), before the first sentence
try { warmUpVoiceAndEar(); } catch (_) {}
};
const switchToTranslator = () => {
if (typeof playSubtleClick === 'function') playSubtleClick();
if (navTranslatorBtn) navTranslatorBtn.classList.add('active');
if (navVoiceVcBtn) navVoiceVcBtn.classList.remove('active');
if (navChatBtn) navChatBtn.classList.remove('active');
if (translatorView) translatorView.classList.remove('hidden');
if (voiceVcView) voiceVcView.classList.add('hidden');
if (chatView) chatView.classList.add('hidden');
};
const switchToChat = () => {
if (typeof playSubtleClick === 'function') playSubtleClick();
if (navChatBtn) navChatBtn.classList.add('active');
if (navTranslatorBtn) navTranslatorBtn.classList.remove('active');
if (navVoiceVcBtn) navVoiceVcBtn.classList.remove('active');
if (chatView) chatView.classList.remove('hidden');
if (translatorView) translatorView.classList.add('hidden');
if (voiceVcView) voiceVcView.classList.add('hidden');
if (typeof scrollChatToBottom === 'function') scrollChatToBottom();
};
if (navVoiceVcBtn) navVoiceVcBtn.addEventListener('click', switchToVcView);
if (openFullVcViewBtn) openFullVcViewBtn.addEventListener('click', switchToVcView);
if (navTranslatorBtn) {
navTranslatorBtn.addEventListener('click', switchToTranslator);
}
if (navChatBtn) {
navChatBtn.addEventListener('click', switchToChat);
}
const vcWaveformBar = document.getElementById('vcWaveformBar');
const vcStatusText = document.getElementById('vcStatusText');
const vcAutoSpeakToggle = document.getElementById('vcAutoSpeakToggle');
const clearVcHistoryBtn = document.getElementById('clearVcHistoryBtn');
const vcConversationFeed = document.getElementById('vcConversationFeed');
const vcCountBadge = document.getElementById('vcCountBadge');
const vcSpeaker1Select = document.getElementById('vcSpeaker1Select');
const vcSpeaker2Select = document.getElementById('vcSpeaker2Select');
const vcSwapLangsBtn = document.getElementById('vcSwapLangsBtn');
const vcKurdishMicBtn = document.getElementById('vcKurdishMicBtn');
const vcEnglishMicBtn = document.getElementById('vcEnglishMicBtn');
const vcAutoDetectMicBtn = document.getElementById('vcAutoDetectMicBtn');
const quickKurdishMicBtn = document.getElementById('quickKurdishMicBtn');
const quickEnglishMicBtn = document.getElementById('quickEnglishMicBtn');
function updateVcLanguageUI() {
const s1 = voiceVcState.speaker1Lang || 'ku';
const s2 = voiceVcState.speaker2Lang || 'en';
const info1 = VC_LANGUAGES[s1] || VC_LANGUAGES.ku;
const info2 = VC_LANGUAGES[s2] || VC_LANGUAGES.en;
const s1Badge = document.getElementById('vcSpeaker1Badge');
const s1Flag = document.getElementById('vcSpeaker1Flag');
const s1Title = document.getElementById('vcSpeaker1Title');
const s1Hint = document.getElementById('vcSpeaker1Hint');
const s1BtnLabel = document.getElementById('vcSpeaker1BtnLabel');
const s2Badge = document.getElementById('vcSpeaker2Badge');
const s2Flag = document.getElementById('vcSpeaker2Flag');
const s2Title = document.getElementById('vcSpeaker2Title');
const s2Hint = document.getElementById('vcSpeaker2Hint');
const s2BtnLabel = document.getElementById('vcSpeaker2BtnLabel');
const subtitle = document.getElementById('vcSubtitle');
const autoLabel = document.getElementById('vcAutoBtnLabel');
if (s1Badge) s1Badge.textContent = `دەنگی تۆ (${info1.name})`;
if (s1Flag) s1Flag.textContent = info1.flag;
if (s1Title) s1Title.textContent = info1.name;
if (s1Hint) s1Hint.textContent = info1.hintText;
if (s1BtnLabel) s1BtnLabel.textContent = info1.speakBtnText;
if (vcKurdishMicBtn) vcKurdishMicBtn.title = info1.speakBtnText;
if (s2Badge) s2Badge.textContent = `دەنگی بەرامبەر (${info2.name})`;
if (s2Flag) s2Flag.textContent = info2.flag;
if (s2Title) s2Title.textContent = info2.name;
if (s2Hint) s2Hint.textContent = info2.hintText;
if (s2BtnLabel) s2BtnLabel.textContent = info2.speakBtnText;
if (vcEnglishMicBtn) vcEnglishMicBtn.title = info2.speakBtnText;
if (subtitle) {
subtitle.textContent = `بە ${info1.name} بدوێ ئەپەکە بە دەنگ دەیکاتە ${info2.name}، بە ${info2.name} قسە بکە دەیکاتە دەنگی ${info1.name}!`;
}
if (autoLabel) {
autoLabel.textContent = `دۆزینەوەی خۆکار (${info1.flag} ⇄ ${info2.flag})`;
}
if (vcAutoDetectMicBtn) {
vcAutoDetectMicBtn.title = `دۆزینەوەی خۆکار: بە ${info1.name} یان ${info2.name} بدوێ خۆی دەیدۆزێتەوە و وەریدەگێڕێت`;
}
if (vcStatusText && !voiceVcState.isRecording) {
vcStatusText.textContent = `ئامادەیە بۆ گفتوگۆ (${info1.name} ⇄ ${info2.name}) — پەنجە بە مایکرۆفۆنێک بنێ و قسە بکە...`;
}
try {
localStorage.setItem('vc_speaker1_lang', s1);
localStorage.setItem('vc_speaker2_lang', s2);
} catch (_) {}
}
if (vcSpeaker1Select) {
vcSpeaker1Select.value = voiceVcState.speaker1Lang;
vcSpeaker1Select.addEventListener('change', (e) => {
let val = e.target.value;
if (val === voiceVcState.speaker2Lang) {
voiceVcState.speaker2Lang = voiceVcState.speaker1Lang;
if (vcSpeaker2Select) vcSpeaker2Select.value = voiceVcState.speaker2Lang;
}
voiceVcState.speaker1Lang = val;
updateVcLanguageUI();
});
}
if (vcSpeaker2Select) {
vcSpeaker2Select.value = voiceVcState.speaker2Lang;
vcSpeaker2Select.addEventListener('change', (e) => {
let val = e.target.value;
if (val === voiceVcState.speaker1Lang) {
voiceVcState.speaker1Lang = voiceVcState.speaker2Lang;
if (vcSpeaker1Select) vcSpeaker1Select.value = voiceVcState.speaker1Lang;
}
voiceVcState.speaker2Lang = val;
updateVcLanguageUI();
});
}
if (vcSwapLangsBtn) {
vcSwapLangsBtn.addEventListener('click', () => {
const temp = voiceVcState.speaker1Lang;
voiceVcState.speaker1Lang = voiceVcState.speaker2Lang;
voiceVcState.speaker2Lang = temp;
if (vcSpeaker1Select) vcSpeaker1Select.value = voiceVcState.speaker1Lang;
if (vcSpeaker2Select) vcSpeaker2Select.value = voiceVcState.speaker2Lang;
updateVcLanguageUI();
if (typeof playSubtleClick === 'function') playSubtleClick();
});
}
updateVcLanguageUI();
let _vcAudioPlayer = null;
let _vcPlaybackToken = 0;
let _vcAudioContext = null;
let _vcCurrentSourceNode = null;
function getVcAudioContext() {
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (AudioCtx) {
if (!_vcAudioContext) {
_vcAudioContext = new AudioCtx();
}
if (_vcAudioContext.state === 'suspended') {
_vcAudioContext.resume().catch(() => {});
}
}
} catch (_) {}
return _vcAudioContext;
}
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
function stopVcAudio() {
_vcPlaybackToken++;
_stopSpeech();
if (_vcCurrentSourceNode) {
try { _vcCurrentSourceNode.stop(); } catch (_) {}
try { _vcCurrentSourceNode.disconnect(); } catch (_) {}
_vcCurrentSourceNode = null;
}
if (_vcAudioPlayer) {
_vcAudioPlayer.onended = null;
_vcAudioPlayer.onerror = null;
try {
_vcAudioPlayer.pause();
_vcAudioPlayer.currentTime = 0;
} catch (_) {}
}
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
}
window._stopVcAudio = stopVcAudio;
function unlockVcAudioPlayer() {
// 1. Prime the AudioContext on user gesture (Crucial for iOS Safari & Android Chrome)
const ctx = getSilkAudioContext() || getVcAudioContext();
if (ctx && ctx.state === 'suspended') {
ctx.resume().catch(() => {});
}
// 2. Prime the HTML5 Audio elements with mobile playsinline attributes
const dummySilentWav = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
if (!_ttsAudioEl) {
_ttsAudioEl = new Audio();
_ttsAudioEl.preload = 'auto';
_ttsAudioEl.setAttribute('playsinline', 'true');
_ttsAudioEl.setAttribute('webkit-playsinline', 'true');
}
if (!_vcAudioPlayer) {
_vcAudioPlayer = new Audio();
_vcAudioPlayer.preload = 'auto';
_vcAudioPlayer.setAttribute('playsinline', 'true');
_vcAudioPlayer.setAttribute('webkit-playsinline', 'true');
}
try {
_ttsAudioEl.src = dummySilentWav;
const p1 = _ttsAudioEl.play();
if (p1 && typeof p1.then === 'function') {
p1.then(() => { try { _ttsAudioEl.pause(); } catch (_) {} }).catch(() => {});
}
_vcAudioPlayer.src = dummySilentWav;
const p2 = _vcAudioPlayer.play();
if (p2 && typeof p2.then === 'function') {
p2.then(() => { try { _vcAudioPlayer.pause(); } catch (_) {} }).catch(() => {});
}
} catch (_) {}
}
if (vcAutoSpeakToggle) {
vcAutoSpeakToggle.checked = true;
}
if (clearVcHistoryBtn && vcConversationFeed) {
clearVcHistoryBtn.addEventListener('click', () => {
vcConversationFeed.innerHTML = `
<div class="vc-empty-placeholder">
<span style="font-size: 2.2rem;">🎙️ ⇄ 🎧</span>
<h4 style="color: #fff; margin: 8px 0 4px;">ژووری وەرگێڕی ڕاستەوخۆی دەنگی (Voice vs Voice)</h4>
<p style="color: #94a3b8; font-size: 0.82rem; max-width: 480px; margin: 0 auto;">
مێژووی گفتوگۆ سڕایەوە. پەنجە بە مایکرۆفۆن بنێ و دەست بکە بە قسەکردن!
</p>
</div>
`;
voiceVcState.historyCount = 0;
if (vcCountBadge) vcCountBadge.textContent = '٠ وتە';
showToast('مێژووی گفتوگۆ پاککرایەوە', '🗑️');
});
}
function addVcDialogue(sourceText, translatedText, sourceLang, targetLang, preloadedAudioBase64, audioMime, directAudioUrl) {
if (!vcConversationFeed) return;
LalaStats.count('v');
if (sourceLang === 'ku') sourceText = fixKurdishSoraniGreetings(sourceText);
if (targetLang === 'ku') translatedText = fixKurdishSoraniGreetings(translatedText);
const placeholder = vcConversationFeed.querySelector('.vc-empty-placeholder');
if (placeholder) placeholder.remove();
voiceVcState.historyCount++;
if (vcCountBadge) vcCountBadge.textContent = `${voiceVcState.historyCount} وتە`;
const s1 = voiceVcState.speaker1Lang || 'ku';
const s2 = voiceVcState.speaker2Lang || 'en';
const info1 = VC_LANGUAGES[s1] || VC_LANGUAGES.ku;
const info2 = VC_LANGUAGES[s2] || VC_LANGUAGES.en;
const isSpeaker1 = (sourceLang === s1);
const speakerInfo = isSpeaker1 ? info1 : info2;
const targetInfo = isSpeaker1 ? info2 : info1;
const item = document.createElement('div');
item.className = `vc-dialogue-item ${isSpeaker1 ? 'kurdish-turn' : 'english-turn'}`;
const speakerName = `${speakerInfo.flag} ${speakerInfo.name}`;
const targetVoiceLabel = `وەرگێڕ (${targetInfo.flag} ${targetInfo.name})`;
const now = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
item.innerHTML = `
<div class="vc-dialogue-header">
<span style="font-weight: 700; color: ${isSpeaker1 ? '#fca5a5' : '#93c5fd'};">
${speakerName}
</span>
<span>${now}</span>
</div>
<div class="vc-turn-original">${escapeHtml(sourceText)}</div>
<div class="vc-turn-translated">
<div style="flex: 1;">
<div style="font-size: 0.72rem; color: var(--text-dim); margin-bottom: 2px;">${targetVoiceLabel}:</div>
<div class="vc-translated-text">${escapeHtml(translatedText)}</div>
</div>
<button class="vc-play-turn-btn" title="دووبارە گوێگرتنەوە" aria-label="گوێگرتن لە دەنگەکە">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<polygon points="5 3 19 12 5 21 5 3"></polygon>
</svg>
</button>
</div>
`;
const playBtn = item.querySelector('.vc-play-turn-btn');
if (playBtn) {
const handlePlay = (e) => {
if (e) e.stopPropagation();
unlockVcAudioPlayer();
const isTargetKu = targetLang === 'ku' || (targetLang === 'auto' && /[\u0600-\u06FF]/.test(translatedText) && (s1 === 'ku' || s2 === 'ku'));
if (isTargetKu) {
playKurdishSentenceStream(translatedText, 'sorani');
} else {
playVcAudio(translatedText, targetLang, preloadedAudioBase64, audioMime, directAudioUrl);
}
};
playBtn.addEventListener('click', handlePlay);
playBtn.addEventListener('touchstart', () => unlockVcAudioPlayer(), { passive: true });
}
vcConversationFeed.appendChild(item);
vcConversationFeed.scrollTop = vcConversationFeed.scrollHeight;
}
function playVcAudio(text, lang, preloadedAudioBase64, audioMime, directAudioUrl) {
if (!text) return;
stopVcAudio();
const currentToken = ++_vcPlaybackToken;
const cleanLang = (lang || '').toLowerCase().trim();
const s1 = voiceVcState.speaker1Lang || 'ku';
const s2 = voiceVcState.speaker2Lang || 'en';
const isKurdish = cleanLang === 'ku' || (cleanLang === 'auto' && /[\u0600-\u06FF]/.test(text) && (s1 === 'ku' || s2 === 'ku'));
if (isKurdish) text = normalizeKurdishNumbers(fixKurdishSoraniGreetings(text));
const lInfo = VC_LANGUAGES[cleanLang] || { name: cleanLang };
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar speaking';
if (vcStatusText) {
vcStatusText.textContent = isKurdish
? '🔊 بێژەری سۆرانی دەدوێت...'
: `🔊 بێژەری ${lInfo.name || cleanLang} دەدوێت...`;
}
const onPlaybackComplete = () => {
if (currentToken !== _vcPlaybackToken) return;
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'ئامادەیە بۆ وەرگرتنی وتەی تر...';
};
if (directAudioUrl) {
playSilkStudioAudio(directAudioUrl, {
filter: isKurdish,
onStart: () => {},
onEnd: onPlaybackComplete
});
return;
}
if (preloadedAudioBase64 && preloadedAudioBase64.length > 200) {
playSilkStudioAudio(preloadedAudioBase64, {
filter: isKurdish,
onStart: () => {},
onEnd: onPlaybackComplete
});
return;
}
_playNeuralFallback(text, cleanLang);
}
function _playNeuralFallback(text, lang) {
const lInfo = VC_LANGUAGES[lang] || { name: lang };
_playNeuralTTS(text, lang, {
speed: 1.0,
onStart: () => {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar speaking';
if (vcStatusText) {
vcStatusText.textContent = (lang === 'ku')
? '🔊 بێژەری کوردیی سۆرانی (ڕەسەن) دەدوێت...'
: `🔊 بێژەری ${lInfo.name || lang} دەدوێت...`;
}
},
onEnd: () => {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'ئامادەیە بۆ وەرگرتنی وتەی تر...';
}
});
}
// Ultra-Fast Progressive Sentence-by-Sentence Kurdish Speech Streaming
// Synthesizes first sentence in ~1.2s so user hears voice speaking immediately,
// while subsequent sentences are synthesized in the background with zero gaps!
function playKurdishSentenceStream(fullText, dialect = 'sorani') {
const clean = normalizeKurdishNumbers(fixKurdishSoraniGreetings((fullText || '').trim()));
if (!clean) return;
_stopSpeech();
const currentToken = ++_vcPlaybackToken;
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar speaking';
if (vcStatusText) vcStatusText.textContent = '🔊 بێژەری کوردیی سۆرانی دەدوێت...';
// Split text into natural sentence boundaries
const rawParts = clean.split(/(?<=[.!?؟\n])\s+/);
const sentences = [];
for (const p of rawParts) {
const trimmed = p.trim();
if (!trimmed) continue;
// Only very long sentences are cut at commas (cutting short ones breaks numbers)
if (trimmed.split(/\s+/).length > 40) {
const sub = trimmed.split(/(?<=[،,])\s+/);
for (const sp of sub) if (sp.trim()) sentences.push(sp.trim());
} else {
sentences.push(trimmed);
}
}
if (sentences.length === 0) return;
const audioUrls = new Array(sentences.length).fill(null);
let playIndex = 0;
let isPlaying = false;
const playNextSentence = () => {
if (currentToken !== _vcPlaybackToken) return;
if (playIndex >= sentences.length) {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'ئامادەیە بۆ وەرگرتنی وتەی تر...';
isPlaying = false;
return;
}
const nextUrl = audioUrls[playIndex];
if (nextUrl) {
isPlaying = true;
playIndex++;
playSilkStudioAudio(nextUrl, {
filter: true,
onEnd: () => {
if (currentToken === _vcPlaybackToken) {
playNextSentence();
}
}
});
} else {
isPlaying = false;
}
};
// Synthesize sentence 0 immediately (< 1.2s)
synthesizeNativeKurdishClient(sentences[0], dialect).then(url => {
if (currentToken !== _vcPlaybackToken) return;
audioUrls[0] = url;
if (!isPlaying) {
playNextSentence();
}
}).catch(() => {});
// Pipeline remaining sentences in background
for (let i = 1; i < sentences.length; i++) {
const idx = i;
synthesizeNativeKurdishClient(sentences[idx], dialect).then(url => {
if (currentToken !== _vcPlaybackToken) return;
audioUrls[idx] = url;
if (!isPlaying && playIndex === idx) {
playNextSentence();
}
}).catch(() => {});
}
}
function buildVcPrompt(spokenLang, lang1Code, lang2Code) {
const l1 = VC_LANGUAGES[lang1Code] || VC_LANGUAGES.ku;
const l2 = VC_LANGUAGES[lang2Code] || VC_LANGUAGES.en;
const kurdishRules = `
CRITICAL KURDISH RULES:
- Use authentic Sorani e.g. برام, هاوڕێکەم, سڵاو; never literal Persian/Arabic calques like برای من, هاوڕێی من.
- NUMBERS AND DATES: Write numbers, dates, times, days, and months clearly in natural Kurdish words (e.g. پازدەی ئایاری دوو هەزار و بیست و چوار, سەد و پەنجا, کاتژمێر دە و نیو) so the Kurdish voice speaks them fluently.
- TELEPHONE NUMBERS: In Kurdish, phone numbers are NEVER spoken digit-by-digit. Group into authentic Kurdish cadence: prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا), middle 3 digits (چوارسەد و یەک), 2 digits (شەست و هەشت), 2 digits (دە / دەیە). e.g. '07704016810' -> 'سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە'.`;
let instruction = "";
if (spokenLang === lang1Code) {
const isTargetKu = (lang2Code === 'ku');
instruction = `The speaker is speaking ${l1.promptName}.\n1. Transcribe the spoken speech accurately in 'sourceText'.\n2. Translate into natural, complete ${l2.promptName} in 'translatedText'.${isTargetKu ? '\n' + kurdishRules : ''}\nIf silence or noise: return silence: true.`;
} else if (spokenLang === lang2Code) {
const isTargetKu = (lang1Code === 'ku');
instruction = `The speaker is speaking ${l2.promptName}.\n1. Transcribe the spoken speech accurately in 'sourceText'.\n2. Translate into natural, complete ${l1.promptName} in 'translatedText'.${isTargetKu ? '\n' + kurdishRules : ''}\nIf silence or noise: return silence: true.`;
} else {
// Auto detect between the two selected languages
const isL1Ku = (lang1Code === 'ku');
const isL2Ku = (lang2Code === 'ku');
instruction = `Detect whether the speaker spoke ${l1.promptName} or ${l2.promptName}.\n1. Transcribe accurately in 'sourceText'.\n2. If speaker spoke ${l1.promptName}, set sourceLang='${lang1Code}', targetLang='${lang2Code}', and translate into ${l2.promptName} in 'translatedText'.${isL2Ku ? '\n' + kurdishRules : ''}\n3. If speaker spoke ${l2.promptName}, set sourceLang='${lang2Code}', targetLang='${lang1Code}', and translate into ${l1.promptName} in 'translatedText'.${isL1Ku ? '\n' + kurdishRules : ''}\nIf silence or noise: return silence: true.`;
}
return `${instruction}\nCRITICAL: If audio is silence, background noise, or unintelligible, return: {"sourceText": "", "translatedText": "", "silence": true}\nReturn ONLY valid JSON with keys: sourceText, translatedText, sourceLang, targetLang, silence`;
}
async function transcribeAndTranslateVoiceClient(audioBlob, b64Data, spokenLang) {
const apiKey = (typeof state !== 'undefined' && state.apiKey) || DEFAULT_GEMINI_API_KEY;
if (!apiKey) {
// No personal key in this browser: let the server translate (it holds the key privately)
throw new Error('No browser API key; using server');
}
const mime = (audioBlob && audioBlob.type) ? audioBlob.type.split(';')[0].trim() : 'audio/webm';
const s1 = voiceVcState.speaker1Lang || 'ku';
const s2 = voiceVcState.speaker2Lang || 'en';
const prompt = buildVcPrompt(spokenLang, s1, s2);
// Only ultra-fast Gemini 3.1 Flash-Lite (Verified 2.58s on 2 full minutes of audio)
const models = [
'gemini-3.1-flash-lite',
'gemini-3.1-flash-lite-preview'
];
for (const m of models) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 14000);
const url = `https://generativelanguage.googleapis.com/v1beta/models/${m}:generateContent?key=${apiKey}`;
const payload = {
contents: [{
parts: [
{ text: prompt },
{ inline_data: { mime_type: mime, data: b64Data } }
]
}],
generationConfig: {
responseMimeType: "application/json",
temperature: 0.0,
maxOutputTokens: 2048
}
};
const resp = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal
});
clearTimeout(timeoutId);
if (resp.ok) {
const respData = await resp.json();
const raw = respData?.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || '{}';
let cleaned = raw;
if (cleaned.startsWith('```json')) cleaned = cleaned.slice(7);
else if (cleaned.startsWith('```')) cleaned = cleaned.slice(3);
if (cleaned.endsWith('```')) cleaned = cleaned.slice(0, -3);
const parsed = JSON.parse(cleaned.trim());
if (!parsed.sourceLang) {
parsed.sourceLang = (spokenLang === s1 || spokenLang === s2) ? spokenLang : 'auto';
}
if (!parsed.targetLang) {
parsed.targetLang = parsed.sourceLang === s1 ? s2 : s1;
}
return parsed;
}
} catch (e) {
console.warn(`Model ${m} failed in client fallback:`, e);
}
}
throw new Error("Client Gemini fallback failed");
}
async function startVcRecording(spokenLang, triggerBtn) {
if (voiceVcState.isRecording) {
stopVcRecording(true);
return;
}
// Stop any existing audio so the mic never records the phone's own speaker
stopVcAudio();
unlockVcAudioPlayer();
// Get our own Kurdish ear ready in the background (backup when Google is full or busy)
if ([spokenLang, voiceVcState.speaker1Lang, voiceVcState.speaker2Lang].includes('ku')) {
try { startLalaEar(); } catch (_) {}
}
voiceVcState.hasSpoken = false;
voiceVcState.speechSamplesCount = 0;
voiceVcState.manualStop = false;
try {
// High-performance voice speech constraints (16kHz mono captures full human voice at 1/3 the data size)
const audioConstraints = {
echoCancellation: { ideal: true },
noiseSuppression: { ideal: true },
autoGainControl: { ideal: true },
channelCount: { ideal: 1 },
sampleRate: { ideal: 16000 }
};
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: audioConstraints });
} catch (_) {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
}
voiceVcState.stream = stream;
voiceVcState.audioChunks = [];
voiceVcState.activeSpeaker = spokenLang;
voiceVcState.activeTriggerBtn = triggerBtn;
// Select supported audio mimeType
let mimeType = 'audio/webm;codecs=opus';
if (!MediaRecorder.isTypeSupported(mimeType)) {
mimeType = 'audio/webm';
if (!MediaRecorder.isTypeSupported(mimeType)) {
mimeType = 'audio/mp4';
if (!MediaRecorder.isTypeSupported(mimeType)) {
mimeType = '';
}
}
}
voiceVcState.mimeType = mimeType;
let mediaRecorder;
try {
const recorderOptions = { audioBitsPerSecond: 24000 };
if (mimeType) recorderOptions.mimeType = mimeType;
mediaRecorder = new MediaRecorder(stream, recorderOptions);
} catch (_) {
const recorderOptions = mimeType ? { mimeType } : undefined;
mediaRecorder = new MediaRecorder(stream, recorderOptions);
}
voiceVcState.mediaRecorder = mediaRecorder;
mediaRecorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) {
voiceVcState.audioChunks.push(e.data);
}
};
mediaRecorder.onstop = async () => {
if (voiceVcState.timerInterval) {
clearInterval(voiceVcState.timerInterval);
voiceVcState.timerInterval = null;
}
if (voiceVcState.vadInterval) {
clearInterval(voiceVcState.vadInterval);
voiceVcState.vadInterval = null;
}
if (voiceVcState.audioContext) {
try {
if (voiceVcState.audioContext.state !== 'closed') {
voiceVcState.audioContext.close();
}
} catch (_) {}
voiceVcState.audioContext = null;
}
stream.getTracks().forEach(t => t.stop());
stopBrowserListening(); // its text (if any) is kept for the backup below
if (triggerBtn) {
triggerBtn.classList.remove('recording');
const orig = triggerBtn.getAttribute('data-original-html');
if (orig) triggerBtn.innerHTML = orig;
}
voiceVcState.manualStop = false;
const audioBlob = new Blob(voiceVcState.audioChunks, { type: voiceVcState.mimeType || 'audio/webm' });
const hadSpoken = !!voiceVcState.hasSpoken;
const elapsedSec = (Date.now() - (voiceVcState.recordingStartTime || 0)) / 1000;
// If user tapped without speaking, or the microphone only heard silence / ambient noise:
if (!hadSpoken || audioBlob.size < 2200 || elapsedSec < 0.6) {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) {
vcStatusText.textContent = 'هیچ دەنگێک تۆمار نەکرا، تکایە کاتێک قسە دەکەیت دوگمەکە دابگرە...';
}
return;
}
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar speaking';
if (vcStatusText) vcStatusText.textContent = '⚡ دەنگەکەت وەرگیرا، بە خێرایی وەردەگێڕدرێت...';
try {
// Convert Blob to base64 using Promise
const b64 = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
try {
const res = reader.result;
if (typeof res === 'string') {
resolve(res.split(',')[1] || '');
} else {
resolve('');
}
} catch (e) {
reject(e);
}
};
reader.onerror = reject;
reader.readAsDataURL(audioBlob);
});
if (!b64) {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'دەنگەکە بەتاڵ بوو، تکایە دووبارە قسە بکەرەوە.';
return;
}
const isStaticCloud = isStaticOnlyHost();
const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const apiBase = isLocal ? '' : ((window.location.protocol === 'file:' || !window.location.host) ? 'http://localhost:3000' : '');
const isElevenLabsEnabled = localStorage.getItem('elevenlabs_enabled') === 'true';
const elevenLabsApiKey = localStorage.getItem('elevenlabs_api_key') || '';
const elevenLabsVoiceId = localStorage.getItem('elevenlabs_voice_id') || '';
let data = null;
let fetchErr = null;
const vcS1 = voiceVcState.speaker1Lang || 'ku';
const vcS2 = voiceVcState.speaker2Lang || 'en';
// Kurdish speech is heard by OUR OWN ear first (inside the phone, free, no daily limit).
// Only the explicit Kurdish button (or Auto with no Kurdish-only doubt) goes to our ear first.
const kurdishSpeaker = spokenLang === 'ku' || (spokenLang === 'auto' && (vcS1 === 'ku' || vcS2 === 'ku'));
const earFirst = spokenLang === 'ku';
voiceVcState.earReport = '';
let earPromise = null;
const earListenAndTranslate = async () => {
if (vcStatusText) vcStatusText.textContent = '👂 گوێی کوردی گوێ دەگرێت...';
let heard = '';
if (!(window.LalaEar && window.LalaEar.isLoaded())) {
// Not downloaded yet: wait for it (shows the percentage)
_lalaEarWaiting = true;
if (vcStatusText) vcStatusText.textContent = `👂 گوێی کوردی ئامادە دەکرێت... ${_lalaEarPct}%`;
await startLalaEar(true);
_lalaEarWaiting = false;
}
if (window.LalaEar && window.LalaEar.isLoaded()) {
if (vcStatusText) vcStatusText.textContent = '👂 گوێی کوردی گوێ دەگرێت...';
heard = earPromise ? await earPromise : await window.LalaEar.transcribe(audioBlob).catch(() => '');
}
if (!heard || !/[-ۿ]/.test(heard)) {
voiceVcState.earReport = 'گوێی کوردی کاری نەکرد: ' + ((window.LalaEar && window.LalaEar.lastError) ||
(window.LalaEar ? (window.LalaEar.isLoaded() ? 'هیچ وشەیەکی نەبیست' : 'دانەبەزیوە') : 'بار نەبوو'));
return null;
}
const tgt = vcS1 === 'ku' ? vcS2 : vcS1;
if (vcStatusText) vcStatusText.textContent = '🧠 وەردەگێڕدرێت...';
let translated = '';
try {
const tr = await translateTextReliable(heard, 'ku', tgt);
translated = tr ? tr.translation : '';
} catch (_) {}
if (!translated) {
voiceVcState.earReport = 'گوێی کوردی بیستی، بەڵام وەرگێڕان سەرکەوتوو نەبوو';
return null;
}
voiceVcState.earReport = '';
return { sourceText: heard, translatedText: translated, sourceLang: 'ku', targetLang: tgt, engine: 'lala-ear' };
};
if (earFirst) {
data = await earListenAndTranslate();
} else if (kurdishSpeaker && window.LalaEar && window.LalaEar.isLoaded()) {
// Auto mode: start our ear in parallel as a backup
earPromise = window.LalaEar.transcribe(audioBlob).catch(() => '');
}
if (!data && vcStatusText) {
vcStatusText.textContent = elapsedSec > 15
? '⚡ دەنگەکەت بە خێرایی با وەردەگێڕدرێت...'
: '⚡ دەنگەکەت وەرگیرا، بە خێرایی وەردەگێڕدرێت...';
}
if (!data) {
try {
data = await transcribeAndTranslateVoiceClient(audioBlob, b64, spokenLang);
} catch (clientErr) {
console.warn('Direct Gemini client failed, trying server fallback:', clientErr);
fetchErr = clientErr;
}
}
// Google (backup for Kurdish, main for other languages)
if ((!data || !data.sourceText) && !isStaticCloud) {
try {
const controller = new AbortController();
// When our own ear is ready, don't wait long for a busy Google
// Kurdish speakers have our own ear as backup, so don't wait long for a busy Google
const fetchTimeout = setTimeout(() => controller.abort(), earPromise ? 12000 : (kurdishSpeaker ? 18000 : 35000));
const res = await fetch(`${apiBase}/api/voice/conversation`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
audio_base64: b64,
spoken_lang: spokenLang,
speaker1_lang: voiceVcState.speaker1Lang || 'ku',
speaker2_lang: voiceVcState.speaker2Lang || 'en',
mime_type: audioBlob.type || 'audio/webm',
elevenlabs_enabled: isElevenLabsEnabled,
elevenlabs_key: elevenLabsApiKey,
elevenlabs_voice_id: elevenLabsVoiceId
}),
signal: controller.signal
});
clearTimeout(fetchTimeout);
if (res && res.ok) {
data = await res.json();
}
} catch (retryErr) {
fetchErr = retryErr;
}
}
// Google failed (full / busy / error).
// Our ear only understands KURDISH, so it is used only for the Kurdish button or Auto mode;
// for English (and other languages) the browser's own speech recognition is the backup.
const googleFailed = !data || data.error || (!data.sourceText && !data.silence);
if (googleFailed && spokenLang !== 'ku' && spokenLang !== 'auto') {
const said = joinPhoneNumbers(await finishBrowserListening());
if (said) {
const tgt = spokenLang === vcS1 ? vcS2 : vcS1;
if (vcStatusText) vcStatusText.textContent = '🧠 وەردەگێڕدرێت...';
const tr = await translateTextReliable(said, spokenLang, tgt).catch(() => null);
if (tr && tr.translation) {
data = { sourceText: said, translatedText: tr.translation, sourceLang: spokenLang, targetLang: tgt, engine: 'browser-ear' };
}
}
}
if (googleFailed && kurdishSpeaker && spokenLang === 'auto' && (!data || !data.sourceText)) {
try {
const earData = await earListenAndTranslate();
if (earData) data = earData;
} catch (earErr) {
console.warn('Lala ear fallback failed:', earErr);
}
}
if (voiceVcState.earReport && (!data || data.error || !data.sourceText) && !(data && data.silence)) {
// Show what our own ear did, not a generic "Google is full / timeout"
showToast(voiceVcState.earReport, '👂');
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = voiceVcState.earReport;
console.warn('Lala ear report:', voiceVcState.earReport, data, fetchErr);
return;
}
if (!data) {
throw (fetchErr || new Error('نەتوانرا پەیوەندی بە سیستەمی وەرگێڕانەوە بکرێت'));
}
if (data && data.silence) {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'هیچ قسەیەک نەبیسترا، تکایە ڕوونتر قسە بکە...';
return;
}
if (data && data.sourceText && data.translatedText) {
data.sourceText = joinPhoneNumbers(data.sourceText);
if (data.sourceLang !== 'ku') data.translatedText = joinPhoneNumbers(data.translatedText);
if (data.sourceLang === 'ku') data.sourceText = fixKurdishSoraniGreetings(data.sourceText);
if (data.targetLang === 'ku') data.translatedText = fixKurdishSoraniGreetings(data.translatedText);
const s1 = voiceVcState.speaker1Lang || 'ku';
const s2 = voiceVcState.speaker2Lang || 'en';
const isTgtKurdish = data.targetLang === 'ku' || (data.targetLang === 'auto' && /[\u0600-\u06FF]/.test(data.translatedText) && (s1 === 'ku' || s2 === 'ku'));
const shouldAutoSpeak = !vcAutoSpeakToggle || vcAutoSpeakToggle.checked !== false;
// 1. Instantly render the dialogue text bubble so user sees result without delay
addVcDialogue(data.sourceText, data.translatedText, data.sourceLang, data.targetLang, data.audio_base64, data.audio_mime, data.audio_url);
// 2. Play speech immediately with ZERO delay
if (data.audio_base64) {
if (shouldAutoSpeak) {
playVcAudio(data.translatedText, data.targetLang, data.audio_base64, data.audio_mime, null);
}
} else if (isTgtKurdish) {
if (shouldAutoSpeak) {
// Progressive Kurdish Sentence Streaming: Starts speaking in ~1.2s even for long speech!
playKurdishSentenceStream(data.translatedText, 'sorani');
}
} else if (shouldAutoSpeak) {
// English or other languages: instant speech with 0 delay!
playVcAudio(data.translatedText, data.targetLang, null, null, null);
}
} else if (data && data.error && !data.quota && !/429|quota|Missing Gemini/i.test(String(data.detail || '') + String(data.error || ''))) {
// Google was busy / slow: not the user's fault either
console.warn('VC server error:', data);
showToast('سێرڤەری گوێگرتن ئێستا قەرەباڵغە، تکایە دووبارە قسە بکەرەوە', '🔄');
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'سێرڤەرەکە قەرەباڵغ بوو، تکایە دووبارە هەوڵ بدەرەوە.';
} else if (data && (data.quota || /429|quota|Missing Gemini/i.test(String(data.detail || '') + String(data.error || '')))) {
// Not the user's fault: today's free Google share is used up
showToast('خزمەتگوزاریی گوێگرتن بۆ ئەمڕۆ پڕ بووە. تکایە دواتر هەوڵ بدەرەوە (بەیانی ئاسایی دەبێتەوە)', '⏳');
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = `خزمەتگوزارییەکە بۆ ئەمڕۆ پڕ بووە، دواتر هەوڵ بدەرەوە. [${spokenLang}/${vcS1}/${vcS2} ear5]`;
} else {
showToast('نەتوانرا لە دەنگەکە تێبگات، تکایە بە دەنگێکی ڕوونتر قسە بکەرەوە', '⚠️');
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = 'نەتوانرا لە دەنگەکە تێبگات. تکایە دووبارە قسە بکەرەوە...';
}
} catch (err) {
console.error('VC conversation error:', err);
const isTimeout = err && err.name === 'AbortError';
const msg = isTimeout
? 'سێرڤەر درەنگ وەڵامی دایەوە (Timeout)، تکایە دووبارە قسە بکەرەوە'
: 'هەڵە لە پەیوەستبوون بە سێرڤەری وەرگێڕان، تکایە دووبارە هەوڵبدەرەوە';
showToast(msg, '⚠️');
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar';
if (vcStatusText) vcStatusText.textContent = msg;
}
};
// Start recording cleanly without timeslices to avoid MP4 chunk corruption on mobile
mediaRecorder.start();
voiceVcState.isRecording = true;
voiceVcState.recordingStartTime = Date.now();
// Non-Kurdish speech: the browser listens at the same time, as a free backup for when Google is full
if (spokenLang !== 'ku' && spokenLang !== 'auto') startBrowserListening(spokenLang);
// Visual waveform animation only — ZERO auto-stopping on silence
try {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (AudioCtx) {
const audioCtx = new AudioCtx();
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 256;
analyser.smoothingTimeConstant = 0.25;
source.connect(analyser);
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const vadInterval = setInterval(() => {
if (!voiceVcState.isRecording) {
clearInterval(vadInterval);
return;
}
analyser.getByteFrequencyData(dataArray);
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i];
}
const avg = sum / bufferLength;
if (avg > 16) {
voiceVcState.speechSamplesCount = (voiceVcState.speechSamplesCount || 0) + 1;
if (voiceVcState.speechSamplesCount >= 2) {
voiceVcState.hasSpoken = true;
}
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar listening speaking';
} else {
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar listening';
}
}, 80);
voiceVcState.audioContext = audioCtx;
voiceVcState.vadInterval = vadInterval;
}
} catch (vadErr) {
console.warn('VAD visual feedback warning:', vadErr);
}
if (triggerBtn) {
if (!triggerBtn.getAttribute('data-original-html')) {
triggerBtn.setAttribute('data-original-html', triggerBtn.innerHTML);
}
triggerBtn.classList.add('recording');
}
// Live Elapsed Timer: Shows (0:01), (0:15), (1:20)... NEVER stops automatically!
const updateRecordingUI = () => {
if (!voiceVcState.isRecording) return;
const elapsedSec = Math.floor((Date.now() - voiceVcState.recordingStartTime) / 1000);
const m = Math.floor(elapsedSec / 60);
const s = String(elapsedSec % 60).padStart(2, '0');
const timeStr = `${m}:${s}`;
if (triggerBtn) {
const isKu = (spokenLang === 'ku');
const stopLabel = isKu ? `⏹️ تەواوکردن (${timeStr})` : `⏹️ Stop & Send (${timeStr})`;
const span = triggerBtn.querySelector('.giant-btn-label') || triggerBtn.querySelector('span');
if (span) {
span.textContent = stopLabel;
} else {
triggerBtn.innerHTML = `<span>${stopLabel}</span>`;
}
}
if (vcStatusText) {
const lInfo = VC_LANGUAGES[spokenLang] || { name: spokenLang };
if (spokenLang === 'ku') {
vcStatusText.textContent = `🔴 لە تۆمارکردندایە (${timeStr})... هەركات قسەکردنت تەواو بوو پەنجە لە دوگمەکە بنێ بۆ وەرگێڕان.`;
} else if (spokenLang === 'auto') {
vcStatusText.textContent = `🔴 لە تۆمارکردندایە (${timeStr} - دۆزینەوەی خۆکار)... بۆ تەواوکردن پەنجە لە دوگمەکە بنێ.`;
} else {
vcStatusText.textContent = `🔴 لە تۆمارکردندایە (${timeStr} - ${lInfo.name})... هەركات قسەکردنت تەواو بوو پەنجە لە دوگمەکە بنێ بۆ وەرگێڕان.`;
}
}
};
updateRecordingUI();
voiceVcState.timerInterval = setInterval(updateRecordingUI, 1000);
if (vcWaveformBar) vcWaveformBar.className = 'vc-waveform-bar listening';
} catch (err) {
console.error(err);
showToast('مایکرۆفۆن پەسەند نەکرا یان کێشەی هەیە', '⚠️');
if (vcStatusText) vcStatusText.textContent = 'مایکرۆفۆن پەسەند نەکرا یان بەردەست نییە.';
}
}
function stopVcRecording(isManual = false) {
if (!voiceVcState.isRecording) return;
voiceVcState.isRecording = false;
if (voiceVcState.timerInterval) {
clearInterval(voiceVcState.timerInterval);
voiceVcState.timerInterval = null;
}
if (voiceVcState.vadInterval) {
clearInterval(voiceVcState.vadInterval);
voiceVcState.vadInterval = null;
}
if (voiceVcState.audioContext) {
try {
if (voiceVcState.audioContext.state !== 'closed') {
voiceVcState.audioContext.close();
}
} catch (_) {}
voiceVcState.audioContext = null;
}
if (voiceVcState.mediaRecorder && voiceVcState.mediaRecorder.state !== 'inactive') {
try { voiceVcState.mediaRecorder.stop(); } catch (_) {}
}
if (voiceVcState.activeTriggerBtn) {
voiceVcState.activeTriggerBtn.classList.remove('recording');
const orig = voiceVcState.activeTriggerBtn.getAttribute('data-original-html');
if (orig) voiceVcState.activeTriggerBtn.innerHTML = orig;
}
}
const setupMicToggle = (btn, lang) => {
if (!btn) return;
const onTrigger = (e) => {
if (e) e.stopPropagation();
const now = Date.now();
if (voiceVcState.lastToggleTime && (now - voiceVcState.lastToggleTime < 350)) {
return;
}
voiceVcState.lastToggleTime = now;
unlockVcAudioPlayer();
stopVcAudio();
if (voiceVcState.isRecording) {
// Tap with finger while recording -> stops and translates!
stopVcRecording(true);
} else {
// Tap with finger while idle -> starts recording!
let activeLang = lang;
if (lang === 'speaker1') activeLang = voiceVcState.speaker1Lang || 'ku';
else if (lang === 'speaker2') activeLang = voiceVcState.speaker2Lang || 'en';
startVcRecording(activeLang, btn);
}
};
btn.addEventListener('click', onTrigger);
btn.addEventListener('touchstart', () => unlockVcAudioPlayer(), { passive: true });
};
setupMicToggle(vcKurdishMicBtn, 'speaker1');
setupMicToggle(vcEnglishMicBtn, 'speaker2');
setupMicToggle(vcAutoDetectMicBtn, 'auto');
setupMicToggle(quickKurdishMicBtn, 'speaker1');
setupMicToggle(quickEnglishMicBtn, 'speaker2');
}
// Start app
document.addEventListener('DOMContentLoaded', initApp);
|