akhaliq HF staff anzorq commited on
Commit
52ffa26
0 Parent(s):

Duplicate from anzorq/sd-space-creator

Browse files

Co-authored-by: AQ <anzorq@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SD Space Creator
3
+ emoji: 🌌🔨
4
+ colorFrom: red
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 3.10.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ duplicated_from: anzorq/sd-space-creator
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from huggingface_hub import HfApi, upload_folder
4
+ import gradio as gr
5
+ import requests
6
+ from huggingface_hub import whoami, list_models
7
+
8
+
9
+ def error_str(error, title="Error"):
10
+ return f"""#### {title}
11
+ {error}""" if error else ""
12
+
13
+ def url_to_model_id(model_id_str):
14
+ return model_id_str.split("/")[-2] + "/" + model_id_str.split("/")[-1] if model_id_str.startswith("https://huggingface.co/") else model_id_str
15
+
16
+ def has_diffusion_model(model_id, token):
17
+ api = HfApi(token=token)
18
+ return any([f.endswith("diffusion_pytorch_model.bin") for f in api.list_repo_files(repo_id=model_id)])
19
+
20
+ def get_my_model_names(token):
21
+
22
+ try:
23
+ author = whoami(token=token)
24
+ model_infos = list_models(author=author["name"], use_auth_token=token)
25
+
26
+
27
+ model_names = []
28
+ for model_info in model_infos:
29
+ model_id = model_info.modelId
30
+ if has_diffusion_model(model_id, token):
31
+ model_names.append(model_id)
32
+
33
+ # if not model_names:
34
+ # return [], Exception("No diffusion models found in your account.")
35
+
36
+ return model_names, None
37
+
38
+ except Exception as e:
39
+ return [], e
40
+
41
+ def on_token_change(token):
42
+
43
+ if token:
44
+ model_names, error = get_my_model_names(token)
45
+ return gr.update(visible=not error), gr.update(choices=model_names, label="Select a model:"), error_str(error)
46
+ else:
47
+ return gr.update(visible=False), gr.update(choices=[], label="Select a model:"), None
48
+
49
+ def on_load_model(user_model_id, other_model_id, token):
50
+
51
+ if not user_model_id and not other_model_id:
52
+ return None, None, None, None, gr.update(value=error_str("Please enter a model ID."))
53
+
54
+ try:
55
+ model_id = url_to_model_id(other_model_id) if other_model_id else user_model_id
56
+ original_model_id = model_id
57
+
58
+ if not has_diffusion_model(model_id, token):
59
+ return None, None, None, None, gr.update(value=error_str("There are no diffusion weights in the model you selected."))
60
+
61
+ user = whoami(token=token)
62
+ model_id = user["name"] + "/" + model_id.split("/")[-1]
63
+ title = " ".join([w.capitalize() for w in model_id.split("/")[-1].replace("-", " ").replace("_", " ").split(" ")])
64
+
65
+ description = f"""Demo for <a href="https://huggingface.co/{original_model_id}">{title}</a> Stable Diffusion model."""
66
+
67
+ return gr.update(visible=True), gr.update(value=model_id), gr.update(value=title), gr.update(value=description), None
68
+
69
+ except Exception as e:
70
+ return None, None, None, None, gr.update(value=error_str(e))
71
+
72
+ def create_and_push(space_type, hardware, private_space, other_model_name, radio_model_names, model_id, title, description, prefix, update, token):
73
+
74
+ try:
75
+
76
+ # 1. Create the new space
77
+ api = HfApi(token=token)
78
+ repo_url = api.create_repo(
79
+ repo_id=model_id,
80
+ exist_ok=update,
81
+ repo_type="space",
82
+ space_sdk="gradio",
83
+ private=private_space
84
+ )
85
+ api_url = f'https://huggingface.co/api/spaces/{model_id}'
86
+ headers = { "Authorization" : f"Bearer {token}"}
87
+ # add HUGGING_FACE_HUB_TOKEN secret to new space
88
+ requests.post(f'{api_url}/secrets', json={"key":"HUGGING_FACE_HUB_TOKEN","value":token}, headers=headers)
89
+ # set new Space Hardware flavor
90
+ requests.post(f'{api_url}/hardware', json={'flavor': hardware}, headers=headers)
91
+
92
+ # 2. Replace the name, title, and description in the template
93
+ with open("template/app_simple.py" if space_type == "Simple" else "template/app_advanced.py", "r") as f:
94
+ app = f.read()
95
+ app = app.replace("$model_id", url_to_model_id(other_model_name) if other_model_name else radio_model_names)
96
+ app = app.replace("$title", title)
97
+ app = app.replace("$description", description)
98
+ app = app.replace("$prefix", prefix)
99
+ app = app.replace("$space_id", whoami(token=token)["name"] + "/" + model_id.split("/")[-1])
100
+
101
+ # 3. save the new app.py file
102
+ with open("app.py", "w") as f:
103
+ f.write(app)
104
+
105
+ # 4. Upload the new app.py to the space
106
+ api.upload_file(
107
+ path_or_fileobj="app.py",
108
+ path_in_repo="app.py",
109
+ repo_id=model_id,
110
+ token=token,
111
+ repo_type="space",
112
+ )
113
+
114
+ # 5. Upload template/requirements.txt to the space
115
+ if space_type == "Advanced":
116
+ api.upload_file(
117
+ path_or_fileobj="template/requirements.txt",
118
+ path_in_repo="requirements.txt",
119
+ repo_id=model_id,
120
+ token=token,
121
+ repo_type="space",
122
+ )
123
+
124
+ # 5. Delete the app.py file
125
+ os.remove("app.py")
126
+
127
+ return f"""Successfully created space at: <a href="{repo_url}" target="_blank">{repo_url}</a>"""
128
+
129
+ except Exception as e:
130
+ return error_str(e)
131
+
132
+
133
+ DESCRIPTION = """### Create a gradio space for your Diffusers🧨 model
134
+ With this space, you can easily create a gradio demo for your Diffusers model and share it with the community.
135
+ """
136
+
137
+ with gr.Blocks() as demo:
138
+
139
+ gr.Markdown(DESCRIPTION)
140
+ with gr.Row():
141
+
142
+ with gr.Column(scale=11):
143
+ with gr.Column():
144
+ gr.Markdown("#### 1. Choose a model")
145
+ input_token = gr.Textbox(
146
+ max_lines=1,
147
+ type="password",
148
+ label="Enter your Hugging Face token",
149
+ placeholder="WRITE permission is required!",
150
+ )
151
+ gr.Markdown("You can get a token [here](https://huggingface.co/settings/tokens)")
152
+ with gr.Group(visible=False) as group_model:
153
+ radio_model_names = gr.Radio(label="Your models:")
154
+ other_model_name = gr.Textbox(label="Other model:", placeholder="URL or model id, e.g. username/model_name")
155
+ btn_load = gr.Button(value="Load model")
156
+
157
+ with gr.Column(scale=10):
158
+ with gr.Column(visible=False) as group_create:
159
+ gr.Markdown("#### 2. Enter details and create the space")
160
+ name = gr.Textbox(label="Name", placeholder="e.g. diffusers-demo")
161
+ title = gr.Textbox(label="Title", placeholder="e.g. Diffusers Demo")
162
+ description = gr.Textbox(label="Description", placeholder="e.g. Demo for my awesome Diffusers model", lines=5)
163
+ prefix = gr.Textbox(label="Prefix tokens", placeholder="Tokens that are required to be present in the prompt, e.g. `rick and morty style`")
164
+ gr.Markdown("""#### Choose space type
165
+ - **Simple** - Runs on GPU using Hugging Face inference API, but you cannot control image generation parameters.
166
+ - **Advanced** - Runs on CPU by default, with the option to upgrade to GPU. You can control image generation parameters: guidance, number of steps, image size, etc. Also supports **image-to-image** generation.""")
167
+ space_type =gr.Radio(label="Space type", choices=["Simple", "Advanced"], value="Simple")
168
+ update = gr.Checkbox(label="Update the space if it already exists?")
169
+ private_space = gr.Checkbox(label="Private Space")
170
+ gr.Markdown("Choose the new Space Hardware <small>[check pricing page](https://huggingface.co/pricing#spaces), you need payment method to upgrade your Space hardware</small>")
171
+ hardware = gr.Dropdown(["cpu-basic","cpu-upgrade","t4-small","t4-medium","a10g-small","a10g-large"],value = "cpu-basic", label="Space Hardware")
172
+ brn_create = gr.Button("Create the space")
173
+
174
+ error_output = gr.Markdown(label="Output")
175
+
176
+
177
+ input_token.change(
178
+ fn=on_token_change,
179
+ inputs=input_token,
180
+ outputs=[group_model, radio_model_names, error_output],
181
+ queue=False,
182
+ scroll_to_output=True)
183
+
184
+ btn_load.click(
185
+ fn=on_load_model,
186
+ inputs=[radio_model_names, other_model_name, input_token],
187
+ outputs=[group_create, name, title, description, error_output],
188
+ queue=False,
189
+ scroll_to_output=True)
190
+
191
+ brn_create.click(
192
+ fn=create_and_push,
193
+ inputs=[space_type, hardware, private_space, other_model_name, radio_model_names, name, title, description, prefix, update, input_token],
194
+ outputs=[error_output],
195
+ scroll_to_output=True
196
+ )
197
+
198
+ # gr.Markdown("""<img src="https://raw.githubusercontent.com/huggingface/diffusers/main/docs/source/imgs/diffusers_library.jpg" width="150"/>""")
199
+ gr.HTML("""
200
+ <div style="border-top: 1px solid #303030;">
201
+ <br>
202
+ <p>Space by: <a href="https://twitter.com/hahahahohohe"><img src="https://img.shields.io/twitter/follow/hahahahohohe?label=%40anzorq&style=social" alt="Twitter Follow"></a></p><br>
203
+ <a href="https://www.buymeacoffee.com/anzorq" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 45px !important;width: 162px !important;" ></a><br><br>
204
+ <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.sd-space-creator" alt="visitors"></p>
205
+ </div>
206
+ """)
207
+
208
+ demo.queue()
209
+ demo.launch(debug=True)
template/app_advanced.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+
6
+ model_id = '$model_id'
7
+ prefix = '$prefix'
8
+
9
+ scheduler = DPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler")
10
+
11
+ pipe = StableDiffusionPipeline.from_pretrained(
12
+ model_id,
13
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
14
+ scheduler=scheduler)
15
+
16
+ pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(
17
+ model_id,
18
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
19
+ scheduler=scheduler)
20
+
21
+ if torch.cuda.is_available():
22
+ pipe = pipe.to("cuda")
23
+ pipe_i2i = pipe_i2i.to("cuda")
24
+
25
+ def error_str(error, title="Error"):
26
+ return f"""#### {title}
27
+ {error}""" if error else ""
28
+
29
+ def inference(prompt, guidance, steps, width=512, height=512, seed=0, img=None, strength=0.5, neg_prompt="", auto_prefix=False):
30
+
31
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
32
+ prompt = f"{prefix} {prompt}" if auto_prefix else prompt
33
+
34
+ try:
35
+ if img is not None:
36
+ return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
37
+ else:
38
+ return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None
39
+ except Exception as e:
40
+ return None, error_str(e)
41
+
42
+ def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator):
43
+
44
+ result = pipe(
45
+ prompt,
46
+ negative_prompt = neg_prompt,
47
+ num_inference_steps = int(steps),
48
+ guidance_scale = guidance,
49
+ width = width,
50
+ height = height,
51
+ generator = generator)
52
+
53
+ return result.images[0]
54
+
55
+ def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
56
+
57
+ ratio = min(height / img.height, width / img.width)
58
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
59
+ result = pipe_i2i(
60
+ prompt,
61
+ negative_prompt = neg_prompt,
62
+ init_image = img,
63
+ num_inference_steps = int(steps),
64
+ strength = strength,
65
+ guidance_scale = guidance,
66
+ width = width,
67
+ height = height,
68
+ generator = generator)
69
+
70
+ return result.images[0]
71
+
72
+ css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
73
+ """
74
+ with gr.Blocks(css=css) as demo:
75
+ gr.HTML(
76
+ f"""
77
+ <div class="main-div">
78
+ <div>
79
+ <h1>$title</h1>
80
+ </div>
81
+ <p>
82
+ $description<br>
83
+ {"Add the following tokens to your prompts for the model to work properly: <b>prefix</b>" if prefix else ""}
84
+ </p>
85
+ Running on {"<b>GPU 🔥</b>" if torch.cuda.is_available() else f"<b>CPU 🥶</b>. For faster inference it is recommended to <b>upgrade to GPU in <a href='https://huggingface.co/spaces/$space_id/settings'>Settings</a></b>"} after duplicating the space<br><br>
86
+ <a style="display:inline-block" href="https://huggingface.co/spaces/$space_id?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
87
+ </div>
88
+ """
89
+ )
90
+ with gr.Row():
91
+
92
+ with gr.Column(scale=55):
93
+ with gr.Group():
94
+ with gr.Row():
95
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder=f"{prefix} [your prompt]").style(container=False)
96
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
97
+
98
+ image_out = gr.Image(height=512)
99
+ error_output = gr.Markdown()
100
+
101
+ with gr.Column(scale=45):
102
+ with gr.Tab("Options"):
103
+ with gr.Group():
104
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
105
+ auto_prefix = gr.Checkbox(label="Prefix styling tokens automatically ($prefix)", value=prefix, visible=prefix)
106
+
107
+ with gr.Row():
108
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
109
+ steps = gr.Slider(label="Steps", value=25, minimum=2, maximum=75, step=1)
110
+
111
+ with gr.Row():
112
+ width = gr.Slider(label="Width", value=512, minimum=64, maximum=1024, step=8)
113
+ height = gr.Slider(label="Height", value=512, minimum=64, maximum=1024, step=8)
114
+
115
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
116
+
117
+ with gr.Tab("Image to image"):
118
+ with gr.Group():
119
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
120
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
121
+
122
+ auto_prefix.change(lambda x: gr.update(placeholder=f"{prefix} [your prompt]" if x else "[Your prompt]"), inputs=auto_prefix, outputs=prompt, queue=False)
123
+
124
+ inputs = [prompt, guidance, steps, width, height, seed, image, strength, neg_prompt, auto_prefix]
125
+ outputs = [image_out, error_output]
126
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
127
+ generate.click(inference, inputs=inputs, outputs=outputs)
128
+
129
+ gr.HTML("""
130
+ <div style="border-top: 1px solid #303030;">
131
+ <br>
132
+ <p>This space was created using <a href="https://huggingface.co/spaces/anzorq/sd-space-creator">SD Space Creator</a>.</p>
133
+ </div>
134
+ """)
135
+
136
+ demo.queue(concurrency_count=1)
137
+ demo.launch()
template/app_simple.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+
4
+ API_KEY=os.environ.get('HUGGING_FACE_HUB_TOKEN', None)
5
+
6
+ article = """---
7
+ This space was created using [SD Space Creator](https://huggingface.co/spaces/anzorq/sd-space-creator)."""
8
+
9
+ gr.Interface.load(
10
+ name="models/$model_id",
11
+ title="""$title""",
12
+ description="""$description""",
13
+ article=article,
14
+ api_key=API_KEY,
15
+ ).queue(concurrency_count=20).launch()
template/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ diffusers
4
+ #transformers
5
+ git+https://github.com/huggingface/transformers
6
+ accelerate
7
+ ftfy