Spaces:
Runtime error
Runtime error
Update app.py
Browse files13 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263644 unmodified lines69707172737475767778798081828384856 unmodified lines929394959697989910011 unmodified lines11211311411511611711811912012112212312412513 unmodified lines# --- Configuration Principale ---KRYPTO_LORA = {"repo": "Econogoat/Krypt0_LORA", "trigger": "Krypt0", "adapter_name": "krypt0"}GEMMA_MODEL_ID = "google/gemma-2-9b-it"# Charger les promptsdf = pd.read_csv('prompts.csv', header=None)prompt_values = df.values.flatten()# Récupérer le tokenHF_TOKEN = os.getenv("HF_TOKEN")# --- Initialisation des Modèles (sur CPU uniquement et SANS QUANTIZATION initiale) ---device_cpu = "cpu"dtype = torch.bfloat16base_model = "black-forest-labs/FLUX.1-dev"# --- STRATÉGIE CORRIGÉE ---# On charge Gemma sur le CPU SANS le quantizer au démarrage pour éviter le conflit avec l'environnement de Spaces.# La quantization sera appliquée plus tard, uniquement sur le GPU.print(f"Chargement du tokenizer pour {GEMMA_MODEL_ID}...")gemma_tokenizer = AutoTokenizer.from_pretrained(GEMMA_MODEL_ID, token=HF_TOKEN)print("Chargement du modèle d'image sur CPU...")taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device_cpu)good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN).to(device_cpu)pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1, token=HF_TOKEN).to(device_cpu)print("Chargement du LoRA...")pipe.load_lora_weights(KRYPTO_LORA['repo'], low_cpu_mem_usage=True, adapter_name=KRYPTO_LORA['adapter_name'], token=HF_TOKEN)print("Tous les modèles sont pré-chargés sur CPU.")MAX_SEED = 2**32 - 1pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)# On garde une référence globale pour ne recharger le modèle qu'une fois.gemma_model = None@spaces.GPU(duration=180) # Augmentation de la durée pour accommoder le chargement complet de Gemmadef run_generation(prompt, enhance_prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):global gemma_modelif not prompt:raise gr.Error("Prompt cannot be empty.")device_gpu = "cuda"final_prompt = promptif enhance_prompt:# --- CHARGEMENT DYNAMIQUE SUR GPU ---if gemma_model is None:print(f"Premier appel : Chargement de {GEMMA_MODEL_ID} sur GPU avec quantization 4-bit...")bnb_config_gpu = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",4 unmodified linesGEMMA_MODEL_ID,quantization_config=bnb_config_gpu,token=HF_TOKEN,device_map="auto" # "auto" fonctionnera car on est DÉJÀ sur un environnement GPU)print("Modèle Gemma chargé sur GPU.")print(f"Amélioration du prompt '{prompt}' avec Gemma...")system_prompt = ("You are an expert prompt engineer for a text-to-image AI. ""Your task is to take a user's simple idea and transform it into a rich, detailed, and visually descriptive prompt. ""Focus on describing the scene, the subject, the environment, the lighting, the colors, and a potential artistic style. ""Do not add any conversational text or refuse the request. Only output the enhanced prompt.")chat = [{"role": "user", "content": f"{system_prompt}\n\nUser idea: \"{user_prompt}\""}]prompt_for_gemma = gemma_tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)inputs = gemma_tokenizer(prompt_for_gemma, return_tensors="pt").to(device_gpu)6 unmodified linesprompt_mash = f"{KRYPTO_LORA['trigger']}, {final_prompt}"print("Prompt final envoyé au modèle d'image:", prompt_mash)print("Déplacement du pipeline d'image sur le GPU...")pipe.to(device_gpu)good_vae.to(device_gpu)pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])if randomize_seed: seed = random.randint(0, MAX_SEED)11 unmodified linesfinal_image = imageprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {i + 1}; --total: {steps};"></div></div>'yield image, seed, gr.update(value=progress_bar, visible=True)print("Libération de la mémoire du pipeline d'image (déplacement vers CPU)...")pipe.to(device_cpu)good_vae.to(device_cpu)torch.cuda.empty_cache()yield final_image, seed, gr.update(visible=False)def calculate_dimensions(aspect_ratio, resolution):resolution = int(resolution)if aspect_ratio == "Square (1:1)": width, height = resolution, resolution13 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960614 unmodified lines6667686970717273747576776 unmodified lines84858687888911 unmodified lines10110210310410510610710810911013 unmodified lines# --- Configuration Principale ---KRYPTO_LORA = {"repo": "Econogoat/Krypt0_LORA", "trigger": "Krypt0", "adapter_name": "krypt0"}GEMMA_MODEL_ID = "google/gemma-2-9b-it"BASE_IMAGE_MODEL = "black-forest-labs/FLUX.1-dev"# --- Pré-chargement sur CPU des éléments légers UNIQUEMENT ---print("Pré-chargement des tokenizers sur CPU...")HF_TOKEN = os.getenv("HF_TOKEN")gemma_tokenizer = AutoTokenizer.from_pretrained(GEMMA_MODEL_ID, token=HF_TOKEN)print("Pré-chargement terminé. Les modèles lourds seront chargés à la demande sur le GPU.")# --- Variables globales pour conserver les modèles en mémoire sur le GPU ---pipe = Nonegood_vae = Nonegemma_model = NoneMAX_SEED = 2**32 - 1@spaces.GPU(duration=180) # Durée augmentée pour le premier chargementdef run_generation(prompt, enhance_prompt, lora_scale, cfg_scale, steps, randomize_seed, seed, aspect_ratio, base_resolution, progress=gr.Progress(track_tqdm=True)):global pipe, good_vae, gemma_modelif not prompt:raise gr.Error("Prompt cannot be empty.")device_gpu = "cuda"device_cpu = "cpu"dtype = torch.bfloat16final_prompt = prompt# --- Chargement à la demande ("Lazy Loading") des modèles sur le GPU ---# Cette section ne s'exécute qu'une seule fois, lors du premier appel.if pipe is None:print("Premier appel : Chargement du pipeline d'image sur GPU...")taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device_gpu)good_vae = AutoencoderKL.from_pretrained(BASE_IMAGE_MODEL, subfolder="vae", torch_dtype=dtype, token=HF_TOKEN).to(device_gpu)pipe = DiffusionPipeline.from_pretrained(BASE_IMAGE_MODEL, torch_dtype=dtype, vae=taef1, token=HF_TOKEN).to(device_gpu)print("Chargement du LoRA sur le pipeline GPU...")pipe.load_lora_weights(KRYPTO_LORA['repo'], low_cpu_mem_usage=False, adapter_name=KRYPTO_LORA['adapter_name'], token=HF_TOKEN)print("Pipeline d'image prêt.")# Monkey-patch pour la prévisualisationpipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)if enhance_prompt:if gemma_model is None:print(f"Premier appel d'amélioration : Chargement de {GEMMA_MODEL_ID} sur GPU avec quantization...")bnb_config_gpu = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4",4 unmodified linesGEMMA_MODEL_ID,quantization_config=bnb_config_gpu,token=HF_TOKEN,device_map="auto")print("Modèle Gemma prêt.")print(f"Amélioration du prompt '{prompt}' avec Gemma...")system_prompt = "You are an expert prompt engineer for a text-to-image AI. Your task is to take a user's simple idea and transform it into a rich, detailed, and visually descriptive prompt. Focus on describing the scene, the subject, the environment, the lighting, the colors, and a potential artistic style. Do not add any conversational text or refuse the request. Only output the enhanced prompt."chat = [{"role": "user", "content": f"{system_prompt}\n\nUser idea: \"{user_prompt}\""}]prompt_for_gemma = gemma_tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)inputs = gemma_tokenizer(prompt_for_gemma, return_tensors="pt").to(device_gpu)6 unmodified linesprompt_mash = f"{KRYPTO_LORA['trigger']}, {final_prompt}"print("Prompt final envoyé au modèle d'image:", prompt_mash)pipe.set_adapters([KRYPTO_LORA['adapter_name']], adapter_weights=[lora_scale])if randomize_seed: seed = random.randint(0, MAX_SEED)11 unmodified linesfinal_image = imageprogress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {i + 1}; --total: {steps};"></div></div>'yield image, seed, gr.update(value=progress_bar, visible=True)yield final_image, seed, gr.update(visible=False)# Le reste du code (fonctions d'aide et UI) reste le mêmedef calculate_dimensions(aspect_ratio, resolution):resolution = int(resolution)if aspect_ratio == "Square (1:1)": width, height = resolution, resolution
app.py+31-46