Leteint commited on
Commit
0996984
·
verified ·
1 Parent(s): 35f5aef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -98
app.py CHANGED
@@ -1,127 +1,62 @@
1
- import spaces # Pour Zero GPU gratuit
2
  import torch
3
  import gradio as gr
4
  from diffusers import FluxPipeline
5
- from huggingface_hub import hf_hub_download
6
  import random
7
  import os
8
 
9
- # Authentification HuggingFace
10
- from huggingface_hub import login
11
  hf_token = os.getenv("HF_TOKEN")
12
  print(f"Token trouvé : {bool(hf_token)}")
13
- print(f"Longueur du token : {len(hf_token) if hf_token else 0}")
14
-
15
-
16
  if hf_token:
17
  login(token=hf_token)
18
- print("✅ Authentifié sur HuggingFace")
19
- else:
20
- print("⚠️ HF_TOKEN non trouvé - certains modèles peuvent être inaccessibles")
21
-
22
-
23
 
24
-
25
- # Chargement du modèle Flux.1-schnell
26
  model_id = "black-forest-labs/FLUX.1-schnell"
27
-
28
- # Variables globales pour LoRA
29
  lora_repo = None
30
  lora_path = None
31
 
32
  def load_lora(repo_id, style):
33
  global lora_repo, lora_path
34
  try:
35
- # Construire le nom du fichier basé sur le style
36
  filename = f"{style}_lora.safetensors"
37
-
38
  lora_path = hf_hub_download(repo_id=repo_id, filename=filename)
39
  lora_repo = repo_id
40
- return f"✅ LoRA chargé : {repo_id} ({filename})"
41
  except Exception as e:
42
- return f"❌ Erreur LoRA : {str(e)}"
43
 
44
- @spaces.GPU(duration=120) # Allocation GPU pour 120s
45
  def generate(prompt, negative_prompt, width=1024, height=1024, steps=4, seed=-1, lora_scale=0.8):
46
- try:
47
- # Chargement du pipe dans la fonction (obligatoire pour Zero GPU)
48
- pipe = FluxPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
49
- pipe.to("cuda")
50
-
51
- # Chargement LoRA si disponible
52
- if lora_repo and lora_path:
53
- pipe.load_lora_weights(lora_path)
54
- pipe.fuse_lora(lora_scale=lora_scale)
55
-
56
- generator = torch.Generator("cuda").manual_seed(seed if seed != -1 else random.randint(0, 2**32))
57
-
58
- image = pipe(
59
- prompt,
60
- negative_prompt=negative_prompt,
61
- height=height,
62
- width=width,
63
- num_inference_steps=steps,
64
- guidance_scale=0.0,
65
- generator=generator
66
- ).images[0]
67
-
68
- # Nettoyage VRAM
69
- del pipe
70
- torch.cuda.empty_cache()
71
- return image
72
- except Exception as e:
73
- print(f"Erreur génération: {e}") # Debug dans les logs
74
- import traceback
75
- traceback.print_exc()
76
- return None
77
-
78
- # Interface Gradio
79
- with gr.Blocks(title="Flux Schnell + LoRA") as demo:
80
- gr.Markdown("# 🎨 Flux.1 Schnell + LoRA\nGénérateur rapide (4 steps) avec support LoRA personnalisé")
81
 
82
- with gr.Row():
83
- with gr.Column(scale=1):
84
- lora_input = gr.Textbox(
85
- label="Repo HuggingFace LoRA",
86
- placeholder="ex: stabilityai/stable-diffusion-xl-base-1.0",
87
- value="XLabs-AI/flux-lora-collection"
88
- )
89
- subfolder_input = gr.Dropdown(
90
- label="Style LoRA",
91
- choices=["realism", "anime", "scenery", "art", "disney"],
92
- value="realism"
93
- )
94
- load_btn = gr.Button("Charger LoRA", variant="secondary")
95
- status = gr.Textbox(label="Status", interactive=False)
96
-
97
- with gr.Column(scale=4):
98
- prompt = gr.Textbox(
99
- label="Prompt",
100
- placeholder="une belle image artistique, haute qualité, détaillée",
101
- lines=3,
102
- value="beautiful artistic portrait, high quality, detailed"
103
- )
104
- neg_prompt = gr.Textbox(
105
- label="Prompt négatif",
106
- value="blurry, deformed, ugly, lowres, text, watermark"
107
- )
108
 
109
- with gr.Row():
110
- steps = gr.Slider(1, 20, value=4, label="Steps", step=1)
111
- width = gr.Slider(512, 2048, value=1024, step=128, label="Largeur")
112
- height = gr.Slider(512, 2048, value=1024, step=128, label="Hauteur")
113
- lora_scale_slider = gr.Slider(0, 2, value=0.8, step=0.1, label="Force LoRA")
114
- seed = gr.Number(value=-1, label="Seed (-1=random)", precision=0)
115
 
116
- generate_btn = gr.Button("🚀 Générer Image", variant="primary", size="lg")
117
- output = gr.Image(label="Résultat", type="pil")
118
 
119
- load_btn.click(load_lora, inputs=[lora_input, subfolder_input], outputs=status)
120
- generate_btn.click(
121
- generate,
122
- inputs=[prompt, neg_prompt, width, height, steps, seed, lora_scale_slider],
123
- outputs=output
124
- )
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- if __name__ == "__main__":
127
- demo.launch(theme=gr.themes.Soft())
 
1
+ import spaces
2
  import torch
3
  import gradio as gr
4
  from diffusers import FluxPipeline
5
+ from huggingface_hub import hf_hub_download, login
6
  import random
7
  import os
8
 
9
+ # Authentification (gardez ça)
 
10
  hf_token = os.getenv("HF_TOKEN")
11
  print(f"Token trouvé : {bool(hf_token)}")
 
 
 
12
  if hf_token:
13
  login(token=hf_token)
14
+ print("✅ Authentifié")
 
 
 
 
15
 
 
 
16
  model_id = "black-forest-labs/FLUX.1-schnell"
 
 
17
  lora_repo = None
18
  lora_path = None
19
 
20
  def load_lora(repo_id, style):
21
  global lora_repo, lora_path
22
  try:
 
23
  filename = f"{style}_lora.safetensors"
 
24
  lora_path = hf_hub_download(repo_id=repo_id, filename=filename)
25
  lora_repo = repo_id
26
+ return f"✅ LoRA: {repo_id} ({filename})"
27
  except Exception as e:
28
+ return f"❌ {e}"
29
 
30
+ @spaces.GPU(duration=120)
31
  def generate(prompt, negative_prompt, width=1024, height=1024, steps=4, seed=-1, lora_scale=0.8):
32
+ pipe = FluxPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
33
+ pipe.to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ if lora_repo and lora_path:
36
+ pipe.load_lora_weights(lora_path)
37
+ pipe.fuse_lora(lora_scale=lora_scale) # Après to("cuda")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ pipe.enable_model_cpu_offload() # Optim VRAM
 
 
 
 
 
40
 
41
+ generator = torch.Generator("cuda").manual_seed(seed if seed != -1 else random.randint(0, 2**32))
 
42
 
43
+ image = pipe(
44
+ prompt,
45
+ negative_prompt=negative_prompt,
46
+ height=height, width=width,
47
+ num_inference_steps=steps,
48
+ guidance_scale=0.0,
49
+ generator=generator,
50
+ max_sequence_length=256 # Pour FLUX
51
+ ).images[0]
52
+
53
+ del pipe # Nettoyage
54
+ torch.cuda.empty_cache()
55
+ return image
56
+
57
+ # Interface Gradio (inchangée)
58
+ with gr.Blocks(title="Flux Schnell + LoRA") as demo:
59
+ # ... (votre interface reste identique)
60
+ pass
61
 
62
+ demo.launch()