gaur3009 commited on
Commit
98d80f4
·
verified ·
1 Parent(s): 603e7b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -194
app.py CHANGED
@@ -1,211 +1,132 @@
1
  import gradio as gr
 
 
 
2
  import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
- import torch
6
  from PIL import Image
7
- import requests
8
- from io import BytesIO
9
- import time
10
 
11
- device = "cuda" if torch.cuda.is_available() else "cpu"
12
-
13
- # Load the design generation model
14
- repo = "artificialguybr/TshirtDesignRedmond-V2"
15
-
16
- def generate_image(prompt):
17
- api_url = f"https://api-inference.huggingface.co/models/{repo}"
18
- payload = {
19
- "inputs": prompt,
20
- "parameters": {
21
- "negative_prompt": "(worst quality, low quality, etc.)",
22
- "num_inference_steps": 30,
23
- "scheduler": "DPMSolverMultistepScheduler"
24
- },
25
- }
26
-
27
- while True:
28
- response = requests.post(api_url, json=payload)
29
- if response.status_code == 200:
30
- return Image.open(BytesIO(response.content))
31
- else:
32
- raise Exception(f"API Error: {response.status_code}")
33
-
34
- # Load the clothing customization model
35
- if torch.cuda.is_available():
36
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
37
- pipe.enable_xformers_memory_efficient_attention()
38
- pipe = pipe.to(device)
39
- else:
40
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
41
- pipe = pipe.to(device)
42
 
43
- MAX_SEED = np.iinfo(np.int32).max
44
- MAX_IMAGE_SIZE = 1024
45
 
46
- def customize_clothing(prompt_part1, color, dress_type, design_prompt, prompt_part5, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
47
- # Generate the design first
48
- design_image = generate_image(design_prompt)
 
49
 
50
- # Now customize the clothing with the generated design
51
- prompt = f"{prompt_part1} {color} colored plain {dress_type} with custom design, {prompt_part5}"
52
 
53
- if randomize_seed:
54
- seed = random.randint(0, MAX_SEED)
55
-
56
- generator = torch.Generator().manual_seed(seed)
57
 
58
- image = pipe(
59
- prompt=prompt,
60
- negative_prompt=negative_prompt,
61
- guidance_scale=guidance_scale,
62
- num_inference_steps=num_inference_steps,
63
- width=width,
64
- height=height,
65
- generator=generator
66
- ).images[0]
67
 
68
- return image
 
 
 
69
 
70
- examples = [
71
- "red, t-shirt, cute panda",
72
- "blue, hoodie, skull",
73
- ]
74
 
75
- css = """
76
- #col-container {
77
- margin: 0 auto;
78
- max-width: 520px;
79
- }
80
- """
81
 
82
- if torch.cuda.is_available():
83
- power_device = "GPU"
84
- else:
85
- power_device = "CPU"
86
 
87
- with gr.Blocks(css=css) as demo:
88
-
89
- with gr.Column(elem_id="col-container"):
90
- gr.Markdown(f"""
91
- # Text-to-Image Gradio Template
92
- Currently running on {power_device}.
93
- """)
94
-
95
- with gr.Row():
96
-
97
- prompt_part1 = gr.Textbox(
98
- value="a single",
99
- label="Prompt Part 1",
100
- show_label=False,
101
- interactive=False,
102
- container=False,
103
- elem_id="prompt_part1",
104
- visible=False,
105
- )
106
-
107
- prompt_part2 = gr.Textbox(
108
- label="color",
109
- show_label=False,
110
- max_lines=1,
111
- placeholder="color (e.g., color category)",
112
- container=False,
113
- )
114
-
115
- prompt_part3 = gr.Textbox(
116
- label="dress_type",
117
- show_label=False,
118
- max_lines=1,
119
- placeholder="dress_type (e.g., t-shirt, sweatshirt, shirt, hoodie)",
120
- container=False,
121
- )
122
-
123
- prompt_part4 = gr.Textbox(
124
- label="design",
125
- show_label=False,
126
- max_lines=1,
127
- placeholder="design",
128
- container=False,
129
- )
130
-
131
- prompt_part5 = gr.Textbox(
132
- value="hanging on the plain wall",
133
- label="Prompt Part 5",
134
- show_label=False,
135
- interactive=False,
136
- container=False,
137
- elem_id="prompt_part5",
138
- visible=False,
139
- )
140
-
141
- run_button = gr.Button("Run", scale=0)
142
-
143
- result = gr.Image(label="Result", show_label=False)
144
 
145
- with gr.Accordion("Advanced Settings", open=False):
146
-
147
- negative_prompt = gr.Textbox(
148
- label="Negative prompt",
149
- max_lines=1,
150
- placeholder="Enter a negative prompt",
151
- visible=False,
152
- )
153
-
154
- seed = gr.Slider(
155
- label="Seed",
156
- minimum=0,
157
- maximum=MAX_SEED,
158
- step=1,
159
- value=0,
160
- )
161
-
162
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
163
-
164
- with gr.Row():
165
-
166
- width = gr.Slider(
167
- label="Width",
168
- minimum=256,
169
- maximum=MAX_IMAGE_SIZE,
170
- step=32,
171
- value=512,
172
- )
173
-
174
- height = gr.Slider(
175
- label="Height",
176
- minimum=256,
177
- maximum=MAX_IMAGE_SIZE,
178
- step=32,
179
- value=512,
180
- )
181
-
182
- with gr.Row():
183
-
184
- guidance_scale = gr.Slider(
185
- label="Guidance scale",
186
- minimum=0.0,
187
- maximum=10.0,
188
- step=0.1,
189
- value=0.0,
190
- )
191
-
192
- num_inference_steps = gr.Slider(
193
- label="Number of inference steps",
194
- minimum=1,
195
- maximum=12,
196
- step=1,
197
- value=2,
198
- )
199
 
200
- gr.Examples(
201
- examples=examples,
202
- inputs=[prompt_part2]
203
- )
204
-
205
- run_button.click(
206
- fn=customize_clothing,
207
- inputs=[prompt_part1, prompt_part2, prompt_part3, prompt_part4, prompt_part5, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
208
- outputs=[result]
209
  )
210
-
211
- demo.queue().launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from diffusers import StableDiffusionXLPipeline, EDMEulerScheduler
3
+ from custom_pipeline import CosStableDiffusionXLInstructPix2PixPipeline
4
+ from huggingface_hub import hf_hub_download
5
  import numpy as np
6
+ import math
7
+ #import spaces
8
+ import torch
9
  from PIL import Image
10
+ import gc
 
 
11
 
12
+ if torch.backends.mps.is_available():
13
+ DEVICE = "mps"
14
+ torch.mps.empty_cache()
15
+ gc.collect()
16
+ elif torch.cuda.is_available():
17
+ DEVICE = "cuda"
18
+ torch.cuda.empty_cache()
19
+ gc.collect()
20
+ else:
21
+ DEVICE = "cpu"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ print(f"DEVICE={DEVICE}")
 
24
 
25
+ #edit_file = hf_hub_download(repo_id="stabilityai/cosxl", filename="cosxl_edit.safetensors")
26
+ #normal_file = hf_hub_download(repo_id="stabilityai/cosxl", filename="cosxl.safetensors")
27
+ edit_file = hf_hub_download(repo_id="cocktailpeanut/c", filename="cosxl_edit.safetensors")
28
+ normal_file = hf_hub_download(repo_id="cocktailpeanut/c", filename="cosxl.safetensors")
29
 
30
+ def set_timesteps_patched(self, num_inference_steps: int, device = None):
31
+ self.num_inference_steps = num_inference_steps
32
 
33
+ ramp = np.linspace(0, 1, self.num_inference_steps)
34
+ sigmas = torch.linspace(math.log(self.config.sigma_min), math.log(self.config.sigma_max), len(ramp)).exp().flip(0)
 
 
35
 
36
+ sigmas = (sigmas).to(dtype=torch.float32, device=device)
37
+ self.timesteps = self.precondition_noise(sigmas)
 
 
 
 
 
 
 
38
 
39
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
40
+ self._step_index = None
41
+ self._begin_index = None
42
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
43
 
44
+ EDMEulerScheduler.set_timesteps = set_timesteps_patched
 
 
 
45
 
46
+ pipe_edit = CosStableDiffusionXLInstructPix2PixPipeline.from_single_file(
47
+ edit_file, num_in_channels=8
48
+ )
49
+ pipe_edit.scheduler = EDMEulerScheduler(sigma_min=0.002, sigma_max=120.0, sigma_data=1.0, prediction_type="v_prediction")
50
+ pipe_edit.to(DEVICE)
 
51
 
52
+ pipe_normal = StableDiffusionXLPipeline.from_single_file(normal_file, torch_dtype=torch.float16)
53
+ pipe_normal.scheduler = EDMEulerScheduler(sigma_min=0.002, sigma_max=120.0, sigma_data=1.0, prediction_type="v_prediction")
54
+ pipe_normal.to(DEVICE)
 
55
 
56
+ #@spaces.GPU
57
+ def run_normal(prompt, negative_prompt="", guidance_scale=7, progress=gr.Progress(track_tqdm=True)):
58
+ return pipe_normal(prompt, negative_prompt=negative_prompt, guidance_scale=guidance_scale, num_inference_steps=20).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ #@spaces.GPU
61
+ def run_edit(image, prompt, resolution, negative_prompt="", guidance_scale=7, progress=gr.Progress(track_tqdm=True)):
62
+ #resolution = 1024
63
+ print(f"width={image.width}, height={image.height}")
64
+ image.thumbnail((resolution, resolution), Image.Resampling.LANCZOS)
65
+ #image.resize((resolution, resolution))
66
+ #return pipe_edit(prompt=prompt,image=image,height=resolution,width=resolution,negative_prompt=negative_prompt, guidance_scale=guidance_scale,num_inference_steps=20).images[0]
67
+ print(f"width={image.width}, height={image.height}")
68
+ img = pipe_edit(prompt=prompt,image=image,height=image.height,width=image.width,negative_prompt=negative_prompt, guidance_scale=guidance_scale,num_inference_steps=20).images[0]
69
+ if DEVICE == "cuda":
70
+ torch.cuda.empty_cache()
71
+ gc.collect()
72
+ elif DEVICE == "mps":
73
+ torch.mps.empty_cache()
74
+ gc.collect()
75
+ return img
76
+ css = '''
77
+ .gradio-container{
78
+ max-width: 768px !important;
79
+ margin: 0 auto;
80
+ }
81
+ '''
82
+ normal_examples = ["portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography", "backlit photography of a dog", "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", "A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece"]
83
+ edit_examples = [["mountain.png", "make it a cloudy day"], ["painting.png", "make the earring fancier"]]
84
+ with gr.Blocks(css=css) as demo:
85
+ gr.Markdown('''# CosXL demo
86
+ Unofficial demo for CosXL, a SDXL model tuned to produce full color range images. CosXL Edit allows you to perform edits on images. Both have a [non-commercial community license](https://huggingface.co/stabilityai/cosxl/blob/main/LICENSE)
87
+ ''')
88
+ with gr.Tab("CosXL Edit"):
89
+ with gr.Group():
90
+ image_edit = gr.Image(label="Image you would like to edit", type="pil")
91
+ prompt_edit = gr.Textbox(label="Prompt", scale=4, placeholder="Edit instructions, e.g.: Make the day cloudy")
92
+ size_edit = gr.Number(label="Size", value=1024, maximum=1024, minimum=512, precision=0)
93
+ button_edit = gr.Button("Generate", min_width=120)
94
+ output_edit = gr.Image(label="Your result image", interactive=False)
95
+ with gr.Accordion("Advanced Settings", open=False):
96
+ negative_prompt_edit = gr.Textbox(label="Negative Prompt")
97
+ guidance_scale_edit = gr.Number(label="Guidance Scale", value=7)
98
+ gr.Examples(examples=edit_examples, fn=run_edit, inputs=[image_edit, prompt_edit, size_edit], outputs=[output_edit], cache_examples=False)
99
+ with gr.Tab("CosXL"):
100
+ with gr.Group():
101
+ with gr.Row():
102
+ prompt_normal = gr.Textbox(show_label=False, scale=4, placeholder="Your prompt, e.g.: backlit photography of a dog")
103
+ button_normal = gr.Button("Generate", min_width=120)
104
+ output_normal = gr.Image(label="Your result image", interactive=False)
105
+ with gr.Accordion("Advanced Settings", open=False):
106
+ negative_prompt_normal = gr.Textbox(label="Negative Prompt")
107
+ guidance_scale_normal = gr.Number(label="Guidance Scale", value=7)
108
+ gr.Examples(examples=normal_examples, fn=run_normal, inputs=[prompt_normal], outputs=[output_normal], cache_examples=False)
109
+ button_edit.click(
 
 
 
 
110
 
 
 
 
 
 
 
 
 
 
111
  )
112
+ gr.on(
113
+ triggers=[
114
+ button_normal.click,
115
+ prompt_normal.submit
116
+ ],
117
+ fn=run_normal,
118
+ inputs=[prompt_normal, negative_prompt_normal, guidance_scale_normal],
119
+ outputs=[output_normal],
120
+ )
121
+ gr.on(
122
+ triggers=[
123
+ button_edit.click,
124
+ prompt_edit.submit
125
+ ],
126
+ fn=run_edit,
127
+ inputs=[image_edit, prompt_edit, size_edit, negative_prompt_edit, guidance_scale_edit],
128
+ outputs=[output_edit]
129
+ )
130
+ if __name__ == "__main__":
131
+ #demo.launch(share=True)
132
+ demo.launch()