File size: 6,981 Bytes
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38729c1
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
38729c1
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38729c1
 
 
 
 
 
 
 
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38729c1
 
 
 
de1cc63
 
38729c1
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38729c1
25268a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import os
import subprocess
from huggingface_hub import HfApi, upload_folder
import gradio as gr

from huggingface_hub import whoami, list_models


def error_str(error, title="Error"):
    return f"""#### {title}
            {error}"""  if error else ""

def get_my_model_names(token):
    
    try:
        author = whoami(token=token)
        model_infos = list_models(author=author["name"], use_auth_token=token)

        api = HfApi(token=token)
        model_names = []
        for model_info in model_infos:
            model_id = model_info.modelId
            if any([f.endswith("diffusion_pytorch_model.bin") for f in api.list_repo_files(repo_id=model_id)]):
                model_names.append(model_id)
        
        if not model_names:
            return [], Exception("No diffusion models found in your account.")

        return model_names, None
        
    except Exception as e:
        return [], e

def on_token_change(token):
    model_names, error = get_my_model_names(token)

    return gr.update(visible=bool(model_names)), gr.update(visible=bool(model_names)), gr.update(choices=model_names), gr.update(visible=bool(model_names)), gr.update(value=error_str(error))

def create_and_push(space_type, model_id, title, description, prefix, update, token):

    try:

        # 1. Create the new space
        api = HfApi(token=token)
        repo_url = api.create_repo(
            repo_id=model_id,
            exist_ok=update,
            repo_type="space",
            space_sdk="gradio",
        )

        # 2. Replace the name, title, and description in the template
        with open("template/app_simple.py" if space_type == "Simple" else "template/app_advanced.py", "r") as f:
            app = f.read()
        app = app.replace("$model_id", model_id)
        app = app.replace("$title", title)
        app = app.replace("$description", description)
        app = app.replace("$prefix", prefix)

        # 3. save the new app.py file
        with open("app.py", "w") as f:
            f.write(app)

        # 4. Upload the new app.py to the space
        api.upload_file(
            path_or_fileobj="app.py",
            path_in_repo="app.py",
            repo_id=model_id,
            token=token,
            repo_type="space",
        )

        # 5. Upload template/requirements.txt to the space
        if space_type == "Advanced":
            api.upload_file(
                path_or_fileobj="template/requirements.txt",
                path_in_repo="requirements.txt",
                repo_id=model_id,
                token=token,
                repo_type="space",
            )

        # 5. Delete the app.py file
        os.remove("app.py")

        return f"""Successfully created space at: <a href="{repo_url}" target="_blank">{repo_url}</a>"""

    except Exception as e:
        return error_str(e)

def on_model_change(radio_model_names):

    name = radio_model_names
    title = " ".join([w.capitalize() for w in name.split("/")[-1].replace("-", " ").replace("_", " ").split(" ")])
    
    description = f"""Demo for <a href="https://huggingface.co/{radio_model_names}">{title}</a> Stable Diffusion model.<br>
    Add the following tokens to your prompts for the model to work properly: <b>$prefix</b>."""

    return gr.update(value=name), gr.update(value=title), gr.update(value=description)


DESCRIPTION = """### Create a gradio space for your Diffusers🧨 model
                With this space, you can easily create a gradio demo for your Diffusers model and share it with the community.
            """

with gr.Blocks() as demo:

    gr.Markdown(DESCRIPTION)
    with gr.Row():

        with gr.Column(scale=11):
            with gr.Column():
                gr.Markdown("#### 1. Choose a model")
                input_token = gr.Textbox(
                    max_lines=1,
                    label="Enter your Hugging Face token",
                    placeholder="WRITE permission is required!",
                )
                gr.Markdown("You can get a token [here](https://huggingface.co/settings/tokens)")
                with gr.Group(visible=False) as group_model:
                    radio_model_names = gr.Radio(label="Choose a model")

        with gr.Column(scale=10):
            with gr.Column(visible=False) as group_create:
                gr.Markdown("#### 2. Enter details and create the space")
                name = gr.Textbox(label="Name", placeholder="e.g. diffusers-demo")
                title = gr.Textbox(label="Title", placeholder="e.g. Diffusers Demo")
                description = gr.Textbox(label="Description", placeholder="e.g. Demo for my awesome Diffusers model")
                prefix = gr.Textbox(label="Prefix tokens", placeholder="Tokens that are required to be present in the prompt, e.g. `rick and morty style`")
                gr.Markdown("""#### Choose space type
                - **Simple** - Runs on GPU using Hugging Face inference API, but you cannot control image generation parameters.
                - **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.""")
                space_type =gr.Radio(label="Space type", choices=["Simple", "Advanced"], value="Simple")
                update = gr.Checkbox(label="Update the space if it already exists?")
                

                brn_create = gr.Button("Create the space")

    error_output = gr.Markdown(label="Output")


    input_token.change(
        fn=on_token_change,
        inputs=input_token,
        outputs=[group_model, group_create, radio_model_names, error_output],
        queue=False,
        scroll_to_output=True)

    radio_model_names.change(
        fn=on_model_change,
        inputs=radio_model_names,
        outputs=[name, title, description],
        queue=False,
        scroll_to_output=True)

    brn_create.click(
        fn=create_and_push,
        inputs=[space_type, radio_model_names, title, description, prefix, update, input_token],
        outputs=[error_output],
        scroll_to_output=True
    )

    # gr.Markdown("""<img src="https://raw.githubusercontent.com/huggingface/diffusers/main/docs/source/imgs/diffusers_library.jpg" width="150"/>""")
    gr.HTML("""
    <div style="border-top: 1px solid #303030;">
      <br>
      <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>
      <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>
      <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.sd-space-creator" alt="visitors"></p>
    </div>
    """)
    
demo.queue()
demo.launch(debug=True)