John6666 commited on
Commit
cc6e31a
1 Parent(s): 5fbe98e

Upload 11 files

Browse files
Files changed (4) hide show
  1. app.py +14 -9
  2. model.py +0 -4
  3. multit2i.py +58 -18
  4. tagger/tagger.py +3 -0
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import gradio as gr
 
2
  from multit2i import (
3
  load_models,
4
  infer_multi,
@@ -13,9 +14,8 @@ from multit2i import (
13
  get_negative_suffix,
14
  get_recom_prompt_type,
15
  set_recom_prompt_preset,
 
16
  )
17
- from model import models
18
-
19
  from tagger.tagger import (
20
  predict_tags_wd,
21
  remove_specific_prompt,
@@ -35,8 +35,8 @@ from tagger.utils import (
35
  )
36
 
37
 
38
- load_models(models, 10)
39
- #load_models(models, 20) # Fetching 20 models at the same time. default: 5 *This option is not working so far.
40
 
41
 
42
  css = """
@@ -59,6 +59,7 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
59
  v2_length = gr.Radio(label="Length", info="The total length of the tags.", choices=list(V2_LENGTH_OPTIONS), value="long")
60
  v2_identity = gr.Radio(label="Keep identity", info="How strictly to keep the identity of the character or subject. If you specify the detail of subject in the prompt, you should choose `strict`. Otherwise, choose `none` or `lax`. `none` is very creative but sometimes ignores the input prompt.", choices=list(V2_IDENTITY_OPTIONS), value="lax")
61
  v2_ban_tags = gr.Textbox(label="Ban tags", info="Tags to ban from the output.", placeholder="alternate costumen, ...", value="censored")
 
62
  v2_model = gr.Dropdown(label="Model", choices=list(V2_ALL_MODELS.keys()), value=list(V2_ALL_MODELS.keys())[0])
63
  with gr.Accordion("Model", open=True):
64
  model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0])
@@ -69,7 +70,7 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
69
  with gr.Accordion(label="Advanced options", open=False):
70
  tagger_general_threshold = gr.Slider(label="Threshold", minimum=0.0, maximum=1.0, value=0.3, step=0.01, interactive=True)
71
  tagger_character_threshold = gr.Slider(label="Character threshold", minimum=0.0, maximum=1.0, value=0.8, step=0.01, interactive=True)
72
- tagger_tag_type = gr.Radio(label="Convert tags to", info="danbooru for Animagine, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru")
73
  tagger_recom_prompt = gr.Radio(label="Insert reccomended prompt", choices=["None", "Animagine", "Pony"], value="None", interactive=True)
74
  tagger_keep_tags = gr.Radio(label="Remove tags leaving only the following", choices=["body", "dress", "all"], value="all")
75
  tagger_algorithms = gr.CheckboxGroup(["Use WD Tagger", "Use Florence-2-SD3-Long-Captioner"], label="Algorithms", value=["Use WD Tagger"])
@@ -103,8 +104,6 @@ with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:
103
  f"""This demo was created in reference to the following demos.
104
  - [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood).
105
  - [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL).
106
- <br>The first startup takes a mind-boggling amount of time, but not so much after the second.
107
- This is due to the time it takes for Gradio to generate an example image to cache.
108
  """
109
  )
110
  gr.DuplicateButton(value="Duplicate Space")
@@ -134,8 +133,14 @@ This is due to the time it takes for Gradio to generate an example image to cach
134
  clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)
135
  recom_prompt_preset.change(set_recom_prompt_preset, [recom_prompt_preset],
136
  [positive_prefix, positive_suffix, negative_prefix, negative_suffix], queue=False, show_api=False)
137
- random_prompt.click(v2_random_prompt, [prompt, v2_series, v2_character, v2_rating, v2_aspect_ratio, v2_length,
138
- v2_identity, v2_ban_tags, v2_model], [prompt, v2_series, v2_character], queue=False, show_api=False)
 
 
 
 
 
 
139
  tagger_generate_from_image.click(
140
  predict_tags_wd,
141
  [tagger_image, prompt, tagger_algorithms, tagger_general_threshold, tagger_character_threshold],
 
1
  import gradio as gr
2
+ from model import models
3
  from multit2i import (
4
  load_models,
5
  infer_multi,
 
14
  get_negative_suffix,
15
  get_recom_prompt_type,
16
  set_recom_prompt_preset,
17
+ get_tag_type,
18
  )
 
 
19
  from tagger.tagger import (
20
  predict_tags_wd,
21
  remove_specific_prompt,
 
35
  )
36
 
37
 
38
+ load_models(models, 5)
39
+ #load_models(models, 20) # Fetching 20 models at the same time. default: 5
40
 
41
 
42
  css = """
 
59
  v2_length = gr.Radio(label="Length", info="The total length of the tags.", choices=list(V2_LENGTH_OPTIONS), value="long")
60
  v2_identity = gr.Radio(label="Keep identity", info="How strictly to keep the identity of the character or subject. If you specify the detail of subject in the prompt, you should choose `strict`. Otherwise, choose `none` or `lax`. `none` is very creative but sometimes ignores the input prompt.", choices=list(V2_IDENTITY_OPTIONS), value="lax")
61
  v2_ban_tags = gr.Textbox(label="Ban tags", info="Tags to ban from the output.", placeholder="alternate costumen, ...", value="censored")
62
+ v2_tag_type = gr.Radio(label="Tag Type", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru", visible=False)
63
  v2_model = gr.Dropdown(label="Model", choices=list(V2_ALL_MODELS.keys()), value=list(V2_ALL_MODELS.keys())[0])
64
  with gr.Accordion("Model", open=True):
65
  model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0])
 
70
  with gr.Accordion(label="Advanced options", open=False):
71
  tagger_general_threshold = gr.Slider(label="Threshold", minimum=0.0, maximum=1.0, value=0.3, step=0.01, interactive=True)
72
  tagger_character_threshold = gr.Slider(label="Character threshold", minimum=0.0, maximum=1.0, value=0.8, step=0.01, interactive=True)
73
+ tagger_tag_type = gr.Radio(label="Convert tags to", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru")
74
  tagger_recom_prompt = gr.Radio(label="Insert reccomended prompt", choices=["None", "Animagine", "Pony"], value="None", interactive=True)
75
  tagger_keep_tags = gr.Radio(label="Remove tags leaving only the following", choices=["body", "dress", "all"], value="all")
76
  tagger_algorithms = gr.CheckboxGroup(["Use WD Tagger", "Use Florence-2-SD3-Long-Captioner"], label="Algorithms", value=["Use WD Tagger"])
 
104
  f"""This demo was created in reference to the following demos.
105
  - [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood).
106
  - [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL).
 
 
107
  """
108
  )
109
  gr.DuplicateButton(value="Duplicate Space")
 
133
  clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)
134
  recom_prompt_preset.change(set_recom_prompt_preset, [recom_prompt_preset],
135
  [positive_prefix, positive_suffix, negative_prefix, negative_suffix], queue=False, show_api=False)
136
+ random_prompt.click(
137
+ v2_random_prompt, [prompt, v2_series, v2_character, v2_rating, v2_aspect_ratio, v2_length,
138
+ v2_identity, v2_ban_tags, v2_model], [prompt, v2_series, v2_character], show_api=False,
139
+ ).success(
140
+ get_tag_type, [positive_prefix, positive_suffix, negative_prefix, negative_suffix], [v2_tag_type], queue=False, show_api=False
141
+ ).success(
142
+ convert_danbooru_to_e621_prompt, [prompt, v2_tag_type], [prompt], queue=False, show_api=False,
143
+ )
144
  tagger_generate_from_image.click(
145
  predict_tags_wd,
146
  [tagger_image, prompt, tagger_algorithms, tagger_general_threshold, tagger_character_threshold],
model.py CHANGED
@@ -19,9 +19,6 @@ models = [
19
  ]
20
 
21
 
22
- models = ['yodayo-ai/kivotos-xl-2.0', 'Raelina/Rae-Diffusion-XL-V2']
23
-
24
-
25
  # Examples:
26
  #models = ['yodayo-ai/kivotos-xl-2.0', 'yodayo-ai/holodayo-xl-2.1'] # specific models
27
  #models = find_model_list("John6666", [], "", "last_modified", 20) # John6666's latest 20 models
@@ -29,4 +26,3 @@ models = ['yodayo-ai/kivotos-xl-2.0', 'Raelina/Rae-Diffusion-XL-V2']
29
  #models = find_model_list("John6666", [], "anime", "last_modified", 20) # John6666's latest 20 models without 'anime' tag
30
  #models = find_model_list("", [], "", "last_modified", 20) # latest 20 text-to-image models of huggingface
31
  #models = find_model_list("", [], "", "downloads", 20) # monthly most downloaded 20 text-to-image models of huggingface
32
-
 
19
  ]
20
 
21
 
 
 
 
22
  # Examples:
23
  #models = ['yodayo-ai/kivotos-xl-2.0', 'yodayo-ai/holodayo-xl-2.1'] # specific models
24
  #models = find_model_list("John6666", [], "", "last_modified", 20) # John6666's latest 20 models
 
26
  #models = find_model_list("John6666", [], "anime", "last_modified", 20) # John6666's latest 20 models without 'anime' tag
27
  #models = find_model_list("", [], "", "last_modified", 20) # latest 20 text-to-image models of huggingface
28
  #models = find_model_list("", [], "", "downloads", 20) # monthly most downloaded 20 text-to-image models of huggingface
 
multit2i.py CHANGED
@@ -1,6 +1,7 @@
1
  import gradio as gr
2
  import asyncio
3
- from threading import RLock, Thread
 
4
  from pathlib import Path
5
 
6
 
@@ -70,8 +71,7 @@ def get_t2i_model_info_dict(repo_id: str):
70
  elif 'diffusers:StableDiffusion3Pipeline' in tags: info["ver"] = "SD3"
71
  else: info["ver"] = "Other"
72
  info["url"] = f"https://huggingface.co/{repo_id}/"
73
- if model.card_data and model.card_data.tags:
74
- info["tags"] = model.card_data.tags
75
  info["downloads"] = model.downloads
76
  info["likes"] = model.likes
77
  info["last_modified"] = model.last_modified.strftime("lastmod: %Y-%m-%d")
@@ -108,31 +108,61 @@ def save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):
108
  return gr.update(value=output_images), gr.update(value=output_paths)
109
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def load_model(model_name: str):
112
  global loaded_models
113
  global model_info_dict
114
  if model_name in loaded_models.keys(): return loaded_models[model_name]
115
  try:
116
- with lock:
117
- loaded_models[model_name] = gr.load(f'models/{model_name}')
118
  print(f"Loaded: {model_name}")
119
  except Exception as e:
120
- with lock:
121
- if model_name in loaded_models.keys(): del loaded_models[model_name]
122
  print(f"Failed to load: {model_name}")
123
  print(e)
124
  return None
125
  try:
126
- with lock:
127
- model_info_dict[model_name] = get_t2i_model_info_dict(model_name)
128
  except Exception as e:
129
- with lock:
130
- if model_name in model_info_dict.keys(): del model_info_dict[model_name]
131
  print(e)
132
  return loaded_models[model_name]
133
 
134
 
135
- async def async_load_models(models: list, limit: int=5, wait=10):
136
  sem = asyncio.Semaphore(limit)
137
  async def async_load_model(model: str):
138
  async with sem:
@@ -247,6 +277,16 @@ def get_negative_suffix():
247
  return list(negative_suffix.keys())
248
 
249
 
 
 
 
 
 
 
 
 
 
 
250
  def get_model_info_md(model_name: str):
251
  if model_name in model_info_dict.keys(): return model_info_dict[model_name].get("md", "")
252
 
@@ -277,13 +317,13 @@ def infer(prompt: str, neg_prompt: str, model_name: str):
277
 
278
  async def infer_multi(prompt: str, neg_prompt: str, results: list, image_num: float, model_name: str,
279
  pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):
280
- #from tqdm.asyncio import tqdm_asyncio
281
  image_num = int(image_num)
282
  images = results if results else []
283
  prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)
284
  tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for i in range(image_num)]
285
- results = await asyncio.gather(*tasks, return_exceptions=True)
286
- #results = await tqdm_asyncio.gather(*tasks)
287
  if not results: results = []
288
  for result in results:
289
  with lock:
@@ -293,7 +333,7 @@ async def infer_multi(prompt: str, neg_prompt: str, results: list, image_num: fl
293
 
294
  async def infer_multi_random(prompt: str, neg_prompt: str, results: list, image_num: float,
295
  pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):
296
- #from tqdm.asyncio import tqdm_asyncio
297
  import random
298
  image_num = int(image_num)
299
  images = results if results else []
@@ -301,8 +341,8 @@ async def infer_multi_random(prompt: str, neg_prompt: str, results: list, image_
301
  model_names = random.choices(list(loaded_models.keys()), k = image_num)
302
  prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)
303
  tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for model_name in model_names]
304
- results = await asyncio.gather(*tasks, return_exceptions=True)
305
- #await tqdm_asyncio.gather(*tasks)
306
  if not results: results = []
307
  for result in results:
308
  with lock:
 
1
  import gradio as gr
2
  import asyncio
3
+ import queue
4
+ from threading import RLock
5
  from pathlib import Path
6
 
7
 
 
71
  elif 'diffusers:StableDiffusion3Pipeline' in tags: info["ver"] = "SD3"
72
  else: info["ver"] = "Other"
73
  info["url"] = f"https://huggingface.co/{repo_id}/"
74
+ info["tags"] = model.card_data.tags if model.card_data and model.card_data.tags else []
 
75
  info["downloads"] = model.downloads
76
  info["likes"] = model.likes
77
  info["last_modified"] = model.last_modified.strftime("lastmod: %Y-%m-%d")
 
108
  return gr.update(value=output_images), gr.update(value=output_paths)
109
 
110
 
111
+ def load_from_model(model_name: str, hf_token: str = None):
112
+ import httpx
113
+ import huggingface_hub
114
+ from gradio.exceptions import ModelNotFoundError
115
+ model_url = f"https://huggingface.co/{model_name}"
116
+ api_url = f"https://api-inference.huggingface.co/models/{model_name}"
117
+ print(f"Fetching model from: {model_url}")
118
+
119
+ headers = {"Authorization": f"Bearer {hf_token}"} if hf_token is not None else {}
120
+ response = httpx.request("GET", api_url, headers=headers)
121
+ if response.status_code != 200:
122
+ raise ModelNotFoundError(
123
+ f"Could not find model: {model_name}. If it is a private or gated model, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `hf_token` parameter."
124
+ )
125
+ headers["X-Wait-For-Model"] = "true"
126
+ client = huggingface_hub.InferenceClient(model=model_name, headers=headers, token=hf_token)
127
+ inputs = gr.components.Textbox(label="Input")
128
+ outputs = gr.components.Image(label="Output")
129
+ fn = client.text_to_image
130
+
131
+ def query_huggingface_inference_endpoints(*data):
132
+ return fn(*data)
133
+
134
+ interface_info = {
135
+ "fn": query_huggingface_inference_endpoints,
136
+ "inputs": inputs,
137
+ "outputs": outputs,
138
+ "title": model_name,
139
+ }
140
+ return gr.Interface(**interface_info)
141
+
142
+
143
  def load_model(model_name: str):
144
  global loaded_models
145
  global model_info_dict
146
  if model_name in loaded_models.keys(): return loaded_models[model_name]
147
  try:
148
+ loaded_models[model_name] = load_from_model(model_name)
 
149
  print(f"Loaded: {model_name}")
150
  except Exception as e:
151
+ if model_name in loaded_models.keys(): del loaded_models[model_name]
 
152
  print(f"Failed to load: {model_name}")
153
  print(e)
154
  return None
155
  try:
156
+ model_info_dict[model_name] = get_t2i_model_info_dict(model_name)
157
+ print(f"Assigned: {model_name}")
158
  except Exception as e:
159
+ if model_name in model_info_dict.keys(): del model_info_dict[model_name]
160
+ print(f"Failed to assigned: {model_name}")
161
  print(e)
162
  return loaded_models[model_name]
163
 
164
 
165
+ async def async_load_models(models: list, limit: int=5):
166
  sem = asyncio.Semaphore(limit)
167
  async def async_load_model(model: str):
168
  async with sem:
 
277
  return list(negative_suffix.keys())
278
 
279
 
280
+ def get_tag_type(pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = []):
281
+ tag_type = "danbooru"
282
+ words = pos_pre + pos_suf + neg_pre + neg_suf
283
+ for word in words:
284
+ if "Pony" in word:
285
+ tag_type = "e621"
286
+ break
287
+ return tag_type
288
+
289
+
290
  def get_model_info_md(model_name: str):
291
  if model_name in model_info_dict.keys(): return model_info_dict[model_name].get("md", "")
292
 
 
317
 
318
  async def infer_multi(prompt: str, neg_prompt: str, results: list, image_num: float, model_name: str,
319
  pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):
320
+ from tqdm.asyncio import tqdm_asyncio
321
  image_num = int(image_num)
322
  images = results if results else []
323
  prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)
324
  tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for i in range(image_num)]
325
+ #results = await asyncio.gather(*tasks, return_exceptions=True)
326
+ results = await tqdm_asyncio.gather(*tasks)
327
  if not results: results = []
328
  for result in results:
329
  with lock:
 
333
 
334
  async def infer_multi_random(prompt: str, neg_prompt: str, results: list, image_num: float,
335
  pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):
336
+ from tqdm.asyncio import tqdm_asyncio
337
  import random
338
  image_num = int(image_num)
339
  images = results if results else []
 
341
  model_names = random.choices(list(loaded_models.keys()), k = image_num)
342
  prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)
343
  tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for model_name in model_names]
344
+ #results = await asyncio.gather(*tasks, return_exceptions=True)
345
+ results = await tqdm_asyncio.gather(*tasks)
346
  if not results: results = []
347
  for result in results:
348
  with lock:
tagger/tagger.py CHANGED
@@ -31,12 +31,15 @@ PEOPLE_TAGS = (
31
 
32
 
33
  RATING_MAP = {
 
34
  "general": "safe",
35
  "sensitive": "sensitive",
36
  "questionable": "nsfw",
37
  "explicit": "explicit, nsfw",
38
  }
39
  DANBOORU_TO_E621_RATING_MAP = {
 
 
40
  "safe": "rating_safe",
41
  "sensitive": "rating_safe",
42
  "nsfw": "rating_explicit",
 
31
 
32
 
33
  RATING_MAP = {
34
+ "sfw": "safe",
35
  "general": "safe",
36
  "sensitive": "sensitive",
37
  "questionable": "nsfw",
38
  "explicit": "explicit, nsfw",
39
  }
40
  DANBOORU_TO_E621_RATING_MAP = {
41
+ "sfw": "rating_safe",
42
+ "general": "rating_safe",
43
  "safe": "rating_safe",
44
  "sensitive": "rating_safe",
45
  "nsfw": "rating_explicit",