John6666 commited on
Commit
ae677ba
1 Parent(s): 56120d6

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +13 -12
  2. app.py +198 -0
  3. requirements.txt +1 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Recent Anime Models
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: purple
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: Recent 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,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+
4
+ models = [
5
+ 'cagliostrolab/animagine-xl-3.1',
6
+ 'votepurchase/ponyDiffusionV6XL',
7
+ 'yodayo-ai/kivotos-xl-2.0',
8
+ 'yodayo-ai/holodayo-xl-2.1',
9
+ 'stabilityai/stable-diffusion-xl-base-1.0',
10
+ 'eienmojiki/Anything-XL',
11
+ 'eienmojiki/Starry-XL-v5.2',
12
+ 'digiplay/majicMIX_sombre_v2',
13
+ 'digiplay/majicMIX_realistic_v7',
14
+ 'digiplay/DreamShaper_8',
15
+ 'digiplay/BeautifulArt_v1',
16
+ 'digiplay/DarkSushi2.5D_v1',
17
+ 'digiplay/darkphoenix3D_v1.1',
18
+ 'digiplay/BeenYouLiteL11_diffusers',
19
+ 'votepurchase/counterfeitV30_v30',
20
+ 'Meina/MeinaMix_V11',
21
+ 'Meina/MeinaUnreal_V5',
22
+ 'Meina/MeinaPastel_V7',
23
+ 'KBlueLeaf/Kohaku-XL-Epsilon-rev2',
24
+ 'KBlueLeaf/Kohaku-XL-Epsilon-rev3',
25
+ 'kayfahaarukku/UrangDiffusion-1.1',
26
+ 'Raelina/Rae-Diffusion-XL-V2',
27
+ 'Raelina/Raemu-XL-V4',
28
+ ]
29
+ loaded_models = {}
30
+ model_info_dict = {}
31
+
32
+
33
+ def list_sub(a, b):
34
+ return [e for e in a if e not in b]
35
+
36
+
37
+ def is_repo_name(s):
38
+ import re
39
+ return re.fullmatch(r'^[^/]+?/[^/]+?$', s)
40
+
41
+
42
+ def get_t2i_model_info_dict(repo_id: str):
43
+ from huggingface_hub import HfApi
44
+ api = HfApi()
45
+ info = {"md": "None"}
46
+ try:
47
+ if not is_repo_name(repo_id) or not api.repo_exists(repo_id=repo_id): return info
48
+ model = api.model_info(repo_id=repo_id)
49
+ except Exception as e:
50
+ print(f"Error: Failed to get {repo_id}'s info.")
51
+ print(e)
52
+ return info
53
+ if model.private or model.gated: return info
54
+ try:
55
+ tags = model.tags
56
+ except Exception:
57
+ return info
58
+ if not 'diffusers' in model.tags: return info
59
+ if 'diffusers:StableDiffusionXLPipeline' in tags: info["ver"] = "SDXL"
60
+ elif 'diffusers:StableDiffusionPipeline' in tags: info["ver"] = "SD1.5"
61
+ elif 'diffusers:StableDiffusion3Pipeline' in tags: info["ver"] = "SD3"
62
+ else: info["ver"] = "Other"
63
+ info["url"] = f"https://huggingface.co/{repo_id}/"
64
+ if model.card_data and model.card_data.tags:
65
+ info["tags"] = model.card_data.tags
66
+ info["downloads"] = model.downloads
67
+ info["likes"] = model.likes
68
+ info["last_modified"] = model.last_modified.strftime("lastmod: %Y-%m-%d")
69
+ un_tags = ['text-to-image', 'stable-diffusion', 'stable-diffusion-api', 'safetensors', 'stable-diffusion-xl']
70
+ descs = [info["ver"]] + list_sub(info["tags"], un_tags) + [f'DLs: {info["downloads"]}'] + [f'❤: {info["likes"]}'] + [info["last_modified"]]
71
+ info["md"] = f'Model Info: {", ".join(descs)} [Model Repo]({info["url"]})'
72
+ return info
73
+
74
+
75
+ def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):
76
+ from datetime import datetime, timezone, timedelta
77
+ progress(0, desc="Updating gallery...")
78
+ dt_now = datetime.now(timezone(timedelta(hours=9)))
79
+ basename = dt_now.strftime('%Y%m%d_%H%M%S_')
80
+ i = 1
81
+ if not images: return images
82
+ output_images = []
83
+ output_paths = []
84
+ for image in images:
85
+ filename = f'{image[1]}_{basename}{str(i)}.png'
86
+ i += 1
87
+ oldpath = Path(image[0])
88
+ newpath = oldpath
89
+ try:
90
+ if oldpath.stem == "image" and oldpath.exists():
91
+ newpath = oldpath.resolve().rename(Path(filename).resolve())
92
+ except Exception as e:
93
+ print(e)
94
+ pass
95
+ finally:
96
+ output_paths.append(str(newpath))
97
+ output_images.append((str(newpath), str(filename)))
98
+ progress(1, desc="Gallery updated.")
99
+ return gr.update(value=output_images), gr.update(value=output_paths)
100
+
101
+
102
+ def load_model(model_name: str):
103
+ if model_name in loaded_models.keys(): return loaded_models[model_name]
104
+ try:
105
+ loaded_models[model_name] = gr.load(f'models/{model_name}')
106
+ print(f"Loaded: {model_name}")
107
+ except Exception as e:
108
+ if model_name in loaded_models.keys(): del loaded_models[model_name]
109
+ print(f"Failed to load: {model_name}")
110
+ print(e)
111
+ return None
112
+ try:
113
+ model_info_dict[model_name] = get_t2i_model_info_dict(model_name)
114
+ except Exception as e:
115
+ if model_name in model_info_dict.keys(): del model_info_dict[model_name]
116
+ print(e)
117
+ return loaded_models[model_name]
118
+
119
+
120
+ for model in models:
121
+ load_model(model)
122
+
123
+
124
+ def get_model_info_md(model_name: str):
125
+ if model_name in model_info_dict.keys(): return model_info_dict[model_name].get("md", "")
126
+
127
+
128
+ def change_model(model_name: str):
129
+ load_model(model_name)
130
+ return get_model_info_md(model_name)
131
+
132
+
133
+ def infer(prompt: str, model_name: str, recom_prompt: bool, progress=gr.Progress(track_tqdm=True)):
134
+ from PIL import Image
135
+ import random
136
+ seed = ""
137
+ rand = random.randint(1, 500)
138
+ for i in range(rand):
139
+ seed += " "
140
+ rprompt = ", highly detailed, masterpiece, best quality, very aesthetic, absurdres, " if recom_prompt else ""
141
+ caption = model_name.split("/")[-1]
142
+ try:
143
+ model = load_model(model_name)
144
+ if not model: return (Image(), None)
145
+ image_path = model(prompt + rprompt + seed)
146
+ image = Image.open(image_path).convert('RGB')
147
+ except Exception as e:
148
+ print(e)
149
+ return (Image(), None)
150
+ return (image, caption)
151
+
152
+
153
+ def infer_multi(prompt: str, model_name: str, recom_prompt: bool, image_num: float, results: list, progress=gr.Progress(track_tqdm=True)):
154
+ image_num = int(image_num)
155
+ images = results if results else []
156
+ for i in range(image_num):
157
+ images.append(infer(prompt, model_name, recom_prompt))
158
+ yield images
159
+
160
+
161
+ css = """"""
162
+
163
+ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
164
+ with gr.Column():
165
+ model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0], allow_custom_value=True)
166
+ model_info = gr.Markdown(value=get_model_info_md(list(loaded_models.keys())[0]))
167
+ image_num = gr.Slider(label="Number of Images", minimum=1, maximum=8, value=1, step=1)
168
+ recom_prompt = gr.Checkbox(label="Recommended Prompt", value=True)
169
+ prompt = gr.Text(label="Prompt", lines=1, max_lines=8, placeholder="1girl, solo, ...")
170
+ run_button = gr.Button("Generate Image")
171
+ results = gr.Gallery(label="Gallery", interactive=False, show_download_button=True, show_share_button=False,
172
+ container=True, format="png", object_fit="contain")
173
+ image_files = gr.Files(label="Download", interactive=False)
174
+ clear_results = gr.Button("Clear Gallery and Download")
175
+ gr.Markdown(
176
+ f"""This demo was created in reference to the following demos.
177
+ - [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood).
178
+ - [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL).
179
+ <br>The first startup takes a mind-boggling amount of time, but not so much after the second.
180
+ This is due to the time it takes for Gradio to generate an example image to cache.
181
+ """
182
+ )
183
+ gr.DuplicateButton(value="Duplicate Space")
184
+
185
+ model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)
186
+ gr.on(
187
+ triggers=[run_button.click, prompt.submit],
188
+ fn=infer_multi,
189
+ inputs=[prompt, model_name, recom_prompt, image_num, results],
190
+ outputs=[results],
191
+ queue=True,
192
+ show_progress="full",
193
+ show_api=True,
194
+ ).success(save_gallery_images, [results], [results, image_files], queue=False, show_api=False)
195
+ clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)
196
+
197
+ demo.queue()
198
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ huggingface_hub