sashulyak commited on
Commit
0156d87
·
1 Parent(s): c2d3537

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +338 -4
app.py CHANGED
@@ -1,7 +1,341 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ from pathlib import Path
4
+ import argparse
5
+ import shutil
6
+ from train_dreambooth import run_training
7
+ from convertosd import convert
8
+ from PIL import Image
9
+ from slugify import slugify
10
+ import requests
11
+ import torch
12
+ import zipfile
13
+ import urllib.parse
14
+ from diffusers import StableDiffusionPipeline
15
 
16
+ css = '''
17
+ .instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important}
18
+ .arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important}
19
+ #component-4, #component-3, #component-10{min-height: 0}
20
+ '''
21
+ model_to_load = "multimodalart/sd-fine-tunable"
22
+ maximum_concepts = 3
23
+ #Pre download the files even if we don't use it here
24
+ StableDiffusionPipeline.from_pretrained(model_to_load)
25
 
26
+ def zipdir(path, ziph):
27
+ # ziph is zipfile handle
28
+ for root, dirs, files in os.walk(path):
29
+ for file in files:
30
+ ziph.write(os.path.join(root, file),
31
+ os.path.relpath(os.path.join(root, file),
32
+ os.path.join(path, '..')))
33
+
34
+ def swap_text(option):
35
+ mandatory_liability = "You must have the right to do so and you are liable for the images you use, example:"
36
+ if(option == "object"):
37
+ instance_prompt_example = "cttoy"
38
+ freeze_for = 50
39
+ return [f"You are going to train `object`(s), upload 5-10 images of each object you are planning on training on from different angles/perspectives. {mandatory_liability}:", '''<img src="file/cat-toy.png" />''', f"You should name your concept with a unique made up word that has low chance of the model already knowing it (e.g.: `{instance_prompt_example}` here). Images will be automatically cropped to 512x512.", freeze_for]
40
+ elif(option == "person"):
41
+ instance_prompt_example = "julcto"
42
+ freeze_for = 100
43
+ return [f"You are going to train a `person`(s), upload 10-20 images of each person you are planning on training on from different angles/perspectives. {mandatory_liability}:", '''<img src="file/person.png" />''', f"You should name the files with a unique word that represent your concept (e.g.: `{instance_prompt_example}` here). Images will be automatically cropped to 512x512.", freeze_for]
44
+ elif(option == "style"):
45
+ instance_prompt_example = "trsldamrl"
46
+ freeze_for = 10
47
+ return [f"You are going to train a `style`, upload 10-20 images of the style you are planning on training on. Name the files with the words you would like {mandatory_liability}:", '''<img src="file/trsl_style.png" />''', f"You should name your files with a unique word that represent your concept (e.g.: `{instance_prompt_example}` here). Images will be automatically cropped to 512x512.", freeze_for]
48
+
49
+ def count_files(*inputs):
50
+ file_counter = 0
51
+ concept_counter = 0
52
+ for i, input in enumerate(inputs):
53
+ if(i < maximum_concepts-1):
54
+ files = inputs[i]
55
+ if(files):
56
+ concept_counter+=1
57
+ file_counter+=len(files)
58
+ uses_custom = inputs[-1]
59
+ type_of_thing = inputs[-4]
60
+ if(uses_custom):
61
+ Training_Steps = int(inputs[-3])
62
+ else:
63
+ if(type_of_thing == "person"):
64
+ Training_Steps = file_counter*200*2
65
+ else:
66
+ Training_Steps = file_counter*200
67
+ return(gr.update(visible=True, value=f"You are going to train {concept_counter} {type_of_thing}(s), with {file_counter} images for {Training_Steps} steps. This should take around {round(Training_Steps/1.5, 2)} seconds, or {round((Training_Steps/1.5)/3600, 2)} hours. As a reminder, the T4 GPU costs US$0.60 for 1h. Once training is over, don't forget to swap the hardware back to CPU."))
68
+
69
+ def train(*inputs):
70
+ if "IS_SHARED_UI" in os.environ:
71
+ raise gr.Error("This Space only works in duplicated instances")
72
+ if os.path.exists("output_model"): shutil.rmtree('output_model')
73
+ if os.path.exists("instance_images"): shutil.rmtree('instance_images')
74
+ if os.path.exists("diffusers_model.zip"): os.remove("diffusers_model.zip")
75
+ if os.path.exists("model.ckpt"): os.remove("model.ckpt")
76
+ file_counter = 0
77
+ for i, input in enumerate(inputs):
78
+ if(i < maximum_concepts-1):
79
+ if(input):
80
+ os.makedirs('instance_images',exist_ok=True)
81
+ files = inputs[i+(maximum_concepts*2)]
82
+ prompt = inputs[i+maximum_concepts]
83
+ if(prompt == "" or prompt == None):
84
+ raise gr.Error("You forgot to define your concept prompt")
85
+ for j, file_temp in enumerate(files):
86
+ file = Image.open(file_temp.name)
87
+ width, height = file.size
88
+ side_length = min(width, height)
89
+ left = (width - side_length)/2
90
+ top = (height - side_length)/2
91
+ right = (width + side_length)/2
92
+ bottom = (height + side_length)/2
93
+ image = file.crop((left, top, right, bottom))
94
+ image = image.resize((512, 512))
95
+ extension = file_temp.name.split(".")[1]
96
+ image = image.convert('RGB')
97
+ image.save(f'instance_images/{prompt}_({j+1}).jpg', format="JPEG", quality = 100)
98
+ file_counter += 1
99
+
100
+ os.makedirs('output_model',exist_ok=True)
101
+ uses_custom = inputs[-1]
102
+ type_of_thing = inputs[-4]
103
+ if(uses_custom):
104
+ Training_Steps = int(inputs[-3])
105
+ Train_text_encoder_for = int(inputs[-2])
106
+ else:
107
+ Training_Steps = file_counter*200
108
+ if(type_of_thing == "object"):
109
+ Train_text_encoder_for=30
110
+ elif(type_of_thing == "person"):
111
+ Train_text_encoder_for=60
112
+ elif(type_of_thing == "style"):
113
+ Train_text_encoder_for=15
114
+
115
+ class_data_dir = None
116
+ stptxt = int((Training_Steps*Train_text_encoder_for)/100)
117
+ args_general = argparse.Namespace(
118
+ image_captions_filename = True,
119
+ train_text_encoder = True,
120
+ stop_text_encoder_training = stptxt,
121
+ save_n_steps = 0,
122
+ pretrained_model_name_or_path = model_to_load,
123
+ instance_data_dir="instance_images",
124
+ class_data_dir=class_data_dir,
125
+ output_dir="output_model",
126
+ instance_prompt="",
127
+ seed=42,
128
+ resolution=512,
129
+ mixed_precision="fp16",
130
+ train_batch_size=1,
131
+ gradient_accumulation_steps=1,
132
+ use_8bit_adam=True,
133
+ learning_rate=2e-6,
134
+ lr_scheduler="polynomial",
135
+ lr_warmup_steps = 0,
136
+ max_train_steps=Training_Steps,
137
+ )
138
+ run_training(args_general)
139
+ torch.cuda.empty_cache()
140
+ #convert("output_model", "model.ckpt")
141
+ #shutil.rmtree('instance_images')
142
+ #shutil.make_archive("diffusers_model", 'zip', "output_model")
143
+ with zipfile.ZipFile('diffusers_model.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
144
+ zipdir('output_model/', zipf)
145
+ torch.cuda.empty_cache()
146
+ return [gr.update(visible=True, value=["diffusers_model.zip"]), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)]
147
+
148
+ def generate(prompt):
149
+ from diffusers import StableDiffusionPipeline
150
+
151
+ pipe = StableDiffusionPipeline.from_pretrained("./output_model", torch_dtype=torch.float16)
152
+ pipe = pipe.to("cuda")
153
+ image = pipe(prompt).images[0]
154
+ return(image)
155
+
156
+ def push(model_name, where_to_upload, hf_token):
157
+ if(not os.path.exists("model.ckpt")):
158
+ convert("output_model", "model.ckpt")
159
+ from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
160
+ from huggingface_hub import create_repo
161
+ model_name_slug = slugify(model_name)
162
+ api = HfApi()
163
+ your_username = api.whoami(token=hf_token)["name"]
164
+ if(where_to_upload == "My personal profile"):
165
+ model_id = f"{your_username}/{model_name_slug}"
166
+ else:
167
+ model_id = f"sd-dreambooth-library/{model_name_slug}"
168
+ headers = {"Authorization" : f"Bearer: {hf_token}", "Content-Type": "application/json"}
169
+ response = requests.post("https://huggingface.co/organizations/sd-dreambooth-library/share/SSeOwppVCscfTEzFGQaqpfcjukVeNrKNHX", headers=headers)
170
+
171
+ images_upload = os.listdir("instance_images")
172
+ image_string = ""
173
+ instance_prompt_list = []
174
+ previous_instance_prompt = ''
175
+ for i, image in enumerate(images_upload):
176
+ instance_prompt = image.split("_")[0]
177
+ if(instance_prompt != previous_instance_prompt):
178
+ title_instance_prompt_string = instance_prompt
179
+ instance_prompt_list.append(instance_prompt)
180
+ else:
181
+ title_instance_prompt_string = ''
182
+ previous_instance_prompt = instance_prompt
183
+ image_string = f'''{title_instance_prompt_string}
184
+ {image_string}![{instance_prompt} {i}](https://huggingface.co/{model_id}/resolve/main/concept_images/{urllib.parse.quote(image)})'''
185
+ readme_text = f'''---
186
+ license: creativeml-openrail-m
187
+ tags:
188
+ - text-to-image
189
+ ---
190
+ ### {model_name} Dreambooth model trained by {api.whoami(token=hf_token)["name"]} with [Hugging Face Dreambooth Training Space](https://huggingface.co/spaces/multimodalart/dreambooth-training)
191
+
192
+ You run your new concept via `diffusers` [Colab Notebook for Inference](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_dreambooth_inference.ipynb)
193
+
194
+ Sample pictures of this concept:
195
+ {image_string}
196
+ '''
197
+ #Save the readme to a file
198
+ readme_file = open("README.md", "w")
199
+ readme_file.write(readme_text)
200
+ readme_file.close()
201
+ #Save the token identifier to a file
202
+ text_file = open("token_identifier.txt", "w")
203
+ text_file.write(', '.join(instance_prompt_list))
204
+ text_file.close()
205
+ create_repo(model_id,private=True, token=hf_token)
206
+ operations = [
207
+ CommitOperationAdd(path_in_repo="token_identifier.txt", path_or_fileobj="token_identifier.txt"),
208
+ CommitOperationAdd(path_in_repo="README.md", path_or_fileobj="README.md"),
209
+ CommitOperationAdd(path_in_repo=f"model.ckpt",path_or_fileobj="model.ckpt")
210
+ ]
211
+ api.create_commit(
212
+ repo_id=model_id,
213
+ operations=operations,
214
+ commit_message=f"Upload the model {model_name}",
215
+ token=hf_token
216
+ )
217
+ api.upload_folder(
218
+ folder_path="output_model",
219
+ repo_id=model_id,
220
+ token=hf_token
221
+ )
222
+ api.upload_folder(
223
+ folder_path="instance_images",
224
+ path_in_repo="concept_images",
225
+ repo_id=model_id,
226
+ token=hf_token
227
+ )
228
+ return [gr.update(visible=True, value=f"Successfully uploaded your model. Access it [here](https://huggingface.co/{model_id})"), gr.update(visible=True, value=["diffusers_model.zip", "model.ckpt"])]
229
+
230
+ def convert_to_ckpt():
231
+ convert("output_model", "model.ckpt")
232
+ return gr.update(visible=True, value=["diffusers_model.zip", "model.ckpt"])
233
+
234
+ with gr.Blocks(css=css) as demo:
235
+ with gr.Box():
236
+ if "IS_SHARED_UI" in os.environ:
237
+ gr.HTML('''
238
+ <div class="gr-prose" style="max-width: 80%">
239
+ <h2>Attention - This Space doesn't work in this shared UI</h2>
240
+ <p>For it to work, you have to duplicate the Space and run it on your own profile where a (paid) private GPU will be attributed to it during runtime. As each T4 costs US$0,60/h, it should cost < US$1 to train a model with less than 100 images on default settings!</p>
241
+ <img class="instruction" src="file/duplicate.png">
242
+ <img class="arrow" src="file/arrow.png" />
243
+ </div>
244
+ ''')
245
+ else:
246
+ gr.HTML('''
247
+ <div class="gr-prose" style="max-width: 80%">
248
+ <h2>You have successfully cloned the Dreambooth Training Space</h2>
249
+ <p>If you haven't already, attribute a T4 GPU to it (via the Settings tab) and run the training below. You will be billed by the minute from when you activate the GPU until when you turn it off.</p>
250
+ </div>
251
+ ''')
252
+ gr.Markdown("# Dreambooth training")
253
+ gr.Markdown("Customize Stable Diffusion by giving it with few-shot examples. Based on TheLastBen's [fast-DreamBooth Colab](https://colab.research.google.com/github/TheLastBen/fast-stable-diffusion/blob/main/fast-DreamBooth.ipynb) with 🧨 diffusers")
254
+ with gr.Row():
255
+ type_of_thing = gr.Dropdown(label="What would you like to train?", choices=["object", "person", "style"], value="object", interactive=True)
256
+
257
+ with gr.Row():
258
+ with gr.Column():
259
+ thing_description = gr.Markdown("You are going to train an `object`, upload 5-10 images of the object you are planning on training on from different angles/perspectives. You must have the right to do so and you are liable for the images you use, example:")
260
+ thing_image_example = gr.HTML('''<img src="file/cat-toy.png" />''')
261
+ things_naming = gr.Markdown("You should name your concept with a unique made up word that has low chance of the model already knowing it (e.g.: `cttoy` here). Images will be automatically cropped to 512x512.")
262
+ with gr.Column():
263
+ file_collection = []
264
+ concept_collection = []
265
+ buttons_collection = []
266
+ delete_collection = []
267
+ is_visible = []
268
+
269
+ row = [None] * maximum_concepts
270
+ for x in range(maximum_concepts):
271
+ ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])
272
+ if(x == 0):
273
+ visible = True
274
+ is_visible.append(gr.State(value=True))
275
+ else:
276
+ visible = False
277
+ is_visible.append(gr.State(value=False))
278
+
279
+ file_collection.append(gr.File(label=f"Upload the images for your {ordinal(x+1)} concept", file_count="multiple", interactive=True, visible=visible))
280
+ with gr.Column(visible=visible) as row[x]:
281
+ concept_collection.append(gr.Textbox(label=f"{ordinal(x+1)} concept prompt - use a unique, made up word to avoid collisions"))
282
+ with gr.Row():
283
+ if(x < maximum_concepts-1):
284
+ buttons_collection.append(gr.Button(value="Add +1 concept", visible=visible))
285
+ if(x > 0):
286
+ delete_collection.append(gr.Button(value=f"Delete {ordinal(x+1)} concept"))
287
+
288
+ counter_add = 1
289
+ for button in buttons_collection:
290
+ if(counter_add < len(buttons_collection)):
291
+ button.click(lambda:
292
+ [gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), True, None],
293
+ None,
294
+ [row[counter_add], file_collection[counter_add], buttons_collection[counter_add-1], buttons_collection[counter_add], is_visible[counter_add], file_collection[counter_add]], queue=False)
295
+ else:
296
+ button.click(lambda:[gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), True], None, [row[counter_add], file_collection[counter_add], buttons_collection[counter_add-1], is_visible[counter_add]], queue=False)
297
+ counter_add += 1
298
+
299
+ counter_delete = 1
300
+ for delete_button in delete_collection:
301
+ if(counter_delete < len(delete_collection)+1):
302
+ delete_button.click(lambda:[gr.update(visible=False),gr.update(visible=False), gr.update(visible=True), False], None, [file_collection[counter_delete], row[counter_delete], buttons_collection[counter_delete-1], is_visible[counter_delete]], queue=False)
303
+ counter_delete += 1
304
+
305
+
306
+
307
+ with gr.Accordion("Custom Settings", open=False):
308
+ swap_auto_calculated = gr.Checkbox(label="Use custom settings")
309
+ gr.Markdown("If not checked, the number of steps and % of frozen encoder will be tuned automatically according to the amount of images you upload and whether you are training an `object`, `person` or `style` as follows: The number of steps is calculated by number of images uploaded multiplied by 20. The text-encoder is frozen after 10% of the steps for a style, 30% of the steps for an object and is fully trained for persons.")
310
+ steps = gr.Number(label="How many steps", value=800)
311
+ perc_txt_encoder = gr.Number(label="Percentage of the training steps the text-encoder should be trained as well", value=30)
312
+
313
+ type_of_thing.change(fn=swap_text, inputs=[type_of_thing], outputs=[thing_description, thing_image_example, things_naming, perc_txt_encoder], queue=False)
314
+ training_summary = gr.Textbox("", visible=False, label="Training Summary")
315
+ steps.change(fn=count_files, inputs=file_collection+[type_of_thing]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary], queue=False)
316
+ perc_txt_encoder.change(fn=count_files, inputs=file_collection+[type_of_thing]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary], queue=False)
317
+ for file in file_collection:
318
+ file.change(fn=count_files, inputs=file_collection+[type_of_thing]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[training_summary], queue=False)
319
+ train_btn = gr.Button("Start Training")
320
+ with gr.Box(visible=False) as try_your_model:
321
+ gr.Markdown("## Try your model")
322
+ with gr.Row():
323
+ prompt = gr.Textbox(label="Type your prompt")
324
+ result_image = gr.Image()
325
+ generate_button = gr.Button("Generate Image")
326
+ with gr.Box(visible=False) as push_to_hub:
327
+ gr.Markdown("## Push to Hugging Face Hub")
328
+ model_name = gr.Textbox(label="Name of your model", placeholder="Tarsila do Amaral Style")
329
+ where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], label="Upload to")
330
+ gr.Markdown("[A Hugging Face write access token](https://huggingface.co/settings/tokens), go to \"New token\" -> Role : Write. A regular read token won't work here.")
331
+ hf_token = gr.Textbox(label="Hugging Face Write Token")
332
+ push_button = gr.Button("Push to the Hub")
333
+ result = gr.File(label="Download the uploaded models in the diffusers format", visible=True)
334
+ success_message_upload = gr.Markdown(visible=False)
335
+ convert_button = gr.Button("Convert to CKPT", visible=False)
336
+
337
+ train_btn.click(fn=train, inputs=is_visible+concept_collection+file_collection+[type_of_thing]+[steps]+[perc_txt_encoder]+[swap_auto_calculated], outputs=[result, try_your_model, push_to_hub, convert_button])
338
+ generate_button.click(fn=generate, inputs=prompt, outputs=result_image)
339
+ push_button.click(fn=push, inputs=[model_name, where_to_upload, hf_token], outputs=[success_message_upload, result])
340
+ convert_button.click(fn=convert_to_ckpt, inputs=[], outputs=result)
341
+ demo.launch(debug=True)