Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files12345678910111213148 unmodified lines2324252627282930313233343536373839404142434445464748494 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112259 unmodified lines18218318418518618718818919019119219319419519619719819920095 unmodified lines29629729829930030130230330430539 unmodified lines34534634734834935035135235335435535635735835924 unmodified lines384385386387388389390391392393394395396397398399400401402403404import spacesimport gradio as grimport torchfrom diffusers import ZImagePipeline, AutoPipelineForText2Imageimport osfrom pathlib import Path# Load the base model directly at startupprint("Loading Z-Image Turbo model...")print("This may take a few minutes on first run while the model downloads...")# Load the pipeline with optimal settingspipe = ZImagePipeline.from_pretrained("Tongyi-MAI/Z-Image-Turbo",8 unmodified linesprint("Model loaded successfully!")# Store the current model statecurrent_model = "base"lora_loaded = False@spaces.GPU()def generate_image(prompt,model_choice,progress=gr.Progress(track_tqdm=True)):"""Generate an image using Z-Image Turbo model with optional LoRA.Args:prompt: Text description of the desired imagemodel_choice: Either "Base Model" or "Classic Painting LoRA"Returns:Generated PIL Image"""global pipe, current_model, lora_loadedif pipe is None:raise gr.Error("Model failed to load on startup. Please restart the application.")4 unmodified lines# Determine devicedevice = "cuda" if torch.cuda.is_available() else "cpu"# Handle model switchingprogress(0.05, desc="Loading model...")try:if model_choice == "Classic Painting LoRA" and current_model != "lora":# Load LoRA weightsif not lora_loaded:print("Loading Classic Painting LoRA...")pipe.load_lora_weights("renderartist/Classic-Painting-Z-Image-Turbo-LoRA",adapter_name="classic_painting",weight_name="pytorch_lora_weights.safetensors")lora_loaded = True# Set LoRA adapterpipe.set_adapters(["classic_painting"], adapter_weights=[0.8])current_model = "lora"progress(0.15, desc="LoRA loaded, generating image...")# Generate with LoRA settingsgenerator = torch.Generator(device).manual_seed(42)result = pipe(prompt=prompt,negative_prompt=None,height=1024,width=1024,num_inference_steps=9,guidance_scale=0.0,generator=generator,)elif model_choice == "Base Model" and current_model != "base":# Disable LoRApipe.disable_lora()current_model = "base"progress(0.15, desc="Generating image...")# Generate with base model settingsgenerator = torch.Generator(device).manual_seed(42)result = pipe(prompt=prompt,negative_prompt=None,height=1024,width=1024,num_inference_steps=9,guidance_scale=0.0,generator=generator,)else:# Model already loaded, just generateprogress(0.15, desc="Generating image...")generator = torch.Generator(device).manual_seed(42)result = pipe(prompt=prompt,negative_prompt=None,height=1024,width=1024,num_inference_steps=9,guidance_scale=0.0,generator=generator,)image = result.images[0]progress(1.0, desc="Complete!")59 unmodified linesbox-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);}/* Model Selector */.model-selector {margin-bottom: 24px;}.model-selector label {font-size: 15px !important;font-weight: 500 !important;color: #1d1d1f !important;margin-bottom: 8px !important;display: block !important;}/* Textbox */textarea {font-size: 17px !important;95 unmodified linescolor: #86868b !important;}.dark .model-selector label {color: #f5f5f7 !important;}/* Responsive */@media (max-width: 734px) {.main-title {39 unmodified lines# Input Sectionwith gr.Column(elem_classes="input-section"):# Model Selectorwith gr.Group(elem_classes="model-selector"):model_choice = gr.Radio(choices=["Base Model", "Classic Painting LoRA"],value="Base Model",label="Select Model",info="Choose between the base Z-Image Turbo model or the Classic Painting LoRA variant")prompt = gr.Textbox(placeholder="Describe the image you want to create...",lines=3,24 unmodified linesgr.HTML("""<div class="footer-text"><p>Powered by Z-Image Turbo from Tongyi-MAI</p><p>Classic Painting LoRA by renderartist</p></div>""")# Event handlersgenerate_btn.click(fn=generate_image,inputs=[prompt, model_choice],outputs=output_image,api_visibility="public")prompt.submit(fn=generate_image,inputs=[prompt, model_choice],outputs=output_image,api_visibility="public")1234567891011121314158 unmodified lines2425262728293031323334353637383940414243444 unmodified lines4950515253545556575859606162636465666768697059 unmodified lines13013113213313413595 unmodified lines23123223323423523639 unmodified lines27627727827928028124 unmodified lines306307308309310311312313314315316317318319320321322323324325import spacesimport gradio as grimport torchfrom diffusers import ZImagePipelineimport osfrom pathlib import Path# Load the model directly at startupprint("Loading Z-Image Turbo model...")print("This may take a few minutes on first run while the model downloads...")# Load the pipeline with optimal settingspipe = ZImagePipeline.from_pretrained("Tongyi-MAI/Z-Image-Turbo",8 unmodified linesprint("Model loaded successfully!")@spaces.GPU()def generate_image(prompt,progress=gr.Progress(track_tqdm=True)):"""Generate an image using Z-Image Turbo model.Args:prompt: Text description of the desired imageReturns:Generated PIL Image"""global pipeif pipe is None:raise gr.Error("Model failed to load on startup. Please restart the application.")4 unmodified lines# Determine devicedevice = "cuda" if torch.cuda.is_available() else "cpu"# Set random seed for reproducibilitygenerator = torch.Generator(device).manual_seed(42)# Generate the image with optimal settingsprogress(0.1, desc="Generating image...")try:result = pipe(prompt=prompt,negative_prompt=None,height=1024,width=1024,num_inference_steps=9,guidance_scale=0.0,generator=generator,)image = result.images[0]progress(1.0, desc="Complete!")59 unmodified linesbox-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);}/* Textbox */textarea {font-size: 17px !important;95 unmodified linescolor: #86868b !important;}/* Responsive */@media (max-width: 734px) {.main-title {39 unmodified lines# Input Sectionwith gr.Column(elem_classes="input-section"):prompt = gr.Textbox(placeholder="Describe the image you want to create...",lines=3,24 unmodified linesgr.HTML("""<div class="footer-text"><p>Powered by Z-Image Turbo from Tongyi-MAI</p></div>""")# Event handlersgenerate_btn.click(fn=generate_image,inputs=prompt,outputs=output_image,api_visibility="public")prompt.submit(fn=generate_image,inputs=prompt,outputs=output_image,api_visibility="public")
app.py+21-100