spdraptor commited on
Commit
0a05d1f
·
verified ·
1 Parent(s): 96423ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -140
app.py CHANGED
@@ -1,146 +1,101 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
- import torch
6
-
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
-
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
-
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
22
-
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
 
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
 
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
 
117
- with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
- )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
- )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
138
- )
139
-
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
144
- )
145
 
146
  demo.queue().launch()
 
1
  import gradio as gr
2
+ from PIL import Image, ImageColor
3
+ from back_task import *
4
+
5
+ # The function that does the hard work
6
+ def generate(radio,color,prompt, guidance_loss_scale):
7
+ print(color)
8
+ if radio == "color guidance":
9
+ target_color = ImageColor.getcolor(color, "RGB") # Target color as RGB
10
+ target_color = [a / 255 for a in target_color] # Rescale from (0, 255) to (0, 1)
11
+
12
+ elif radio == "text guidance":
13
+ # We embed a prompt with CLIP as our target
14
+ text = open_clip.tokenize([prompt]).to(device)
15
+ with torch.no_grad(), torch.cuda.amp.autocast():
16
+ text_features = clip_model.encode_text(text)
17
+
18
+ x = torch.randn(1, 3, 256, 256).to(device)
19
+ for i, t in tqdm(enumerate(scheduler.timesteps)):
20
+ model_input = scheduler.scale_model_input(x, t)
21
+ with torch.no_grad():
22
+ noise_pred = image_pipe.unet(model_input, t)["sample"]
23
+
24
+ if radio == "color guidance":
25
+ x = x.detach().requires_grad_()
26
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
27
+ loss = color_loss(x0, target_color) * guidance_loss_scale
28
+ cond_grad = -torch.autograd.grad(loss, x)[0]
29
+ x = x.detach() + cond_grad
30
+ elif radio == "text guidance":
31
+ cond_grad = 0
32
+
33
+ for cut in range(n_cuts):
34
+
35
+ # Set requires grad on x
36
+ x = x.detach().requires_grad_()
37
+
38
+ # Get the predicted x0:
39
+ x0 = scheduler.step(noise_pred, t, x).pred_original_sample
40
+
41
+ # Calculate loss
42
+ loss = clip_loss(x0, text_features) * guidance_loss_scale
43
+
44
+ # Get gradient (scale by n_cuts since we want the average)
45
+ cond_grad -= torch.autograd.grad(loss, x)[0] / n_cuts
46
+
47
+
48
+ # Modify x based on this gradient
49
+ alpha_bar = scheduler.alphas_cumprod[i]
50
+ x = x.detach() + cond_grad * alpha_bar.sqrt() # Note the additional scaling factor here!
51
+
 
 
 
 
 
 
 
52
 
53
+ x = scheduler.step(noise_pred, t, x).prev_sample
54
+ grid = torchvision.utils.make_grid(x, nrow=4)
55
+ im = grid.permute(1, 2, 0).cpu().clip(-1, 1) * 0.5 + 0.5
56
+ im = Image.fromarray(np.array(im * 255).astype(np.uint8))
57
+ # im.save("test.jpeg")
58
+ return im
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+
61
+ title="""<h1 align="center">Make me a WikiArt</h1>
62
+ <p align="center">Try-out of exercise from HF Learn [Difussion Course] </p>
63
+ <p><center>
64
+ <a href="https://huggingface.co/learn/diffusion-course" target="_blank">[HF-Learn]</a>
65
+ </center></p>"""
66
+
67
+ with gr.Blocks() as demo:
68
+ gr.HTML(title)
69
+ with gr.Row():
70
+ with gr.Column():
71
+ # Create a radio button with options "no guidance", "color guidance", and "text guidance"
72
+ radio = gr.Radio(["no guidance", "color guidance", "text guidance"], label="Choose",value="no guidance")
73
+
74
+ # Create a textbox that only shows when 'text guidance' is selected
75
+ text = gr.Textbox(label="This text only shows when 'text guidance' is selected.", visible=False)
76
+
77
+ # Create a color picker (not a tuple)
78
+ color = gr.ColorPicker(label="color", value="#000000", visible=False)
79
+
80
+ # Create a slider that shows when any option is selected
81
+ slider = gr.Slider(label="guidance_scale", minimum=0, maximum=30, value=3, visible=False)
82
+
83
+ def update_visibility(radio):
84
+ value = radio # Get the selected value from the radio button
85
+ if value == "color guidance":
86
+ return [gr.Textbox(visible=False),gr.ColorPicker(visible=True),gr.Slider(visible=True)] #make it visible
87
+ elif value == "text guidance":
88
+ return [gr.Textbox(visible=True),gr.ColorPicker(visible=False),gr.Slider(visible=True)]
89
+ else:
90
+ return [gr.Textbox(visible=False),gr.ColorPicker(visible=False),gr.Slider(visible=False)]
91
+
92
+ radio.change(update_visibility, radio,[text,color,slider])
93
+ with gr.Column():
94
+ outputs = gr.Image(label="result")
 
95
 
96
+ with gr.Row():
97
+ gen_bttn=gr.Button(value="generate")
98
+ gen_bttn.click(generate, inputs=[radio,color,text,slider], outputs=outputs)
99
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  demo.queue().launch()