Spaces:
Paused
Paused
File size: 93,801 Bytes
4858cbf | 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 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#06111e">
<meta name="description" content="A local voice studio for building, managing, and generating custom voice profiles.">
<title>Voice Studio</title>
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<style>
:root {
color-scheme: dark;
--paper: #06111e;
--panel: #0b1b2b;
--ink: #e0f8ff;
--ink-soft: #8eafc1;
--moss: #41e7f5;
--moss-deep: #13bfd2;
--amber: #c9ff74;
--amber-ink: #112031;
--amber-deep: #c9ff74;
--mist: #1d3d50;
--wave: #24586b;
--error: #ff7998;
--panel-glass: color-mix(in srgb, var(--panel) 93%, transparent);
--ui: "Segoe UI", Inter, system-ui, sans-serif;
--read: "Segoe UI", Inter, system-ui, sans-serif;
--r-sm: 8px;
--r-lg: 12px;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0; min-height: 100vh; isolation: isolate;
background: radial-gradient(ellipse at 12% 0%, color-mix(in srgb, var(--moss) 15%, transparent), transparent 34rem),
radial-gradient(ellipse at 92% 28%, color-mix(in srgb, #177da0 13%, transparent), transparent 32rem), var(--paper);
color: var(--ink); font-family: var(--ui); font-size: 16px; line-height: 1.5;
}
body::before, body::after { content: ""; position: fixed; inset: 0; pointer-events: none; z-index: -1; }
body::before { opacity: .22; background-image: linear-gradient(color-mix(in srgb, var(--moss) 19%, transparent) 1px, transparent 1px), linear-gradient(90deg, color-mix(in srgb, var(--moss) 19%, transparent) 1px, transparent 1px); background-size: 44px 44px; mask-image: linear-gradient(to bottom, black, transparent 82%); }
body::after { opacity: .12; background: repeating-linear-gradient(180deg, transparent 0 3px, rgba(150, 235, 255, .13) 4px, transparent 5px); }
button, input, select, textarea { font: inherit; color: inherit; }
:focus-visible { outline: 3px solid var(--amber); outline-offset: 2px; }
.wrap { max-width: 1460px; margin: 0 auto; padding: 28px 32px calc(64px + env(safe-area-inset-bottom)); }
/* header */
header { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 28px; padding-bottom: 20px; border-bottom: 1px solid var(--mist); box-shadow: 0 1px 0 color-mix(in srgb, var(--moss) 20%, transparent); }
.brand { display: flex; align-items: center; gap: 14px; }
.brand-mark { width: 46px; height: 46px; display: grid; place-items: center; border: 1px solid var(--moss); border-radius: 12px; background: color-mix(in srgb, var(--moss) 12%, var(--panel)); color: var(--moss); box-shadow: 0 0 24px color-mix(in srgb, var(--moss) 25%, transparent), inset 0 0 14px color-mix(in srgb, var(--moss) 12%, transparent); }
.brand-mark svg { width: 25px; height: 25px; }
h1 { font-size: clamp(1.55rem, 3vw, 2rem); font-weight: 750; letter-spacing: -0.04em; margin: 0; line-height: 1.05; }
h1 span { display: block; font-size: .72rem; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--moss); margin-top: 7px; }
.status { display: inline-flex; align-items: center; gap: 8px; font-size: 0.92rem; color: var(--ink-soft); }
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--wave); }
.status.ready .dot { background: var(--moss); box-shadow: 0 0 12px var(--moss); }
.status.error { color: var(--error); }
.status.error .dot { background: var(--error); }
.status.loading .dot { animation: pulse 1.4s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: .3; } }
.mobile-launch { display: inline-flex; align-items: center; margin-right: 12px; }
.mobile-nav { display: none; }
/* top grid */
.desk { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 22px; align-items: stretch; }
.page {
background: linear-gradient(145deg, color-mix(in srgb, var(--moss) 5%, var(--panel)), var(--panel) 58%); border: 1px solid var(--mist); border-radius: var(--r-lg);
padding: 24px 28px 20px; display: flex; flex-direction: column; min-height: 420px;
box-shadow: 0 14px 40px rgba(0, 0, 0, .2), inset 0 1px 0 color-mix(in srgb, var(--moss) 16%, transparent);
}
.page label.title { font-weight: 700; font-size: 1.05rem; }
.page .hint { color: var(--ink-soft); font-size: 0.9rem; margin: 2px 0 12px; }
textarea#script {
flex: 1; min-height: 280px; resize: vertical; border: none; background: transparent;
font-family: var(--read); font-size: 1.22rem; line-height: 1.75; padding: 6px 0;
max-width: 68ch;
}
textarea#script:focus-visible { outline: none; }
.page:focus-within { border-color: var(--moss); box-shadow: 0 0 28px color-mix(in srgb, var(--moss) 12%, transparent), inset 0 1px 0 color-mix(in srgb, var(--moss) 24%, transparent); }
.page-foot { display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; border-top: 1px solid var(--mist); padding-top: 14px; margin-top: 10px; }
.count { color: var(--ink-soft); font-size: 0.9rem; }
.go {
background: var(--moss); color: #06202a; border: 1px solid var(--moss); border-radius: 8px;
padding: 12px 26px; font-weight: 700; font-size: 1.02rem; cursor: pointer;
box-shadow: 0 0 22px color-mix(in srgb, var(--moss) 18%, transparent);
}
.go:hover { filter: brightness(1.06); }
.go:disabled { opacity: .55; cursor: not-allowed; filter: none; }
/* controls */
.controls { display: flex; flex-direction: column; gap: 20px; }
.controls > .field, .controls details.more { background: var(--panel-glass); border: 1px solid var(--mist); border-radius: var(--r-lg); padding: 16px; box-shadow: inset 0 1px 0 color-mix(in srgb, var(--moss) 9%, transparent); }
.field label { display: block; font-weight: 700; margin-bottom: 6px; }
.field .row { display: flex; justify-content: space-between; align-items: baseline; }
.field .row output { color: var(--ink-soft); font-variant-numeric: tabular-nums; font-size: .92rem; }
.field small { display: block; color: var(--ink-soft); font-size: .85rem; margin-top: 4px; }
select, input[type=text], input[type=number] {
width: 100%; background: #071522; border: 1px solid var(--mist); border-radius: var(--r-sm);
padding: 9px 10px;
}
input[type=range] { width: 100%; accent-color: var(--moss); }
.takes { display: flex; gap: 6px; }
.takes button {
flex: 1; border: 1px solid var(--mist); background: var(--panel); border-radius: var(--r-sm);
padding: 8px 0; cursor: pointer; font-weight: 500;
}
.takes button[aria-pressed=true] { background: var(--moss); border-color: var(--moss); color: var(--paper); }
details.more summary { cursor: pointer; color: var(--ink-soft); font-size: .92rem; }
details.more[open] summary { margin-bottom: 14px; }
details.more .controls { gap: 16px; }
/* progress */
.progress { margin-top: 26px; display: none; }
.progress.on { display: block; }
.bar { height: 6px; background: var(--mist); border-radius: 99px; overflow: hidden; margin-top: 8px; }
.bar i { display: block; height: 100%; width: 0; background: var(--moss); transition: width .4s ease; }
.progress p { margin: 0; color: var(--ink-soft); font-size: .95rem; }
.error-box { margin-top: 18px; color: var(--error); font-weight: 500; display: none; }
.error-box.on { display: block; }
/* voice profile rebuild */
.rebuild-panel {
margin-top: 28px; padding: 26px 28px; background: var(--panel-glass);
border: 1px solid var(--mist); border-radius: var(--r-lg);
box-shadow: 0 14px 40px rgba(0, 0, 0, .2), inset 0 1px 0 color-mix(in srgb, var(--moss) 11%, transparent);
}
.rebuild-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px; margin-top: 18px; }
.person-controls { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 1fr) auto; align-items: end; gap: 12px; margin-top: 16px; }
.install-app { display: none; }
.person-media { margin-top: 22px; padding: 18px; border: 1px solid var(--mist); border-radius: var(--r-lg); background: color-mix(in srgb, var(--moss) 3%, var(--paper)); }
.person-media h3 { margin: 0 0 4px; }
.person-upload-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-top: 14px; }
.person-upload-grid input[type=file] { display: block; width: 100%; margin: 8px 0; }
.person-recorder { margin-top: 16px; padding: 18px; border: 1px solid color-mix(in srgb, var(--moss) 45%, var(--mist)); border-radius: var(--r-lg); background: linear-gradient(135deg, color-mix(in srgb, var(--moss) 8%, var(--panel)), var(--panel)); box-shadow: inset 0 0 26px color-mix(in srgb, var(--moss) 5%, transparent); }
.recorder-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.recorder-head h3 { margin: 0; }
.recorder-badge { display: inline-flex; align-items: center; gap: 7px; color: var(--moss); border: 1px solid color-mix(in srgb, var(--moss) 50%, var(--mist)); border-radius: 99px; padding: 4px 10px; font-size: .72rem; font-weight: 800; letter-spacing: .12em; }
.recorder-badge i { width: 7px; height: 7px; border-radius: 50%; background: var(--moss); box-shadow: 0 0 10px var(--moss); }
.prompt-card { margin-top: 14px; padding: 16px; min-height: 130px; border: 1px solid var(--mist); border-radius: var(--r-sm); background: color-mix(in srgb, var(--paper) 68%, transparent); }
.prompt-card p { margin: 0; font-family: var(--read); font-size: 1.05rem; line-height: 1.7; }
.recorder-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 14px; }
.record-button { background: var(--moss); color: #06202a; border-color: var(--moss); font-weight: 750; }
.record-button.recording { background: var(--error); color: #25050e; border-color: var(--error); }
.recorder-time { color: var(--moss); font-variant-numeric: tabular-nums; font-weight: 750; min-width: 62px; }
.recorder-preview { width: 100%; margin-top: 12px; }
.recorder-preview[hidden] { display: none; }
.recorder-status { display: block; margin-top: 10px; color: var(--ink-soft); font-size: .9rem; }
.recorder-status.error { color: var(--error); }
.recorder-status.success { color: var(--amber); }
.person-media-status { color: var(--ink-soft); font-size: .92rem; margin-top: 10px; }
.voice-sample-list { display: grid; gap: 8px; margin-top: 14px; }
.voice-sample-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--mist); border-radius: var(--r-sm); background: color-mix(in srgb, var(--paper) 55%, transparent); }
.voice-sample-row audio { display: block; width: 100%; max-width: 440px; margin-top: 6px; }
.voice-sample-row p { margin: 0; font-weight: 700; }
.voice-sample-empty { margin: 10px 0 0; color: var(--ink-soft); font-size: .9rem; }
.person-media-status { color: var(--ink-soft); font-size: .92rem; margin-top: 10px; }
.person-media-progress[hidden] { display: none; }
.source-list { max-height: 190px; overflow: auto; border: 1px solid var(--mist); border-radius: var(--r-sm); padding: 8px 10px; }
.source-option { display: flex; align-items: center; gap: 8px; padding: 5px 0; }
.source-option input { accent-color: var(--moss); }
.reference-manager { margin-top: 22px; padding-top: 20px; border-top: 1px solid var(--mist); }
.reference-list { display: grid; gap: 10px; }
.reference-review-card { max-width: 680px; margin: 16px auto; padding: 22px; border: 1px solid var(--mist); border-radius: var(--r-lg); background: color-mix(in srgb, var(--paper) 72%, var(--panel)); text-align: center; }
.reference-review-card h3 { margin: 0; font-size: 1.2rem; }
.reference-review-card p { color: var(--ink-soft); }
.reference-review-card audio { display: block; width: 100%; margin: 18px 0; }
.reference-review-actions { display: flex; justify-content: center; gap: 12px; flex-wrap: wrap; margin-top: 16px; }
.reference-review-actions .btn { min-width: 130px; padding: 10px 18px; font-weight: 700; }
.top-reference-list { display: grid; gap: 10px; margin: 14px 0 24px; }
.top-reference-item { display: grid; grid-template-columns: 38px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 12px; border: 1px solid var(--mist); border-radius: var(--r-sm); }
.top-reference-rank { color: var(--amber-deep); font-weight: 800; font-size: 1.1rem; text-align: center; }
.top-reference-item p { margin: 0; font-weight: 700; }
.top-reference-item small { display: block; color: var(--ink-soft); }
.top-reference-item audio { display: block; width: 100%; margin-top: 6px; }
.btn.review-delete { color: var(--error); border-color: var(--error); }
.btn.review-keep { color: var(--moss-deep); border-color: var(--moss); }
.btn.review-promote { background: var(--amber); border-color: var(--amber); color: var(--amber-ink); }
.reference-item { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; padding: 10px 12px; border: 1px solid var(--mist); border-radius: var(--r-sm); }
.reference-item p { margin: 0 0 4px; font-weight: 700; }
.reference-item small { display: block; color: var(--ink-soft); }
.reference-item audio { width: 100%; margin-top: 6px; }
.reference-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
.reference-status { color: var(--ink-soft); font-size: .92rem; }
.rebuild-actions { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-top: 18px; }
.rebuild-status { color: var(--ink-soft); font-size: .92rem; }
.rebuild-progress { width: 100%; max-width: 440px; height: 6px; background: var(--mist); border-radius: 99px; overflow: hidden; }
.rebuild-progress i { display: block; height: 100%; width: 0; background: var(--moss); transition: width .3s ease; }
.rebuild-error { color: var(--error); font-weight: 500; margin: 12px 0 0; }
.rebuild-note { color: var(--ink-soft); font-size: .9rem; margin: 8px 0 0; }
.compare-panel { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--mist); }
.compare-audio { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-top: 14px; }
.compare-audio[hidden], .rebuild-progress[hidden] { display: none; }
.compare-audio label { display: block; font-weight: 700; margin-bottom: 6px; }
.compare-audio audio { width: 100%; }
.field audio { width: 100%; margin-top: 10px; }
.field audio[hidden] { display: none; }
.compare-script { width: 100%; min-height: 90px; margin-top: 10px; resize: vertical; background: #071522; border: 1px solid var(--mist); border-radius: var(--r-sm); padding: 10px; }
@media (max-width: 860px) { .rebuild-grid, .person-controls, .person-upload-grid { grid-template-columns: 1fr; } .rebuild-panel { padding: 18px 16px; } }
@media (max-width: 600px) { .compare-audio { grid-template-columns: 1fr; } .reference-review-card { padding: 16px; } .top-reference-item { grid-template-columns: 32px minmax(0, 1fr); } .top-reference-item .btn { grid-column: 2; justify-self: start; } }
/* takes */
section.results { margin-top: 38px; }
h2 { font-size: 1.35rem; font-weight: 700; margin: 0 0 4px; letter-spacing: -0.01em; }
.sub { color: var(--ink-soft); margin: 0 0 16px; font-size: .95rem; }
.take {
display: grid; grid-template-columns: 52px minmax(0, 1fr) auto; gap: 16px; align-items: center;
padding: 14px 0; border-top: 1px solid var(--mist);
}
.take:last-child { border-bottom: 1px solid var(--mist); }
.play {
width: 52px; height: 52px; border-radius: 50%; border: 2px solid var(--moss); background: transparent;
cursor: pointer; display: grid; place-items: center; color: var(--moss);
}
.play svg { width: 18px; height: 18px; }
.play.on { background: var(--moss); color: var(--paper); }
.wave { position: relative; height: 64px; cursor: pointer; }
.wave canvas { width: 100%; height: 100%; display: block; }
.meta { font-size: .88rem; color: var(--ink-soft); margin-top: 4px; display: flex; gap: 14px; flex-wrap: wrap; }
.take .text { font-family: var(--read); font-size: .98rem; margin: 0 0 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acts { display: flex; gap: 8px; align-items: center; }
.btn {
border: 1px solid var(--mist); background: color-mix(in srgb, var(--panel) 84%, var(--moss)); border-radius: 7px; padding: 7px 14px;
cursor: pointer; font-size: .9rem; text-decoration: none; white-space: nowrap; color: var(--ink);
}
.btn:hover { border-color: var(--moss); box-shadow: 0 0 14px color-mix(in srgb, var(--moss) 16%, transparent); }
.btn:disabled { opacity: .48; cursor: not-allowed; box-shadow: none; }
.btn.approved { background: var(--amber); border-color: var(--amber); color: var(--amber-ink); font-weight: 700; }
.btn.discard { color: var(--error); border-color: var(--error); }
.btn.discard:hover { background: var(--error); color: var(--panel); }
.take.is-approved .text { font-weight: 500; }
.tabs { display: flex; gap: 18px; margin-bottom: 14px; border-bottom: 1px solid var(--mist); }
.tabs button { background: none; border: none; padding: 8px 0; cursor: pointer; color: var(--ink-soft); font-weight: 500; border-bottom: 3px solid transparent; margin-bottom: -1px; }
.tabs button[aria-selected=true] { color: var(--ink); border-bottom-color: var(--moss); font-weight: 700; }
.empty { color: var(--ink-soft); padding: 18px 0; }
footer { margin-top: 48px; color: var(--ink-soft); font-size: .85rem; max-width: 70ch; }
@media (max-width: 860px) {
.desk { grid-template-columns: 1fr; }
.wrap { padding: 20px 16px 48px; }
.page { padding: 18px 16px 14px; min-height: 0; }
.take { grid-template-columns: 44px minmax(0, 1fr); }
.play { width: 44px; height: 44px; }
.acts { grid-column: 1 / -1; justify-content: flex-end; }
}
@media (max-width: 600px) {
.wrap { padding: max(16px, env(safe-area-inset-top)) 14px calc(40px + env(safe-area-inset-bottom)); }
header { align-items: flex-start; margin-bottom: 18px; }
.status { width: 100%; font-size: .84rem; }
h1 { font-size: 1.55rem; }
h1 span { font-size: .62rem; letter-spacing: .1em; }
.page { padding: 16px; }
textarea#script { min-height: 210px; font-size: 1.05rem; }
.page-foot { align-items: stretch; }
.page-foot .go { width: 100%; }
.rebuild-grid { gap: 14px; }
.person-controls .btn { width: 100%; }
.person-media { padding: 14px; }
.person-recorder { padding: 14px; }
.recorder-controls { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.recorder-controls .btn { min-height: 44px; white-space: normal; }
.recorder-time { grid-column: 1 / -1; text-align: center; }
.voice-sample-row { grid-template-columns: minmax(0, 1fr); }
.voice-sample-row .btn { justify-self: start; min-height: 42px; }
.reference-actions > .btn { min-height: 44px; }
.take { grid-template-columns: 44px minmax(0, 1fr); gap: 10px; }
.take .acts { grid-column: 1 / -1; justify-content: flex-start; flex-wrap: wrap; }
.take .acts .btn { min-height: 42px; }
.compare-panel { overflow-wrap: anywhere; }
button, select, input, textarea { touch-action: manipulation; }
}
.mobile-app .wrap { padding-bottom: calc(96px + env(safe-area-inset-bottom)); }
.mobile-app .mobile-nav { position: fixed; z-index: 10; left: 12px; right: 12px; bottom: max(10px, env(safe-area-inset-bottom)); display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; padding: 7px; border: 1px solid color-mix(in srgb, var(--moss) 35%, var(--mist)); border-radius: 14px; background: color-mix(in srgb, var(--panel) 90%, transparent); box-shadow: 0 12px 34px rgba(0, 0, 0, .42), 0 0 20px color-mix(in srgb, var(--moss) 10%, transparent); backdrop-filter: blur(18px); }
.mobile-app .mobile-nav a { min-height: 48px; display: grid; place-items: center; align-content: center; gap: 1px; border-radius: 9px; color: var(--ink-soft); font-size: .72rem; font-weight: 700; text-decoration: none; }
.mobile-app .mobile-nav a[aria-current="page"], .mobile-app .mobile-nav a:focus-visible { color: var(--moss); background: color-mix(in srgb, var(--moss) 10%, transparent); }
.mobile-app .mobile-nav-icon { font-size: 1.15rem; line-height: 1.1; }
.mobile-app .mobile-launch { display: none; }
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none"><path d="M3 10v4m4-8v12m4-15v18m4-13v8m4-11v14m3-9v4" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>
</div>
<h1>Voice Studio <span>Local voice synthesis · personal voice lab</span></h1>
</div>
<div>
<a class="btn mobile-launch" href="/mobile">Open mobile app</a>
<button class="btn install-app" id="installApp" type="button">Install app</button>
<div class="status loading" id="status" role="status"><span class="dot"></span><span id="statusText">Loading the voice model…</span></div>
</div>
</header>
<div class="desk" id="composeSection">
<div class="page">
<label class="title" for="script">Script</label>
<p class="hint">Choose a voice, write your script, and shape the delivery. A blank line between paragraphs adds a longer pause.</p>
<textarea id="script" spellcheck="true" placeholder="Type or paste your script here.
Separate paragraphs with a blank line for a longer pause."></textarea>
<div class="page-foot">
<span class="count" id="count">0 words</span>
<button class="go" id="go" disabled>Generate takes</button>
</div>
</div>
<div class="controls" aria-label="Voice and delivery">
<div class="field">
<label for="voice">Voice</label>
<select id="voice"></select>
<small id="voiceInfo"></small>
</div>
<div class="field">
<div class="row"><label for="exag">Energy</label><output id="exagOut"></output></div>
<input type="range" id="exag" min="0.25" max="1.2" step="0.05" value="0.5">
<small>Move left for a calmer read, right for more energy</small>
</div>
<div class="field">
<div class="row"><label for="cfg">Pace</label><output id="cfgOut"></output></div>
<input type="range" id="cfg" min="0.1" max="0.9" step="0.05" value="0.5">
<small>Lower is slower and more deliberate</small>
</div>
<div class="field">
<label id="takesLabel">Takes</label>
<div class="takes" role="group" aria-labelledby="takesLabel">
<button type="button" data-n="1" aria-pressed="false">1</button>
<button type="button" data-n="2" aria-pressed="false">2</button>
<button type="button" data-n="3" aria-pressed="true">3</button>
<button type="button" data-n="4" aria-pressed="false">4</button>
</div>
<small>Each take is delivered a little differently</small>
</div>
<details class="more">
<summary>More settings</summary>
<div class="controls">
<div class="field">
<div class="row"><label for="temp">Variation</label><output id="tempOut"></output></div>
<input type="range" id="temp" min="0.4" max="1.1" step="0.05" value="0.8">
<small>How different the takes are from each other</small>
</div>
<div class="field">
<div class="row"><label for="pause">Pause between sentences</label><output id="pauseOut"></output></div>
<input type="range" id="pause" min="0" max="0.8" step="0.05" value="0.25">
</div>
<div class="field">
<label for="seed">Repeat a take</label>
<input type="text" id="seed" inputmode="numeric" placeholder="Paste a take's number">
<small>Same number, voice and settings give the same result</small>
</div>
</div>
</details>
</div>
</div>
<section class="rebuild-panel" aria-labelledby="rebuildTitle">
<h2 id="rebuildTitle">Voice library</h2>
<p class="sub">Create a voice from recordings, manage reference clips, and build or refine voice profiles. Record only voices you own or have permission to use.</p>
<div class="person-controls">
<div class="field">
<label for="personSelect">Person</label>
<select id="personSelect"></select>
</div>
<div class="field">
<label for="newPersonName">Add a person</label>
<input type="text" id="newPersonName" maxlength="60" placeholder="Name">
</div>
<button class="btn" id="addPerson" type="button">Add person</button>
</div>
<p class="rebuild-note" id="personNotice"></p>
<div class="person-media" aria-labelledby="personMediaTitle">
<h3 id="personMediaTitle">Add this person’s clips</h3>
<p class="rebuild-note">Record or upload 1–5 clean WAV samples (10–30 seconds, only this speaker) so Studio can identify their voice in videos. Then upload videos to extract and filter that speaker’s clips.</p>
<div class="person-upload-grid">
<div class="field">
<label for="personReferenceFiles">Voice sample WAV files</label>
<input id="personReferenceFiles" type="file" accept=".wav,audio/wav" multiple>
<button class="btn" id="uploadPersonReferences" type="button">Add voice samples</button>
<input id="mobileVoiceCapture" type="file" accept="audio/*" capture="user" hidden>
<button class="btn" id="recordOnDevice" type="button">Record on this device</button>
<small>Use clear speech without other speakers. Up to five samples per person.</small>
</div>
<div class="field">
<label for="personVideoFiles">Source video/audio files</label>
<input id="personVideoFiles" type="file" accept=".mp4,.mov,.mkv,.webm,.avi,.m4v,.mts,.wav,.mp3,.m4a" multiple>
<button class="btn" id="uploadPersonVideos" type="button">Add videos</button>
<small>Files stay on this computer. Supported video/audio files; 8 GB maximum per file.</small>
</div>
</div>
<div>
<h3>Saved voice samples</h3>
<div class="voice-sample-list" id="personVoiceSampleList" aria-live="polite"></div>
</div>
<div class="person-recorder" aria-labelledby="recorderTitle">
<div class="recorder-head">
<h3 id="recorderTitle">Voice capture</h3>
<span class="recorder-badge"><i aria-hidden="true"></i> LOCAL MIC INPUT</span>
</div>
<p class="rebuild-note">Read at a comfortable pace in a quiet room. Each take is converted to WAV in your browser, previewed, then saved on this computer as a voice sample. Four original prompts help capture varied sounds and delivery.</p>
<div class="field">
<label for="voicePromptSelect">Read-aloud prompt</label>
<select id="voicePromptSelect">
<option value="0">01 · Clear introduction</option>
<option value="1">02 · Descriptive narration</option>
<option value="2">03 · Warm conversation</option>
<option value="3">04 · Questions and emphasis</option>
</select>
</div>
<div class="prompt-card"><p id="voicePromptText"></p></div>
<div class="recorder-controls">
<button class="btn record-button" id="startVoiceRecording" type="button" disabled>Record prompt</button>
<button class="btn" id="stopVoiceRecording" type="button" disabled>Stop recording</button>
<span class="recorder-time" id="voiceRecordingTime" aria-live="off">00:00</span>
<button class="btn review-promote" id="saveVoiceRecording" type="button" disabled>Use recording as sample</button>
<button class="btn" id="discardVoiceRecording" type="button" disabled>Discard take</button>
</div>
<audio class="recorder-preview" id="voiceRecordingPreview" controls preload="metadata" hidden aria-label="Preview recorded voice sample"></audio>
<span class="recorder-status" id="voiceRecorderStatus" role="status" aria-live="polite">Choose a prompt and record 10–30 seconds. At least one clear sample is required; using three or more prompts is recommended.</span>
</div>
<div class="reference-actions">
<button class="btn review-promote" id="preparePersonDataset" type="button" disabled>Prepare clips from videos</button>
<span class="person-media-status" id="personMediaStatus" role="status">Loading this person’s files…</span>
</div>
<div class="rebuild-progress person-media-progress" id="personDatasetProgress" role="progressbar" aria-label="Video clip preparation progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden><i id="personDatasetBar"></i></div>
<p class="rebuild-error" id="personDatasetError" role="alert" hidden></p>
</div>
<div class="rebuild-grid">
<div class="field">
<label>Audio sources</label>
<div class="source-list" id="rebuildSources" aria-label="Select source folders"></div>
<small id="sourceInfo">Finding available datasets and clips…</small>
</div>
<div class="field">
<label for="rebuildAnchor">Anchor clip</label>
<select id="rebuildAnchor"></select>
<small>Choose a clean clip, ideally 7–15 seconds, with the delivery you want.</small>
<audio id="rebuildAnchorAudio" controls preload="none" aria-label="Listen to selected anchor clip" hidden></audio>
</div>
<div class="field">
<label for="rebuildMax">Maximum clips</label>
<input type="number" id="rebuildMax" min="3" max="4000" value="400">
<small>More clips take longer; 400 is usually enough.</small>
<label for="rebuildSim" style="margin-top:14px">Minimum speaker match</label>
<div class="row"><span></span><output id="rebuildSimOut">0.65</output></div>
<input type="range" id="rebuildSim" min="0" max="1" step="0.05" value="0.65">
<small>For prepared datasets, clips below this target-speaker match score are excluded.</small>
<label for="rebuildBlend" style="margin-top:14px">Identity blend</label>
<div class="row"><span></span><output id="rebuildBlendOut">1.00</output></div>
<input type="range" id="rebuildBlend" min="0" max="1" step="0.05" value="1">
<small>1 uses the full dataset identity; lower values blend more of the anchor voice back in.</small>
</div>
</div>
<div class="reference-manager" aria-labelledby="referenceTitle">
<h2 id="referenceTitle">Review reference clips</h2>
<p class="rebuild-note">Review one clip at a time. Delete removes the source clip, Keep saves your decision without promoting it, and Promote adds it to this person’s active six in place of the weakest reference. Prepared datasets use their speaker-match scores; folders use audio quality.</p>
<div class="reference-actions">
<button class="btn" id="startReferenceReview" type="button">Start / refresh review</button>
<span class="reference-status" id="referenceStatus" role="status"></span>
</div>
<div class="reference-review-card" id="referenceReviewCard" hidden>
<h3 id="reviewTitle"></h3>
<p id="reviewInfo"></p>
<p id="reviewText"></p>
<audio id="reviewAudio" controls preload="none"></audio>
<div class="reference-review-actions">
<button class="btn review-delete" id="reviewDelete" type="button">Delete</button>
<button class="btn review-keep" id="reviewKeep" type="button">Keep</button>
<button class="btn review-promote" id="reviewPromote" type="button">Promote</button>
</div>
</div>
<h3>Top 6 next candidates</h3>
<p class="rebuild-note">The highest-ranked unreviewed clips from the selected sources. Preview any clip or promote it directly.</p>
<div class="top-reference-list" id="topReferenceList" aria-live="polite"></div>
<h3>Active six references</h3>
<div class="reference-list" id="referenceList" aria-live="polite"></div>
<p class="rebuild-error" id="referenceError" role="alert" hidden></p>
</div>
<p class="rebuild-note" id="profileInfo"></p>
<div class="rebuild-actions">
<button class="go" id="rebuildButton" type="button">Rebuild profile</button>
<div class="rebuild-progress" id="rebuildProgress" role="progressbar" aria-label="Profile rebuild progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden><i id="rebuildBar"></i></div>
<span class="rebuild-status" id="rebuildStatus" role="status"></span>
</div>
<p class="rebuild-error" id="rebuildError" role="alert" hidden></p>
<div class="compare-panel">
<h2>Compare profiles</h2>
<p class="rebuild-note">Build a candidate, then generate both profiles from the same short script, settings, and seed. Listen before adopting it.</p>
<label for="compareScript">A/B test script</label>
<textarea class="compare-script" id="compareScript" maxlength="500">Hello, and welcome. Today, I’d like to share something new with you.</textarea>
<div class="rebuild-actions">
<button class="btn" id="compareButton" type="button" disabled>Generate A/B samples</button>
<button class="btn approved" id="adoptButton" type="button" disabled>Use candidate voice</button>
<span class="rebuild-status" id="compareStatus" role="status"></span>
</div>
<div class="compare-audio" id="compareAudio" hidden>
<div><label>Current profile (A)</label><audio id="compareCurrent" controls></audio></div>
<div><label>Candidate profile (B)</label><audio id="compareCandidate" controls></audio></div>
</div>
<p class="rebuild-error" id="compareError" role="alert" hidden></p>
</div>
</section>
<div class="progress" id="progress" aria-live="polite">
<p id="progressText"></p>
<div class="bar"><i id="barFill"></i></div>
</div>
<div class="error-box" id="errorBox" role="alert"></div>
<section class="results" id="latest" hidden>
<h2>New takes</h2>
<p class="sub">Play the takes, keep the best one, and mark approved when it is ready to use.</p>
<div id="latestList"></div>
</section>
<section class="results" id="librarySection">
<h2>Library</h2>
<div class="tabs" role="tablist">
<button role="tab" aria-selected="true" data-tab="all">Everything</button>
<button role="tab" aria-selected="false" data-tab="approved">Approved</button>
</div>
<div id="historyList"></div>
</section>
<footer>
Every file is AI-generated and carries an inaudible watermark marking it as synthetic. Label it as AI wherever it's published.
Files are saved in the output folder, each with a matching settings file.
</footer>
</div>
<nav class="mobile-nav" aria-label="Mobile app navigation">
<a href="#composeSection" aria-current="page"><span class="mobile-nav-icon" aria-hidden="true">◉</span><span>Create</span></a>
<a href="#rebuildTitle"><span class="mobile-nav-icon" aria-hidden="true">◇</span><span>Voices</span></a>
<a href="#librarySection"><span class="mobile-nav-icon" aria-hidden="true">▤</span><span>Library</span></a>
</nav>
<script>
const MOBILE_APP = location.pathname === "/mobile" || location.pathname === "/mobile/";
if (MOBILE_APP) document.body.classList.add("mobile-app");
const $ = (id) => document.getElementById(id);
const state = { takes: 3, ready: false, playing: null, tab: "all", voices: [], referenceBusy: false, reviewCandidate: null, personId: "brian", people: [] };
const PLAY = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M7 4.5v15l13-7.5z"/></svg>';
const VOICE_PROMPTS = [
"Today, I’m recording my natural speaking voice. I’m speaking clearly at a comfortable pace, as if I were introducing myself to someone new. The room is quiet, and I’m keeping my voice relaxed.",
"A small copper kettle rested beside the open window while rain tapped gently on the roof. Beyond the garden, a train crossed the bridge, its bright lights moving slowly through the evening mist.",
"I’m glad we have a little time to talk today. There’s no need to rush; I can explain the idea step by step, pause when I need to, and make sure every part is easy to follow.",
"Could you bring the blue folder, the green mug, and three fresh sheets of paper? That sounds simple, but listen to how each word changes. Now let me say it again with a little more excitement!"
];
let voiceRecorder = null;
let voiceRecorderStream = null;
let voiceRecorderChunks = [];
let voiceRecorderBusy = false;
let voiceRecordingFailed = false;
let voiceRecordingStartedAt = 0;
let voiceRecordingTimer = null;
let voiceRecordingBlob = null;
let voiceRecordingPersonId = null;
let voiceRecordingPromptIndex = 0;
let voiceRecordingPreviewUrl = null;
const PAUSE = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M6 4h4v16H6zm8 0h4v16h-4z"/></svg>';
function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
async function api(path, body) {
const res = await fetch(path, body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
return data;
}
function fmtTime(s) { s = Math.max(0, Math.round(s)); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`; }
function words(t) { return (t.trim().match(/\S+/g) || []).length; }
/* ------------- status ------------- */
async function pollStatus() {
try {
const s = await api("/api/status");
const el = $("status");
el.className = "status " + (s.error ? "error" : s.ready ? "ready" : "loading");
$("statusText").textContent = s.error ? s.error
: s.ready ? `Ready (${s.model} model on ${s.device === "cpu" ? "CPU" : s.device.toUpperCase()})`
: "Loading the voice model…";
state.ready = s.ready; state.device = s.device;
updateGo(); updateRebuildButton();
if (!s.ready && !s.error) setTimeout(pollStatus, 1500);
} catch { setTimeout(pollStatus, 3000); }
}
/* ------------- voices ------------- */
async function loadVoices() {
const v = await api("/api/voices");
const sel = $("voice"); sel.innerHTML = "";
state.voices = [...v.profiles, ...v.clips];
const add = (label, list, fmt) => {
if (!list.length) return;
const g = document.createElement("optgroup"); g.label = label;
list.forEach((x) => { const o = document.createElement("option"); o.value = x.path; o.textContent = fmt(x); g.appendChild(o); });
sel.appendChild(g);
};
add("Voice profiles (built from many clips)", v.profiles, (x) => x.name);
add("Single clips", v.clips, (x) => `${x.name} (${x.seconds}s)`);
if (!state.voices.length) {
const o = document.createElement("option"); o.textContent = "No voices found"; o.value = ""; sel.appendChild(o);
$("voiceInfo").textContent = "Build a profile with build_voice.py, or add 7-15 second clips to refs or a named *_voice_refs folder.";
}
try { const saved = localStorage.getItem("voice"); if (saved && state.voices.some((x) => x.path === saved)) sel.value = saved; } catch {}
describeVoice(); updateGo(); updateCompareButtons();
}
function currentVoice() { return state.voices.find((x) => x.path === $("voice").value); }
function describeVoice() {
const v = currentVoice(); if (!v) return;
$("voiceInfo").textContent = v.type === "profile"
? `Built from ${v.clips ?? "several"} clips${v.anchor ? `, delivery from ${v.anchor}` : ""}`
: "Copies this one clip's voice and energy";
}
$("voice").addEventListener("change", () => { try { localStorage.setItem("voice", $("voice").value); } catch {} describeVoice(); });
/* ------------- voice profile rebuild ------------- */
async function loadPeople(selectedId) {
const data = await api("/api/people");
state.people = data.people;
const selector = $("personSelect");
selector.replaceChildren();
state.people.forEach((person) => {
const option = document.createElement("option");
option.value = person.id;
option.textContent = person.name;
selector.appendChild(option);
});
let desired = selectedId || state.personId;
try { desired = selectedId || localStorage.getItem("person") || desired; } catch {}
state.personId = state.people.some((person) => person.id === desired) ? desired : "brian";
selector.value = state.personId;
$("personNotice").textContent = state.personId === "brian"
? "The default voice keeps its existing profile and reference locations."
: "This person has separate voice samples, videos, dataset, references, and voice profiles.";
}
async function addPerson() {
const button = $("addPerson");
button.disabled = true;
try {
const result = await api("/api/people", { name: $("newPersonName").value });
$("newPersonName").value = "";
await loadPeople(result.person.id);
await loadRebuildOptions();
await refreshPersonMedia();
} catch (e) {
$("rebuildError").textContent = e.message;
$("rebuildError").hidden = false;
} finally {
button.disabled = false;
}
}
async function refreshPersonMedia() {
try {
const media = await api(`/api/person/media?person=${encodeURIComponent(state.personId)}`);
const referenceCount = media.references.length;
const videoCount = media.videos.length;
$("personMediaStatus").textContent =
`${media.person.name}: ${referenceCount} voice sample${referenceCount === 1 ? "" : "s"}, ` +
`${videoCount} video/audio file${videoCount === 1 ? "" : "s"}` +
(media.dataset_ready ? ", prepared dataset available." : ".");
renderPersonVoiceSamples(media.references);
$("preparePersonDataset").disabled = referenceCount === 0 || videoCount === 0 ||
state.datasetPreparing || voiceRecorderBusy || Boolean(voiceRecordingBlob);
syncVoiceRecorderAvailability(referenceCount);
return media;
} catch (e) {
$("personMediaStatus").textContent = "Could not load this person’s uploaded files.";
$("personDatasetError").textContent = e.message;
$("personDatasetError").hidden = false;
}
}
async function uploadPersonFiles(kind) {
const input = kind === "reference" ? $("personReferenceFiles") : $("personVideoFiles");
const button = kind === "reference" ? $("uploadPersonReferences") : $("uploadPersonVideos");
const files = [...input.files];
if (!files.length) {
$("personDatasetError").textContent = "Choose one or more files to upload.";
$("personDatasetError").hidden = false;
return;
}
const personId = state.personId;
button.disabled = true;
$("personSelect").disabled = true;
$("personDatasetError").hidden = true;
try {
const currentMedia = await api(`/api/person/media?person=${encodeURIComponent(personId)}`);
if (kind === "reference" && files.length > 5 - currentMedia.references.length) {
throw new Error(`This person can have at most five voice samples; ${5 - currentMedia.references.length} slot(s) remain.`);
}
for (let index = 0; index < files.length; index++) {
const file = files[index];
$("personMediaStatus").textContent = `Uploading ${index + 1} of ${files.length}: ${file.name}`;
const query = new URLSearchParams({ person: personId, kind, name: file.name });
const response = await fetch(`/api/person/upload?${query}`, {
method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file,
});
const result = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(result.error || `Upload failed (${response.status}).`);
}
input.value = "";
await refreshPersonMedia();
if (kind === "reference") {
await loadVoices();
await loadRebuildOptions();
}
} catch (e) {
$("personDatasetError").textContent = e.message;
$("personDatasetError").hidden = false;
await refreshPersonMedia();
} finally {
button.disabled = false;
$("personSelect").disabled = false;
}
}
function syncVoiceRecorderAvailability(referenceCount) {
$("startVoiceRecording").disabled = referenceCount >= 5 || voiceRecorderBusy ||
state.datasetPreparing || Boolean(voiceRecordingBlob);
$("recordOnDevice").disabled = referenceCount >= 5 || voiceRecorderBusy || state.datasetPreparing;
$("voicePromptSelect").disabled = voiceRecorderBusy || state.datasetPreparing || Boolean(voiceRecordingBlob);
$("saveVoiceRecording").disabled = !voiceRecordingBlob || voiceRecorderBusy || referenceCount >= 5;
$("discardVoiceRecording").disabled = !voiceRecordingBlob || voiceRecorderBusy;
$("stopVoiceRecording").disabled = !voiceRecorder || voiceRecorder.state !== "recording";
$("preparePersonDataset").disabled = $("preparePersonDataset").disabled ||
voiceRecorderBusy || Boolean(voiceRecordingBlob);
}
function renderPersonVoiceSamples(references) {
const list = $("personVoiceSampleList");
list.replaceChildren();
const uploads = references.filter((name) => /^voice_ref[1-5]\.wav$/i.test(name));
if (!uploads.length) {
const empty = document.createElement("p");
empty.className = "voice-sample-empty";
empty.textContent = "No uploaded samples yet. Recorded or uploaded samples appear here for preview and removal.";
list.appendChild(empty);
return;
}
uploads.forEach((name) => {
const row = document.createElement("div");
row.className = "voice-sample-row";
const details = document.createElement("div");
const title = document.createElement("p");
title.textContent = name;
const audio = document.createElement("audio");
audio.controls = true;
audio.preload = "none";
audio.src = `/api/person/reference-audio?person=${encodeURIComponent(state.personId)}&name=${encodeURIComponent(name)}`;
details.append(title, audio);
const remove = document.createElement("button");
remove.className = "btn discard";
remove.type = "button";
remove.textContent = "Remove";
remove.disabled = state.datasetPreparing;
remove.setAttribute("aria-label", `Remove voice sample ${name}`);
remove.addEventListener("click", () => removePersonVoiceSample(name, remove));
row.append(details, remove);
list.appendChild(row);
});
}
async function removePersonVoiceSample(name, button) {
if (state.datasetPreparing) return;
if (!window.confirm(`Remove ${name} from this person's voice samples?`)) return;
button.disabled = true;
try {
await api("/api/person/reference/delete", { person: state.personId, name });
await refreshPersonMedia();
await loadVoices();
await loadRebuildOptions();
setVoiceRecorderStatus(`${name} removed. You can record or upload a replacement sample.`, "success");
} catch (error) {
setVoiceRecorderStatus(error.message || "Could not remove this voice sample.", "error");
button.disabled = false;
}
}
function setVoiceRecorderStatus(message, kind = "") {
const status = $("voiceRecorderStatus");
status.textContent = message;
status.classList.remove("error", "success");
if (kind) status.classList.add(kind);
}
function showVoicePrompt() {
voiceRecordingPromptIndex = Number($("voicePromptSelect").value) || 0;
$("voicePromptText").textContent = VOICE_PROMPTS[voiceRecordingPromptIndex];
}
function releaseVoiceRecorder() {
if (voiceRecordingTimer) clearInterval(voiceRecordingTimer);
voiceRecordingTimer = null;
if (voiceRecorderStream) voiceRecorderStream.getTracks().forEach((track) => track.stop());
voiceRecorderStream = null;
voiceRecorder = null;
$("personSelect").disabled = false;
$("uploadPersonReferences").disabled = false;
$("uploadPersonVideos").disabled = false;
$("startVoiceRecording").classList.remove("recording");
$("startVoiceRecording").textContent = "Record prompt";
$("stopVoiceRecording").disabled = true;
}
function encodeAudioAsWav(audioBuffer) {
const channels = audioBuffer.numberOfChannels;
const frameCount = audioBuffer.length;
const bytesPerSample = 2;
const dataBytes = frameCount * bytesPerSample;
const buffer = new ArrayBuffer(44 + dataBytes);
const view = new DataView(buffer);
const writeText = (offset, text) => {
for (let index = 0; index < text.length; index++) {
view.setUint8(offset + index, text.charCodeAt(index));
}
};
writeText(0, "RIFF");
view.setUint32(4, 36 + dataBytes, true);
writeText(8, "WAVE");
writeText(12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, audioBuffer.sampleRate, true);
view.setUint32(28, audioBuffer.sampleRate * bytesPerSample, true);
view.setUint16(32, bytesPerSample, true);
view.setUint16(34, 16, true);
writeText(36, "data");
view.setUint32(40, dataBytes, true);
const channelData = Array.from({ length: channels }, (_, index) => audioBuffer.getChannelData(index));
for (let frame = 0; frame < frameCount; frame++) {
let sample = 0;
for (const channel of channelData) sample += channel[frame];
sample /= channels;
sample = Math.max(-1, Math.min(1, sample));
view.setInt16(44 + frame * bytesPerSample, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);
}
return new Blob([buffer], { type: "audio/wav" });
}
async function convertVoiceRecording(blob) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) throw new Error("This browser cannot convert the recording to WAV.");
const context = new AudioContextClass();
try {
const decoded = await context.decodeAudioData(await blob.arrayBuffer());
return encodeAudioAsWav(decoded);
} finally {
await context.close();
}
}
async function uploadVoiceSampleBlob(blob, personId, filename) {
const media = await api(`/api/person/media?person=${encodeURIComponent(personId)}`);
if (media.references.length >= 5) throw new Error("This person already has five voice samples. Remove a sample before adding another.");
const query = new URLSearchParams({ person: personId, kind: "reference", name: filename });
const response = await fetch(`/api/person/upload?${query}`, {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: blob,
});
const result = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(result.error || `Sample upload failed (${response.status}).`);
return result;
}
function updateRecordingClock() {
const elapsed = (Date.now() - voiceRecordingStartedAt) / 1000;
const seconds = Math.floor(elapsed);
$("voiceRecordingTime").textContent =
`${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
if (elapsed >= 29.5 && voiceRecorder?.state === "recording") {
setVoiceRecorderStatus("Maximum 30-second sample reached. Preparing your WAV preview…");
voiceRecorder.stop();
}
}
async function startVoiceRecording() {
if (voiceRecorderBusy || state.datasetPreparing) return;
if (!navigator.mediaDevices?.getUserMedia || !window.MediaRecorder) {
setVoiceRecorderStatus("Live microphone access requires a secure browser connection. Use “Record on this device” to open your phone’s built-in recorder, or open Studio through localhost/HTTPS.", "error");
return;
}
voiceRecorderBusy = true;
voiceRecordingPersonId = state.personId;
voiceRecordingPromptIndex = Number($("voicePromptSelect").value) || 0;
voiceRecorderChunks = [];
voiceRecordingFailed = false;
syncVoiceRecorderAvailability(Number.POSITIVE_INFINITY);
$("personSelect").disabled = true;
$("uploadPersonReferences").disabled = true;
$("uploadPersonVideos").disabled = true;
try {
setVoiceRecorderStatus("Requesting microphone access…");
voiceRecorderStream = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false }
});
voiceRecorder = new MediaRecorder(voiceRecorderStream);
voiceRecorder.addEventListener("dataavailable", (event) => {
if (event.data.size) voiceRecorderChunks.push(event.data);
});
voiceRecorder.addEventListener("stop", async () => {
const duration = (Date.now() - voiceRecordingStartedAt) / 1000;
releaseVoiceRecorder();
voiceRecorderBusy = true;
if (voiceRecordingFailed) {
voiceRecordingFailed = false;
voiceRecorderBusy = false;
await refreshPersonMedia();
return;
}
$("voiceRecordingTime").textContent = `${String(Math.floor(duration / 60)).padStart(2, "0")}:${String(Math.floor(duration % 60)).padStart(2, "0")}`;
if (duration < 10) {
voiceRecorderBusy = false;
setVoiceRecorderStatus("That take was under 10 seconds. Please record at least 10 seconds, up to 30.", "error");
await refreshPersonMedia();
return;
}
setVoiceRecorderStatus("Converting your recording to WAV for preview…");
try {
const raw = new Blob(voiceRecorderChunks, { type: voiceRecorderChunks[0]?.type || "audio/webm" });
voiceRecordingBlob = await convertVoiceRecording(raw);
if (voiceRecordingPreviewUrl) URL.revokeObjectURL(voiceRecordingPreviewUrl);
voiceRecordingPreviewUrl = URL.createObjectURL(voiceRecordingBlob);
$("voiceRecordingPreview").src = voiceRecordingPreviewUrl;
$("voiceRecordingPreview").hidden = false;
setVoiceRecorderStatus(`WAV preview ready (${duration.toFixed(1)} seconds). Listen, then save it as a sample for ${state.people.find((person) => person.id === voiceRecordingPersonId)?.name || "the selected person"}.`, "success");
} catch (error) {
voiceRecordingBlob = null;
setVoiceRecorderStatus(error.message || "The recording could not be converted to WAV.", "error");
} finally {
voiceRecorderBusy = false;
await refreshPersonMedia();
}
}, { once: true });
voiceRecorder.addEventListener("error", (event) => {
voiceRecordingFailed = true;
setVoiceRecorderStatus(event.error?.message || "The microphone recording failed.", "error");
if (voiceRecorder?.state === "recording") voiceRecorder.stop();
}, { once: true });
voiceRecorder.start(200);
voiceRecordingStartedAt = Date.now();
$("voiceRecordingTime").textContent = "00:00";
$("startVoiceRecording").classList.add("recording");
$("startVoiceRecording").textContent = "Recording…";
$("stopVoiceRecording").disabled = false;
voiceRecordingTimer = setInterval(updateRecordingClock, 250);
setVoiceRecorderStatus("Recording locally. Read naturally and keep the whole sample between 10 and 30 seconds.");
} catch (error) {
releaseVoiceRecorder();
voiceRecorderBusy = false;
const message = error.name === "NotAllowedError"
? "Microphone access was denied. Allow microphone access in your browser and try again."
: error.message || "Could not start microphone recording.";
setVoiceRecorderStatus(message, "error");
await refreshPersonMedia();
}
}
function stopVoiceRecording() {
if (!voiceRecorder || voiceRecorder.state !== "recording") return;
$("stopVoiceRecording").disabled = true;
setVoiceRecorderStatus("Finishing recording…");
voiceRecorder.stop();
}
async function uploadDeviceRecording(event) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file || voiceRecorderBusy || state.datasetPreparing) return;
const personId = state.personId;
voiceRecorderBusy = true;
syncVoiceRecorderAvailability(Number.POSITIVE_INFINITY);
$("personSelect").disabled = true;
$("uploadPersonReferences").disabled = true;
$("uploadPersonVideos").disabled = true;
setVoiceRecorderStatus("Converting the device recording to WAV…");
try {
const wav = await convertVoiceRecording(file);
const duration = await new Promise((resolve, reject) => {
const url = URL.createObjectURL(wav);
const audio = document.createElement("audio");
audio.preload = "metadata";
audio.onloadedmetadata = () => {
URL.revokeObjectURL(url);
resolve(audio.duration);
};
audio.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error("Could not read the duration of this audio recording."));
};
audio.src = url;
});
if (!Number.isFinite(duration) || duration < 10 || duration > 30) {
throw new Error("Voice samples must be 10–30 seconds long. Record a new take and try again.");
}
await uploadVoiceSampleBlob(wav, personId, "device-voice-sample.wav");
setVoiceRecorderStatus(`Device recording saved as a ${duration.toFixed(1)}-second voice sample.`, "success");
await loadVoices();
await loadRebuildOptions();
} catch (error) {
setVoiceRecorderStatus(error.message || "Could not process the device recording.", "error");
} finally {
voiceRecorderBusy = false;
$("personSelect").disabled = false;
$("uploadPersonReferences").disabled = false;
$("uploadPersonVideos").disabled = false;
await refreshPersonMedia();
}
}
async function saveVoiceRecording() {
if (!voiceRecordingBlob || voiceRecorderBusy || !voiceRecordingPersonId) return;
voiceRecorderBusy = true;
$("saveVoiceRecording").disabled = true;
$("personSelect").disabled = true;
$("uploadPersonReferences").disabled = true;
$("uploadPersonVideos").disabled = true;
try {
const promptNumber = String(voiceRecordingPromptIndex + 1).padStart(2, "0");
await uploadVoiceSampleBlob(voiceRecordingBlob, voiceRecordingPersonId, `voice-prompt-${promptNumber}.wav`);
voiceRecordingBlob = null;
voiceRecordingPersonId = null;
$("voiceRecordingPreview").pause();
$("voiceRecordingPreview").removeAttribute("src");
$("voiceRecordingPreview").hidden = true;
$("voiceRecordingTime").textContent = "00:00";
if (voiceRecordingPreviewUrl) URL.revokeObjectURL(voiceRecordingPreviewUrl);
voiceRecordingPreviewUrl = null;
setVoiceRecorderStatus("Voice sample saved locally. Choose another prompt to record the next sample.", "success");
await loadVoices();
await loadRebuildOptions();
} catch (error) {
setVoiceRecorderStatus(error.message || "Could not save this voice sample.", "error");
} finally {
voiceRecorderBusy = false;
$("personSelect").disabled = false;
$("uploadPersonReferences").disabled = false;
$("uploadPersonVideos").disabled = false;
await refreshPersonMedia();
}
}
function discardVoiceRecording() {
if (voiceRecordingPreviewUrl) URL.revokeObjectURL(voiceRecordingPreviewUrl);
voiceRecordingPreviewUrl = null;
voiceRecordingBlob = null;
voiceRecordingPersonId = null;
$("voiceRecordingPreview").pause();
$("voiceRecordingPreview").removeAttribute("src");
$("voiceRecordingPreview").hidden = true;
$("voiceRecordingTime").textContent = "00:00";
setVoiceRecorderStatus("Take discarded. Choose a prompt and record another sample.");
refreshPersonMedia();
}
async function preparePersonDataset() {
$("personDatasetError").hidden = true;
$("personDatasetProgress").hidden = false;
$("personDatasetBar").style.width = "0%";
state.datasetPreparing = true;
$("preparePersonDataset").disabled = true;
$("uploadPersonReferences").disabled = true;
$("uploadPersonVideos").disabled = true;
$("personSelect").disabled = true;
syncVoiceRecorderAvailability(Number.POSITIVE_INFINITY);
try {
let job = await api("/api/person/prepare-dataset", { person: state.personId });
while (job.state === "queued" || job.state === "running") {
$("personMediaStatus").textContent = job.message || "Preparing speaker clips…";
$("personDatasetBar").style.width = `${job.progress || 0}%`;
$("personDatasetProgress").setAttribute("aria-valuenow", job.progress || 0);
await new Promise((resolve) => setTimeout(resolve, 1500));
job = await api(`/api/person/dataset/${job.id}`);
}
if (job.state === "error") throw new Error(job.error || "Video clip preparation failed.");
const result = job.result;
const sourceList = await api(`/api/rebuild/options?person=${encodeURIComponent(state.personId)}`);
const selected = sourceList.sources.filter((source) => source.selected).map((source) => source.path);
if (sourceList.sources.some((source) => source.path === result.dataset)) {
if (!selected.includes(result.dataset)) selected.push(result.dataset);
await api("/api/person/sources", { person: state.personId, sources: selected });
}
const media = await refreshPersonMedia();
await loadRebuildOptions();
await loadVoices();
$("personDatasetBar").style.width = "100%";
$("personDatasetProgress").setAttribute("aria-valuenow", 100);
const failures = result.failures?.length
? ` ${result.failures.length} video(s) failed: ${result.failures.map((item) => `${item.video} (${item.error})`).join("; ")}.`
: "";
$("personMediaStatus").textContent = result.clips_kept
? `Prepared ${result.clips_kept} clips from ${result.videos_processed} videos. ` +
`The dataset is selected below; choose an anchor, then rebuild the profile.${failures}`
: result.videos_skipped === result.videos_found && media?.dataset_ready
? "These videos were already prepared. The existing dataset is still selected below; choose an anchor, then rebuild the profile."
: `Preparation finished but found no usable clips. Check the voice samples and videos, then try again.${failures}`;
} catch (e) {
$("personDatasetError").textContent = e.message;
$("personDatasetError").hidden = false;
$("personMediaStatus").textContent = "Clip preparation did not complete.";
} finally {
state.datasetPreparing = false;
$("personSelect").disabled = false;
$("uploadPersonReferences").disabled = false;
$("uploadPersonVideos").disabled = false;
await refreshPersonMedia();
}
}
async function loadRebuildOptions() {
try {
const data = await api(`/api/rebuild/options?person=${encodeURIComponent(state.personId)}`);
const sources = $("rebuildSources");
sources.innerHTML = "";
data.sources.forEach((source) => {
const label = document.createElement("label");
label.className = "source-option";
const checkbox = document.createElement("input");
checkbox.type = "checkbox"; checkbox.value = source.path; checkbox.checked = source.selected;
const text = document.createElement("span");
text.textContent = `${source.name} (${source.clips} clips)`;
label.append(checkbox, text); sources.appendChild(label);
});
$("sourceInfo").textContent = data.sources.length
? `Sources selected for ${data.person.name}. Prepared datasets use their kept clips and speaker-match scores; folders use all supported audio files.`
: "No audio sources found. Add a prepared dataset, or clips to refs or a named *_voice_refs folder.";
const anchor = $("rebuildAnchor");
anchor.innerHTML = "";
data.anchors.forEach((item) => {
const option = document.createElement("option");
option.value = item.path; option.textContent = `${item.name} (${item.seconds}s)`;
anchor.appendChild(option);
});
const previousAnchor = (data.profile.anchor || "").replaceAll("\\", "/");
if (data.anchors.some((item) => item.path === previousAnchor)) anchor.value = previousAnchor;
updateAnchorPreview();
if (data.profile.created) {
$("profileInfo").textContent = `${data.person.name} profile: ${data.profile.clips_used} clips, built ${new Date(data.profile.created).toLocaleString()}.`;
} else {
$("profileInfo").textContent = `No ${data.person.name} profile yet; rebuilding will create ${data.profile.path}.`;
}
state.rebuildProfilePath = data.profile.path;
state.candidateProfilePath = data.candidate.path;
if (data.candidate.exists) {
$("profileInfo").textContent += ` ${data.person.name} candidate ready (${data.candidate.clips_used} clips, built ${new Date(data.candidate.created).toLocaleString()}).`;
}
updateCompareButtons();
updateRebuildButton();
await loadReferences();
} catch (e) {
$("sourceInfo").textContent = "Could not load rebuild options.";
$("rebuildError").textContent = e.message;
$("rebuildError").hidden = false;
}
}
async function loadReferences() {
try {
const data = await api(`/api/references?person=${encodeURIComponent(state.personId)}`);
renderReferences(data.items);
} catch (e) {
$("referenceError").textContent = e.message;
$("referenceError").hidden = false;
}
}
function renderReferences(items) {
const list = $("referenceList");
list.replaceChildren();
if (!items.length) {
const empty = document.createElement("p");
empty.className = "rebuild-note";
empty.textContent = "No reference clips yet. Promote clips from the review queue to fill the active six.";
list.appendChild(empty);
return;
}
items.forEach((item) => {
const row = document.createElement("div");
row.className = "reference-item";
const details = document.createElement("div");
const title = document.createElement("p");
title.textContent = `${item.slot}${item.seconds ? ` · ${item.seconds}s` : ""}`;
details.appendChild(title);
const info = document.createElement("small");
const facts = [
item.source_clip ? `From ${item.source_clip}` : item.source,
item.similarity == null ? null : `Speaker match ${item.similarity}`,
].filter(Boolean);
info.textContent = facts.join(" · ") || "Active reference";
details.appendChild(info);
if (item.text) {
const transcript = document.createElement("small");
transcript.textContent = item.text;
details.appendChild(transcript);
}
const audio = document.createElement("audio");
audio.controls = true;
audio.preload = "none";
audio.src = `/files/${encodeURI(item.file)}`;
details.appendChild(audio);
row.appendChild(details);
list.appendChild(row);
});
}
function selectedReferenceSources() {
return [...$("rebuildSources").querySelectorAll("input:checked")].map((el) => el.value);
}
function renderReview(data) {
const item = data.candidate;
state.reviewCandidate = item;
renderTopReferenceCandidates(data.top_candidates || []);
const card = $("referenceReviewCard");
card.hidden = !item;
for (const id of ["reviewDelete", "reviewKeep", "reviewPromote"]) $(id).disabled = !item || state.referenceBusy;
if (!item) {
$("reviewAudio").pause();
$("reviewAudio").removeAttribute("src");
$("reviewTitle").textContent = "";
$("reviewInfo").textContent = "";
$("reviewText").textContent = "";
$("referenceStatus").textContent = "No more unreviewed clips in the selected sources.";
return;
}
$("reviewTitle").textContent = item.name;
$("reviewInfo").textContent = `${item.source} · ${item.seconds}s` +
(item.similarity == null ? "" : ` · Speaker match ${item.similarity}`) +
(data.remaining ? ` · ${data.remaining} remaining` : "");
$("reviewText").textContent = item.text || "No transcript available.";
$("reviewAudio").src = `/api/reference-review/audio?person=${encodeURIComponent(state.personId)}&path=${encodeURIComponent(item.path)}`;
$("referenceStatus").textContent = "Listen, then choose Delete, Keep, or Promote.";
}
function renderTopReferenceCandidates(items) {
const list = $("topReferenceList");
list.replaceChildren();
if (!items.length) {
const empty = document.createElement("p");
empty.className = "rebuild-note";
empty.textContent = "No unreviewed candidates are available.";
list.appendChild(empty);
return;
}
items.forEach((item, index) => {
const row = document.createElement("div");
row.className = "top-reference-item";
const rank = document.createElement("span");
rank.className = "top-reference-rank";
rank.textContent = `#${index + 1}`;
const details = document.createElement("div");
const name = document.createElement("p");
name.textContent = item.name;
details.appendChild(name);
const info = document.createElement("small");
info.textContent = `${item.source} · ${item.seconds}s` +
(item.similarity == null ? "" : ` · Speaker match ${item.similarity}`);
details.appendChild(info);
if (item.text) {
const transcript = document.createElement("small");
transcript.textContent = item.text;
details.appendChild(transcript);
}
const audio = document.createElement("audio");
audio.controls = true;
audio.preload = "none";
audio.src = `/api/reference-review/audio?person=${encodeURIComponent(state.personId)}&path=${encodeURIComponent(item.path)}`;
details.appendChild(audio);
const promote = document.createElement("button");
promote.className = "btn review-promote";
promote.type = "button";
promote.textContent = "Promote";
promote.disabled = state.referenceBusy;
promote.addEventListener("click", () => reviewReferenceAction("promote", item));
row.append(rank, details, promote);
list.appendChild(row);
});
}
async function startReferenceReview() {
state.referenceBusy = true;
$("startReferenceReview").disabled = true;
$("referenceError").hidden = true;
renderReview({ candidate: null });
$("referenceStatus").textContent = "Finding and ranking clips…";
try {
const result = await api("/api/reference-review/start", {
person: state.personId, sources: selectedReferenceSources(),
});
renderReview(result);
} catch (e) {
$("referenceError").textContent = e.message;
$("referenceError").hidden = false;
$("referenceStatus").textContent = "Could not start the review.";
} finally {
state.referenceBusy = false;
$("startReferenceReview").disabled = false;
for (const id of ["reviewDelete", "reviewKeep", "reviewPromote"]) $(id).disabled = !state.reviewCandidate;
$("topReferenceList").querySelectorAll("button").forEach((button) => { button.disabled = false; });
}
}
async function reviewReferenceAction(action, selectedItem = state.reviewCandidate) {
const item = selectedItem;
if (!item || state.referenceBusy) return;
if (action === "delete" && !window.confirm(`Permanently delete the source audio "${item.name}"? This cannot be undone.`)) return;
state.referenceBusy = true;
$("referenceError").hidden = true;
for (const id of ["reviewDelete", "reviewKeep", "reviewPromote"]) $(id).disabled = true;
try {
const result = await api("/api/reference-review/action", {
action, path: item.path, sources: selectedReferenceSources(),
person: state.personId,
});
if (action === "promote") await loadReferences();
renderReview(result);
if (action === "delete") $("referenceStatus").textContent = `Deleted ${item.name}. ` + $("referenceStatus").textContent;
else if (action === "keep") $("referenceStatus").textContent = `Kept ${item.name}. ` + $("referenceStatus").textContent;
else $("referenceStatus").textContent = result.message || `Promoted ${item.name}.`;
} catch (e) {
$("referenceError").textContent = e.message;
$("referenceError").hidden = false;
$("referenceStatus").textContent = "The review action did not complete.";
} finally {
state.referenceBusy = false;
for (const id of ["reviewDelete", "reviewKeep", "reviewPromote"]) $(id).disabled = !state.reviewCandidate;
$("topReferenceList").querySelectorAll("button").forEach((button) => { button.disabled = false; });
}
}
function updateRebuildButton() {
$("rebuildButton").disabled = !!state.rebuilding || !!state.comparing || !state.ready ||
!$("rebuildSources").querySelector("input:checked") || !$("rebuildAnchor").value;
}
function updateCompareButtons() {
const candidate = !!state.candidateProfilePath && state.voices.some((voice) => voice.path === state.candidateProfilePath);
$("compareButton").disabled = !!state.comparing || !state.ready || !candidate || !currentProfileExists();
$("adoptButton").disabled = !!state.comparing || !candidate;
}
function currentProfileExists() {
return state.voices.some((voice) => voice.path === state.rebuildProfilePath);
}
async function rebuildVoice() {
if (!window.confirm("Build a new candidate profile from the selected clips? Your current voice stays unchanged until you choose Use candidate voice.")) return;
$("rebuildError").hidden = true;
$("rebuildButton").disabled = true;
$("rebuildButton").textContent = "Rebuilding…";
state.rebuilding = true;
try {
let job = await api("/api/rebuild", {
person: state.personId,
sources: [...$("rebuildSources").querySelectorAll("input:checked")].map((el) => el.value),
anchor: $("rebuildAnchor").value,
max_clips: $("rebuildMax").value,
min_sim: +$("rebuildSim").value,
blend: +$("rebuildBlend").value,
});
$("rebuildProgress").hidden = false;
while (job.state === "queued" || job.state === "running") {
$("rebuildStatus").textContent = job.message || "Rebuilding voice profile…";
$("rebuildBar").style.width = `${job.progress || 0}%`;
$("rebuildProgress").setAttribute("aria-valuenow", job.progress || 0);
await new Promise((resolve) => setTimeout(resolve, 1000));
job = await api(`/api/rebuild/${job.id}`);
}
if (job.state === "error") throw new Error(job.error || "Voice profile rebuild failed.");
$("rebuildBar").style.width = "100%";
$("rebuildProgress").setAttribute("aria-valuenow", 100);
$("rebuildStatus").textContent = `Rebuilt from ${job.result.clips_used} clips. Refreshing voice list…`;
await loadVoices();
await loadRebuildOptions();
$("rebuildStatus").textContent = `Candidate built from ${job.result.clips_used} quality-filtered clips across ${job.result.source_groups} recordings (${job.result.clips_rejected_quality} clips rejected). Compare A/B, then adopt if it sounds better.`;
updateCompareButtons();
} catch (e) {
$("rebuildError").textContent = e.message;
$("rebuildError").hidden = false;
$("rebuildStatus").textContent = "Rebuild did not complete.";
} finally {
state.rebuilding = false;
$("rebuildButton").textContent = "Rebuild profile";
updateRebuildButton();
updateCompareButtons();
}
}
$("rebuildButton").addEventListener("click", rebuildVoice);
$("rebuildAnchor").addEventListener("change", () => { updateAnchorPreview(); updateRebuildButton(); });
$("personSelect").addEventListener("change", async () => {
state.personId = $("personSelect").value;
try { localStorage.setItem("person", state.personId); } catch {}
state.reviewCandidate = null;
$("referenceReviewCard").hidden = true;
$("topReferenceList").replaceChildren();
$("reviewAudio").pause();
$("reviewAudio").removeAttribute("src");
await loadRebuildOptions();
await refreshPersonMedia();
});
$("addPerson").addEventListener("click", addPerson);
$("uploadPersonReferences").addEventListener("click", () => uploadPersonFiles("reference"));
$("uploadPersonVideos").addEventListener("click", () => uploadPersonFiles("video"));
$("recordOnDevice").addEventListener("click", () => $("mobileVoiceCapture").click());
$("mobileVoiceCapture").addEventListener("change", uploadDeviceRecording);
$("voicePromptText").textContent = VOICE_PROMPTS[0];
$("voicePromptSelect").addEventListener("change", showVoicePrompt);
$("startVoiceRecording").addEventListener("click", startVoiceRecording);
$("stopVoiceRecording").addEventListener("click", stopVoiceRecording);
$("saveVoiceRecording").addEventListener("click", saveVoiceRecording);
$("discardVoiceRecording").addEventListener("click", discardVoiceRecording);
$("preparePersonDataset").addEventListener("click", preparePersonDataset);
window.addEventListener("beforeunload", () => {
if (voiceRecordingTimer) clearInterval(voiceRecordingTimer);
if (voiceRecorderStream) voiceRecorderStream.getTracks().forEach((track) => track.stop());
if (voiceRecordingPreviewUrl) URL.revokeObjectURL(voiceRecordingPreviewUrl);
});
let pendingInstallPrompt;
window.addEventListener("beforeinstallprompt", (event) => {
event.preventDefault();
pendingInstallPrompt = event;
$("installApp").style.display = "inline-flex";
});
$("installApp").addEventListener("click", async () => {
if (!pendingInstallPrompt) return;
pendingInstallPrompt.prompt();
await pendingInstallPrompt.userChoice;
pendingInstallPrompt = null;
$("installApp").style.display = "none";
});
if (MOBILE_APP && "IntersectionObserver" in window) {
const mobileLinks = [...document.querySelectorAll(".mobile-nav a")];
const sections = mobileLinks.map((link) => document.querySelector(link.getAttribute("href"))).filter(Boolean);
const navObserver = new IntersectionObserver((entries) => {
const visible = entries.filter((entry) => entry.isIntersecting)
.sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
if (!visible) return;
mobileLinks.forEach((link) => {
const active = link.hash === `#${visible.target.id}`;
if (active) link.setAttribute("aria-current", "page");
else link.removeAttribute("aria-current");
});
}, { rootMargin: "-18% 0px -58% 0px", threshold: [0, 0.2, 0.5] });
sections.forEach((section) => navObserver.observe(section));
}
if ("serviceWorker" in navigator && location.protocol !== "file:") {
navigator.serviceWorker.register("/sw.js").catch((error) => {
console.warn("Voice Studio app shell could not be installed for offline use.", error);
});
}
$("newPersonName").addEventListener("keydown", (event) => {
if (event.key === "Enter") addPerson();
});
$("startReferenceReview").addEventListener("click", startReferenceReview);
$("reviewDelete").addEventListener("click", () => reviewReferenceAction("delete"));
$("reviewKeep").addEventListener("click", () => reviewReferenceAction("keep"));
$("reviewPromote").addEventListener("click", () => reviewReferenceAction("promote"));
$("rebuildSources").addEventListener("change", () => {
updateRebuildButton();
state.reviewCandidate = null;
$("reviewAudio").pause();
$("reviewAudio").removeAttribute("src");
$("referenceReviewCard").hidden = true;
$("referenceStatus").textContent = "Source selection changed. Start a new review.";
api("/api/person/sources", { person: state.personId, sources: selectedReferenceSources() })
.then(async () => {
const data = await api(`/api/rebuild/options?person=${encodeURIComponent(state.personId)}`);
const anchor = $("rebuildAnchor");
const previousAnchor = anchor.value;
anchor.replaceChildren();
data.anchors.forEach((item) => {
const option = document.createElement("option");
option.value = item.path;
option.textContent = `${item.name} (${item.seconds}s)`;
anchor.appendChild(option);
});
if (data.anchors.some((item) => item.path === previousAnchor)) anchor.value = previousAnchor;
else if (data.anchors.some((item) => item.path === (data.profile.anchor || "").replaceAll("\\", "/"))) {
anchor.value = (data.profile.anchor || "").replaceAll("\\", "/");
}
updateAnchorPreview();
updateRebuildButton();
$("sourceInfo").textContent = `Source selection saved for ${$("personSelect").selectedOptions[0].textContent}.`;
})
.catch((e) => {
$("rebuildError").textContent = e.message;
$("rebuildError").hidden = false;
});
});
function updateAnchorPreview() {
const audio = $("rebuildAnchorAudio");
const path = $("rebuildAnchor").value;
audio.pause();
if (!path) {
audio.removeAttribute("src");
audio.hidden = true;
return;
}
audio.src = `/api/anchor-audio?person=${encodeURIComponent(state.personId)}&path=${encodeURIComponent(path)}`;
audio.hidden = false;
}
async function compareProfiles() {
$("compareError").hidden = true;
state.comparing = true;
updateCompareButtons();
$("compareStatus").textContent = "Starting matched A/B generation…";
try {
let job = await api("/api/compare", {
person: state.personId,
text: $("compareScript").value,
exaggeration: +$("exag").value,
cfg: +$("cfg").value,
temperature: +$("temp").value,
seed: 123456,
});
while (job.state === "queued" || job.state === "running") {
$("compareStatus").textContent = job.message || "Generating samples…";
await new Promise((resolve) => setTimeout(resolve, 1000));
job = await api(`/api/compare/${job.id}`);
}
if (job.state === "error") throw new Error(job.error || "Comparison failed.");
$("compareCurrent").src = "/files/" + encodeURI(job.result[0].file);
$("compareCandidate").src = "/files/" + encodeURI(job.result[1].file);
$("compareAudio").hidden = false;
$("compareStatus").textContent = "A/B samples are ready. Listen and decide whether to use the candidate.";
} catch (e) {
$("compareError").textContent = e.message;
$("compareError").hidden = false;
$("compareStatus").textContent = "Comparison did not complete.";
} finally {
state.comparing = false;
updateCompareButtons();
}
}
$("compareButton").addEventListener("click", compareProfiles);
$("adoptButton").addEventListener("click", async () => {
if (!window.confirm("Replace the current voice profile with the candidate profile?")) return;
$("adoptButton").disabled = true;
$("compareError").hidden = true;
try {
const adopted = await api("/api/rebuild/adopt", { person: state.personId });
await loadVoices();
$("voice").value = adopted.path;
try { localStorage.setItem("voice", adopted.path); } catch {}
describeVoice();
await loadRebuildOptions();
$("compareStatus").textContent = `Candidate adopted (${adopted.clips_used} clips).`;
} catch (e) {
$("compareError").textContent = e.message;
$("compareError").hidden = false;
} finally {
updateCompareButtons();
}
});
for (const [id, out] of [["rebuildSim", "rebuildSimOut"], ["rebuildBlend", "rebuildBlendOut"]]) {
$(id).addEventListener("input", () => { $(out).textContent = (+$(id).value).toFixed(2); });
}
/* ------------- controls ------------- */
const sliders = [["exag", (v) => v < 0.45 ? "calm" : v < 0.7 ? "natural" : v < 0.95 ? "lively" : "very excited"],
["cfg", (v) => v < 0.35 ? "slow" : v < 0.65 ? "natural" : "quick"],
["temp", (v) => v < 0.65 ? "steady" : v < 0.9 ? "natural" : "loose"],
["pause", (v) => `${(+v).toFixed(2)}s`]];
sliders.forEach(([id, label]) => {
const el = $(id), out = $(id + "Out");
try { const s = localStorage.getItem("s_" + id); if (s !== null) el.value = s; } catch {}
const upd = () => { out.textContent = label(+el.value); try { localStorage.setItem("s_" + id, el.value); } catch {} };
el.addEventListener("input", upd); upd();
});
document.querySelectorAll(".takes button").forEach((b) => b.addEventListener("click", () => {
state.takes = +b.dataset.n;
document.querySelectorAll(".takes button").forEach((x) => x.setAttribute("aria-pressed", x === b));
}));
$("script").addEventListener("input", () => {
const n = words($("script").value);
const secs = n / 2.6;
$("count").textContent = n ? `${n} word${n === 1 ? "" : "s"}, about ${fmtTime(secs)} of speech` : "0 words";
try { localStorage.setItem("script", $("script").value); } catch {}
updateGo();
});
try { const s = localStorage.getItem("script"); if (s) { $("script").value = s; $("script").dispatchEvent(new Event("input")); } } catch {}
function updateGo() { $("go").disabled = !(state.ready && currentVoice() && $("script").value.trim() && !state.busy); }
/* ------------- generate ------------- */
$("go").addEventListener("click", generate);
$("script").addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "Enter" && !$("go").disabled) generate(); });
async function generate() {
const v = currentVoice();
showError("");
state.busy = true; updateGo();
$("go").textContent = "Generating…";
try {
let job = await api("/api/generate", {
text: $("script").value, voice: { type: v.type, path: v.path }, takes: state.takes,
exaggeration: +$("exag").value, cfg: +$("cfg").value, temperature: +$("temp").value,
pause: +$("pause").value, seed: $("seed").value.trim() || null,
});
const speechSecs = words($("script").value) / 2.6 * job.takes_wanted;
const perSec = state.device === "cpu" ? 5 : 0.6;
$("progress").classList.add("on");
while (job.state === "queued" || job.state === "running") {
const pct = job.pieces ? (job.done_pieces / job.pieces) * 100 : 0;
$("barFill").style.width = `${Math.max(3, pct)}%`;
if (job.state === "queued") {
$("progressText").textContent = job.ahead ? `Waiting for ${job.ahead} earlier request${job.ahead > 1 ? "s" : ""} to finish…` : "Starting…";
} else {
const left = Math.max(0, speechSecs * perSec - (job.elapsed || 0));
$("progressText").textContent = `Take ${job.take} of ${job.takes_wanted}, line ${job.piece} of ${job.chunks}` +
(left > 5 ? `. About ${fmtTime(left)} left.` : ".");
}
await new Promise((r) => setTimeout(r, 1000));
job = await api(`/api/jobs/${job.id}`);
}
if (job.state === "error") throw new Error(job.error);
$("barFill").style.width = "100%";
$("progressText").textContent = `Done in ${fmtTime(job.elapsed || 0)}.`;
renderList($("latestList"), job.results);
$("latest").hidden = false;
$("latest").scrollIntoView({ behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", block: "start" });
loadHistory();
} catch (e) {
showError(e.message);
$("progress").classList.remove("on");
} finally {
state.busy = false; $("go").textContent = "Generate takes"; updateGo();
}
}
function showError(msg) { $("errorBox").textContent = msg; $("errorBox").classList.toggle("on", !!msg); }
/* ------------- takes list ------------- */
function renderList(container, items, emptyText) {
container.innerHTML = "";
if (!items.length) { container.innerHTML = `<p class="empty">${emptyText || "Nothing here yet."}</p>`; return; }
items.forEach((it) => container.appendChild(takeRow(it)));
}
function takeRow(it) {
const row = document.createElement("div");
row.className = "take" + (it.approved ? " is-approved" : "");
const src = "/files/" + encodeURI(it.file);
const when = it.created ? new Date(it.created).toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "";
row.innerHTML = `
<button class="play" aria-label="Play">${PLAY}</button>
<div>
<p class="text"></p>
<div class="wave"><canvas></canvas></div>
<div class="meta"></div>
</div>
<div class="acts">
<button class="btn approve"></button>
<a class="btn" href="${src}?download=1" download>Download</a>
<button class="btn discard" type="button">Discard</button>
</div>`;
row.querySelector(".text").textContent = it.text;
const meta = row.querySelector(".meta");
[it.of_takes > 1 ? `Take ${it.take} of ${it.of_takes}` : null, it.seconds ? `${it.seconds}s` : null,
it.voice, `Take number ${it.seed}`, when].filter(Boolean).forEach((t) => {
const s = document.createElement("span"); s.textContent = t; meta.appendChild(s);
});
const audio = new Audio(src); audio.preload = "none";
const playBtn = row.querySelector(".play");
const canvas = row.querySelector("canvas");
let peaks = null;
const draw = () => drawWave(canvas, peaks, audio.duration ? audio.currentTime / audio.duration : 0, it.approved);
fetchPeaks(src).then((p) => { peaks = p; draw(); }).catch(() => {});
new ResizeObserver(draw).observe(canvas);
audio.addEventListener("timeupdate", draw);
audio.addEventListener("ended", () => { setPlaying(playBtn, false); draw(); });
playBtn.addEventListener("click", () => {
if (state.playing && state.playing.audio !== audio) { state.playing.audio.pause(); setPlaying(state.playing.btn, false); }
if (audio.paused) { audio.play(); setPlaying(playBtn, true); state.playing = { audio, btn: playBtn }; }
else { audio.pause(); setPlaying(playBtn, false); }
});
row.querySelector(".wave").addEventListener("click", (e) => {
const r = canvas.getBoundingClientRect();
const go = () => { audio.currentTime = ((e.clientX - r.left) / r.width) * audio.duration; draw(); };
if (isNaN(audio.duration)) { audio.addEventListener("loadedmetadata", go, { once: true }); audio.load(); } else go();
});
const ap = row.querySelector(".approve");
const setAp = () => { ap.textContent = it.approved ? "Approved" : "Approve"; ap.classList.toggle("approved", it.approved);
ap.setAttribute("aria-pressed", it.approved); row.classList.toggle("is-approved", it.approved); draw(); };
setAp();
row.dataset.file = it.file;
row.syncApproved = (v) => { it.approved = v; setAp(); };
ap.addEventListener("click", async () => {
try {
const r = await api("/api/approve", { file: it.file, approved: !it.approved });
it.approved = r.approved; setAp();
// keep the same take in the other list in sync
if (row.parentElement && row.parentElement.id !== "historyList") loadHistory();
else if (state.tab === "approved") loadHistory();
document.querySelectorAll("#latestList .take").forEach((el) => { if (el !== row && el.dataset.file === it.file) el.syncApproved(it.approved); });
}
catch (e) { showError(e.message); }
});
const discardBtn = row.querySelector(".discard");
discardBtn.setAttribute("aria-label", `Discard take ${it.name}`);
discardBtn.addEventListener("click", async () => {
if (!window.confirm(`Permanently delete "${it.name}" and its Studio metadata? This cannot be undone.`)) return;
discardBtn.disabled = true;
try {
await api("/api/discard", { file: it.file });
audio.pause();
if (state.playing?.audio === audio) state.playing = null;
peakCache.delete(src);
row.remove();
for (const list of [$("latestList"), $("historyList")]) {
if (list && !list.querySelector(".take")) {
const emptyText = list.id === "historyList" && state.tab === "approved"
? "No approved takes yet. Mark a take approved when it is ready to use."
: "Nothing here yet.";
list.innerHTML = `<p class="empty">${emptyText}</p>`;
}
}
await loadHistory();
} catch (e) {
discardBtn.disabled = false;
showError(e.message);
}
});
return row;
}
function setPlaying(btn, on) { btn.innerHTML = on ? PAUSE : PLAY; btn.classList.toggle("on", on); btn.setAttribute("aria-label", on ? "Pause" : "Play"); }
const peakCache = new Map();
let audioCtx;
async function fetchPeaks(src) {
if (peakCache.has(src)) return peakCache.get(src);
audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();
const buf = await (await fetch(src)).arrayBuffer();
const data = (await audioCtx.decodeAudioData(buf)).getChannelData(0);
const n = 400, step = Math.floor(data.length / n) || 1, peaks = [];
for (let i = 0; i < n; i++) {
let m = 0; for (let j = i * step; j < Math.min(data.length, (i + 1) * step); j++) m = Math.max(m, Math.abs(data[j]));
peaks.push(m);
}
const max = Math.max(...peaks, 0.01);
const norm = peaks.map((p) => p / max);
peakCache.set(src, norm); return norm;
}
function drawWave(canvas, peaks, progress, approved) {
const dpr = window.devicePixelRatio || 1, w = canvas.clientWidth, h = canvas.clientHeight;
if (!w) return;
canvas.width = w * dpr; canvas.height = h * dpr;
const ctx = canvas.getContext("2d"); ctx.scale(dpr, dpr); ctx.clearRect(0, 0, w, h);
const bar = 3, gap = 2, n = Math.floor(w / (bar + gap));
const played = approved ? cssVar("--amber-deep") : cssVar("--moss");
const rest = approved ? cssVar("--amber") : cssVar("--wave");
for (let i = 0; i < n; i++) {
const p = peaks ? peaks[Math.floor((i / n) * peaks.length)] : 0.08;
const bh = Math.max(3, p * (h - 6));
ctx.fillStyle = i / n < progress ? played : rest;
const x = i * (bar + gap), y = (h - bh) / 2;
ctx.beginPath(); (ctx.roundRect ? ctx.roundRect(x, y, bar, bh, 1.5) : ctx.rect(x, y, bar, bh)); ctx.fill();
}
}
/* ------------- library ------------- */
document.querySelectorAll(".tabs button").forEach((b) => b.addEventListener("click", () => {
state.tab = b.dataset.tab;
document.querySelectorAll(".tabs button").forEach((x) => x.setAttribute("aria-selected", x === b));
loadHistory();
}));
async function loadHistory() {
try {
const h = await api("/api/history" + (state.tab === "approved" ? "?approved=1" : ""));
renderList($("historyList"), h.items, state.tab === "approved"
? "No approved takes yet. Mark a take approved when it is ready to use."
: "Nothing generated yet. Write a script above and generate your first takes.");
} catch (e) { $("historyList").innerHTML = ""; showError(e.message); }
}
pollStatus(); loadVoices(); loadHistory(); loadPeople().then(async () => {
await loadRebuildOptions();
await refreshPersonMedia();
}).catch((e) => {
$("rebuildError").textContent = e.message;
$("rebuildError").hidden = false;
});
</script>
</body>
</html> |