SpyC0der77 commited on
Commit
3fe3a3a
·
verified ·
1 Parent(s): d062a35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -156
app.py CHANGED
@@ -1,157 +1,72 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
- import peft
5
-
6
- # import spaces #[uncomment to use ZeroGPU]
7
- from diffusers import DiffusionPipeline
8
  import torch
9
-
10
- device = "cuda" if torch.cuda.is_available() else "cpu"
11
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
12
-
13
- if torch.cuda.is_available():
14
- torch_dtype = torch.float16
15
- else:
16
- torch_dtype = torch.float32
17
-
18
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
19
- pipe.load_lora_weights("fofr/sdxl-emoji", weight_name="lora.safetensors", adapter_name="toy")
20
-
21
- pipe = pipe.to(device)
22
-
23
- MAX_SEED = np.iinfo(np.int32).max
24
- MAX_IMAGE_SIZE = 1024
25
-
26
-
27
- # @spaces.GPU #[uncomment to use ZeroGPU]
28
- def infer(
29
- prompt,
30
- negative_prompt,
31
- seed,
32
- randomize_seed,
33
- width,
34
- height,
35
- guidance_scale,
36
- num_inference_steps,
37
- progress=gr.Progress(track_tqdm=True),
38
- ):
39
- if randomize_seed:
40
- seed = random.randint(0, MAX_SEED)
41
-
42
- generator = torch.Generator().manual_seed(seed)
43
-
44
- image = pipe(
45
- prompt=prompt,
46
- negative_prompt=negative_prompt,
47
- guidance_scale=guidance_scale,
48
- num_inference_steps=num_inference_steps,
49
- width=width,
50
- height=height,
51
- generator=generator,
52
- ).images[0]
53
-
54
- return image, seed
55
-
56
-
57
- examples = [
58
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
59
- "An astronaut riding a green horse",
60
- "A delicious ceviche cheesecake slice",
61
- ]
62
-
63
- css = """
64
- #col-container {
65
- margin: 0 auto;
66
- max-width: 640px;
67
- }
68
- """
69
-
70
- with gr.Blocks(css=css) as demo:
71
- with gr.Column(elem_id="col-container"):
72
- gr.Markdown(" # Text-to-Image Gradio Template")
73
-
74
- with gr.Row():
75
- prompt = gr.Text(
76
- label="Prompt",
77
- show_label=False,
78
- max_lines=1,
79
- placeholder="Enter your prompt",
80
- container=False,
81
- )
82
-
83
- run_button = gr.Button("Run", scale=0, variant="primary")
84
-
85
- result = gr.Image(label="Result", show_label=False)
86
-
87
- with gr.Accordion("Advanced Settings", open=False):
88
- negative_prompt = gr.Text(
89
- label="Negative prompt",
90
- max_lines=1,
91
- placeholder="Enter a negative prompt",
92
- visible=False,
93
- )
94
-
95
- seed = gr.Slider(
96
- label="Seed",
97
- minimum=0,
98
- maximum=MAX_SEED,
99
- step=1,
100
- value=0,
101
- )
102
-
103
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
104
-
105
- with gr.Row():
106
- width = gr.Slider(
107
- label="Width",
108
- minimum=256,
109
- maximum=MAX_IMAGE_SIZE,
110
- step=32,
111
- value=1024, # Replace with defaults that work for your model
112
- )
113
-
114
- height = gr.Slider(
115
- label="Height",
116
- minimum=256,
117
- maximum=MAX_IMAGE_SIZE,
118
- step=32,
119
- value=1024, # Replace with defaults that work for your model
120
- )
121
-
122
- with gr.Row():
123
- guidance_scale = gr.Slider(
124
- label="Guidance scale",
125
- minimum=0.0,
126
- maximum=10.0,
127
- step=0.1,
128
- value=0.0, # Replace with defaults that work for your model
129
- )
130
-
131
- num_inference_steps = gr.Slider(
132
- label="Number of inference steps",
133
- minimum=1,
134
- maximum=50,
135
- step=1,
136
- value=2, # Replace with defaults that work for your model
137
- )
138
-
139
- gr.Examples(examples=examples, inputs=[prompt])
140
- gr.on(
141
- triggers=[run_button.click, prompt.submit],
142
- fn=infer,
143
- inputs=[
144
- prompt,
145
- negative_prompt,
146
- seed,
147
- randomize_seed,
148
- width,
149
- height,
150
- guidance_scale,
151
- num_inference_steps,
152
- ],
153
- outputs=[result, seed],
154
- )
155
-
156
- if __name__ == "__main__":
157
- demo.launch()
 
 
 
 
 
 
 
 
1
  import torch
2
+ import gradio as gr
3
+ from diffusers import StableDiffusionXLPipeline
4
+
5
+ # --- Settings and paths ---
6
+ # Base SDXL model – change this to the base model you want to use.
7
+ BASE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"
8
+ # Path to your LoRA weights (assumed to be in a format that Diffusers can use)
9
+ LORA_PATH = "fofr/sdxl-emoji"
10
+
11
+ # --- Load the base pipeline ---
12
+ pipe = StableDiffusionXLPipeline.from_pretrained(
13
+ BASE_MODEL,
14
+ torch_dtype=torch.float16,
15
+ variant="fp16", # Use FP16 variant if available for speed
16
+ safety_checker=None, # (Optional) disable safety checker to speed things up
17
+ )
18
+ pipe.to("cuda")
19
+
20
+ # --- Enable fast attention if available ---
21
+ try:
22
+ pipe.enable_xformers_memory_efficient_attention()
23
+ except Exception as e:
24
+ print("xFormers not enabled:", e)
25
+
26
+ # --- Apply the LoRA weights ---
27
+ # Diffusers v0.18+ supports applying LoRA weights to parts of the pipeline.
28
+ # Here we assume the LoRA affects the UNet (and, if needed, the text encoder).
29
+ try:
30
+ # For the UNet:
31
+ pipe.unet.load_attn_procs(LORA_PATH)
32
+ # If you also have LoRA weights for the text encoder, you might do:
33
+ # pipe.text_encoder.load_attn_procs(LORA_PATH)
34
+ except Exception as e:
35
+ print("Error applying LoRA weights:", e)
36
+
37
+ # --- Define the image generation function ---
38
+ def generate_image(prompt: str, steps: int = 30, guidance: float = 7.5):
39
+ """
40
+ Generate an image from a text prompt.
41
+
42
+ Args:
43
+ prompt (str): The text prompt.
44
+ steps (int): Number of inference steps.
45
+ guidance (float): Guidance scale (higher values encourage the image to follow the prompt).
46
+
47
+ Returns:
48
+ A generated PIL image.
49
+ """
50
+ # Use autocast for faster FP16 inference on CUDA
51
+ with torch.cuda.amp.autocast():
52
+ result = pipe(prompt, num_inference_steps=steps, guidance_scale=guidance)
53
+ return result.images[0]
54
+
55
+ # --- Build the Gradio interface ---
56
+ demo = gr.Interface(
57
+ fn=generate_image,
58
+ inputs=[
59
+ gr.Textbox(lines=2, placeholder="Enter your prompt here...", label="Prompt"),
60
+ gr.Slider(minimum=10, maximum=100, step=5, value=30, label="Inference Steps"),
61
+ gr.Slider(minimum=1.0, maximum=15.0, step=0.5, value=7.5, label="Guidance Scale")
62
+ ],
63
+ outputs=gr.Image(type="pil", label="Generated Image"),
64
+ title="Super Fast SDXL-Emoji Generator",
65
+ description=(
66
+ "This demo uses a Stable Diffusion XL model enhanced with a custom LoRA "
67
+ "to generate images quickly. Adjust the prompt and settings below, then hit 'Submit'!"
68
+ ),
69
+ )
70
+
71
+ # --- Launch the demo ---
72
+ demo.launch()