Update app.py
Browse files11 unmodified lines1213141516171819202121 unmodified lines434445464748495051525354555657581 unmodified line6061626364656619 unmodified lines86878889909192939495969798991001011021031041051061071081091 unmodified line11111211311411511611750 unmodified lines1681691701711721731741751761771781791801811821831841855 unmodified lines19119219319419519619711 unmodified lines2092102112122132142152162172182192202212222232242252263 unmodified lines23023123223323423523623723823924024124211 unmodified linesfrom diffusers import FluxPipelinefrom PIL import Image# Setup and initialization codecache_path = path.join(path.dirname(path.abspath(__file__)), "models")# Use PERSISTENT_DIR environment variable for SpacesPERSISTENT_DIR = os.environ.get("PERSISTENT_DIR", ".")gallery_path = path.join(PERSISTENT_DIR, "gallery")21 unmodified linesif not path.exists(cache_path):os.makedirs(cache_path, exist_ok=True)pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))pipe.fuse_lora(lora_scale=0.125)pipe.to(device="cuda", dtype=torch.bfloat16)def save_image(image):"""Save the generated image and return the path"""try:# Ensure gallery directory existsif not os.path.exists(gallery_path):try:os.makedirs(gallery_path, exist_ok=True)1 unmodified lineprint(f"Failed to create gallery directory: {str(e)}")return None# Generate unique filename with timestamp and random suffixtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")random_suffix = os.urandom(4).hex()filename = f"generated_{timestamp}_{random_suffix}.png"19 unmodified linesprint(f"Error in save_image: {str(e)}")return Nonedef load_gallery():"""Load all images from the gallery directory"""try:# Ensure gallery directory existsos.makedirs(gallery_path, exist_ok=True)# Get all image files and sort by modification timeimage_files = []for f in os.listdir(gallery_path):if f.lower().endswith(('.png', '.jpg', '.jpeg')):full_path = os.path.join(gallery_path, f)image_files.append((full_path, os.path.getmtime(full_path)))# Sort by modification time (newest first)image_files.sort(key=lambda x: x[1], reverse=True)# Return only the file pathsreturn [f[0] for f in image_files]except Exception as e:print(f"Error loading gallery: {str(e)}")1 unmodified line# Create Gradio interfacewith gr.Blocks(theme=gr.themes.Soft()) as demo:with gr.Row():with gr.Column(scale=3):prompt = gr.Textbox(50 unmodified lines"✨ Generate Image",elem_classes=["generate-btn"])with gr.Column(scale=4, elem_classes=["fixed-width"]):# Current generated imageoutput = gr.Image(label="Generated Image",elem_id="output-image",elem_classes=["output-image", "fixed-width"])# Gallery of generated imagesgallery = gr.Gallery(label="Generated Images Gallery",show_label=True,5 unmodified lineselem_classes=["gallery-container", "fixed-width"])# Load existing gallery images on startupgallery.value = load_gallery()@spaces.GPU11 unmodified linesmax_sequence_length=256).images[0]# Save the generated imagesaved_path = save_image(generated_image)if saved_path is None:print("Warning: Failed to save generated image")# Return both the generated image and updated galleryreturn generated_image, load_gallery()except Exception as e:print(f"Error in image generation: {str(e)}")return None, load_gallery()# Connect the generation button to both the image output and gallery updatedef update_seed():return get_random_seed()3 unmodified linesoutputs=[output, gallery])# Add randomize seed button functionalityrandomize_seed.click(update_seed,outputs=[seed])# Also randomize seed after each generationgenerate_btn.click(update_seed,outputs=[seed]11 unmodified lines1213141516171819202122232421 unmodified lines4647484950515253545556575859606162636465666768697071721 unmodified line74757677787919 unmodified lines991001011021031041051061071081091101111121131141151161171 unmodified line11912012112212312450 unmodified lines1751761771781791801811821831841851861871885 unmodified lines19419519619719819911 unmodified lines2112122132142152162172182192202212222232242253 unmodified lines22923023123223323423523623723823911 unmodified linesfrom diffusers import FluxPipelinefrom PIL import Image# Hugging Face 토큰 설정HF_TOKEN = os.getenv("HF_TOKEN")if HF_TOKEN is None:raise ValueError("HF_TOKEN environment variable is not set")# Setup and initialization codecache_path = path.join(path.dirname(path.abspath(__file__)), "models")PERSISTENT_DIR = os.environ.get("PERSISTENT_DIR", ".")gallery_path = path.join(PERSISTENT_DIR, "gallery")21 unmodified linesif not path.exists(cache_path):os.makedirs(cache_path, exist_ok=True)# 인증된 모델 로드pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev",torch_dtype=torch.bfloat16,use_auth_token=HF_TOKEN)# Hyper-SD LoRA 로드 (인증 포함)pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD","Hyper-FLUX.1-dev-8steps-lora.safetensors",use_auth_token=HF_TOKEN))pipe.fuse_lora(lora_scale=0.125)pipe.to(device="cuda", dtype=torch.bfloat16)def save_image(image):"""Save the generated image and return the path"""try:if not os.path.exists(gallery_path):try:os.makedirs(gallery_path, exist_ok=True)1 unmodified lineprint(f"Failed to create gallery directory: {str(e)}")return Nonetimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")random_suffix = os.urandom(4).hex()filename = f"generated_{timestamp}_{random_suffix}.png"19 unmodified linesprint(f"Error in save_image: {str(e)}")return Nonedef load_gallery():"""Load all images from the gallery directory"""try:os.makedirs(gallery_path, exist_ok=True)image_files = []for f in os.listdir(gallery_path):if f.lower().endswith(('.png', '.jpg', '.jpeg')):full_path = os.path.join(gallery_path, f)image_files.append((full_path, os.path.getmtime(full_path)))image_files.sort(key=lambda x: x[1], reverse=True)return [f[0] for f in image_files]except Exception as e:print(f"Error loading gallery: {str(e)}")1 unmodified line# Create Gradio interfacewith gr.Blocks(theme=gr.themes.Soft()) as demo:with gr.Row():with gr.Column(scale=3):prompt = gr.Textbox(50 unmodified lines"✨ Generate Image",elem_classes=["generate-btn"])with gr.Column(scale=4, elem_classes=["fixed-width"]):output = gr.Image(label="Generated Image",elem_id="output-image",elem_classes=["output-image", "fixed-width"])gallery = gr.Gallery(label="Generated Images Gallery",show_label=True,5 unmodified lineselem_classes=["gallery-container", "fixed-width"])gallery.value = load_gallery()@spaces.GPU11 unmodified linesmax_sequence_length=256).images[0]saved_path = save_image(generated_image)if saved_path is None:print("Warning: Failed to save generated image")return generated_image, load_gallery()except Exception as e:print(f"Error in image generation: {str(e)}")return None, load_gallery()def update_seed():return get_random_seed()3 unmodified linesoutputs=[output, gallery])randomize_seed.click(update_seed,outputs=[seed])generate_btn.click(update_seed,outputs=[seed]
app.py+19-22