'use client'; import { useState, 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 { InpaintingCanvas } from '@/components/inpainting-canvas'; import { apiClient, type JobInfo } from '@/lib/api'; import { Loader2, X, Download } from 'lucide-react'; import { downloadAuthenticatedImage } from '@/lib/utils'; import { useLocalStorage } from '@/lib/hooks'; type InpaintingFormData = { prompt: string; negative_prompt: string; source_image: string; mask_image: string; steps: number; cfg_scale: number; seed: string; sampling_method: string; strength: number; width?: number; height?: number; }; const defaultFormData: InpaintingFormData = { prompt: '', negative_prompt: '', source_image: '', mask_image: '', steps: 20, cfg_scale: 7.5, seed: '', sampling_method: 'euler_a', strength: 0.75, width: 512, height: 512, }; export default function InpaintingPage() { const [formData, setFormData] = useLocalStorage( 'inpainting-form-data', defaultFormData ); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [jobInfo, setJobInfo] = useState(null); const [generatedImages, setGeneratedImages] = useState([]); const [loraModels, setLoraModels] = useState([]); const [embeddings, setEmbeddings] = useState([]); useEffect(() => { const loadModels = async () => { try { const [loras, embeds] = await Promise.all([ apiClient.getModels('lora'), apiClient.getModels('embedding'), ]); setLoraModels(loras.models.map(m => m.name)); setEmbeddings(embeds.models.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 handleSourceImageChange = (image: string) => { setFormData((prev) => ({ ...prev, source_image: image })); setError(null); }; const handleMaskImageChange = (image: string) => { setFormData((prev) => ({ ...prev, mask_image: image })); setError(null); }; 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, 2000); } 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.source_image) { setError('Please upload a source image first'); return; } if (!formData.mask_image) { setError('Please create a mask first'); return; } setLoading(true); setError(null); setGeneratedImages([]); setJobInfo(null); try { const job = await apiClient.inpainting(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 - Canvas and Form */}
setFormData({ ...formData, prompt: value })} placeholder="Describe what to generate in the masked areas..." rows={3} loras={loraModels} embeddings={embeddings} />

Tip: Use {''} for LoRAs and embedding names directly

setFormData({ ...formData, negative_prompt: value })} placeholder="What to avoid in the generated areas..." 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
))}
)}
); }