Nymbo commited on
Commit
3455385
·
verified ·
1 Parent(s): d33ef8e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -101
app.py CHANGED
@@ -1,112 +1,163 @@
1
  import gradio as gr
2
- import requests
3
- import io
4
- import random
5
- import os
6
- import time
7
- from PIL import Image
8
- from deep_translator import GoogleTranslator
9
- import json
 
 
 
 
 
 
 
 
 
10
 
11
- # Project by Nymbo
12
 
13
- API_URL = "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell"
14
- API_TOKEN = os.getenv("HF_READ_TOKEN")
15
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
16
- timeout = 100
17
-
18
- def query(prompt, negative_prompt, steps=30, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, width=512, height=512):
19
- if not prompt:
20
- return None
21
-
22
- key = random.randint(0, 999)
23
-
24
- API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN")])
25
- headers = {"Authorization": f"Bearer {API_TOKEN}"}
26
-
27
- prompt_translated = GoogleTranslator(source='auto', target='en').translate(prompt)
28
- print(f'\033[1mGeneration {key} translation:\033[0m {prompt_translated}')
29
-
30
- full_prompt = f"{prompt_translated} | ultra detail, ultra elaboration, ultra quality, perfect."
31
- print(f'\033[1mGeneration {key}:\033[0m {full_prompt}')
32
-
33
- # Use a random seed if seed is -1
34
- seed_value = seed if seed != -1 else random.randint(1, 1000000000)
35
-
36
- payload = {
37
- "inputs": full_prompt,
38
- "negative_prompt": negative_prompt,
39
- "steps": steps,
40
- "cfg_scale": cfg_scale,
41
- "seed": seed_value,
42
- "strength": strength,
43
- "width": width,
44
- "height": height,
45
- "sampler": sampler
46
- }
47
-
48
- response = requests.post(API_URL, headers=headers, json=payload, timeout=timeout)
49
- if response.status_code != 200:
50
- print(f"Error: Failed to get image. Response status: {response.status_code}")
51
- print(f"Response content: {response.text}")
52
- if response.status_code == 503:
53
- raise gr.Error(f"{response.status_code} : The model is being loaded")
54
- raise gr.Error(f"{response.status_code}")
55
-
56
- try:
57
- image_bytes = response.content
58
- image = Image.open(io.BytesIO(image_bytes))
59
- print(f'\033[1mGeneration {key} completed!\033[0m ({full_prompt})')
60
- return image
61
- except Exception as e:
62
- print(f"Error when trying to open the image: {e}")
63
- return None
64
 
65
  css = """
66
- #app-container {
67
- max-width: 600px;
68
- margin-left: auto;
69
- margin-right: auto;
70
- }
71
  """
72
 
73
- with gr.Blocks(theme='Nymbo/Nymbo_Theme', css=css) as app:
74
- gr.HTML("<center><h1>FLUX.1-Schnell</h1></center>")
75
- with gr.Column(elem_id="app-container"):
76
- with gr.Row():
77
- with gr.Column(elem_id="prompt-container"):
78
- with gr.Row():
79
- text_prompt = gr.Textbox(label="Prompt", placeholder="Enter a prompt here", lines=2, elem_id="prompt-text-input")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  with gr.Row():
81
- with gr.Accordion("Advanced Settings", open=False):
82
- negative_prompt = gr.Textbox(
83
- label="Negative Prompt",
84
- placeholder="What should not be in the image",
85
- value="(deformed, distorted, disfigured), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, misspellings, typos",
86
- lines=3,
87
- elem_id="negative-prompt-text-input"
88
- )
89
- steps = gr.Slider(label="Sampling steps", value=30, minimum=1, maximum=100, step=1)
90
- cfg = gr.Slider(label="CFG Scale", value=7, minimum=1, maximum=20, step=0.5)
91
- method = gr.Radio(
92
- label="Sampling method",
93
- value="DPM++ 2M Karras",
94
- choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"]
95
- )
96
- strength = gr.Slider(label="Strength", value=0.7, minimum=0, maximum=1, step=0.01)
97
- seed = gr.Number(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1)
98
- width = gr.Number(label="Width", value=512, minimum=64, maximum=1024, step=64)
99
- height = gr.Number(label="Height", value=512, minimum=64, maximum=1024, step=64)
100
-
101
- with gr.Row():
102
- text_button = gr.Button("Run", variant='primary', elem_id="gen-button")
103
  with gr.Row():
104
- image_output = gr.Image(type="pil", label="Image Output", elem_id="gallery")
105
-
106
- text_button.click(
107
- query,
108
- inputs=[text_prompt, negative_prompt, steps, cfg, method, seed, strength, width, height],
109
- outputs=image_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- app.launch(show_api=False, share=False)
 
 
1
  import gradio as gr
2
+ from model import models
3
+ from multit2i import (
4
+ load_models, infer_fn, infer_rand_fn, save_gallery,
5
+ change_model, warm_model, get_model_info_md, loaded_models,
6
+ get_positive_prefix, get_positive_suffix, get_negative_prefix, get_negative_suffix,
7
+ get_recom_prompt_type, set_recom_prompt_preset, get_tag_type,
8
+ )
9
+ from tagger.tagger import (
10
+ predict_tags_wd, remove_specific_prompt, convert_danbooru_to_e621_prompt,
11
+ insert_recom_prompt, compose_prompt_to_copy,
12
+ )
13
+ from tagger.fl2sd3longcap import predict_tags_fl2_sd3
14
+ from tagger.v2 import V2_ALL_MODELS, v2_random_prompt
15
+ from tagger.utils import (
16
+ V2_ASPECT_RATIO_OPTIONS, V2_RATING_OPTIONS,
17
+ V2_LENGTH_OPTIONS, V2_IDENTITY_OPTIONS,
18
+ )
19
 
 
20
 
21
+ max_images = 8
22
+ load_models(models)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  css = """
25
+ .model_info { text-align: center; }
26
+ .output { width=112px; height=112px; !important; }
27
+ .gallery { width=100%; min_height=768px; !important; }
 
 
28
  """
29
 
30
+ with gr.Blocks(theme="Nymbo/Nymbo_Theme", fill_width=True, css=css) as demo:
31
+ with gr.Column():
32
+ with gr.Group():
33
+ model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0], allow_custom_value=True)
34
+ model_info = gr.Markdown(value=get_model_info_md(list(loaded_models.keys())[0]), elem_classes="model_info")
35
+ with gr.Group():
36
+ with gr.Accordion("Prompt from Image File", open=False):
37
+ tagger_image = gr.Image(label="Input image", type="pil", sources=["upload", "clipboard"], height=256)
38
+ with gr.Accordion(label="Advanced options", open=False):
39
+ tagger_general_threshold = gr.Slider(label="Threshold", minimum=0.0, maximum=1.0, value=0.3, step=0.01, interactive=True)
40
+ tagger_character_threshold = gr.Slider(label="Character threshold", minimum=0.0, maximum=1.0, value=0.8, step=0.01, interactive=True)
41
+ tagger_tag_type = gr.Radio(label="Convert tags to", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru")
42
+ tagger_recom_prompt = gr.Radio(label="Insert reccomended prompt", choices=["None", "Animagine", "Pony"], value="None", interactive=True)
43
+ tagger_keep_tags = gr.Radio(label="Remove tags leaving only the following", choices=["body", "dress", "all"], value="all")
44
+ tagger_algorithms = gr.CheckboxGroup(["Use WD Tagger", "Use Florence-2-SD3-Long-Captioner"], label="Algorithms", value=["Use WD Tagger"])
45
+ tagger_generate_from_image = gr.Button(value="Generate Tags from Image")
46
+ with gr.Row():
47
+ v2_character = gr.Textbox(label="Character", placeholder="hatsune miku", scale=2)
48
+ v2_series = gr.Textbox(label="Series", placeholder="vocaloid", scale=2)
49
+ random_prompt = gr.Button(value="Extend Prompt 🎲", size="sm", scale=1)
50
+ clear_prompt = gr.Button(value="Clear Prompt 🗑️", size="sm", scale=1)
51
+ prompt = gr.Text(label="Prompt", lines=2, max_lines=8, placeholder="1girl, solo, ...", show_copy_button=True)
52
+ neg_prompt = gr.Text(label="Negative Prompt", lines=1, max_lines=8, placeholder="", visible=False)
53
+ with gr.Accordion("Advanced options", open=False):
54
+ width = gr.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
55
+ height = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
56
+ steps = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
57
+ cfg = gr.Number(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
58
+ with gr.Accordion("Recommended Prompt", open=False):
59
+ recom_prompt_preset = gr.Radio(label="Set Presets", choices=get_recom_prompt_type(), value="Common")
60
  with gr.Row():
61
+ positive_prefix = gr.CheckboxGroup(label="Use Positive Prefix", choices=get_positive_prefix(), value=[])
62
+ positive_suffix = gr.CheckboxGroup(label="Use Positive Suffix", choices=get_positive_suffix(), value=["Common"])
63
+ negative_prefix = gr.CheckboxGroup(label="Use Negative Prefix", choices=get_negative_prefix(), value=[])
64
+ negative_suffix = gr.CheckboxGroup(label="Use Negative Suffix", choices=get_negative_suffix(), value=["Common"])
65
+ with gr.Accordion("Prompt Transformer", open=False):
66
+ v2_rating = gr.Radio(label="Rating", choices=list(V2_RATING_OPTIONS), value="sfw")
67
+ v2_aspect_ratio = gr.Radio(label="Aspect ratio", info="The aspect ratio of the image.", choices=list(V2_ASPECT_RATIO_OPTIONS), value="square", visible=False)
68
+ v2_length = gr.Radio(label="Length", info="The total length of the tags.", choices=list(V2_LENGTH_OPTIONS), value="long")
69
+ 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")
70
+ v2_ban_tags = gr.Textbox(label="Ban tags", info="Tags to ban from the output.", placeholder="alternate costumen, ...", value="censored")
71
+ v2_tag_type = gr.Radio(label="Tag Type", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru", visible=False)
72
+ v2_model = gr.Dropdown(label="Model", choices=list(V2_ALL_MODELS.keys()), value=list(V2_ALL_MODELS.keys())[0])
73
+ v2_copy = gr.Button(value="Copy to clipboard", size="sm", interactive=False)
74
+ image_num = gr.Slider(label="Number of images", minimum=1, maximum=max_images, value=1, step=1, interactive=True, scale=1)
 
 
 
 
 
 
 
 
75
  with gr.Row():
76
+ run_button = gr.Button("Generate Image", scale=6)
77
+ random_button = gr.Button("Random Model 🎲", scale=3)
78
+ stop_button = gr.Button('Stop', interactive=False, scale=1)
79
+ with gr.Column():
80
+ with gr.Group():
81
+ with gr.Row():
82
+ output = [gr.Image(label='', elem_classes="output", type="filepath", format=".png",
83
+ show_download_button=True, show_share_button=False, show_label=False,
84
+ interactive=False, min_width=80, visible=True) for _ in range(max_images)]
85
+ with gr.Group():
86
+ results = gr.Gallery(label="Gallery", elem_classes="gallery", interactive=False, show_download_button=True, show_share_button=False,
87
+ container=True, format="png", object_fit="cover", columns=2, rows=2)
88
+ image_files = gr.Files(label="Download", interactive=False)
89
+ clear_results = gr.Button("Clear Gallery / Download 🗑️")
90
+ with gr.Column():
91
+ examples = gr.Examples(
92
+ examples = [
93
+ ["souryuu asuka langley, 1girl, neon genesis evangelion, plugsuit, pilot suit, red bodysuit, sitting, crossing legs, black eye patch, cat hat, throne, symmetrical, looking down, from bottom, looking at viewer, outdoors"],
94
+ ["sailor moon, magical girl transformation, sparkles and ribbons, soft pastel colors, crescent moon motif, starry night sky background, shoujo manga style"],
95
+ ["kafuu chino, 1girl, solo"],
96
+ ["1girl"],
97
+ ["beautiful sunset"],
98
+ ],
99
+ inputs=[prompt],
100
+ )
101
+ gr.Markdown(
102
+ f"""This demo was created in reference to the following demos.<br>
103
+ [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood),
104
+ [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL),
105
+ [Yntec/Diffusion80XX](https://huggingface.co/spaces/Yntec/Diffusion80XX).
106
+ """
107
  )
108
+ gr.DuplicateButton(value="Duplicate Space")
109
+ gr.Markdown(f"Just a few edits to *model.py* are all it takes to complete your own collection.")
110
+
111
+ gr.on(triggers=[run_button.click, prompt.submit, random_button.click], fn=lambda: gr.update(interactive=True), inputs=None, outputs=stop_button, show_api=False)
112
+ model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)\
113
+ .success(warm_model, [model_name], None, queue=True, show_api=False)
114
+ for i, o in enumerate(output):
115
+ img_i = gr.Number(i, visible=False)
116
+ image_num.change(lambda i, n: gr.update(visible = (i < n)), [img_i, image_num], o, show_api=False)
117
+ gen_event = gr.on(triggers=[run_button.click, prompt.submit],
118
+ fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4: infer_fn(m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4) if (i < n) else None,
119
+ inputs=[img_i, image_num, model_name, prompt, neg_prompt, height, width, steps, cfg,
120
+ positive_prefix, positive_suffix, negative_prefix, negative_suffix],
121
+ outputs=[o], queue=True, show_api=False)
122
+ gen_event2 = gr.on(triggers=[random_button.click],
123
+ fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4: infer_rand_fn(m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4) if (i < n) else None,
124
+ inputs=[img_i, image_num, model_name, prompt, neg_prompt, height, width, steps, cfg,
125
+ positive_prefix, positive_suffix, negative_prefix, negative_suffix],
126
+ outputs=[o], queue=True, show_api=False)
127
+ o.change(save_gallery, [o, results], [results, image_files], show_api=False)
128
+ stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event, gen_event2], show_api=False)
129
+
130
+ clear_prompt.click(lambda: None, None, [prompt], queue=False, show_api=False)
131
+ clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)
132
+ recom_prompt_preset.change(set_recom_prompt_preset, [recom_prompt_preset],
133
+ [positive_prefix, positive_suffix, negative_prefix, negative_suffix], queue=False, show_api=False)
134
+
135
+ random_prompt.click(
136
+ v2_random_prompt, [prompt, v2_series, v2_character, v2_rating, v2_aspect_ratio, v2_length,
137
+ v2_identity, v2_ban_tags, v2_model], [prompt, v2_series, v2_character], show_api=False,
138
+ ).success(
139
+ get_tag_type, [positive_prefix, positive_suffix, negative_prefix, negative_suffix], [v2_tag_type], queue=False, show_api=False
140
+ ).success(
141
+ convert_danbooru_to_e621_prompt, [prompt, v2_tag_type], [prompt], queue=False, show_api=False,
142
+ )
143
+ tagger_generate_from_image.click(
144
+ lambda: ("", "", ""), None, [v2_series, v2_character, prompt], queue=False, show_api=False,
145
+ ).success(
146
+ predict_tags_wd,
147
+ [tagger_image, prompt, tagger_algorithms, tagger_general_threshold, tagger_character_threshold],
148
+ [v2_series, v2_character, prompt, v2_copy],
149
+ show_api=False,
150
+ ).success(
151
+ predict_tags_fl2_sd3, [tagger_image, prompt, tagger_algorithms], [prompt], show_api=False,
152
+ ).success(
153
+ remove_specific_prompt, [prompt, tagger_keep_tags], [prompt], queue=False, show_api=False,
154
+ ).success(
155
+ convert_danbooru_to_e621_prompt, [prompt, tagger_tag_type], [prompt], queue=False, show_api=False,
156
+ ).success(
157
+ insert_recom_prompt, [prompt, neg_prompt, tagger_recom_prompt], [prompt, neg_prompt], queue=False, show_api=False,
158
+ ).success(
159
+ compose_prompt_to_copy, [v2_character, v2_series, prompt], [prompt], queue=False, show_api=False,
160
+ )
161
 
162
+ demo.queue()
163
+ demo.launch()