appinitdev commited on
Commit
c291298
路
verified 路
1 Parent(s): 74aaf6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -25
app.py CHANGED
@@ -1,13 +1,13 @@
1
  import torch
2
  import spaces
3
  import gradio as gr
4
- from diffusers import FluxImg2ImgPipeline
5
  from PIL import Image
6
 
7
- # 1. Carga del modelo optimizado en memoria
8
  model_id = "black-forest-labs/FLUX.1-schnell"
9
- print("Cargando pipeline en GPU...")
10
- pipe = FluxImg2ImgPipeline.from_pretrained(
11
  model_id,
12
  torch_dtype=torch.bfloat16
13
  ).to("cuda")
@@ -16,45 +16,62 @@ pipe = FluxImg2ImgPipeline.from_pretrained(
16
  print("Inyectando LoRA...")
17
  pipe.load_lora_weights("joyfox/Kontext-Cosplay-Lora", weight_name="kontext_cosplay_lora_20000.safetensors")
18
 
19
- # 3. Funci贸n de generaci贸n corregida
20
  @spaces.GPU
21
- def generate_cosplay(image, prompt, strength, steps):
22
- if image is None:
 
23
  return None
24
 
25
- # Redimensionamos para mantener estabilidad en FLUX
26
- image = image.convert("RGB").resize((1024, 1024))
27
 
28
- # Trigger indispensable del LoRA
29
- full_prompt = f"{prompt}, r2cos"
 
 
 
 
 
30
 
31
- # Eliminamos la semilla fija estricta para permitir variedad por intento,
32
- # pero puedes volver a usar un generador si deseas replicabilidad exacta.
 
 
 
 
 
 
33
 
34
- # Ejecuci贸n con los nuevos par谩metros din谩micos
35
  result = pipe(
36
  prompt=full_prompt,
37
  image=image,
38
- strength=strength, # Control din谩mico desde la UI
39
- num_inference_steps=steps, # Elevado para dar tiempo al LoRA
 
40
  guidance_scale=0.0
41
  ).images[0]
42
 
43
  return result
44
 
45
- # 4. Interfaz de Gradio interactiva
46
  demo = gr.Interface(
47
- fn=generate_cosplay,
48
  inputs=[
49
- gr.Image(type="pil", label="Foto de Referencia"),
50
- gr.Textbox(label="Descripci贸n del personaje (Ej: Naruto, Cyberpunk, Samurai)"),
51
- gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.05, label="Fuerza de Transformaci贸n (Strength)"),
52
- gr.Slider(minimum=10, maximum=30, value=16, step=1, label="Pasos de Inferencia Totales (Steps)")
 
 
 
 
53
  ],
54
  outputs=gr.Image(label="Resultado Cosplay"),
55
- title="Kontext-Cosplay AI Pro",
56
- description="Ajusta los deslizadores si la imagen cambia muy poco."
57
  )
58
 
59
  if __name__ == "__main__":
60
- demo.launch()
 
1
  import torch
2
  import spaces
3
  import gradio as gr
4
+ from diffusers import FluxInpaintPipeline
5
  from PIL import Image
6
 
7
+ # 1. Carga del modelo en modo Inpaint
8
  model_id = "black-forest-labs/FLUX.1-schnell"
9
+ print("Cargando pipeline de Inpainting en GPU...")
10
+ pipe = FluxInpaintPipeline.from_pretrained(
11
  model_id,
12
  torch_dtype=torch.bfloat16
13
  ).to("cuda")
 
16
  print("Inyectando LoRA...")
17
  pipe.load_lora_weights("joyfox/Kontext-Cosplay-Lora", weight_name="kontext_cosplay_lora_20000.safetensors")
18
 
19
+ # 3. Funci贸n de generaci贸n con Inpainting
20
  @spaces.GPU
21
+ def generate_cosplay_inpaint(input_dict, prompt, strength, steps):
22
+ # input_dict contiene la imagen original y los trazos del pincel
23
+ if input_dict is None or input_dict["background"] is None:
24
  return None
25
 
26
+ # 3.1 Procesar imagen original
27
+ image = input_dict["background"].convert("RGB").resize((1024, 1024))
28
 
29
+ # 3.2 Construir la m谩scara desde los trazos del usuario
30
+ layers = input_dict.get("layers", [])
31
+ if not layers:
32
+ raise gr.Error("隆Debes usar el pincel para pintar sobre la ropa!")
33
+
34
+ # Creamos una m谩scara negra vac铆a del mismo tama帽o
35
+ mask = Image.new("L", image.size, 0)
36
 
37
+ # Sumamos todos los trazos (capas) que el usuario dibuj贸
38
+ for layer in layers:
39
+ layer_resized = layer.convert("RGBA").resize((1024, 1024))
40
+ alpha_channel = layer_resized.split()[3] # Extraemos por d贸nde pas贸 el pincel
41
+ mask.paste(alpha_channel, (0, 0), alpha_channel)
42
+
43
+ # 3.3 Configurar el prompt
44
+ full_prompt = f"{prompt}, r2cos"
45
 
46
+ # 3.4 Ejecutar el modelo Inpaint
47
  result = pipe(
48
  prompt=full_prompt,
49
  image=image,
50
+ mask_image=mask, # Aqu铆 le pasamos la m谩scara a la IA
51
+ strength=strength,
52
+ num_inference_steps=steps,
53
  guidance_scale=0.0
54
  ).images[0]
55
 
56
  return result
57
 
58
+ # 4. Interfaz interactiva con editor de imagen
59
  demo = gr.Interface(
60
+ fn=generate_cosplay_inpaint,
61
  inputs=[
62
+ gr.ImageEditor(
63
+ type="pil",
64
+ label="1. Sube tu foto y PINTA LA ROPA (deja la cara intacta)",
65
+ brush=gr.Brush(colors=["#FF0000"], color_mode="fixed") # Pincel rojo para ver bien
66
+ ),
67
+ gr.Textbox(label="2. Descripci贸n (Ej: detailed samurai armor, cyberpunk)"),
68
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.85, step=0.05, label="Fuerza (Strength)"),
69
+ gr.Slider(minimum=10, maximum=30, value=20, step=1, label="Pasos (Steps)")
70
  ],
71
  outputs=gr.Image(label="Resultado Cosplay"),
72
+ title="Kontext-Cosplay AI Inpaint",
73
+ description="Pinta de rojo la ropa y el fondo. La IA transformar谩 solo la zona pintada, respetando la cara original."
74
  )
75
 
76
  if __name__ == "__main__":
77
+ demo.launch()