Spaces:
Sleeping
Sleeping
File size: 46,371 Bytes
0990e16 b026827 0990e16 40bb061 0990e16 b026827 40bb061 cf04566 b026827 24f90ad 0990e16 b026827 0990e16 b026827 2375d6a 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 c69ca19 0990e16 2375d6a 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 24f90ad 40bb061 b026827 24f90ad b026827 24f90ad 40bb061 b026827 cf04566 b026827 40bb061 24f90ad c69ca19 24f90ad c69ca19 24f90ad b026827 40bb061 b026827 40bb061 b026827 24f90ad b026827 24f90ad b026827 40bb061 b026827 40bb061 b026827 24f90ad b026827 24f90ad b026827 24f90ad b026827 24f90ad 40bb061 b026827 24f90ad 469acad 0990e16 b026827 469acad b026827 469acad b026827 24f90ad b026827 469acad b026827 469acad 24f90ad 0990e16 b026827 0990e16 24f90ad b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 b026827 0990e16 2375d6a b026827 24f90ad 0990e16 b026827 0990e16 b026827 0990e16 2375d6a 0990e16 534e812 40bb061 5636c50 3b19377 f8d9c90 63559db 0990e16 2375d6a 0990e16 2375d6a 0990e16 5636c50 0990e16 2375d6a 0990e16 a60fe8e 5636c50 984fa0e 63559db 0990e16 24f90ad 0990e16 24f90ad 0990e16 2375d6a a60fe8e 2375d6a 0990e16 3b19377 984fa0e f8d9c90 77a5a1b 2375d6a 77a5a1b a60fe8e 77a5a1b a60fe8e 2375d6a 77a5a1b a60fe8e 77a5a1b a60fe8e 77a5a1b a60fe8e 2375d6a 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b a60fe8e 5808c79 a60fe8e 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b 5808c79 77a5a1b a60fe8e 2375d6a a60fe8e 2375d6a a60fe8e 2375d6a a60fe8e 2375d6a a60fe8e 2375d6a a60fe8e 2375d6a a60fe8e 77a5a1b 2375d6a 77a5a1b 2375d6a a60fe8e 2375d6a 77a5a1b 2375d6a a60fe8e 2375d6a a60fe8e 2375d6a 77a5a1b a60fe8e 2375d6a a60fe8e 2375d6a 77a5a1b 2375d6a 77a5a1b a60fe8e 2375d6a 5808c79 2375d6a 5808c79 77a5a1b 5808c79 77a5a1b a60fe8e 2375d6a 63559db 0990e16 5636c50 0990e16 24f90ad 0990e16 | 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 | 'use strict';
/* โโ tiny DOM helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
const $ = (sel, el = document) => el.querySelector(sel);
const $$ = (sel, el = document) => Array.from(el.querySelectorAll(sel));
const _post = (url, body) => fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then(async r => {
if (!r.ok) {
const j = await r.json().catch(() => ({ detail: r.statusText }));
throw new Error(j.detail || `HTTP ${r.status}`);
}
return r.json();
});
const API = {
meta: () => fetch('/api/meta').then(r => r.json()),
tensions: () => fetch('/api/tensions').then(r => r.json()),
rules: () => fetch('/api/rules').then(r => r.json()),
generate: (body) => _post('/api/generate', body),
productFromPrompt: (body) => _post('/api/products/from_prompt', body),
tensionFromPrompt: (body) => _post('/api/tensions/from_prompt', body),
};
/* โโ Persona presets โ bright, varied, ad-friendly โโโโโโโโโโโ */
const PERSONA_PRESETS = {
newbie: '์ฒซ ์ถ๊ทผํ๋ 25์ธ ์ ์
์ฌ์, ๋๊ทผ๊ฑฐ๋ฆผ๊ณผ ์ค๋ ',
family: '35์ธ ๋ถ๋ชจ, ์์ด์ ํจ๊ปํ๋ ๋ฐ๋ปํ ์ฃผ๋ง ์ผ์',
student: '20์ธ ๋ํ์, ์น๊ตฌ๋ค๊ณผ ๋์ ํ๋ ์ ํ๊ธฐ ์ฒซ ์ฃผ',
couple: '์ ํผ๋ถ๋ถ, ์ ์ง์์ ํจ๊ป ๋ง๋๋ ์ฒซ ์์นจ',
friends: '์น๊ตฌ 4๋ช
, ์ค๋๋ง์ ๋ชจ์ธ ์ฅ์ ํํฐ์ ํ๊ธฐ',
solo: '40๋ 1์ธ ๊ฐ๊ตฌ, ํผ์๋ง์ ํ์จํ ์ ๋
๋ฃจํด',
travel: '28์ธ ์ง์ฅ์ธ, ์ฒซ ํด์ธ ์ฌํ ๊ณตํญ ๊ฒ์ดํธ์ ๋๊ทผ๊ฑฐ๋ฆผ',
senior: '60๋ ์ด๋ฅด์ , ๋งค์ผ ๋๋ค์์ ๋ฐ๊ฒฌํ๋ ์์ ๊ธฐ์จ',
parent_baby: '30๋ ์ ์์ ๋ถ๋ชจ, ์ฒซ ์๊ธฐ์์ ๋ฐ๋ปํ ์๋ฒฝ',
entrepreneur: '32์ธ ์ฐฝ์
๊ฐ, ์ฒซ ๋งค์ถ์ ํํฌ์ ๋ค์ ๋์ ',
hobby: '์ทจ๋ฏธ๋ฅผ ์์ํ 45์ธ, ์ฒ์ ๋ง๋ ์ํ ์์ ๋ฏธ์',
reunion: '10๋
๋ง์ ์ฌํํ ๋์ฐฝ๋ค, ๋ค์ ๋ง๋ ๋ฐ๊ฐ์',
};
/* โโ Preset prompt strings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
const PROMPT_PRESETS = {
watch: '์๋ ๋ก๊ทธ ์๋ชฉ์๊ณ AETHER-A ยท ์ฉ๋, ์ด์นจ, ์ฌํ์ด์ด ํฌ๋ฆฌ์คํ, ๋ฐฉ์, ๊ฐ์ฃฝ ์คํธ๋ฉ',
coffee: '์์ ๋ก์คํ
์๋ ์ปคํผ NOVA-Bean ยท ์๋, ๊ทธ๋ผ์ธ๋, ํํฐ, ์ถ์ถ์, ์ธ๋ผ๋ฏน ์',
phone: '์ค๋งํธํฐ AETHER-Phone ยท OLED ๋์คํ๋ ์ด, ํธ๋ฆฌํ ์นด๋ฉ๋ผ, ๋ฐฐํฐ๋ฆฌ, AI ์นฉ์
, ์ง๋๋ชจํฐ',
sneaker: '๋ฌ๋ํ PULSE-Run ยท ๋ฏธ๋์ ํผ, ์์์ ๊ณ ๋ฌด, ๋ํธ ์ดํผ, ๋ ์ด์ค, TPU ๋ค๊ฟ์น์ปต',
beer: '์์ IPA ๋งฅ์ฃผ HOP-Haru ยท ๊ฐ์ ๋ณ, ํฌ๋ผ์ด ์บก, ํค๋ ๊ฑฐํ, ๋ผ๋ฒจ, ํ',
cosmetic: '์คํจ์ผ์ด ์ฐํ GLOW-Han ยท ์ ๋ฆฌ ์คํฌ์ด๋, ๊ฐ์ ์์ธ์ ๋ณ, ์ธ๋ผ, ํ๋ฐฉ ํ๋ธ ํฅ, ํ์ง ๋ฐ์ค',
car: '์ ๊ธฐ์ฐจ SPIRA-EV ยท ๋ฐ๋ฅ ๋ฐฐํฐ๋ฆฌํฉ, ๋์ผ ๋ง๊ทธ๋ท ๋ชจํฐ, 17์ธ์น ์คํฌ๋ฆฐ, ์ํฌ ํธ๋ค, 800V ์ถฉ์ ํฌํธ',
laundry: 'O2O ํ๋ฆฌ๋ฏธ์ ์ธํ ์๋น์ค MOON-Fold ยท ์๊ฑฐ๊ธฐ์ฌ, ์ฑ ์ค์๊ฐ ์๋ฆผ, ๋น๋ ์ปค๋ฒ, ํฅ๊ธฐ ์บก์, ์ท๊ฑธ์ด',
edu: '์จ๋ผ์ธ ์ฝ๋ฉ ๋ถํธ์บ ํ CODE-Muze ยท ์์ ๊ฐ์, ๊ณผ์ ํผ๋๋ฐฑ, 1:1 ์ฝ๋๋ฆฌ๋ทฐ, ์ฌ๋ ๋ฐฉ, ์๋ฃ์ฆ',
banking: '๋ชจ๋ฐ์ผ ์ํ ์ฑ HANA-Flow ยท ํ ํ๋ฉด ์์ ฏ, ์ก๊ธ ๋ฒํผ, ์์ฒด ์ธ์ฆ, ์๋ฆผ ๋ฐฐ๋, ์ฑ๋ด',
};
/* โโ State โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
let TENSIONS = [];
let CHARTS = [];
let PIPELINE_TIMER = null;
let CURRENT_PRODUCT = null; // {product_id, brand, category, atoms, ...}
let LAST_PRODUCT_PROMPT = null;
let CURRENT_TENSION = null; // {id, name, greimas_square, emotional_payoff, description}
let LAST_TENSION_KEY = null; // string โ either preset id or "custom:<prompt>"
let LATEST_RESULTS = null; // raw /api/generate result โ for media handlers
let HAS_FAL = false; // set from /api/meta
const MEDIA_STATE = {}; // MEDIA_STATE[seedIdx][beatIdx] = {image_url?, video_url?, status, message}
/* โโ Boot โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
document.addEventListener('DOMContentLoaded', () => {
try {
wireInputs();
} catch (e) {
console.error('wireInputs failed:', e);
showGlobalError(`์ด๊ธฐํ ์คํจ: ${e.message || e}. ๋ธ๋ผ์ฐ์ ๋ฅผ ํ๋ ๋ฆฌํ๋ ์ํ์ธ์ (Ctrl+Shift+R).`);
}
Promise.all([loadMeta(), loadTensions(), loadRules()]).catch(e => {
console.error('initial loads failed:', e);
});
});
async function loadMeta() {
try {
const m = await API.meta();
const vEl = $('#version'); if (vEl) vEl.textContent = m.version;
const sel = $('#backendSel');
if (!sel) return;
sel.querySelectorAll('option').forEach(o => {
if (o.value === 'claude' && !m.has_anthropic_key) {
o.disabled = true; o.textContent += ' (no key)';
}
if (o.value === 'fireworks' && !m.has_fireworks_key) {
o.disabled = true; o.textContent += ' (no key)';
}
if (o.value === 'hf' && !m.has_hf_token) {
o.disabled = true; o.textContent += ' (no token)';
}
});
sel.value = m.default_backend || 'claude';
HAS_FAL = !!m.has_fal_key;
syncBackendPlaceholder();
} catch (e) { console.error('meta failed', e); }
}
async function loadTensions() {
TENSIONS = await API.tensions();
// Auto-select first tension as default without requiring user action
if (!CURRENT_TENSION && TENSIONS.length > 0) {
setTension(TENSIONS[0], TENSIONS[0].id);
}
}
async function loadRules() {
const rules = await API.rules();
const rows = [
`<div class="rule-row header">
<div>rule_id</div><div>name</div><div>pattern</div><div>theoretical_anchor</div>
</div>`,
];
rules.forEach(r => {
rows.push(`
<div class="rule-row">
<div class="rule-id">${r.rule_id}</div>
<div><strong>${escapeHtml(r.name)}</strong></div>
<div>${escapeHtml(r.pattern)}</div>
<div class="rule-anchor">${escapeHtml(r.theoretical_anchor)}</div>
</div>`);
});
const tbl = $('#rulesTable');
if (tbl) tbl.innerHTML = rows.join('');
}
/* โโ Wire up inputs defensively โ any single null never breaks the rest โ */
function wireInputs() {
safeOn('#nSeeds', 'input', e => {
const out = $('#nSeedsVal'); if (out) out.textContent = e.target.value;
});
safeOn('#topK', 'input', e => {
const out = $('#topKVal'); if (out) out.textContent = e.target.value;
});
safeOn('#backendSel', 'change', syncBackendPlaceholder);
safeOn('#genBtn', 'click', runGenerate);
safeOn('#productPrompt', 'input', () => {
if (!$('#productPrompt')) return;
if ($('#productPrompt').value.trim() !== LAST_PRODUCT_PROMPT) {
setStatus('#productStatus', 'idle', 'Generate๋ฅผ ๋๋ฅด๋ฉด Kimi-K2P6๊ฐ genome์ ํ์ฅํฉ๋๋ค.');
}
});
safeOn('#tensionPrompt', 'input', () => {
const val = $('#tensionPrompt').value.trim();
if (!val) {
setStatus('#tensionStatus', 'idle', 'ํ๋ฆฌ์
์ ํด๋ฆญํ๊ฑฐ๋ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ธ์.');
return;
}
const key = 'custom:' + val;
if (key !== LAST_TENSION_KEY) {
setStatus('#tensionStatus', 'idle', 'Generate ์ ์์ ์
๋ ฅ์ Greimas ์ฌ๊ฐํ์ผ๋ก ํ์ฅํฉ๋๋ค.');
// Clear current tension preview until expanded
if (CURRENT_TENSION && LAST_TENSION_KEY && LAST_TENSION_KEY.startsWith('custom:')) {
hideGreimasPreview();
}
}
});
$$('.product-presets .preset-chip-inline').forEach(btn => {
btn.addEventListener('click', () => {
const key = btn.dataset.preset;
const val = PROMPT_PRESETS[key];
const ta = $('#productPrompt');
if (val && ta) {
ta.value = val;
ta.dispatchEvent(new Event('input'));
ta.focus();
}
});
});
$$('.tension-presets .preset-chip-inline').forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.dataset.tension;
const t = TENSIONS.find(x => x.id === id);
if (!t) return;
// Clear the textarea so the preset takes priority
const ta = $('#tensionPrompt'); if (ta) ta.value = '';
setTension(t, id);
});
});
$$('.persona-presets .preset-chip-inline').forEach(btn => {
btn.addEventListener('click', () => {
const key = btn.dataset.persona;
const val = PERSONA_PRESETS[key];
const ta = $('#personaIn');
if (val && ta) { ta.value = val; ta.focus(); }
});
});
}
function safeOn(selector, ev, handler) {
const el = $(selector);
if (!el) { console.warn('element missing:', selector); return; }
el.addEventListener(ev, handler);
}
function syncBackendPlaceholder() {
const v = $('#backendSel') ? $('#backendSel').value : 'claude';
const placeholders = {
claude: 'claude-sonnet-4-6',
fireworks: 'accounts/fireworks/models/kimi-k2p6',
hf: 'Qwen/Qwen2.5-72B-Instruct',
none: '(not used)',
};
if ($('#modelIn')) $('#modelIn').placeholder = placeholders[v] || '';
}
/* โโ Tension handling โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
function setTension(t, key) {
CURRENT_TENSION = t;
LAST_TENSION_KEY = key;
renderGreimasPreview(t);
setStatus('#tensionStatus', 'ready',
`โ <strong>${escapeHtml(t.name)}</strong> ยท ${escapeHtml(t.emotional_payoff || '')}`);
}
function renderGreimasPreview(t) {
if (!t || !t.greimas_square) return;
const sq = t.greimas_square;
const preview = $('#tensionPreview');
if (preview) preview.hidden = false;
if ($('[data-pos="s1"]')) $('[data-pos="s1"]').textContent = sq.S1;
if ($('[data-pos="s2"]')) $('[data-pos="s2"]').textContent = sq.S2;
if ($('[data-pos="ns1"]')) $('[data-pos="ns1"]').textContent = sq.not_S1;
if ($('[data-pos="ns2"]')) $('[data-pos="ns2"]').textContent = sq.not_S2;
const payoff = $('#tensionPayoff');
if (payoff) {
payoff.innerHTML =
`${escapeHtml(t.description || '')}<br/><strong>payoff:</strong> ${escapeHtml(t.emotional_payoff || '')}`;
}
}
function hideGreimasPreview() {
const preview = $('#tensionPreview');
if (preview) preview.hidden = true;
}
async function ensureTensionReady() {
const customText = $('#tensionPrompt') ? $('#tensionPrompt').value.trim() : '';
// Priority: if user typed custom text, use it (overrides any preset)
if (customText) {
const key = 'custom:' + customText;
if (CURRENT_TENSION && LAST_TENSION_KEY === key) return CURRENT_TENSION;
const backend = $('#backendSel').value === 'none' ? 'fireworks' : $('#backendSel').value;
setStatus('#tensionStatus', 'loading', '๐งฌ Kimi-K2P6๊ฐ Greimas ์ฌ๊ฐํ์ผ๋ก ํ์ฅ ์คโฆ (10~20์ด)');
try {
const t = await API.tensionFromPrompt({ prompt: customText, backend });
setTension(t, key);
return t;
} catch (e) {
setStatus('#tensionStatus', 'error', `โ ${escapeHtml(e.message || String(e))}`);
throw e;
}
}
if (CURRENT_TENSION) return CURRENT_TENSION;
throw new Error('๊ธด์ฅ ์ํฉ์ ์ ํํ๊ฑฐ๋ ์
๋ ฅํ์ธ์.');
}
/* โโ Product handling โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
async function ensureProductReady() {
const text = $('#productPrompt') ? $('#productPrompt').value.trim() : '';
if (!text) throw new Error('์ ํ ๋๋ ์๋น์ค ์ค๋ช
์ ์
๋ ฅํ์ธ์.');
if (CURRENT_PRODUCT && LAST_PRODUCT_PROMPT === text) return CURRENT_PRODUCT;
const backend = $('#backendSel').value === 'none' ? 'fireworks' : $('#backendSel').value;
setStatus('#productStatus', 'loading', '๐งฌ Kimi-K2P6๊ฐ genome์ ํ์ฅ ์คโฆ (30~60์ด)');
try {
const product = await API.productFromPrompt({ prompt: text, backend });
CURRENT_PRODUCT = product;
LAST_PRODUCT_PROMPT = text;
const atoms = (product.atoms || []).map(a => a.name).join(' ยท ');
setStatus('#productStatus', 'ready',
`โ <strong>${escapeHtml(product.brand)}</strong> ยท ${escapeHtml(product.category)} ยท ${product.atom_count} atoms` +
(atoms ? `<br/><span style="color: var(--text-subtle); font-size: 11px;">${escapeHtml(atoms)}</span>` : '')
);
return product;
} catch (e) {
setStatus('#productStatus', 'error', `โ ${escapeHtml(e.message || String(e))}`);
throw e;
}
}
/* โโ Generate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
async function runGenerate() {
// โโ Synchronous visual feedback FIRST (before any await).
// Without this, user sees NO change for a few ms after click,
// so they think the button is broken.
setRunning(true);
const err = $('#errBox'); if (err) { err.hidden = true; err.textContent = ''; }
const empty = $('#emptyState'); if (empty) empty.style.display = 'none';
animatePipeline();
// Also immediately reflect prep state in the status dots
if (!$('#productPrompt').value.trim()) {
// Nothing to expand โ will fail validation below, but show prep status anyway
setStatus('#productStatus', 'loading', 'โณ ์
๋ ฅ ํ์ธ ์คโฆ');
} else if (!CURRENT_PRODUCT || LAST_PRODUCT_PROMPT !== $('#productPrompt').value.trim()) {
setStatus('#productStatus', 'loading', '๐งฌ genome ํ์ฅ ์ค๋น ์คโฆ');
}
if ($('#tensionPrompt').value.trim() &&
(LAST_TENSION_KEY !== 'custom:' + $('#tensionPrompt').value.trim())) {
setStatus('#tensionStatus', 'loading', '๐งฌ Greimas ์ฌ๊ฐํ ์ค๋น ์คโฆ');
}
let tension, product;
try {
tension = await ensureTensionReady();
} catch (e) {
resetPipeline();
showGlobalError(`โ ${e.message || e}`);
setRunning(false);
if ($('#summaryBar') && $('#summaryBar').hidden && empty) empty.style.display = '';
return;
}
try {
product = await ensureProductReady();
} catch (e) {
resetPipeline();
showGlobalError(`โ ${e.message || e}`);
setRunning(false);
if ($('#summaryBar') && $('#summaryBar').hidden && empty) empty.style.display = '';
return;
}
const durInput = $$('input[name="duration"]').find(r => r.checked);
const body = {
product_id: product.product_id,
tension_id: tension.id,
persona: ($('#personaIn') && $('#personaIn').value.trim()) || '์ผ๋ฐ ์๋น์',
duration: durInput ? parseInt(durInput.value, 10) : 15,
n_seeds: $('#nSeeds') ? parseInt($('#nSeeds').value, 10) : 5,
top_k: $('#topK') ? parseInt($('#topK').value, 10) : 3,
backend: $('#backendSel').value,
model: ($('#modelIn') && $('#modelIn').value.trim()) || null,
rng_seed: $('#rngSeed') ? parseInt($('#rngSeed').value || '42', 10) : 42,
};
try {
const r = await API.generate(body);
completePipeline();
renderResults(r);
} catch (e) {
resetPipeline();
const msg = e && e.message ? e.message : String(e);
showGlobalError(`โ ${msg}`);
if ($('#summaryBar') && $('#summaryBar').hidden && empty) empty.style.display = '';
console.error(e);
} finally {
setRunning(false);
}
}
function showGlobalError(msg) {
const box = $('#errBox');
if (box) { box.hidden = false; box.textContent = msg; }
else { alert(msg); }
}
function setStatus(sel, kind, html) {
const box = $(sel);
if (!box) return;
const dot = box.querySelector('.status-dot');
const text = box.querySelector('.status-text');
if (dot) dot.className = `status-dot status-${kind}`;
if (text) text.innerHTML = html;
}
function setRunning(running) {
const btn = $('#genBtn'); if (!btn) return;
btn.disabled = running;
const spin = btn.querySelector('.btn-spinner');
const lbl = btn.querySelector('.btn-label');
if (spin) spin.hidden = !running;
if (lbl) lbl.textContent = running ? '์์ฑ ์คโฆ' : 'โก Generate';
}
/* โโ Pipeline animation โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
function animatePipeline() {
resetPipeline();
const stages = ['corpus', 'encoding', 'incubation', 'emergence', 'filtering'];
let i = 0;
const tick = () => {
if (i > 0) {
const prev = document.querySelector(`.stage[data-stage="${stages[i-1]}"]`);
if (prev) { prev.classList.remove('active'); prev.classList.add('done'); }
}
if (i < stages.length) {
const cur = document.querySelector(`.stage[data-stage="${stages[i]}"]`);
if (cur) cur.classList.add('active');
i++;
PIPELINE_TIMER = setTimeout(tick, 1200);
}
};
tick();
}
function completePipeline() {
if (PIPELINE_TIMER) { clearTimeout(PIPELINE_TIMER); PIPELINE_TIMER = null; }
$$('.stage').forEach(s => { s.classList.remove('active'); s.classList.add('done'); });
}
function resetPipeline() {
if (PIPELINE_TIMER) { clearTimeout(PIPELINE_TIMER); PIPELINE_TIMER = null; }
$$('.stage').forEach(s => s.classList.remove('active', 'done'));
}
/* โโ Render results โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
function renderResults(data) {
LATEST_RESULTS = data;
// Reset media state for a fresh run
Object.keys(MEDIA_STATE).forEach(k => { delete MEDIA_STATE[k]; });
const bar = $('#summaryBar'); if (bar) bar.hidden = false;
if ($('#sumCount')) $('#sumCount').textContent = data.summary.count;
if ($('#sumAvg')) $('#sumAvg').textContent = (data.summary.avg_final || 0).toFixed(3);
if ($('#sumTop')) $('#sumTop').textContent = (data.summary.top_final || 0).toFixed(3);
if ($('#sumBackend')) $('#sumBackend').textContent =
data.summary.backend +
(data.summary.model ? ' ยท ' + data.summary.model.split('/').pop() : '');
CHARTS.forEach(c => { try { c.destroy(); } catch(_){} });
CHARTS = [];
const box = $('#seedsBox'); if (!box) return;
box.innerHTML = '';
data.seeds.forEach((s, idx) => {
box.appendChild(renderSeedCard(s, idx + 1));
});
// Kick off the fal.ai auto-chain for the top 3 seeds' first beat
if (HAS_FAL) {
autoMediaChain(data.seeds);
} else {
showFalMissingBanner();
}
}
function showFalMissingBanner() {
// soft notice at top of seeds list
const box = $('#seedsBox'); if (!box) return;
const notice = document.createElement('div');
notice.className = 'err';
notice.style.marginBottom = '12px';
notice.textContent = 'โ ๏ธ FAL_KEY ๋ฏธ์ค์ โ ์ด๋ฏธ์ง/๋น๋์ค ์์ฑ์ด ๋นํ์ฑ๋ฉ๋๋ค (Settings โ Secrets โ FAL_KEY).';
box.prepend(notice);
}
function renderSeedCard(s, rank) {
const seed = s.seed;
const score = s.score;
const final = score.final;
const color = final >= 0.5 ? '#10b981' : final >= 0.3 ? '#f59e0b' : '#ef4444';
const R = 34, CIRC = 2 * Math.PI * R;
const offset = CIRC * (1 - Math.max(0, Math.min(1, final)));
const card = document.createElement('div');
card.className = 'seed-card';
card.innerHTML = `
<div class="seed-head">
<div class="seed-rank-block">
<span class="seed-rank-label">Rank</span>
<div class="seed-rank">#${rank}</div>
</div>
<div class="seed-info">
<div class="seed-id">${escapeHtml(seed.seed_id)}</div>
<div class="seed-rules">
${seed.rules_applied.map(r => `<span class="rule-pill">${escapeHtml(r)}</span>`).join('')}
</div>
</div>
<div class="final-gauge" title="final score">
<svg viewBox="0 0 80 80">
<circle class="final-gauge-track" cx="40" cy="40" r="${R}"/>
<circle class="final-gauge-fill" cx="40" cy="40" r="${R}"
stroke="${color}"
stroke-dasharray="${CIRC}"
stroke-dashoffset="${offset}"/>
</svg>
<div class="final-gauge-text">
<div>
<div class="final-gauge-value">${final.toFixed(2)}</div>
<div class="final-gauge-label">final</div>
</div>
</div>
</div>
</div>
${seed.scene_summary ? `
<div class="scene-summary">
<span class="scene-summary-badge">๐ ํ ์ค ์์ฝ</span>
<span class="scene-summary-text">${escapeHtml(seed.scene_summary)}</span>
</div>` : ''}
${seed.wow_anchor ? `<div class="seed-anchor">${escapeHtml(seed.wow_anchor)}</div>` : ''}
${renderTournament(seed.tournament)}
${renderConstraints(seed.creative_constraints)}
<div class="seed-section-title">Concept</div>
<div class="seed-concept">${escapeHtml(seed.concept)}</div>
<div class="seed-section-title">Pixar Story Spine ยท ${seed.duration}s ยท ${seed.beats.length} beats</div>
<div class="timeline">
<div class="timeline-bar">${renderBeatBar(seed.beats, seed.duration)}</div>
<div class="timeline-scale">${renderTicks(seed.duration)}</div>
</div>
<div class="seed-section-title">Beats ยท ์ด๋ฏธ์ง/๋น๋์ค</div>
<div class="beats-detail">
${seed.beats.map((b, bi) => `
<div class="beat-row">
<div class="beat-row-time">${b.time_range[0]}โ${b.time_range[1]}s</div>
<div class="beat-row-name">${escapeHtml(b.beat)}</div>
<div class="beat-row-content">${escapeHtml(b.content || 'โ')}</div>
<div class="beat-media" data-media="${rank - 1}-${bi}"></div>
</div>
`).join('')}
</div>
<div data-stitch-host="${rank - 1}"></div>
<div class="aether-provenance" title="AETHER 5-์์ฑ์๊ฐ ๋ด๋ถ์์ ์๋ก๋ฅผ ์์ยท์๊ทน์ผ๋ก ์กฐ์จํ์ฌ ์ด ํ๋์ ์ฅ๋ฉด์ ํฉ์ฑํ์ต๋๋ค.">
โ๏ธ AETHER 5-์์ฑ์ ๋ฉํ์ธ์ง: ๆจ(์จ์) โ ็ซ(์ฆํญ) โ ๅ(์ง๋ฐ) โ ้(ํธ์ง) โ ๆฐด(ํตํฉ)
</div>
${renderAetherCritique(seed.aether_critique)}
${renderRawDetails(seed)}
<div class="scores-section">
<div class="radar-wrap"><canvas></canvas></div>
<div class="scores-table">
${scoreItem('Novelty', score.novelty)}
${scoreItem('Utility', score.utility)}
${scoreItem('Affect', score.affect)}
${scoreItem('Humor/Pathos', score.humor_or_pathos)}
${scoreItem('Surprise', score.surprise)}
${scoreItem('Risk', score.risk, { risk: true })}
${scoreItem('Gating', (score.gating_passed || 0) + '/5', { raw: true })}
${scoreItem('Final', score.final, { bold: true })}
</div>
</div>
`;
const canvas = $('canvas', card);
const chart = new Chart(canvas.getContext('2d'), {
type: 'radar',
data: {
labels: ['Novelty', 'Utility', 'Affect', 'Humor/Pathos', 'Surprise'],
datasets: [{
data: [
score.novelty, score.utility, score.affect,
score.humor_or_pathos, score.surprise,
],
backgroundColor: 'rgba(79, 70, 229, 0.18)',
borderColor: '#4f46e5',
borderWidth: 2,
pointBackgroundColor: '#4f46e5',
pointBorderColor: '#ffffff',
pointRadius: 3,
}],
},
options: {
responsive: true, maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
r: {
suggestedMin: 0, suggestedMax: 1,
ticks: { display: false, stepSize: 0.25 },
grid: { color: '#e6e9f0' },
angleLines: { color: '#e6e9f0' },
pointLabels: { font: { size: 10, weight: '600' }, color: '#475569' },
},
},
},
});
CHARTS.push(chart);
// Initialize media slots AFTER DOM insertion โ queued as a microtask so
// the card is already in the tree when we query data-media attributes.
queueMicrotask(() => {
seed.beats.forEach((_, bi) => renderMediaSlot(rank - 1, bi));
renderStitchSection(rank - 1);
});
return card;
}
function renderTournament(t) {
if (!t || typeof t !== 'object') return '';
const inv = (t.structural_invention || '').trim();
const why = (t.why_winner || '').trim();
const ru = (t.runners_up || '').trim();
if (!inv && !why) return '';
return `
<div class="tournament">
<div class="tournament-head">
<span class="tournament-badge">๐ ํ ๋๋จผํธ ์ฐ์น</span>
<span class="tournament-label">LLM ํ์ฌ๊ฐ ${escapeHtml(t.winner_index !== undefined ? '#' + (Number(t.winner_index) + 1) : '')} ํ๋ณด๋ฅผ ๊ตฌ์กฐ์ ์ฐฝ๋ฐ 1์๋ก ์ ์ </span>
</div>
${inv ? `
<div class="tournament-row">
<span class="tournament-key">๊ตฌ์กฐ์ ๋ฐ๋ช
</span>
<span class="tournament-val tournament-val-invention">${escapeHtml(inv)}</span>
</div>` : ''}
${why ? `
<div class="tournament-row">
<span class="tournament-key">๊ฒฐ์ ์ ์ด์ </span>
<span class="tournament-val">${escapeHtml(why)}</span>
</div>` : ''}
${ru ? `
<div class="tournament-row">
<span class="tournament-key">์ฐจ์ ์ ์ฝ์ </span>
<span class="tournament-val tournament-val-muted">${escapeHtml(ru)}</span>
</div>` : ''}
</div>
`;
}
function renderAetherCritique(c) {
if (!c || typeof c !== 'object') return '';
const verdict = (c.verdict || 'PASS').toUpperCase();
const isRevise = verdict === 'REVISE';
const verdictBadge = isRevise
? '<span class="critique-verdict critique-verdict-revise">REVISE โ ์ฌ์งํ ์ ์ฉ๋จ</span>'
: '<span class="critique-verdict critique-verdict-pass">PASS โ ์ถ๊ฐ ์์ ์์</span>';
const rows = [
['๐ณ ๆจ ์ง๊ด', c.wood, 'ๆจ (Wood) โ KEY VISUAL์ด 1๋
๋ค์๋ ๊ธฐ์ต๋๋๊ฐ? ํด๋ฆฌ์
ฐ๋?'],
['๐ฅ ็ซ ๊ฐ์ ', c.fire, '็ซ (Fire) โ ์ฒซ 3์ด๊ฐ ์์ ๋ฉ์ถ๊ฒ ํ๋๊ฐ? ์ถ์์ด๋ก ๋๋ง์น ๊ณณ์?'],
['๐ชจ ๅ ๋
ผ๋ฆฌยทํ์ฐ', c.earth, 'ๅ (Earth) โ ๋ค๋ฅธ ๋ธ๋๋๋ก ๋ฐ๊ฟ๋ ์ฑ๋ฆฝํ๋๊ฐ?'],
['โ๏ธ ้ ๋นํยท์ ๋จ', c.metal, '้ (Metal) โ ๊ฐ์ฅ ์ฝํ BEAT + ์ฆ์ ๊ฐํด์ง๋ ๋์.'],
['๐ ๆฐด ํต์ฐฐ', c.water, 'ๆฐด (Water) โ ๋ณด์ง ๋ชปํ ์ง์ค + ํฑ CF์ ๋ฟ์ง ๋ชปํ ๊ฒฐ.'],
].filter(([, v]) => v && v.trim());
if (!rows.length && !c.revision_brief) return '';
const briefBlock = c.revision_brief && c.revision_brief.trim()
? `<div class="critique-brief"><span class="critique-brief-label">์ฌ์งํ ์ง์</span>
<span class="critique-brief-text">${escapeHtml(c.revision_brief)}</span></div>`
: '';
return `
<details class="critique" ${isRevise ? 'open' : ''}>
<summary class="critique-summary">
๐ง AETHER ๋ฉํ์ธ์ง ๋นํ ${verdictBadge}
</summary>
<div class="critique-body">
<div class="critique-grid">
${rows.map(([k, v, tip]) => `
<div class="critique-row" title="${escapeHtml(tip)}">
<span class="critique-key">${k}</span>
<span class="critique-val">${escapeHtml(v)}</span>
</div>`).join('')}
</div>
${briefBlock}
</div>
</details>
`;
}
function renderConstraints(c) {
if (!c) return '';
const rows = [
['๐ฆ ์ค๋ธ์ ', c.object],
['๐ฅ ์นด๋ฉ๋ผ', c.shot],
['๐ ๊ณต๊ฐ๊ฐ', c.synesthesia],
['๐ฌ ์ฅ๋ฅด ์ ํ', c.genre_twist],
['โฑ ์๊ฐ ๊ตฌ์กฐ', c.time],
['๐ ์์ฑ์ด', c.onomatopoeia],
].filter(([, v]) => v);
if (!rows.length) return '';
return `
<div class="constraints">
<div class="constraints-head">์ฐฝ๋ฐ ๊ฐ์ ์กฐ๊ฑด <small>ยท Kimi-K2P6์ ํ๋ ์ฃผ์
๋ ๊ตฌ์ฒด ์ ์ฝ</small></div>
<div class="constraints-grid">
${rows.map(([k, v]) => `
<div class="constraint-chip">
<span class="constraint-key">${k}</span>
<span class="constraint-val">${escapeHtml(v)}</span>
</div>`).join('')}
</div>
</div>
`;
}
/* โโ Media (fal.ai images + Bytedance Seedance 2.0 video) โโโโโโโโโโโโโโโโ */
const STITCH_STATE = {}; // legacy; not used by auto chain anymore
const FINAL_VIDEO_STATE = {}; // FINAL_VIDEO_STATE[seedIdx] = {status, video_url, target_seconds, message}
/** Auto-pipeline (top seed only):
* Phase 1 โ generate images for ALL beats with sliding-window ref chain
* Phase 2 โ ONE single i2v call (Seedance 2.0) using the first chained
* image + a combined multi-scene prompt โ one full-spot video
*/
async function autoMediaChain(seeds) {
if (!seeds || !seeds.length) return;
const sIdx = 0;
const beats = seeds[sIdx].seed.beats || [];
if (!beats.length) return;
// Phase 1 โ image chain (same as before)
for (let i = 0; i < beats.length; i++) {
const ok = await _genImageForBeat(sIdx, i, /*useChain*/ true);
if (!ok) break;
}
// Phase 2 โ single full-spot Seedance video
await generateFinalVideo(sIdx);
renderStitchSection(sIdx); // backward-compat: clears any old stitch UI
}
/** Build a single multi-scene prompt that walks Seedance through every beat. */
function buildCombinedScenePrompt(beats) {
const total = beats[beats.length - 1]?.time_range?.[1] || 15;
const lines = [
`๋ค์์ ${total}์ด ๊ธธ์ด์ ์๋ค๋งํฑ ๊ด๊ณ ์์์ด๋ค. ${beats.length}๊ฐ์ ์ฌ์ด ๋ถ๋๋ฝ๊ฒ ์ด์ด์ง๋ค.`,
"๊ฐ ์ฌ์ ๋ช
์๋ ํ์์ฝ๋ ๋์ ์ฐ์ถํ๊ณ , ์ฌ ์ฌ์ด์ ์์ฐ์ค๋ฌ์ด ์ปทยท๋งค์น ์ปทยท๋์กธ๋ธ๋ฅผ ์ฌ์ฉํ๋ค.",
"",
];
beats.forEach((b, i) => {
lines.push(`Scene ${i + 1} (${b.time_range[0]}-${b.time_range[1]}์ด)`);
if (b.content) lines.push(b.content);
lines.push("");
});
lines.push("์ ์ฒด ์์์ ์ํ์ ์ฐ์์ฑ์ ์ ์งํ๋ฉฐ, ์ฒซ ์ปท์ ์ธ๋ฌผยทํ๊ฒฝ์ด ์์ฐ์ค๋ฝ๊ฒ ๋ฐ์ ํ๋ค. ์๋งยทํ
์คํธยท๋ก๊ณ ์ผ์ฒด ์์.");
return lines.join("\n");
}
function _isContentPolicyError(msg) {
const m = String(msg || '').toLowerCase();
return m.includes('content_policy_violation')
|| m.includes('content policy')
|| m.includes('likenesses of real people')
|| m.includes('private information');
}
/** Generate a single full-spot video (Seedance 2.0).
* Anchor = first chained image. If Seedance rejects on content policy,
* automatically retry with the next image in the chain. */
async function generateFinalVideo(sIdx, anchorBeatIdx = 0) {
const seed = LATEST_RESULTS?.seeds?.[sIdx]?.seed;
if (!seed) return;
const beats = seed.beats || [];
if (!beats.length) return;
// Build candidate list (any beat with an image) starting from anchorBeatIdx
const allCandidates = [];
for (let i = 0; i < beats.length; i++) {
const u = MEDIA_STATE[sIdx]?.[i]?.image_url;
if (u) allCandidates.push({ beatIdx: i, url: u });
}
if (!allCandidates.length) {
FINAL_VIDEO_STATE[sIdx] = {
status: 'error',
message: '์ด๋ฏธ์ง๊ฐ ์์ง ์์ฑ๋์ง ์์ ๋น๋์ค๋ฅผ ์์ํ ์ ์์ต๋๋ค.',
};
renderFinalVideoSection(sIdx);
return;
}
// Reorder so anchorBeatIdx comes first, then the rest in beat order
const candidates = [
...allCandidates.filter(c => c.beatIdx === anchorBeatIdx),
...allCandidates.filter(c => c.beatIdx !== anchorBeatIdx),
];
const totalSec = beats[beats.length - 1].time_range[1];
const combinedScene = buildCombinedScenePrompt(beats);
let lastErr = '';
let policyRejections = 0;
for (let attempt = 0; attempt < candidates.length; attempt++) {
const cand = candidates[attempt];
FINAL_VIDEO_STATE[sIdx] = {
status: 'loading',
target_seconds: totalSec,
anchor_beat: cand.beatIdx,
message: attempt === 0
? `๐ฌ Seedance 2.0์ด ${totalSec}์ด ์์ ์์ฑ ์คโฆ (์ต์ปค: ๋นํธ ${cand.beatIdx + 1}, 3~6๋ถ)`
: `โ ๏ธ ์ ์ฑ
๊ฑฐ๋ถ ${policyRejections}ํ โ ๋นํธ ${cand.beatIdx + 1} ์ด๋ฏธ์ง๋ก ์ฌ์๋ ์คโฆ`,
};
renderFinalVideoSection(sIdx);
try {
const r = await fetch('/api/media/video', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
scene: combinedScene,
image_url: cand.url,
duration_seconds: totalSec,
}),
});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
FINAL_VIDEO_STATE[sIdx] = {
status: 'ready',
video_url: data.video_url,
target_seconds: totalSec,
anchor_beat: cand.beatIdx,
policy_retries: policyRejections,
};
renderFinalVideoSection(sIdx);
return;
} catch (e) {
const msg = e.message || String(e);
lastErr = msg;
if (_isContentPolicyError(msg)) {
policyRejections += 1;
continue; // try next candidate
}
// non-policy error: stop, show
FINAL_VIDEO_STATE[sIdx] = {
status: 'error',
target_seconds: totalSec,
message: `๋น๋์ค ์์ฑ ์คํจ: ${msg}`,
};
renderFinalVideoSection(sIdx);
return;
}
}
// All candidates rejected by policy
FINAL_VIDEO_STATE[sIdx] = {
status: 'error',
target_seconds: totalSec,
message: `Seedance๊ฐ ๋ชจ๋ ์ด๋ฏธ์ง๋ฅผ ์ ์ฑ
์ผ๋ก ๊ฑฐ๋ถ (${policyRejections}ํ). `
+ `์ด๋ฏธ์ง๋ฅผ ์ฌ์์ฑํ ๋ค (์ธ๋ฌผ ์ ๋ฉด ํฌํธ๋ ์ดํธ ํํผ) ๋ค์ ์๋ํ์ธ์. ${lastErr.slice(0, 200)}`,
};
renderFinalVideoSection(sIdx);
}
/** Render the single-final-video section at the bottom of the seed card. */
function renderFinalVideoSection(sIdx) {
const host = document.querySelector(`[data-stitch-host="${sIdx}"]`);
if (!host) return;
const seed = LATEST_RESULTS?.seeds?.[sIdx]?.seed;
if (!seed) { host.innerHTML = ''; return; }
const totalSec = seed.beats[seed.beats.length - 1]?.time_range?.[1] || 15;
const st = FINAL_VIDEO_STATE[sIdx] || {};
const beats = seed.beats || [];
const imagesReady = beats.filter((_, i) => MEDIA_STATE[sIdx]?.[i]?.image_url).length;
const html = [];
html.push(`<div class="seed-section-title">๐ฌ ์ต์ข
${totalSec}์ด ๊ด๊ณ ์์ (Bytedance Seedance 2.0)</div>`);
html.push(`<div class="final-stitch">`);
if (st.status === 'loading') {
html.push(`<div class="media-status media-loading">${escapeHtml(st.message)}</div>`);
} else if (st.status === 'error') {
html.push(`<div class="media-status media-error-msg">${escapeHtml(st.message)}</div>`);
}
if (st.video_url) {
const anchorIdx = (typeof st.anchor_beat === 'number') ? st.anchor_beat + 1 : 1;
const retryNote = st.policy_retries
? ` ยท ์ ์ฑ
๊ฑฐ๋ถ ${st.policy_retries}ํ ํ ์ฌ์๋ ์ฑ๊ณต`
: '';
html.push(`
<div class="media-thumb stitch-thumb">
<video src="${escapeAttr(st.video_url)}" controls playsinline preload="metadata"></video>
</div>
<div class="stitch-progress">
${totalSec}์ด ์์ ยท ${beats.length}๊ฐ ์ฌ ํตํฉ i2v ยท ์ต์ปค ์ด๋ฏธ์ง: ๋นํธ ${anchorIdx}${retryNote}
</div>
<div class="stitch-actions">
<a class="btn-stitch-download"
href="/api/media/download?url=${encodeURIComponent(st.video_url)}&filename=aether_final_seed${sIdx}_${totalSec}s.mp4"
title="์ต์ข
์์ ๋ค์ด๋ก๋">โ ${totalSec}์ด ๊ด๊ณ ๋ค์ด๋ก๋</a>
<button type="button" class="btn-stitch" data-final-seed="${sIdx}">๐ ์์ ์ฌ์์ฑ</button>
</div>
`);
} else if (st.status !== 'loading') {
const enough = imagesReady >= 1;
const disabled = !enough ? 'disabled' : '';
// If a previous run errored on policy, surface a "Try with another anchor" hint
const anchorButtons = (st.status === 'error' && imagesReady > 1)
? beats.map((_, i) => MEDIA_STATE[sIdx]?.[i]?.image_url
? `<button type="button" class="btn-media" data-final-seed="${sIdx}" data-anchor-beat="${i}">๐ฏ ๋นํธ ${i + 1} ์ด๋ฏธ์ง๋ก ์ฌ์๋</button>`
: ''
).join('')
: '';
html.push(`
<div class="stitch-progress">
์ด๋ฏธ์ง ${imagesReady}/${beats.length} ์ค๋น
${enough ? `ยท ${totalSec}์ด ๋จ์ผ ์์ ์์ฑ ๊ฐ๋ฅ` : 'โ ์ฒซ ๋นํธ ์ด๋ฏธ์ง๋ถํฐ ํ์'}
</div>
<button type="button" class="btn-stitch" data-final-seed="${sIdx}" ${disabled}>
๐ฌ ${totalSec}์ด ๊ด๊ณ ์์ ์์ฑ (Seedance 2.0, ํ ๋ฒ ํธ์ถ)
</button>
${anchorButtons ? `<div class="media-controls" style="flex-direction:row;flex-wrap:wrap;">${anchorButtons}</div>` : ''}
`);
}
html.push(`</div>`);
host.innerHTML = html.join('');
}
/** Backward-compat: keep the old name pointing at the new section. */
function renderStitchSection(sIdx) {
renderFinalVideoSection(sIdx);
}
/** Generate image for one beat. If useChain, attach last 3 prior images as refs. */
async function _genImageForBeat(sIdx, bIdx, useChain) {
const beat = LATEST_RESULTS?.seeds?.[sIdx]?.seed?.beats?.[bIdx];
if (!beat?.content) return false;
const total = LATEST_RESULTS.seeds[sIdx].seed.beats.length;
const refs = [];
if (useChain) {
for (let k = Math.max(0, bIdx - 3); k < bIdx; k++) {
const u = MEDIA_STATE[sIdx]?.[k]?.image_url;
if (u) refs.push(u);
}
}
_setMediaState(sIdx, bIdx, {
status: 'loading',
kind: 'image',
message: refs.length
? `๐ผ ์ด๋ฏธ์ง ${bIdx + 1}/${total} (์ฐธ์กฐ ${refs.length})โฆ`
: `๐ผ ์ด๋ฏธ์ง ${bIdx + 1}/${total} ์์ฑ ์คโฆ`,
});
try {
const body = { scene: beat.content };
if (refs.length) body.ref_image_urls = refs;
const r = await fetch('/api/media/image', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body),
});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
_setMediaState(sIdx, bIdx, { image_url: data.image_url, status: 'ready' });
return true;
} catch (e) {
_setMediaState(sIdx, bIdx, {
status: 'error', kind: 'image',
message: `์ด๋ฏธ์ง ์คํจ: ${e.message || e}`,
});
return false;
}
}
async function _genVideoForBeat(sIdx, bIdx) {
const beat = LATEST_RESULTS?.seeds?.[sIdx]?.seed?.beats?.[bIdx];
if (!beat?.content) return false;
const imgUrl = MEDIA_STATE[sIdx]?.[bIdx]?.image_url;
if (!imgUrl) return false;
const total = LATEST_RESULTS.seeds[sIdx].seed.beats.length;
_setMediaState(sIdx, bIdx, {
status: 'loading', kind: 'video',
message: `๐ฌ ๋น๋์ค ${bIdx + 1}/${total} ์์ฑ ์คโฆ (60-180์ด)`,
});
try {
const r = await fetch('/api/media/video', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({scene: beat.content, image_url: imgUrl}),
});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
_setMediaState(sIdx, bIdx, { video_url: data.video_url, status: 'ready' });
return true;
} catch (e) {
_setMediaState(sIdx, bIdx, {
status: 'error', kind: 'video',
message: `๋น๋์ค ์คํจ: ${e.message || e}`,
});
return false;
}
}
/** Manual handlers โ buttons call these. */
async function manualGenerateImage(sIdx, bIdx) {
await _genImageForBeat(sIdx, bIdx, /*useChain*/ true);
// re-render stitch in case state changed
renderStitchSection(sIdx);
}
// manualGenerateVideo removed โ single full-spot Seedance video replaces per-beat i2v.
/** Manual: text-to-image for any beat (no refs). */
async function manualGenerateImage(sIdx, bIdx) {
const beat = LATEST_RESULTS?.seeds?.[sIdx]?.seed?.beats?.[bIdx];
if (!beat || !beat.content) return;
_setMediaState(sIdx, bIdx, {
status: 'loading',
kind: 'image',
message: '๐ผ ์ด๋ฏธ์ง ์์ฑ ์คโฆ',
});
try {
const r = await fetch('/api/media/image', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({scene: beat.content}),
});
const data = await r.json();
if (!r.ok) throw new Error(data.detail || `HTTP ${r.status}`);
_setMediaState(sIdx, bIdx, { image_url: data.image_url, status: 'ready' });
} catch (e) {
_setMediaState(sIdx, bIdx, {
status: 'error',
kind: 'image',
message: `์ด๋ฏธ์ง ์คํจ: ${e.message || e}`,
});
}
}
/* manualGenerateVideo: removed. Single Seedance 2.0 call replaces it. */
/** Merge partial state, then re-render the slot. */
function _setMediaState(sIdx, bIdx, patch) {
MEDIA_STATE[sIdx] = MEDIA_STATE[sIdx] || {};
MEDIA_STATE[sIdx][bIdx] = Object.assign(
{},
MEDIA_STATE[sIdx][bIdx] || {},
patch,
);
renderMediaSlot(sIdx, bIdx);
}
function renderMediaSlot(sIdx, bIdx) {
const slot = document.querySelector(`[data-media="${sIdx}-${bIdx}"]`);
if (!slot) return;
const st = (MEDIA_STATE[sIdx] || {})[bIdx] || {};
const isAuto = bIdx === 0 && sIdx < 3; // first beat of top 3 seeds is auto
slot.innerHTML = mediaSlotHtml(sIdx, bIdx, st, isAuto);
}
function mediaSlotHtml(sIdx, bIdx, st, _isAuto) {
const parts = [];
// Status (loading / error) โ image only; per-beat video is gone.
if (st.status === 'loading' && st.message) {
parts.push(`<div class="media-status media-loading">${escapeHtml(st.message)}</div>`);
} else if (st.status === 'error' && st.message) {
parts.push(`<div class="media-status media-error-msg">${escapeHtml(st.message)}</div>`);
}
const fname = (kind) => `aether_${sIdx}_${String(bIdx).padStart(2,'0')}.${kind}`;
// Image preview
if (st.image_url) {
parts.push(`
<div class="media-thumb">
<img src="${escapeAttr(st.image_url)}" alt="scene ${bIdx + 1}" loading="lazy" />
<a class="media-download"
href="/api/media/download?url=${encodeURIComponent(st.image_url)}&filename=${encodeURIComponent(fname('jpg'))}"
title="์ด๋ฏธ์ง ๋ค์ด๋ก๋">โ</a>
</div>
`);
}
// (Per-beat video preview removed โ single full-spot video lives at card bottom.)
// Image-only controls โ single i2v video is generated once for the whole spot.
if (HAS_FAL) {
const imgDisabled = st.status === 'loading' ? 'disabled' : '';
const imgLabel = st.image_url ? '๐ ์ด๋ฏธ์ง ์ฌ์์ฑ' : '๐ผ ์ด๋ฏธ์ง ์์ฑ';
parts.push(`
<div class="media-controls">
<button type="button" class="btn-media" data-media-btn="image"
data-seed="${sIdx}" data-beat="${bIdx}" ${imgDisabled}>${imgLabel}</button>
</div>
`);
}
return parts.join('');
}
/* (Legacy renderStitchSection / stitchAllVideos removed โ replaced by
* renderFinalVideoSection + generateFinalVideo defined earlier in this file.
* The forwarder near the top still exposes `renderStitchSection` for any
* call sites that haven't migrated yet.)
*/
function escapeAttr(s) {
return String(s || '').replace(/"/g, '"').replace(/</g, '<');
}
/* Delegate clicks on per-beat image buttons + final-video regen + anchor retry. */
document.addEventListener('click', (e) => {
// Final-video regen / try-another-anchor (.btn-media or .btn-stitch with data-final-seed)
const finalEl = e.target.closest('[data-final-seed]');
if (finalEl && !finalEl.disabled) {
const sIdx = parseInt(finalEl.dataset.finalSeed ?? finalEl.dataset.stitchSeed, 10);
const anchor = finalEl.dataset.anchorBeat;
if (!Number.isNaN(sIdx)) {
generateFinalVideo(sIdx, anchor !== undefined ? parseInt(anchor, 10) : 0);
}
return;
}
const finalBtn = e.target.closest('.btn-stitch');
if (finalBtn && !finalBtn.disabled) {
const sIdx = parseInt(finalBtn.dataset.stitchSeed, 10);
if (!Number.isNaN(sIdx)) generateFinalVideo(sIdx);
return;
}
const btn = e.target.closest('.btn-media');
if (!btn) return;
const sIdx = parseInt(btn.dataset.seed, 10);
const bIdx = parseInt(btn.dataset.beat, 10);
if (btn.dataset.mediaBtn === 'image') {
manualGenerateImage(sIdx, bIdx);
}
});
function renderRawDetails(seed) {
const parts = [];
if (seed.raw_collision) {
parts.push(`
<details class="raw-details">
<summary>๐ ๋ชจ๋ธ ์๋ณธ ์ถ๋ ฅ ยท Concept (์ฐธ๊ณ ์๋ฃ)</summary>
<pre class="raw-body">${escapeHtml(seed.raw_collision)}</pre>
</details>
`);
}
if (seed.raw_spine) {
parts.push(`
<details class="raw-details">
<summary>๐ ๋ชจ๋ธ ์๋ณธ ์ถ๋ ฅ ยท Pixar Spine (์ฐธ๊ณ ์๋ฃ)</summary>
<pre class="raw-body">${escapeHtml(seed.raw_spine)}</pre>
</details>
`);
}
return parts.join('');
}
function renderBeatBar(beats, duration) {
return beats.map((b, i) => {
const pct = ((b.time_range[1] - b.time_range[0]) / duration) * 100;
const short = (b.beat || '').split('_')[0] || b.beat;
return `
<div class="beat-seg beat-color-${Math.min(i, 5)}" style="width: ${pct}%;"
title="${escapeHtml(b.beat)} ยท ${b.time_range[0]}-${b.time_range[1]}s">
<div class="beat-seg-name">${escapeHtml(short)}</div>
<div class="beat-seg-time">${b.time_range[0]}-${b.time_range[1]}s</div>
</div>
`;
}).join('');
}
function renderTicks(duration) {
const ticks = duration === 15 ? [0, 3, 6, 9, 12, 15] : [0, 5, 10, 15, 20, 25, 30];
return ticks.map(t => {
const left = (t / duration) * 100;
return `<span class="timeline-tick" style="left: ${left}%;">${t}s</span>`;
}).join('');
}
function scoreItem(label, val, opts = {}) {
const v = opts.raw ? val : (typeof val === 'number' ? val.toFixed(3) : val);
const style = [];
if (opts.risk && Number(val) > 0) style.push('color: var(--danger);');
if (opts.bold) style.push('color: var(--primary); font-size: 15px;');
return `
<div class="score-item">
<span class="score-item-label">${label}</span>
<span class="score-item-value" style="${style.join(' ')}">${v}</span>
</div>
`;
}
function escapeHtml(s) {
if (s == null) return '';
return String(s).replace(/[&<>"']/g, ch => ({
'&':'&','<':'<','>':'>','"':'"',"'":''',
}[ch]));
}
|