Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349import osimport randomimport uuidimport jsonimport timeimport asyncioimport refrom threading import Threadimport gradio as grimport spacesimport torchimport numpy as npfrom PIL import Imageimport edge_ttsfrom transformers import (AutoModelForCausalLM,AutoTokenizer,TextIteratorStreamer,Qwen2VLForConditionalGeneration,AutoProcessor,)from transformers.image_utils import load_imagefrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteSchedulerMAX_MAX_NEW_TOKENS = 2048DEFAULT_MAX_NEW_TOKENS = 1024MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# -----------------------# Progress Bar Helper# -----------------------def progress_bar_html(label: str) -> str:"""Returns an HTML snippet for a thin progress bar with a label.The progress bar is styled as a dark red animated bar."""return f'''<div style="display: flex; align-items: center;"><span style="margin-right: 10px; font-size: 14px;">{label}</span><div style="width: 110px; height: 5px; background-color: #DDA0DD; border-radius: 2px; overflow: hidden;"><div style="width: 100%; height: 100%; background-color: #FF00FF; animation: loading 1.5s linear infinite;"></div></div></div><style>@keyframes loading {{0% {{ transform: translateX(-100%); }}100% {{ transform: translateX(100%); }}}}</style>'''# -----------------------# Text Generation Setup# -----------------------model_id = "prithivMLmods/DeepHermes-3-Llama-3-3B-Preview-abliterated"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id,device_map="auto",torch_dtype=torch.bfloat16,)model.eval()TTS_VOICES = ["en-US-JennyNeural", # @tts1"en-US-GuyNeural", # @tts2]# -----------------------# Multimodal OCR Setup# -----------------------MODEL_ID = "prithivMLmods/Qwen2-VL-OCR2-2B-Instruct"processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)model_m = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_ID,trust_remote_code=True,torch_dtype=torch.float16).to("cuda").eval()async def text_to_speech(text: str, voice: str, output_file="output.mp3"):"""Convert text to speech using Edge TTS and save as MP3"""communicate = edge_tts.Communicate(text, voice)await communicate.save(output_file)return output_filedef clean_chat_history(chat_history):"""Filter out any chat entries whose "content" is not a string."""cleaned = []for msg in chat_history:if isinstance(msg, dict) and isinstance(msg.get("content"), str):cleaned.append(msg)return cleaned# -----------------------# Stable Diffusion Image Generation Setup# -----------------------MAX_SEED = np.iinfo(np.int32).maxUSE_TORCH_COMPILE = FalseENABLE_CPU_OFFLOAD = Falseif torch.cuda.is_available():pipe = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0_Lightning",torch_dtype=torch.float16,use_safetensors=True,)pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)# LoRA options with one example for each.LORA_OPTIONS = {"Realism": ("prithivMLmods/Canopus-Realism-LoRA", "Canopus-Realism-LoRA.safetensors", "rlms"),"Pixar": ("prithivMLmods/Canopus-Pixar-Art", "Canopus-Pixar-Art.safetensors", "pixar"),"Photoshoot": ("prithivMLmods/Canopus-Photo-Shoot-Mini-LoRA", "Canopus-Photo-Shoot-Mini-LoRA.safetensors", "photo"),"Clothing": ("prithivMLmods/Canopus-Clothing-Adp-LoRA", "Canopus-Dress-Clothing-LoRA.safetensors", "clth"),"Interior": ("prithivMLmods/Canopus-Interior-Architecture-0.1", "Canopus-Interior-Architecture-0.1δ.safetensors", "arch"),"Fashion": ("prithivMLmods/Canopus-Fashion-Product-Dilation", "Canopus-Fashion-Product-Dilation.safetensors", "fashion"),"Minimalistic": ("prithivMLmods/Pegasi-Minimalist-Image-Style", "Pegasi-Minimalist-Image-Style.safetensors", "minimalist"),"Modern": ("prithivMLmods/Canopus-Modern-Clothing-Design", "Canopus-Modern-Clothing-Design.safetensors", "mdrnclth"),"Animaliea": ("prithivMLmods/Canopus-Animaliea-Artism", "Canopus-Animaliea-Artism.safetensors", "Animaliea"),"Wallpaper": ("prithivMLmods/Canopus-Liquid-Wallpaper-Art", "Canopus-Liquid-Wallpaper-Minimalize-LoRA.safetensors", "liquid"),"Cars": ("prithivMLmods/Canes-Cars-Model-LoRA", "Canes-Cars-Model-LoRA.safetensors", "car"),"PencilArt": ("prithivMLmods/Canopus-Pencil-Art-LoRA", "Canopus-Pencil-Art-LoRA.safetensors", "Pencil Art"),"ArtMinimalistic": ("prithivMLmods/Canopus-Art-Medium-LoRA", "Canopus-Art-Medium-LoRA.safetensors", "mdm"),}# Load all LoRA weightsfor model_name, weight_name, adapter_name in LORA_OPTIONS.values():pipe.load_lora_weights(model_name, weight_name=weight_name, adapter_name=adapter_name)pipe.to("cuda")else:pipe = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0_Lightning",torch_dtype=torch.float32,use_safetensors=True,).to(device)def save_image(img: Image.Image) -> str:"""Save a PIL image with a unique filename and return the path."""unique_name = str(uuid.uuid4()) + ".png"img.save(unique_name)return unique_namedef randomize_seed_fn(seed: int, randomize_seed: bool) -> int:if randomize_seed:seed = random.randint(0, MAX_SEED)return seed@spaces.GPU(duration=180, enable_queue=True)def generate_image(prompt: str,negative_prompt: str = "",seed: int = 0,width: int = 1024,height: int = 1024,guidance_scale: float = 3.0,randomize_seed: bool = True,lora_model: str = "Realism",progress=gr.Progress(track_tqdm=True),):seed = int(randomize_seed_fn(seed, randomize_seed))effective_negative_prompt = negative_prompt # Use provided negative prompt if anymodel_name, weight_name, adapter_name = LORA_OPTIONS[lora_model]pipe.set_adapters(adapter_name)outputs = pipe(prompt=prompt,negative_prompt=effective_negative_prompt,width=width,height=height,guidance_scale=guidance_scale,num_inference_steps=28,num_images_per_prompt=1,cross_attention_kwargs={"scale": 0.65},output_type="pil",)images = outputs.imagesimage_paths = [save_image(img) for img in images]return image_paths, seed# -----------------------# Main Chat/Generation Function# -----------------------@spaces.GPUdef generate(input_dict: dict,chat_history: list[dict],max_new_tokens: int = 1024,temperature: float = 0.6,top_p: float = 0.9,top_k: int = 50,repetition_penalty: float = 1.2,):"""Generates chatbot responses with support for multimodal input, TTS, and image generation.Special commands:- "@tts1" or "@tts2": triggers text-to-speech.- "@<lora_command>": triggers image generation using the new LoRA pipeline.Available commands (case-insensitive): @realism, @pixar, @photoshoot, @clothing, @interior, @fashion,@minimalistic, @modern, @animaliea, @wallpaper, @cars, @pencilart, @artminimalistic."""text = input_dict["text"]files = input_dict.get("files", [])# Check for image generation command based on LoRA tags.lora_mapping = { key.lower(): key for key in LORA_OPTIONS }for key_lower, key in lora_mapping.items():command_tag = "@" + key_lowerif text.strip().lower().startswith(command_tag):prompt_text = text.strip()[len(command_tag):].strip()yield progress_bar_html(f"Processing Image Generation ({key} style)")image_paths, used_seed = generate_image(prompt=prompt_text,negative_prompt="",seed=1,width=1024,height=1024,guidance_scale=3,randomize_seed=True,lora_model=key,)yield progress_bar_html("Finalizing Image Generation")yield gr.Image(image_paths[0])return# Check for TTS command (@tts1 or @tts2)tts_prefix = "@tts"is_tts = any(text.strip().lower().startswith(f"{tts_prefix}{i}") for i in range(1, 3))voice_index = next((i for i in range(1, 3) if text.strip().lower().startswith(f"{tts_prefix}{i}")), None)if is_tts and voice_index:voice = TTS_VOICES[voice_index - 1]text = text.replace(f"{tts_prefix}{voice_index}", "").strip()conversation = [{"role": "user", "content": text}]else:voice = Nonetext = text.replace(tts_prefix, "").strip()conversation = clean_chat_history(chat_history)conversation.append({"role": "user", "content": text})if files:if len(files) > 1:images = [load_image(image) for image in files]elif len(files) == 1:images = [load_image(files[0])]else:images = []messages = [{"role": "user","content": [*[{"type": "image", "image": image} for image in images],{"type": "text", "text": text},]}]prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = processor(text=[prompt], images=images, return_tensors="pt", padding=True).to("cuda")streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}thread = Thread(target=model_m.generate, kwargs=generation_kwargs)thread.start()buffer = ""yield progress_bar_html("Processing with Qwen2VL Ocr")for new_text in streamer:buffer += new_textbuffer = buffer.replace("<|im_end|>", "")time.sleep(0.01)yield bufferelse:input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")input_ids = input_ids.to(model.device)streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)generation_kwargs = {"input_ids": input_ids,"streamer": streamer,"max_new_tokens": max_new_tokens,"do_sample": True,"top_p": top_p,"top_k": top_k,"temperature": temperature,"num_beams": 1,"repetition_penalty": repetition_penalty,}t = Thread(target=model.generate, kwargs=generation_kwargs)t.start()outputs = []for new_text in streamer:outputs.append(new_text)yield "".join(outputs)final_response = "".join(outputs)yield final_responseif is_tts and voice:output_file = asyncio.run(text_to_speech(final_response, voice))yield gr.Audio(output_file, autoplay=True)# -----------------------# Gradio Chat Interface# -----------------------demo = gr.ChatInterface(fn=generate,additional_inputs=[gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS),gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6),gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9),gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50),gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2),],examples=[["@realism Chocolate dripping from a donut, hyper-realistic"],["@pixar Young man with wavy hair in an armchair, Pixar style"],["@realism Futuristic cityscape with neon lights"],["Write the python array rotation program"],["@photoshoot Dramatic portrait lighting"],[{"text": "Summarize the letter", "files": ["examples/1.png"]}],["@tts1 Who was Nikola Tesla and how did he die?"],["@clothing Fashionable streetwear in the city"],["@interior Modern minimalist living room"],["@fashion Runway model in haute couture"],["@minimalistic Elegant serene landscape"],["@modern Abstract geometric art"],["@animaliea Cute animal portrait, vibrant colors"],["@wallpaper Scenic mountain desktop wallpaper"],["@cars Sleek sports car on city streets"],["@pencilart Detailed historic building sketch"],["@artminimalistic Subtle minimalist artwork"],["@tts2 What causes rainbows?"],],cache_examples=False,type="messages",description="# **Gen Vision Sdxl** `tts: @tts1 @tts2` \n `image-tags: @realism, @pixar, @photoshoot, @clothing, @interior, @fashion, @minimalistic, @modern, @animaliea, @wallpaper, @cars, @pencilart, @artminimalistic` \n \n `default: chat, image inference`",fill_height=True,textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple", placeholder="text, image-infer, image-generation, tts"),stop_btn="Stop Generation",multimodal=True,)if __name__ == "__main__":demo.queue(max_size=20).launch(share=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415import osimport gradio as grimport jsonimport loggingimport torchfrom PIL import Imageimport spacesfrom diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipelinefrom diffusers.utils import load_imagefrom huggingface_hub import hf_hub_download, HfFileSystem, ModelCardimport copyimport randomimport timeimport re# Load LoRAs from JSON filewith open('loras.json', 'r') as f:loras = json.load(f)# Initialize the base model for SDXLdtype = torch.float16 if torch.cuda.is_available() else torch.float32device = "cuda" if torch.cuda.is_available() else "cpu"base_model = "stabilityai/stable-diffusion-xl-base-1.0"# Load SDXL pipelinespipe = StableDiffusionXLPipeline.from_pretrained(base_model,torch_dtype=dtype,use_safetensors=True).to(device)pipe_i2i = StableDiffusionXLImg2ImgPipeline.from_pretrained(base_model,torch_dtype=dtype,use_safetensors=True).to(device)MAX_SEED = 2**32 - 1# Custom SDXL generation function for live preview@torch.inference_mode()def generate_sdxl_images(pipe,prompt: str,height: int = 1024,width: int = 1024,num_inference_steps: int = 50,guidance_scale: float = 7.5,generator: Optional[torch.Generator] = None,output_type: str = "pil",):# Encode promptprompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds = pipe.encode_prompt(prompt=prompt,num_images_per_prompt=1,do_classifier_free_guidance=True,)# Prepare latentslatents = pipe.prepare_latents(batch_size=1,num_channels_latents=pipe.unet.config.in_channels,height=height,width=width,dtype=prompt_embeds.dtype,device=pipe.device,generator=generator,)# Prepare timestepspipe.scheduler.set_timesteps(num_inference_steps, device=pipe.device)timesteps = pipe.scheduler.timesteps# Prepare guidancedo_classifier_free_guidance = guidance_scale > 1.0if do_classifier_free_guidance:prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds])# Denoising loopfor i, t in enumerate(timesteps):# Expand latents for guidancelatent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents# Predict noisenoise_pred = pipe.unet(latent_model_input,t,encoder_hidden_states=prompt_embeds,added_cond_kwargs={"text_embeds": pooled_prompt_embeds},).sample# Perform guidanceif do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)# Step schedulerlatents = pipe.scheduler.step(noise_pred, t, latents).prev_sample# Decode latents to image every stepimage = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]yield pipe.image_processor.postprocess(image, output_type=output_type)[0]# Final imageimage = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]yield pipe.image_processor.postprocess(image, output_type=output_type)[0]class calculateDuration:def __init__(self, activity_name=""):self.activity_name = activity_namedef __enter__(self):self.start_time = time.time()return selfdef __exit__(self, exc_type, exc_value, traceback):self.end_time = time.time()self.elapsed_time = self.end_time - self.start_timeif self.activity_name:print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")else:print(f"Elapsed time: {self.elapsed_time:.6f} seconds")def update_selection(evt: gr.SelectData, width, height):selected_lora = loras[evt.index]new_placeholder = f"Type a prompt for {selected_lora['title']}"lora_repo = selected_lora["repo"]updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"if "aspect" in selected_lora:if selected_lora["aspect"] == "portrait":width = 768height = 1024elif selected_lora["aspect"] == "landscape":width = 1024height = 768else:width = 1024height = 1024return (gr.update(placeholder=new_placeholder),updated_text,evt.index,width,height,)@spaces.GPU(duration=70)def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):pipe.to("cuda")generator = torch.Generator(device="cuda").manual_seed(seed)with calculateDuration("Generating image"):for img in generate_sdxl_images(pipe,prompt=prompt_mash,num_inference_steps=steps,guidance_scale=cfg_scale,width=width,height=height,generator=generator,output_type="pil",):yield imgdef generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, seed):generator = torch.Generator(device="cuda").manual_seed(seed)pipe_i2i.to("cuda")image_input = load_image(image_input_path)final_image = pipe_i2i(prompt=prompt_mash,image=image_input,strength=image_strength,num_inference_steps=steps,guidance_scale=cfg_scale,width=width,height=height,generator=generator,output_type="pil",).images[0]return final_image@spaces.GPU(duration=70)def run_lora(prompt, image_input, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):if selected_index is None:raise gr.Error("You must select a LoRA before proceeding.")selected_lora = loras[selected_index]lora_path = selected_lora["repo"]trigger_word = selected_lora["trigger_word"]if trigger_word:if "trigger_position" in selected_lora and selected_lora["trigger_position"] == "prepend":prompt_mash = f"{trigger_word} {prompt}"else:prompt_mash = f"{prompt} {trigger_word}"else:prompt_mash = prompt# Unload previous LoRA weightswith calculateDuration("Unloading LoRA"):pipe.unload_lora_weights()pipe_i2i.unload_lora_weights()# Load LoRA weights and set adapter scalewith calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):weight_name = selected_lora.get("weights", None)adapter_name = "lora"pipe.load_lora_weights(lora_path, weight_name=weight_name, adapter_name=adapter_name)pipe.set_adapters([adapter_name], [lora_scale])pipe_i2i.load_lora_weights(lora_path, weight_name=weight_name, adapter_name=adapter_name)pipe_i2i.set_adapters([adapter_name], [lora_scale])# Set random seedwith calculateDuration("Randomizing seed"):if randomize_seed:seed = random.randint(0, MAX_SEED)if image_input is not None:final_image = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, seed)yield final_image, seed, gr.update(visible=False)else:image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress)final_image = Nonestep_counter = 0for image in image_generator:step_counter += 1final_image = imageprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'yield image, seed, gr.update(value=progress_bar, visible=True)yield final_image, seed, gr.update(value=progress_bar, visible=False)def get_huggingface_safetensors(link):split_link = link.split("/")if len(split_link) != 2:raise Exception("Invalid Hugging Face repository link format.")# Load model cardmodel_card = ModelCard.load(link)base_model = model_card.data.get("base_model")print(base_model)# Validate model type for SDXLif base_model != "stabilityai/stable-diffusion-xl-base-1.0":raise Exception("Not an SDXL LoRA!")# Extract image and trigger wordimage_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)trigger_word = model_card.data.get("instance_prompt", "")image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None# Initialize Hugging Face file systemfs = HfFileSystem()try:list_of_files = fs.ls(link, detail=False)safetensors_name = Nonehighest_trained_file = Nonehighest_steps = -1last_safetensors_file = Nonestep_pattern = re.compile(r"_0{3,}\d+") # Detects step count `_000...`for file in list_of_files:filename = file.split("/")[-1]if filename.endswith(".safetensors"):last_safetensors_file = filenamematch = step_pattern.search(filename)if not match:safetensors_name = filenamebreakelse:steps = int(match.group().lstrip("_"))if steps > highest_steps:highest_trained_file = filenamehighest_steps = stepsif not image_url and filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):image_url = f"https://huggingface.co/{link}/resolve/main/{filename}"if not safetensors_name:safetensors_name = highest_trained_file if highest_trained_file else last_safetensors_fileif not safetensors_name:raise Exception("No valid *.safetensors file found in the repository.")except Exception as e:print(e)raise Exception("You didn't include a valid Hugging Face repository with a *.safetensors LoRA")return split_link[1], link, safetensors_name, trigger_word, image_urldef check_custom_model(link):if link.startswith("https://"):if link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co"):link_split = link.split("huggingface.co/")return get_huggingface_safetensors(link_split[1])else:return get_huggingface_safetensors(link)def add_custom_lora(custom_lora):global lorasif custom_lora:try:title, repo, path, trigger_word, image = check_custom_model(custom_lora)print(f"Loaded custom LoRA: {repo}")card = f'''<div class="custom_lora_card"><span>Loaded custom LoRA:</span><div class="card_internal"><img src="{image}" /><div><h3>{title}</h3><small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small></div></div></div>'''existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)if not existing_item_index:new_item = {"image": image,"title": title,"repo": repo,"weights": path,"trigger_word": trigger_word}print(new_item)existing_item_index = len(loras)loras.append(new_item)return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_wordexcept Exception as e:gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-SDXL LoRA")return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-SDXL LoRA"), gr.update(visible=True), gr.update(), "", None, ""else:return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""def remove_custom_lora():return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""run_lora.zerogpu = Truecss = '''#gen_btn{height: 100%}#gen_column{align-self: stretch}#title{text-align: center}#title h1{font-size: 3em; display:inline-flex; align-items:center}#title img{width: 100px; margin-right: 0.5em}#gallery .grid-wrap{height: 10vh}#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}.card_internal{display: flex;height: 100px;margin-top: .5em}.card_internal img{margin-right: 1em}.styler{--form-gap-width: 0px !important}#progress{height:30px}#progress .generating{display:none}.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}'''font = [gr.themes.GoogleFont("Source Sans Pro"), "Arial", "sans-serif"]with gr.Blocks(theme=gr.themes.Soft(font=font), css=css, delete_cache=(60, 60)) as app:title = gr.HTML("""<h1>SDXL LoRA DLC</h1>""",elem_id="title",)selected_index = gr.State(None)with gr.Row():with gr.Column(scale=3):prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")with gr.Column(scale=1, elem_id="gen_column"):generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")with gr.Row():with gr.Column():selected_info = gr.Markdown("")gallery = gr.Gallery([(item["image"], item["title"]) for item in loras],label="LoRA Gallery",allow_preview=False,columns=3,elem_id="gallery",show_share_button=False)with gr.Group():custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="username/sdxl-lora-model")gr.Markdown("[Check the list of SDXL LoRAs](https://huggingface.co/models?other=base_model:stabilityai/stable-diffusion-xl-base-1.0)", elem_id="lora_list")custom_lora_info = gr.HTML(visible=False)custom_lora_button = gr.Button("Remove custom LoRA", visible=False)with gr.Column():progress_bar = gr.Markdown(elem_id="progress", visible=False)result = gr.Image(label="Generated Image")with gr.Row():with gr.Accordion("Advanced Settings", open=False):with gr.Row():input_image = gr.Image(label="Input image", type="filepath")image_strength = gr.Slider(label="Denoise Strength", info="Lower means more image influence", minimum=0.1, maximum=1.0, step=0.01, value=0.75)with gr.Column():with gr.Row():cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=7.5)steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=30)with gr.Row():width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)with gr.Row():randomize_seed = gr.Checkbox(True, label="Randomize seed")seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=1.0)gallery.select(update_selection,inputs=[width, height],outputs=[prompt, selected_info, selected_index, width, height])custom_lora.input(add_custom_lora,inputs=[custom_lora],outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt])custom_lora_button.click(remove_custom_lora,outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora])gr.on(triggers=[generate_button.click, prompt.submit],fn=run_lora,inputs=[prompt, input_image, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],outputs=[result, seed, progress_bar])app.queue()app.launch()
app.py+386-320