cobramv12 commited on
Commit
219831b
·
verified ·
1 Parent(s): fd5e232

Fix: Switch to Native Gradio SDK for ZeroGPU stability

Browse files
Files changed (1) hide show
  1. app.py +98 -62
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import sys
2
  import os
 
 
3
 
4
  # --- PARCHES CRÍTICOS ---
5
  try:
@@ -9,105 +11,139 @@ try:
9
  if isinstance(schema, bool): return "Any"
10
  return old_json_schema_to_python_type(schema, defs)
11
  client_utils._json_schema_to_python_type = patched_json_schema_to_python_type
12
- print("Gradio Patch Applied")
13
  except: pass
14
 
15
  import spaces
16
  import gradio as gr
17
- import torch
18
  from PIL import Image
19
  import tempfile
20
 
21
- # MODELOS PREDEFINIDOS
22
- MODELS = {
23
  "CyberRealistic Pony (Recomendado)": "cyberdelia/CyberRealisticPony",
24
  "RealVisXL V4.0": "SG161222/RealVisXL_V4.0",
25
- "Juggernaut XL V9": "RunDiffusion/Juggernaut-XL-v9",
26
- "SDXL Base 1.0": "stabilityai/stable-diffusion-xl-base-1.0"
 
 
 
27
  }
28
 
29
- # LORAS PREDEFINIDOS
30
- LORAS = {
31
  "Ninguno": "",
32
- "Detalle Extremo (XL)": "h94/IP-Adapter",
33
- "Realismo Fotográfico": "latent-consistency/lcm-lora-sdxl",
34
- "Estilo Pixel Art": "nerijs/pixel-art-xl"
35
  }
36
 
 
37
  def load_t2i(model_id, is_img2img=False):
38
  from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
39
  cls = StableDiffusionXLImg2ImgPipeline if is_img2img else StableDiffusionXLPipeline
40
- pipe = cls.from_pretrained(
41
- model_id, torch_dtype=torch.float16, use_safetensors=True, variant="fp16",
42
- low_cpu_mem_usage=True
43
- )
44
  return pipe
45
 
 
 
 
 
 
 
46
  @spaces.GPU(duration=100)
47
- def generate_t2i(prompt, neg, model_name, custom_model, lora_name, custom_lora, lora_scale, steps, cfg, w, h, init_img):
48
- model_id = custom_model if custom_model else MODELS.get(model_name)
49
- lora_id = custom_lora if custom_lora else LORAS.get(lora_name)
50
-
51
  is_img2img = init_img is not None
52
  pipe = load_t2i(model_id, is_img2img).to("cuda")
53
 
54
- if lora_id:
55
  try:
56
- pipe.load_lora_weights(lora_id)
57
  pipe.fuse_lora(lora_scale=lora_scale)
58
- except Exception as e:
59
- print(f"LoRA Error: {e}")
60
 
61
- kwargs = {
62
- "prompt": prompt,
63
- "negative_prompt": neg,
64
- "num_inference_steps": int(steps),
65
- "guidance_scale": cfg,
66
- "width": int(w),
67
- "height": int(h)
68
- }
69
-
70
  if is_img2img:
71
  kwargs["image"] = Image.fromarray(init_img).convert("RGB").resize((int(w), int(h)))
72
  kwargs.pop("width"); kwargs.pop("height")
73
  kwargs["strength"] = 0.6
74
 
75
- return pipe(**kwargs).images[0]
 
 
 
 
 
76
 
77
- # UI DESIGN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple")) as demo:
79
- gr.HTML("<h1 style='text-align:center;'>🎨 Studio Privado v2.2 PRO</h1>")
80
 
81
  with gr.Tabs():
82
- with gr.Tab("🖼 Generador de Imágenes"):
83
  with gr.Row():
84
- with gr.Column(scale=1):
85
- prompt = gr.Textbox(label="Prompt (Descripción)", placeholder="Una mujer cyberpunk en neon city...", lines=3)
86
- neg = gr.Textbox(label="Prompt Negativo", value="blurry, ugly, low quality, deformed")
87
-
 
 
88
  with gr.Row():
89
- model_sel = gr.Dropdown(choices=list(MODELS.keys()), value="CyberRealistic Pony (Recomendado)", label="Seleccionar Modelo")
90
- custom_model = gr.Textbox(label="O usar ID de HF (opcional)", placeholder="usuario/modelo")
91
-
 
 
 
 
 
 
 
 
 
 
 
 
92
  with gr.Row():
93
- lora_sel = gr.Dropdown(choices=list(LORAS.keys()), value="Ninguno", label="Seleccionar Extensión (LoRA)")
94
- custom_lora = gr.Textbox(label="O ID de LoRA personalizado", placeholder="usuario/lora")
95
-
96
- lora_scale = gr.Slider(0, 1.5, 0.8, label="Peso de la Extensión")
97
-
98
- with gr.Accordion("Configuración Avanzada", open=False):
99
- steps = gr.Slider(10, 50, 30, step=1, label="Pasos")
100
- cfg = gr.Slider(1, 15, 7, label="Guidance Scale")
101
- with gr.Row():
102
- w = gr.Slider(512, 1024, 1024, step=64, label="Ancho")
103
- h = gr.Slider(512, 1024, 1024, step=64, label="Alto")
104
-
105
- init_img = gr.Image(label="Imagen de Referencia (Img2Img)", type="numpy")
106
- btn = gr.Button("GENERAR IMAGEN", variant="primary")
107
-
108
- with gr.Column(scale=1):
109
- output = gr.Image(label="Resultado")
110
-
111
- btn.click(generate_t2i, [prompt, neg, model_sel, custom_model, lora_sel, custom_lora, lora_scale, steps, cfg, w, h, init_img], output)
112
 
113
  demo.queue().launch(show_api=False, server_name="0.0.0.0", server_port=7860)
 
1
  import sys
2
  import os
3
+ import gc
4
+ import torch
5
 
6
  # --- PARCHES CRÍTICOS ---
7
  try:
 
11
  if isinstance(schema, bool): return "Any"
12
  return old_json_schema_to_python_type(schema, defs)
13
  client_utils._json_schema_to_python_type = patched_json_schema_to_python_type
 
14
  except: pass
15
 
16
  import spaces
17
  import gradio as gr
 
18
  from PIL import Image
19
  import tempfile
20
 
21
+ # CONFIG
22
+ SDXL_MODELS = {
23
  "CyberRealistic Pony (Recomendado)": "cyberdelia/CyberRealisticPony",
24
  "RealVisXL V4.0": "SG161222/RealVisXL_V4.0",
25
+ "Juggernaut XL V9": "RunDiffusion/Juggernaut-XL-v9"
26
+ }
27
+
28
+ LTX_MODELS = {
29
+ "LTX-Video (Standard)": "Lightricks/LTX-Video"
30
  }
31
 
32
+ LTX_LORAS = {
 
33
  "Ninguno": "",
34
+ "Real Nudity Alpha (NSFW)": "Lora-Daddy/Ltx2.3-real-nudity-early-alpha-30k-steps",
35
+ "LTX Realism Boost": "strangerzonehf/LTX-Video-LoRA"
 
36
  }
37
 
38
+ # --- FUNCIONES DE CARGA ---
39
  def load_t2i(model_id, is_img2img=False):
40
  from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
41
  cls = StableDiffusionXLImg2ImgPipeline if is_img2img else StableDiffusionXLPipeline
42
+ pipe = cls.from_pretrained(model_id, torch_dtype=torch.float16, use_safetensors=True, variant="fp16")
 
 
 
43
  return pipe
44
 
45
+ def load_video(model_id):
46
+ from diffusers import LTXPipeline
47
+ pipe = LTXPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
48
+ return pipe
49
+
50
+ # --- GENERACIÓN ---
51
  @spaces.GPU(duration=100)
52
+ def generate_t2i(prompt, neg, model_name, lora_id_custom, lora_scale, steps, cfg, w, h, init_img):
53
+ model_id = SDXL_MODELS.get(model_name)
 
 
54
  is_img2img = init_img is not None
55
  pipe = load_t2i(model_id, is_img2img).to("cuda")
56
 
57
+ if lora_id_custom:
58
  try:
59
+ pipe.load_lora_weights(lora_id_custom)
60
  pipe.fuse_lora(lora_scale=lora_scale)
61
+ except: pass
 
62
 
63
+ kwargs = {"prompt": prompt, "negative_prompt": neg, "num_inference_steps": int(steps), "guidance_scale": cfg, "width": int(w), "height": int(h)}
 
 
 
 
 
 
 
 
64
  if is_img2img:
65
  kwargs["image"] = Image.fromarray(init_img).convert("RGB").resize((int(w), int(h)))
66
  kwargs.pop("width"); kwargs.pop("height")
67
  kwargs["strength"] = 0.6
68
 
69
+ res = pipe(**kwargs).images[0]
70
+ # Limpieza
71
+ del pipe
72
+ gc.collect()
73
+ torch.cuda.empty_cache()
74
+ return res
75
 
76
+ @spaces.GPU(duration=200)
77
+ def generate_video(prompt, model_name, lora_name, lora_custom, lora_scale, init_image, steps, cfg):
78
+ from diffusers.utils import export_to_video
79
+ model_id = LTX_MODELS.get(model_name)
80
+ lora_id = lora_custom if lora_custom else LTX_LORAS.get(lora_name)
81
+
82
+ pipe = load_video(model_id).to("cuda")
83
+
84
+ if lora_id:
85
+ try:
86
+ pipe.load_lora_weights(lora_id)
87
+ except: pass
88
+
89
+ kwargs = {
90
+ "prompt": prompt,
91
+ "negative_prompt": "low quality, blurry, static",
92
+ "num_frames": 49,
93
+ "num_inference_steps": int(steps),
94
+ "guidance_scale": cfg
95
+ }
96
+
97
+ if lora_id:
98
+ kwargs["cross_attention_kwargs"] = {"scale": lora_scale}
99
+
100
+ if init_image is not None:
101
+ kwargs["image"] = Image.fromarray(init_image).convert("RGB").resize((768, 512))
102
+
103
+ output = pipe(**kwargs)
104
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
105
+ export_to_video(output.frames[0], tmp.name, fps=24)
106
+
107
+ # Limpieza profunda
108
+ del pipe
109
+ gc.collect()
110
+ torch.cuda.empty_cache()
111
+ return tmp.name
112
+
113
+ # --- INTERFAZ ---
114
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple")) as demo:
115
+ gr.HTML("<h1 style='text-align:center;'>🚀 Studio Privado v2.3 Pro</h1>")
116
 
117
  with gr.Tabs():
118
+ with gr.Tab("🖼 Imagen / T2I"):
119
  with gr.Row():
120
+ with gr.Column():
121
+ t2i_p = gr.Textbox(label="Prompt", lines=3)
122
+ t2i_n = gr.Textbox(label="Negativo", value="blurry, ugly")
123
+ t2i_m = gr.Dropdown(choices=list(SDXL_MODELS.keys()), value="CyberRealistic Pony (Recomendado)", label="Modelo")
124
+ t2i_lora = gr.Textbox(label="LoRA ID Personalizado (Opcional)")
125
+ t2i_ls = gr.Slider(0, 1.5, 0.8, label="Peso LoRA")
126
  with gr.Row():
127
+ t2i_w = gr.Slider(512, 1024, 1024, step=64, label="Ancho")
128
+ t2i_h = gr.Slider(512, 1024, 1024, step=64, label="Alto")
129
+ t2i_btn = gr.Button("GENERAR IMAGEN", variant="primary")
130
+ t2i_out = gr.Image(label="Resultado")
131
+ t2i_btn.click(generate_t2i, [t2i_p, t2i_n, t2i_m, t2i_lora, t2i_ls, gr.Number(value=30, visible=False), gr.Number(value=7, visible=False), t2i_w, t2i_h, gr.State(None)], t2i_out)
132
+
133
+ with gr.Tab("🎬 Video / M-Sequence"):
134
+ with gr.Row():
135
+ with gr.Column():
136
+ v_p = gr.Textbox(label="Video Prompt", lines=3)
137
+ v_m = gr.Dropdown(choices=list(LTX_MODELS.keys()), value="LTX-Video (Standard)", label="Modelo de Video")
138
+ v_lora = gr.Dropdown(choices=list(LTX_LORAS.keys()), value="Real Nudity Alpha (NSFW)", label="Seleccionar LoRA Video")
139
+ v_lora_c = gr.Textbox(label="O ID LoRA Video personalizado")
140
+ v_ls = gr.Slider(0, 1.5, 1.0, label="Peso LoRA Video")
141
+ v_img = gr.Image(label="Imagen de Inicio (Opcional)", type="numpy")
142
  with gr.Row():
143
+ v_steps = gr.Slider(10, 50, 30, step=1, label="Pasos")
144
+ v_cfg = gr.Slider(1, 10, 3.5, label="Guidance")
145
+ v_btn = gr.Button("GENERAR VIDEO", variant="primary")
146
+ v_out = gr.Video(label="Resultado Video")
147
+ v_btn.click(generate_video, [v_p, v_m, v_lora, v_lora_c, v_ls, v_img, v_steps, v_cfg], v_out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  demo.queue().launch(show_api=False, server_name="0.0.0.0", server_port=7860)