import gradio as gr import os import tempfile from huggingface_hub import InferenceClient from pathlib import Path import time # Initialize Hugging Face Inference Client client = InferenceClient(api_key=os.environ.get("HF_TOKEN")) def cleanup_temp_files(): """Clean up old temporary image files.""" try: temp_dir = tempfile.gettempdir() for file_path in Path(temp_dir).glob("*.png"): try: if file_path.stat().st_mtime < (time.time() - 300): # 5 minutes file_path.unlink(missing_ok=True) except Exception: pass except Exception as e: print(f"Cleanup error: {e}") def generate_image(prompt: str) -> tuple: """Generate image using Hugging Face's free text-to-image model.""" cleanup_temp_files() if not os.environ.get("HF_TOKEN"): return (None, "❌ Please set HF_TOKEN environment variable") try: # Use a free, fast, high-quality model: FLUX.1-schnell image = client.text_to_image( prompt=prompt, model="black-forest-labs/FLUX.1-schnell", width=1024, height=1024, num_inference_steps=4 # Very fast (4 steps!) ) # Save image to temp file temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False) image.save(temp_file.name) return (temp_file.name, "✅ Image generated successfully!") except Exception as e: return (None, f"❌ Error generating image: {str(e)}") def create_ui(): css = """ .status-box { margin-top: 1rem; padding: 0.8rem 1rem; border-radius: 8px; font-weight: 500; border-left: 4px solid; } .status-success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; } .status-error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; } """ with gr.Blocks(title="HF Text-to-Image (Free)", theme=gr.themes.Soft(), css=css) as demo: gr.HTML("""
Generate high-quality images using FLUX.1-schnell (free on Hugging Face!)
✅ Works with free HF accounts • ⚡ Only 4 inference steps!
⚠️ Requires Hugging Face API token (set as HF_TOKEN)