sunyoung00 commited on
Commit
947a2f3
·
verified ·
1 Parent(s): cd76426

Delete index.html

Browse files
Files changed (1) hide show
  1. index.html +0 -700
index.html DELETED
@@ -1,700 +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.0" />
6
- <title>CLOVIS AI 룩북 생성기</title>
7
- <script src="https://cdn.tailwindcss.com"></script>
8
- <script>
9
- tailwind.config = { darkMode: 'class', theme: { extend: { colors: { brand: { blue: '#3B82F6', hover: '#2563EB' } } } } }
10
- </script>
11
- <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin />
12
- <link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css" />
13
- <style>
14
- * { font-family: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
15
- body { -webkit-font-smoothing: antialiased; background: #1a1a1a; color: #f9fafb; margin: 0; overflow: hidden; }
16
- ::-webkit-scrollbar { width: 6px; height: 6px; }
17
- ::-webkit-scrollbar-track { background: #1a1a1a; }
18
- ::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
19
- ::-webkit-scrollbar-thumb:hover { background: #4b5563; }
20
- @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
21
- @keyframes shimmer { 0% { background-position: -600px 0; } 100% { background-position: 600px 0; } }
22
- @keyframes pulseRing { 0% { transform: scale(0.85); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
23
- .animate-fadeIn { animation: fadeIn .25s ease-out; }
24
- .shimmer { background: linear-gradient(90deg, #232323 0%, #2c2c2c 40%, #232323 80%); background-size: 600px 100%; animation: shimmer 1.6s linear infinite; }
25
- .pulse-ring::before { content: ''; position: absolute; inset: -6px; border-radius: 9999px; border: 2px solid #3B82F6; animation: pulseRing 1.4s ease-out infinite; }
26
- .ai-label-overlay { position: absolute; top: 12pt; right: 12pt; font-weight: 300; font-size: 10pt; color: #3c3c3c; pointer-events: none; z-index: 2; letter-spacing: -0.02em; }
27
- .drop-active { border-color: #3B82F6 !important; background: rgba(59,130,246,.08) !important; }
28
- textarea { resize: vertical; }
29
- </style>
30
- <script type="importmap">
31
- { "imports": {
32
- "react": "https://esm.sh/react@19.1.0",
33
- "react/": "https://esm.sh/react@19.1.0/",
34
- "react-dom/": "https://esm.sh/react-dom@19.1.0/",
35
- "lucide-react": "https://esm.sh/lucide-react@0.462.0?external=react"
36
- } }
37
- </script>
38
- </head>
39
- <body>
40
- <div id="root"></div>
41
- <script type="module">
42
- import React, { useState, useEffect, useRef, useCallback } from 'react';
43
- import ReactDOM from 'react-dom/client';
44
- import { Download, X, Upload, Sparkles, RefreshCw, AlertTriangle, Clock, Check, ImagePlus, User, Maximize2, ChevronDown } from 'lucide-react';
45
-
46
- const h = React.createElement;
47
-
48
- // ═══════════════════════════════════════════════════════════
49
- // Constants — 워크플로우(SPAO.json) CustomCombo 옵션과 1:1
50
- // ═══════════════════════════════════════════════════════════
51
- const SHOT_OPTIONS = ['전신컷', '상반신컷', '하반신컷']; // 프레임은 항상 샷 규칙이 정함 (레퍼런스는 포즈 참고용)
52
- const ANGLE_OPTIONS = ['정면', '반측면', '측면', '로우앵글', '하이앵글', '후면', '레퍼런스 따름'];
53
- const GAZE_OPTIONS = ['카메라 응시', '자연스러운 시선', '레퍼런스 따름'];
54
- const AGE_OPTIONS = ['성인', '키즈'];
55
- const DETAIL_GROUPS = [
56
- { key: 'outer', label: '아우터', length: 'outer_length', fit: 'outer_fit' },
57
- { key: 'top', label: '상의', length: 'top_length', fit: 'top_fit' },
58
- { key: 'bottom', label: '하의', length: 'bottom_length', fit: 'bottom_fit' },
59
- ];
60
- const DETAIL_OPTIONS = {
61
- outer_length: { label: '아우터 길이', options: ['허리', '골반', '허벅지'], def: '골반' },
62
- outer_fit: { label: '아우터 핏', options: ['슬림', '표준', '오버'], def: '표준' },
63
- top_length: { label: '상의 길이', options: ['허리', '골반', '허벅지'], def: '골반' },
64
- top_fit: { label: '상의 핏', options: ['슬림', '표준', '오버'], def: '오버' },
65
- bottom_length: { label: '하의 길이', options: ['허벅지', '무릎', '종아리', '발목', '신발'], def: '신발' },
66
- bottom_fit: { label: '하의 핏', options: ['슬림', '표준', '오버'], def: '오버' },
67
- };
68
-
69
- const ADULT_FACE_PRESETS = [
70
- { id: 'preset_17', label: '여성 1', url: '/face_preset_17.png' },
71
- { id: 'preset_18', label: '여성 2', url: '/face_preset_18.png' },
72
- { id: 'preset_19', label: '여성 3', url: '/face_preset_19.png' },
73
- ];
74
- // CLOVIS 는 키즈 라인이 없어 키즈 프리셋·연령 토글을 노출하지 않음 (워크플로우 age 콤보에는 '성인' 고정 전달)
75
-
76
- const IMAGE_SLOTS = [
77
- { key: 'outer', label: '아우터', required: false },
78
- { key: 'top', label: '상의', required: false },
79
- { key: 'bottom', label: '하의', required: false, hint: '원피스도 여기' },
80
- { key: 'shoes', label: '신발', required: false },
81
- { key: 'inner', label: '이너웨어', required: false },
82
- { key: 'belt', label: '벨트', required: false },
83
- { key: 'background', label: '배경', required: false, hint: '비우면 기본 스튜디오' },
84
- { key: 'pose', label: '레퍼런스 포즈', required: false, hint: '포즈 참고용 · 구도는 샷 선택 기준' },
85
- ];
86
-
87
- // 디테일 참조: 클로즈업을 생성 모델에 직접 참조로 전달 (전체 최대 4장)
88
- // 옷마다 슬롯 2개(a/b), 슬롯별로 종류를 고름 — 종류는 comfy_client.DETAIL_KIND_EN 키와 1:1
89
- const DETAIL_MAX = 4;
90
- const DETAIL_SLOTS = ['a', 'b'];
91
- // 옷 종류별 디테일 항목 — key 는 comfy_client.DETAIL_KIND_EN 과 1:1. short: 칩 표시, label: 툴팁
92
- const K = {
93
- texture: { key: 'texture', short: '조직감', label: '원단 조직감 (옷 전체에 반영)' },
94
- logo: { key: 'logo', short: '로고', label: '로고·프린트 (메인 사진과 같은 위치)' },
95
- neckline: { key: 'neckline', short: '넥라인', label: '넥라인·카라' },
96
- collar: { key: 'collar', short: '카라·후드', label: '카라·후드·라펠' },
97
- sleeve: { key: 'sleeve', short: '소매', label: '소매·커프스' },
98
- hem: { key: 'hem', short: '밑단', label: '밑단·헴 마감' },
99
- waist: { key: 'waist', short: '허리', label: '허리 (웨이스트밴드·벨트루프·드로스트링)' },
100
- pocket: { key: 'pocket', short: '포켓', label: '포켓 (형태·스티치·플랩)' },
101
- closure: { key: 'closure', short: '지퍼·버튼', label: '지퍼·버튼·스냅' },
102
- trim: { key: 'trim', short: '부자재', label: '부자재 (라벨·탭·와펜 등)' },
103
- material: { key: 'material', short: '소재', label: '소재·질감 (가죽·스웨이드·메시 등, 전체에 반영)' },
104
- sole: { key: 'sole', short: '밑창', label: '밑창·아웃솔' },
105
- lacing: { key: 'lacing', short: '끈', label: '끈·아일렛·설포' },
106
- heel: { key: 'heel', short: '뒤축', label: '뒤축·힐탭·발목' },
107
- buckle: { key: 'buckle', short: '버클', label: '버클' },
108
- edge: { key: 'edge', short: '스티치', label: '스티치·엣지·벨트홀' },
109
- };
110
- const DETAIL_KINDS_BY_GARMENT = {
111
- outer: [K.texture, K.logo, K.collar, K.sleeve, K.hem, K.pocket, K.closure, K.trim],
112
- top: [K.texture, K.logo, K.neckline, K.sleeve, K.hem, K.pocket, K.trim],
113
- bottom: [K.texture, K.logo, K.waist, K.hem, K.pocket, K.closure, K.trim],
114
- shoes: [K.material, K.logo, K.sole, K.lacing, K.heel, K.trim],
115
- inner: [K.texture, K.logo, K.neckline, K.sleeve, K.hem],
116
- belt: [K.material, K.buckle, K.logo, K.edge],
117
- };
118
- // 슬롯 기본값: 왼쪽 = 소재/조직감, 오른쪽 = 로고 (벨트는 버클)
119
- const defaultKind = (g, slot) => {
120
- const list = DETAIL_KINDS_BY_GARMENT[g] || [];
121
- if (slot === 'a') return list[0]?.key;
122
- return g === 'belt' ? 'buckle' : (list.find(k => k.key === 'logo') || list[1] || list[0])?.key;
123
- };
124
- const DETAIL_GARMENTS = [
125
- { key: 'outer', label: '아우터' }, { key: 'top', label: '상의' }, { key: 'bottom', label: '하의' },
126
- { key: 'shoes', label: '신발' }, { key: 'inner', label: '이너웨어' }, { key: 'belt', label: '벨트' },
127
- ];
128
-
129
- // AI 표기 — 저장 시 캔버스에 삽입 (기존 앱과 동일 규격)
130
- const AI_LABEL_TEXT = 'AI 생성 이미지';
131
- const AI_LABEL_FONT_PT = 28;
132
- const AI_LABEL_MARGIN_PT = 12 * (28 / 10);
133
-
134
- // ═══════════════════════════════════════════════════════════
135
- // Helpers
136
- // ═══════════════════════════════════════════════════════════
137
- const fileToDataUrl = (file, maxSide = 1536) => new Promise((resolve, reject) => {
138
- const reader = new FileReader();
139
- reader.onerror = reject;
140
- reader.onload = () => {
141
- const img = new Image();
142
- img.onerror = reject;
143
- img.onload = () => {
144
- const scale = Math.min(1, maxSide / Math.max(img.width, img.height));
145
- const w = Math.round(img.width * scale), hgt = Math.round(img.height * scale);
146
- const canvas = document.createElement('canvas');
147
- canvas.width = w; canvas.height = hgt;
148
- const ctx = canvas.getContext('2d');
149
- const keepPng = /png|webp/i.test(file.type);
150
- if (!keepPng) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, hgt); }
151
- ctx.drawImage(img, 0, 0, w, hgt);
152
- resolve(keepPng ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.92));
153
- };
154
- img.src = reader.result;
155
- };
156
- reader.readAsDataURL(file);
157
- });
158
-
159
- const drawAiDisclosureOnCanvas = (ctx, width, height) => {
160
- ctx.save();
161
- ctx.textAlign = 'right'; ctx.textBaseline = 'top'; ctx.fillStyle = '#3c3c3c';
162
- ctx.font = `300 ${AI_LABEL_FONT_PT}pt 'Pretendard', 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif`;
163
- const ptToPx = 96 / 72;
164
- const m = Math.max(AI_LABEL_MARGIN_PT * ptToPx, Math.min(width, height) * 0.028, 18);
165
- ctx.fillText(AI_LABEL_TEXT, width - m, m);
166
- ctx.restore();
167
- };
168
-
169
- async function downloadWithLabel(imageUrl, filename, withLabel = true) {
170
- const img = new Image();
171
- await new Promise((res, rej) => { img.onload = res; img.onerror = rej; img.src = imageUrl; });
172
- const canvas = document.createElement('canvas');
173
- canvas.width = img.naturalWidth; canvas.height = img.naturalHeight;
174
- const ctx = canvas.getContext('2d');
175
- ctx.drawImage(img, 0, 0);
176
- if (withLabel) drawAiDisclosureOnCanvas(ctx, canvas.width, canvas.height);
177
- const a = document.createElement('a');
178
- a.href = canvas.toDataURL('image/png'); a.download = filename; a.click();
179
- }
180
-
181
- const sleep = (ms) => new Promise(r => setTimeout(r, ms));
182
-
183
- // 비로그인 사용자도 작업을 다시 불러올 수 있도록 브라우저별 ID를 보관 (로그인 시엔 서버가 계정명으로 묶음)
184
- const CLIENT_ID = (() => {
185
- try {
186
- let id = localStorage.getItem('clovis_client_id');
187
- if (!id) { id = crypto.randomUUID(); localStorage.setItem('clovis_client_id', id); }
188
- return id;
189
- } catch { return 'c-' + Math.random().toString(36).slice(2); }
190
- })();
191
- const apiHeaders = (json = false) => ({ 'X-Client-Id': CLIENT_ID, ...(json ? { 'Content-Type': 'application/json' } : {}) });
192
-
193
- // 제출 → jobId → 폴링. 긴 HTTP 연결을 잡고 있지 않으므로 Space 프록시 타임아웃과 무관.
194
- async function submitToComfy(payload) {
195
- const res = await fetch('/api/comfy/generate', { method: 'POST', headers: apiHeaders(true), body: JSON.stringify(payload) });
196
- if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.detail || `HTTP ${res.status}`); }
197
- return (await res.json()).jobId;
198
- }
199
- async function pollComfyJob(jobId, onProgress) {
200
- let misses = 0;
201
- while (true) {
202
- await sleep(3000);
203
- let r;
204
- try { r = await fetch(`/api/comfy/jobs/${jobId}`, { headers: apiHeaders() }); } catch { if (++misses > 10) throw new Error('서버 응답이 없습니다.'); continue; }
205
- if (r.status === 404) throw new Error('작업 정보를 잃어버렸습니다 (서버 재시작). 다시 시도해주세요.');
206
- if (!r.ok) { if (++misses > 10) throw new Error(`HTTP ${r.status}`); continue; }
207
- misses = 0;
208
- const j = await r.json();
209
- onProgress?.(j);
210
- if (j.status === 'done') return j;
211
- if (j.status === 'cancelled') return null; // 사용자 취소 — 조용히 종료
212
- if (j.status === 'error') throw new Error(j.error || '생성 실패');
213
- }
214
- }
215
-
216
- const fmtSec = (s) => { s = Math.round(s || 0); return s >= 60 ? `${Math.floor(s / 60)}분 ${s % 60}초` : `${s}초`; };
217
-
218
- // ═══════════════════════════════════════════════════════════
219
- // UI atoms
220
- // ═══════════════════════════════════════════════════════════
221
- const SectionTitle = ({ children, right }) => h('div', { className: 'flex items-center justify-between mb-2.5' },
222
- h('h3', { className: 'text-[13px] font-semibold text-gray-200 tracking-tight' }, children), right || null);
223
-
224
- const Segmented = ({ options, value, onChange, cols }) => h('div', {
225
- className: `grid gap-1.5`, style: { gridTemplateColumns: `repeat(${cols || options.length}, minmax(0, 1fr))` } },
226
- options.map(o => h('button', {
227
- key: o, type: 'button', onClick: () => onChange(o),
228
- className: `px-2 py-2 rounded-lg text-[12.5px] font-medium border transition-colors ${value === o
229
- ? 'bg-brand-blue border-brand-blue text-white'
230
- : 'bg-[#242424] border-[#333] text-gray-300 hover:border-[#4b5563] hover:text-white'}`
231
- }, o)));
232
-
233
- const UploadTile = ({ slot, value, onChange, disabled }) => {
234
- const inputRef = useRef(null);
235
- const [drag, setDrag] = useState(false);
236
- const handleFiles = async (files) => {
237
- const f = files?.[0]; if (!f || !f.type.startsWith('image/')) return;
238
- onChange(await fileToDataUrl(f), f.name);
239
- };
240
- return h('div', {
241
- className: `relative rounded-xl border overflow-hidden group ${drag ? 'drop-active' : ''} ${value ? 'border-[#3a3a3a]' : 'border-dashed border-[#3a3a3a] bg-[#212121] hover:border-[#4b5563]'}`,
242
- style: { aspectRatio: '3 / 4' },
243
- onDragOver: e => { e.preventDefault(); setDrag(true); }, onDragLeave: () => setDrag(false),
244
- onDrop: e => { e.preventDefault(); setDrag(false); if (!disabled) handleFiles(e.dataTransfer.files); },
245
- onClick: () => !disabled && !value && inputRef.current?.click(),
246
- },
247
- h('input', { ref: inputRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: e => { handleFiles(e.target.files); e.target.value = ''; } }),
248
- value
249
- ? h(React.Fragment, null,
250
- h('img', { src: value, className: 'w-full h-full object-cover bg-white', alt: slot.label }),
251
- !disabled && h('button', { type: 'button', onClick: e => { e.stopPropagation(); onChange(null, null); },
252
- className: 'absolute top-1.5 right-1.5 w-6 h-6 rounded-full bg-black/70 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity' }, h(X, { size: 13 })),
253
- h('div', { className: 'absolute bottom-0 inset-x-0 px-2 py-1 bg-gradient-to-t from-black/70 to-transparent text-[11px] text-white' }, slot.label))
254
- : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-1 text-gray-500 cursor-pointer' },
255
- h(ImagePlus, { size: 18 }),
256
- h('span', { className: 'text-[11.5px] text-gray-300' }, slot.label, slot.required && h('span', { className: 'text-brand-blue ml-0.5' }, '*')),
257
- slot.hint && h('span', { className: 'text-[10px] text-gray-500 px-2 text-center leading-tight' }, slot.hint))
258
- );
259
- };
260
-
261
- const DetailTile = ({ value, onChange, disabled }) => {
262
- const inputRef = useRef(null);
263
- const handleFiles = async (files) => {
264
- const f = files?.[0]; if (!f || !f.type.startsWith('image/')) return;
265
- onChange(await fileToDataUrl(f, 1024), f.name);
266
- };
267
- return h('div', {
268
- className: `relative w-full rounded-lg overflow-hidden group ${value ? 'border border-[#3a3a3a]' : 'border border-dashed border-[#3a3a3a] bg-[#212121] hover:border-[#4b5563]'} ${disabled ? 'opacity-60 border-[#333]' : ''}`,
269
- style: { aspectRatio: '1 / 1' },
270
- onDragOver: e => e.preventDefault(), onDrop: e => { e.preventDefault(); if (!disabled) handleFiles(e.dataTransfer.files); },
271
- onClick: () => !disabled && !value && inputRef.current?.click(),
272
- },
273
- h('input', { ref: inputRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: e => { handleFiles(e.target.files); e.target.value = ''; } }),
274
- value
275
- ? h(React.Fragment, null,
276
- h('img', { src: value, className: 'w-full h-full object-cover bg-white' }),
277
- !disabled && h('button', { type: 'button', onClick: e => { e.stopPropagation(); onChange(null, null); },
278
- className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-black/70 text-white flex items-center justify-center opacity-0 group-hover:opacity-100' }, h(X, { size: 11 })))
279
- : h('div', { className: 'absolute inset-0 flex items-center justify-center text-gray-600 cursor-pointer' }, h(ImagePlus, { size: 14 })));
280
- };
281
-
282
- const FaceTile = ({ preset, selected, onClick }) => h('button', {
283
- type: 'button', onClick, title: preset.label,
284
- className: `relative rounded-xl overflow-hidden border-2 transition-colors ${selected ? 'border-brand-blue' : 'border-transparent hover:border-[#4b5563]'}`,
285
- style: { aspectRatio: '1 / 1' } },
286
- h('img', { src: preset.url, className: 'w-full h-full object-cover', alt: preset.label }),
287
- selected && h('div', { className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-brand-blue flex items-center justify-center' }, h(Check, { size: 12, className: 'text-white' })),
288
- h('div', { className: 'absolute bottom-0 inset-x-0 px-1.5 py-0.5 bg-black/60 text-[10.5px] text-white text-center' }, preset.label));
289
-
290
- // ═══════════════════════════════════════════════════════════
291
- // App
292
- // ═══════════════════════════════════════════════════════════
293
- function App() {
294
- const [user, setUser] = useState({ username: 'anonymous', is_logged_in: false, oauth_enabled: false });
295
- const [health, setHealth] = useState(null);
296
-
297
- const age = '성인'; // CLOVIS: 성인 고정
298
- const [facePreset, setFacePreset] = useState('preset_17');
299
- const [detailKinds, setDetailKinds] = useState({}); // 'outer:a' → kind key
300
- const [genCount, setGenCount] = useState(1); // 한 번에 생성할 매수
301
- const [faceUpload, setFaceUpload] = useState(null);
302
- const [shot, setShot] = useState('전신컷');
303
- const [angle, setAngle] = useState('반측면');
304
- const [gaze, setGaze] = useState('자연스러운 시선');
305
- const [prompt, setPrompt] = useState('');
306
- const [details, setDetails] = useState(Object.fromEntries(Object.entries(DETAIL_OPTIONS).map(([k, v]) => [k, v.def])));
307
- const [detailTab, setDetailTab] = useState('top');
308
- const [images, setImages] = useState({});
309
- const [imageNames, setImageNames] = useState({}); // 슬롯별 원본 파일명 (Dataset 로그·스타일코드 집계용)
310
- const [faceUploadName, setFaceUploadName] = useState(null);
311
- const [poseSpec, setPoseSpec] = useState(''); // 포즈 지시 문장 (비우면 GPT 비전이 레퍼런스에서 자동 추출)
312
-
313
- const [jobs, setJobs] = useState([]); // 진행 중/실패 작업 [{id, jobId, meta, stageLabel, startedAt, error}]
314
- const [tick, setTick] = useState(0); // 경과시간 표시용 1초 타이머
315
- const [results, setResults] = useState([]); // [{id, imageUrl, meta, elapsedSec}]
316
- const [current, setCurrent] = useState(null);
317
- const [error, setError] = useState(null);
318
- const [aiLabel, setAiLabel] = useState(true);
319
- const [lightbox, setLightbox] = useState(false); // 결과 이미지 확대 보기
320
- const [showSpecs, setShowSpecs] = useState(false); // 의상 분석 결과 / 최종 프롬프트 펼치기
321
- useEffect(() => {
322
- if (!lightbox) return;
323
- const onKey = (e) => { if (e.key === 'Escape') setLightbox(false); };
324
- window.addEventListener('keydown', onKey);
325
- return () => window.removeEventListener('keydown', onKey);
326
- }, [lightbox]);
327
- const faceFileRef = useRef(null);
328
-
329
- useEffect(() => {
330
- fetch('/api/whoami').then(r => r.ok ? r.json() : null).then(d => d && setUser(d)).catch(() => {});
331
- fetch('/api/comfy/health').then(r => r.ok ? r.json() : { ok: false, error: '브리지 라우트가 없습니다' }).then(setHealth).catch(() => setHealth({ ok: false, error: '상태 확인 실패' }));
332
- }, []);
333
-
334
- const activeJobs = jobs.filter(j => !j.error);
335
- useEffect(() => {
336
- if (activeJobs.length === 0) return;
337
- const id = setInterval(() => setTick(t => t + 1), 1000);
338
- return () => clearInterval(id);
339
- }, [activeJobs.length]);
340
-
341
- const presets = ADULT_FACE_PRESETS;
342
- const setImg = (key, v, name) => {
343
- setImages(prev => ({ ...prev, [key]: v })); setImageNames(prev => ({ ...prev, [key]: v ? (name || null) : null }));
344
- if (key === 'pose' && !v) { if (angle === '레퍼런스 따름') setAngle('반측면'); if (gaze === '레퍼런스 따름') setGaze('자연스러운 시선'); }
345
- };
346
-
347
- const kindOf = (g, slot) => { // 저장된 값이 그 옷 종류에 없으면 기본값으로
348
- const list = DETAIL_KINDS_BY_GARMENT[g] || [];
349
- const v = detailKinds[`${g}:${slot}`];
350
- return list.some(k => k.key === v) ? v : defaultKind(g, slot);
351
- };
352
- const detailList = DETAIL_GARMENTS.flatMap(g => DETAIL_SLOTS.map(slot => ({ garment: g.key, kind: kindOf(g.key, slot), image: images[`detail:${g.key}:${slot}`], filename: imageNames[`detail:${g.key}:${slot}`] })))
353
- .filter(x => x.image && images[x.garment]);
354
- const detailCount = detailList.length;
355
- const missing = [];
356
- if (!images.outer && !images.top && !images.bottom) missing.push('의상 1개 이상 (아우터·상의·하의)');
357
- const canGenerate = missing.length === 0 && (faceUpload || facePreset) && health?.ok;
358
-
359
- // 하나의 payload 로 작업 1건 시작. payload 는 결과에 함께 보관되어 "이 설정으로 다시 생성"에 쓰인다.
360
- const startJob = async (payload, meta) => {
361
- const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
362
- setJobs(prev => [...prev, { id, meta, payload, stageLabel: '요청 전송 중', startedAt: Date.now() }]);
363
- const patch = (p) => setJobs(prev => prev.map(j => j.id === id ? { ...j, ...p } : j));
364
- let jobId;
365
- try {
366
- jobId = await submitToComfy(payload);
367
- } catch (e) {
368
- patch({ error: e.message }); return;
369
- }
370
- patch({ jobId, stageLabel: '대기 중' });
371
- await trackJob(id, jobId, meta, patch, payload);
372
- };
373
-
374
- const buildPayload = () => {
375
- const meta = { shot, angle, gaze, age, prompt, face: faceUpload ? '업로드' : (presets.find(p => p.id === facePreset)?.label || facePreset) };
376
- const mainImages = Object.fromEntries(Object.entries(images).filter(([k, v]) => v && !k.startsWith('detail:')));
377
- return { face: faceUpload || facePreset, faceFilename: faceUpload ? faceUploadName : null, images: mainImages, imageFilenames: imageNames,
378
- details: detailList.slice(0, DETAIL_MAX).map(x => ({ garment: x.garment, kind: x.kind, image: x.image, filename: x.filename || null })),
379
- poseSpec: (images.pose || poseSpec.trim()) ? poseSpec.trim() : '',
380
- options: { shot, angle, gaze, age, ...details }, prompt, meta };
381
- };
382
-
383
- const handleGenerate = () => {
384
- if (user.oauth_enabled && !user.is_logged_in) { alert("로그인이 필요합니다. 우측 상단의 'Hugging Face로 로그인' 버튼을 눌러주세요."); return; }
385
- if (!canGenerate) return;
386
- setError(null);
387
- const payload = buildPayload();
388
- for (let i = 0; i < genCount; i++) startJob(payload, payload.meta); // 같은 payload 객체 공유 (메모리 절약)
389
- };
390
-
391
- // 세션 결과 삭제: 화면에서 제거 + 서버 보관분도 삭제해 새로고침 복구를 막음
392
- const deleteResult = async (r) => {
393
- if (!confirm('이 결과를 지울까요? 되돌릴 수 없어요.')) return;
394
- setResults(prev => {
395
- const next = prev.filter(x => x.id !== r.id);
396
- setCurrent(cur => (cur?.id === r.id ? (next[0] || null) : cur));
397
- return next;
398
- });
399
- try { if (r.jobId) await fetch(`/api/comfy/jobs/${r.jobId}`, { method: 'DELETE', headers: apiHeaders() }); } catch {}
400
- };
401
-
402
- // 세션 결과에 보관된 payload 로 동일 조건 재생성 (현재 ��� 상태는 건드리지 않음)
403
- const regenFrom = (r) => {
404
- if (user.oauth_enabled && !user.is_logged_in) { alert("로그인이 필요합니다."); return; }
405
- if (!r?.payload) return;
406
- startJob(r.payload, r.meta);
407
- };
408
-
409
- // 서버 작업을 완료까지 따라가며 결과/에러를 반영 (새 요청과 새로고침 복구 둘 다 사용)
410
- const trackJob = async (id, jobId, meta, patch, payload = null) => {
411
- try {
412
- const j = await pollComfyJob(jobId, (st) => patch({ stageLabel: st.stageLabel, execStartedAt: st.execStartedAt || null }));
413
- if (!j) { setJobs(prev => prev.filter(x => x.id !== id)); return; } // 취소됨
414
- const item = { id, jobId, imageUrl: j.imageUrl, meta, payload, elapsedSec: j.elapsedSec, createdAt: j.createdAt, garmentSpecs: j.garmentSpecs || null, finalPrompt: j.finalPrompt || null, poseSpec: j.poseSpec || null };
415
- setResults(prev => prev.some(r => r.id === id) ? prev : [item, ...prev]);
416
- setCurrent(prev => prev || item);
417
- setJobs(prev => prev.filter(x => x.id !== id));
418
- } catch (e) {
419
- patch({ error: e.message });
420
- }
421
- };
422
- const dismissJob = (id) => setJobs(prev => prev.filter(j => j.id !== id));
423
- const cancelJob = async (job) => { // 진행 중 작업 취소: 서버에 요청 후 카드 제거 (폴링도 cancelled 를 보고 멈춤)
424
- setJobs(prev => prev.map(x => x.id === job.id ? { ...x, cancelling: true, stageLabel: '취소 중' } : x));
425
- try { if (job.jobId) await fetch(`/api/comfy/jobs/${job.jobId}/cancel`, { method: 'POST', headers: apiHeaders() }); } catch {}
426
- setJobs(prev => prev.filter(x => x.id !== job.id));
427
- };
428
-
429
- // 새로고침/재접속 시 서버에 남아 있는 내 작업 복구
430
- useEffect(() => {
431
- (async () => {
432
- try {
433
- const r = await fetch('/api/comfy/jobs', { headers: apiHeaders() });
434
- if (!r.ok) return;
435
- const { jobs: saved } = await r.json();
436
- const done = saved.filter(j => j.status === 'done' && j.imageUrl)
437
- .map(j => ({ id: j.id, jobId: j.id, imageUrl: j.imageUrl, meta: j.meta || {}, elapsedSec: j.elapsedSec, createdAt: j.createdAt, garmentSpecs: j.garmentSpecs || null, finalPrompt: j.finalPrompt || null, poseSpec: j.poseSpec || null }))
438
- .sort((a, b) => b.createdAt - a.createdAt);
439
- if (done.length) { setResults(done); setCurrent(prev => prev || done[0]); }
440
- const pending = saved.filter(j => j.status !== 'done' && j.status !== 'cancelled');
441
- if (pending.length) {
442
- setJobs(pending.map(j => ({ id: j.id, jobId: j.id, meta: j.meta || {}, stageLabel: j.stageLabel, startedAt: j.createdAt, execStartedAt: j.execStartedAt || null, error: j.error || null })));
443
- for (const j of pending.filter(x => x.status === 'running')) {
444
- const patch = (p) => setJobs(prev => prev.map(x => x.id === j.id ? { ...x, ...p } : x));
445
- trackJob(j.id, j.id, j.meta || {}, patch);
446
- }
447
- }
448
- } catch {}
449
- })();
450
- }, []);
451
-
452
- // ── Left: settings ────────────────────────────────────────
453
- const left = h('aside', { className: 'w-full lg:w-[420px] xl:w-[460px] shrink-0 h-full overflow-y-auto border-r border-[#2a2a2a] bg-[#1e1e1e]' },
454
- h('div', { className: 'p-5 space-y-6' },
455
-
456
- h('section', null,
457
- h(SectionTitle, null, '얼굴'),
458
- h('div', { className: 'grid grid-cols-4 gap-2' },
459
- presets.map(p => h(FaceTile, { key: p.id, preset: p, selected: !faceUpload && facePreset === p.id, onClick: () => { setFaceUpload(null); setFacePreset(p.id); } })),
460
- h('button', { type: 'button', onClick: () => faceFileRef.current?.click(),
461
- className: `relative rounded-xl overflow-hidden border-2 ${faceUpload ? 'border-brand-blue' : 'border-dashed border-[#3a3a3a] hover:border-[#4b5563] bg-[#242424]'}`, style: { aspectRatio: '1 / 1' } },
462
- faceUpload
463
- ? h(React.Fragment, null, h('img', { src: faceUpload, className: 'w-full h-full object-cover' }),
464
- h('span', { onClick: e => { e.stopPropagation(); setFaceUpload(null); }, className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-black/70 flex items-center justify-center' }, h(X, { size: 11 })),
465
- h('div', { className: 'absolute bottom-0 inset-x-0 py-0.5 bg-black/60 text-[10.5px] text-center' }, '업로드'))
466
- : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-1 text-gray-400' }, h(User, { size: 16 }), h('span', { className: 'text-[10.5px]' }, '직접 업로드'))),
467
- h('input', { ref: faceFileRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: async e => { const f = e.target.files?.[0]; if (f) { setFaceUpload(await fileToDataUrl(f, 1024)); setFaceUploadName(f.name); } e.target.value = ''; } }))),
468
-
469
- h('section', null, h(SectionTitle, null, '샷 선택'), h(Segmented, { options: SHOT_OPTIONS, value: shot, cols: 3, onChange: setShot })),
470
- h('section', null,
471
- h(SectionTitle, { right: images.pose && h('span', { className: 'text-[11px] text-gray-500' }, "'레퍼런스 따름' = 포즈 사진의 앵글") }, '카메라 앵글'),
472
- h(Segmented, { options: images.pose ? ANGLE_OPTIONS : ANGLE_OPTIONS.filter(o => o !== '레퍼런스 따름'), value: angle, onChange: setAngle, cols: 4 })),
473
- h('section', null, h(SectionTitle, null, '시선'), h(Segmented, { options: images.pose ? GAZE_OPTIONS : GAZE_OPTIONS.filter(o => o !== '레퍼런스 따름'), value: gaze, onChange: setGaze })),
474
-
475
- h('section', null,
476
- h(SectionTitle, null, '프롬프트 작성'),
477
- h('textarea', { value: prompt, onChange: e => setPrompt(e.target.value), rows: 3,
478
- placeholder: '추가 지시사항 (선택). 예: 손을 주머니에 넣고 살짝 미소, 소매를 한 번 접어 올린 스타일링',
479
- className: 'w-full rounded-xl bg-[#242424] border border-[#333] px-3 py-2.5 text-[13px] text-gray-100 placeholder-gray-500 focus:outline-none focus:border-brand-blue' })),
480
-
481
- h('section', null,
482
- h(SectionTitle, { right: h('span', { className: 'text-[11px] text-gray-500' }, '아우터·상의·하의 중 1개 이상') }, '이미지 업로드'),
483
- h('div', { className: 'grid grid-cols-4 gap-2' },
484
- IMAGE_SLOTS.map(s => h(UploadTile, { key: s.key, slot: s, value: images[s.key], onChange: (v, name) => setImg(s.key, v, name) })))),
485
-
486
- (images.pose || poseSpec) && (health?.ok && health.poseText !== false) && h('section', { className: 'animate-fadeIn' },
487
- h(SectionTitle, { right: h('span', { className: 'text-[11px] text-gray-500' }, '비우면 레퍼런스에서 자동 추출') }, '포즈 지시 (선택)'),
488
- h('textarea', { value: poseSpec, onChange: e => setPoseSpec(e.target.value), rows: 3,
489
- placeholder: '예: 오른팔을 들어 손등을 오른쪽 관자놀이에 가볍게 댄다. 왼팔은 자연스럽게 내리고 체중은 왼발에. 몸통은 카메라 쪽으로 살짝 우측.',
490
- className: 'w-full rounded-xl bg-[#242424] border border-[#333] px-3 py-2.5 text-[12.5px] text-gray-100 placeholder-gray-500 focus:outline-none focus:border-brand-blue' }),
491
- h('p', { className: 'text-[11px] text-gray-500 mt-1.5 leading-relaxed' }, '레퍼런스 포즈를 문장으로 바꿔 프롬프트 맨 끝에 최우선 지시로 넣어요. 결과가 나오면 아래 패널에서 자동 추출된 문장을 확인하고, 틀린 부분을 여기서 고쳐 다시 생성할 수 있어요.')),
492
-
493
- h('section', null,
494
- h(SectionTitle, null, '길이 · 핏'),
495
- h('div', { className: 'flex gap-1.5 mb-3' },
496
- DETAIL_GROUPS.map(g => h('button', {
497
- key: g.key, type: 'button', onClick: () => setDetailTab(g.key),
498
- className: `px-3 py-1.5 rounded-lg text-[12.5px] font-semibold transition-colors ${detailTab === g.key
499
- ? 'bg-brand-blue text-white'
500
- : (images[g.key] ? 'bg-[#2a2a2a] text-gray-200 hover:bg-[#333]' : 'bg-[#242424] text-gray-500 hover:text-gray-300')}`
501
- }, g.label, images[g.key] ? h('span', { className: `ml-1.5 inline-block w-1.5 h-1.5 rounded-full align-middle ${detailTab === g.key ? 'bg-white' : 'bg-brand-blue'}` }) : null))),
502
- (() => {
503
- const g = DETAIL_GROUPS.find(x => x.key === detailTab);
504
- const rows = [['길이', g.length], ['핏', g.fit]];
505
- return h('div', { key: g.key, className: 'space-y-2 animate-fadeIn' },
506
- rows.map(([label, k]) => h('div', { key: k, className: 'grid grid-cols-[52px_1fr] items-center gap-2' },
507
- h('span', { className: 'text-[12px] text-gray-400' }, label),
508
- h('div', { className: 'flex flex-wrap gap-1.5' },
509
- DETAIL_OPTIONS[k].options.map(o => h('button', {
510
- key: o, type: 'button', onClick: () => setDetails(d => ({ ...d, [k]: o })),
511
- className: `px-3 py-1.5 rounded-lg text-[12.5px] font-medium border transition-colors ${details[k] === o
512
- ? 'bg-brand-blue border-brand-blue text-white'
513
- : 'bg-[#242424] border-[#333] text-gray-300 hover:border-[#4b5563] hover:text-white'}`
514
- }, o))))),
515
- !images[g.key] && h('p', { className: 'text-[11px] text-gray-500 pt-1' }, `${g.label} 이미지를 올리지 않으면 이 설정은 사용되지 않아요.`));
516
- })()),
517
-
518
- h('section', null,
519
- h(SectionTitle, { right: h('span', { className: `text-[11px] ${detailCount >= DETAIL_MAX ? 'text-amber-400' : 'text-gray-500'}` }, `선택 · ${detailCount}/${DETAIL_MAX}장`) }, '디테일 참조'),
520
- health?.ok && health.detailCuts === false
521
- ? h('p', { className: 'text-[11.5px] text-gray-500' }, '현재 배포된 워크플로우(workflow_api.json)에 디테일 참조 입력이 없어 사용할 수 없어요. v5 워크플로우를 Export (API)해서 교체해주세요.')
522
- : h(React.Fragment, null,
523
- h('p', { className: 'text-[11px] text-gray-500 mb-2.5 leading-relaxed' }, '클로즈업을 올리고 어떤 부위인지 골라주세요 (옷 종류별로 항목이 달라요). 조직감·소재는 옷 전체에, 나머지는 그 부위에만 반영하고 실루엣은 메인 사진 그대로 유지하도록 전달돼요. 참조가 많으면 정확도가 떨어져서 전체 4장까지만.'),
524
- h('div', { className: 'grid grid-cols-2 gap-x-4 gap-y-2.5' },
525
- DETAIL_GARMENTS.map(g => {
526
- const enabled = !!images[g.key];
527
- return h('div', { key: g.key, className: 'flex items-center gap-2' },
528
- h('span', { className: `w-14 shrink-0 text-[12px] ${enabled ? 'text-gray-300' : 'text-gray-600'}`, title: enabled ? '' : `${g.label} 이미지를 먼저 올려주세요` }, g.label),
529
- DETAIL_SLOTS.map(slot => {
530
- const id = `${g.key}:${slot}`;
531
- const cur = images[`detail:${id}`];
532
- const kind = kindOf(g.key, slot);
533
- const kindList = DETAIL_KINDS_BY_GARMENT[g.key] || [];
534
- const kindObj = kindList.find(k => k.key === kind) || kindList[0];
535
- return h('div', { key: slot, className: 'w-16 flex flex-col items-center gap-1' },
536
- h(DetailTile, { value: cur, disabled: !enabled || (!cur && detailCount >= DETAIL_MAX), onChange: (v, name) => setImg(`detail:${id}`, v, name) }),
537
- // 종류 선택 칩 — 네이티브 select 를 버튼처럼 보이게 (appearance-none + 커스텀 화살표)
538
- h('div', { className: 'relative w-full', title: enabled ? `${kindObj.label} · 클릭해서 부위 변경` : '' },
539
- h('select', {
540
- value: kind, disabled: !enabled,
541
- onChange: e => setDetailKinds(prev => ({ ...prev, [id]: e.target.value })),
542
- style: { appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none' },
543
- className: `w-full h-6 rounded-md border text-[10.5px] font-medium pl-1.5 pr-5 cursor-pointer focus:outline-none focus:border-brand-blue transition-colors
544
- ${cur ? 'bg-brand-blue/15 border-brand-blue/60 text-blue-200 hover:bg-brand-blue/25'
545
- : 'bg-[#2a2a2a] border-[#3f3f3f] text-gray-300 hover:border-[#5a5a5a] hover:bg-[#303030]'}
546
- disabled:opacity-40 disabled:cursor-default`
547
- }, kindList.map(k => h('option', { key: k.key, value: k.key, className: 'bg-[#242424] text-gray-200' }, k.short))),
548
- h(ChevronDown, { size: 12, className: `absolute right-1 top-1/2 -translate-y-1/2 pointer-events-none ${cur ? 'text-blue-200' : 'text-gray-400'}` })));
549
- }));
550
- })))),
551
-
552
- h('div', { className: 'pt-3 pb-3 sticky bottom-0 bg-[#1e1e1e] border-t border-[#2a2a2a] -mx-5 px-5' },
553
- missing.length > 0 && h('p', { className: 'text-[11.5px] text-gray-500 mb-2' }, `필요: ${missing.join(', ')}`),
554
- activeJobs.length > 0 && missing.length === 0 && h('p', { className: 'text-[11.5px] text-gray-500 mb-2' }, `${activeJobs.length}건 진행 중 — 설정을 바꿔 바로 다음 컷을 걸어둘 수 있어요`),
555
- h('div', { className: 'flex items-center justify-between mb-2' },
556
- h('span', { className: 'text-[11.5px] text-gray-500' }, '매수'),
557
- h('div', { className: 'flex gap-1' }, [1, 2].map(n =>
558
- h('button', { key: n, type: 'button', onClick: () => setGenCount(n),
559
- className: `px-3 py-1 rounded-lg text-[12px] font-medium transition-colors ${genCount === n ? 'bg-brand-blue text-white' : 'bg-[#2a2a2a] text-gray-400 hover:text-gray-200'}` }, `${n}장`)))),
560
- h('button', { type: 'button', onClick: handleGenerate, disabled: !canGenerate,
561
- className: `w-full h-12 rounded-xl font-semibold text-[14px] flex items-center justify-center gap-2 transition-colors ${canGenerate ? 'bg-brand-blue hover:bg-brand-hover text-white' : 'bg-[#2a2a2a] text-gray-500 cursor-not-allowed'}` },
562
- h(Sparkles, { size: 16 }),
563
- activeJobs.length > 0 ? `룩북 생성${genCount > 1 ? ` ${genCount}장` : ''} (${activeJobs.length}건 진행 중)` : `룩북 생성${genCount > 1 ? ` ${genCount}장` : ''}`))));
564
-
565
- // ── Right: result ─────────────────────────────────────────
566
- const right = h('main', { className: 'flex-1 h-full overflow-y-auto' },
567
- h('div', { className: 'max-w-5xl mx-auto p-6 lg:p-8' },
568
- !health?.ok && health && h('div', { className: 'mb-5 rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-[13px] text-amber-200 flex gap-2' },
569
- h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', null, health.error || 'Comfy 브리지 설정을 확인해주세요.')),
570
- health?.ok && health.loginRequired === false && h('div', { className: 'mb-5 rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-[13px] text-amber-200 flex gap-2' },
571
- h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', null, 'HF OAuth가 연결되지 않아 로그인 없이 누구나 생성할 수 있는 상태입니다. README의 hf_oauth 설정과 Space 재시작을 확인해주세요.')),
572
- error && h('div', { className: 'mb-5 rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-[13px] text-red-200 flex gap-2 animate-fadeIn' },
573
- h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', { className: 'break-all' }, error)),
574
-
575
- jobs.length > 0 && h('div', { className: 'mb-5 rounded-xl border border-[#2a2a2a] bg-[#202020] overflow-hidden animate-fadeIn' },
576
- h('div', { className: 'px-4 py-2.5 border-b border-[#2a2a2a] text-[12.5px] font-semibold text-gray-300 flex items-center gap-2' },
577
- h(RefreshCw, { size: 13, className: activeJobs.length ? 'animate-spin text-brand-blue' : 'text-gray-500' }),
578
- `진행 중 ${activeJobs.length}건`, jobs.length - activeJobs.length > 0 ? h('span', { className: 'text-red-300 font-normal' }, ` · 실패 ${jobs.length - activeJobs.length}건`) : null),
579
- jobs.map((j, i) => h('div', { key: j.id, className: `px-4 py-2.5 flex items-center gap-3 text-[12.5px] ${i > 0 ? 'border-t border-[#262626]' : ''}` },
580
- h('div', { className: `w-1.5 h-1.5 rounded-full shrink-0 ${j.error ? 'bg-red-400' : 'bg-brand-blue pulse-ring relative'}` }),
581
- h('div', { className: 'flex-1 min-w-0' },
582
- h('div', { className: 'text-gray-100 truncate' }, `${j.meta.face} · ${j.meta.shot} · ${j.meta.angle} · ${j.meta.gaze}`, j.meta.prompt ? h('span', { className: 'text-gray-500' }, ` · "${j.meta.prompt}"`) : null),
583
- h('div', { className: j.error ? 'text-red-300 break-all' : 'text-gray-400' },
584
- j.error ? j.error : (j.execStartedAt ? `${j.stageLabel} · ${fmtSec((Date.now() - j.execStartedAt) / 1000)}` : `${j.stageLabel} · 대기 ${fmtSec((Date.now() - j.startedAt) / 1000)}`))),
585
- j.error
586
- ? h('button', { type: 'button', title: '지우기', onClick: () => dismissJob(j.id), className: 'text-gray-500 hover:text-white' }, h(X, { size: 14 }))
587
- : h('button', { type: 'button', title: '작업 취소', disabled: j.cancelling, onClick: () => cancelJob(j),
588
- className: 'shrink-0 text-[11.5px] px-2.5 py-1 rounded-lg border border-[#3a3a3a] text-gray-400 hover:text-red-300 hover:border-red-400/50 disabled:opacity-50 transition-colors' },
589
- j.cancelling ? '취소 중…' : '취소')))),
590
-
591
- h('div', { className: 'grid grid-cols-1 md:grid-cols-[minmax(0,1fr)_200px] gap-6' },
592
- // 메인 뷰어
593
- h('div', { className: 'rounded-2xl bg-[#202020] border border-[#2a2a2a] overflow-hidden relative', style: { minHeight: '60vh' } },
594
- !current && activeJobs.length > 0
595
- ? h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-5' },
596
- h('div', { className: 'shimmer absolute inset-0 opacity-60' }),
597
- h('div', { className: 'relative pulse-ring w-14 h-14 rounded-full bg-brand-blue/20 flex items-center justify-center' }, h(Sparkles, { size: 22, className: 'text-brand-blue' })),
598
- h('div', { className: 'relative text-center' },
599
- h('div', { className: 'text-[15px] font-semibold text-gray-100' }, activeJobs[0].stageLabel),
600
- h('div', { className: 'mt-1 text-[12.5px] text-gray-400 flex items-center justify-center gap-1' }, h(Clock, { size: 12 }),
601
- activeJobs[0].execStartedAt ? `${fmtSec((Date.now() - activeJobs[0].execStartedAt) / 1000)} 경과 · 보통 1~2분 소요` : '실행 순서를 기다리는 중')),
602
- h('p', { className: 'relative text-[11.5px] text-gray-500 max-w-xs text-center' }, '이 탭을 닫지 마세요. 생성이 끝나면 여기에 이미지가 표시됩니다.'))
603
- : current
604
- ? h('div', { className: 'animate-fadeIn flex flex-col' },
605
- h('div', { className: 'flex justify-center bg-[#1c1c1c]' },
606
- h('div', { className: 'relative inline-block' },
607
- h('img', { src: current.imageUrl, onClick: () => setLightbox(true), title: '클릭하면 크게 보기',
608
- className: 'max-h-[78vh] w-auto max-w-full block bg-white cursor-zoom-in', alt: '생성 결과' }),
609
- aiLabel && h('div', { className: 'ai-label-overlay' }, AI_LABEL_TEXT),
610
- h('button', { type: 'button', onClick: () => setLightbox(true), title: '크게 보기',
611
- className: 'absolute bottom-3 right-3 w-9 h-9 rounded-lg bg-black/55 hover:bg-black/75 text-white flex items-center justify-center' }, h(Maximize2, { size: 16 })))),
612
- h('div', { className: 'flex items-center justify-between gap-3 px-4 py-3 border-t border-[#2a2a2a]' },
613
- h('label', { className: 'flex items-center gap-2 cursor-pointer select-none text-[12.5px] text-gray-300' },
614
- h('button', { type: 'button', role: 'switch', 'aria-checked': aiLabel, onClick: () => setAiLabel(v => !v),
615
- className: `relative w-9 h-5 rounded-full transition-colors ${aiLabel ? 'bg-brand-blue' : 'bg-[#3a3a3a]'}` },
616
- h('span', { className: `absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${aiLabel ? 'translate-x-4' : ''}` })),
617
- h('span', null, "'AI 생성 이미지' 표기"),
618
- h('span', { className: 'text-gray-500' }, aiLabel ? '화면·다운로드에 포함' : '표기 없음')),
619
- h('button', { type: 'button', onClick: () => downloadWithLabel(current.imageUrl, `clovis_${current.meta.shot}_${current.meta.angle}_${current.id}.png`, aiLabel),
620
- className: 'h-10 px-4 rounded-xl bg-brand-blue hover:bg-brand-hover text-white text-[13px] font-semibold flex items-center gap-1.5' }, h(Download, { size: 15 }), '다운로드')))
621
- : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center text-gray-500 gap-2' },
622
- h(Upload, { size: 28, className: 'opacity-50' }),
623
- h('p', { className: 'text-[13.5px]' }, '왼쪽에서 얼굴·의상을 고르고 룩북 생성을 누르면'),
624
- h('p', { className: 'text-[13.5px]' }, '한 번에 모델컷이 생성됩니다.'))),
625
- // 히스토리
626
- h('div', null,
627
- h('h3', { className: 'text-[13px] font-semibold text-gray-300 mb-2.5' }, `이번 세션 결과 ${results.length ? `(${results.length})` : ''}`),
628
- results.length === 0
629
- ? h('p', { className: 'text-[12px] text-gray-500' }, '아직 없음')
630
- : h('div', { className: 'grid grid-cols-3 md:grid-cols-1 gap-2' },
631
- results.map(r => h('div', { key: r.id, className: 'relative group' },
632
- h('button', { type: 'button', onClick: () => setCurrent(r),
633
- className: `w-full relative rounded-xl overflow-hidden border-2 ${current?.id === r.id ? 'border-brand-blue' : 'border-transparent hover:border-[#4b5563]'}` },
634
- h('img', { src: r.imageUrl, className: 'w-full h-auto block bg-white' }),
635
- h('div', { className: 'absolute bottom-0 inset-x-0 px-2 py-1 bg-black/65 text-[10.5px] text-left leading-tight' },
636
- h('div', null, `${r.meta.face ? r.meta.face + ' · ' : ''}${r.meta.shot} · ${r.meta.angle}`),
637
- h('div', { className: 'text-gray-300' }, `${r.meta.gaze} · ${fmtSec(r.elapsedSec)}`))),
638
- h('div', { className: 'absolute top-1.5 right-1.5 hidden group-hover:flex gap-1' },
639
- r.payload && h('button', { type: 'button', onClick: (e) => { e.stopPropagation(); regenFrom(r); }, title: '이 설정으로 다시 생성',
640
- className: 'w-7 h-7 rounded-lg bg-black/60 hover:bg-brand-blue text-white flex items-center justify-center transition-colors' },
641
- h(RefreshCw, { size: 13 })),
642
- h('button', { type: 'button', onClick: (e) => { e.stopPropagation(); deleteResult(r); }, title: '이 결과 지우기',
643
- className: 'w-7 h-7 rounded-lg bg-black/60 hover:bg-red-500 text-white flex items-center justify-center transition-colors' },
644
- h(X, { size: 13 })))))))),
645
-
646
- current && h('div', { className: 'mt-5 text-[12px] text-gray-500' },
647
- `${current.meta.age} · ${current.meta.shot} · ${current.meta.angle} · ${current.meta.gaze}`, current.meta.prompt ? ` · "${current.meta.prompt}"` : ''),
648
- current && (current.garmentSpecs || current.finalPrompt || current.poseSpec) && h('div', { className: 'mt-3 rounded-xl border border-[#2a2a2a] bg-[#202020]' },
649
- h('button', { type: 'button', onClick: () => setShowSpecs(v => !v), className: 'w-full flex items-center justify-between px-4 py-2.5 text-[12.5px] font-semibold text-gray-300 hover:text-white' },
650
- h('span', null, '포즈 분석 · 의상 분석 · 최종 프롬프트'), h('span', { className: 'text-gray-500 font-normal' }, showSpecs ? '접기' : '펼치기')),
651
- showSpecs && h('div', { className: 'px-4 pb-4 space-y-3 animate-fadeIn' },
652
- current.poseSpec && h('div', null,
653
- h('div', { className: 'flex items-center justify-between mb-1' },
654
- h('div', { className: 'text-[11px] text-gray-500' }, '포즈 분석 (레퍼런스 → 문장, 프롬프트 최우선 지시)'),
655
- h('button', { type: 'button', onClick: () => { setPoseSpec(current.poseSpec); document.querySelector('aside')?.scrollTo({ top: 0, behavior: 'smooth' }); },
656
- className: 'text-[11px] text-brand-blue hover:underline' }, '이 문장을 수정해서 다시 생성')),
657
- h('pre', { className: 'text-[11.5px] text-gray-200 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-40 overflow-y-auto' }, current.poseSpec)),
658
- current.garmentSpecs && h('div', null,
659
- h('div', { className: 'text-[11px] text-gray-500 mb-1' }, 'GPT 비전 의상 분석 (GARMENT SPECS)'),
660
- h('pre', { className: 'text-[11.5px] text-gray-200 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-48 overflow-y-auto' }, current.garmentSpecs)),
661
- current.finalPrompt && h('div', null,
662
- h('div', { className: 'text-[11px] text-gray-500 mb-1' }, 'GPT-image에 전달된 최종 프롬프트'),
663
- h('pre', { className: 'text-[11.5px] text-gray-300 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-64 overflow-y-auto' }, current.finalPrompt))))));
664
-
665
- // ── Header ────────────────────────────────────────────────
666
- const header = h('header', { className: 'h-14 shrink-0 border-b border-[#2a2a2a] bg-[#1a1a1a] flex items-center justify-between px-5' },
667
- h('div', { className: 'flex items-center gap-5' },
668
- h('div', { className: 'flex items-center gap-3' },
669
- h('div', { className: 'w-8 h-8 rounded-lg bg-brand-blue flex items-center justify-center' }, h(Sparkles, { size: 16, className: 'text-white' })),
670
- h('div', { className: 'text-[15px] font-bold tracking-tight' }, 'CLOVIS AI 룩북 생성기')),
671
- user.oauth_enabled && h('div', { className: 'flex items-center gap-2 text-[12.5px] pl-5 border-l border-[#2a2a2a]' },
672
- user.is_logged_in
673
- ? h(React.Fragment, null,
674
- h('span', { className: 'text-gray-300' }, user.name || user.username),
675
- h('a', { href: user.logout_url, className: 'text-gray-500 hover:text-white' }, '로그아웃'))
676
- : h('a', { href: user.login_url, className: 'px-3 py-1.5 rounded-lg bg-[#2a2a2a] hover:bg-[#333] text-gray-100' }, '🤗 Hugging Face로 로그인'))),
677
- h('div', null,
678
- health && !health.ok && h('span', { className: 'inline-flex items-center gap-1.5 text-[12.5px] text-amber-400' },
679
- h('span', { className: 'w-1.5 h-1.5 rounded-full bg-amber-400' }), 'Comfy 설정 필요')));
680
-
681
- const lightboxEl = lightbox && current && h('div', {
682
- className: 'fixed inset-0 z-50 bg-black/90 flex items-center justify-center animate-fadeIn cursor-zoom-out',
683
- onClick: () => setLightbox(false) },
684
- h('img', { src: current.imageUrl, alt: '생성 결과 확대', onClick: e => e.stopPropagation(),
685
- className: 'max-w-[96vw] max-h-[96vh] object-contain bg-white cursor-default shadow-2xl' }),
686
- aiLabel && h('div', { className: 'absolute top-4 right-16 text-[12px] text-gray-300 font-light pointer-events-none' }, AI_LABEL_TEXT),
687
- h('button', { type: 'button', onClick: () => setLightbox(false), title: '닫기 (Esc)',
688
- className: 'absolute top-4 right-4 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center' }, h(X, { size: 18 })),
689
- h('div', { className: 'absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2', onClick: e => e.stopPropagation() },
690
- h('button', { type: 'button', onClick: () => downloadWithLabel(current.imageUrl, `clovis_${current.meta.shot}_${current.meta.angle}_${current.id}.png`, aiLabel),
691
- className: 'h-10 px-4 rounded-xl bg-brand-blue hover:bg-brand-hover text-white text-[13px] font-semibold flex items-center gap-1.5' }, h(Download, { size: 15 }), '다운로드')));
692
-
693
- return h('div', { className: 'h-screen flex flex-col bg-[#1a1a1a]' }, header,
694
- h('div', { className: 'flex-1 flex flex-col lg:flex-row min-h-0' }, left, right), lightboxEl);
695
- }
696
-
697
- ReactDOM.createRoot(document.getElementById('root')).render(h(App));
698
- </script>
699
- </body>
700
- </html>