Spaces:
Runtime error
Runtime error
Commit
•
c947e95
1
Parent(s):
b5965be
Update app.py
Browse files
app.py
CHANGED
@@ -10,11 +10,16 @@ from slugify import slugify
|
|
10 |
import requests
|
11 |
import torch
|
12 |
import zipfile
|
|
|
13 |
import urllib.parse
|
14 |
import gc
|
15 |
from diffusers import StableDiffusionPipeline
|
16 |
from huggingface_hub import snapshot_download
|
17 |
|
|
|
|
|
|
|
|
|
18 |
css = '''
|
19 |
.instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important}
|
20 |
.arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important}
|
@@ -68,9 +73,14 @@ def count_files(*inputs):
|
|
68 |
Training_Steps = file_counter*200*2
|
69 |
else:
|
70 |
Training_Steps = file_counter*200
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
def pad_image(image):
|
76 |
w, h = image.size
|
@@ -86,17 +96,17 @@ def pad_image(image):
|
|
86 |
return new_image
|
87 |
|
88 |
def train(*inputs):
|
|
|
|
|
|
|
89 |
torch.cuda.empty_cache()
|
90 |
if 'pipe' in globals():
|
91 |
del pipe
|
92 |
gc.collect()
|
93 |
-
|
94 |
-
if "IS_SHARED_UI" in os.environ:
|
95 |
-
raise gr.Error("This Space only works in duplicated instances")
|
96 |
-
|
97 |
if os.path.exists("output_model"): shutil.rmtree('output_model')
|
98 |
if os.path.exists("instance_images"): shutil.rmtree('instance_images')
|
99 |
-
if os.path.exists("diffusers_model.
|
100 |
if os.path.exists("model.ckpt"): os.remove("model.ckpt")
|
101 |
if os.path.exists("hastrained.success"): os.remove("hastrained.success")
|
102 |
file_counter = 0
|
@@ -168,17 +178,19 @@ def train(*inputs):
|
|
168 |
shutil.copytree(f"{safety_checker}/feature_extractor", "output_model/feature_extractor")
|
169 |
shutil.copytree(f"{safety_checker}/safety_checker", "output_model/safety_checker")
|
170 |
shutil.copy(f"model_index.json", "output_model/model_index.json")
|
171 |
-
|
172 |
-
with zipfile.ZipFile('diffusers_model.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
|
173 |
-
|
174 |
-
print("Training completed!")
|
175 |
-
|
176 |
if(not remove_attribution_after):
|
|
|
|
|
|
|
177 |
if os.path.exists("intraining.lock"): os.remove("intraining.lock")
|
178 |
trained_file = open("hastrained.success", "w")
|
179 |
trained_file.close()
|
|
|
180 |
return [
|
181 |
-
gr.update(visible=True, value=["diffusers_model.
|
182 |
gr.update(visible=True), #try_your_model
|
183 |
gr.update(visible=True), #push_to_hub
|
184 |
gr.update(visible=True), #convert_button
|
@@ -281,26 +293,35 @@ Sample pictures of:
|
|
281 |
repo_id=model_id,
|
282 |
token=hf_token
|
283 |
)
|
284 |
-
if
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
|
|
289 |
|
290 |
-
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.
|
291 |
|
292 |
def convert_to_ckpt():
|
293 |
convert("output_model", "model.ckpt")
|
294 |
-
return gr.update(visible=True, value=["diffusers_model.
|
295 |
|
296 |
def check_status(top_description):
|
297 |
if os.path.exists("hastrained.success"):
|
298 |
-
|
299 |
-
|
300 |
-
<
|
301 |
-
|
302 |
-
|
303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
304 |
show_outputs = True
|
305 |
elif os.path.exists("intraining.lock"):
|
306 |
update_top_tag = gr.update(value='''
|
@@ -313,8 +334,8 @@ def check_status(top_description):
|
|
313 |
else:
|
314 |
update_top_tag = gr.update(value=top_description)
|
315 |
show_outputs = False
|
316 |
-
if os.path.exists("diffusers_model.
|
317 |
-
update_files_tag = gr.update(visible=show_outputs, value=["diffusers_model.
|
318 |
else:
|
319 |
update_files_tag = gr.update(visible=show_outputs)
|
320 |
return [
|
@@ -330,23 +351,30 @@ def checkbox_swap(checkbox):
|
|
330 |
|
331 |
with gr.Blocks(css=css) as demo:
|
332 |
with gr.Box():
|
333 |
-
if
|
334 |
top_description = gr.HTML(f'''
|
335 |
<div class="gr-prose" style="max-width: 80%">
|
336 |
<h2>Attention - This Space doesn't work in this shared UI</h2>
|
337 |
-
<p>For it to work, you
|
338 |
<img class="instruction" src="file/duplicate.png">
|
339 |
<img class="arrow" src="file/arrow.png" />
|
340 |
</div>
|
341 |
''')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
342 |
else:
|
343 |
top_description = gr.HTML(f'''
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
gr.Markdown("# Dreambooth
|
350 |
gr.Markdown("Customize Stable Diffusion by training it on a few examples of concepts, up to 3 concepts on the same model. This Space is based on TheLastBen's [fast-DreamBooth Colab](https://colab.research.google.com/github/TheLastBen/fast-stable-diffusion/blob/main/fast-DreamBooth.ipynb) with [🧨 diffusers](https://github.com/huggingface/diffusers)")
|
351 |
|
352 |
with gr.Row() as what_are_you_training:
|
@@ -406,14 +434,15 @@ with gr.Blocks(css=css) as demo:
|
|
406 |
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.")
|
407 |
steps = gr.Number(label="How many steps", value=800)
|
408 |
perc_txt_encoder = gr.Number(label="Percentage of the training steps the text-encoder should be trained as well", value=30)
|
409 |
-
|
410 |
with gr.Box(visible=False) as training_summary:
|
411 |
training_summary_text = gr.HTML("", visible=False, label="Training Summary")
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
|
|
417 |
|
418 |
train_btn = gr.Button("Start Training")
|
419 |
|
|
|
10 |
import requests
|
11 |
import torch
|
12 |
import zipfile
|
13 |
+
import tarfile
|
14 |
import urllib.parse
|
15 |
import gc
|
16 |
from diffusers import StableDiffusionPipeline
|
17 |
from huggingface_hub import snapshot_download
|
18 |
|
19 |
+
|
20 |
+
is_spaces = True if "SPACE_ID" in os.environ else False
|
21 |
+
is_shared_ui = True if "IS_SHARED_UI" in os.environ else False
|
22 |
+
|
23 |
css = '''
|
24 |
.instruction{position: absolute; top: 0;right: 0;margin-top: 0px !important}
|
25 |
.arrow{position: absolute;top: 0;right: -110px;margin-top: -8px !important}
|
|
|
73 |
Training_Steps = file_counter*200*2
|
74 |
else:
|
75 |
Training_Steps = file_counter*200
|
76 |
+
if(is_spaces):
|
77 |
+
summary_sentence = f'''You are going to train {concept_counter} {type_of_thing}(s), with {file_counter} images for {Training_Steps} steps. The training should take around {round(Training_Steps/1.1, 2)} seconds, or {round((Training_Steps/1.1)/60, 2)} minutes.
|
78 |
+
The setup, compression and uploading the model can take up to 20 minutes.<br>As the T4-Small GPU costs US$0.60 for 1h, <span style="font-size: 120%"><b>the estimated cost for this training is US${round((((Training_Steps/1.1)/3600)+0.3+0.1)*0.60, 2)}.</b></span><br><br>
|
79 |
+
If you check the box below the GPU attribution will automatically removed after training is done and the model is uploaded. If not, don't forget to come back here and swap the hardware back to CPU.<br><br>'''
|
80 |
+
else:
|
81 |
+
summary_sentence = f'''You are going to train {concept_counter} {type_of_thing}(s), with {file_counter} images for {Training_Steps} steps.<br><br>'''
|
82 |
+
|
83 |
+
return([gr.update(visible=True), gr.update(visible=True, value=summary_sentence)])
|
84 |
|
85 |
def pad_image(image):
|
86 |
w, h = image.size
|
|
|
96 |
return new_image
|
97 |
|
98 |
def train(*inputs):
|
99 |
+
if is_shared_ui:
|
100 |
+
raise gr.Error("This Space only works in duplicated instances")
|
101 |
+
|
102 |
torch.cuda.empty_cache()
|
103 |
if 'pipe' in globals():
|
104 |
del pipe
|
105 |
gc.collect()
|
106 |
+
|
|
|
|
|
|
|
107 |
if os.path.exists("output_model"): shutil.rmtree('output_model')
|
108 |
if os.path.exists("instance_images"): shutil.rmtree('instance_images')
|
109 |
+
if os.path.exists("diffusers_model.tar"): os.remove("diffusers_model.tar")
|
110 |
if os.path.exists("model.ckpt"): os.remove("model.ckpt")
|
111 |
if os.path.exists("hastrained.success"): os.remove("hastrained.success")
|
112 |
file_counter = 0
|
|
|
178 |
shutil.copytree(f"{safety_checker}/feature_extractor", "output_model/feature_extractor")
|
179 |
shutil.copytree(f"{safety_checker}/safety_checker", "output_model/safety_checker")
|
180 |
shutil.copy(f"model_index.json", "output_model/model_index.json")
|
181 |
+
|
182 |
+
#with zipfile.ZipFile('diffusers_model.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
|
183 |
+
# zipdir('output_model/', zipf)
|
|
|
|
|
184 |
if(not remove_attribution_after):
|
185 |
+
print("Archiving model file...")
|
186 |
+
with tarfile.open("diffusers_model.tar", "w") as tar:
|
187 |
+
tar.add("diffusers_model", arcname=os.path.basename("diffusers_model"))
|
188 |
if os.path.exists("intraining.lock"): os.remove("intraining.lock")
|
189 |
trained_file = open("hastrained.success", "w")
|
190 |
trained_file.close()
|
191 |
+
print("Training completed!")
|
192 |
return [
|
193 |
+
gr.update(visible=True, value=["diffusers_model.tar"]), #result
|
194 |
gr.update(visible=True), #try_your_model
|
195 |
gr.update(visible=True), #push_to_hub
|
196 |
gr.update(visible=True), #convert_button
|
|
|
293 |
repo_id=model_id,
|
294 |
token=hf_token
|
295 |
)
|
296 |
+
if is_spaces:
|
297 |
+
if(not comes_from_automated):
|
298 |
+
extra_message = "Don't forget to remove the GPU attribution after you play with it."
|
299 |
+
else:
|
300 |
+
extra_message = "The GPU has been removed automatically as requested, and you can try the model via the model page"
|
301 |
+
api.create_discussion(repo_id=os.environ['SPACE_ID'], title=f"Your model {model_name} has finished trained from the Dreambooth Train Spaces!", description=f"Your model has been successfully uploaded to: https://huggingface.co/{model_id}. {extra_message}",repo_type="space", token=hf_token)
|
302 |
|
303 |
+
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.tar", "model.ckpt"])]
|
304 |
|
305 |
def convert_to_ckpt():
|
306 |
convert("output_model", "model.ckpt")
|
307 |
+
return gr.update(visible=True, value=["diffusers_model.tar", "model.ckpt"])
|
308 |
|
309 |
def check_status(top_description):
|
310 |
if os.path.exists("hastrained.success"):
|
311 |
+
if is_spaces:
|
312 |
+
update_top_tag = gr.update(value=f'''
|
313 |
+
<div class="gr-prose" style="max-width: 80%">
|
314 |
+
<h2>Your model has finished training ✅</h2>
|
315 |
+
<p>Yay, congratulations on training your model. Scroll down to play with with it, save it (either downloading it or on the Hugging Face Hub). Once you are done, your model is safe, and you don't want to train a new one, go to the <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}">settings page</a> and downgrade your Space to a CPU Basic</p>
|
316 |
+
</div>
|
317 |
+
''')
|
318 |
+
else:
|
319 |
+
update_top_tag = gr.update(value=f'''
|
320 |
+
<div class="gr-prose" style="max-width: 80%">
|
321 |
+
<h2>Your model has finished training ✅</h2>
|
322 |
+
<p>Yay, congratulations on training your model. Scroll down to play with with it, save it (either downloading it or on the Hugging Face Hub).</p>
|
323 |
+
</div>
|
324 |
+
''')
|
325 |
show_outputs = True
|
326 |
elif os.path.exists("intraining.lock"):
|
327 |
update_top_tag = gr.update(value='''
|
|
|
334 |
else:
|
335 |
update_top_tag = gr.update(value=top_description)
|
336 |
show_outputs = False
|
337 |
+
if os.path.exists("diffusers_model.tar"):
|
338 |
+
update_files_tag = gr.update(visible=show_outputs, value=["diffusers_model.tar"])
|
339 |
else:
|
340 |
update_files_tag = gr.update(visible=show_outputs)
|
341 |
return [
|
|
|
351 |
|
352 |
with gr.Blocks(css=css) as demo:
|
353 |
with gr.Box():
|
354 |
+
if is_shared_ui:
|
355 |
top_description = gr.HTML(f'''
|
356 |
<div class="gr-prose" style="max-width: 80%">
|
357 |
<h2>Attention - This Space doesn't work in this shared UI</h2>
|
358 |
+
<p>For it to work, you can either run locally or duplicate the Space and run it on your own profile using a (paid) private T4 GPU for training. As each T4 costs US$0.60/h, it should cost < US$1 to train most models using default settings! <a class="duplicate-button" style="display:inline-block" href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></p>
|
359 |
<img class="instruction" src="file/duplicate.png">
|
360 |
<img class="arrow" src="file/arrow.png" />
|
361 |
</div>
|
362 |
''')
|
363 |
+
elif(is_spaces):
|
364 |
+
top_description = gr.HTML(f'''
|
365 |
+
<div class="gr-prose" style="max-width: 80%">
|
366 |
+
<h2>You have successfully duplicated the Dreambooth Training Space 🎉</h2>
|
367 |
+
<p>If you haven't already, <a href="https://huggingface.co/spaces/{os.environ['SPACE_ID']}/settings">attribute a T4 GPU to it (via the Settings tab)</a> and run the training below. You will be billed by the minute from when you activate the GPU until when it is turned it off.</p>
|
368 |
+
</div>
|
369 |
+
''')
|
370 |
else:
|
371 |
top_description = gr.HTML(f'''
|
372 |
+
<div class="gr-prose" style="max-width: 80%">
|
373 |
+
<h2>You have successfully cloned the Dreambooth Training Space locally 🎉</h2>
|
374 |
+
<p>If you are having problems with the requirements, try installing xformers with `%pip install git+https://github.com/facebookresearch/xformers@1d31a3a#egg=xformers`</p>
|
375 |
+
</div>
|
376 |
+
''')
|
377 |
+
gr.Markdown("# Dreambooth Training UI")
|
378 |
gr.Markdown("Customize Stable Diffusion by training it on a few examples of concepts, up to 3 concepts on the same model. This Space is based on TheLastBen's [fast-DreamBooth Colab](https://colab.research.google.com/github/TheLastBen/fast-stable-diffusion/blob/main/fast-DreamBooth.ipynb) with [🧨 diffusers](https://github.com/huggingface/diffusers)")
|
379 |
|
380 |
with gr.Row() as what_are_you_training:
|
|
|
434 |
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.")
|
435 |
steps = gr.Number(label="How many steps", value=800)
|
436 |
perc_txt_encoder = gr.Number(label="Percentage of the training steps the text-encoder should be trained as well", value=30)
|
437 |
+
|
438 |
with gr.Box(visible=False) as training_summary:
|
439 |
training_summary_text = gr.HTML("", visible=False, label="Training Summary")
|
440 |
+
if(is_spaces):
|
441 |
+
training_summary_checkbox = gr.Checkbox(label="Automatically remove paid GPU attribution and upload model to the Hugging Face Hub after training", value=False)
|
442 |
+
training_summary_model_name = gr.Textbox(label="Name of your model", visible=False)
|
443 |
+
training_summary_where_to_upload = gr.Dropdown(["My personal profile", "Public Library"], label="Upload to", visible=False)
|
444 |
+
training_summary_token_message = 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.", visible=False)
|
445 |
+
training_summary_token = gr.Textbox(label="Hugging Face Write Token", type="password", visible=False)
|
446 |
|
447 |
train_btn = gr.Button("Start Training")
|
448 |
|