sunyoung00 commited on
Commit
fffd4fd
·
verified ·
1 Parent(s): 403fd60

Delete index.html

Browse files
Files changed (1) hide show
  1. index.html +0 -1150
index.html DELETED
@@ -1,1150 +0,0 @@
1
- <!doctype html>
2
- <html lang="ko" class="dark">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <meta name="color-scheme" content="dark">
7
- <title>AI 얼굴 교체</title>
8
- <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
9
- <link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
10
- <style>
11
- :root {
12
- --bg: #1a1a1a; --panel: #1e1e1e; --surface: #202020; --surface2: #242424; --surface3: #2a2a2a;
13
- --line: #2a2a2a; --line2: #333333; --line3: #3a3a3a; --hover: #4b5563;
14
- --blue: #3b82f6; --blue-h: #2563eb;
15
- --text: #f9fafb; --text2: #d1d5db; --text3: #9ca3af; --text4: #6b7280;
16
- --amber: #fbbf24; --red: #f87171; --green: #34d399;
17
- --font: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Apple SD Gothic Neo', 'Malgun Gothic', 'Segoe UI', sans-serif;
18
- }
19
- * { box-sizing: border-box; font-family: var(--font); }
20
- html, body { height: 100%; }
21
- 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; }
22
- button, input, textarea, select { font: inherit; color: inherit; }
23
- button { cursor: pointer; }
24
- [hidden] { display: none !important; }
25
- :focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
26
- ::-webkit-scrollbar { width: 6px; height: 6px; }
27
- ::-webkit-scrollbar-track { background: var(--bg); }
28
- ::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
29
- ::-webkit-scrollbar-thumb:hover { background: var(--hover); }
30
- svg { flex-shrink: 0; }
31
-
32
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
33
- @keyframes shimmer { 0% { background-position: -600px 0; } 100% { background-position: 600px 0; } }
34
- @keyframes pulseRing { 0% { transform: scale(0.85); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
35
- @keyframes spin { to { transform: rotate(360deg); } }
36
- .fade { animation: fadeIn .25s ease-out; }
37
- .shimmer { background: linear-gradient(90deg, #232323 0%, #2c2c2c 40%, #232323 80%); background-size: 600px 100%; animation: shimmer 1.6s linear infinite; }
38
- .spin { display: inline-flex; animation: spin 1s linear infinite; }
39
- @media (prefers-reduced-motion: reduce) { .shimmer, .ring::before, .fade { animation: none; } .spin { animation-duration: 3s; } }
40
-
41
- /* ── 셸 / 헤더 ─────────────────────────── */
42
- .shell { height: 100vh; display: flex; flex-direction: column; }
43
- .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; }
44
- .hdr-l, .hdr-r { display: flex; align-items: center; gap: 16px; min-width: 0; }
45
- .brand { display: flex; align-items: center; gap: 12px; }
46
- .logo { width: 32px; height: 32px; border-radius: 8px; background: var(--blue); display: grid; place-items: center; color: #fff; }
47
- .brand b { font-size: 15px; font-weight: 700; letter-spacing: -0.01em; white-space: nowrap; }
48
- .pills { display: flex; gap: 4px; }
49
- .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; }
50
- .pill:hover { color: #e5e7eb; background: var(--line); }
51
- .pill.on { background: var(--line2); color: #fff; }
52
- .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; }
53
- .status { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--text3); white-space: nowrap; }
54
- .status i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
55
- .status.ok { color: var(--green); } .status.warn { color: var(--amber); }
56
-
57
- .body { flex: 1; min-height: 0; display: flex; }
58
-
59
- /* ── 왼쪽 패널 ─────────────────────────── */
60
-
61
- .stick { position: sticky; top: 0; z-index: 5; background: rgba(26,26,26,.96); backdrop-filter: blur(6px); border-bottom: 1px solid var(--line); }
62
- .strip .go { height: 36px; padding: 0 18px; font-size: 13px; }
63
- .strip .sum { margin: 10px 0 0; font-size: 12px; color: var(--text3); }
64
- .strip .sum:empty { display: none; }
65
- .strip .sum b { color: #e5e7eb; font-weight: 600; }
66
- .stick .strip { position: static; background: transparent; backdrop-filter: none; border-bottom: 0; padding: 12px 24px 14px; }
67
-
68
- .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; }
69
- .drop:hover { border-color: var(--hover); }
70
- .drop.over, body.dragging .drop { border-color: var(--blue); background: rgba(59,130,246,.08); }
71
- .drop .ic { color: var(--text4); margin-bottom: 8px; }
72
- .drop p { margin: 0; font-size: 13.5px; font-weight: 600; color: #e5e7eb; }
73
- .drop .sub { margin: 4px 0 14px; font-size: 11.5px; color: var(--text4); line-height: 1.5; }
74
- .drop .btns { display: flex; gap: 8px; justify-content: center; }
75
- .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; }
76
- .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; }
77
- .toast.ok { border-color: rgba(52,211,153,.45); }
78
- .toast.warn { border-color: rgba(245,158,11,.5); color: #fde68a; }
79
- .toast.err { border-color: rgba(239,68,68,.5); color: #fecaca; }
80
- .pickhint { margin: 10px 2px 0; font-size: 11.5px; color: var(--text4); line-height: 1.6; }
81
- .pickhint b { color: var(--text2); font-weight: 600; }
82
- .pickhint a { color: var(--blue); font-weight: 600; text-decoration: none; }
83
- .pickhint a:hover { text-decoration: underline; }
84
- label.drop { display: block; }
85
- .drop .btn { margin-top: 2px; pointer-events: none; }
86
- .pbar { display: flex; height: 8px; border-radius: 4px; background: var(--line2); overflow: hidden; }
87
- .pbar i { display: block; height: 100%; transition: width .5s ease; }
88
- .pbar i.done { background: var(--blue); }
89
- .pbar i.run { background: repeating-linear-gradient(45deg, #7db3f8 0 8px, #3b82f6 8px 16px); background-size: 22px 22px; animation: stripes 1s linear infinite; }
90
- .pbar i.bad { background: var(--red); }
91
- .pbar i.can { background: #6b7280; }
92
- .pbar.thin { height: 6px; margin: 0 0 10px; }
93
- @keyframes stripes { to { background-position: 22px 0; } }
94
- @media (prefers-reduced-motion: reduce) { .pbar i.run { animation: none; } }
95
- .strip .pct { font-variant-numeric: tabular-nums; font-size: 13px; font-weight: 700; color: #93c5fd; min-width: 44px; text-align: right; }
96
- .strip .barrow { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
97
- .strip .barrow .pbar { flex: 1; }
98
- .btn.stopbtn { color: #fca5a5; border-color: rgba(239,68,68,.45); background: rgba(239,68,68,.08); }
99
- .btn.stopbtn:hover:not(:disabled) { background: rgba(239,68,68,.16); color: #fecaca; border-color: rgba(239,68,68,.7); }
100
- .hdr-r a.status { color: var(--blue); text-decoration: none; font-weight: 600; }
101
- .hdr-r a.status:hover { text-decoration: underline; }
102
-
103
- .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; }
104
- .btn:hover:not(:disabled) { border-color: var(--hover); color: #fff; }
105
- .btn:disabled { background: var(--surface3); border-color: var(--surface3); color: var(--text4); cursor: not-allowed; }
106
- .btn.primary { background: var(--blue); border-color: var(--blue); color: #fff; }
107
- .btn.primary:hover:not(:disabled) { background: var(--blue-h); border-color: var(--blue-h); }
108
- .btn.primary:disabled { background: var(--surface3); border-color: var(--surface3); color: var(--text4); }
109
- .btn.danger:hover:not(:disabled) { color: #fca5a5; border-color: rgba(239,68,68,.45); background: rgba(239,68,68,.08); }
110
- .btn.sm { height: 30px; padding: 0 10px; font-size: 12px; border-radius: 8px; }
111
- .btn.lg { height: 48px; width: 100%; border-radius: 12px; font-size: 14px; }
112
- .linkbtn { background: none; border: 0; padding: 0; color: var(--blue); font-size: 12px; font-weight: 600; }
113
- .linkbtn:hover { text-decoration: underline; }
114
-
115
- .seg { display: grid; gap: 6px; grid-template-columns: repeat(var(--n, 3), minmax(0, 1fr)); }
116
- .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; }
117
- .seg button:hover:not(:disabled):not(.on) { border-color: var(--hover); color: #fff; }
118
- .seg button.on { background: var(--blue); border-color: var(--blue); color: #fff; }
119
- .seg button.on[data-gender=skip] { background: var(--line3); border-color: var(--line3); }
120
- .seg button:disabled { cursor: not-allowed; opacity: .5; }
121
- .seg button.on:disabled { opacity: .75; }
122
-
123
-
124
- /* ── 오른쪽 메인 ───────────────────────── */
125
- .main { flex: 1; min-width: 0; overflow-y: auto; }
126
- .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; }
127
- .strip-row { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
128
- .strip .big { font-size: 15px; font-weight: 700; letter-spacing: -0.01em; }
129
- .strip .big small { font-weight: 500; font-size: 12.5px; color: var(--text3); margin-left: 8px; }
130
- .chips { display: flex; gap: 6px; flex-wrap: wrap; flex: 1; min-width: 0; }
131
- .chip { font-size: 11.5px; font-weight: 600; border-radius: 9999px; padding: 3px 10px; background: var(--surface3); color: var(--text2); }
132
- .chip.warn { background: rgba(245,158,11,.14); color: var(--amber); }
133
- .chip.bad { background: rgba(239,68,68,.14); color: var(--red); }
134
- .chip.go { background: rgba(59,130,246,.16); color: #93c5fd; }
135
- .bar { height: 4px; border-radius: 2px; background: var(--line2); margin-top: 12px; overflow: hidden; }
136
- .bar i { display: block; height: 100%; width: 0; background: var(--blue); transition: width .35s; }
137
- .acts { display: flex; gap: 8px; }
138
-
139
- .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; }
140
- .note svg { margin-top: 2px; }
141
- .note .grow { flex: 1; min-width: 0; }
142
- .note .row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
143
- .note.warn { border: 1px solid rgba(245,158,11,.4); background: rgba(245,158,11,.1); color: #fde68a; }
144
- .note.err { border: 1px solid rgba(239,68,68,.4); background: rgba(239,68,68,.1); color: #fecaca; }
145
- .note.warn .btn, .note.err .btn { background: rgba(0,0,0,.25); }
146
-
147
- .hero { max-width: 720px; margin: 0 auto; padding: 9vh 24px 40px; }
148
- .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; }
149
- .drop.big:hover { border-color: var(--hover); }
150
- .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; }
151
- .drop.big h2 { margin: 0 0 8px; font-size: 22px; font-weight: 700; letter-spacing: -0.02em; color: var(--text); }
152
- .drop.big p { margin: 0 0 24px; font-size: 14px; font-weight: 400; color: var(--text3); line-height: 1.7; }
153
- .drop.big .btn { height: 42px; padding: 0 24px; font-size: 13.5px; }
154
-
155
- .folder { padding: 20px 24px 2px; }
156
- .folder-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
157
- .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; }
158
- .folder-head h3 svg { color: var(--text4); }
159
- .folder-head .cnt { color: var(--text4); font-size: 12px; }
160
- .folder-head .sp { flex: 1; }
161
- .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); gap: 12px; }
162
-
163
- .card { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; display: flex; flex-direction: column; }
164
- .card.is-error { border-color: rgba(239,68,68,.45); }
165
- .card figure.res { margin: 0; position: relative; aspect-ratio: 2 / 3; background: #161616; overflow: hidden; }
166
- .card figure.res > img:not(.origthumb) { width: 100%; height: 100%; object-fit: contain; display: block; }
167
- .card figure.res.clickable { cursor: zoom-in; }
168
- .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; }
169
- .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; }
170
- .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; }
171
- .card figure.res:hover .zoom { opacity: 1; }
172
- .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); }
173
- .ph.cover { background: rgba(14,14,14,.66); }
174
- .ph.cover.soft { background: rgba(14,14,14,.34); }
175
- .ph.err { color: var(--red); }
176
- .ph .t { color: #f3f4f6; font-weight: 600; font-size: 12px; }
177
- .ph .s { color: var(--text3); font-size: 11px; }
178
- .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; }
179
- .ring::before { content: ''; position: absolute; inset: -5px; border-radius: 9999px; border: 2px solid var(--blue); animation: pulseRing 1.4s ease-out infinite; }
180
- .cprog { position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background: rgba(255,255,255,.14); }
181
- .cprog i { display: block; height: 100%; background: var(--blue); transition: width .8s ease; }
182
-
183
- .meta { padding: 8px 10px 10px; display: flex; flex-direction: column; gap: 7px; }
184
- .fname { font-weight: 600; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
185
- .seg.mini { gap: 4px; }
186
- .seg.mini button { padding: 5px 0; font-size: 11.5px; border-radius: 7px; }
187
- .row2 { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 26px; }
188
- .state { display: flex; align-items: center; gap: 6px; font-size: 11.5px; color: var(--text3); min-width: 0; }
189
- .state i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
190
- .state span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
191
- .state.ok { color: var(--green); } .state.warn { color: var(--amber); } .state.bad { color: var(--red); } .state.go { color: #93c5fd; }
192
- .state em { font-style: normal; font-variant-numeric: tabular-nums; margin-left: 2px; opacity: .9; }
193
- .row2 .btn.sm { height: 26px; padding: 0 8px; font-size: 11.5px; }
194
- .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; }
195
-
196
- /* ── 지난 결과 ─────────────────────────── */
197
- .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; }
198
- /* 입력창·선택 상자 기본 모양 (지난 화면 정리 때 빠졌던 것을 복구) */
199
- .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; }
200
- .inp::placeholder { color: var(--text4); }
201
- .inp:hover { border-color: var(--hover); }
202
- .inp:focus { outline: none; border-color: var(--blue); }
203
- .inp::-webkit-search-cancel-button { filter: invert(.7); cursor: pointer; }
204
- 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; }
205
- .htop .inp { height: 34px; padding: 0 12px; width: 240px; border-radius: 8px; }
206
- .htop select.inp { width: auto; padding-right: 30px; }
207
- .htop .btn.sm { height: 34px; }
208
- .htop .hcount { font-size: 12.5px; color: var(--text3); margin-left: 4px; }
209
- .htop .sp { flex: 1; }
210
- .hday { padding: 24px 28px 0; }
211
- .hday > h3 { margin: 0; font-size: 14px; font-weight: 700; letter-spacing: -0.01em; }
212
- .hday > h3 small { font-weight: 500; color: var(--text4); margin-left: 8px; font-size: 12px; }
213
- .hgroup { margin-top: 14px; }
214
- .hgroup-head { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
215
- .hgroup-head b { font-size: 13px; font-weight: 600; word-break: break-all; display: flex; align-items: center; gap: 7px; }
216
- .hgroup-head b svg { color: var(--text4); }
217
- .hgroup-head span { color: var(--text4); font-size: 12px; }
218
- .hgroup-head .sp { flex: 1; }
219
- .hgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
220
- .hcard { background: var(--surface); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; position: relative; }
221
- .hcard.sel { border-color: var(--blue); box-shadow: 0 0 0 1px var(--blue); }
222
- .hcard figure { margin: 0; aspect-ratio: 2 / 3; background: #161616; cursor: zoom-in; }
223
- .hcard img { width: 100%; height: 100%; object-fit: contain; display: block; }
224
- .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; }
225
- .hcard:hover .pick, .hcard.sel .pick, .has-sel .hcard .pick { opacity: 1; }
226
- .hcard .pick input { margin: 0; width: 15px; height: 15px; accent-color: var(--blue); cursor: pointer; }
227
- .hcard .meta { padding: 10px 12px 12px; gap: 8px; }
228
-
229
- .empty2 { max-width: 420px; margin: 16vh auto 0; text-align: center; color: var(--text3); line-height: 1.7; padding: 0 20px; }
230
- .empty2 b { display: block; color: var(--text); font-size: 16px; margin-bottom: 6px; }
231
-
232
- /* ── 라이트박스 ────────────────────────── */
233
- .lb { position: fixed; inset: 0; background: rgba(8, 8, 8, .94); z-index: 50; display: flex; flex-direction: column; }
234
- .lb-head { display: flex; align-items: center; gap: 10px; padding: 12px 18px; }
235
- .lb-head .t { flex: 1; font-weight: 600; font-size: 13.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
236
- .lb-body { flex: 1; min-height: 0; display: grid; place-items: center; padding: 0 18px 12px; }
237
- .cmp { position: relative; max-width: 100%; max-height: 100%; touch-action: none; user-select: none; cursor: ew-resize; line-height: 0; border-radius: 12px; overflow: hidden; }
238
- .cmp .a { display: block; max-width: calc(100vw - 36px); max-height: calc(100vh - 130px); }
239
- .cmp .b { position: absolute; inset: 0; width: 100%; height: 100%; }
240
- .cmp .barv { position: absolute; top: 0; bottom: 0; width: 2px; background: #fff; box-shadow: 0 0 0 1px rgba(0,0,0,.3); }
241
- .cmp .barv::after { content: '⇆'; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 34px; height: 34px; border-radius: 50%; background: #fff; display: grid; place-items: center; line-height: 1; font-size: 16px; color: #111; }
242
- .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; }
243
- .cmp .tag.l { left: 10px; } .cmp .tag.r { right: 10px; }
244
- .lb-foot { text-align: center; color: var(--text4); font-size: 12px; padding: 0 0 14px; }
245
-
246
- .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; }
247
- .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; }
248
- body.dragging .veil { display: grid; }
249
-
250
- @media (max-width: 1023px) {
251
- body { overflow: auto; }
252
- .shell { height: auto; min-height: 100vh; }
253
- .body { flex-direction: column; }
254
- .main { overflow: visible; }
255
- .strip, .htop { position: static; }
256
- .hdr { flex-wrap: wrap; height: auto; padding: 10px 16px; }
257
- }
258
- </style>
259
- </head>
260
- <body>
261
- <div class="veil"><div>여기에 놓으면 추가돼요</div></div>
262
-
263
- <div class="shell">
264
- <header class="hdr">
265
- <div class="hdr-l">
266
- <div class="brand"><div class="logo" id="logo"></div><b>AI 얼굴 교체</b></div>
267
- <nav class="pills" aria-label="화면 전환">
268
- <button class="pill on" type="button" data-view="work">작업</button>
269
- <button class="pill" type="button" data-view="hist">지난 결과<span class="bdg" id="histBadge" hidden></span></button>
270
- </nav>
271
- </div>
272
- <div class="hdr-r">
273
- <a class="status" id="openTab" target="_blank" rel="noopener" hidden>새 탭에서 열기</a>
274
- <span class="status" id="conn" hidden><i></i><span></span></span>
275
- <span class="status" id="dur" hidden><i></i><span></span></span>
276
- </div>
277
- </header>
278
-
279
- <div class="body">
280
- <main class="main" id="main">
281
- <div id="workView">
282
- <div class="stick" hidden>
283
- <div class="strip" id="top" hidden>
284
- <div class="strip-row">
285
- <div class="big" id="sumLine"></div>
286
- <div class="chips" id="chips"></div>
287
- <div class="acts">
288
- <button class="btn sm" id="retry" type="button" hidden>실패·취소한 건 다시 시도</button>
289
- <button class="btn sm" id="zipAll" type="button" disabled>완료분 ZIP 받기</button>
290
- <button class="btn sm danger" id="clear" type="button">목록 비우기</button>
291
- <label class="btn sm" id="addZip" for="zipInput" role="button" tabindex="0" hidden>ZIP 추가</label>
292
- <button class="btn stopbtn" id="stop" type="button" hidden>전체 취소</button>
293
- <button class="btn primary go" id="go" type="button" disabled>이미지를 올려 주세요</button>
294
- </div>
295
- </div>
296
- <div class="barrow"><div class="pbar" id="pbar"></div><span class="pct" id="pct">0%</span></div>
297
- <p class="sum" id="sum"></p>
298
- </div>
299
- </div>
300
- <div id="banners"></div>
301
- <div id="folders"></div>
302
- <div class="hero fade" id="empty">
303
- <label class="drop big" id="drop" for="zipInput" tabindex="0" role="button" aria-label="ZIP 파일 선택">
304
- <div class="badge" id="icDrop"></div>
305
- <h2>ZIP 파일을 올려 주세요</h2>
306
- <p>폴더를 ZIP으로 묶어 끌어다 놓거나 눌러서 선택하세요.<br>안에 있는 사진이 모두 나타나고, 파일명·폴더 이름·ZIP 이름의 남자·여자(남/여도 가능)에 맞는 얼굴로 바꿔 드려요.<br>ZIP이 여러 개면 <b style="color:#e5e7eb;font-weight:600">한꺼번에 끌어다 놓거나</b>, 선택창에서는 하나씩 올려 주세요.</p>
307
- <span class="btn primary">ZIP 파일 선택</span>
308
- </label>
309
- </div>
310
- </div>
311
-
312
- <div id="histView" hidden>
313
- <div class="htop" id="htop">
314
- <input class="inp" id="hq" type="search" placeholder="파일명·폴더 검색" aria-label="검색">
315
- <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>
316
- <span class="hcount" id="hcount"></span><span class="sp"></span>
317
- <button class="btn sm" id="hall" type="button">전체 선택</button>
318
- <button class="btn sm primary" id="hzip" type="button" disabled>선택 ZIP 받기</button>
319
- <button class="btn sm danger" id="hdel" type="button" disabled>선택 지우기</button>
320
- </div>
321
- <div id="hbanner"></div>
322
- <div id="hlist"></div>
323
- <div class="empty2" id="hempty" hidden><b>저장된 결과가 없어요</b><span id="hemptyMsg">작업이 끝나면 여기에 자동으로 쌓여요.</span></div>
324
- </div>
325
- </main>
326
- </div>
327
- </div>
328
-
329
- <div class="lb" id="lb" hidden>
330
- <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>
331
- <div class="lb-body"><div class="cmp" id="cmp"></div></div>
332
- <div class="lb-foot">좌우로 끌어서 원본과 결과를 비교하세요 · Esc로 닫기</div>
333
- </div>
334
-
335
- <div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
336
- <input id="zipInput" class="vh" type="file" accept=".zip,application/zip,application/x-zip-compressed" tabindex="-1" aria-hidden="true">
337
- <form id="zipForm" method="post" action="/api/swap/zip" hidden><input name="ids"><input name="name"></form>
338
-
339
- <script>
340
- (() => {
341
- 'use strict';
342
- const $ = (s) => document.querySelector(s);
343
- const IMG_RE = /\.(jpe?g|jfif|png|webp|bmp)$/i;
344
- const SYS_FILES = /^(\.ds_store|thumbs\.db|desktop\.ini)$/i;
345
- const NO_FOLDER = '(폴더 없이 올린 파일)';
346
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
347
- const uid = () => (crypto.randomUUID ? crypto.randomUUID() : 'i' + Math.random().toString(36).slice(2) + Date.now().toString(36));
348
- const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
349
- const fmtSec = (s) => { s = Math.round(s || 0); return s >= 60 ? `${Math.floor(s / 60)}분 ${s % 60}초` : `${s}초`; };
350
- const GNAME = { male: '남자', female: '여자' };
351
-
352
- /* ── 아이콘 (lucide) ───────────────────────────────── */
353
- const ICON = {
354
- 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"/>',
355
- 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"/>',
356
- 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"/>',
357
- 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"/>',
358
- 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"/>',
359
- 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"/>',
360
- 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"/>',
361
- chev: '<path d="m6 9 6 6 6-6"/>',
362
- };
363
- 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>`;
364
- $('#logo').innerHTML = ic('sparkles', 16); $('#icDrop').innerHTML = ic('folder', 28);
365
-
366
- const state = {
367
- items: [],
368
- faces: { male: { id: 'default-male', ok: true }, female: { id: 'default-female', ok: true } },
369
- inflight: 0, running: false, cancelled: false, defaults: null, health: null,
370
- view: 'work', histStatus: null,
371
- conc: Math.min(4, Math.max(1, parseInt(new URLSearchParams(location.search).get('conc'), 10) || 2)), // 한 번에(동시에) 생성할 장수 — 기본 2장 (관리자용: 주소 뒤에 ?conc=3)
372
- maxConc: 4,
373
- };
374
-
375
- /* ── 사용자에게 보여줄 말로 바꾸기 ───────────────────── */
376
- const FRIENDLY_STAGE = {
377
- '대기 중': '곧 시작해요', '이미지 업로드 중': '이미지를 올리는 중', '워크플로우 제출 중': '작업을 보내는 중',
378
- 'Comfy 대기열': '차례를 기다리는 중', 'Comfy 대기열 (동시 실행 제한)': '차례를 기다리는 중',
379
- 'GPU 준비 중': '준비하는 중', '생��� 중': '얼굴을 바꾸는 중', '결과 받는 중': '결과를 받는 중',
380
- };
381
- const friendlyStage = (s) => FRIENDLY_STAGE[s] || s || '처리하는 중';
382
- function friendlyError(msg) {
383
- const m = msg || '';
384
- if (/크레딧|HTTP 402/.test(m)) return 'Comfy 크레딧이 부족해요. 관리자에게 충전을 요청해 주세요.';
385
- if (/API 키|HTTP 401|COMFY_CLOUD_API_KEY/.test(m)) return '서비스 연결 설정에 문제가 있어요. 관리자에게 알려 주세요.';
386
- if (/한도|구독|HTTP 429/.test(m)) return '한꺼번에 처리할 수 있는 한도를 넘었어요. 잠시 뒤 다시 시도해 주세요.';
387
- if (/이미지를 열 수 없|이미지 파일이 아닙니다|빈 파일/.test(m)) return '이미지 파일을 읽을 수 없어요. 다른 파일로 시도해 주세요.';
388
- if (/안에 작업이 끝나지|시간/.test(m)) return '처리 시간이 너무 오래 걸렸어요. 다시 시도해 주세요.';
389
- if (/재시작/.test(m)) return '서버가 다시 시작되어 진행 정보를 잃었어요. 지난 결과에서 확인하거나 다시 시도해 주세요.';
390
- if (/서버에 연결|응답이 없/.test(m)) return '서버와 연결이 끊겼어요. 잠시 뒤 다시 시도해 주세요.';
391
- return '처리하지 못했어요. 다시 시도해 주세요.';
392
- }
393
-
394
- /* ── 파일명에서 성별 인식 ─────────────────────────────
395
- 맥에서 올린 한글 파일명은 자모가 분리(NFD)돼 있어 NFC로 맞춘 뒤 찾는다. */
396
- function detectGender(name, isFolder = false) {
397
- // 확장자는 빼고 본다. 맥에서 올린 한글 파일명은 자모가 분리(NFD)돼 있어 NFC 로 맞춘 뒤 찾는다.
398
- let n = name.normalize('NFC').toLowerCase();
399
- if (!isFolder) n = n.replace(/\.[a-z0-9]{2,5}$/, '');
400
- // 한 글자(남·여)는 아무 데나 들어 있으면 안 된다(여행·남산 등) →
401
- // 앞뒤가 글자(한글·영문)가 아닌 구분자(_ - 공백 . 숫자 괄호 …)이거나 처음·끝일 때만 성별로 본다.
402
- const token = (words) => new RegExp('(^|[^가-힣a-z])(' + words + ')(?=$|[^가-힣a-z])').test(n);
403
- const f = /여자|여성/.test(n) || token('female|woman|women|여');
404
- const m = /남자|남성/.test(n) || token('male|man|men|남');
405
- if (f && !m) return 'female';
406
- if (m && !f) return 'male';
407
- return null; // 없거나 둘 다 있으면 직접 선택
408
- }
409
-
410
- // 파일명에 표기가 있으면 그 성별. 없으면 가까운 폴더부터 위로 올라가며 폴더 이름에서 찾고,
411
- // 그래도 없으면 마지막으로 ZIP 파일 이름(예: 6_SPPPG4VU10_25_여자.zip)을 본다.
412
- // (예: 남자/001.jpg, 촬영/여/a.jpg, 남자/여행/b.jpg → 남자)
413
- function genderFromPath(rel, zipName) {
414
- const parts = rel.split('/');
415
- const byFile = detectGender(parts[parts.length - 1]);
416
- if (byFile) return { g: byFile, from: 'file' };
417
- for (let i = parts.length - 2; i >= 0; i--) {
418
- const byFolder = detectGender(parts[i], true);
419
- if (byFolder) return { g: byFolder, from: 'folder' };
420
- }
421
- if (zipName) {
422
- const byZip = detectGender(zipName.replace(/\.zip$/i, ''), true);
423
- if (byZip) return { g: byZip, from: 'zip' };
424
- }
425
- return { g: null, from: null };
426
- }
427
-
428
- function addEntries(list) {
429
- let added = 0, folderDerived = 0, zipDerived = 0;
430
- for (const { file, relPath, zipName } of list) {
431
- const rel = relPath.replace(/^\/+/, '');
432
- const name = rel.split('/').pop();
433
- if (!IMG_RE.test(name) || name.startsWith('.')) continue;
434
- const key = `${rel}|${file.size}|${file.lastModified}`;
435
- if (state.items.some((i) => i.key === key)) continue;
436
- const { g, from } = genderFromPath(rel, zipName);
437
- if (from === 'folder') folderDerived++;
438
- if (from === 'zip') zipDerived++;
439
- state.items.push({
440
- id: uid(), key, file, name, relPath: rel,
441
- folder: rel.includes('/') ? rel.split('/')[0] : NO_FOLDER,
442
- auto: g, autoFrom: from, gender: g, status: g ? 'idle' : 'needs',
443
- previewUrl: URL.createObjectURL(file), jobId: null, error: '', showErr: false, stageLabel: '', startedAt: 0, elapsed: 0,
444
- });
445
- added++;
446
- }
447
- state.items.sort((a, b) => a.folder.localeCompare(b.folder, 'ko') || a.relPath.localeCompare(b.relPath, 'ko', { numeric: true }));
448
- addEntries.folderDerived = folderDerived; addEntries.zipDerived = zipDerived;
449
- renderAll();
450
- return added;
451
- }
452
-
453
- /* ── 올린 결과를 사용자에게 알려주기 (조용히 실패하지 않도록) ── */
454
- function toast(msg, kind = 'info', ms = 7000) {
455
- const el = $('#toast'); if (!el) return;
456
- el.className = `toast ${kind}`; el.textContent = msg; el.hidden = false;
457
- clearTimeout(toast._t); toast._t = setTimeout(() => { el.hidden = true; }, ms);
458
- }
459
- function ingest(list, extra = {}) {
460
- const exOther = extra.other || 0;
461
- if (!list.length && !exOther && !extra.encrypted) { toast('선택한 곳에 파일이 없어요. 이미지가 들어 있는 폴더인지 확인해 주세요.', 'warn'); return; }
462
- const files = list.filter(({ relPath }) => { const n = relPath.split('/').pop(); return !n.startsWith('.') && !SYS_FILES.test(n); });
463
- const imgs = files.filter(({ relPath }) => IMG_RE.test(relPath));
464
- const other = files.filter(({ relPath }) => !IMG_RE.test(relPath));
465
- const otherN = other.length + exOther;
466
- const before = state.items.length;
467
- addEntries(list);
468
- const added = state.items.length - before;
469
- const tail = extra.note ? ` ${extra.note}` : '';
470
- if (!imgs.length) {
471
- if (extra.encrypted) { toast('암호가 걸린 ZIP은 읽을 수 없어요. 암호 없이 다시 압축해 주세요.', 'warn'); return; }
472
- const exts = [...new Set([...other.map(({ relPath }) => extOf(relPath) || '?'), ...(extra.exts || [])].map((x) => x.toUpperCase()))].slice(0, 4).join(', ');
473
- toast(`올릴 수 있는 이미지가 없어요. jpg·png·webp 파일만 가능해요${exts ? ` (찾은 형식: ${exts})` : ''}.`, 'warn');
474
- } else if (!added) {
475
- toast('이미 올린 이미지예요.' + tail, 'info');
476
- } else {
477
- const parts = [`${added}장을 추가했어요`];
478
- if (addEntries.folderDerived > 0) parts.push(`폴더 이름으로 남자·여자를 정한 사진 ${addEntries.folderDerived}장`);
479
- if (addEntries.zipDerived > 0) parts.push(`ZIP 이름으로 남자·여자를 정한 사진 ${addEntries.zipDerived}장`);
480
- if (imgs.length - added > 0) parts.push(`이미 있는 ${imgs.length - added}장은 건너뛰었어요`);
481
- if (otherN) parts.push(`이미지가 아닌 파일 ${otherN}개는 건너뛰었어요`);
482
- if (extra.encrypted) parts.push(`암호가 걸린 파일 ${extra.encrypted}개는 읽지 못했어요`);
483
- toast(parts.join(' · ') + '.' + tail, 'ok', 6000);
484
- }
485
- }
486
-
487
- /* ── ZIP 한 개로 올리기 (보안 프로그램이 여러 개 선택을 막을 때) ──
488
- 브라우저에서 바로 풀어서 폴더 구조·한글 파일명을 그대로 살린다. 외부 라이브러리는 쓰지 않는다. */
489
- const MIME = { jpg: 'image/jpeg', jpeg: 'image/jpeg', jfif: 'image/jpeg', png: 'image/png', webp: 'image/webp', bmp: 'image/bmp' };
490
- const extOf = (n) => ((n.match(/\.([^./]+)$/) || [])[1] || '').toLowerCase();
491
- function decodeZipName(bytes, flags) {
492
- if (flags & 0x800) return new TextDecoder('utf-8').decode(bytes);
493
- try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } // 맥·최신 윈도우
494
- catch { try { return new TextDecoder('euc-kr').decode(bytes); } catch { return new TextDecoder().decode(bytes); } } // 예전 윈도우(CP949)
495
- }
496
- async function readZip(zipFile, onProgress) {
497
- const size = zipFile.size;
498
- if (size < 22) throw new Error('ZIP 파일이 아니거나 손상되었어요.');
499
- const tailLen = Math.min(size, 22 + 65535);
500
- const tail = new DataView(await zipFile.slice(size - tailLen, size).arrayBuffer());
501
- let eocd = -1;
502
- for (let i = tailLen - 22; i >= 0; i--) if (tail.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
503
- if (eocd < 0) throw new Error('ZIP 파일이 아니거나 손상되었어요.');
504
- const total = tail.getUint16(eocd + 10, true), cdSize = tail.getUint32(eocd + 12, true), cdOff = tail.getUint32(eocd + 16, true);
505
- if (total === 0xFFFF || cdOff === 0xFFFFFFFF || cdSize === 0xFFFFFFFF) throw new Error('4GB가 넘는 ZIP은 읽을 수 없어요. 나눠서 올려 주세요.');
506
- const cd = new DataView(await zipFile.slice(cdOff, cdOff + cdSize).arrayBuffer());
507
- const entries = []; let p = 0;
508
- while (p + 46 <= cd.byteLength && cd.getUint32(p, true) === 0x02014b50) {
509
- const nameLen = cd.getUint16(p + 28, true), extraLen = cd.getUint16(p + 30, true), cmtLen = cd.getUint16(p + 32, true);
510
- entries.push({
511
- flags: cd.getUint16(p + 8, true), method: cd.getUint16(p + 10, true), time: cd.getUint16(p + 12, true), date: cd.getUint16(p + 14, true),
512
- comp: cd.getUint32(p + 20, true), off: cd.getUint32(p + 42, true),
513
- name: decodeZipName(new Uint8Array(cd.buffer, cd.byteOffset + p + 46, nameLen), cd.getUint16(p + 8, true)).replace(/\\/g, '/').replace(/^\/+/, ''),
514
- });
515
- p += 46 + nameLen + extraLen + cmtLen;
516
- }
517
- const zipBase = zipFile.name.replace(/\.zip$/i, '');
518
- const out = []; let other = 0, encrypted = 0; const exts = [];
519
- const want = entries.filter((e) => !e.name.endsWith('/') && !e.name.startsWith('__MACOSX/'));
520
- let done = 0;
521
- for (const e of want) {
522
- const base = e.name.split('/').pop();
523
- if (base.startsWith('.') || SYS_FILES.test(base)) continue;
524
- if (!IMG_RE.test(base)) { other++; const x = extOf(base); if (x) exts.push(x); continue; }
525
- if (e.flags & 1) { encrypted++; continue; }
526
- if (e.comp === 0xFFFFFFFF || e.off === 0xFFFFFFFF) throw new Error('4GB가 넘는 ZIP은 읽을 수 없어요. 나눠서 올려 주세요.');
527
- const lh = new DataView(await zipFile.slice(e.off, e.off + 30).arrayBuffer());
528
- if (lh.getUint32(0, true) !== 0x04034b50) continue;
529
- const start = e.off + 30 + lh.getUint16(26, true) + lh.getUint16(28, true);
530
- const raw = zipFile.slice(start, start + e.comp);
531
- let blob;
532
- if (e.method === 0) blob = raw;
533
- else if (e.method === 8) {
534
- if (typeof DecompressionStream === 'undefined') throw new Error('이 브라우저에서는 압축된 ZIP을 읽을 수 없어요. 최신 Chrome·Edge로 열어 주세요.');
535
- blob = await new Response(raw.stream().pipeThrough(new DecompressionStream('deflate-raw'))).blob();
536
- } else { other++; continue; }
537
- const t = e.time, d = e.date;
538
- const mtime = new Date((d >> 9) + 1980, ((d >> 5) & 15) - 1, d & 31, t >> 11, (t >> 5) & 63, (t & 31) * 2).getTime();
539
- 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 });
540
- if (onProgress && (++done % 5 === 0)) onProgress(done, want.length);
541
- }
542
- return { list: out, other, encrypted, exts };
543
- }
544
- async function expandZips(list) {
545
- const out = []; const extra = { other: 0, exts: [], encrypted: 0 };
546
- for (const it of list) {
547
- if (/\.zip$/i.test(it.file.name)) {
548
- const r = await readZip(it.file, (n, t) => toast(`ZIP을 읽는 중… ${n}/${t}`, 'info', 60000));
549
- out.push(...r.list); extra.other += r.other; extra.exts.push(...r.exts); extra.encrypted += r.encrypted;
550
- } else out.push(it);
551
- }
552
- return { list: out, extra };
553
- }
554
- async function ingestAsync(list, note) {
555
- try { const r = await expandZips(list); ingest(r.list, { ...r.extra, note }); }
556
- catch (err) { console.error(err); toast(err.message || 'ZIP을 읽지 못했어요.', 'err', 9000); }
557
- }
558
- window.addEventListener('error', (e) => toast(`화면에서 오류가 났어요: ${e.message || '알 수 없는 오류'}`, 'err', 12000));
559
- window.addEventListener('unhandledrejection', (e) => toast(`화면에서 오류가 났어요: ${(e.reason && e.reason.message) || e.reason || '알 수 없는 오류'}`, 'err', 12000));
560
-
561
- const fromInput = (files) => [...files].map((f) => ({ file: f, relPath: f.webkitRelativePath || f.name }));
562
- function readAll(reader) {
563
- return new Promise((res, rej) => {
564
- const acc = [];
565
- (function next() { reader.readEntries((b) => { if (!b.length) res(acc); else { acc.push(...b); next(); } }, rej); })();
566
- });
567
- }
568
- async function walk(entry, prefix, out) {
569
- if (entry.isFile) {
570
- const file = await new Promise((res, rej) => entry.file(res, rej));
571
- out.push({ file, relPath: prefix + entry.name });
572
- } else if (entry.isDirectory) {
573
- const kids = await readAll(entry.createReader());
574
- for (const k of kids) await walk(k, prefix + entry.name + '/', out);
575
- }
576
- }
577
- async function fromDrop(dt) {
578
- const entries = [];
579
- for (const it of dt.items || []) { // webkitGetAsEntry 는 await 이전에 모두 호출해야 한다
580
- if (it.kind === 'file') { const e = it.webkitGetAsEntry && it.webkitGetAsEntry(); if (e) entries.push(e); }
581
- }
582
- if (!entries.length) return fromInput(dt.files || []);
583
- const out = [];
584
- for (const e of entries) await walk(e, '', out);
585
- return out;
586
- }
587
-
588
- /* ── 렌더링 ─────────────────────────────────────────── */
589
- /* ── 진행률 (서버가 알려주는 단계 → 퍼센트) ───────────── */
590
- const STAGE_PCT = { uploading: 15, submitting: 25, queued_waiting: 35, preparing: 45, downloading: 96 };
591
- const BUSY = ['sending', 'running', 'cancelling'];
592
- function itemProgress(it) {
593
- if (it.status === 'done') return 100;
594
- if (it.status === 'sending') return 8;
595
- if (!BUSY.includes(it.status)) return 0;
596
- const st = it.stage || 'queued_waiting';
597
- if (st === 'executing') { // 실행 중에는 시간에 따라 천천히 차오르게(최대 95%)
598
- const t = Math.max(0, (Date.now() - (it.execStart || Date.now())) / 1000);
599
- return Math.round(50 + 45 * (1 - Math.exp(-t / 70)));
600
- }
601
- return STAGE_PCT[st] ?? 30;
602
- }
603
-
604
- function statusLine(it) {
605
- switch (it.status) {
606
- case 'idle': return ['대기', ''];
607
- case 'needs': return ['남자·여자를 선택하세요', 'warn'];
608
- case 'skip': return ['건너뜀', ''];
609
- case 'queued': return ['순서 대기', ''];
610
- case 'sending': return ['보내는 중', 'go'];
611
- case 'running': return [friendlyStage(it.stageLabel), 'go'];
612
- case 'cancelling': return ['취소하는 중…', 'warn'];
613
- case 'cancelled': return ['취소됨', ''];
614
- case 'done': return [`완료 · ${fmtSec(it.elapsed)}`, 'ok'];
615
- case 'error': return [friendlyError(it.error), 'bad'];
616
- }
617
- return ['', ''];
618
- }
619
-
620
- function overlayHTML(it) { // 사진 위에 ���는 상태 표시
621
- switch (it.status) {
622
- case 'sending': case 'running':
623
- return `<div class="ph cover"><div class="ring">${ic('sparkles', 15)}</div><div class="t">${esc(friendlyStage(it.stageLabel || '이미지를 보내는 중'))}</div></div>`;
624
- case 'cancelling': return `<div class="ph cover"><div class="t">취소하는 중…</div></div>`;
625
- case 'cancelled': return `<div class="ph cover"><div class="t">취소됨</div></div>`;
626
- case 'error': return `<div class="ph cover err">${ic('alert', 18)}<div class="t" style="color:var(--red)">처리하지 못했어요</div></div>`;
627
- case 'queued': return `<div class="ph cover soft"><div class="t">순서 대기</div></div>`;
628
- case 'skip': return `<div class="ph cover soft"><div class="s">건너뜀</div></div>`;
629
- case 'needs': return `<div class="ph cover soft"><div class="t">남자·여자 선택</div></div>`;
630
- }
631
- return '';
632
- }
633
-
634
- function cardHTML(it) { // 폴더 안 사진 1장 = 작은 타일 1개
635
- const [st, cls] = statusLine(it);
636
- const locked = ['queued', 'sending', 'running', 'cancelling', 'done'].includes(it.status);
637
- const seg = ['male', 'female', 'skip'].map((g) => {
638
- const on = g === 'skip' ? it.status === 'skip' : it.gender === g && it.status !== 'skip';
639
- return `<button type="button" class="${on ? 'on' : ''}" data-gender="${g}" ${locked ? 'disabled' : ''}>${g === 'skip' ? '건너뜀' : GNAME[g]}</button>`;
640
- }).join('');
641
- const done = it.status === 'done', busy = BUSY.includes(it.status), pct = itemProgress(it);
642
- const autoNote = it.gender === it.auto ? (it.autoFrom === 'folder' ? '폴더 이름' : it.autoFrom === 'zip' ? 'ZIP 이름' : '') : '';
643
- const actions = done ? `<a class="btn sm" href="/api/swap/jobs/${it.jobId}/download">${ic('download', 12)}받기</a>`
644
- : (it.status === 'error' || it.status === 'cancelled') ? `<button class="btn sm" type="button" data-retry>${ic('refresh', 12)}다시 시도</button>`
645
- : (it.status === 'queued' || it.status === 'sending' || it.status === 'running') ? `<button class="btn sm stopbtn" type="button" data-cancel>취소</button>` : '';
646
- return `
647
- <figure class="res ${done ? 'clickable' : ''}" ${done ? 'data-open title="눌러서 원본과 비교"' : ''}>
648
- <img alt="" loading="lazy" decoding="async" src="${done ? `/api/swap/jobs/${it.jobId}/thumb` : it.previewUrl}">
649
- ${done ? `<img class="origthumb" alt="원본" src="${it.previewUrl}"><span class="zoom">${ic('maximize', 14)}</span>` : ''}
650
- ${!done && it.gender && it.status !== 'skip' ? `<span class="gchip"${autoNote ? ` title="${autoNote}에서 정했어요"` : ''}>${GNAME[it.gender]}${autoNote ? ` (${autoNote === 'ZIP 이름' ? 'ZIP' : '폴더'})` : ''}</span>` : ''}
651
- ${overlayHTML(it)}
652
- ${busy ? `<div class="cprog" title="진행률"><i data-prog="${it.id}" style="width:${pct}%"></i></div>` : ''}
653
- </figure>
654
- <div class="meta">
655
- <div class="fname" title="${esc(it.relPath)}">${esc(it.name)}</div>
656
- <div class="seg mini" role="group" aria-label="바꿔 넣을 얼굴">${seg}</div>
657
- <div class="row2">
658
- <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>
659
- ${actions}
660
- </div>
661
- ${it.status === 'error' ? `<div><button class="linkbtn" type="button" data-detail>${it.showErr ? '자세히 접기' : '자세히 보기'}</button>${it.showErr ? `<div class="errbox">${esc(it.error)}</div>` : ''}</div>` : ''}
662
- </div>`;
663
- }
664
-
665
- function renderAll() {
666
- const folders = new Map();
667
- for (const it of state.items) { if (!folders.has(it.folder)) folders.set(it.folder, []); folders.get(it.folder).push(it); }
668
- $('#folders').innerHTML = [...folders.entries()].map(([name, items]) => `
669
- <section class="folder" data-folder="${esc(name)}">
670
- <div class="folder-head">
671
- <h3>${ic('folder', 16)}${esc(name)}</h3><span class="cnt" data-cnt>${items.length}장</span><span class="sp"></span>
672
- <button class="btn sm" type="button" data-zip ${items.some((i) => i.status === 'done') ? '' : 'disabled'}>${ic('download', 13)}이 폴더 ZIP</button>
673
- <button class="btn sm danger" type="button" data-remove>폴더 빼기</button>
674
- </div>
675
- <div class="grid">${items.map((it) => `<article class="card ${it.status === 'error' ? 'is-error' : ''}" data-id="${it.id}">${cardHTML(it)}</article>`).join('')}</div>
676
- </section>`).join('');
677
- $('#empty').hidden = state.items.length > 0;
678
- syncTop();
679
- updateSummary();
680
- }
681
-
682
- function updateItem(it) {
683
- const el = document.querySelector(`.card[data-id="${it.id}"]`);
684
- if (!el) return renderAll();
685
- el.className = `card ${it.status === 'error' ? 'is-error' : ''}`;
686
- el.innerHTML = cardHTML(it);
687
- const sec = el.closest('.folder');
688
- if (sec) {
689
- const mine = state.items.filter((i) => i.folder === sec.dataset.folder);
690
- sec.querySelector('[data-zip]').disabled = !mine.some((i) => i.status === 'done');
691
- }
692
- updateSummary();
693
- }
694
-
695
- const count = (s) => state.items.filter((i) => s.includes(i.status)).length;
696
- const concurrency = () => Math.min(state.maxConc, Math.max(1, state.conc));
697
-
698
- function etaText() {
699
- const done = state.items.filter((i) => i.status === 'done' && i.elapsed);
700
- const left = count(['queued', 'sending', 'running']);
701
- if (!done.length || !left) return '';
702
- const avg = done.reduce((a, i) => a + i.elapsed, 0) / done.length;
703
- const min = Math.max(1, Math.round((Math.ceil(left / concurrency()) * avg) / 60));
704
- return `약 ${min}분 남았어요`;
705
- }
706
-
707
- function renderBanners() {
708
- const parts = [];
709
- 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>`);
710
- const needs = count(['needs']);
711
- if (needs) parts.push(`<div class="note warn">${ic('alert', 16)}<div class="grow"><b>${needs}장</b>은 파일명에서 남자·여자를 알 수 없어요. 카드에서 하나씩 고르거나, 한 번에 정할 수 있어요.<div class="row">
712
- <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>`);
713
- $('#banners').innerHTML = parts.join('');
714
- }
715
-
716
- /* ── 전체 진행 막대 ─────────────────────────────────── */
717
- function overallStats() {
718
- const items = state.items.filter((i) => i.status !== 'skip');
719
- const n = items.length;
720
- let done = 0, run = 0, bad = 0, can = 0;
721
- for (const it of items) {
722
- if (it.status === 'done') done += 1;
723
- else if (BUSY.includes(it.status)) run += itemProgress(it) / 100;
724
- else if (it.status === 'error') bad += 1;
725
- else if (it.status === 'cancelled') can += 1;
726
- }
727
- return { n, done, run, bad, can, pct: n ? Math.min(100, Math.round(((done + run) / n) * 100)) : 0 };
728
- }
729
- function renderOverallBar() {
730
- const o = overallStats(); if (!o.n) { $('#pbar').innerHTML = ''; $('#pct').textContent = '0%'; return o; }
731
- const w = (x) => `${((x / o.n) * 100).toFixed(2)}%`;
732
- $('#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>`;
733
- $('#pct').textContent = `${o.pct}%`;
734
- return o;
735
- }
736
- function tickProgress() { // 1초마다 막대만 가볍게 갱신
737
- let any = false;
738
- for (const it of state.items) {
739
- if (!BUSY.includes(it.status)) continue;
740
- any = true;
741
- const pct = itemProgress(it);
742
- const bar = document.querySelector(`[data-prog="${it.id}"]`); if (bar) bar.style.width = `${pct}%`;
743
- const tx = document.querySelector(`[data-ptxt="${it.id}"]`); if (tx) tx.textContent = `${pct}%`;
744
- }
745
- if (any) { renderOverallBar(); updateSumText(); }
746
- }
747
- setInterval(tickProgress, 1000);
748
-
749
- function updateSumText() {
750
- const total = state.items.length;
751
- const idle = count(['idle']), needs = count(['needs']), done = count(['done']);
752
- const faceMissing = ['male', 'female'].filter((g) => !state.faces[g].ok && state.items.some((i) => i.gender === g && ['idle', 'queued'].includes(i.status)));
753
- const o = overallStats(), eta = etaText();
754
- $('#sum').innerHTML = state.running ? ''
755
- : faceMissing.length ? `<b>${faceMissing.map((g) => GNAME[g]).join('·')}</b> 얼굴 사진이 서버에 없어서 시작할 수 없어요. 관리자에게 알려 주세요.`
756
- : needs ? `남자·여자가 정해지지 않은 <b>${needs}장</b>은 건너뛰고 시작해요.`
757
- : idle ? `<b>${idle}장</b>을 처리하면 Comfy 크레딧이 사용돼요.` : '';
758
- }
759
-
760
- function updateSummary() {
761
- const total = state.items.length;
762
- const idle = count(['idle']), needs = count(['needs']), done = count(['done']), err = count(['error']), can = count(['cancelled']);
763
- const active = count(['queued', 'sending', 'running', 'cancelling']), skip = count(['skip']);
764
- const targets = total - skip;
765
- $('#addZip').hidden = total === 0;
766
-
767
- const eta = etaText();
768
- const started = done + active + err + can > 0; // 작업을 시작하기 전에는 진행 막대를 숨긴다
769
- $('.barrow').hidden = !started;
770
- $('#sumLine').innerHTML = started && targets ? `${done} / ${targets}장 완료${eta ? `<small>${eta}</small>` : ''}` : `사진 ${total}장`;
771
- $('#chips').innerHTML =
772
- (state.running ? `<span class="chip">한 번에 ${concurrency()}장씩</span>` : '') +
773
- (active ? `<span class="chip go">진행 중 ${active}</span>` : '') +
774
- (idle ? `<span class="chip">시작 전 ${idle}</span>` : '') +
775
- (needs ? `<span class="chip warn">남자·여자 선택 필요 ${needs}</span>` : '') +
776
- (err ? `<span class="chip bad">실패 ${err}</span>` : '') +
777
- (can ? `<span class="chip">취소 ${can}</span>` : '') +
778
- (skip ? `<span class="chip">건너뜀 ${skip}</span>` : '');
779
- renderOverallBar();
780
- $('#zipAll').disabled = done === 0;
781
- $('#retry').hidden = (err + can) === 0 || state.running;
782
- renderBanners();
783
-
784
- const faceMissing = ['male', 'female'].filter((g) => !state.faces[g].ok && state.items.some((i) => i.gender === g && ['idle', 'queued'].includes(i.status)));
785
- const go = $('#go');
786
- go.disabled = state.running || idle === 0 || faceMissing.length > 0 || !!(state.health && !state.health.ok);
787
- go.innerHTML = state.running ? `<span class="spin">${ic('refresh', 15)}</span>얼굴을 바꾸는 중…`
788
- : idle ? `${ic('sparkles', 15)}${idle}장 얼굴 교체 시작` : total ? (done ? '모두 끝났어요' : '시작할 이미지가 없어요') : '이미지를 올려 주세요';
789
- $('#stop').hidden = !state.running;
790
- updateSumText();
791
- }
792
-
793
- /* ── 실행 큐 ────────────────────────────────────────── */
794
- const settings = () => ({}); // 얼굴 교체 설정은 서버(워크플로우)의 기본값을 그대로 쓴다
795
- const resetItem = (it) => { it.status = 'queued'; it.error = ''; it.cancelRequested = false; it.stage = ''; it.execStart = 0; it.jobId = null; };
796
-
797
- function startAll() {
798
- state.cancelled = false; state.running = true;
799
- for (const it of state.items) if (it.status === 'idle') it.status = 'queued';
800
- renderAll(); pump();
801
- }
802
-
803
- function pump() {
804
- if (state.cancelled) return maybeFinish();
805
- while (state.inflight < concurrency()) {
806
- const it = state.items.find((i) => i.status === 'queued');
807
- if (!it) break;
808
- state.inflight++; it.status = 'sending'; it.startedAt = Date.now(); updateItem(it);
809
- runItem(it).finally(() => { state.inflight--; pump(); });
810
- }
811
- maybeFinish();
812
- }
813
-
814
- let softToastAt = 0;
815
- function maybeFinish() {
816
- if (state.running && !state.items.some((i) => ['queued', 'sending', 'running', 'cancelling'].includes(i.status))) {
817
- state.running = false; updateSummary();
818
- if (state.cancelled && Date.now() - softToastAt > 10000) toast('취소했어요. 취소한 이미지는 ‘다시 시도’로 처음부터 할 수 있어요.', 'ok', 5000); // 'Cloud 에서 계속 진행' 경고가 떠 있으면 덮어쓰지 않는다
819
- }
820
- }
821
-
822
- /* ── 취소 ───────────────────────────────────────────── */
823
- async function postCancel(ids) {
824
- ids = ids.filter(Boolean); if (!ids.length) return;
825
- try { await fetch('/api/swap/cancel', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids }) }); }
826
- catch { toast('취소 요청을 보내지 못했어요. 잠시 뒤 다시 눌러 주세요.', 'warn'); }
827
- }
828
- function notifySoft() {
829
- if (Date.now() - softToastAt < 8000) return; softToastAt = Date.now();
830
- toast('Comfy Cloud에서 이미 실행 중이던 작업은 끝까지 진행될 수 있어요. 결과는 버렸고, 크레딧이 일부 쓰였을 수 있어요.', 'warn', 9000);
831
- }
832
- function cancelAll() {
833
- if (!state.running) return;
834
- softToastAt = 0; state.cancelled = true;
835
- const ids = [];
836
- for (const it of state.items) {
837
- if (it.status === 'queued') it.status = 'idle'; // 아직 보내지 않은 건 그냥 대기로 되돌림
838
- else if (it.status === 'sending') { it.cancelRequested = true; it.status = 'cancelling'; }
839
- else if (it.status === 'running') { it.cancelRequested = true; it.status = 'cancelling'; ids.push(it.jobId); }
840
- }
841
- renderAll(); postCancel(ids);
842
- toast('취소하는 중이에요. 잠시만 기다려 주세요.', 'info', 4000);
843
- maybeFinish();
844
- }
845
- function cancelItem(it) {
846
- softToastAt = 0;
847
- if (it.status === 'queued') { it.status = 'idle'; return updateItem(it); }
848
- if (it.status === 'sending') { it.cancelRequested = true; it.status = 'cancelling'; return updateItem(it); }
849
- if (it.status === 'running') { it.cancelRequested = true; it.status = 'cancelling'; updateItem(it); postCancel([it.jobId]); }
850
- }
851
-
852
- async function runItem(it) {
853
- try {
854
- const fd = new FormData();
855
- fd.append('image', it.file, it.name);
856
- fd.append('rel_path', it.relPath);
857
- fd.append('gender', it.gender);
858
- fd.append('face_id', state.faces[it.gender].id);
859
- fd.append('settings', JSON.stringify(settings()));
860
- const r = await fetch('/api/swap/jobs', { method: 'POST', body: fd });
861
- if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || `서버 오류 (HTTP ${r.status})`); }
862
- it.jobId = (await r.json()).jobId;
863
- if (it.cancelRequested) { it.status = 'cancelling'; updateItem(it); await postCancel([it.jobId]); } // 보내는 중에 취소를 눌렀다면 바로 취소
864
- else { it.status = 'running'; it.stageLabel = '대기 중'; it.stage = 'queued_waiting'; updateItem(it); }
865
-
866
- let misses = 0;
867
- for (;;) {
868
- await sleep(it.status === 'cancelling' ? 1000 : 3000);
869
- let res;
870
- try { res = await fetch(`/api/swap/jobs/${it.jobId}`); } catch { if (++misses > 10) throw new Error('서버 응답이 없습니다.'); continue; }
871
- if (res.status === 404) throw new Error('작업 정보를 잃어버렸습니다 (서버가 재시작됨). 다시 시도해주세요.');
872
- if (!res.ok) { if (++misses > 10) throw new Error(`서버 오류 (HTTP ${res.status})`); continue; }
873
- misses = 0;
874
- const j = await res.json();
875
- if (j.stage === 'executing' && !it.execStart) it.execStart = Date.now();
876
- it.stage = j.stage;
877
- if (j.status === 'cancelled') { it.status = 'cancelled'; if (j.cancelMode === 'soft') notifySoft(); break; }
878
- if (j.status === 'done') { it.status = 'done'; it.elapsed = j.elapsedSec; refreshStatus(); break; }
879
- if (j.status === 'error') throw new Error(j.error || '처리에 실패했습니다.');
880
- if (j.stageLabel !== it.stageLabel) { it.stageLabel = j.stageLabel; if (it.status !== 'cancelling') updateItem(it); }
881
- }
882
- } catch (e) {
883
- if (it.cancelRequested) it.status = 'cancelled'; else { it.status = 'error'; it.error = e.message || String(e); }
884
- }
885
- updateItem(it);
886
- }
887
-
888
- /* ── 라이트박스: 원본 ↔ 결과 슬라이더 ───────────────── */
889
- function openCompare({ title, before, after, dl }) {
890
- $('#lbTitle').textContent = title;
891
- $('#lbDl').href = dl;
892
- $('#cmp').innerHTML = `<img class="a" alt="원본" src="${before}"><img class="b" alt="결과" src="${after}" style="clip-path: inset(0 0 0 50%)"><div class="barv" style="left:50%"></div><span class="tag l">원본</span><span class="tag r">결과</span>`;
893
- $('#lb').hidden = false;
894
- document.body.style.overflow = 'hidden';
895
- }
896
- const openLightbox = (it) => openCompare({ title: it.relPath, before: it.previewUrl, after: `/api/swap/jobs/${it.jobId}/view`, dl: `/api/swap/jobs/${it.jobId}/download` });
897
- function closeLightbox() { $('#lb').hidden = true; $('#cmp').innerHTML = ''; document.body.style.overflow = ''; }
898
- (function bindCompare() {
899
- const box = $('#cmp'); let drag = false;
900
- const move = (e) => {
901
- const r = box.getBoundingClientRect();
902
- const p = Math.min(100, Math.max(0, ((e.clientX - r.left) / r.width) * 100));
903
- const b = box.querySelector('.b'), bar = box.querySelector('.barv');
904
- if (b) b.style.clipPath = `inset(0 0 0 ${p}%)`;
905
- if (bar) bar.style.left = `${p}%`;
906
- };
907
- box.addEventListener('pointerdown', (e) => { drag = true; box.setPointerCapture(e.pointerId); move(e); });
908
- box.addEventListener('pointermove', (e) => { if (drag) move(e); });
909
- box.addEventListener('pointerup', () => { drag = false; });
910
- })();
911
-
912
- /* ── ZIP ────────────────────────────────────────────── */
913
- function submitZip(ids, name) {
914
- if (!ids.length) return;
915
- const f = $('#zipForm');
916
- f.ids.value = ids.join(','); f.name.value = name;
917
- f.submit();
918
- }
919
- const downloadZip = (items, name) => submitZip(items.filter((i) => i.status === 'done').map((i) => i.jobId), name);
920
-
921
- /* ── 탭 / 지난 결과 ─────────────────────────────────── */
922
- const hist = { items: [], sel: new Set(), loaded: false };
923
- const syncTop = () => { const show = state.view === 'work' && state.items.length > 0; $('#top').hidden = !show; $('.stick').hidden = !show; };
924
-
925
- function setView(v) {
926
- state.view = v;
927
- document.querySelectorAll('.pill').forEach((b) => b.classList.toggle('on', b.dataset.view === v));
928
- $('#workView').hidden = v !== 'work'; $('#histView').hidden = v !== 'hist';
929
- syncTop();
930
- if (v === 'hist') loadHistory();
931
- }
932
- document.querySelectorAll('.pill').forEach((b) => { b.onclick = () => setView(b.dataset.view); });
933
-
934
- function renderDur() {
935
- const st = state.histStatus, el = $('#dur');
936
- if (!st) { el.hidden = true; return; }
937
- el.hidden = false;
938
- if (st.durable) {
939
- el.className = `status ${st.error ? 'warn' : 'ok'}`;
940
- el.querySelector('span').textContent = st.error ? '저장소 연결을 확인하는 중' : st.unsynced ? '결과 저장하는 중…' : '결과가 자동으로 저장돼요';
941
- el.title = `${st.remote}${st.error ? ' · ' + st.error : ''}`;
942
- } else {
943
- el.className = 'status warn';
944
- el.querySelector('span').textContent = '임시 저장 (재시작하면 사라져요)';
945
- el.title = 'Space Secrets 에 HF_TOKEN, HF_DATASET_REPO 를 넣으면 계속 남아요.';
946
- }
947
- const b = $('#histBadge'); b.hidden = !st.count; b.textContent = st.count || '';
948
- }
949
- function renderConn() {
950
- const el = $('#conn');
951
- if (state.health && !state.health.ok) { el.hidden = false; el.className = 'status warn'; el.querySelector('span').textContent = '서비스 연결 설정 필요'; } else el.hidden = true;
952
- }
953
- async function refreshStatus() {
954
- try { state.histStatus = await (await fetch('/api/history/status')).json(); renderDur(); } catch { /* 무시 */ }
955
- }
956
-
957
- async function loadHistory() {
958
- try {
959
- const [h] = await Promise.all([fetch('/api/history').then((r) => r.json()), refreshStatus()]);
960
- hist.items = h.items; hist.loaded = true;
961
- for (const id of [...hist.sel]) if (!hist.items.some((i) => i.id === id)) hist.sel.delete(id);
962
- renderHistory();
963
- } catch { $('#hbanner').innerHTML = `<div class="note err">${ic('alert', 16)}<div class="grow">저장된 결과를 불러오지 못했어요. 잠시 뒤 다시 열어 보세요.</div></div>`; }
964
- }
965
-
966
- const kstDay = (back = 0) => new Date(Date.now() + 9 * 3600e3 - back * 86400e3).toISOString().slice(0, 10);
967
- function visibleHistory() {
968
- const q = $('#hq').value.trim().normalize('NFC').toLowerCase();
969
- const range = $('#hrange').value;
970
- const cutoff = range === 'all' ? '' : kstDay(parseInt(range, 10) - 1);
971
- return hist.items.filter((i) => (!q || (i.rel_path || '').normalize('NFC').toLowerCase().includes(q)) && (!cutoff || i.date >= cutoff));
972
- }
973
-
974
- function histCard(i) {
975
- const sel = hist.sel.has(i.id);
976
- return `<article class="hcard ${sel ? 'sel' : ''}" data-hid="${i.id}">
977
- <label class="pick" title="선택"><input type="checkbox" ${sel ? 'checked' : ''}></label>
978
- <figure data-hopen title="눌러서 원본과 비교"><img loading="lazy" decoding="async" alt="" src="/api/swap/jobs/${i.id}/thumb"></figure>
979
- <div class="meta">
980
- <div class="fname" title="${esc(i.rel_path)}">${esc(i.filename)}</div>
981
- <div class="row2"><span class="state"><span>${GNAME[i.gender] || ''} · ${esc(i.time || '')}</span></span><a class="btn sm" href="/api/swap/jobs/${i.id}/download">${ic('download', 13)}받기</a></div>
982
- </div></article>`;
983
- }
984
-
985
- function renderHistory() {
986
- const st = state.histStatus; let banner = '';
987
- 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>`;
988
- else if (st && st.error) banner = `<div class="note err">${ic('alert', 16)}<div class="grow">저장소와 연결이 불안정해요. 결과는 지금 서버에 남아 있고, 연결되면 다시 저장을 시도해요.</div></div>`;
989
- else if (st && st.durable && st.restored === false) banner = `<div class="note warn">${ic('alert', 16)}<div class="grow">예전 기록을 불러오는 중이에요. 잠시 뒤 다시 열어 보세요.</div></div>`;
990
- $('#hbanner').innerHTML = banner;
991
-
992
- const items = visibleHistory();
993
- const byDate = new Map();
994
- for (const i of items) {
995
- if (!byDate.has(i.date)) byDate.set(i.date, new Map());
996
- const fm = byDate.get(i.date); if (!fm.has(i.folder)) fm.set(i.folder, []); fm.get(i.folder).push(i);
997
- }
998
- $('#hlist').innerHTML = [...byDate.entries()].sort((a, b) => b[0].localeCompare(a[0])).map(([date, fm]) => {
999
- const n = [...fm.values()].reduce((a, v) => a + v.length, 0);
1000
- return `<section class="hday"><h3>${esc(date)}<small>${n}장</small></h3>` +
1001
- [...fm.entries()].sort((a, b) => a[0].localeCompare(b[0], 'ko')).map(([folder, list]) => {
1002
- list.sort((a, b) => a.rel_path.localeCompare(b.rel_path, 'ko', { numeric: true }));
1003
- const ids = list.map((x) => x.id).join(',');
1004
- return `<div class="hgroup"><div class="hgroup-head"><b>${ic('folder', 15)}${esc(folder)}</b><span>${list.length}장</span><span class="sp"></span>
1005
- <button class="btn sm" type="button" data-hzipg data-ids="${ids}" data-name="${esc(date + '_' + folder)}">${ic('download', 13)}이 폴더 ZIP</button></div>
1006
- <div class="hgrid">${list.map(histCard).join('')}</div></div>`;
1007
- }).join('') + '</section>';
1008
- }).join('');
1009
- $('#hempty').hidden = items.length > 0;
1010
- $('#hemptyMsg').textContent = hist.items.length ? '검색 조건에 맞는 결과가 없어요.' : '작업이 끝나면 여기에 자동으로 쌓여요.';
1011
- updateHistToolbar();
1012
- }
1013
-
1014
- function updateHistToolbar() {
1015
- const vis = visibleHistory(), n = hist.sel.size;
1016
- $('#hcount').textContent = n ? `${n}장 선택됨` : `${vis.length}장`;
1017
- $('#hzip').disabled = n === 0; $('#hdel').disabled = n === 0;
1018
- $('#hall').textContent = vis.length && vis.every((i) => hist.sel.has(i.id)) ? '전체 해제' : '전체 선택';
1019
- $('#hlist').classList.toggle('has-sel', n > 0);
1020
- }
1021
-
1022
- $('#hq').addEventListener('input', () => { clearTimeout($('#hq')._t); $('#hq')._t = setTimeout(renderHistory, 200); });
1023
- $('#hrange').addEventListener('change', renderHistory);
1024
- $('#hall').onclick = () => {
1025
- const vis = visibleHistory(), all = vis.length && vis.every((i) => hist.sel.has(i.id));
1026
- vis.forEach((i) => (all ? hist.sel.delete(i.id) : hist.sel.add(i.id)));
1027
- renderHistory();
1028
- };
1029
- $('#hzip').onclick = () => submitZip([...hist.sel], `faceswap_선택_${kstDay()}`);
1030
- $('#hdel').onclick = async () => {
1031
- const ids = [...hist.sel]; if (!ids.length) return;
1032
- if (!confirm(`${ids.length}장을 지난 결과에서 지울까요?\n저장소의 파일은 그대로 남고, 이 목록에서만 사라져요.`)) return;
1033
- await fetch('/api/history/hide', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids }) });
1034
- hist.sel.clear(); loadHistory();
1035
- };
1036
- $('#hlist').addEventListener('change', (e) => {
1037
- const card = e.target.closest('.hcard'); if (!card || !e.target.matches('.pick input')) return;
1038
- const id = card.dataset.hid;
1039
- if (e.target.checked) hist.sel.add(id); else hist.sel.delete(id);
1040
- card.classList.toggle('sel', e.target.checked); updateHistToolbar();
1041
- });
1042
- $('#hlist').addEventListener('click', (e) => {
1043
- const z = e.target.closest('[data-hzipg]');
1044
- if (z) return submitZip(z.dataset.ids.split(','), z.dataset.name);
1045
- const open = e.target.closest('[data-hopen]');
1046
- if (open) {
1047
- const i = hist.items.find((x) => x.id === open.closest('.hcard').dataset.hid); if (!i) return;
1048
- openCompare({ title: i.rel_path, before: `/api/swap/jobs/${i.id}/source`, after: `/api/swap/jobs/${i.id}/view`, dl: `/api/swap/jobs/${i.id}/download` });
1049
- }
1050
- });
1051
-
1052
- /* ── 이벤트 ─────────────────────────────────────────── */
1053
- // ZIP 하나만 받는다. <label for=zipInput> 이라 브라우저가 직접 선택창을 연다(자바스크립트 클릭이 막힌 환경에서도 동작).
1054
- $('#zipInput').onchange = (e) => {
1055
- const f = e.target.files[0]; e.target.value = '';
1056
- if (!f) return;
1057
- if (!/\.zip$/i.test(f.name)) return toast('ZIP 파일(.zip)만 올릴 수 있어요. 폴더를 마우스 오른쪽 클릭 → 압축으로 ZIP을 만들어 주세요.', 'warn', 8000);
1058
- ingestAsync([{ file: f, relPath: f.name }], '선택창은 한 번에 한 개만 올릴 수 있어요. ZIP이 더 있으면 ‘ZIP 추가’를 다시 누르거나 끌어다 놓으세요.');
1059
- };
1060
- ['#drop', '#addZip'].forEach((sel) => {
1061
- $(sel).addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; e.preventDefault(); $('#zipInput').click(); });
1062
- });
1063
-
1064
- let dragDepth = 0;
1065
- window.addEventListener('dragenter', (e) => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { dragDepth++; document.body.classList.add('dragging'); } });
1066
- window.addEventListener('dragleave', () => { dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) document.body.classList.remove('dragging'); });
1067
- window.addEventListener('dragover', (e) => e.preventDefault());
1068
- window.addEventListener('drop', async (e) => {
1069
- e.preventDefault(); dragDepth = 0; document.body.classList.remove('dragging');
1070
- if (state.view !== 'work') setView('work');
1071
- let list;
1072
- try { list = await fromDrop(e.dataTransfer); }
1073
- catch (err) { console.error(err); return toast('올린 파일을 읽지 못했어요. ZIP 파일로 다시 올려 주세요.', 'err', 9000); }
1074
- ingestAsync(list);
1075
- });
1076
-
1077
- $('#go').onclick = startAll;
1078
- $('#stop').onclick = cancelAll;
1079
- $('#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(); };
1080
- $('#zipAll').onclick = () => downloadZip(state.items, 'faceswap_results');
1081
- $('#clear').onclick = () => {
1082
- if (state.running) return alert('처리 중에는 비울 수 없어요. 취소하거나 끝날 때까지 기다려 주세요.');
1083
- state.items.forEach((i) => URL.revokeObjectURL(i.previewUrl)); state.items = []; renderAll();
1084
- };
1085
- $('#lbClose').onclick = closeLightbox;
1086
- $('#lb').addEventListener('click', (e) => { if (e.target.id === 'lb' || e.target.classList.contains('lb-body')) closeLightbox(); });
1087
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('#lb').hidden) closeLightbox(); });
1088
-
1089
- $('#banners').addEventListener('click', (e) => {
1090
- const b = e.target.closest('[data-bulk]'); if (!b) return;
1091
- for (const it of state.items) {
1092
- if (it.status !== 'needs') continue;
1093
- if (b.dataset.bulk === 'skip') it.status = 'skip'; else { it.gender = b.dataset.bulk; it.status = 'idle'; }
1094
- }
1095
- renderAll();
1096
- });
1097
-
1098
- $('#folders').addEventListener('click', (e) => {
1099
- const card = e.target.closest('.card'); const sec = e.target.closest('.folder');
1100
- if (card) {
1101
- const it = state.items.find((i) => i.id === card.dataset.id);
1102
- if (!it) return;
1103
- const gbtn = e.target.closest('[data-gender]');
1104
- if (gbtn && !gbtn.disabled) {
1105
- const g = gbtn.dataset.gender;
1106
- if (g === 'skip') it.status = 'skip'; else { it.gender = g; it.status = 'idle'; }
1107
- it.error = ''; return updateItem(it);
1108
- }
1109
- if (e.target.closest('[data-cancel]')) return cancelItem(it);
1110
- if (e.target.closest('[data-retry]')) { resetItem(it); state.cancelled = false; state.running = true; updateItem(it); return pump(); }
1111
- if (e.target.closest('[data-detail]')) { it.showErr = !it.showErr; return updateItem(it); }
1112
- if (e.target.closest('[data-open]')) return openLightbox(it);
1113
- } else if (sec) {
1114
- const name = sec.dataset.folder;
1115
- const mine = state.items.filter((i) => i.folder === name);
1116
- if (e.target.closest('[data-zip]')) return downloadZip(mine, name);
1117
- if (e.target.closest('[data-remove]')) {
1118
- if (mine.some((i) => ['queued', 'sending', 'running', 'cancelling'].includes(i.status))) return alert('처리 중인 이미지가 있어 뺄 수 없어요. 먼저 취소해 주세요.');
1119
- mine.forEach((i) => URL.revokeObjectURL(i.previewUrl));
1120
- state.items = state.items.filter((i) => i.folder !== name); renderAll();
1121
- }
1122
- }
1123
- });
1124
-
1125
- if (window.top !== window.self) { // HF 처럼 다른 페이지 안에 끼워진 경우
1126
- $('#openTab').hidden = false; $('#openTab').href = location.href;
1127
- }
1128
-
1129
- window.addEventListener('beforeunload', (e) => { if (state.running) { e.preventDefault(); e.returnValue = ''; } });
1130
-
1131
- /* ── 초기화 ─────────────────────────────────────────── */
1132
- async function init() {
1133
- renderAll();
1134
- try {
1135
- const f = await (await fetch('/api/swap/faces')).json();
1136
- for (const g of ['male', 'female']) state.faces[g] = { id: f[g].id, ok: f[g].available };
1137
- } catch { /* 무시 */ }
1138
- try {
1139
- state.health = await (await fetch('/api/health')).json();
1140
- if (state.health.maxConcurrent) state.maxConc = Math.max(1, Math.min(4, state.health.maxConcurrent));
1141
- state.conc = Math.min(state.conc, state.maxConc);
1142
- } catch { state.health = { ok: false, error: '서버에 연결하지 못했어요. 잠시 뒤 새로고침해 주세요.' }; }
1143
- renderConn(); updateSummary();
1144
- refreshStatus(); setInterval(refreshStatus, 30000);
1145
- }
1146
- init();
1147
- })();
1148
- </script>
1149
- </body>
1150
- </html>