import React, { useState } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Button } from './ui/button'; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from './ui/form'; import { Input } from './ui/input'; import { Slider } from './ui/slider'; import { Switch } from './ui/switch'; import { cn } from '@/lib/utils'; import { Card } from './ui/card'; import { Loader2 } from 'lucide-react'; // Define form schema const formSchema = z.object({ prompt: z.string().min(1, { message: 'Prompt is required', }).max(1000, { message: 'Prompt must be less than 1000 characters', }), width: z.number().min(256).max(1024).default(512), height: z.number().min(256).max(1024).default(512), seed: z.number().default(0), randomize_seed: z.boolean().default(true), guidance_scale: z.number().min(0).max(20).default(7.5), num_inference_steps: z.number().min(1).max(50).default(20), }); type FormValues = z.infer; export default function ImageGenerator() { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [imageUrl, setImageUrl] = useState(null); // Default form values const defaultValues: FormValues = { prompt: '', width: 512, height: 512, seed: 0, randomize_seed: true, guidance_scale: 7.5, num_inference_steps: 20, }; // Initialize form const form = useForm({ resolver: zodResolver(formSchema), defaultValues, }); // Handle form submission const onSubmit = async (data: FormValues) => { setIsLoading(true); setError(null); try { const response = await fetch('/api/generate-image', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || 'Failed to generate image'); } const result = await response.json(); setImageUrl(result.imageUrl); } catch (err: any) { setError(err.message || 'An error occurred while generating the image'); console.error('Error generating image:', err); } finally { setIsLoading(false); } }; return (

Image Generator

{isLoading &&
Generating...
}
( Prompt Describe the image you want to generate )} />
( Width: {field.value}px field.onChange(value[0])} /> )} /> ( Height: {field.value}px field.onChange(value[0])} /> )} />
(
Randomize Seed Use a random seed for each generation
)} /> {!form.watch("randomize_seed") && ( ( Seed: {field.value} field.onChange(parseInt(e.target.value) || 0)} /> Specific seed for reproducible results )} /> )} ( Guidance Scale: {field.value} field.onChange(value[0])} /> How closely to follow the prompt (higher = more faithful) )} /> ( Inference Steps: {field.value} field.onChange(value[0])} /> Number of denoising steps (higher = better quality but slower) )} /> {error && (
{error}
)}
{imageUrl ? (
Generated
) : (

Your generated image will appear here

)}
); }