'use client'; import { useState, useRef, useEffect } from 'react'; import { Header } from '@/components/header'; import { AppLayout } from '@/components/layout'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Textarea } from '@/components/ui/textarea'; import { PromptTextarea } from '@/components/prompt-textarea'; import { Label } from '@/components/ui/label'; import { Card, CardContent } from '@/components/ui/card'; import { apiClient, type JobInfo } from '@/lib/api'; import { Loader2, Download, X, Upload } from 'lucide-react'; import { downloadImage, downloadAuthenticatedImage, fileToBase64 } from '@/lib/utils'; import { useLocalStorage } from '@/lib/hooks'; type Img2ImgFormData = { prompt: string; negative_prompt: string; image: string; strength: number; steps: number; cfg_scale: number; seed: string; sampling_method: string; }; const defaultFormData: Img2ImgFormData = { prompt: '', negative_prompt: '', image: '', strength: 0.75, steps: 20, cfg_scale: 7.5, seed: '', sampling_method: 'euler_a', }; export default function Img2ImgPage() { const [formData, setFormData] = useLocalStorage( 'img2img-form-data', defaultFormData ); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [jobInfo, setJobInfo] = useState(null); const [generatedImages, setGeneratedImages] = useState([]); const [previewImage, setPreviewImage] = useState(null); const [loraModels, setLoraModels] = useState([]); const [embeddings, setEmbeddings] = useState([]); const fileInputRef = useRef(null); useEffect(() => { const loadModels = async () => { try { const [loras, embeds] = await Promise.all([ apiClient.getModels('lora'), apiClient.getModels('embedding'), ]); setLoraModels(loras.map(m => m.name)); setEmbeddings(embeds.map(m => m.name)); } catch (err) { console.error('Failed to load models:', err); } }; loadModels(); }, []); const handleInputChange = ( e: React.ChangeEvent ) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: name === 'prompt' || name === 'negative_prompt' || name === 'seed' || name === 'sampling_method' ? value : Number(value), })); }; const handleImageUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; try { const base64 = await fileToBase64(file); setFormData((prev) => ({ ...prev, image: base64 })); setPreviewImage(base64); setError(null); } catch (err) { setError('Failed to load image'); } }; const pollJobStatus = async (jobId: string) => { const maxAttempts = 300; let attempts = 0; const poll = async () => { try { const status = await apiClient.getJobStatus(jobId); setJobInfo(status); if (status.status === 'completed') { let imageUrls: string[] = []; // Handle both old format (result.images) and new format (outputs) if (status.outputs && status.outputs.length > 0) { // New format: convert output URLs to authenticated image URLs with cache-busting imageUrls = status.outputs.map((output: any) => { const filename = output.filename; return apiClient.getImageUrl(jobId, filename); }); } else if (status.result?.images && status.result.images.length > 0) { // Old format: convert image URLs to authenticated URLs imageUrls = status.result.images.map((imageUrl: string) => { // Extract filename from URL if it's already a full URL if (imageUrl.includes('/output/')) { const parts = imageUrl.split('/output/'); if (parts.length === 2) { const filename = parts[1].split('?')[0]; // Remove query params return apiClient.getImageUrl(jobId, filename); } } // If it's just a filename, convert it directly return apiClient.getImageUrl(jobId, imageUrl); }); } // Create a new array to trigger React re-render setGeneratedImages([...imageUrls]); setLoading(false); } else if (status.status === 'failed') { setError(status.error || 'Generation failed'); setLoading(false); } else if (status.status === 'cancelled') { setError('Generation was cancelled'); setLoading(false); } else if (attempts < maxAttempts) { attempts++; setTimeout(poll, 1000); } else { setError('Job polling timeout'); setLoading(false); } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to check job status'); setLoading(false); } }; poll(); }; const handleGenerate = async (e: React.FormEvent) => { e.preventDefault(); if (!formData.image) { setError('Please upload an image first'); return; } setLoading(true); setError(null); setGeneratedImages([]); setJobInfo(null); try { const job = await apiClient.img2img(formData); setJobInfo(job); const jobId = job.request_id || job.id; if (jobId) { await pollJobStatus(jobId); } else { setError('No job ID returned from server'); setLoading(false); } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to generate image'); setLoading(false); } }; const handleCancel = async () => { const jobId = jobInfo?.request_id || jobInfo?.id; if (jobId) { try { await apiClient.cancelJob(jobId); setLoading(false); setError('Generation cancelled'); } catch (err) { console.error('Failed to cancel job:', err); } } }; return (
{/* Left Panel - Form */}
{previewImage && (
Source
)}
setFormData({ ...formData, prompt: value })} placeholder="Describe the transformation you want..." rows={3} loras={loraModels} embeddings={embeddings} />

Tip: Use <lora:name:weight> for LoRAs and embedding names directly

setFormData({ ...formData, negative_prompt: value })} placeholder="What to avoid..." rows={2} loras={loraModels} embeddings={embeddings} />

Lower values preserve more of the original image

{loading && ( )}
{error && (
{error}
)} {loading && jobInfo && (

Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}

Status: {jobInfo.status}

{jobInfo.progress !== undefined && (

Progress: {Math.round(jobInfo.progress * 100)}%

)}
)}
{/* Right Panel - Generated Images */}

Generated Images

{generatedImages.length === 0 ? (

{loading ? 'Generating...' : 'Generated images will appear here'}

) : (
{generatedImages.map((image, index) => (
{`Generated
))}
)}
); }