John6666 commited on
Commit
4308686
1 Parent(s): 26a3e5d

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +13 -12
  2. app.py +199 -0
  3. requirements.txt +1 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Popular Anime Models
3
- emoji: 📈
4
- colorFrom: purple
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 4.39.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
+ ---
2
+ title: Popular SDXL Anime Text-to-Image Models Playground (John6666)
3
+ emoji: 🖼️
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.39.0
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: Text-to-Image
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+
4
+
5
+ loaded_models = {}
6
+ model_info_dict = {}
7
+
8
+
9
+ def list_sub(a, b):
10
+ return [e for e in a if e not in b]
11
+
12
+
13
+ def list_uniq(l):
14
+ return sorted(set(l), key=l.index)
15
+
16
+
17
+ def is_repo_name(s):
18
+ import re
19
+ return re.fullmatch(r'^[^/]+?/[^/]+?$', s)
20
+
21
+
22
+ def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30):
23
+ from huggingface_hub import HfApi
24
+ api = HfApi()
25
+ default_tags = ["diffusers"]
26
+ models = []
27
+ try:
28
+ model_infos = api.list_models(author=author, task="text-to-image", pipeline_tag="text-to-image",
29
+ tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit * 5)
30
+ except Exception as e:
31
+ print(f"Error: Failed to list models.")
32
+ print(e)
33
+ return models
34
+ for model in model_infos:
35
+ if not model.private and not model.gated:
36
+ if not_tag and not_tag in model.tags: continue
37
+ models.append(model.id)
38
+ if len(models) == limit: break
39
+ return models
40
+
41
+
42
+ models = find_model_list("John6666", ["anime"], "", "downloads", 40)
43
+
44
+
45
+ def get_t2i_model_info_dict(repo_id: str):
46
+ from huggingface_hub import HfApi
47
+ api = HfApi()
48
+ info = {"md": "None"}
49
+ try:
50
+ if not is_repo_name(repo_id) or not api.repo_exists(repo_id=repo_id): return info
51
+ model = api.model_info(repo_id=repo_id)
52
+ except Exception as e:
53
+ print(f"Error: Failed to get {repo_id}'s info.")
54
+ print(e)
55
+ return info
56
+ if model.private or model.gated: return info
57
+ try:
58
+ tags = model.tags
59
+ except Exception:
60
+ return info
61
+ if not 'diffusers' in model.tags: return info
62
+ if 'diffusers:StableDiffusionXLPipeline' in tags: info["ver"] = "SDXL"
63
+ elif 'diffusers:StableDiffusionPipeline' in tags: info["ver"] = "SD1.5"
64
+ elif 'diffusers:StableDiffusion3Pipeline' in tags: info["ver"] = "SD3"
65
+ else: info["ver"] = "Other"
66
+ info["url"] = f"https://huggingface.co/{repo_id}/"
67
+ if model.card_data and model.card_data.tags:
68
+ info["tags"] = model.card_data.tags
69
+ info["downloads"] = model.downloads
70
+ info["likes"] = model.likes
71
+ info["last_modified"] = model.last_modified.strftime("lastmod: %Y-%m-%d")
72
+ un_tags = ['text-to-image', 'stable-diffusion', 'stable-diffusion-api', 'safetensors', 'stable-diffusion-xl']
73
+ descs = [info["ver"]] + list_sub(info["tags"], un_tags) + [f'DLs: {info["downloads"]}'] + [f'❤: {info["likes"]}'] + [info["last_modified"]]
74
+ info["md"] = f'Model Info: {", ".join(descs)} [Model Repo]({info["url"]})'
75
+ return info
76
+
77
+
78
+ def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):
79
+ from datetime import datetime, timezone, timedelta
80
+ progress(0, desc="Updating gallery...")
81
+ dt_now = datetime.now(timezone(timedelta(hours=9)))
82
+ basename = dt_now.strftime('%Y%m%d_%H%M%S_')
83
+ i = 1
84
+ if not images: return images
85
+ output_images = []
86
+ output_paths = []
87
+ for image in images:
88
+ filename = f'{image[1]}_{basename}{str(i)}.png'
89
+ i += 1
90
+ oldpath = Path(image[0])
91
+ newpath = oldpath
92
+ try:
93
+ if oldpath.stem == "image" and oldpath.exists():
94
+ newpath = oldpath.resolve().rename(Path(filename).resolve())
95
+ except Exception as e:
96
+ print(e)
97
+ pass
98
+ finally:
99
+ output_paths.append(str(newpath))
100
+ output_images.append((str(newpath), str(filename)))
101
+ progress(1, desc="Gallery updated.")
102
+ return gr.update(value=output_images), gr.update(value=output_paths)
103
+
104
+
105
+ def load_model(model_name: str):
106
+ if model_name in loaded_models.keys(): return loaded_models[model_name]
107
+ try:
108
+ loaded_models[model_name] = gr.load(f'models/{model_name}')
109
+ print(f"Loaded: {model_name}")
110
+ except Exception as e:
111
+ if model_name in loaded_models.keys(): del loaded_models[model_name]
112
+ print(f"Failed to load: {model_name}")
113
+ print(e)
114
+ return None
115
+ try:
116
+ model_info_dict[model_name] = get_t2i_model_info_dict(model_name)
117
+ except Exception as e:
118
+ if model_name in model_info_dict.keys(): del model_info_dict[model_name]
119
+ print(e)
120
+ return loaded_models[model_name]
121
+
122
+
123
+ for model in models:
124
+ load_model(model)
125
+
126
+
127
+ def get_model_info_md(model_name: str):
128
+ if model_name in model_info_dict.keys(): return model_info_dict[model_name].get("md", "")
129
+
130
+
131
+ def change_model(model_name: str):
132
+ load_model(model_name)
133
+ return get_model_info_md(model_name)
134
+
135
+
136
+ def infer(prompt: str, model_name: str, recom_prompt: bool, progress=gr.Progress(track_tqdm=True)):
137
+ from PIL import Image
138
+ import random
139
+ seed = ""
140
+ rand = random.randint(1, 500)
141
+ for i in range(rand):
142
+ seed += " "
143
+ rprompt = ", highly detailed, masterpiece, best quality, very aesthetic, absurdres, " if recom_prompt else ""
144
+ caption = model_name.split("/")[-1]
145
+ try:
146
+ model = load_model(model_name)
147
+ if not model: return (Image(), None)
148
+ image_path = model(prompt + rprompt + seed)
149
+ image = Image.open(image_path).convert('RGB')
150
+ except Exception as e:
151
+ print(e)
152
+ return (Image(), None)
153
+ return (image, caption)
154
+
155
+
156
+ def infer_multi(prompt: str, model_name: str, recom_prompt: bool, image_num: float, results: list, progress=gr.Progress(track_tqdm=True)):
157
+ image_num = int(image_num)
158
+ images = results if results else []
159
+ for i in range(image_num):
160
+ images.append(infer(prompt, model_name, recom_prompt))
161
+ yield images
162
+
163
+
164
+ css = """"""
165
+
166
+ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
167
+ with gr.Column():
168
+ model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0], allow_custom_value=True)
169
+ model_info = gr.Markdown(value=get_model_info_md(list(loaded_models.keys())[0]))
170
+ image_num = gr.Slider(label="Number of Images", minimum=1, maximum=8, value=1, step=1)
171
+ recom_prompt = gr.Checkbox(label="Recommended Prompt", value=True)
172
+ prompt = gr.Text(label="Prompt", lines=1, max_lines=8, placeholder="1girl, solo, ...")
173
+ run_button = gr.Button("Generate Image")
174
+ results = gr.Gallery(label="Gallery", interactive=False, show_download_button=True, show_share_button=False,
175
+ container=True, format="png", object_fit="contain")
176
+ image_files = gr.Files(label="Download", interactive=False)
177
+ clear_results = gr.Button("Clear Gallery and Download")
178
+ gr.Markdown(
179
+ f"""This demo was created in reference to the following demos.
180
+ - [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood).
181
+ - [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL).
182
+ """
183
+ )
184
+ gr.DuplicateButton(value="Duplicate Space")
185
+
186
+ model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)
187
+ gr.on(
188
+ triggers=[run_button.click, prompt.submit],
189
+ fn=infer_multi,
190
+ inputs=[prompt, model_name, recom_prompt, image_num, results],
191
+ outputs=[results],
192
+ queue=True,
193
+ show_progress="full",
194
+ show_api=True,
195
+ ).success(save_gallery_images, [results], [results, image_files], queue=False, show_api=False)
196
+ clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)
197
+
198
+ demo.queue()
199
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ huggingface_hub