Update app.py
Browse files9 unmodified lines10111213141516171819202122232425262728293031323334353637383940415 unmodified lines47484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031044 unmodified lines1091101111121131141151161174 unmodified lines12212312412512612712812913013113213313413513646 unmodified lines18318418518618718818920 unmodified lines2102112122132142152169 unmodified linesimport torchfrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler# Use environment variables for flexibilityMODEL_ID = os.getenv("MODEL_ID", "sd-community/sdxl-flash")MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # Allow generating multiple images at once# Determine device and load model outside of function for efficiencydevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")pipe = StableDiffusionXLPipeline.from_pretrained(MODEL_ID,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,use_safetensors=True,add_watermarker=False,).to(device)pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)# Torch compile for potential speedup (experimental)if USE_TORCH_COMPILE:pipe.compile()# CPU offloading for larger RAM capacity (experimental)if ENABLE_CPU_OFFLOAD:pipe.enable_model_cpu_offload()MAX_SEED = np.iinfo(np.int32).maxdef save_image(img):unique_name = str(uuid.uuid4()) + ".png"5 unmodified linesseed = random.randint(0, MAX_SEED)return seed@spaces.GPU(duration=35, enable_queue=True)def generate(prompt: str,negative_prompt: str = "",use_negative_prompt: bool = False,seed: int = 1,width: int = 1024,height: int = 1024,guidance_scale: float = 3,num_inference_steps: int = 30,randomize_seed: bool = False,use_resolution_binning: bool = True,num_images: int = 1, # Number of images to generateprogress=gr.Progress(track_tqdm=True),):seed = int(randomize_seed_fn(seed, randomize_seed))generator = torch.Generator(device=device).manual_seed(seed)# Improved options handlingoptions = {"prompt": [prompt] * num_images,"negative_prompt": [negative_prompt] * num_images if use_negative_prompt else None,"width": width,"height": height,"guidance_scale": guidance_scale,"num_inference_steps": num_inference_steps,"generator": generator,"output_type": "pil",}# Use resolution binning for faster generation with less VRAM usageif use_resolution_binning:options["use_resolution_binning"] = True# Generate images potentially in batchesimages = []for i in range(0, num_images, BATCH_SIZE):batch_options = options.copy()batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]if "negative_prompt" in batch_options:batch_options["negative_prompt"] = options["negative_prompt"][i:i+BATCH_SIZE]images.extend(pipe(**batch_options).images)image_paths = [save_image(img) for img in images]return image_paths, seedexamples = ["a cat eating a piece of cheese","a ROBOT riding a BLUE horse on Mars, photorealistic, 4k","Ironman VS Hulk, ultrarealistic","Astronaut in a jungle, cold color palette, oil pastel, detailed, 8k","An alien holding a sign board containing the word 'Flash', futuristic, neonpunk","Kids going to school, Anime style"]4 unmodified linesvisibility: hidden}'''with gr.Blocks(css=css) as demo:gr.Markdown("""# SDXL Flash""")with gr.Group():with gr.Row():prompt = gr.Text(4 unmodified linescontainer=False,)run_button = gr.Button("Run", scale=0)result = gr.Gallery(label="Result", columns=1, show_label=False)with gr.Accordion("Advanced options", open=False):num_images = gr.Slider(label="Number of Images",minimum=1,maximum=4,step=1,value=1,)with gr.Row():use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)negative_prompt = gr.Text(46 unmodified linesgr.Examples(examples=examples,inputs=prompt,cache_examples=False)use_negative_prompt.change(20 unmodified linesguidance_scale,num_inference_steps,randomize_seed,num_images],outputs=[result, seed],api_name="run",9 unmodified lines10111213141516171819202122232425262728293031323334355 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889904 unmodified lines95969798991001011021034 unmodified lines10810911011111211311411546 unmodified lines16216316416516616716816917020 unmodified lines1911921931941951969 unmodified linesimport torchfrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteSchedulerif not torch.cuda.is_available():DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"MAX_SEED = np.iinfo(np.int32).maxCACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "1") == "1"MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")if torch.cuda.is_available():pipe = StableDiffusionXLPipeline.from_pretrained("sd-community/sdxl-flash",torch_dtype=torch.float16,use_safetensors=True,add_watermarker=False)pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)pipe.to("cuda")def save_image(img):unique_name = str(uuid.uuid4()) + ".png"5 unmodified linesseed = random.randint(0, MAX_SEED)return seed@spaces.GPU(duration=30, queue=False)def generate(prompt: str,negative_prompt: str = "",use_negative_prompt: bool = False,seed: int = 0,width: int = 1024,height: int = 1024,guidance_scale: float = 3,num_inference_steps: int = 25,randomize_seed: bool = False,use_resolution_binning: bool = True,progress=gr.Progress(track_tqdm=True),):pipe.to(device)seed = int(randomize_seed_fn(seed, randomize_seed))generator = torch.Generator().manual_seed(seed)options = {"prompt":prompt,"negative_prompt":negative_prompt,"width":width,"height":height,"guidance_scale":guidance_scale,"num_inference_steps":num_inference_steps,"generator":generator,"use_resolution_binning":use_resolution_binning,"output_type":"pil",}images = pipe(**options).imagesimage_paths = [save_image(img) for img in images]return image_paths, seedexamples = ["a cat eating a piece of cheese","a ROBOT riding a BLUE horse on Mars, photorealistic","a cartoon of a IRONMAN fighting with HULK, wall painting","a cute robot artist painting on an easel, concept art","Astronaut in a jungle, cold color palette, oil pastel, detailed, 8k","An alien grasping a sign board contain word 'Flash', futuristic, neonpunk, detailed","Kids going to school, Anime style"]4 unmodified linesvisibility: hidden}'''with gr.Blocks(css=css) as demo:gr.Markdown("""# SDXL Flash### First Image processing takes time then images generate faster.""")with gr.Group():with gr.Row():prompt = gr.Text(4 unmodified linescontainer=False,)run_button = gr.Button("Run", scale=0)result = gr.Gallery(label="Result", columns=1)with gr.Accordion("Advanced options", open=False):with gr.Row():use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)negative_prompt = gr.Text(46 unmodified linesgr.Examples(examples=examples,inputs=prompt,outputs=[result, seed],fn=generate,cache_examples=CACHE_EXAMPLES,)use_negative_prompt.change(20 unmodified linesguidance_scale,num_inference_steps,randomize_seed,],outputs=[result, seed],api_name="run",
app.py+43-63