freshcodestech commited on
Commit
f2d2936
·
verified ·
1 Parent(s): 11b5374

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -47
app.py CHANGED
@@ -1,76 +1,89 @@
1
- # app.py
2
  import torch, gradio as gr
3
  from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
4
 
5
- # Models
6
- BASE = "stabilityai/stable-diffusion-xl-base-1.0"
7
- LORA_REPO = "freshcodestech/LingoSpace"
8
- LORA_FILE = "LingoSpace-10.safetensors"
9
- LORA_STRENGTH = 0.8 # 0.6–1.0
 
10
 
11
- PROMPTS = [
12
- "A cartoon raccoon in a space suit with some rice food, highly detailed, vibrant, futuristic art style",
13
- "A cartoon bear in a space suit with some meat food, cinematic lighting, sci-fi background",
14
- "A cartoon giraffe in a space suit with some pizza food, whimsical, colorful, space kitchen scene",
15
- ]
16
-
17
- # Device / dtype
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
19
- dtype = torch.float16 if device == "cuda" else torch.float32
20
 
21
- # Load SDXL (disable watermarker to avoid extra deps on Spaces)
22
  pipe = StableDiffusionXLPipeline.from_pretrained(
23
- BASE,
24
  torch_dtype=dtype,
25
  use_safetensors=True,
26
  add_watermarker=False,
27
- **({"variant": "fp16"} if device == "cuda" else {})
28
  )
29
  pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
30
  pipe = pipe.to(device)
31
 
32
- # Load LoRA from Hub
33
- pipe.load_lora_weights(LORA_REPO, weight_name=LORA_FILE)
 
 
 
 
 
 
34
 
35
- # If your diffusers supports adapter weights:
36
  if hasattr(pipe, "set_adapters"):
37
- # (adapter name is "default" when not specified in load_lora_weights)
38
- pipe.set_adapters("default", weight=LORA_STRENGTH)
39
 
40
- # Memory helpers
41
  if device == "cuda":
42
  if hasattr(pipe, "enable_xformers_memory_efficient_attention"):
43
  pipe.enable_xformers_memory_efficient_attention()
44
  pipe.enable_attention_slicing()
45
  pipe.enable_vae_tiling()
46
 
47
- # Gen settings (smaller & fewer steps on CPU so it doesn’t crawl)
48
- STEPS = 30 if device == "cuda" else 15
49
- CFG = 7.5
50
- H = 1024 if device == "cuda" else 768
51
- W = 1024 if device == "cuda" else 768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- def generate_images():
54
- images = []
55
- for i, p in enumerate(PROMPTS):
56
- out = pipe(
57
- p,
58
- num_inference_steps=STEPS,
59
- guidance_scale=CFG,
60
- height=H,
61
- width=W,
62
- # Works even if set_adapters isn't available (older diffusers):
63
- cross_attention_kwargs={"scale": LORA_STRENGTH},
64
- )
65
- images.append(out.images[0])
66
- return images
67
 
68
  demo = gr.Interface(
69
- fn=generate_images,
70
- inputs=None,
71
- outputs=[gr.Image(label=f"Image {i+1}") for i in range(len(PROMPTS))],
72
- title="SDXL + LoRA: LingoSpace",
73
- description=f"Device: {device.upper()} | Base: SDXL | LoRA: {LORA_REPO}/{LORA_FILE}",
 
 
 
 
 
 
 
74
  )
75
 
76
  if __name__ == "__main__":
 
1
+ # app.py — SDXL + LoRA from Hugging Face (PEFT backend)
2
  import torch, gradio as gr
3
  from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
4
 
5
+ # --- Config ---
6
+ BASE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"
7
+ LORA_REPO = "freshcodestech/LingoSpace" # your HF LoRA repo
8
+ LORA_FILE = "LingoSpace-10.safetensors" # exact filename in that repo
9
+ ADAPTER = "lingospace" # local nickname; can be any safe string
10
+ LORA_W = 0.8 # LoRA strength (0.6–1.0 is typical)
11
 
12
+ # Device / dtype (GPU preferred)
 
 
 
 
 
 
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
+ dtype = torch.float16 if device == "cuda" else torch.float32
15
 
16
+ # --- Load SDXL base (disable watermarker to avoid extra deps on Spaces) ---
17
  pipe = StableDiffusionXLPipeline.from_pretrained(
18
+ BASE_MODEL,
19
  torch_dtype=dtype,
20
  use_safetensors=True,
21
  add_watermarker=False,
22
+ **({"variant": "fp16"} if device == "cuda" else {}) # fp16 only on GPU
23
  )
24
  pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
25
  pipe = pipe.to(device)
26
 
27
+ # --- Load LoRA from the Hub via PEFT backend ---
28
+ # NOTE: This requires `peft` to be installed (see requirements.txt below).
29
+ pipe.load_lora_weights(
30
+ LORA_REPO,
31
+ weight_name=LORA_FILE,
32
+ adapter_name=ADAPTER,
33
+ use_peft_backend=True
34
+ )
35
 
36
+ # Preferred scaling API (if available)
37
  if hasattr(pipe, "set_adapters"):
38
+ pipe.set_adapters(ADAPTER, weight=LORA_W)
 
39
 
40
+ # Memory helpers (helpful on T4 small)
41
  if device == "cuda":
42
  if hasattr(pipe, "enable_xformers_memory_efficient_attention"):
43
  pipe.enable_xformers_memory_efficient_attention()
44
  pipe.enable_attention_slicing()
45
  pipe.enable_vae_tiling()
46
 
47
+ # --- Inference ---
48
+ def infer(prompt, steps, cfg, h, w, lora_strength):
49
+ # Fallback strength control for older diffusers if set_adapters doesn’t exist:
50
+ kwargs = {}
51
+ if not hasattr(pipe, "set_adapters"):
52
+ kwargs["cross_attention_kwargs"] = {"scale": float(lora_strength)}
53
+ else:
54
+ # If adapter API exists, update weight dynamically
55
+ pipe.set_adapters(ADAPTER, weight=float(lora_strength))
56
+
57
+ out = pipe(
58
+ prompt,
59
+ num_inference_steps=int(steps),
60
+ guidance_scale=float(cfg),
61
+ height=int(h),
62
+ width=int(w),
63
+ **kwargs
64
+ )
65
+ return out.images[0]
66
+
67
+ DEFAULT_PROMPT = "lingospace, cartoon, 2d illustration, flat colors, clean lineart, a raccoon in a compact utility space suit, holding a steaming bowl of rice, stars and soft nebula, cozy composition"
68
 
69
+ # Use smaller defaults on CPU for speed
70
+ DEF_STEPS = 30 if device == "cuda" else 15
71
+ DEF_H = 1024 if device == "cuda" else 768
72
+ DEF_W = 1024 if device == "cuda" else 768
 
 
 
 
 
 
 
 
 
 
73
 
74
  demo = gr.Interface(
75
+ fn=infer,
76
+ inputs=[
77
+ gr.Textbox(label="Prompt", value=DEFAULT_PROMPT, lines=3),
78
+ gr.Slider(10, 50, value=DEF_STEPS, step=1, label="Steps"),
79
+ gr.Slider(3.0, 9.0, value=7.5, step=0.5, label="CFG"),
80
+ gr.Slider(512, 1216, value=DEF_H, step=64, label="Height"),
81
+ gr.Slider(512, 1216, value=DEF_W, step=64, label="Width"),
82
+ gr.Slider(0.3, 1.2, value=LORA_W, step=0.05, label="LoRA Strength"),
83
+ ],
84
+ outputs=gr.Image(label="Output"),
85
+ title="SDXL + LoRA (freshcodestech/LingoSpace)",
86
+ description=f"Device: {device.upper()} | Base: {BASE_MODEL} | LoRA: {LORA_REPO}/{LORA_FILE}"
87
  )
88
 
89
  if __name__ == "__main__":