Spaces:
Sleeping
Sleeping
Download index.html from sunyoung00/SPAO: direct link, hf CLI and curl.
- Browser
- Download file 154 kB
-
https://huggingface.co/spaces/sunyoung00/SPAO/resolve/main/index.html
- Command line
-
hf download hf://spaces/sunyoung00/SPAO/index.html
-
curl -L -o index.html https://huggingface.co/spaces/sunyoung00/SPAO/resolve/main/index.html
154 kB
<!doctype html>
<html lang="ko" class="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>AI 얼굴 교체</title>
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
<style>
:root {
--bg: #1a1a1a; --panel: #1e1e1e; --surface: #202020; --surface2: #242424; --surface3: #2a2a2a;
--line: #2a2a2a; --line2: #333333; --line3: #3a3a3a; --hover: #4b5563;
--blue: #3b82f6; --blue-h: #2563eb;
--text: #f9fafb; --text2: #d1d5db; --text3: #9ca3af; --text4: #6b7280;
--amber: #fbbf24; --red: #f87171; --green: #34d399;
--font: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', 'Malgun Gothic', 'Segoe UI', sans-serif;
}
* { box-sizing: border-box; font-family: var(--font); }
html, body { height: 100%; }
body { margin: 0; background: var(--bg); color: var(--text); font-size: 14px; -webkit-font-smoothing: antialiased; overflow: hidden; word-break: keep-all; overflow-wrap: break-word; }
button, input, textarea, select { font: inherit; color: inherit; }
button { cursor: pointer; }
[hidden] { display: none !important; }
:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--hover); }
svg { flex-shrink: 0; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes shimmer { 0% { background-position: -600px 0; } 100% { background-position: 600px 0; } }
@keyframes pulseRing { 0% { transform: scale(0.85); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
@keyframes spin { to { transform: rotate(360deg); } }
.fade { animation: fadeIn .25s ease-out; }
.shimmer { background: linear-gradient(90deg, #232323 0%, #2c2c2c 40%, #232323 80%); background-size: 600px 100%; animation: shimmer 1.6s linear infinite; }
.spin { display: inline-flex; animation: spin 1s linear infinite; }
@media (prefers-reduced-motion: reduce) { .shimmer, .ring::before, .fade { animation: none; } .spin { animation-duration: 3s; } }
/* ── 셸 / 헤더 ─────────────────────────── */
.shell { height: 100vh; display: flex; flex-direction: column; }
.hdr { height: 56px; flex-shrink: 0; border-bottom: 1px solid var(--line); background: var(--bg); display: flex; align-items: center; justify-content: space-between; padding: 0 20px; gap: 12px; }
.hdr-l, .hdr-r { display: flex; align-items: center; gap: 16px; min-width: 0; }
.brand { display: flex; align-items: center; gap: 12px; }
.logo { width: 32px; height: 32px; border-radius: 8px; background: var(--blue); display: grid; place-items: center; color: #fff; }
.brand b { font-size: 15px; font-weight: 700; letter-spacing: -0.01em; white-space: nowrap; }
.pills { display: flex; gap: 4px; }
.pill { border: 0; background: transparent; color: var(--text3); padding: 6px 12px; border-radius: 8px; font-size: 12.5px; font-weight: 600; display: flex; align-items: center; gap: 6px; transition: background .15s, color .15s; }
.pill:hover { color: #e5e7eb; background: var(--line); }
.pill.on { background: var(--line2); color: #fff; }
.bdg { min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9999px; background: var(--blue); color: #fff; font-size: 10.5px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; }
.status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--text3); white-space: nowrap; }
.status i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.status.ok { color: var(--green); } .status.warn { color: var(--amber); }
.body { flex: 1; min-height: 0; display: flex; }
/* ── 왼쪽 패널 ─────────────────────────── */
.stick { position: sticky; top: 0; z-index: 5; background: rgba(26,26,26,.96); backdrop-filter: blur(6px); border-bottom: 1px solid var(--line); }
.strip .startbtn { height: 36px; padding: 0 18px; font-size: 13px; }
.strip .sum { margin: 10px 0 0; font-size: 12px; color: var(--text3); }
.strip .sum:empty { display: none; }
.strip .sum b { color: #e5e7eb; font-weight: 600; }
.stick .strip { position: static; background: transparent; backdrop-filter: none; border-bottom: 0; padding: 12px 24px 14px; }
.drop { border: 1px dashed var(--line3); background: #212121; border-radius: 12px; padding: 24px 16px 16px; text-align: center; transition: border-color .15s, background .15s; cursor: pointer; }
.drop:hover { border-color: var(--hover); }
.drop.over, body.dragging .drop { border-color: var(--blue); background: rgba(59,130,246,.08); }
.drop .ic { color: var(--text4); margin-bottom: 8px; }
.drop p { margin: 0; font-size: 13.5px; font-weight: 600; color: #e5e7eb; }
.drop .sub { margin: 4px 0 14px; font-size: 11.5px; color: var(--text4); line-height: 1.5; }
.drop .btns { display: flex; gap: 8px; justify-content: center; }
.vh { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); border: 0; opacity: 0; pointer-events: none; }
.toast { position: fixed; left: 50%; top: 66px; transform: translateX(-50%); z-index: 60; max-width: min(560px, calc(100vw - 32px)); padding: 12px 16px; border-radius: 12px; font-size: 13px; line-height: 1.55; background: #262626; border: 1px solid var(--line3); color: var(--text); box-shadow: 0 8px 28px rgba(0,0,0,.45); animation: fadeIn .2s ease-out; }
.toast.ok { border-color: rgba(52,211,153,.45); }
.toast.warn { border-color: rgba(245,158,11,.5); color: #fde68a; }
.toast.err { border-color: rgba(239,68,68,.5); color: #fecaca; }
.pickhint { margin: 10px 2px 0; font-size: 11.5px; color: var(--text4); line-height: 1.6; }
.pickhint b { color: var(--text2); font-weight: 600; }
.pickhint a { color: var(--blue); font-weight: 600; text-decoration: none; }
.pickhint a:hover { text-decoration: underline; }
label.drop { display: block; }
.drop .btn { margin-top: 2px; pointer-events: none; }
.pbar { display: flex; height: 8px; border-radius: 4px; background: var(--line2); overflow: hidden; }
.pbar i { display: block; height: 100%; transition: width .5s ease; }
.pbar i.done { background: var(--blue); }
.pbar i.run { background: repeating-linear-gradient(45deg, #7db3f8 0 8px, #3b82f6 8px 16px); background-size: 22px 22px; animation: stripes 1s linear infinite; }
.pbar i.bad { background: var(--red); }
.pbar i.can { background: #6b7280; }
.pbar.thin { height: 6px; margin: 0 0 10px; }
@keyframes stripes { to { background-position: 22px 0; } }
@media (prefers-reduced-motion: reduce) { .pbar i.run { animation: none; } }
.strip .pct { font-variant-numeric: tabular-nums; font-size: 13px; font-weight: 700; color: #93c5fd; min-width: 44px; text-align: right; }
.strip .barrow { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
.strip .barrow .pbar { flex: 1; }
.btn.stopbtn { color: #fca5a5; border-color: rgba(239,68,68,.45); background: rgba(239,68,68,.08); }
.btn.stopbtn:hover:not(:disabled) { background: rgba(239,68,68,.16); color: #fecaca; border-color: rgba(239,68,68,.7); }
.hdr-r a.status { color: var(--blue); text-decoration: none; font-weight: 600; }
.hdr-r a.status:hover { text-decoration: underline; }
.btn { height: 34px; padding: 0 14px; border-radius: 8px; border: 1px solid var(--line2); background: var(--surface2); color: var(--text2); font-size: 12.5px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; gap: 6px; white-space: nowrap; flex-shrink: 0; text-decoration: none; transition: border-color .15s, color .15s, background .15s; }
.btn:hover:not(:disabled) { border-color: var(--hover); color: #fff; }
.btn:disabled { background: var(--surface3); border-color: var(--surface3); color: var(--text4); cursor: not-allowed; }
.btn.primary { background: var(--blue); border-color: var(--blue); color: #fff; }
.btn.primary:hover:not(:disabled) { background: var(--blue-h); border-color: var(--blue-h); }
.btn.primary:disabled { background: var(--surface3); border-color: var(--surface3); color: var(--text4); }
.btn.danger:hover:not(:disabled) { color: #fca5a5; border-color: rgba(239,68,68,.45); background: rgba(239,68,68,.08); }
.btn.sm { height: 30px; padding: 0 10px; font-size: 12px; border-radius: 8px; }
.btn.lg { height: 48px; width: 100%; border-radius: 12px; font-size: 14px; }
.linkbtn { background: none; border: 0; padding: 0; color: var(--blue); font-size: 12px; font-weight: 600; }
.linkbtn:hover { text-decoration: underline; }
.seg { display: grid; gap: 6px; grid-template-columns: repeat(var(--n, 3), minmax(0, 1fr)); }
.seg button { padding: 8px 6px; border-radius: 8px; font-size: 12.5px; font-weight: 500; border: 1px solid var(--line2); background: var(--surface2); color: var(--text2); transition: border-color .15s, color .15s; }
.seg button:hover:not(:disabled):not(.on) { border-color: var(--hover); color: #fff; }
.seg button.on { background: var(--blue); border-color: var(--blue); color: #fff; }
.seg button.on[data-gender=skip] { background: var(--line3); border-color: var(--line3); }
.seg button.view { border-color: #fff; color: #fff; background: var(--surface3); } /* 카드에서 원본을 보는 중 (파랑 = 내보내기에 쓰는 컷) */
.seg button:disabled { cursor: not-allowed; opacity: .5; }
.seg button.on:disabled { opacity: .75; }
/* ── 오른쪽 메인 ───────────────────────── */
.main { flex: 1; min-width: 0; overflow-y: auto; }
.strip { position: sticky; top: 0; z-index: 4; background: rgba(26,26,26,.96); backdrop-filter: blur(6px); border-bottom: 1px solid var(--line); padding: 14px 28px 16px; }
.strip-row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.strip .big { font-size: 15px; font-weight: 700; letter-spacing: -0.01em; }
.strip .big small { font-weight: 500; font-size: 12.5px; color: var(--text3); margin-left: 8px; }
.chips { display: flex; gap: 6px; flex-wrap: wrap; flex: 1; min-width: 0; align-items: center; }
.chip { font-size: 11.5px; font-weight: 600; line-height: 1.4; border-radius: 9999px; padding: 3px 10px; background: var(--surface3); color: var(--text2); }
.chip.warn { background: rgba(245,158,11,.14); color: var(--amber); }
.chip.bad { background: rgba(239,68,68,.14); color: var(--red); }
.chip.go { background: rgba(59,130,246,.16); color: #93c5fd; }
.bar { height: 4px; border-radius: 2px; background: var(--line2); margin-top: 12px; overflow: hidden; }
.bar i { display: block; height: 100%; width: 0; background: var(--blue); transition: width .35s; }
.acts { display: flex; gap: 8px; }
.note { margin: 16px 28px 0; padding: 12px 14px; border-radius: 12px; font-size: 13px; line-height: 1.55; display: flex; gap: 10px; align-items: flex-start; }
.note svg { margin-top: 2px; }
.note .grow { flex: 1; min-width: 0; }
.note .row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
.note.warn { border: 1px solid rgba(245,158,11,.4); background: rgba(245,158,11,.1); color: #fde68a; }
.note.err { border: 1px solid rgba(239,68,68,.4); background: rgba(239,68,68,.1); color: #fecaca; }
.note.warn .btn, .note.err .btn { background: rgba(0,0,0,.25); }
.hero { max-width: 720px; margin: 0 auto; padding: 9vh 24px 40px; }
.drop.big { display: block; padding: 56px 28px 46px; border: 1.5px dashed var(--line3); border-radius: 20px; background: #1f1f1f; text-align: center; cursor: pointer; transition: border-color .15s, background .15s; }
.drop.big:hover { border-color: var(--hover); }
.drop.big .badge { width: 60px; height: 60px; margin: 0 auto 18px; border-radius: 9999px; background: rgba(59,130,246,.15); color: var(--blue); display: grid; place-items: center; }
.drop.big h2 { margin: 0 0 8px; font-size: 22px; font-weight: 700; letter-spacing: -0.02em; color: var(--text); }
.drop.big p { margin: 0 0 24px; font-size: 14px; font-weight: 400; color: var(--text3); line-height: 1.7; }
.drop.big .btn { height: 42px; padding: 0 24px; font-size: 13.5px; }
.folder { padding: 20px 24px 2px; }
.folder-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
.folder-head h3 { margin: 0; font-size: 14px; font-weight: 600; letter-spacing: -0.01em; word-break: break-all; display: flex; align-items: center; gap: 8px; }
.folder-head h3 svg { color: var(--text4); }
.folder-head .cnt { color: var(--text4); font-size: 12px; }
.crumb { color: var(--text4); font-weight: 500; font-size: 12.5px; margin-right: -2px; }
.folder-head .sp { flex: 1; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); gap: 12px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; display: flex; flex-direction: column; }
.card.is-error { border-color: rgba(239,68,68,.45); }
.card figure.res { margin: 0; position: relative; aspect-ratio: 2 / 3; background: #161616; overflow: hidden; }
.card figure.res > img:not(.origthumb) { width: 100%; height: 100%; object-fit: contain; display: block; }
.card figure.res.clickable { cursor: zoom-in; }
.card figure.res > img.origthumb { position: absolute; left: 8px; bottom: 8px; width: 38px; height: 50px; object-fit: cover; object-position: center top; border-radius: 6px; border: 1.5px solid rgba(255,255,255,.85); box-shadow: 0 2px 8px rgba(0,0,0,.5); display: block; }
.card .gchip { position: absolute; left: 8px; top: 8px; font-size: 11px; font-weight: 600; color: #fff; background: rgba(0,0,0,.62); border-radius: 6px; padding: 2px 7px; }
.card .cutbadge { position: absolute; right: 8px; top: 8px; z-index: 3; background: rgba(0,0,0,.66); color: #fff; font-size: 11.5px; font-weight: 700; line-height: 1.4; padding: 2px 9px; border-radius: 9999px; pointer-events: none; }
.card .vseg { margin-top: -2px; }
.card .vseg button[disabled] { opacity: .55; }
.fileset { display: contents; }
.fileset.multi { display: grid; gap: 12px; }
.card.used { border-color: var(--blue); box-shadow: 0 0 0 1px var(--blue); }
.card .vchip { position: absolute; right: 8px; top: 8px; z-index: 3; font-size: 11px; font-weight: 600; line-height: 1.4; color: #fff; background: rgba(0,0,0,.62); border: 0; border-radius: 6px; padding: 2px 8px; }
.card .vchip.pick { cursor: pointer; }
.card .vchip.pick:hover { background: rgba(59,130,246,.85); }
.card .vchip.use { background: var(--blue); }
.row3 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.row3 .btn.sm { width: 100%; padding: 0 6px; }
.card .zoom { position: absolute; right: 8px; bottom: 8px; width: 26px; height: 26px; border-radius: 8px; background: rgba(0,0,0,.65); color: #fff; display: grid; place-items: center; opacity: 0; transition: opacity .15s; }
.card figure.res:hover .zoom { opacity: 1; }
.ph { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; padding: 10px; text-align: center; font-size: 12px; line-height: 1.45; color: var(--text3); }
.ph.cover { background: rgba(14,14,14,.66); }
.ph.cover.soft { background: rgba(14,14,14,.34); }
.ph.err { color: var(--red); }
.ph .t { color: #f3f4f6; font-weight: 600; font-size: 12px; }
.ph .s { color: var(--text3); font-size: 11px; }
.ring { position: relative; width: 32px; height: 32px; border-radius: 9999px; background: rgba(59,130,246,.22); color: var(--blue); display: grid; place-items: center; margin-bottom: 6px; }
.ring::before { content: ''; position: absolute; inset: -5px; border-radius: 9999px; border: 2px solid var(--blue); animation: pulseRing 1.4s ease-out infinite; }
.cprog { position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background: rgba(255,255,255,.14); }
.cprog i { display: block; height: 100%; background: var(--blue); transition: width .8s ease; }
.meta { padding: 8px 10px 10px; display: flex; flex-direction: column; gap: 7px; }
.fname { font-weight: 600; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.seg.mini { gap: 4px; }
.seg.mini button { padding: 5px 0; font-size: 11.5px; border-radius: 7px; }
.row2 { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 26px; }
.state { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--text3); min-width: 0; }
.state i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
.state span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.state.ok { color: var(--green); } .state.warn { color: var(--amber); } .state.bad { color: var(--red); } .state.go { color: #93c5fd; }
.state em { font-style: normal; font-variant-numeric: tabular-nums; margin-left: 2px; opacity: .9; }
.row2 .btn.sm { height: 26px; padding: 0 8px; font-size: 11.5px; }
.errbox { font-size: 11.5px; line-height: 1.5; color: #fecaca; background: rgba(239,68,68,.08); border: 1px solid rgba(239,68,68,.25); border-radius: 8px; padding: 8px 10px; word-break: break-all; margin-top: 6px; }
/* ── 지난 결과 ─────────────────────────── */
.htop { position: sticky; top: 0; z-index: 4; background: rgba(26,26,26,.96); backdrop-filter: blur(6px); border-bottom: 1px solid var(--line); padding: 12px 28px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
/* 입력창·선택 상자 기본 모양 (지난 화면 정리 때 빠졌던 것을 복구) */
.inp { width: 100%; border-radius: 12px; background: var(--surface2); border: 1px solid var(--line2); padding: 9px 12px; font-size: 13px; color: #f3f4f6; color-scheme: dark; appearance: none; -webkit-appearance: none; }
.inp::placeholder { color: var(--text4); }
.inp:hover { border-color: var(--hover); }
.inp:focus { outline: none; border-color: var(--blue); }
.inp::-webkit-search-cancel-button { filter: invert(.7); cursor: pointer; }
select.inp { cursor: pointer; padding-right: 30px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 11px center; }
.htop .inp { height: 34px; padding: 0 12px; width: 240px; border-radius: 8px; }
.htop select.inp { width: auto; padding-right: 30px; }
.htop .btn.sm { height: 34px; }
.htop .hcount { font-size: 12.5px; color: var(--text3); margin-left: 4px; }
.htop .sp { flex: 1; }
/* 통계 대시보드 */
.htop input[type=date].inp { width: 148px; }
.sbody { padding: 22px 28px 70px; display: grid; gap: 16px; }
.scards { display: grid; grid-template-columns: repeat(auto-fit, minmax(168px, 1fr)); gap: 12px; }
.scard { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; }
.scard .k { font-size: 12px; color: var(--text3); }
.scard .v { font-size: 24px; font-weight: 700; margin-top: 4px; color: #f3f4f6; }
.scard .v small { font-size: 12px; color: var(--text4); font-weight: 500; margin-left: 4px; }
.scard .n { font-size: 11.5px; color: var(--text4); margin-top: 5px; line-height: 1.4; }
.spanel { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; padding: 16px 18px; min-width: 0; }
.spanel h3 { margin: 0 0 12px; font-size: 13.5px; font-weight: 600; color: #f3f4f6; display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
.spanel h3 span { color: var(--text4); font-weight: 500; font-size: 12px; }
.s2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; }
.sbars { display: flex; align-items: flex-end; gap: 6px; overflow-x: auto; padding-bottom: 4px; min-height: 170px; }
.sbar { display: flex; flex-direction: column; align-items: center; justify-content: flex-end; gap: 4px; min-width: 30px; font-size: 10.5px; color: var(--text4); }
.sbar b { font-size: 11px; font-weight: 600; color: #d1d5db; }
.sstack { width: 18px; display: flex; flex-direction: column; justify-content: flex-end; border-radius: 5px 5px 0 0; overflow: hidden; background: rgba(255,255,255,.06); }
.sstack i { display: block; width: 100%; }
.sg { background: var(--blue); } .sr { background: var(--amber); }
.slegend { display: flex; gap: 14px; margin-top: 8px; font-size: 12px; color: var(--text3); }
.slegend i { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 6px; }
.shbar { display: grid; grid-template-columns: 52px 1fr 110px; gap: 10px; align-items: center; font-size: 12.5px; margin: 8px 0; }
.shbar .t { height: 8px; border-radius: 4px; background: rgba(255,255,255,.07); overflow: hidden; }
.shbar .t i { display: block; height: 100%; background: var(--blue); border-radius: 4px; }
.shbar .c { color: var(--text3); text-align: right; font-variant-numeric: tabular-nums; }
.shours { display: flex; align-items: flex-end; gap: 3px; height: 96px; }
.shours div { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 4px; font-size: 9.5px; color: var(--text4); min-width: 0; }
.shours i { display: block; width: 100%; background: var(--blue); border-radius: 3px 3px 0 0; opacity: .85; }
table.stbl { width: 100%; border-collapse: collapse; font-size: 12.5px; }
.stbl th { text-align: left; font-weight: 600; color: var(--text3); font-size: 11.5px; padding: 8px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
.stbl td { padding: 9px 10px; border-bottom: 1px solid rgba(255,255,255,.05); vertical-align: middle; }
.stbl .num { text-align: right; font-variant-numeric: tabular-nums; }
.stbl td.fn { max-width: 340px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stbl img { width: 34px; height: 46px; object-fit: cover; border-radius: 6px; background: #161616; display: block; cursor: pointer; }
.stbl .sub { color: var(--text4); font-size: 11px; }
.pillt { display: inline-block; font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 9999px; background: rgba(59,130,246,.16); color: #93c5fd; }
.pillt.regen { background: rgba(245,158,11,.16); color: #fcd34d; }
.smore { margin-top: 10px; text-align: center; }
.snote { color: var(--text4); font-size: 12px; line-height: 1.55; }
.hday { padding: 24px 28px 0; }
.hday > h3 { margin: 0; font-size: 14px; font-weight: 700; letter-spacing: -0.01em; }
.hday > h3 small { font-weight: 500; color: var(--text4); margin-left: 8px; font-size: 12px; }
.hgroup { margin-top: 14px; }
.hgroup-head { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
.hgroup-head b { font-size: 13px; font-weight: 600; word-break: break-all; display: flex; align-items: center; gap: 7px; }
.hgroup-head b svg { color: var(--text4); }
.hgroup-head span { color: var(--text4); font-size: 12px; }
.hgroup-head .sp { flex: 1; }
.hgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
.hcard { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; position: relative; }
.hcard.sel { border-color: var(--blue); box-shadow: 0 0 0 1px var(--blue); }
.hcard figure { margin: 0; aspect-ratio: 2 / 3; background: #161616; cursor: zoom-in; }
.hcard img { width: 100%; height: 100%; object-fit: contain; display: block; }
.hcard .pick { position: absolute; left: 8px; top: 8px; width: 24px; height: 24px; border-radius: 7px; background: rgba(0,0,0,.7); border: 1px solid rgba(255,255,255,.35); display: grid; place-items: center; opacity: 0; transition: opacity .12s; cursor: pointer; }
.hcard:hover .pick, .hcard.sel .pick, .has-sel .hcard .pick { opacity: 1; }
.hcard .pick input { margin: 0; width: 15px; height: 15px; accent-color: var(--blue); cursor: pointer; }
.hcard .meta { padding: 10px 12px 12px; gap: 8px; }
.hcard .cutbadge { position: absolute; right: 8px; top: 8px; z-index: 2; background: rgba(0,0,0,.66); color: #fff; font-size: 11.5px; font-weight: 700; line-height: 1.4; padding: 2px 9px; border-radius: 9999px; pointer-events: none; }
.hcard .row3 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.hcard .row3 .btn.sm { width: 100%; padding: 0 6px; }
.gal { position: fixed; inset: 0; background: #0c0c0c; z-index: 55; display: flex; flex-direction: column; }
.gal-head { display: flex; align-items: center; gap: 10px; padding: 14px 22px; }
.gal-head .t { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.gal-head .t svg { flex: none; color: var(--text4); }
.gal-head .t small { color: var(--text4); font-weight: 500; margin-left: 8px; font-size: 12px; }
.gal-body { position: relative; flex: 1; min-height: 0; overflow-y: auto; overflow-x: hidden; padding: 0 22px 70px; display: flex; flex-direction: column; scroll-behavior: auto; }
.gal-head .btn { flex: none; }
.gfile { min-width: 0; padding-bottom: 28px; border-bottom: 1px solid var(--line); }
.gfile:last-child { border-bottom: 0; }
.gfile-head { position: sticky; top: 0; z-index: 4; background: #0c0c0c; display: flex; align-items: baseline; gap: 10px; padding: 14px 2px 12px; }
.gfile-head b { font-size: 14px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.gfile-head span { color: var(--text4); font-size: 12px; flex: none; }
.gfile-head .gnum { margin-left: auto; }
.gfile.focus .gfile-head b { color: #93c5fd; }
.gfile-cuts { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 280px)); gap: 14px; justify-content: start; }
.gfile-head .btn { margin-left: auto; }
.gfile-head .btn + .gnum { margin-left: 0; }
@keyframes gspin { to { transform: rotate(360deg); } }
.gcut.pending { border-style: dashed; background: transparent; }
.gcut.pending figure { cursor: default; display: grid; place-items: center; text-align: center; padding: 12px; }
.gph { display: grid; justify-items: center; gap: 8px; color: var(--text3); font-size: 12.5px; }
.gph b { color: #e5e7eb; font-size: 13px; }
.gph .gspin { width: 28px; height: 28px; border: 3px solid rgba(255,255,255,.14); border-top-color: var(--blue); border-radius: 50%; animation: gspin 1s linear infinite; }
.gph .err { color: #fca5a5; max-width: 200px; word-break: keep-all; line-height: 1.45; }
.gcut .gtag.new { left: 58px; background: #16a34a; }
.gcut { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; }
.gcut.rep { border-color: var(--blue); box-shadow: 0 0 0 1px var(--blue); }
.gcut figure { margin: 0; position: relative; aspect-ratio: 2 / 3; background: #161616; cursor: zoom-in; }
.gcut img { width: 100%; height: 100%; object-fit: contain; display: block; }
.gcut .gtag { position: absolute; left: 10px; top: 10px; background: rgba(0,0,0,.66); color: #fff; font-size: 11.5px; font-weight: 700; line-height: 1.4; padding: 2px 9px; border-radius: 9999px; }
.gcut .gtag.rep { left: auto; right: 10px; background: var(--blue); }
.gcut .meta { padding: 10px 12px 12px; display: grid; gap: 8px; }
.gcut .row3 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.gcut .row3 .btn.sm { width: 100%; padding: 0 6px; }
.gcut .row3 .btn.sm[disabled] { opacity: .55; }
.empty2 { max-width: 420px; margin: 16vh auto 0; text-align: center; color: var(--text3); line-height: 1.7; padding: 0 20px; }
.empty2 b { display: block; color: var(--text); font-size: 16px; margin-bottom: 6px; }
/* ── 라이트박스 ────────────────────────── */
.lb { position: fixed; inset: 0; background: rgba(8, 8, 8, .94); z-index: 60; display: flex; flex-direction: column; }
.lb-head { display: flex; align-items: center; gap: 10px; padding: 12px 18px; }
.lb-head .t { flex: 1; font-weight: 600; font-size: 13.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lb-body { flex: 1; min-height: 0; display: grid; place-items: center; padding: 0 18px 12px; }
.cmp { position: relative; max-width: 100%; max-height: 100%; user-select: none; cursor: pointer; line-height: 0; border-radius: 12px; overflow: hidden; }
.cmp .a { display: block; max-width: calc(100vw - 36px); max-height: calc(100vh - 130px); }
.cmp .b { position: absolute; inset: 0; width: 100%; height: 100%; }
.cmp img { -webkit-user-drag: none; }
.lb-tabs { display: flex; justify-content: center; gap: 6px; flex-wrap: wrap; padding: 0 18px 12px; }
.lb-tabs button { height: 36px; min-width: 64px; padding: 0 16px; border-radius: 9999px; border: 1px solid var(--line2); background: var(--surface2); color: var(--text2); font-size: 13.5px; font-weight: 600; cursor: pointer; }
.lb-tabs button:hover { background: var(--surface3); color: var(--text); }
.lb-tabs button.on { background: var(--blue); border-color: var(--blue); color: #fff; }
.cmp .tag { position: absolute; top: 10px; font-size: 11.5px; font-weight: 600; line-height: 1; background: rgba(0,0,0,.65); color: #fff; border-radius: 6px; padding: 5px 8px; }
.cmp .tag.l { left: 10px; }
.lb-foot { text-align: center; color: var(--text4); font-size: 12px; padding: 0 0 14px; }
.veil { position: fixed; inset: 0; z-index: 40; background: rgba(59,130,246,.1); border: 3px dashed var(--blue); pointer-events: none; display: none; place-items: center; }
.veil div { background: rgba(26,26,26,.92); border: 1px solid var(--line2); border-radius: 16px; padding: 18px 26px; font-weight: 600; font-size: 15px; }
body.dragging .veil { display: grid; }
@media (max-width: 1023px) {
body { overflow: auto; }
.shell { height: auto; min-height: 100vh; }
.body { flex-direction: column; }
.main { overflow: visible; }
.strip, .htop { position: static; }
.hdr { flex-wrap: wrap; height: auto; padding: 10px 16px; }
}
/* ── 설정 패널: 성별 일괄 · 페르소나 모델 · 변형 강도 ── */
.setup { margin: 16px 28px 0; border: 1px solid var(--line2); background: var(--surface); border-radius: 12px; }
.setup-h { display: flex; align-items: center; gap: 10px; padding: 11px 16px; }
.setup-h b { font-size: 13.5px; font-weight: 700; letter-spacing: -0.01em; }
.setup-h .sub { color: var(--text3); font-size: 12px; flex: 1; min-width: 0; }
.lnk { border: 0; background: transparent; color: #93c5fd; font-size: 12.5px; font-weight: 600; padding: 4px 8px; border-radius: 6px; }
.lnk:hover { background: rgba(59,130,246,.12); }
.setup-body { border-top: 1px solid var(--line); padding: 2px 16px 12px; }
.srow { display: grid; grid-template-columns: 150px minmax(0, 1fr); gap: 14px; padding: 14px 0; align-items: start; }
.srow + .srow { border-top: 1px solid var(--line); }
.slab { font-size: 13px; font-weight: 700; padding-top: 6px; }
.slab small { display: block; font-weight: 500; font-size: 11.5px; color: var(--text3); line-height: 1.5; margin-top: 4px; }
.sctl { min-width: 0; }
.brow { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.bseg { width: min(100%, 380px); }
.bseg button { height: 36px; padding: 0 8px; }
.bcount { font-size: 12px; color: var(--text3); }
.bcount b { color: #e5e7eb; font-weight: 700; }
.bcount .warn { color: var(--amber); }
.persona { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.pcard { display: flex; gap: 12px; padding: 10px; border: 1px solid var(--line2); border-radius: 12px; background: var(--surface2); min-width: 0; }
.pimg { width: 78px; height: 100px; border-radius: 8px; overflow: hidden; background: #111; flex-shrink: 0; display: grid; place-items: center; color: var(--text4); font-size: 11px; text-align: center; padding: 4px; }
.pimg img { width: 100%; height: 100%; object-fit: cover; object-position: top; display: block; }
.pbody { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
.pt { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.pt b { font-size: 13px; }
.ptag { font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 9999px; background: var(--surface3); color: var(--text2); }
.ptag.up { background: rgba(59,130,246,.16); color: #93c5fd; }
.pfile { font-size: 11.5px; color: var(--text3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pfile:empty { display: none; }
.pbtn { display: flex; gap: 6px; flex-wrap: wrap; }
.hl { display: block; font-size: 11.5px; color: var(--text3); }
.hl .inp { width: 100%; margin-top: 4px; height: 32px; font-size: 12px; }
.s2 { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 0 28px; border-top: 1px solid var(--line); }
.s2 > .srow { grid-template-columns: 1fr; gap: 8px; padding: 14px 0; border-top: 0; }
.s2 > .srow + .srow { border-top: 0; border-left: 1px solid var(--line); padding-left: 28px; }
.s2 .slab { padding-top: 0; }
.rng { display: grid; grid-template-columns: 52px minmax(0, 1fr) 46px; align-items: center; gap: 12px; max-width: 520px; }
.rng + .rng { margin-top: 6px; }
.rng label { font-size: 12.5px; font-weight: 600; color: var(--text2); }
.rng output { font-variant-numeric: tabular-nums; font-weight: 700; font-size: 13px; text-align: right; color: #e5e7eb; }
.rng input[type=range] { width: 100%; accent-color: var(--blue); height: 24px; }
.rscale { display: flex; justify-content: space-between; font-size: 11px; color: var(--text4); margin: 0 58px 0 64px; max-width: 520px; }
.shelp { margin: 8px 0 0; font-size: 12px; color: var(--text3); line-height: 1.65; max-width: 640px; }
.shelp b { color: var(--text2); font-weight: 600; }
.shelp .lnk { padding: 0 4px; font-size: 12px; }
@media (max-width: 1240px) { .s2 { grid-template-columns: 1fr; } .s2 > .srow + .srow { border-left: 0; padding-left: 0; border-top: 1px solid var(--line); } }
@media (max-width: 900px) { .srow { grid-template-columns: 1fr; gap: 8px; } .slab { padding-top: 0; } .persona { grid-template-columns: 1fr; } .setup { margin: 12px 14px 0; } }
</style>
</head>
<body>
<div class="veil"><div>여기에 놓으면 추가돼요</div></div>
<div class="shell">
<header class="hdr">
<div class="hdr-l">
<div class="brand"><div class="logo" id="logo"></div><b>AI 얼굴 교체</b></div>
<nav class="pills" aria-label="화면 전환">
<button class="pill on" type="button" data-view="work">작업</button>
<button class="pill" type="button" data-view="hist">지난 결과<span class="bdg" id="histBadge" hidden></span></button>
<button class="pill" type="button" data-view="stats">통계</button>
</nav>
</div>
<div class="hdr-r">
<span class="status" id="userChip" hidden><i></i><span></span></span>
<a class="status" id="authLink" target="_blank" rel="noopener" hidden></a>
<a class="status" id="openTab" target="_blank" rel="noopener" hidden>새 탭에서 열기</a>
<span class="status" id="conn" hidden><i></i><span></span></span>
<span class="status" id="dur" hidden><i></i><span></span></span>
</div>
</header>
<div class="body">
<main class="main" id="main">
<div id="workView">
<div class="stick" hidden>
<div class="strip" id="top" hidden>
<div class="strip-row">
<div class="big" id="sumLine"></div>
<div class="chips" id="chips"></div>
<div class="acts">
<button class="btn sm" id="retry" type="button" hidden>실패·취소한 건 다시 시도</button>
<button class="btn sm" id="zipAll" type="button" disabled>완료분 ZIP 다운로드</button>
<button class="btn sm danger" id="clear" type="button">목록 비우기</button>
<label class="btn sm" id="addZip" for="zipInput" role="button" tabindex="0" hidden>ZIP 추가</label>
<button class="btn stopbtn" id="stop" type="button" hidden>전체 취소</button>
<button class="btn primary startbtn" id="go" type="button" disabled>이미지를 올려 주세요</button>
</div>
</div>
<div class="barrow"><div class="pbar" id="pbar"></div><span class="pct" id="pct">0%</span></div>
<p class="sum" id="sum"></p>
</div>
</div>
<section class="setup" id="setup" aria-label="얼굴 교체 설정">
<div class="setup-h"><b>얼굴 교체 설정</b><span class="sub" id="setupSub"></span><button class="lnk" id="setupToggle" type="button" aria-expanded="true">접기</button></div>
<div class="setup-body" id="setupBody">
<div class="srow">
<div class="slab">성별 일괄 선택<small>건너뜀·작업 중·완료된 사진은 그대로 둬요</small></div>
<div class="sctl"><div class="brow">
<div class="seg bseg" style="--n:3" role="group" aria-label="성별 일괄 선택"><button type="button" data-bg="male">전체 남자</button><button type="button" data-bg="female">전체 여자</button><button type="button" data-bg="auto" title="파일명·폴더 이름·ZIP 이름으로 다시 정해요">파일명대로</button></div>
<span class="bcount" id="bulkCount"></span>
</div></div>
</div>
<div class="s2">
<div class="srow">
<div class="slab">변형 강도<small>낮을수록 원본이 많이 남고, 높을수록 모델 사진 쪽으로 많이 바뀌어요</small></div>
<div class="sctl">
<div class="rng" id="rowFace"><label for="rFace" id="lFace">얼굴</label><input type="range" id="rFace" min="0.1" max="1" step="0.05" value="0.4"><output id="vFace" for="rFace">0.40</output></div>
<div class="rng" id="rowHair"><label for="rHair">머리</label><input type="range" id="rHair" min="0.1" max="1" step="0.05" value="0.4"><output id="vHair" for="rHair">0.40</output></div>
<div class="rscale"><span>원본 유지</span><span>많이 바뀜</span></div>
<p class="shelp">머리가 안 바뀌면 <b>머리</b>를, 얼굴이 안 바뀌면 <b>얼굴</b>을 올려 보세요. 너무 높으면 피부 톤·경계가 어색해질 수 있어요. <b>이후에 시작하는 작업부터</b> 적용돼요. <button class="lnk" id="rReset" type="button">기본값으로</button></p>
</div>
</div>
<div class="srow">
<div class="slab">페르소나 모델<small>기본은 서버의 기본 모델이에요. 원하면 직접 올릴 수 있어요(정면 얼굴이 크게 나온 사진이 좋아요)</small></div>
<div class="sctl"><div class="persona" id="persona"></div></div>
</div>
</div>
</div>
</section>
<div id="banners"></div>
<div id="folders"></div>
<div class="hero fade" id="empty">
<label class="drop big" id="drop" for="zipInput" tabindex="0" role="button" aria-label="ZIP 파일 선택">
<div class="badge" id="icDrop"></div>
<h2>ZIP 파일을 올려 주세요</h2>
<p>폴더를 ZIP으로 묶어 끌어다 놓거나 눌러서 선택하세요.<br>안에 있는 사진이 모두 나타나고, 파일명·폴더 이름·ZIP 이름의 남자·여자(남/여도 가능)에 맞는 얼굴로 바꿔 드려요.<br>ZIP이 여러 개면 <b style="color:#e5e7eb;font-weight:600">한꺼번에 끌어다 놓거나</b>, 선택창에서는 하나씩 올려 주세요.</p>
<span class="btn primary">ZIP 파일 선택</span>
</label>
</div>
</div>
<div id="histView" hidden>
<div class="htop" id="htop">
<input class="inp" id="hq" type="search" placeholder="파일명·폴더 검색" aria-label="검색">
<select class="inp" id="hrange" aria-label="기간"><option value="all">전체 기간</option><option value="1">오늘</option><option value="7">최근 7일</option><option value="30">최근 30일</option></select>
<span class="hcount" id="hcount"></span><span class="sp"></span>
<button class="btn sm" id="hall" type="button">전체 선택</button>
<button class="btn sm primary" id="hzip" type="button" disabled>선택 ZIP 다운로드</button>
<button class="btn sm danger" id="hdel" type="button" disabled>선택 지우기</button>
</div>
<div id="hbanner"></div>
<div id="hlist"></div>
<div class="empty2" id="hempty" hidden><b>저장된 결과가 없어요</b><span id="hemptyMsg">작업이 끝나면 여기에 자동으로 쌓여요.</span></div>
</div>
<div id="statsView" hidden>
<div class="htop" id="sTop">
<button class="btn sm" type="button" data-sp="1">오늘</button>
<button class="btn sm" type="button" data-sp="7">7일</button>
<button class="btn sm" type="button" data-sp="30">30일</button>
<button class="btn sm" type="button" data-sp="all">전체</button>
<input class="inp" id="sFrom" type="date" aria-label="시작일"><span class="hcount">~</span><input class="inp" id="sTo" type="date" aria-label="종료일">
<button class="btn sm primary" id="sApply" type="button">기간 적용</button>
<span class="sp"></span>
<button class="btn sm" id="sRefresh" type="button">↻ 새로고침</button>
</div>
<div id="sbanner"></div>
<div class="sbody" id="sbody"></div>
</div>
</main>
</div>
</div>
<div class="gal" id="gal" hidden>
<div class="gal-head"><div class="t" id="galTitle"></div><button class="btn sm" id="galZip" type="button">선택한 컷 ZIP 다운로드</button><button class="btn sm" id="galClose" type="button">닫기</button></div>
<div class="gal-body" id="galBody"></div>
</div>
<div class="lb" id="lb" hidden>
<div class="lb-head"><div class="t" id="lbTitle"></div><a class="btn sm" id="lbDl" href="#">이 결과 다운로드</a><button class="btn sm" id="lbClose" type="button">닫기</button></div>
<div class="lb-tabs" id="lbTabs" role="tablist" aria-label="원본과 결과 보기"></div>
<div class="lb-body"><div class="cmp" id="cmp" title="누르면 원본 ↔ 결과가 바뀌어요"></div></div>
<div class="lb-foot">위 버튼으로 원본·1안·2안을 바꿔 보세요 · 이미지를 누르면 원본 ↔ 결과 전환 · ← → 키로 넘기기 · Esc로 닫기</div>
</div>
<div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
<input id="zipInput" class="vh" type="file" accept=".zip,application/zip,application/x-zip-compressed" tabindex="-1" aria-hidden="true">
<form id="zipForm" method="post" action="/api/swap/zip" hidden><input name="ids"><input name="name"></form>
<script>
(() => {
'use strict';
const $ = (s) => document.querySelector(s);
const IMG_RE = /\.(jpe?g|jfif|png|webp|bmp)$/i;
const SYS_FILES = /^(\.ds_store|thumbs\.db|desktop\.ini)$/i;
const NO_FOLDER = '(폴더 없이 올린 파일)';
// 묶음 기준 = 사진이 직접 들어 있는 폴더(경로 전체). 예) 피카소테스트/1_SPFZG4TU03_50_여자/a.jpg → '피카소테스트/1_SPFZG4TU03_50_여자'
const parentDir = (rel) => ((rel || '').includes('/') ? rel.split('/').slice(0, -1).join('/') : NO_FOLDER);
const folderParts = (path) => { if (path === NO_FOLDER) return { crumb: '', name: path }; const p = path.split('/'); return { crumb: p.slice(0, -1).join(' / '), name: p[p.length - 1] }; };
const folderTitleHTML = (path) => { const f = folderParts(path); return `${f.crumb ? `<span class="crumb">${esc(f.crumb)} /</span>` : ''}<span>${esc(f.name)}</span>`; };
const zipNameOf = (folder, date) => (folder === NO_FOLDER ? `faceswap_${date}` : folderParts(folder).name); // 폴더 ZIP 이름 = 원본 폴더 이름 그대로(날짜 없음)
const cmpFolder = (a, b) => a.localeCompare(b, 'ko', { numeric: true }); // 1, 2, 10, 32 … 자연스러운 번호 순
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const uid = () => (crypto.randomUUID ? crypto.randomUUID() : 'i' + Math.random().toString(36).slice(2) + Date.now().toString(36));
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const fmtSec = (s) => { s = Math.round(s || 0); return s >= 60 ? `${Math.floor(s / 60)}분 ${s % 60}초` : `${s}초`; };
const GNAME = { male: '남자', female: '여자' };
const VARIANTS = Math.min(3, Math.max(1, parseInt(new URLSearchParams(location.search).get('variants'), 10) || 2)); // 파일당 생성 장수(1안·2안) — 기본 2 (관리자용: 주소 뒤에 ?variants=1)
/* ── 아이콘 (lucide) ───────────────────────────────── */
const ICON = {
sparkles: '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/>',
download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
folder: '<path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/>',
imageplus: '<path d="M16 5h6"/><path d="M19 2v6"/><path d="M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/><circle cx="9" cy="9" r="2"/>',
refresh: '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
alert: '<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>',
maximize: '<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" x2="14" y1="3" y2="10"/><line x1="3" x2="10" y1="21" y2="14"/>',
chev: '<path d="m6 9 6 6 6-6"/>',
};
const ic = (n, size = 16) => `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICON[n]}</svg>`;
$('#logo').innerHTML = ic('sparkles', 16); $('#icDrop').innerHTML = ic('folder', 28);
const state = {
items: [],
faces: { male: { id: 'default-male', ok: true }, female: { id: 'default-female', ok: true } },
str: { face: 0.4, hair: 0.4 }, // 변형 강도(얼굴·머리) — 서버 기본값은 init 에서 받아 온다
origView: new Set(), // 카드에서 '원본'을 보고 있는 사진(fileId)
hairText: { male: null, female: null }, // 머리 스타일 설명 (null = 기본값 사용)
inflight: 0, running: false, cancelled: false, defaults: null, health: null, defaultOk: { male: true, female: true },
view: 'work', histStatus: null,
conc: Math.min(4, Math.max(1, parseInt(new URLSearchParams(location.search).get('conc'), 10) || 2)), // 한 번에(동시에) 생성할 장수 — 기본 2장 (관리자용: 주소 뒤에 ?conc=3)
maxConc: 4,
};
/* ── 사용자에게 보여줄 말로 바꾸기 ───────────────────── */
const FRIENDLY_STAGE = {
'대기 중': '곧 시작해요', '이미지 업로드 중': '이미지를 올리는 중', '워크플로우 제출 중': '작업을 보내는 중',
'Comfy 대기열': '차례를 기다리는 중', 'Comfy 대기열 (동시 실행 제한)': '차례를 기다리는 중',
'GPU 준비 중': '준비하는 중', '생성 중': '얼굴을 바꾸는 중', '결과 받는 중': '결과를 받는 중',
};
const friendlyStage = (s) => FRIENDLY_STAGE[s] || s || '처리하는 중';
function friendlyError(msg) {
const m = msg || '';
if (/크레딧|HTTP 402/.test(m)) return 'Comfy 크레딧이 부족해요. 관리자에게 충전을 요청해 주세요.';
if (/API 키|HTTP 401|COMFY_CLOUD_API_KEY/.test(m)) return '서비스 연결 설정에 문제가 있어요. 관리자에게 알려 주세요.';
if (/한도|구독|HTTP 429/.test(m)) return '한꺼번에 처리할 수 있는 한도를 넘었어요. 잠시 뒤 다시 시도해 주세요.';
if (/이미지를 열 수 없|이미지 파일이 아닙니다|빈 파일/.test(m)) return '이미지 파일을 읽을 수 없어요. 다른 파일로 시도해 주세요.';
if (/안에 작업이 끝나지|시간/.test(m)) return '처리 시간이 너무 오래 걸렸어요. 다시 시도해 주세요.';
if (/재시작/.test(m)) return '서버가 다시 시작되어 진행 정보를 잃었어요. 지난 결과에서 확인하거나 다시 시도해 주세요.';
if (/서버에 연결|응답이 없/.test(m)) return '서버와 연결이 끊겼어요. 잠시 뒤 다시 시도해 주세요.';
return '처리하지 못했어요. 다시 시도해 주세요.';
}
/* ── 파일명에서 성별 인식 ─────────────────────────────
맥에서 올린 한글 파일명은 자모가 분리(NFD)돼 있어 NFC로 맞춘 뒤 찾는다. */
function detectGender(name, isFolder = false) {
// 확장자는 빼고 본다. 맥에서 올린 한글 파일명은 자모가 분리(NFD)돼 있어 NFC 로 맞춘 뒤 찾는다.
let n = name.normalize('NFC').toLowerCase();
if (!isFolder) n = n.replace(/\.[a-z0-9]{2,5}$/, '');
// 한 글자(남·여)는 아무 데나 들어 있으면 안 된다(여행·남산 등) →
// 앞뒤가 글자(한글·영문)가 아닌 구분자(_ - 공백 . 숫자 괄호 …)이거나 처음·끝일 때만 성별로 본다.
const token = (words) => new RegExp('(^|[^가-힣a-z])(' + words + ')(?=$|[^가-힣a-z])').test(n);
const f = /여자|여성/.test(n) || token('female|woman|women|여');
const m = /남자|남성/.test(n) || token('male|man|men|남');
if (f && !m) return 'female';
if (m && !f) return 'male';
return null; // 없거나 둘 다 있으면 직접 선택
}
// 파일명에 표기가 있으면 그 성별. 없으면 가까운 폴더부터 위로 올라가며 폴더 이름에서 찾고,
// 그래도 없으면 마지막으로 ZIP 파일 이름(예: 6_SPPPG4VU10_25_여자.zip)을 본다.
// (예: 남자/001.jpg, 촬영/여/a.jpg, 남자/여행/b.jpg → 남자)
function genderFromPath(rel, zipName) {
const parts = rel.split('/');
const byFile = detectGender(parts[parts.length - 1]);
if (byFile) return { g: byFile, from: 'file' };
for (let i = parts.length - 2; i >= 0; i--) {
const byFolder = detectGender(parts[i], true);
if (byFolder) return { g: byFolder, from: 'folder' };
}
if (zipName) {
const byZip = detectGender(zipName.replace(/\.zip$/i, ''), true);
if (byZip) return { g: byZip, from: 'zip' };
}
return { g: null, from: null };
}
const sortItems = () => state.items.sort((a, b) => cmpFolder(a.folder, b.folder) || a.relPath.localeCompare(b.relPath, 'ko', { numeric: true }) || (a.variant - b.variant));
const siblings = (it) => state.items.filter((x) => x.fileId === it.fileId); // 같은 사진의 1안·2안
const hasTwin = (it) => state.items.some((x) => x.fileId === it.fileId && x !== it);
const LOCKED = ['queued', 'sending', 'running', 'cancelling', 'done'];
function addEntries(list) {
let added = 0, folderDerived = 0, zipDerived = 0;
for (const { file, relPath, zipName } of list) {
const rel = relPath.replace(/^\/+/, '');
const name = rel.split('/').pop();
if (!IMG_RE.test(name) || name.startsWith('.')) continue;
const key = `${rel}|${file.size}|${file.lastModified}`;
if (state.items.some((i) => i.key === key)) continue;
const { g, from } = genderFromPath(rel, zipName);
if (from === 'folder') folderDerived++;
if (from === 'zip') zipDerived++;
state.items.push({
id: uid(), key, file, name, relPath: rel,
folder: parentDir(rel),
auto: g, autoFrom: from, gender: g, status: g ? 'idle' : 'needs',
previewUrl: URL.createObjectURL(file), jobId: null, error: '', showErr: false, stageLabel: '', startedAt: 0, elapsed: 0,
fileId: uid(), variant: 1, use: true, prev: null, cancelRequested: false,
});
added++;
}
sortItems();
addEntries.folderDerived = folderDerived; addEntries.zipDerived = zipDerived;
renderAll();
return added;
}
/* ── 올린 결과를 사용자에게 알려주기 (조용히 실패하지 않도록) ── */
function toast(msg, kind = 'info', ms = 7000) {
const el = $('#toast'); if (!el) return;
el.className = `toast ${kind}`; el.textContent = msg; el.hidden = false;
clearTimeout(toast._t); toast._t = setTimeout(() => { el.hidden = true; }, ms);
}
function ingest(list, extra = {}) {
const exOther = extra.other || 0;
if (!list.length && !exOther && !extra.encrypted) { toast('선택한 곳에 파일이 없어요. 이미지가 들어 있는 폴더인지 확인해 주세요.', 'warn'); return; }
const files = list.filter(({ relPath }) => { const n = relPath.split('/').pop(); return !n.startsWith('.') && !SYS_FILES.test(n); });
const imgs = files.filter(({ relPath }) => IMG_RE.test(relPath));
const other = files.filter(({ relPath }) => !IMG_RE.test(relPath));
const otherN = other.length + exOther;
const before = state.items.length;
addEntries(list);
const added = state.items.length - before;
const tail = extra.note ? ` ${extra.note}` : '';
if (!imgs.length) {
if (extra.encrypted) { toast('암호가 걸린 ZIP은 읽을 수 없어요. 암호 없이 다시 압축해 주세요.', 'warn'); return; }
const exts = [...new Set([...other.map(({ relPath }) => extOf(relPath) || '?'), ...(extra.exts || [])].map((x) => x.toUpperCase()))].slice(0, 4).join(', ');
toast(`올릴 수 있는 이미지가 없어요. jpg·png·webp 파일만 가능해요${exts ? ` (찾은 형식: ${exts})` : ''}.`, 'warn');
} else if (!added) {
toast('이미 올린 이미지예요.' + tail, 'info');
} else {
const parts = [`${added}장을 추가했어요`];
if (addEntries.folderDerived > 0) parts.push(`폴더 이름으로 남자·여자를 정한 사진 ${addEntries.folderDerived}장`);
if (addEntries.zipDerived > 0) parts.push(`ZIP 이름으로 남자·여자를 정한 사진 ${addEntries.zipDerived}장`);
if (imgs.length - added > 0) parts.push(`이미 있는 ${imgs.length - added}장은 건너뛰었어요`);
if (otherN) parts.push(`이미지가 아닌 파일 ${otherN}개는 건너뛰었어요`);
if (extra.encrypted) parts.push(`암호가 걸린 파일 ${extra.encrypted}개는 읽지 못했어요`);
toast(parts.join(' · ') + '.' + tail, 'ok', 6000);
}
}
/* ── ZIP 한 개로 올리기 (보안 프로그램이 여러 개 선택을 막을 때) ──
브라우저에서 바로 풀어서 폴더 구조·한글 파일명을 그대로 살린다. 외부 라이브러리는 쓰지 않는다. */
const MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', jfif: 'image/jpeg', png: 'image/png', webp: 'image/webp', bmp: 'image/bmp' };
const extOf = (n) => ((n.match(/\.([^./]+)$/) || [])[1] || '').toLowerCase();
function decodeZipName(bytes, flags) {
if (flags & 0x800) return new TextDecoder('utf-8').decode(bytes);
try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } // 맥·최신 윈도우
catch { try { return new TextDecoder('euc-kr').decode(bytes); } catch { return new TextDecoder().decode(bytes); } } // 예전 윈도우(CP949)
}
async function readZip(zipFile, onProgress) {
const size = zipFile.size;
if (size < 22) throw new Error('ZIP 파일이 아니거나 손상되었어요.');
const tailLen = Math.min(size, 22 + 65535);
const tail = new DataView(await zipFile.slice(size - tailLen, size).arrayBuffer());
let eocd = -1;
for (let i = tailLen - 22; i >= 0; i--) if (tail.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
if (eocd < 0) throw new Error('ZIP 파일이 아니거나 손상되었어요.');
const total = tail.getUint16(eocd + 10, true), cdSize = tail.getUint32(eocd + 12, true), cdOff = tail.getUint32(eocd + 16, true);
if (total === 0xFFFF || cdOff === 0xFFFFFFFF || cdSize === 0xFFFFFFFF) throw new Error('4GB가 넘는 ZIP은 읽을 수 없어요. 나눠서 올려 주세요.');
const cd = new DataView(await zipFile.slice(cdOff, cdOff + cdSize).arrayBuffer());
const entries = []; let p = 0;
while (p + 46 <= cd.byteLength && cd.getUint32(p, true) === 0x02014b50) {
const nameLen = cd.getUint16(p + 28, true), extraLen = cd.getUint16(p + 30, true), cmtLen = cd.getUint16(p + 32, true);
entries.push({
flags: cd.getUint16(p + 8, true), method: cd.getUint16(p + 10, true), time: cd.getUint16(p + 12, true), date: cd.getUint16(p + 14, true),
comp: cd.getUint32(p + 20, true), off: cd.getUint32(p + 42, true),
name: decodeZipName(new Uint8Array(cd.buffer, cd.byteOffset + p + 46, nameLen), cd.getUint16(p + 8, true)).replace(/\\/g, '/').replace(/^\/+/, ''),
});
p += 46 + nameLen + extraLen + cmtLen;
}
const zipBase = zipFile.name.replace(/\.zip$/i, '');
const out = []; let other = 0, encrypted = 0; const exts = [];
const want = entries.filter((e) => !e.name.endsWith('/') && !e.name.startsWith('__MACOSX/'));
let done = 0;
for (const e of want) {
const base = e.name.split('/').pop();
if (base.startsWith('.') || SYS_FILES.test(base)) continue;
if (!IMG_RE.test(base)) { other++; const x = extOf(base); if (x) exts.push(x); continue; }
if (e.flags & 1) { encrypted++; continue; }
if (e.comp === 0xFFFFFFFF || e.off === 0xFFFFFFFF) throw new Error('4GB가 넘는 ZIP은 읽을 수 없어요. 나눠서 올려 주세요.');
const lh = new DataView(await zipFile.slice(e.off, e.off + 30).arrayBuffer());
if (lh.getUint32(0, true) !== 0x04034b50) continue;
const start = e.off + 30 + lh.getUint16(26, true) + lh.getUint16(28, true);
const raw = zipFile.slice(start, start + e.comp);
let blob;
if (e.method === 0) blob = raw;
else if (e.method === 8) {
if (typeof DecompressionStream === 'undefined') throw new Error('이 브라우저에서는 압축된 ZIP을 읽을 수 없어요. 최신 Chrome·Edge로 열어 주세요.');
blob = await new Response(raw.stream().pipeThrough(new DecompressionStream('deflate-raw'))).blob();
} else { other++; continue; }
const t = e.time, d = e.date;
const mtime = new Date((d >> 9) + 1980, ((d >> 5) & 15) - 1, d & 31, t >> 11, (t >> 5) & 63, (t & 31) * 2).getTime();
out.push({ file: new File([blob], base, { type: MIME[extOf(base)] || 'image/jpeg', lastModified: mtime }), relPath: e.name.includes('/') ? e.name : `${zipBase}/${e.name}`, zipName: zipFile.name });
if (onProgress && (++done % 5 === 0)) onProgress(done, want.length);
}
return { list: out, other, encrypted, exts };
}
async function expandZips(list) {
const out = []; const extra = { other: 0, exts: [], encrypted: 0 };
for (const it of list) {
if (/\.zip$/i.test(it.file.name)) {
const r = await readZip(it.file, (n, t) => toast(`ZIP을 읽는 중… ${n}/${t}`, 'info', 60000));
out.push(...r.list); extra.other += r.other; extra.exts.push(...r.exts); extra.encrypted += r.encrypted;
} else out.push(it);
}
return { list: out, extra };
}
async function ingestAsync(list, note) {
try { const r = await expandZips(list); ingest(r.list, { ...r.extra, note }); }
catch (err) { console.error(err); toast(err.message || 'ZIP을 읽지 못했어요.', 'err', 9000); }
}
window.addEventListener('error', (e) => toast(`화면에서 오류가 났어요: ${e.message || '알 수 없는 오류'}`, 'err', 12000));
window.addEventListener('unhandledrejection', (e) => toast(`화면에서 오류가 났어요: ${(e.reason && e.reason.message) || e.reason || '알 수 없는 오류'}`, 'err', 12000));
const fromInput = (files) => [...files].map((f) => ({ file: f, relPath: f.webkitRelativePath || f.name }));
function readAll(reader) {
return new Promise((res, rej) => {
const acc = [];
(function next() { reader.readEntries((b) => { if (!b.length) res(acc); else { acc.push(...b); next(); } }, rej); })();
});
}
async function walk(entry, prefix, out) {
if (entry.isFile) {
const file = await new Promise((res, rej) => entry.file(res, rej));
out.push({ file, relPath: prefix + entry.name });
} else if (entry.isDirectory) {
const kids = await readAll(entry.createReader());
for (const k of kids) await walk(k, prefix + entry.name + '/', out);
}
}
async function fromDrop(dt) {
const entries = [];
for (const it of dt.items || []) { // webkitGetAsEntry 는 await 이전에 모두 호출해야 한다
if (it.kind === 'file') { const e = it.webkitGetAsEntry && it.webkitGetAsEntry(); if (e) entries.push(e); }
}
if (!entries.length) return fromInput(dt.files || []);
const out = [];
for (const e of entries) await walk(e, '', out);
return out;
}
/* ── 렌더링 ─────────────────────────────────────────── */
/* ── 진행률 (서버가 알려주는 단계 → 퍼센트) ───────────── */
const STAGE_PCT = { uploading: 15, submitting: 25, queued_waiting: 35, preparing: 45, downloading: 96 };
const BUSY = ['sending', 'running', 'cancelling'];
function itemProgress(it) {
if (it.status === 'done') return 100;
if (it.status === 'sending') return 8;
if (!BUSY.includes(it.status)) return 0;
const st = it.stage || 'queued_waiting';
if (st === 'executing') { // 실행 중에는 시간에 따라 천천히 차오르게(최대 95%)
const t = Math.max(0, (Date.now() - (it.execStart || Date.now())) / 1000);
return Math.round(50 + 45 * (1 - Math.exp(-t / 70)));
}
return STAGE_PCT[st] ?? 30;
}
function statusLine(it) {
switch (it.status) {
case 'idle': return ['대기', ''];
case 'needs': return ['남자·여자를 선택하세요', 'warn'];
case 'skip': return ['건너뜀', ''];
case 'queued': return ['순서 대기', ''];
case 'sending': return ['보내는 중', 'go'];
case 'running': return [friendlyStage(it.stageLabel), 'go'];
case 'cancelling': return ['취소하는 중…', 'warn'];
case 'cancelled': return ['취소됨', ''];
case 'done': return [`완료 · ${fmtSec(it.elapsed)}`, 'ok'];
case 'error': return [friendlyError(it.error), 'bad'];
}
return ['', ''];
}
function overlayHTML(it) { // 사진 위에 얹는 상태 표시
switch (it.status) {
case 'sending': case 'running':
return `<div class="ph cover"><div class="ring">${ic('sparkles', 15)}</div><div class="t">${esc(friendlyStage(it.stageLabel || '이미지를 보내는 중'))}</div></div>`;
case 'cancelling': return `<div class="ph cover"><div class="t">취소하는 중…</div></div>`;
case 'cancelled': return `<div class="ph cover"><div class="t">취소됨</div></div>`;
case 'error': return `<div class="ph cover err">${ic('alert', 18)}<div class="t" style="color:var(--red)">처리하지 못했어요</div></div>`;
case 'queued': return `<div class="ph cover soft"><div class="t">순서 대기</div></div>`;
case 'skip': return `<div class="ph cover soft"><div class="s">건너뜀</div></div>`;
case 'needs': return `<div class="ph cover soft"><div class="t">남자·여자 선택</div></div>`;
}
return '';
}
function cardHTML(it) { // 폴더 안 사진 1장 = 작은 타일 1개
const [st, cls] = statusLine(it);
const locked = ['queued', 'sending', 'running', 'cancelling', 'done'].includes(it.status);
const seg = ['male', 'female', 'skip'].map((g) => {
const on = g === 'skip' ? it.status === 'skip' : it.gender === g && it.status !== 'skip';
return `<button type="button" class="${on ? 'on' : ''}" data-gender="${g}" ${locked ? 'disabled' : ''}>${g === 'skip' ? '건너뜀' : GNAME[g]}</button>`;
}).join('');
const done = it.status === 'done', busy = BUSY.includes(it.status), pct = itemProgress(it);
const autoNote = it.gender === it.auto ? (it.autoFrom === 'folder' ? '폴더 이름' : it.autoFrom === 'zip' ? 'ZIP 이름' : '') : '';
const twin = hasTwin(it), showOrig = origOn(it);
const vchip = twin ? (done ? `<button type="button" class="vchip pick ${it.use ? 'use' : ''}" data-use title="${it.use ? '내보내기(ZIP)에 쓰는 결과예요' : '누르면 이 결과를 쓰도록 바꿔요'}">${it.use ? `✓ ${it.variant}안 사용` : `${it.variant}안 쓰기`}</button>` : `<span class="vchip">${it.variant}안</span>`) : '';
const row3 = done ? `<div class="row3">${showOrig ? `<a class="btn sm" href="${it.previewUrl}" download="${esc(origFileName(it))}" title="원본 사진을 그대로 받아요">${ic('download', 12)}원본 다운로드</a>` : `<a class="btn sm" href="/api/swap/jobs/${it.jobId}/download">${ic('download', 12)}다운로드</a>`}<button class="btn sm" type="button" data-regen title="이 사진을 새로 다시 생성해요(다른 결과가 나와요)">${ic('refresh', 12)}재생성</button></div>` : '';
const viewSeg = done ? `<div class="seg mini vseg" style="--n:2" role="group" aria-label="결과·원본 보기"><button type="button" class="on" data-resview title="결과를 봐요">결과</button><button type="button" class="${showOrig ? 'view' : ''}" data-orig title="원본 사진을 보고 받을 수 있어요">원본</button></div>` : '';
const actions = done ? ''
: (it.status === 'error' || it.status === 'cancelled') ? `<button class="btn sm" type="button" data-retry>${ic('refresh', 12)}다시 시도</button>`
: (it.status === 'queued' || it.status === 'sending' || it.status === 'running') ? `<button class="btn sm stopbtn" type="button" data-cancel>취소</button>` : '';
return `
<figure class="res ${done ? 'clickable' : ''}" ${done ? 'data-open title="눌러서 원본과 비교"' : ''}>
<img alt="" loading="lazy" decoding="async" src="${showOrig ? it.previewUrl : (done ? `/api/swap/jobs/${it.jobId}/thumb` : it.previewUrl)}">
${done ? `<img class="origthumb" alt="${showOrig ? '결과' : '원본'}" src="${showOrig ? `/api/swap/jobs/${it.jobId}/thumb` : it.previewUrl}"><span class="zoom">${ic('maximize', 14)}</span>${showOrig ? '<span class="gchip">원본</span>' : ''}` : ''}
${!done && it.gender && it.status !== 'skip' ? `<span class="gchip"${autoNote ? ` title="${autoNote}에서 정했어요"` : ''}>${GNAME[it.gender]}${autoNote ? ` (${autoNote === 'ZIP 이름' ? 'ZIP' : '폴더'})` : ''}</span>` : ''}
${overlayHTML(it)}
${vchip}
${busy ? `<div class="cprog" title="진행률"><i data-prog="${it.id}" style="width:${pct}%"></i></div>` : ''}
</figure>
<div class="meta">
<div class="fname" title="${esc(it.relPath)}">${esc(it.name)}</div>
<div class="seg mini" role="group" aria-label="바꿔 넣을 얼굴">${seg}</div>
${viewSeg}
<div class="row2">
<span class="state ${cls}"><i></i><span title="${esc(st)}">${esc(st)}</span>${busy && it.status !== 'cancelling' ? `<em data-ptxt="${it.id}">${pct}%</em>` : ''}</span>
${actions}
</div>
${row3}
${it.status === 'error' ? `<div><button class="linkbtn" type="button" data-detail>${it.showErr ? '자세히 접기' : '자세히 보기'}</button>${it.showErr ? `<div class="errbox">${esc(it.error)}</div>` : ''}</div>` : ''}
</div>`;
}
/* ── 같은 사진의 여러 컷(1안·2안)은 카드 한 장으로 묶어 보여준다 (데이터는 컷마다 따로 돈다) ── */
const ACTIVE = ['queued', 'sending', 'running', 'cancelling'];
// 결과 다운로드 주소. tag(1안·2안)를 주면 서버가 파일명 끝에 붙여 준다(같은 사진의 컷이 같은 이름으로 겹치지 않게). 컷이 하나뿐이면 tag 없이.
const dlUrl = (id, tag) => `/api/swap/jobs/${id}/download${tag ? `?tag=${encodeURIComponent(tag)}` : ''}`;
const origOn = (it) => state.origView.has(it.fileId) && it.status === 'done'; // 카드에서 원본을 보여 줄지
const origFileName = (it) => { const n = it.name || it.relPath.split('/').pop(); return /\.[^./]+$/.test(n) ? n.replace(/(\.[^./]+)$/, '_원본$1') : `${n}_원본`; };
function setOrigView(it, on) { if (on) state.origView.add(it.fileId); else state.origView.delete(it.fileId); updateItem(it); }
function curOf(arr) { // 카드에 보여줄 컷: 고른 컷(재생성 중이어도) → 아니면 먼저 끝난 컷
const prim = arr.find((x) => x.use) || arr[0];
if (prim.status === 'done' || prim.prev) return prim;
return arr.find((x) => x.status === 'done') || prim;
}
const groupProgress = (arr) => { const xs = arr.filter((x) => x.status !== 'skip'); return xs.length ? Math.round(xs.reduce((a, x) => a + itemProgress(x), 0) / xs.length) : 0; };
function groupStatus(arr, cur) {
const n = arr.length, done = arr.filter((x) => x.status === 'done').length;
const active = arr.filter((x) => ACTIVE.includes(x.status)), failed = arr.filter((x) => x.status === 'error' || x.status === 'cancelled');
if (done === n) return [`완료 · ${fmtSec(cur.elapsed)}`, 'ok'];
if (active.length) return active.every((x) => x.status === 'cancelling') ? ['취소하는 중…', 'warn'] : [`만드는 중 · ${done}/${n}컷 완료`, 'go'];
if (failed.length) return done ? [`${done}컷 완료 · ${failed.length}컷 ${failed.some((x) => x.status === 'error') ? '실패' : '취소됨'}`, 'bad'] : statusLine(failed[0]);
return statusLine(cur);
}
function groupHTML(arr) {
if (arr.length < 2) return cardHTML(arr[0]);
const cur = curOf(arr), n = arr.length;
const [st, cls] = groupStatus(arr, cur);
const done = cur.status === 'done', showOrig = origOn(cur);
const active = arr.filter((x) => ACTIVE.includes(x.status)), failed = arr.filter((x) => x.status === 'error' || x.status === 'cancelled');
const busy = active.some((x) => x.status !== 'cancelling'), pct = groupProgress(arr);
const started = arr.some((x) => !['idle', 'needs', 'skip'].includes(x.status));
const locked = arr.some((x) => LOCKED.includes(x.status));
const seg = ['male', 'female', 'skip'].map((g) => {
const on = g === 'skip' ? cur.status === 'skip' : cur.gender === g && cur.status !== 'skip';
return `<button type="button" class="${on ? 'on' : ''}" data-gender="${g}" ${locked ? 'disabled' : ''}>${g === 'skip' ? '건너뜀' : GNAME[g]}</button>`;
}).join('');
const ovBtn = `<button type="button" class="${showOrig ? 'view' : ''}" data-orig ${done ? '' : 'disabled'} title="${done ? '원본 사진을 보고 받을 수 있어요 (내보내기에 쓰는 컷 선택은 그대로예요)' : '컷이 끝나면 볼 수 있어요'}">원본</button>`;
const vseg = arr.map((x) => {
const d = x.status === 'done', mark = d ? '' : ACTIVE.includes(x.status) ? ' …' : (x.status === 'error' || x.status === 'cancelled') ? ' ✕' : '';
return `<button type="button" class="${d && x.use ? 'on' : ''}" data-pick="${x.id}" ${d ? '' : 'disabled'} title="${d ? (x.use ? '내보내기(ZIP)에 쓰는 컷이에요' : '누르면 이 컷을 보고 내보내기에 써요') : '아직 끝나지 않았어요'}">${x.variant}안${mark}</button>`;
}).join('');
const autoNote = cur.gender === cur.auto ? (cur.autoFrom === 'folder' ? '폴더 이름' : cur.autoFrom === 'zip' ? 'ZIP 이름' : '') : '';
const lead = [...active].sort((a, b) => itemProgress(b) - itemProgress(a))[0];
const overlay = done ? '' : overlayHTML(lead || failed[0] || cur);
const row3 = done ? `<div class="row3">${showOrig ? `<a class="btn sm" href="${cur.previewUrl}" download="${esc(origFileName(cur))}" title="원본 사진을 그대로 받아요">${ic('download', 12)}원본 다운로드</a>` : `<a class="btn sm" href="${dlUrl(cur.jobId, `${cur.variant}안`)}" title="${cur.variant}안 결과를 받아요(파일명 끝에 _${cur.variant}안이 붙어요)">${ic('download', 12)}다운로드</a>`}<button class="btn sm" type="button" data-regen title="${showOrig ? `내보내기에 쓰는 컷(${cur.variant}안)을 새로 다시 생성해요(다른 결과가 나와요)` : '보고 있는 컷을 새로 다시 생성해요(다른 결과가 나와요)'}">${ic('refresh', 12)}재생성</button></div>` : '';
const actions = active.length ? `<button class="btn sm stopbtn" type="button" data-cancel>취소</button>`
: failed.length ? `<button class="btn sm" type="button" data-retry>${ic('refresh', 12)}다시 시도</button>` : '';
const errItem = !active.length ? failed.find((x) => x.status === 'error') : null;
return `
<figure class="res ${done ? 'clickable' : ''}" ${done ? 'data-open title="눌러서 원본과 비교"' : ''}>
<img alt="" loading="lazy" decoding="async" src="${showOrig ? cur.previewUrl : (done ? `/api/swap/jobs/${cur.jobId}/thumb` : cur.previewUrl)}">
${done ? `<img class="origthumb" alt="${showOrig ? '결과' : '원본'}" src="${showOrig ? `/api/swap/jobs/${cur.jobId}/thumb` : cur.previewUrl}"><span class="zoom">${ic('maximize', 14)}</span>${showOrig ? '<span class="gchip">원본</span>' : ''}` : ''}
${!done && cur.gender && cur.status !== 'skip' ? `<span class="gchip"${autoNote ? ` title="${autoNote}에서 정했어요"` : ''}>${GNAME[cur.gender]}${autoNote ? ` (${autoNote === 'ZIP 이름' ? 'ZIP' : '폴더'})` : ''}</span>` : ''}
${overlay}
<span class="cutbadge">${n}컷</span>
${busy ? `<div class="cprog" title="진행률"><i data-prog="${cur.fileId}" style="width:${pct}%"></i></div>` : ''}
</figure>
<div class="meta">
<div class="fname" title="${esc(cur.relPath)}">${esc(cur.name)}</div>
<div class="seg mini" role="group" aria-label="바꿔 넣을 얼굴">${seg}</div>
${started ? `<div class="seg mini vseg" style="--n:${n + 1}" role="group" aria-label="원본·컷 선택">${ovBtn}${vseg}</div>` : ''}
<div class="row2">
<span class="state ${cls}"><i></i><span title="${esc(st)}">${esc(cls === 'go' ? st.split(' · ')[0] : st)}</span>${busy ? `<em data-ptxt="${cur.fileId}">${pct}%</em>` : ''}</span>
${actions}
</div>
${row3}
${errItem ? `<div><button class="linkbtn" type="button" data-detail="${errItem.id}">${errItem.showErr ? '자세히 접기' : '자세히 보기'}</button>${errItem.showErr ? `<div class="errbox">${esc(errItem.error)}</div>` : ''}</div>` : ''}
</div>`;
}
const groupClass = (arr, cur) => `card ${cur.status === 'error' && !arr.some((x) => x.status === 'done') ? 'is-error' : ''}`;
const cardClass = (it) => `card ${it.status === 'error' ? 'is-error' : ''} ${it.status === 'done' && it.use && hasTwin(it) ? 'used' : ''}`;
function renderAll() {
const folders = new Map();
for (const it of state.items) { if (!folders.has(it.folder)) folders.set(it.folder, []); folders.get(it.folder).push(it); }
$('#folders').innerHTML = [...folders.entries()].map(([name, items]) => `
<section class="folder" data-folder="${esc(name)}">
<div class="folder-head">
<h3 title="${esc(name.replace(/\//g, ' / '))}">${ic('folder', 16)}${folderTitleHTML(name)}</h3><span class="cnt" data-cnt>${new Set(items.map((i) => i.fileId)).size}장</span><span class="sp"></span>
<button class="btn sm" type="button" data-zip ${items.some((i) => i.status === 'done') ? '' : 'disabled'}>${ic('download', 13)}이 폴더 ZIP</button>
<button class="btn sm danger" type="button" data-remove>폴더 빼기</button>
</div>
<div class="grid">${(() => { const sets = new Map(); for (const it of items) { if (!sets.has(it.fileId)) sets.set(it.fileId, []); sets.get(it.fileId).push(it); }
return [...sets.values()].map((arr) => { const cur = curOf(arr); return `<article class="${groupClass(arr, cur)}" data-id="${cur.id}" data-fid="${cur.fileId}">${groupHTML(arr)}</article>`; }).join(''); })()}</div>
</section>`).join('');
$('#empty').hidden = state.items.length > 0;
syncTop();
updateSummary();
}
function updateItem(it) {
const el = document.querySelector(`.card[data-fid="${it.fileId}"]`);
if (!el) return renderAll();
const arr = siblings(it), cur = curOf(arr);
el.dataset.id = cur.id; el.className = groupClass(arr, cur);
el.innerHTML = groupHTML(arr);
const sec = el.closest('.folder');
if (sec) {
const mine = state.items.filter((i) => i.folder === sec.dataset.folder);
sec.querySelector('[data-zip]').disabled = !mine.some((i) => i.status === 'done');
}
updateSummary();
}
const count = (s) => state.items.filter((i) => s.includes(i.status)).length;
const concurrency = () => Math.min(state.maxConc, Math.max(1, state.conc));
function etaText() {
const done = state.items.filter((i) => i.status === 'done' && i.elapsed);
const left = count(['queued', 'sending', 'running']);
if (!done.length || !left) return '';
const avg = done.reduce((a, i) => a + i.elapsed, 0) / done.length;
const min = Math.max(1, Math.round((Math.ceil(left / concurrency()) * avg) / 60));
return `약 ${min}분 남았어요`;
}
function renderBanners() {
const parts = [];
if (state.health && !state.health.ok) parts.push(`<div class="note err">${ic('alert', 16)}<div class="grow">${esc(state.health.error || 'AI 서비스 연결 설정이 필요해요. 관리자에게 알려 주세요.')}</div></div>`);
const needs = count(['needs']);
if (needs) parts.push(`<div class="note warn">${ic('alert', 16)}<div class="grow"><b>${needs}장</b>은 파일명에서 남자·여자를 알 수 없어요. 카드에서 하나씩 고르거나, 한 번에 정할 수 있어요.<div class="row">
<button class="btn sm" type="button" data-bulk="male">모두 남자로</button><button class="btn sm" type="button" data-bulk="female">모두 여자로</button><button class="btn sm" type="button" data-bulk="skip">모두 건너뛰기</button></div></div></div>`);
$('#banners').innerHTML = parts.join('');
}
/* ── 전체 진행 막대 ─────────────────────────────────── */
function overallStats() {
const items = state.items.filter((i) => i.status !== 'skip');
const n = items.length;
let done = 0, run = 0, bad = 0, can = 0;
for (const it of items) {
if (it.status === 'done') done += 1;
else if (BUSY.includes(it.status)) run += itemProgress(it) / 100;
else if (it.status === 'error') bad += 1;
else if (it.status === 'cancelled') can += 1;
}
return { n, done, run, bad, can, pct: n ? Math.min(100, Math.round(((done + run) / n) * 100)) : 0 };
}
function renderOverallBar() {
const o = overallStats(); if (!o.n) { $('#pbar').innerHTML = ''; $('#pct').textContent = '0%'; return o; }
const w = (x) => `${((x / o.n) * 100).toFixed(2)}%`;
$('#pbar').innerHTML = `<i class="done" style="width:${w(o.done)}"></i><i class="run" style="width:${w(o.run)}"></i><i class="bad" style="width:${w(o.bad)}"></i><i class="can" style="width:${w(o.can)}"></i>`;
$('#pct').textContent = `${o.pct}%`;
return o;
}
function tickProgress() { // 1초마다 막대만 가볍게 갱신
let any = false;
for (const it of state.items) {
if (!BUSY.includes(it.status)) continue;
any = true;
const pct = itemProgress(it);
const bar = document.querySelector(`[data-prog="${it.id}"]`); if (bar) bar.style.width = `${pct}%`;
const tx = document.querySelector(`[data-ptxt="${it.id}"]`); if (tx) tx.textContent = `${pct}%`;
}
for (const fid of new Set(state.items.filter((i) => BUSY.includes(i.status)).map((i) => i.fileId))) { // 묶음 카드: 컷들의 평균
const pct = groupProgress(state.items.filter((i) => i.fileId === fid));
const bar = document.querySelector(`[data-prog="${fid}"]`); if (bar) bar.style.width = `${pct}%`;
const tx = document.querySelector(`[data-ptxt="${fid}"]`); if (tx) tx.textContent = `${pct}%`;
}
if (any) { renderOverallBar(); updateSumText(); }
}
setInterval(tickProgress, 1000);
function updateSumText() {
const total = state.items.length;
const idle = count(['idle']), needs = count(['needs']), done = count(['done']);
const faceMissing = ['male', 'female'].filter((g) => !state.faces[g].ok && state.items.some((i) => i.gender === g && ['idle', 'queued'].includes(i.status)));
const o = overallStats(), eta = etaText();
$('#sum').innerHTML = state.running ? ''
: faceMissing.length ? `<b>${faceMissing.map((g) => GNAME[g]).join('·')}</b> 얼굴 사진이 서버에 없어서 시작할 수 없어요. 관리자에게 알려 주세요.`
: needs ? `남자·여자가 정해지지 않은 <b>${needs}장</b>은 건너뛰고 시작해요.` + (idle ? strengthNote() : '')
: idle ? (VARIANTS > 1 ? `<b>${idle}장</b> × ${VARIANTS}안 = <b>${idle * VARIANTS}번</b> 생성돼요. Comfy 크레딧이 그만큼 사용돼요.` : `<b>${idle}장</b>을 처리하면 Comfy 크레딧이 사용돼요.`) + strengthNote() : '';
}
function updateSummary() {
const total = state.items.length;
const idle = count(['idle']), needs = count(['needs']), done = count(['done']), err = count(['error']), can = count(['cancelled']);
const active = count(['queued', 'sending', 'running', 'cancelling']), skip = count(['skip']);
const targets = total - skip;
$('#addZip').hidden = total === 0;
const eta = etaText();
const started = done + active + err + can > 0; // 작업을 시작하기 전에는 진행 막대를 숨긴다
$('.barrow').hidden = !started;
const files = new Set(state.items.filter((i) => i.status !== 'skip').map((i) => i.fileId)).size;
const sub = [VARIANTS > 1 && files ? `사진 ${files}장 × ${VARIANTS}안` : '', eta].filter(Boolean).join(' · ');
$('#sumLine').innerHTML = started && targets ? `${done} / ${targets}장 완료${sub ? `<small>${sub}</small>` : ''}` : `사진 ${new Set(state.items.map((i) => i.fileId)).size}장`;
$('#chips').innerHTML =
(state.running ? `<span class="chip">한 번에 ${concurrency()}장씩</span>` : '') +
(active ? `<span class="chip go">진행 중 ${active}</span>` : '') +
(idle ? `<span class="chip">시작 전 ${idle}</span>` : '') +
(needs ? `<span class="chip warn">남자·여자 선택 필요 ${needs}</span>` : '') +
(err ? `<span class="chip bad">실패 ${err}</span>` : '') +
(can ? `<span class="chip">취소 ${can}</span>` : '') +
(skip ? `<span class="chip">건너뜀 ${skip}</span>` : '');
renderOverallBar();
$('#zipAll').disabled = done === 0;
$('#retry').hidden = (err + can) === 0 || state.running;
renderBanners();
const faceMissing = ['male', 'female'].filter((g) => !state.faces[g].ok && state.items.some((i) => i.gender === g && ['idle', 'queued'].includes(i.status)));
const go = $('#go');
go.disabled = state.running || idle === 0 || faceMissing.length > 0 || !!(state.health && !state.health.ok);
go.innerHTML = state.running ? `<span class="spin">${ic('refresh', 15)}</span>얼굴을 바꾸는 중…`
: idle ? `${ic('sparkles', 15)}${idle}장 얼굴 교체 시작` : total ? (done ? '모두 끝났어요' : '시작할 이미지가 없어요') : '이미지를 올려 주세요';
$('#stop').hidden = !state.running;
updateSumText();
renderBulk();
}
/* ── 실행 큐 ────────────────────────────────────────── */
const fmt2 = (v) => Number(v).toFixed(2);
const defHair = (g) => (state.defaults && state.defaults.hair_desc && state.defaults.hair_desc[g]) || '';
const hairText = (g) => { const v = state.hairText[g]; return (v !== null && v !== undefined) ? v : (state.faces[g].custom ? '' : defHair(g)); };
function strengthNote() {
const d = state.defaults; if (!d) return '';
return d.graded ? ` 변형 강도는 얼굴 <b>${fmt2(state.str.face)}</b> · 머리 <b>${fmt2(state.str.hair)}</b>예요.` : ` 변형 강도는 <b>${fmt2(state.str.face)}</b>예요.`;
}
// 작업에 실어 보내는 설정. 서버가 성별과 합쳐 프롬프트를 만든다(값을 못 받아 왔으면 서버 기본값을 그대로 쓴다).
function settings(g) {
const s = {}, d = state.defaults;
if (d) { if (d.graded) { s.face_strength = state.str.face; s.hair_strength = state.str.hair; } else { s.denoise = state.str.face; } }
if (g) s.hair_desc = hairText(g);
return s;
}
const resetItem = (it) => { it.status = 'queued'; it.error = ''; it.cancelRequested = false; it.stage = ''; it.execStart = 0; it.jobId = null; };
function startAll() {
state.cancelled = false; state.running = true;
const extra = [];
for (const it of state.items) {
if (it.status !== 'idle') continue;
it.status = 'queued';
if (it.variant === 1 && !hasTwin(it)) { // 처음 시작하는 사진은 2안(시드가 다른 작업)을 하나 더 만든다
for (let v = 2; v <= VARIANTS; v++) extra.push({ ...it, id: uid(), key: `${it.key}#${v}`, variant: v, use: false, status: 'queued', jobId: null, error: '', showErr: false, stageLabel: '', stage: '', startedAt: 0, elapsed: 0, execStart: 0, cancelRequested: false, prev: null });
}
}
state.items.push(...extra); sortItems();
renderAll(); pump();
}
/* ── 재생성 / 결과 고르기 ───────────────────────────── */
function restorePrev(it, why) { // 재생성이 취소·실패하면 이전 결과를 되돌린다
if (!it.prev) return false;
it.status = 'done'; it.jobId = it.prev.jobId; it.elapsed = it.prev.elapsed; it.prev = null; it.error = ''; it.stage = ''; it.cancelRequested = false;
if (why) toast(why === 'cancelled' ? '재생성을 취소해서 이전 결과를 그대로 뒀어요.' : '재생성에 실패해서 이전 결과를 그대로 뒀어요.', 'warn', 6000);
return true;
}
function regen(it) {
if (it.status !== 'done') return;
it.prev = { jobId: it.jobId, elapsed: it.elapsed };
state.origView.delete(it.fileId);
resetItem(it); state.cancelled = false; state.running = true;
updateItem(it); pump();
}
function useVariant(it) {
state.origView.delete(it.fileId); // 컷을 고르면 원본 보기는 끝
for (const x of siblings(it)) x.use = x === it;
siblings(it).forEach(updateItem);
}
function exportIds(items) { // 사진마다 '쓰기로 한 결과' 하나만 내보낸다 (1안·2안이 같은 파일명으로 겹치지 않게)
const by = new Map();
for (const it of items) {
if (it.status !== 'done') continue;
const cur = by.get(it.fileId);
if (!cur || (it.use && !cur.use)) by.set(it.fileId, it);
}
return [...by.values()].map((i) => i.jobId);
}
function pump() {
if (state.cancelled) return maybeFinish();
while (state.inflight < concurrency()) {
const it = state.items.find((i) => i.status === 'queued');
if (!it) break;
state.inflight++; it.status = 'sending'; it.startedAt = Date.now(); updateItem(it);
runItem(it).finally(() => { state.inflight--; pump(); });
}
maybeFinish();
}
let softToastAt = 0;
function maybeFinish() {
if (state.running && !state.items.some((i) => ['queued', 'sending', 'running', 'cancelling'].includes(i.status))) {
state.running = false; updateSummary();
if (state.cancelled && Date.now() - softToastAt > 10000) toast('취소했어요. 취소한 이미지는 ‘다시 시도’로 처음부터 할 수 있어요.', 'ok', 5000); // 'Cloud 에서 계속 진행' 경고가 떠 있으면 덮어쓰지 않는다
}
}
/* ── 취소 ───────────────────────────────────────────── */
async function postCancel(ids) {
ids = ids.filter(Boolean); if (!ids.length) return;
try { await fetch('/api/swap/cancel', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids }) }); }
catch { toast('취소 요청을 보내지 못했어요. 잠시 뒤 다시 눌러 주세요.', 'warn'); }
}
function notifySoft() {
if (Date.now() - softToastAt < 8000) return; softToastAt = Date.now();
toast('Comfy Cloud에서 이미 실행 중이던 작업은 끝까지 진행될 수 있어요. 결과는 버렸고, 크레딧이 일부 쓰였을 수 있어요.', 'warn', 9000);
}
function cancelAll() {
if (!state.running) return;
softToastAt = 0; state.cancelled = true;
const ids = [];
for (const it of state.items) {
if (it.status === 'queued') { if (!restorePrev(it)) it.status = 'idle'; } // 아직 보내지 않은 건 대기(재생성 중이던 건 이전 결과)로 되돌림
else if (it.status === 'sending') { it.cancelRequested = true; it.status = 'cancelling'; }
else if (it.status === 'running') { it.cancelRequested = true; it.status = 'cancelling'; ids.push(it.jobId); }
}
renderAll(); postCancel(ids);
toast('취소하는 중이에요. 잠시만 기다려 주세요.', 'info', 4000);
maybeFinish();
}
function cancelItem(it) {
softToastAt = 0;
if (it.status === 'queued') { if (!restorePrev(it)) it.status = 'idle'; return updateItem(it); }
if (it.status === 'sending') { it.cancelRequested = true; it.status = 'cancelling'; return updateItem(it); }
if (it.status === 'running') { it.cancelRequested = true; it.status = 'cancelling'; updateItem(it); postCancel([it.jobId]); }
}
async function runItem(it) {
try {
const fd = new FormData();
fd.append('image', it.file, it.name);
fd.append('rel_path', it.relPath);
fd.append('gender', it.gender);
fd.append('face_id', state.faces[it.gender].id);
fd.append('settings', JSON.stringify(settings(it.gender)));
if (it.prev) fd.append('regen', '1'); // 마음에 안 들어 다시 만든 작업(통계에 재생성으로 기록)
const r = await fetch('/api/swap/jobs', { method: 'POST', body: fd });
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || `서버 오류 (HTTP ${r.status})`); }
it.jobId = (await r.json()).jobId;
if (it.cancelRequested) { it.status = 'cancelling'; updateItem(it); await postCancel([it.jobId]); } // 보내는 중에 취소를 눌렀다면 바로 취소
else { it.status = 'running'; it.stageLabel = '대기 중'; it.stage = 'queued_waiting'; updateItem(it); }
let misses = 0;
for (;;) {
await sleep(it.status === 'cancelling' ? 1000 : 3000);
let res;
try { res = await fetch(`/api/swap/jobs/${it.jobId}`); } catch { if (++misses > 10) throw new Error('서버 응답이 없습니다.'); continue; }
if (res.status === 404) throw new Error('작업 정보를 잃어버렸습니다 (서버가 재시작됨). 다시 시도해주세요.');
if (!res.ok) { if (++misses > 10) throw new Error(`서버 오류 (HTTP ${res.status})`); continue; }
misses = 0;
const j = await res.json();
if (j.stage === 'executing' && !it.execStart) it.execStart = Date.now();
it.stage = j.stage;
if (j.status === 'cancelled') { it.status = 'cancelled'; if (j.cancelMode === 'soft') notifySoft(); break; }
if (j.status === 'done') { it.status = 'done'; it.elapsed = j.elapsedSec; refreshStatus(); break; }
if (j.status === 'error') throw new Error(j.error || '처리에 실패했습니다.');
if (j.stageLabel !== it.stageLabel) { it.stageLabel = j.stageLabel; if (it.status !== 'cancelling') updateItem(it); }
}
} catch (e) {
if (it.cancelRequested) it.status = 'cancelled'; else { it.status = 'error'; it.error = e.message || String(e); }
}
if (it.prev && (it.status === 'error' || it.status === 'cancelled')) restorePrev(it, it.status);
else if (it.status === 'done') it.prev = null;
updateItem(it);
}
/* ── 라이트박스: 원본 · 1안 · 2안 … 버튼으로 바꿔 보기 ──────────────── */
let cmpS = null; // { shots:[{label,url,dl,hint}], i:지금 보는 것(-1=원본), last:마지막으로 본 결과 }
function showShot(k) {
const S = cmpS; if (!S) return;
S.i = k; if (k >= 0) S.last = k;
const box = $('#cmp');
box.querySelectorAll('img').forEach((im) => { im.style.visibility = im.dataset.k === String(k) ? 'visible' : 'hidden'; });
$('#lbTabs').querySelectorAll('button').forEach((b) => { const on = b.dataset.k === String(k); b.classList.toggle('on', on); b.setAttribute('aria-selected', String(on)); });
const tag = box.querySelector('.tag'); if (tag) tag.textContent = k < 0 ? '원본' : S.shots[k].label;
const dl = $('#lbDl');
if (k < 0) { // 원본 탭: 받을 수 있는 원본이 있으면 '원본 다운로드'
dl.hidden = !S.origDl;
if (S.origDl) { dl.href = S.origDl.href; dl.setAttribute('download', S.origDl.name); dl.textContent = S.origDl.label || '원본 다운로드'; }
} else { dl.hidden = false; dl.href = S.shots[k].dl; dl.removeAttribute('download'); dl.textContent = '이 결과 다운로드'; }
}
// shots: 결과 목록(1안·2안…). 하나만 있으면 after/dl 로도 열 수 있다. start: 처음 보여 줄 결과 번호(0부터)
function openCompare({ title, before, after, dl, shots, start = 0, origDl = null, startOrig = false }) {
const list = (shots && shots.length) ? shots : [{ label: '결과', url: after, dl }];
cmpS = { shots: list, i: -1, last: Math.min(Math.max(start, 0), list.length - 1), origDl };
$('#lbTitle').textContent = title;
// 모든 이미지를 겹쳐서 미리 불러 둔다 → 버튼을 눌러도 깜빡임 없이 바로 바뀐다
$('#cmp').innerHTML = `<img class="a" data-k="-1" alt="원본" src="${before}">` + list.map((x, k) => `<img class="b" data-k="${k}" alt="${esc(x.label)}" src="${x.url}">`).join('') + '<span class="tag l"></span>';
$('#lbTabs').innerHTML = [`<button type="button" role="tab" data-k="-1">원본</button>`, ...list.map((x, k) => `<button type="button" role="tab" data-k="${k}"${x.hint ? ` title="${esc(x.hint)}"` : ''}>${esc(x.label)}</button>`)].join('');
$('#lb').hidden = false;
document.body.style.overflow = 'hidden';
showShot(startOrig ? -1 : cmpS.last);
}
// 작업 탭: 같은 사진에서 끝난 1안·2안을 모두 보여 주고, 누른 카드의 컷에서 시작한다
const openLightbox = (it, startOrig = false) => {
const done = siblings(it).filter((x) => x.status === 'done' && x.jobId).sort((a, b) => a.variant - b.variant);
const list = done.length ? done : [it];
const shots = list.map((x) => ({ label: VARIANTS > 1 ? `${x.variant}안` : '결과', url: `/api/swap/jobs/${x.jobId}/view`, dl: dlUrl(x.jobId, VARIANTS > 1 ? `${x.variant}안` : '') }));
openCompare({ title: it.relPath, before: it.previewUrl, shots, start: Math.max(0, list.findIndex((x) => x.id === it.id)), origDl: { href: it.previewUrl, name: origFileName(it), label: '원본 다운로드' }, startOrig });
};
function closeLightbox() { $('#lb').hidden = true; $('#cmp').innerHTML = ''; $('#lbTabs').innerHTML = ''; cmpS = null; document.body.style.overflow = $('#gal').hidden ? '' : 'hidden'; }
(function bindCompare() {
$('#lbTabs').addEventListener('click', (e) => { const b = e.target.closest('button[data-k]'); if (b) showShot(parseInt(b.dataset.k, 10)); });
$('#cmp').addEventListener('click', () => { if (cmpS) showShot(cmpS.i < 0 ? cmpS.last : -1); }); // 이미지를 누르면 원본 ↔ 마지막으로 본 결과
document.addEventListener('keydown', (e) => {
if ($('#lb').hidden || !cmpS || (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft')) return;
const order = [-1, ...cmpS.shots.map((_, k) => k)], pos = order.indexOf(cmpS.i);
showShot(order[Math.min(order.length - 1, Math.max(0, pos + (e.key === 'ArrowRight' ? 1 : -1)))]);
e.preventDefault();
});
})();
/* ── ZIP ────────────────────────────────────────────── */
function submitZip(ids, name) {
if (!ids.length) return;
const f = $('#zipForm');
f.ids.value = ids.join(','); f.name.value = name;
f.submit();
}
const downloadZip = (items, name) => submitZip(exportIds(items), name);
/* ── 탭 / 지난 결과 ─────────────────────────────────── */
const hist = { items: [], sel: new Set(), loaded: false };
const syncTop = () => { const show = state.view === 'work' && state.items.length > 0; $('#top').hidden = !show; $('.stick').hidden = !show; };
function setView(v) {
state.view = v;
document.querySelectorAll('.pill').forEach((b) => b.classList.toggle('on', b.dataset.view === v));
$('#workView').hidden = v !== 'work'; $('#histView').hidden = v !== 'hist'; $('#statsView').hidden = v !== 'stats';
syncTop();
if (v === 'hist') loadHistory();
if (v === 'stats') loadStats();
}
document.querySelectorAll('.pill').forEach((b) => { b.onclick = () => setView(b.dataset.view); });
/* ── 통계 대시보드: 생성 기록(지난 결과 기록)을 기간별로 집계해 보여준다. 완료된 생성만 센다(실패·취소 제외) ── */
const stats = { preset: '30', from: '', to: '', data: null, moreFolders: false, moreRecent: false, loading: false, init: false };
const sRange = (p) => (p === 'all' ? { from: '', to: '' } : { from: kstDay(p === '1' ? 0 : Number(p) - 1), to: kstDay(0) });
const sUser = (u) => (u.username === '' ? '미기록' : u.username === 'anonymous' ? '비로그인' : (u.name || u.username));
const sFmt = (n) => Number(n || 0).toLocaleString();
function sSetPreset(p) {
stats.preset = p; Object.assign(stats, sRange(p));
$('#sFrom').value = stats.from; $('#sTo').value = stats.to;
document.querySelectorAll('[data-sp]').forEach((b) => b.classList.toggle('primary', b.dataset.sp === p));
}
async function loadStats() {
if (stats.loading) return;
if (!stats.init) { stats.init = true; sSetPreset(stats.preset); }
stats.loading = true;
try {
const r = await fetch(`/api/dashboard?${new URLSearchParams({ from: stats.from, to: stats.to })}`);
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || `서버 오류 (HTTP ${r.status})`); }
stats.data = await r.json(); renderStats();
} catch (e) { $('#sbody').innerHTML = `<div class="spanel snote">통계를 불러오지 못했어요: ${esc(e.message)}</div>`; }
finally { stats.loading = false; }
}
function sDays(d) { // 기록이 없는 날도 0 으로 채워 흐름을 보이게(최대 1년)
if (!d.daily.length) return [];
const map = new Map(d.daily.map((x) => [x.day, x]));
const a = new Date(d.daily[0].day + 'T00:00:00Z'), b = new Date(d.daily[d.daily.length - 1].day + 'T00:00:00Z');
if ((b - a) / 86400000 > 365) return d.daily;
const out = []; for (let t = a; t <= b; t = new Date(t.getTime() + 86400000)) { const k = t.toISOString().slice(0, 10); out.push(map.get(k) || { day: k, gen: 0, regen: 0 }); }
return out;
}
function renderStats() {
const d = stats.data, s = d.summary, body = $('#sbody');
const notes = ['완료된 생성만 집계해요(실패·취소한 작업은 제외). 목록에서 숨긴 결과도 포함돼요.'];
if (!d.durable) notes.unshift('지금은 임시 저장이라 서버가 다시 시작되면 통계도 사라져요. 관리자에게 HF_TOKEN·HF_DATASET_REPO 설정을 요청하세요.');
if (s.legacy_rows) notes.push(`${sFmt(s.legacy_rows)}건은 사용자 기록 기능 이전에 만든 결과라 사용자가 '미기록'으로 표시돼요.`);
$('#sbanner').innerHTML = `<div class="snote" style="padding:14px 28px 0">${notes.map(esc).join('<br>')}</div>`;
if (!s.gen) { body.innerHTML = '<div class="spanel snote" style="text-align:center;padding:40px">이 기간에 생성 기록이 없어요.</div>'; return; }
const cards = [
['총 생성', sFmt(s.gen), '건', `사진 ${sFmt(s.files)}장 · 사진당 평균 ${(s.gen / Math.max(s.files, 1)).toFixed(1)}컷`],
['재생성', sFmt(s.regen), '건', `전체의 ${Math.round(s.regen / s.gen * 100)}%`],
['사용자', sFmt(s.users), '명', s.users ? '' : '로그인 기록 없음'],
['활동 일수', sFmt(s.days), '일', s.first_day ? `${s.first_day} ~ ${s.last_day}` : ''],
['평균 소요', s.avg_elapsed == null ? '-' : s.avg_elapsed, s.avg_elapsed == null ? '' : '초', '대기 시간 포함'],
['대략 크레딧', '≈ ' + sFmt(s.credits_est), '', '건수 × 약 8.6 (추정치)'],
];
const days = sDays(d), maxD = Math.max(...days.map((x) => x.gen), 1);
const bars = days.map((x) => { const h = Math.round(x.gen / maxD * 120), rh = x.gen ? Math.round(x.regen / x.gen * h) : 0;
return `<div class="sbar" title="${x.day} · 생성 ${x.gen}건 (재생성 ${x.regen})"><b>${x.gen || ''}</b><div class="sstack" style="height:${Math.max(h, 3)}px"><i class="sg" style="height:${h - rh}px"></i><i class="sr" style="height:${rh}px"></i></div><span>${x.day.slice(5).replace('-', '/')}</span></div>`; }).join('');
const gTot = Math.max(d.gender.male + d.gender.female, 1);
const gRow = (label, n) => `<div class="shbar"><span>${label}</span><div class="t"><i style="width:${Math.round(n / gTot * 100)}%"></i></div><span class="c">${sFmt(n)}건 · ${Math.round(n / gTot * 100)}%</span></div>`;
const hMax = Math.max(...d.hours, 1);
const hours = d.hours.map((n, h) => `<div title="${h}시 · ${n}건"><i style="height:${Math.max(Math.round(n / hMax * 64), n ? 3 : 0)}px"></i><span>${h % 3 === 0 ? h : ''}</span></div>`).join('');
const uRows = d.users.map((u) => `<tr><td><b>${esc(sUser(u))}</b>${u.username && u.username !== 'anonymous' ? `<div class="sub">@${esc(u.username)}</div>` : ''}</td><td class="num">${sFmt(u.gen)}</td><td class="num">${sFmt(u.regen)}</td><td class="num">${sFmt(u.files)}</td><td class="num">${u.avg_elapsed == null ? '-' : u.avg_elapsed + '초'}</td><td class="num">${u.active_days}</td><td>${esc(u.last)}</td></tr>`).join('');
const fAll = d.folders, fShow = stats.moreFolders ? fAll : fAll.slice(0, 15);
const fRows = fShow.map((f) => { const fp = folderParts(f.folder); return `<tr><td class="fn" title="${esc(f.folder.replace(/\//g, ' / '))}">${f.folder === NO_FOLDER ? esc(f.folder) : (fp.crumb ? `<span class="sub">${esc(fp.crumb)} /</span> ` : '') + `<b>${esc(fp.name)}</b>`}</td><td class="num">${sFmt(f.gen)}</td><td class="num">${sFmt(f.files)}</td><td>${esc(f.last)}</td></tr>`; }).join('');
const rAll = d.recent, rShow = stats.moreRecent ? rAll : rAll.slice(0, 15);
const rRows = rShow.map((r) => `<tr><td><img loading="lazy" alt="" data-sopen="${esc(r.id)}" src="/api/swap/jobs/${r.id}/thumb"></td><td>${esc(r.when)}</td><td>${esc(sUser(r))}</td><td class="fn" title="${esc(r.rel_path)}">${esc(r.filename || r.rel_path)}</td><td>${GNAME[r.gender] || ''}</td><td class="num">${r.elapsed == null ? '-' : r.elapsed + '초'}</td><td>${r.regen ? '<span class="pillt regen">재생성</span>' : '<span class="pillt">생성</span>'}</td></tr>`).join('');
body.innerHTML = `
<div class="scards">${cards.map(([k, v, suf, n]) => `<div class="scard"><div class="k">${k}</div><div class="v">${v}${suf ? `<small>${suf}</small>` : ''}</div><div class="n">${esc(n)}</div></div>`).join('')}</div>
<div class="spanel"><h3>일자별 생성 <span>${esc(s.first_day)} ~ ${esc(s.last_day)}</span></h3><div class="sbars">${bars}</div>
<div class="slegend"><span><i style="background:var(--blue)"></i>생성</span><span><i style="background:var(--amber)"></i>재생성</span></div></div>
<div class="s2">
<div class="spanel"><h3>성별</h3>${gRow('남자', d.gender.male)}${gRow('여자', d.gender.female)}</div>
<div class="spanel"><h3>시간대별 <span>한국 시간</span></h3><div class="shours">${hours}</div></div>
</div>
<div class="spanel"><h3>사용자별 <span>생성 많은 순</span></h3><div style="overflow-x:auto"><table class="stbl"><thead><tr><th>사용자</th><th class="num">생성</th><th class="num">재생성</th><th class="num">사진</th><th class="num">평균 소요</th><th class="num">활동일</th><th>최근 활동</th></tr></thead><tbody>${uRows}</tbody></table></div></div>
<div class="spanel"><h3>폴더별 <span>${sFmt(fAll.length)}개 폴더</span></h3><div style="overflow-x:auto"><table class="stbl"><thead><tr><th>폴더</th><th class="num">생성</th><th class="num">사진</th><th>최근 생성</th></tr></thead><tbody>${fRows}</tbody></table></div>
${fAll.length > 15 ? `<div class="smore"><button class="btn sm" type="button" id="sMoreF">${stats.moreFolders ? '접기' : `전체 ${fAll.length}개 보기`}</button></div>` : ''}</div>
<div class="spanel"><h3>최근 생성 <span>최근 ${sFmt(rAll.length)}건 · 이미지를 누르면 원본과 비교</span></h3><div style="overflow-x:auto"><table class="stbl"><thead><tr><th></th><th>시각</th><th>사용자</th><th>파일</th><th>성별</th><th class="num">소요</th><th>구분</th></tr></thead><tbody>${rRows}</tbody></table></div>
${rAll.length > 15 ? `<div class="smore"><button class="btn sm" type="button" id="sMoreR">${stats.moreRecent ? '접기' : `전체 ${rAll.length}건 보기`}</button></div>` : ''}</div>`;
}
document.querySelectorAll('[data-sp]').forEach((b) => { b.onclick = () => { sSetPreset(b.dataset.sp); loadStats(); }; });
$('#sApply').onclick = () => { stats.preset = 'custom'; stats.from = $('#sFrom').value; stats.to = $('#sTo').value; document.querySelectorAll('[data-sp]').forEach((b) => b.classList.remove('primary')); loadStats(); };
$('#sRefresh').onclick = () => loadStats();
$('#sbody').addEventListener('click', (e) => {
if (e.target.closest('#sMoreF')) { stats.moreFolders = !stats.moreFolders; return renderStats(); }
if (e.target.closest('#sMoreR')) { stats.moreRecent = !stats.moreRecent; return renderStats(); }
const im = e.target.closest('[data-sopen]');
if (im) { const r = stats.data.recent.find((x) => x.id === im.dataset.sopen); if (r) openCompare({ title: r.rel_path || r.filename, before: `/api/swap/jobs/${r.id}/source`, after: `/api/swap/jobs/${r.id}/view`, dl: `/api/swap/jobs/${r.id}/download`, origDl: r.hasOriginal ? origDlOf(r) : srcDl(r) }); }
});
function renderDur() {
const st = state.histStatus, el = $('#dur');
if (!st) { el.hidden = true; return; }
el.hidden = false;
if (st.durable) {
el.className = `status ${st.error ? 'warn' : 'ok'}`;
el.querySelector('span').textContent = st.error ? '저장소 연결을 확인하는 중' : st.unsynced ? '결과 저장하는 중…' : '결과가 자동으로 저장돼요';
el.title = `${st.remote}${st.error ? ' · ' + st.error : ''}`;
} else {
el.className = 'status warn';
el.querySelector('span').textContent = '임시 저장 (재시작하면 사라져요)';
el.title = 'Space Secrets 에 HF_TOKEN, HF_DATASET_REPO 를 넣으면 계속 남아요.';
}
const nFiles = hist.loaded ? new Set(hist.items.map(gkeyOf)).size : st.count;
const b = $('#histBadge'); b.hidden = !nFiles; b.textContent = nFiles || '';
}
function renderConn() {
const el = $('#conn');
if (state.health && !state.health.ok) { el.hidden = false; el.className = 'status warn'; el.querySelector('span').textContent = '서비스 연결 설정 필요'; } else el.hidden = true;
}
let histT = 0;
/* ── 로그인 표시: HF 로그인(OAuth)이 켜진 Space 에서만 보인다. 사용 통계에 누가 썼는지 남기기 위함 ── */
const _fetch = window.fetch.bind(window); let _warned401 = false; // 로그인이 만료돼 API 가 401 이면 한 번 알려 준다
window.fetch = async (...a) => {
const r = await _fetch(...a);
if (r.status === 401 && !_warned401 && String(a[0]).startsWith('/api/')) { _warned401 = true; toast('로그인이 만료됐어요. 화면을 새로고침해서 다시 로그인해 주세요.', 'warn', 9000); }
return r;
};
async function loadWho() {
try {
const w = await (await fetch('/api/whoami')).json();
const chip = $('#userChip'), link = $('#authLink');
if (!w.oauth_enabled) return;
if (w.is_logged_in) {
chip.hidden = false; chip.querySelector('span').textContent = w.name || `@${w.username}`; chip.title = `@${w.username} — 사용 통계에 이 계정으로 기록돼요`;
link.textContent = '로그아웃'; link.href = w.logout_url; link.hidden = false; link.removeAttribute('title');
} else {
chip.hidden = true; link.textContent = '로그인'; link.href = w.login_url; link.title = '로그인하면 사용 통계에 이름이 기록돼요'; link.hidden = false;
}
} catch { /* 로그인 표시는 없어도 앱은 동작 */ }
}
async function quietReloadHistory() {
try { const h = await (await fetch('/api/history')).json(); hist.items = h.items; hist.loaded = true; renderDur(); if (state.view === 'hist') renderHistory(); } catch { /* 무시 */ }
}
async function refreshStatus() {
try {
const prev = state.histStatus ? state.histStatus.count : -1;
state.histStatus = await (await fetch('/api/history/status')).json(); renderDur();
if (state.histStatus.count !== prev && state.histStatus.count && !histT) histT = setTimeout(() => { histT = 0; quietReloadHistory(); }, hist.loaded ? 3000 : 0); // 건수가 달라졌을 때만, 최대 3초에 한 번(잦은 요청 방지)
} catch { /* 무시 */ }
}
async function loadHistory() {
try {
const [h] = await Promise.all([fetch('/api/history').then((r) => r.json()), refreshStatus()]);
hist.items = h.items; hist.loaded = true;
const keys = new Set(hist.items.map(gkeyOf));
for (const k of [...hist.sel]) if (!keys.has(k)) hist.sel.delete(k);
renderDur(); renderHistory();
} catch { $('#hbanner').innerHTML = `<div class="note err">${ic('alert', 16)}<div class="grow">저장된 결과를 불러오지 못했어요. 잠시 뒤 다시 열어 보세요.</div></div>`; }
}
/* 같은 날 같은 파일(경로)로 만든 결과(1컷·2컷·재생성…)는 카드 한 장으로 묶고, 눌러서 갤러리로 본다 */
const REP_KEY = 'fsHistRep';
let repMap = (() => { try { return JSON.parse(localStorage.getItem(REP_KEY) || '{}') || {}; } catch { return {}; } })();
const repSave = () => { try { localStorage.setItem(REP_KEY, JSON.stringify(repMap)); } catch { /* 저장이 막혀도 동작에는 지장 없음 */ } };
/* 같은 폴더인데 ZIP 안에서 바깥 폴더만 달라 갈라지는 경우를 합친다: 경로의 '끝'이 같으면 같은 폴더로 본다.
예) '테스트/6_X_여자/6_X' 와 '6_X' → '6_X' 한 곳. '캠페인A/남자' 와 '캠페인B/남자' 처럼 서로 다른 바깥 폴더가 붙어 있으면 따로 둔다. */
const _canon = { ref: null, n: -1, map: new Map() };
function canonMap() {
if (_canon.ref === hist.items && _canon.n === hist.items.length) return _canon.map;
const paths = [...new Set(hist.items.map((i) => parentDir(i.rel_path || '').normalize('NFC')))].filter((x) => x !== NO_FOLDER);
const set = new Set(paths), map = new Map();
for (const pth of paths) {
const segs = pth.split('/'); let best = pth;
for (let k = 1; k < segs.length; k++) { const tail = segs.slice(k).join('/'); if (set.has(tail)) best = tail; } // 바깥 폴더를 하나씩 떼어 보며, 실제로 있는 가장 짧은 끝 경로를 고른다
map.set(pth, best);
}
Object.assign(_canon, { ref: hist.items, n: hist.items.length, map });
return map;
}
const folderKeyOf = (rel) => { const pth = parentDir(rel || '').normalize('NFC'); return pth === NO_FOLDER ? pth : (canonMap().get(pth) || pth); };
const fileNameOf = (i) => ((i.filename || (i.rel_path || '').split('/').pop() || '')).normalize('NFC');
const gkeyOf = (i) => `${i.date}|${folderKeyOf(i.rel_path)}|${fileNameOf(i)}`;
function buildGroups(items) {
const m = new Map();
items.forEach((i, idx) => {
const k = gkeyOf(i);
if (!m.has(k)) m.set(k, { key: k, date: i.date, rel: i.rel_path || i.filename, name: fileNameOf(i), folder: folderKeyOf(i.rel_path), items: [] });
m.get(k).items.push({ ...i, _idx: idx });
});
const chosen = new Set(Object.values(repMap));
for (const g of m.values()) {
g.items.sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '') || a._idx - b._idx); // 최신이 앞
g.rep = g.items.find((x) => x.id === repMap[g.key]) || g.items.find((x) => chosen.has(x.id)) || g.items[0]; // 대표: 고른 것(묶음 기준이 바뀌기 전에 고른 것도 인식), 없으면 최신
}
return [...m.values()];
}
const histGroups = () => buildGroups(visibleHistory());
const kstDay = (back = 0) => new Date(Date.now() + 9 * 3600e3 - back * 86400e3).toISOString().slice(0, 10);
function visibleHistory() {
const q = $('#hq').value.trim().normalize('NFC').toLowerCase();
const range = $('#hrange').value;
const cutoff = range === 'all' ? '' : kstDay(parseInt(range, 10) - 1);
return hist.items.filter((i) => (!q || (i.rel_path || '').normalize('NFC').toLowerCase().includes(q)) && (!cutoff || i.date >= cutoff));
}
function histCard(g) {
const i = g.rep, n = g.items.length, sel = hist.sel.has(g.key);
const cutNo = [...g.items].reverse().findIndex((x) => x.id === i.id) + 1; // 오래된 컷부터 1안·2안…
const dl = `<a class="btn sm" href="${dlUrl(i.id, n > 1 ? `${cutNo}안` : '')}" title="${n > 1 ? `선택한 컷(${cutNo}안) 다운로드` : '다운로드'}">${ic('download', 13)}다운로드</a>`;
return `<article class="hcard ${sel ? 'sel' : ''}" data-gkey="${esc(g.key)}">
<label class="pick" title="선택"><input type="checkbox" ${sel ? 'checked' : ''}></label>
${n > 1 ? `<span class="cutbadge">${n}컷</span>` : ''}
<figure data-hopen title="${n > 1 ? '눌러서 갤러리 보기' : '눌러서 원본과 비교'}"><img loading="lazy" decoding="async" alt="" src="/api/swap/jobs/${i.id}/thumb"></figure>
<div class="meta">
<div class="fname" title="${esc(g.rel)}">${esc(i.filename)}</div>
<div class="row2"><span class="state"><span>${GNAME[i.gender] || ''} · ${esc(i.time || '')}</span></span>${n > 1 ? '' : dl}</div>
${n > 1 ? `<div class="row3">${dl}<button class="btn sm" type="button" data-hgal>갤러리</button></div>` : ''}
</div></article>`;
}
function renderHistory() {
const st = state.histStatus; let banner = '';
if (st && !st.durable) banner = `<div class="note warn">${ic('alert', 16)}<div class="grow">지금은 <b>임시 저장</b>이라 서비스가 다시 시작되면 지난 결과가 사라져요. 관리자에게 <b>HF_TOKEN</b>과 <b>HF_DATASET_REPO</b> 설정을 요청하면 계속 남길 수 있어요.</div></div>`;
else if (st && st.error) banner = `<div class="note err">${ic('alert', 16)}<div class="grow">저장소와 연결이 불안정해요. 결과는 지금 서버에 남아 있고, 연결되면 다시 저장을 시도해요.</div></div>`;
else if (st && st.durable && st.restored === false) banner = `<div class="note warn">${ic('alert', 16)}<div class="grow">예전 기록을 불러오는 중이에요. 잠시 뒤 다시 열어 보세요.</div></div>`;
$('#hbanner').innerHTML = banner;
const items = histGroups();
const byDate = new Map();
for (const g of items) {
if (!byDate.has(g.date)) byDate.set(g.date, new Map());
const fm = byDate.get(g.date); if (!fm.has(g.folder)) fm.set(g.folder, []); fm.get(g.folder).push(g);
}
$('#hlist').innerHTML = [...byDate.entries()].sort((a, b) => b[0].localeCompare(a[0])).map(([date, fm]) => {
const n = [...fm.values()].reduce((a, v) => a + v.length, 0);
return `<section class="hday"><h3>${esc(date)}<small>${n}장</small></h3>` +
[...fm.entries()].sort((a, b) => cmpFolder(a[0], b[0])).map(([folder, list]) => {
list.sort((a, b) => a.name.localeCompare(b.name, 'ko', { numeric: true }));
const ids = list.map((x) => x.rep.id).join(',');
return `<div class="hgroup"><div class="hgroup-head"><b title="${esc([...new Set(list.flatMap((x) => x.items.map((i) => parentDir(i.rel_path).replace(/\//g, ' / '))))].join('\n'))}">${ic('folder', 15)}${folderTitleHTML(folder)}</b><span>${list.length}장</span><span class="sp"></span>
<button class="btn sm" type="button" data-hzipg data-ids="${ids}" data-name="${esc(zipNameOf(folder, date))}">${ic('download', 13)}이 폴더 ZIP</button></div>
<div class="hgrid">${list.map(histCard).join('')}</div></div>`;
}).join('') + '</section>';
}).join('');
$('#hempty').hidden = items.length > 0;
$('#hemptyMsg').textContent = hist.items.length ? '검색 조건에 맞는 결과가 없어요.' : '작업이 끝나면 여기에 자동으로 쌓여요.';
updateHistToolbar();
}
function updateHistToolbar() {
const vis = histGroups(), n = hist.sel.size, cuts = vis.reduce((a, g) => a + g.items.length, 0);
$('#hcount').textContent = n ? `${n}장 선택됨` : `${vis.length}장${cuts > vis.length ? ` (${cuts}컷)` : ''}`;
$('#hzip').disabled = n === 0; $('#hdel').disabled = n === 0;
$('#hall').textContent = vis.length && vis.every((g) => hist.sel.has(g.key)) ? '전체 해제' : '전체 선택';
$('#hlist').classList.toggle('has-sel', n > 0);
}
$('#hq').addEventListener('input', () => { clearTimeout($('#hq')._t); $('#hq')._t = setTimeout(renderHistory, 200); });
$('#hrange').addEventListener('change', renderHistory);
$('#hall').onclick = () => {
const vis = histGroups(), all = vis.length && vis.every((g) => hist.sel.has(g.key));
vis.forEach((g) => (all ? hist.sel.delete(g.key) : hist.sel.add(g.key)));
renderHistory();
};
const selGroups = () => buildGroups(hist.items).filter((g) => hist.sel.has(g.key));
$('#hzip').onclick = () => submitZip(selGroups().map((g) => g.rep.id), `faceswap_선택_${kstDay()}`); // 파일마다 대표 이미지 한 장씩
$('#hdel').onclick = async () => {
const gs = selGroups(); if (!gs.length) return;
const ids = gs.flatMap((g) => g.items.map((x) => x.id));
if (!confirm(`${gs.length}장(결과 ${ids.length}컷)을 지난 결과에서 지울까요?\n저장소의 파일은 그대로 남고, 이 목록에서만 사라져요.`)) return;
await fetch('/api/history/hide', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids }) });
hist.sel.clear(); loadHistory();
};
$('#hlist').addEventListener('change', (e) => {
const card = e.target.closest('.hcard'); if (!card || !e.target.matches('.pick input')) return;
const id = card.dataset.gkey;
if (e.target.checked) hist.sel.add(id); else hist.sel.delete(id);
card.classList.toggle('sel', e.target.checked); updateHistToolbar();
});
$('#hlist').addEventListener('click', (e) => {
const z = e.target.closest('[data-hzipg]');
if (z) return submitZip(z.dataset.ids.split(','), z.dataset.name);
const card = e.target.closest('.hcard'); if (!card) return;
const g = buildGroups(hist.items).find((x) => x.key === card.dataset.gkey); if (!g) return;
if (e.target.closest('[data-hgal]') || (e.target.closest('[data-hopen]') && g.items.length > 1)) return openGallery(g.key);
if (e.target.closest('[data-hopen]')) compareItem(g.rep);
});
/* ── 갤러리: 같은 폴더의 파일들을 스크롤하며 보고, 파일마다 쓸 컷을 고른다 ─────────── */
// 서버에 원본이 저장돼 있으면(원본 저장 기능을 켠 뒤 만든 결과) 원본 그대로 받는다. 같은 사진의 컷은 모두 같은 원본을 가리키므로 하나만 있으면 된다.
const fmtMB = (n) => (n < 1048576 ? `${Math.max(1, Math.round(n / 1024))}KB` : `${(n / 1048576).toFixed(n >= 10485760 ? 0 : 1)}MB`);
const origDlOf = (x) => { const f = x.filename || 'photo'; return { href: `/api/swap/jobs/${x.id}/original`, name: /\.[^./]+$/.test(f) ? f.replace(/(\.[^./]+)$/, '_원본$1') : `${f}_원본`, label: `원본 다운로드${x.origSize ? ` (${fmtMB(x.origSize)})` : ''}` }; };
const srcDl = (i) => ({ href: `/api/swap/jobs/${i.id}/source`, name: `${(i.filename || 'photo').replace(/\.[^./]+$/, '')}_원본(축소본).jpg`, label: '원본(축소본) 다운로드' }); // 서버에는 비교용 축소본(긴 변 1800px)만 있다
const compareItem = (i) => { // 같은 사진(같은 날·같은 파일)의 컷을 오래된 것부터 1안·2안…으로 보여 준다(갤러리의 1컷·2컷과 같은 순서)
const g = buildGroups(hist.items).find((x) => x.items.some((y) => y.id === i.id));
const asc = g ? [...g.items].reverse() : [i];
const shots = asc.map((x, k) => ({ label: asc.length > 1 ? `${k + 1}안` : '결과', url: `/api/swap/jobs/${x.id}/view`, dl: dlUrl(x.id, asc.length > 1 ? `${k + 1}안` : ''), hint: `${x.date || ''} ${x.time || ''} 생성`.trim() }));
openCompare({ title: i.rel_path || i.filename, before: `/api/swap/jobs/${i.id}/source`, shots, start: Math.max(0, asc.findIndex((x) => x.id === i.id)), origDl: (() => { const w = asc.find((x) => x.hasOriginal); return w ? origDlOf(w) : srcDl(i); })() });
};
let galCtx = null, galDirty = false;
const folderGroups = () => buildGroups(hist.items).filter((g) => galCtx && g.date === galCtx.date && g.folder === galCtx.folder).sort((a, b) => a.name.localeCompare(b.name, 'ko', { numeric: true }));
const galPending = new Map(); // 파일 키 → { jobId, started, error, cancelRequested }
const galNew = new Set(); // 방금 새로 만든 컷의 id (갤러리를 닫기 전까지 NEW 표시)
function galFileHTML(g, idx, total) {
const asc = [...g.items].reverse(), n = asc.length; // 오래된 것부터 1컷, 2컷…
const pend = galPending.get(g.key), busy = !!pend && !pend.error;
return `<section class="gfile" data-gkey="${esc(g.key)}">
<div class="gfile-head"><b title="${esc(g.rel)}">${esc(g.rep.filename)}</b><span>${n}컷</span><button class="btn sm" type="button" data-gregen ${busy ? 'disabled' : ''} title="마음에 안 들면 새로 만들어 바로 비교해요">${ic('refresh', 12)}${busy ? '생성 중…' : '재생성'}</button><span class="gnum">${idx + 1} / ${total}</span></div>
<div class="gfile-cuts">${asc.map((i, idx) => {
const on = i.id === g.rep.id;
return `<article class="gcut ${on ? 'rep' : ''}" data-hid="${i.id}">
<figure data-gopen title="눌러서 원본과 비교"><img loading="lazy" decoding="async" alt="" src="/api/swap/jobs/${i.id}/thumb"><span class="gtag">${idx + 1}컷</span>${galNew.has(i.id) ? '<span class="gtag new">NEW</span>' : ''}${on ? '<span class="gtag rep">✓ 선택</span>' : ''}</figure>
<div class="meta"><div class="state"><span>${GNAME[i.gender] || ''} · ${esc(i.time || '')}</span></div>
<div class="row3"><a class="btn sm" href="${dlUrl(i.id, asc.length > 1 ? `${idx + 1}안` : '')}">${ic('download', 13)}다운로드</a><button class="btn sm" type="button" data-grep ${on ? 'disabled' : ''}>${on ? '선택됨' : '해당 컷 선택'}</button></div></div></article>`;
}).join('')}${pend ? `<article class="gcut pending"><figure>${pend.error
? `<div class="gph"><span class="err">${esc(pend.error)}</span></div>`
: `<div class="gph"><div class="gspin"></div><b>새 컷 만드는 중</b><span data-gtimer="${esc(g.key)}">${Math.round((Date.now() - pend.started) / 1000)}초</span></div>`}</figure>
<div class="meta"><div class="state"><span>${pend.error ? '실패했어요' : '끝나면 여기에 붙어요'}</span></div>
<div class="row3">${pend.error ? '<button class="btn sm" type="button" data-gregen>다시 시도</button><button class="btn sm" type="button" data-gdismiss>닫기</button>' : '<button class="btn sm" type="button" data-gcancel style="grid-column: 1 / -1">취소</button>'}</div></div></article>` : ''}</div></section>`;
}
const galSection = (key) => [...$('#galBody').children].find((c) => c.dataset.gkey === key);
function refreshGalFile(key) { // 그 파일 줄만 다시 그린다(스크롤 유지)
const el = galSection(key); if (!el) return;
const g = buildGroups(hist.items).find((x) => x.key === key); if (!g) return;
const kids = [...$('#galBody').children]; el.outerHTML = galFileHTML(g, kids.indexOf(el), kids.length);
}
const findOriginal = (g) => { const want = (g.rel || '').normalize('NFC'); const it = state.items.find((x) => x.file && x.relPath.normalize('NFC') === want); return it ? it.file : null; };
// 서버가 원본 입력을 기억하지 못할 때의 대체 수단: ① 이 화면에 있는 원본 ② 저장된 미리보기(긴 변 최대 1800px)
async function galSourceFile(g, intro) {
const f = findOriginal(g); if (f) return f;
if (!confirm(`${intro}저장된 미리보기(긴 변 최대 1800px)로 다시 만들면 결과 해상도가 원본보다 낮을 수 있어요.\n\n원본 화질로 만들려면 [작업] 탭에 원본 ZIP을 올려 두세요(시작하지 않아도 돼요).\n\n저장된 미리보기로 계속할까요?`)) return null;
try { const r = await fetch(`/api/swap/jobs/${g.rep.id}/source`); if (!r.ok) throw new Error(); const pf = new File([await r.blob()], g.rep.filename || 'image.jpg', { type: 'image/jpeg' }); pf._preview = true; return pf; }
catch { toast('저장된 미리보기를 불러오지 못했어요.', 'warn', 5000); return null; }
}
// 작업 하나를 만들어 끝날 때까지 기다린다. 반환: 'done' | 'cancelled' | 'input_gone'(서버가 기억한 원본이 Comfy Cloud 에서 사라짐)
async function galRun(p, src, g, face) {
const fd = new FormData(); let url;
if (src.fromId) { url = '/api/swap/regen'; fd.append('from_id', src.fromId); } // 서버가 기억한 원본 입력을 그대로 사용(업로드 없음, 원본 화질)
else { url = '/api/swap/jobs'; fd.append('image', src.file, g.rep.filename || src.file.name); fd.append('rel_path', g.rel); fd.append('gender', g.rep.gender); fd.append('regen', '1'); }
fd.append('face_id', face.id); fd.append('settings', JSON.stringify(settings(g.rep.gender)));
if (src.file && src.file._preview) fd.append('preview', '1'); // 저화질 미리보기로 만든 결과는 서버가 '원본'으로 기억하지 않게 표시
const r = await fetch(url, { method: 'POST', body: fd });
if (r.status === 409 && src.fromId) return 'input_gone'; // 이전 버전으로 만든 결과(원본 정보 없음)
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || `서버 오류 (HTTP ${r.status})`); }
p.jobId = (await r.json()).jobId;
if (p.cancelRequested) await postCancel([p.jobId]);
let misses = 0;
for (;;) {
await sleep(2000);
let res; try { res = await fetch(`/api/swap/jobs/${p.jobId}`); } catch { if (++misses > 10) throw new Error('서버 응답이 없습니다.'); continue; }
if (res.status === 404) throw new Error('작업 정보를 잃어버렸어요(서버가 재시작됨). 다시 시도해 주세요.');
if (!res.ok) { if (++misses > 10) throw new Error(`서버 오류 (HTTP ${res.status})`); continue; }
misses = 0; const j = await res.json();
if (j.status === 'cancelled') return 'cancelled';
if (j.status === 'done') return 'done';
if (j.status === 'error') { if (j.errorCode === 'input_gone') return 'input_gone'; throw new Error(j.error || '처리에 실패했어요.'); }
}
}
async function galRegen(key) {
const g = buildGroups(hist.items).find((x) => x.key === key); if (!g) return;
const cur = galPending.get(key); if (cur && !cur.error) return;
const face = state.faces[g.rep.gender];
if (!face || !face.ok) return toast('이 성별의 얼굴 사진이 서버에 없어서 만들 수 없어요. 관리자에게 알려 주세요.', 'warn', 6000);
const srv = g.items.find((x) => x.canRegen); // 서버가 원본 입력을 기억하는 결과가 있으면 그것으로(원본 화질·재업로드 없음)
let src = srv ? { fromId: srv.id } : null;
if (!src) { // 없으면(이전 버전 결과) 이 화면의 원본 → 저장된 미리보기
const f = await galSourceFile(g, '이 파일은 서버에 원본 정보가 없어요.\n'); if (!f) return;
src = { file: f };
}
const p = { jobId: null, started: Date.now(), error: '', cancelRequested: false };
galPending.set(key, p); galDirty = true; refreshGalFile(key);
const before = new Set(g.items.map((x) => x.id));
try {
let out = await galRun(p, src, g, face);
if (out === 'input_gone') { // Comfy Cloud 에서 원본 입력이 사라짐 → 파일로 다시 시도
const f = await galSourceFile(g, '서버가 기억해 둔 원본이 Comfy Cloud에서 사라졌어요.\n');
if (!f) { galPending.delete(key); if (!$('#gal').hidden) refreshGalFile(key); return; }
p.jobId = null; p.started = Date.now(); out = await galRun(p, { file: f }, g, face);
}
if (out === 'done') {
await quietReloadHistory(); galPending.delete(key);
const g2 = buildGroups(hist.items).find((x) => x.key === key); if (g2) for (const x of g2.items) if (!before.has(x.id)) galNew.add(x.id);
refreshStatus();
} else galPending.delete(key); // 취소됨
} catch (e) { if (p.cancelRequested) galPending.delete(key); else p.error = (e.message || String(e)).slice(0, 160); }
if (!$('#gal').hidden) refreshGalFile(key);
}
setInterval(() => { if ($('#gal').hidden || !galPending.size) return; document.querySelectorAll('[data-gtimer]').forEach((el) => { const p = galPending.get(el.dataset.gtimer); if (p) el.textContent = `${Math.round((Date.now() - p.started) / 1000)}초`; }); }, 1000);
function renderGallery() {
const gs = folderGroups(); if (!gs.length) return closeGallery();
const cuts = gs.reduce((a, g) => a + g.items.length, 0);
$('#galTitle').innerHTML = `${ic('folder', 15)}${folderTitleHTML(galCtx.folder)}<small>${esc(galCtx.date)} · ${gs.length}장 · ${cuts}컷</small>`;
$('#galBody').innerHTML = gs.map((g, i) => galFileHTML(g, i, gs.length)).join('');
}
function openGallery(key) {
const g = buildGroups(hist.items).find((x) => x.key === key); if (!g) return;
galCtx = { date: g.date, folder: g.folder }; galDirty = false;
renderGallery(); $('#gal').hidden = false; document.body.style.overflow = 'hidden';
const el = [...$('#galBody').children].find((c) => c.dataset.gkey === key); // 누른 파일 위치로 바로 이동
if (el) { $('#galBody').scrollTop = el.offsetTop - 8; el.classList.add('focus'); setTimeout(() => el.classList.remove('focus'), 2500); }
}
function closeGallery() {
$('#gal').hidden = true; $('#galBody').innerHTML = ''; document.body.style.overflow = ''; galCtx = null; galNew.clear();
if (galDirty) { galDirty = false; renderHistory(); } // 고른 컷을 목록 카드에 반영
}
$('#galClose').onclick = closeGallery;
$('#galZip').onclick = () => { const gs = folderGroups(); if (gs.length) submitZip(gs.map((g) => g.rep.id), zipNameOf(galCtx.folder, galCtx.date)); };
$('#galBody').addEventListener('click', (e) => {
const sec = e.target.closest('.gfile');
if (sec && e.target.closest('[data-gregen]')) return galRegen(sec.dataset.gkey);
if (sec && e.target.closest('[data-gcancel]')) { const p = galPending.get(sec.dataset.gkey); if (p) { p.cancelRequested = true; if (p.jobId) postCancel([p.jobId]); } return; }
if (sec && e.target.closest('[data-gdismiss]')) { galPending.delete(sec.dataset.gkey); return refreshGalFile(sec.dataset.gkey); }
const art = e.target.closest('.gcut'); if (!art || art.classList.contains('pending')) return;
const file = art.closest('.gfile'), key = file.dataset.gkey, i = hist.items.find((x) => x.id === art.dataset.hid); if (!i) return;
if (e.target.closest('[data-grep]')) { // 이 파일의 쓸 컷을 바꾸고, 그 파일만 다시 그린다(스크롤 유지)
repMap[key] = i.id; repSave(); galDirty = true;
const g = buildGroups(hist.items).find((x) => x.key === key);
if (g) { const kids = [...$('#galBody').children]; file.outerHTML = galFileHTML(g, kids.indexOf(file), kids.length); }
return;
}
if (e.target.closest('[data-gopen]')) compareItem(i);
});
/* ── 이벤트 ─────────────────────────────────────────── */
// ZIP 하나만 받는다. <label for=zipInput> 이라 브라우저가 직접 선택창을 연다(자바스크립트 클릭이 막힌 환경에서도 동작).
$('#zipInput').onchange = (e) => {
const f = e.target.files[0]; e.target.value = '';
if (!f) return;
if (!/\.zip$/i.test(f.name)) return toast('ZIP 파일(.zip)만 올릴 수 있어요. 폴더를 마우스 오른쪽 클릭 → 압축으로 ZIP을 만들어 주세요.', 'warn', 8000);
ingestAsync([{ file: f, relPath: f.name }], '선택창은 한 번에 한 개만 올릴 수 있어요. ZIP이 더 있으면 ‘ZIP 추가’를 다시 누르거나 끌어다 놓으세요.');
};
['#drop', '#addZip'].forEach((sel) => {
$(sel).addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; e.preventDefault(); $('#zipInput').click(); });
});
let dragDepth = 0;
window.addEventListener('dragenter', (e) => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { dragDepth++; document.body.classList.add('dragging'); } });
window.addEventListener('dragleave', () => { dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) document.body.classList.remove('dragging'); });
window.addEventListener('dragover', (e) => e.preventDefault());
window.addEventListener('drop', async (e) => {
e.preventDefault(); dragDepth = 0; document.body.classList.remove('dragging');
if (state.view !== 'work') setView('work');
let list;
try { list = await fromDrop(e.dataTransfer); }
catch (err) { console.error(err); return toast('올린 파일을 읽지 못했어요. ZIP 파일로 다시 올려 주세요.', 'err', 9000); }
ingestAsync(list);
});
$('#go').onclick = startAll;
$('#stop').onclick = cancelAll;
$('#retry').onclick = () => { for (const it of state.items) if (it.status === 'error' || it.status === 'cancelled') resetItem(it); state.cancelled = false; state.running = true; renderAll(); pump(); };
$('#zipAll').onclick = () => downloadZip(state.items, 'faceswap_results');
$('#clear').onclick = () => {
if (state.running) return alert('처리 중에는 비울 수 없어요. 취소하거나 끝날 때까지 기다려 주세요.');
state.items.forEach((i) => URL.revokeObjectURL(i.previewUrl)); state.items = []; renderAll();
};
$('#lbClose').onclick = closeLightbox;
$('#lb').addEventListener('click', (e) => { if (e.target.id === 'lb' || e.target.classList.contains('lb-body')) closeLightbox(); });
document.addEventListener('keydown', (e) => { if (e.key !== 'Escape') return; if (!$('#lb').hidden) closeLightbox(); else if (!$('#gal').hidden) closeGallery(); });
$('#banners').addEventListener('click', (e) => {
const b = e.target.closest('[data-bulk]'); if (!b) return;
for (const it of state.items) {
if (it.status !== 'needs') continue;
if (b.dataset.bulk === 'skip') it.status = 'skip'; else { it.gender = b.dataset.bulk; it.status = 'idle'; }
}
renderAll();
});
$('#folders').addEventListener('click', (e) => {
const card = e.target.closest('.card'); const sec = e.target.closest('.folder');
if (card) {
const it = state.items.find((i) => i.id === card.dataset.id);
if (!it) return;
const gbtn = e.target.closest('[data-gender]');
if (gbtn && !gbtn.disabled) {
const g = gbtn.dataset.gender;
for (const x of siblings(it)) { // 같은 사진의 1안·2안은 함께 바꾼다(작업 중·완료된 것은 제외)
if (x !== it && LOCKED.includes(x.status)) continue;
if (g === 'skip') x.status = 'skip'; else { x.gender = g; x.status = 'idle'; }
x.error = '';
if (x !== it) updateItem(x);
}
return updateItem(it);
}
const pk = e.target.closest('[data-pick]');
if (pk) { if (!pk.disabled) { const x = state.items.find((i) => i.id === pk.dataset.pick); if (x) useVariant(x); } return; }
if (e.target.closest('[data-cancel]')) return siblings(it).filter((x) => ['queued', 'sending', 'running'].includes(x.status)).forEach(cancelItem); // 같은 사진의 컷을 모두 취소
if (e.target.closest('[data-regen]')) return regen(it);
if (e.target.closest('[data-use]')) { e.stopPropagation(); return useVariant(it); }
if (e.target.closest('[data-retry]')) { const redo = siblings(it).filter((x) => x.status === 'error' || x.status === 'cancelled'); redo.forEach(resetItem); state.cancelled = false; state.running = true; redo.forEach(updateItem); return pump(); }
const dt = e.target.closest('[data-detail]');
if (dt) { const x = state.items.find((i) => i.id === (dt.dataset.detail || it.id)) || it; x.showErr = !x.showErr; return updateItem(x); }
if (e.target.closest('[data-orig]')) { const b = e.target.closest('[data-orig]'); if (!b.disabled) setOrigView(it, !state.origView.has(it.fileId)); return; }
if (e.target.closest('[data-resview]')) return setOrigView(it, false);
if (e.target.closest('[data-open]')) return openLightbox(it, origOn(it));
} else if (sec) {
const name = sec.dataset.folder;
const mine = state.items.filter((i) => i.folder === name);
if (e.target.closest('[data-zip]')) return downloadZip(mine, folderParts(name).name);
if (e.target.closest('[data-remove]')) {
if (mine.some((i) => ['queued', 'sending', 'running', 'cancelling'].includes(i.status))) return alert('처리 중인 이미지가 있어 뺄 수 없어요. 먼저 취소해 주세요.');
mine.forEach((i) => URL.revokeObjectURL(i.previewUrl));
state.items = state.items.filter((i) => i.folder !== name); renderAll();
}
}
});
if (window.top !== window.self) { // HF 처럼 다른 페이지 안에 끼워진 경우
$('#openTab').hidden = false; $('#openTab').href = location.href;
}
window.addEventListener('beforeunload', (e) => { if (state.running) { e.preventDefault(); e.returnValue = ''; } });
/* ── 설정 패널: 성별 일괄 · 페르소나 모델 · 변형 강도 ───────── */
ICON.upload = '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>';
const LS = { faces: 'fsFaces', str: 'fsStrength', hair: 'fsHair', open: 'fsSetupOpen' };
const lsGet = (k, d) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch { return d; } };
const lsSet = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch { return false; } };
const lsDel = (k) => { try { localStorage.removeItem(k); } catch { /* 무시 */ } };
const GENDERS2 = ['male', 'female'];
const uniqFiles = (arr) => new Set(arr.map((i) => i.fileId)).size;
// 성별 일괄 선택 — 건너뜀·진행 중·완료는 건드리지 않는다
function bulkGender(mode) {
let n = 0;
for (const it of state.items) {
if (LOCKED.includes(it.status) || it.status === 'skip') continue;
if (mode === 'auto') { it.gender = it.auto || null; it.status = it.auto ? 'idle' : 'needs'; }
else { it.gender = mode; it.status = 'idle'; }
it.error = ''; n += 1;
}
renderAll();
toast(n ? (mode === 'auto' ? `파일명·폴더 이름 기준으로 다시 정했어요.` : `${GNAME[mode]}로 바꿨어요. (${new Set(state.items.filter((i) => !LOCKED.includes(i.status) && i.status !== 'skip').map((i) => i.fileId)).size}장)`) : '바꿀 수 있는 사진이 없어요.', n ? 'info' : 'warn', 3500);
}
function renderBulk() {
const el = $('#bulkCount'); if (!el) return;
const has = state.items.length > 0;
const act = state.items.filter((i) => !LOCKED.includes(i.status) && i.status !== 'skip');
const all = (g) => act.length > 0 && act.every((i) => i.gender === g);
document.querySelectorAll('#setup [data-bg]').forEach((b) => {
b.disabled = !has || act.length === 0;
b.classList.toggle('on', b.dataset.bg !== 'auto' && all(b.dataset.bg));
});
const live = state.items.filter((i) => i.status !== 'skip');
const m = uniqFiles(live.filter((i) => i.gender === 'male')), f = uniqFiles(live.filter((i) => i.gender === 'female')), nd = uniqFiles(live.filter((i) => i.status === 'needs'));
el.innerHTML = has ? `남자 <b>${m}</b>장 · 여자 <b>${f}</b>장${nd ? ` · <span class="warn">정해야 할 사진 <b>${nd}</b>장</span>` : ''}` : 'ZIP을 올리면 한 번에 정할 수 있어요';
const d = state.defaults;
$('#setupSub').textContent = `얼굴 ${fmt2(state.str.face)}${d && d.graded ? ` · 머리 ${fmt2(state.str.hair)}` : ''}` + (GENDERS2.some((g) => state.faces[g].custom) ? ' · 직접 올린 모델 사용 중' : '');
}
// 페르소나 모델(얼굴) 카드
function renderPersona() {
$('#persona').innerHTML = GENDERS2.map((g) => {
const f = state.faces[g], custom = !!f.custom;
const img = (!custom && !f.ok) ? '기본 모델이 없어요' : `<img alt="${GNAME[g]} 모델" src="${custom ? f.url : `/api/swap/face-img/${encodeURIComponent(f.id)}`}">`;
return `<div class="pcard" data-pg="${g}">
<div class="pimg">${img}</div>
<div class="pbody">
<div class="pt"><b>${GNAME[g]} 모델</b><span class="ptag ${custom ? 'up' : ''}">${custom ? '내가 올린 사진' : '기본 모델'}</span></div>
<div class="pfile" title="${esc(custom ? f.name : '')}">${esc(custom ? f.name : '')}</div>
<div class="pbtn">
<label class="btn sm" for="faceUp-${g}" role="button" tabindex="0">${ic('upload', 13)}사진 올리기</label><input id="faceUp-${g}" data-faceup="${g}" type="file" accept="image/*" hidden>
<button class="btn sm" type="button" data-facereset="${g}" ${custom ? '' : 'hidden'}>기본으로</button>
</div>
<label class="hl">머리 스타일 설명 <span style="color:var(--text4)">(선택 · 영어 권장)</span><input class="inp" type="text" data-hair="${g}" maxlength="300" placeholder="예: black hair with a center part and long bangs" value="${esc(hairText(g))}"></label>
</div>
</div>`;
}).join('');
}
// 올린 사진을 줄여서(긴 변 1400px, JPEG) 서버에 보낸다 — 용량·형식 문제를 줄이고 이 브라우저에 기억해 둘 수 있다
async function downscaleImage(file, maxSide = 1400) {
let bmp;
try { bmp = await createImageBitmap(file); } catch { throw new Error('이 사진 형식은 열 수 없어요. JPG·PNG·WEBP 로 저장해서 올려 주세요(HEIC 불가).'); }
if (Math.min(bmp.width, bmp.height) < 200) throw new Error(`사진이 너무 작아요(${bmp.width}×${bmp.height}). 짧은 변이 200px 이상인 사진을 올려 주세요.`);
const k = Math.min(1, maxSide / Math.max(bmp.width, bmp.height));
const w = Math.max(1, Math.round(bmp.width * k)), h = Math.max(1, Math.round(bmp.height * k));
const c = document.createElement('canvas'); c.width = w; c.height = h;
const ctx = c.getContext('2d'); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, h); ctx.drawImage(bmp, 0, 0, w, h);
const blob = await new Promise((res) => c.toBlob(res, 'image/jpeg', 0.9));
if (!blob) throw new Error('사진을 처리하지 못했어요. 다른 사진으로 시도해 주세요.');
return blob;
}
const blobToDataUrl = (b) => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsDataURL(b); });
async function postFace(g, blob) {
const fd = new FormData(); fd.append('file', blob, 'face.jpg');
const r = await fetch(`/api/swap/faces/${g}`, { method: 'POST', body: fd });
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || `서버 오류 (HTTP ${r.status})`); }
return r.json();
}
function saveFaces() {
const o = {};
for (const g of GENDERS2) if (state.faces[g].custom) o[g] = { name: state.faces[g].name, url: state.faces[g].url };
if (!Object.keys(o).length) return lsDel(LS.faces);
if (!lsSet(LS.faces, o)) toast('이 브라우저에는 올린 사진을 저장하지 못했어요. 새로고침하면 기본 모델로 돌아가요.', 'warn', 8000);
}
async function setFace(g, file) {
try {
const blob = await downscaleImage(file);
const [j, url] = await Promise.all([postFace(g, blob), blobToDataUrl(blob)]);
state.faces[g] = { id: j.id, ok: true, custom: true, name: file.name || '내 사진', url };
state.hairText[g] = null; lsSet(LS.hair, state.hairText); // 올린 모델에는 기본 머리 설명을 쓰지 않는다(비워 두거나 직접 적는다)
saveFaces(); renderPersona(); updateSummary();
toast(`${GNAME[g]} 모델을 바꿨어요. 이후에 시작하는 작업부터 이 얼굴로 만들어요.`, 'info', 5000);
} catch (e) { toast(e.message || '사진을 올리지 못했어요.', 'warn', 8000); }
}
function resetFace(g) {
state.faces[g] = { id: `default-${g}`, ok: state.defaultOk[g] !== false };
state.hairText[g] = null; lsSet(LS.hair, state.hairText);
saveFaces(); renderPersona(); updateSummary();
toast(`${GNAME[g]} 모델을 기본으로 되돌렸어요.`, 'info', 4000);
}
async function restoreFaces() { // 새로고침해도 올려 둔 사진을 이어 쓴다(서버는 다시 올리면 같은 id 로 이어진다)
const saved = lsGet(LS.faces, {});
for (const g of GENDERS2) {
const sv = saved[g]; if (!sv || !sv.url) continue;
try { const blob = await (await fetch(sv.url)).blob(); const j = await postFace(g, blob); state.faces[g] = { id: j.id, ok: true, custom: true, name: sv.name || '내 사진', url: sv.url }; }
catch { toast(`저장해 둔 ${GNAME[g]} 모델을 불러오지 못해 기본 모델을 써요.`, 'warn', 6000); }
}
}
// 변형 강도
function syncStrength(persist = true) {
const d = state.defaults, graded = !d || d.graded !== false;
$('#rFace').value = state.str.face; $('#vFace').textContent = fmt2(state.str.face);
$('#rHair').value = state.str.hair; $('#vHair').textContent = fmt2(state.str.hair);
$('#rowHair').hidden = !graded; $('#lFace').textContent = graded ? '얼굴' : '변형';
if (persist) lsSet(LS.str, state.str);
updateSummary();
}
function resetStrength() {
const d = state.defaults || {};
state.str.face = d.face_strength ?? 0.4; state.str.hair = d.hair_strength ?? 0.4;
lsDel(LS.str); syncStrength(false);
}
$('#setup').addEventListener('click', (e) => {
const bg = e.target.closest('[data-bg]'); if (bg && !bg.disabled) return bulkGender(bg.dataset.bg);
const fr = e.target.closest('[data-facereset]'); if (fr) return resetFace(fr.dataset.facereset);
if (e.target.closest('#rReset')) return resetStrength();
if (e.target.closest('#setupToggle')) {
const body = $('#setupBody'); body.hidden = !body.hidden;
$('#setupToggle').textContent = body.hidden ? '펼치기' : '접기'; $('#setupToggle').setAttribute('aria-expanded', String(!body.hidden));
lsSet(LS.open, !body.hidden);
}
});
$('#setup').addEventListener('change', (e) => {
const up = e.target.closest('[data-faceup]');
if (up) { const f = up.files && up.files[0]; up.value = ''; if (f) setFace(up.dataset.faceup, f); }
});
$('#setup').addEventListener('input', (e) => {
if (e.target.id === 'rFace') { state.str.face = clamp01(parseFloat(e.target.value)); syncStrength(); }
else if (e.target.id === 'rHair') { state.str.hair = clamp01(parseFloat(e.target.value)); syncStrength(); }
else if (e.target.matches('[data-hair]')) { state.hairText[e.target.dataset.hair] = e.target.value; lsSet(LS.hair, state.hairText); }
});
function clamp01(v) { return Number.isFinite(v) ? Math.min(1, Math.max(0.05, v)) : 0.4; }
$('#setup').addEventListener('keydown', (e) => { if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('label.btn[for]')) { e.preventDefault(); $('#' + e.target.getAttribute('for')).click(); } });
/* ── 초기화 ─────────────────────────────────────────── */
async function init() {
renderAll();
try {
const f = await (await fetch('/api/swap/faces')).json();
for (const g of ['male', 'female']) { state.faces[g] = { id: f[g].id, ok: f[g].available }; state.defaultOk[g] = f[g].available; }
} catch { /* 무시 */ }
try { state.defaults = await (await fetch('/api/swap/defaults')).json(); } catch { state.defaults = null; }
{ // 이 브라우저에 기억해 둔 설정 불러오기
const d = state.defaults || {}, sv = lsGet(LS.str, null);
state.str.face = clamp01(sv && sv.face !== undefined ? sv.face : (d.face_strength ?? 0.4));
state.str.hair = clamp01(sv && sv.hair !== undefined ? sv.hair : (d.hair_strength ?? 0.4));
const sh = lsGet(LS.hair, {}); for (const g of GENDERS2) state.hairText[g] = (typeof sh[g] === 'string') ? sh[g] : null;
if (lsGet(LS.open, true) === false) { $('#setupBody').hidden = true; $('#setupToggle').textContent = '펼치기'; $('#setupToggle').setAttribute('aria-expanded', 'false'); }
}
await restoreFaces();
renderPersona(); syncStrength(false);
try {
state.health = await (await fetch('/api/health')).json();
if (state.health.maxConcurrent) state.maxConc = Math.max(1, Math.min(4, state.health.maxConcurrent));
state.conc = Math.min(state.conc, state.maxConc);
} catch { state.health = { ok: false, error: '서버에 연결하지 못했어요. 잠시 뒤 새로고침해 주세요.' }; }
renderConn(); updateSummary();
refreshStatus(); setInterval(refreshStatus, 30000); loadWho();
}
init();
})();
</script>
</body>
</html>
<html lang="ko" class="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>AI 얼굴 교체</title>
<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
<style>
:root {
--bg: #1a1a1a; --panel: #1e1e1e; --surface: #202020; --surface2: #242424; --surface3: #2a2a2a;
--line: #2a2a2a; --line2: #333333; --line3: #3a3a3a; --hover: #4b5563;
--blue: #3b82f6; --blue-h: #2563eb;
--text: #f9fafb; --text2: #d1d5db; --text3: #9ca3af; --text4: #6b7280;
--amber: #fbbf24; --red: #f87171; --green: #34d399;
--font: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', 'Malgun Gothic', 'Segoe UI', sans-serif;
}
* { box-sizing: border-box; font-family: var(--font); }
html, body { height: 100%; }
body { margin: 0; background: var(--bg); color: var(--text); font-size: 14px; -webkit-font-smoothing: antialiased; overflow: hidden; word-break: keep-all; overflow-wrap: break-word; }
button, input, textarea, select { font: inherit; color: inherit; }
button { cursor: pointer; }
[hidden] { display: none ; }
:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--hover); }
svg { flex-shrink: 0; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes shimmer { 0% { background-position: -600px 0; } 100% { background-position: 600px 0; } }
@keyframes pulseRing { 0% { transform: scale(0.85); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
@keyframes spin { to { transform: rotate(360deg); } }
.fade { animation: fadeIn .25s ease-out; }
.shimmer { background: linear-gradient(90deg, #232323 0%, #2c2c2c 40%, #232323 80%); background-size: 600px 100%; animation: shimmer 1.6s linear infinite; }
.spin { display: inline-flex; animation: spin 1s linear infinite; }
@media (prefers-reduced-motion: reduce) { .shimmer, .ring::before, .fade { animation: none; } .spin { animation-duration: 3s; } }
/* ── 셸 / 헤더 ─────────────────────────── */
.shell { height: 100vh; display: flex; flex-direction: column; }
.hdr { height: 56px; flex-shrink: 0; border-bottom: 1px solid var(--line); background: var(--bg); display: flex; align-items: center; justify-content: space-between; padding: 0 20px; gap: 12px; }
.hdr-l, .hdr-r { display: flex; align-items: center; gap: 16px; min-width: 0; }
.brand { display: flex; align-items: center; gap: 12px; }
.logo { width: 32px; height: 32px; border-radius: 8px; background: var(--blue); display: grid; place-items: center; color: #fff; }
.brand b { font-size: 15px; font-weight: 700; letter-spacing: -0.01em; white-space: nowrap; }
.pills { display: flex; gap: 4px; }
.pill { border: 0; background: transparent; color: var(--text3); padding: 6px 12px; border-radius: 8px; font-size: 12.5px; font-weight: 600; display: flex; align-items: center; gap: 6px; transition: background .15s, color .15s; }
.pill:hover { color: #e5e7eb; background: var(--line); }
.pill.on { background: var(--line2); color: #fff; }
.bdg { min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9999px; background: var(--blue); color: #fff; font-size: 10.5px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; }
.status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--text3); white-space: nowrap; }
.status i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.status.ok { color: var(--green); } .status.warn { color: var(--amber); }
.body { flex: 1; min-height: 0; display: flex; }
/* ── 왼쪽 패널 ─────────────────────────── */
.stick { position: sticky; top: 0; z-index: 5; background: rgba(26,26,26,.96); backdrop-filter: blur(6px); border-bottom: 1px solid var(--line); }
.strip .startbtn { height: 36px; padding: 0 18px; font-size: 13px; }
.strip .sum { margin: 10px 0 0; font-size: 12px; color: var(--text3); }
.strip .sum:empty { display: none; }
.strip .sum b { color: #e5e7eb; font-weight: 600; }
.stick .strip { position: static; background: transparent; backdrop-filter: none; border-bottom: 0; padding: 12px 24px 14px; }
.drop { border: 1px dashed var(--line3); background: #212121; border-radius: 12px; padding: 24px 16px 16px; text-align: center; transition: border-color .15s, background .15s; cursor: pointer; }
.drop:hover { border-color: var(--hover); }
.drop.over, body.dragging .drop { border-color: var(--blue); background: rgba(59,130,246,.08); }
.drop .ic { color: var(--text4); margin-bottom: 8px; }
.drop p { margin: 0; font-size: 13.5px; font-weight: 600; color: #e5e7eb; }
.drop .sub { margin: 4px 0 14px; font-size: 11.5px; color: var(--text4); line-height: 1.5; }
.drop .btns { display: flex; gap: 8px; justify-content: center; }
.vh { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); border: 0; opacity: 0; pointer-events: none; }
.toast { position: fixed; left: 50%; top: 66px; transform: translateX(-50%); z-index: 60; max-width: min(560px, calc(100vw - 32px)); padding: 12px 16px; border-radius: 12px; font-size: 13px; line-height: 1.55; background: #262626; border: 1px solid var(--line3); color: var(--text); box-shadow: 0 8px 28px rgba(0,0,0,.45); animation: fadeIn .2s ease-out; }
.toast.ok { border-color: rgba(52,211,153,.45); }
.toast.warn { border-color: rgba(245,158,11,.5); color: #fde68a; }
.toast.err { border-color: rgba(239,68,68,.5); color: #fecaca; }
.pickhint { margin: 10px 2px 0; font-size: 11.5px; color: var(--text4); line-height: 1.6; }
.pickhint b { color: var(--text2); font-weight: 600; }
.pickhint a { color: var(--blue); font-weight: 600; text-decoration: none; }
.pickhint a:hover { text-decoration: underline; }
label.drop { display: block; }
.drop .btn { margin-top: 2px; pointer-events: none; }
.pbar { display: flex; height: 8px; border-radius: 4px; background: var(--line2); overflow: hidden; }
.pbar i { display: block; height: 100%; transition: width .5s ease; }
.pbar i.done { background: var(--blue); }
.pbar i.run { background: repeating-linear-gradient(45deg, #7db3f8 0 8px, #3b82f6 8px 16px); background-size: 22px 22px; animation: stripes 1s linear infinite; }
.pbar i.bad { background: var(--red); }
.pbar i.can { background: #6b7280; }
.pbar.thin { height: 6px; margin: 0 0 10px; }
@keyframes stripes { to { background-position: 22px 0; } }
@media (prefers-reduced-motion: reduce) { .pbar i.run { animation: none; } }
.strip .pct { font-variant-numeric: tabular-nums; font-size: 13px; font-weight: 700; color: #93c5fd; min-width: 44px; text-align: right; }
.strip .barrow { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
.strip .barrow .pbar { flex: 1; }
.btn.stopbtn { color: #fca5a5; border-color: rgba(239,68,68,.45); background: rgba(239,68,68,.08); }
.btn.stopbtn:hover:not(:disabled) { background: rgba(239,68,68,.16); color: #fecaca; border-color: rgba(239,68,68,.7); }
.hdr-r a.status { color: var(--blue); text-decoration: none; font-weight: 600; }