import gradio as gr from diffusers import AutoPipelineForText2Image import torch import os # Model configuration MODEL_NAME = "katuni4ka/tiny-random-flex.2-preview" CACHE_DIR = "./model_cache" # Create cache directory os.makedirs(CACHE_DIR, exist_ok=True) # Load model with optimized settings pipe = AutoPipelineForText2Image.from_pretrained( MODEL_NAME, torch_dtype=torch.float16, cache_dir=CACHE_DIR ).to("cuda" if torch.cuda.is_available() else "cpu") # Aspect ratio presets ASPECT_RATIOS = { "Square (1:1)": (512, 512), "Landscape (16:9)": (1024, 576), "Portrait (9:16)": (576, 1024), "A4 (3:4)": (864, 1152) } def generate_image(prompt, aspect_ratio, num_inference_steps=25, guidance_scale=4.5): """Generate image with optimized inference settings""" width, height = ASPECT_RATIOS[aspect_ratio] with torch.inference_mode(): image = pipe( prompt=prompt, width=width, height=height, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale ).images[0] return image # UI Configuration with gr.Blocks(theme="huggingface", analytics_enabled=False) as demo: gr.Markdown(""" # Tiny Random Flex Text-to-Image Generator Create images from text prompts using the `katuni4ka/tiny-random-flex.2-preview` model 💡 Tip: Try descriptive prompts like "A futuristic cityscape at sunset" or "Abstract watercolor patterns" """) with gr.Row(): with gr.Column(): prompt = gr.Textbox( label="Prompt", placeholder="Describe your image...", lines=3 ) aspect_ratio = gr.Dropdown( label="Aspect Ratio", choices=list(ASPECT_RATIOS.keys()), value="Square (1:1)" ) generate_btn = gr.Button("🎨 Generate Image", variant="primary") with gr.Column(): output_image = gr.Image(label="Generated Image", interactive=False) generate_btn.click( fn=generate_image, inputs=[prompt, aspect_ratio], outputs=output_image ) gr.Examples( examples=[ ["A vibrant neon cityscape at night", "Landscape (16:9)"], ["Abstract geometric patterns in pastel colors", "Square (1:1)"], ["Mystical forest with glowing plants", "Portrait (9:16)"] ], inputs=[prompt, aspect_ratio] ) if __name__ == "__main__": demo.launch()