import React, { useState, useRef, useEffect } from 'react'; import { ImageIcon, Loader2, AlertCircle, CheckCircle2, Play, Trash2, RefreshCw, Download, Share2, Maximize2, ImagePlus, X, Eye, Key } from 'lucide-react'; // 기본 환경 제공 키 (참조 기능이 없는 순수 텍스트 생성용) const defaultApiKey = ""; const App = () => { // --- 상태 관리 --- const [userApiKey, setUserApiKey] = useState(() => localStorage.getItem('gemini_user_api_key') || ''); const [promptsText, setPromptsText] = useState(''); const [tasks, setTasks] = useState([]); const [isProcessing, setIsProcessing] = useState(false); const [selectedImage, setSelectedImage] = useState(null); const [rawViewImage, setRawViewImage] = useState(null); const [toastMessage, setToastMessage] = useState(''); const [uploadedImages, setUploadedImages] = useState([]); const [aspectRatio, setAspectRatio] = useState('1:1'); const [modelType, setModelType] = useState('pro'); // pro, v2 const fileInputRef = useRef(null); const abortControllerRef = useRef(null); // API 키가 변경될 때마다 브라우저 로컬 스토리지에 저장 useEffect(() => { localStorage.setItem('gemini_user_api_key', userApiKey); }, [userApiKey]); const showToast = (msg) => { setToastMessage(msg); setTimeout(() => setToastMessage(''), 5000); }; const stats = { total: tasks.length, completed: tasks.filter(t => t.status === 'success').length, failed: tasks.filter(t => t.status === 'error').length, pending: tasks.filter(t => ['pending', 'processing'].includes(t.status)).length, }; // 1. 브라우저 단에서 이미지 리사이징 (API 전송 용량 최적화) const resizeImage = (file) => { return new Promise((resolve) => { const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); img.onload = () => { const canvas = document.createElement('canvas'); const MAX_WIDTH = 800; const MAX_HEIGHT = 800; let width = img.width; let height = img.height; if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); resolve(canvas.toDataURL('image/jpeg', 0.9)); }; img.src = e.target.result; }; reader.readAsDataURL(file); }); }; const handleFileUpload = async (e) => { const files = Array.from(e.target.files); if (!files.length) return; showToast('이미지 처리 중...'); const newImages = []; for (const file of files) { const nameWithoutExt = file.name.replace(/\.[^/.]+$/, ""); const optimizedDataUrl = await resizeImage(file); newImages.push({ id: crypto.randomUUID(), name: nameWithoutExt, dataUrl: optimizedDataUrl }); } setUploadedImages(prev => [...prev, ...newImages]); if (fileInputRef.current) fileInputRef.current.value = ''; }; const removeUploadedImage = (id) => { setUploadedImages(prev => prev.filter(img => img.id !== id)); }; // 2. 여러 장의 이미지를 하나의 캔버스에 가로로 이어 붙이는 합성(Stitching) 함수 const stitchImages = async (base64Urls) => { if (base64Urls.length === 1) return base64Urls[0]; // 1장이면 그대로 반환 const loadedImages = await Promise.all(base64Urls.map(url => { return new Promise(resolve => { const img = new Image(); img.onload = () => resolve(img); img.src = url; }); })); const totalWidth = loadedImages.reduce((sum, img) => sum + img.width, 0); const maxHeight = Math.max(...loadedImages.map(img => img.height)); const canvas = document.createElement('canvas'); canvas.width = totalWidth; canvas.height = maxHeight; const ctx = canvas.getContext('2d'); let currentX = 0; loadedImages.forEach(img => { ctx.drawImage(img, currentX, 0); currentX += img.width; }); return canvas.toDataURL('image/jpeg', 0.9); }; // 3. 이미지 생성 API 호출 (직접 이미지 참조 방식) const generateImageWithRetry = async (finalPrompt, referenceBase64, signal) => { // 사용자가 키를 입력했으면 그것을 쓰고, 없으면 기본 환경 키 사용 const activeKey = userApiKey.trim() || defaultApiKey; const targetModel = modelType === 'pro' ? 'imagen-4.0-generate-001' : 'imagen-3.0-generate-001'; const delays = [1000, 2000, 4000]; for (let i = 0; i <= delays.length; i++) { try { if (signal?.aborted) throw new Error('Aborted'); // 페이로드(데이터) 구성 const instanceData = { prompt: finalPrompt }; // 참조 이미지가 있다면 원본 이미지 데이터를 Base64로 직접 포함시킴 if (referenceBase64) { const b64Data = referenceBase64.split(',')[1]; instanceData.image = { bytesBase64Encoded: b64Data }; } const payload = { instances: instanceData, parameters: { sampleCount: 1 } }; if (aspectRatio !== '1:1') payload.parameters.aspectRatio = aspectRatio; const response = await fetch( `https://generativelanguage.googleapis.com/v1beta/models/${targetModel}:predict?key=${activeKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal } ); if (!response.ok) { const errText = await response.text(); let errMsg = `API 에러 (${response.status})`; try { const data = JSON.parse(errText); errMsg = data.error?.message || errMsg; } catch(e){} if (response.status === 401 || response.status === 403) { throw new Error(`인증 실패 (401/403). 상단에 유효한 개인 API 키를 입력해주세요. 상세: ${errMsg}`); } throw new Error(errMsg); } const data = await response.json(); if (data.predictions && data.predictions[0] && data.predictions[0].bytesBase64Encoded) { return `data:image/png;base64,${data.predictions[0].bytesBase64Encoded}`; } else { throw new Error("결과물에 이미지 데이터가 없습니다."); } } catch (error) { if (signal?.aborted) throw new Error('작업 취소됨'); if (i === delays.length) throw error; await new Promise(resolve => setTimeout(resolve, delays[i])); } } }; const handleStartGeneration = async () => { const newPrompts = promptsText.split('\n').map(p => p.trim()).filter(p => p.length > 0); if (newPrompts.length === 0 && tasks.length === 0) return; if (!userApiKey.trim() && promptsText.includes('@[')) { showToast('⚠️ 참조 기능을 사용하려면 개인 API 키 입력이 필수입니다!'); } let currentTasks = [...tasks]; if (newPrompts.length > 0) { const newTasks = newPrompts.map(prompt => ({ id: crypto.randomUUID(), originalPrompt: prompt, finalPrompt: prompt, status: 'pending', imageUrl: null, error: null, matchedImages: [] })); currentTasks = [...currentTasks, ...newTasks]; setTasks(currentTasks); setPromptsText(''); } setIsProcessing(true); abortControllerRef.current = new AbortController(); for (let i = 0; i < currentTasks.length; i++) { if (abortControllerRef.current.signal.aborted) break; const task = currentTasks[i]; if (task.status === 'success') continue; let workingPrompt = task.originalPrompt; const matchedImgs = []; const matches = workingPrompt.match(/@\[(.*?)\]/g); // 프롬프트 내에 @[단어] 가 있는지 확인하여 이미지 추출 if (matches && uploadedImages.length > 0) { for (const match of matches) { const keyword = match.replace('@[', '').replace(']', ''); const foundImg = uploadedImages.find(img => img.name.includes(keyword)); if (foundImg) { matchedImgs.push(foundImg); // Imagen 모델이 텍스트로 참조 여부를 인지하도록 일반적인 문구로 치환 workingPrompt = workingPrompt.replace(match, "[referenced style/subject]"); } else { workingPrompt = workingPrompt.replace(match, ""); } } } setTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'processing', finalPrompt: workingPrompt, matchedImages: matchedImgs, error: null } : t )); try { let stitchedBase64 = null; if (matchedImgs.length > 0) { const base64Urls = matchedImgs.map(img => img.dataUrl); stitchedBase64 = await stitchImages(base64Urls); } const imageUrl = await generateImageWithRetry(workingPrompt, stitchedBase64, abortControllerRef.current.signal); setTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'success', imageUrl } : t)); } catch (error) { setTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'error', error: error.message } : t)); } } setIsProcessing(false); }; const handleStop = () => { if (abortControllerRef.current) abortControllerRef.current.abort(); setIsProcessing(false); }; const handleClear = () => { setTasks([]); setPromptsText(''); }; const handleRetryFailed = () => { setTasks(prev => prev.map(t => t.status === 'error' ? { ...t, status: 'pending', error: null } : t)); setTimeout(() => { if (!isProcessing) handleStartGeneration(); }, 100); }; // --- 다운로드 유틸리티 --- const getFileName = (prompt, index = '') => { const safePrompt = prompt.substring(0, 20).replace(/[^a-z0-9가-힣]/gi, '_'); return `${index ? index + '_' : ''}${safePrompt}.png`; }; const base64ToBlob = (base64Url) => { const parts = base64Url.split(','); const mime = parts[0].match(/:(.*?);/)[1]; const bstr = atob(parts[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) u8arr[n] = bstr.charCodeAt(n); return new Blob([u8arr], { type: mime }); }; const handleDownloadAll = async () => { const successfulTasks = tasks.map((t, index) => ({...t, originalIndex: index + 1})).filter(t => t.status === 'success'); if (successfulTasks.length === 0) return; showToast('일괄 다운로드 시작...'); try { const JSZip = (await import('https://esm.sh/jszip')).default; const zip = new JSZip(); successfulTasks.forEach(task => { const base64Data = task.imageUrl.split(',')[1]; zip.file(getFileName(task.originalPrompt, task.originalIndex), base64Data, { base64: true }); }); const content = await zip.generateAsync({ type: "blob" }); const url = window.URL.createObjectURL(content); const a = document.createElement('a'); a.href = url; a.download = `대량생성이미지_${new Date().toISOString().slice(0,10).replace(/-/g,'')}.zip`; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(url); showToast('✅ 일괄 다운로드(ZIP) 완료!'); } catch (err) { showToast('❌ 압축 파일 생성 실패'); } }; const handleShare = async (task) => { try { const blob = base64ToBlob(task.imageUrl); const file = new File([blob], getFileName(task.originalPrompt), { type: 'image/png' }); if (navigator.canShare && navigator.canShare({ files: [file] })) { await navigator.share({ files: [file], title: '이미지 저장', text: task.originalPrompt }); } else { showToast('공유 기능을 지원하지 않는 기기입니다.'); } } catch (err) {} }; const getAspectRatioClass = () => { if (aspectRatio === '16:9') return 'aspect-video'; if (aspectRatio === '9:16') return 'aspect-[9/16]'; return 'aspect-square'; }; if (rawViewImage) { return (
원본 이미지 직접 참조 모드 (Direct Image-to-Image)
⚠️ 참조 기능을 사용하려면 우측 상단에 API 키를 입력해야 합니다.
)}{task.originalPrompt}