John6666 commited on
Commit
4b2575f
β€’
0 Parent(s):

Super-squash branch 'main' using huggingface_hub

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