Yntec commited on
Commit
e8b84db
·
verified ·
1 Parent(s): dd1315b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -161
app.py CHANGED
@@ -1,161 +1,161 @@
1
- import gradio as gr
2
- import os
3
- import sys
4
- from pathlib import Path
5
- from all_models import models
6
- from externalmod import gr_Interface_load
7
- from prompt_extend import extend_prompt
8
- from random import randint
9
- import asyncio
10
- from threading import RLock
11
- lock = RLock()
12
- HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # If private or gated models aren't used, ENV setting is unnecessary.
13
-
14
- inference_timeout = 300
15
- MAX_SEED = 2**32-1
16
- current_model = models[0]
17
- text_gen1 = extend_prompt
18
-
19
- models2 = [gr_Interface_load(f"models/{m}", live=False, preprocess=True, postprocess=False, hf_token=HF_TOKEN) for m in models]
20
-
21
- def text_it1(inputs, text_gen1=text_gen1):
22
- go_t1 = text_gen1(inputs)
23
- return(go_t1)
24
-
25
- def set_model(current_model):
26
- current_model = models[current_model]
27
- return gr.update(label=(f"{current_model}"))
28
-
29
- def send_it1(inputs, model_choice, neg_input, height, width, steps, cfg, seed):
30
- output1 = gen_fn(model_choice, inputs, neg_input, height, width, steps, cfg, seed)
31
- return (output1)
32
-
33
- # https://huggingface.co/docs/api-inference/detailed_parameters
34
- # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
35
- async def infer(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1, timeout=inference_timeout):
36
- from pathlib import Path
37
- kwargs = {}
38
- if height is not None and height >= 256: kwargs["height"] = height
39
- if width is not None and width >= 256: kwargs["width"] = width
40
- if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
41
- if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
42
- noise = ""
43
- if seed >= 0: kwargs["seed"] = seed
44
- else:
45
- rand = randint(1, 500)
46
- for i in range(rand):
47
- noise += " "
48
- task = asyncio.create_task(asyncio.to_thread(models2[model_index].fn,
49
- prompt=f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
50
- await asyncio.sleep(0)
51
- try:
52
- result = await asyncio.wait_for(task, timeout=timeout)
53
- except asyncio.TimeoutError as e:
54
- print(e)
55
- print(f"Task timed out: {models2[model_index]}")
56
- if not task.done(): task.cancel()
57
- result = None
58
- raise Exception(f"Task timed out: {models2[model_index]}")
59
- except Exception as e:
60
- print(e)
61
- if not task.done(): task.cancel()
62
- result = None
63
- raise Exception(e)
64
- if task.done() and result is not None and not isinstance(result, tuple):
65
- with lock:
66
- png_path = "image.png"
67
- result.save(png_path)
68
- image = str(Path(png_path).resolve())
69
- return image
70
- return None
71
-
72
- def gen_fn(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1):
73
- try:
74
- loop = asyncio.new_event_loop()
75
- result = loop.run_until_complete(infer(model_index, prompt, nprompt,
76
- height, width, steps, cfg, seed, inference_timeout))
77
- except (Exception, asyncio.CancelledError) as e:
78
- print(e)
79
- print(f"Task aborted: {models2[model_index]}")
80
- result = None
81
- raise gr.Error(f"Task aborted: {models2[model_index]}, Error: {e}")
82
- finally:
83
- loop.close()
84
- return result
85
-
86
- css="""
87
- .gradio-container {background-image: linear-gradient(#254150, #1e2f40, #182634) !important;
88
- color: #ffaa66 !important; font-family: 'IBM Plex Sans', sans-serif !important;}
89
- h1 {font-size: 6em; color: #ffc99f; margin-top: 30px; margin-bottom: 30px;
90
- text-shadow: 3px 3px 0 rgba(0, 0, 0, 1) !important;}
91
- h3 {color: #ffc99f; !important;}
92
- h4 {display: inline-block; color: #ffffff !important;}
93
- .wrapper img {font-size: 98% !important; white-space: nowrap !important; text-align: center !important;
94
- display: inline-block !important; color: #ffffff !important;}
95
- .wrapper {color: #ffffff !important;}
96
- .gr-box {background-image: linear-gradient(#182634, #1e2f40, #254150) !important;
97
- border-top-color: #000000 !important; border-right-color: #ffffff !important;
98
- border-bottom-color: #ffffff !important; border-left-color: #000000 !important;}
99
- """
100
-
101
- with gr.Blocks(theme='John6666/YntecDark', fill_width=True, css=css) as myface:
102
- gr.HTML(f"""
103
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
104
- <div class="center"><h1>Blitz Diffusion</h1></div>
105
- <p style="margin-bottom: 1px; color: #ffaa66;">
106
- <h3>{int(len(models))} Stable Diffusion models, but why? For your enjoyment!</h3></p>
107
- <br><div class="wrapper">9.3 <img src="https://huggingface.co/Yntec/DucHaitenLofi/resolve/main/NEW.webp" alt="NEW!" style="width:32px;height:16px;">This has become a legacy backup copy of old <u><a href="https://huggingface.co/spaces/Yntec/ToyWorld">ToyWorld</a></u>'s UI! Newer models added dailty over there! 25 new models since last update!</div>
108
- <p style="margin-bottom: 1px; font-size: 98%">
109
- <br><h4>If a model is already loaded each new image takes less than <b>10</b> seconds to generate!</h4></p>
110
- <p style="margin-bottom: 1px; color: #ffffff;">
111
- <br><div class="wrapper">Generate 6 images from 1 prompt at the <u><a href="https://huggingface.co/spaces/Yntec/PrintingPress">PrintingPress</a></u>, and use 6 different models at <u><a href="https://huggingface.co/spaces/Yntec/diffusion80xx">Huggingface Diffusion!</a></u>!
112
- </p></p></div>
113
- """, elem_classes="gr-box")
114
- with gr.Row():
115
- with gr.Column(scale=100):
116
- # Model selection dropdown
117
- model_name1 = gr.Dropdown(label="Select Model", choices=[m for m in models], type="index",
118
- value=current_model, interactive=True, elem_classes=["gr-box", "gr-input"])
119
- with gr.Row():
120
- with gr.Column(scale=100):
121
- with gr.Group():
122
- magic1 = gr.Textbox(label="Your Prompt", lines=4, elem_classes=["gr-box", "gr-input"]) #Positive
123
- with gr.Accordion("Advanced", open=False, visible=True):
124
- neg_input = gr.Textbox(label='Negative prompt', lines=1, elem_classes=["gr-box", "gr-input"])
125
- with gr.Row():
126
- width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
127
- height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
128
- with gr.Row():
129
- steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0, elem_classes=["gr-box", "gr-input"])
130
- cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0, elem_classes=["gr-box", "gr-input"])
131
- seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1, elem_classes=["gr-box", "gr-input"])
132
- run = gr.Button("Generate Image", variant="primary", elem_classes="gr-button")
133
-
134
- with gr.Row():
135
- with gr.Column():
136
- output1 = gr.Image(label=(f"{current_model}"), show_download_button=True,
137
- interactive=False, show_share_button=False, format=".png", elem_classes="gr-box")
138
-
139
- with gr.Row():
140
- with gr.Column(scale=50):
141
- input_text=gr.Textbox(label="Use this box to extend an idea automagically, by typing some words and clicking Extend Idea", lines=2, elem_classes=["gr-box", "gr-input"])
142
- see_prompts=gr.Button("Extend Idea -> overwrite the contents of the `Your Prompt´ box above", variant="primary", elem_classes="gr-button")
143
- use_short=gr.Button("Copy the contents of this box to the `Your Prompt´ box above", variant="primary", elem_classes="gr-button")
144
- def short_prompt(inputs):
145
- return (inputs)
146
-
147
- model_name1.change(set_model, inputs=model_name1, outputs=[output1])
148
- gr.on(
149
- triggers=[run.click, magic1.submit],
150
- fn=send_it1,
151
- inputs=[magic1, model_name1, neg_input, height, width, steps, cfg, seed],
152
- outputs=[output1],
153
- concurrency_limit=None,
154
- queue=False,
155
- )
156
- use_short.click(short_prompt, inputs=[input_text], outputs=magic1, queue=False)
157
- see_prompts.click(text_it1, inputs=[input_text], outputs=magic1, queue=False)
158
-
159
- myface.queue(default_concurrency_limit=200, max_size=200)
160
- myface.launch(show_api=False, max_threads=400)
161
- # https://github.com/gradio-app/gradio/issues/6339
 
1
+ import gradio as gr
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+ from all_models import models
6
+ from externalmod import gr_Interface_load
7
+ from prompt_extend import extend_prompt
8
+ from random import randint
9
+ import asyncio
10
+ from threading import RLock
11
+ lock = RLock()
12
+ HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # If private or gated models aren't used, ENV setting is unnecessary.
13
+
14
+ inference_timeout = 300
15
+ MAX_SEED = 2**32-1
16
+ current_model = models[0]
17
+ text_gen1 = extend_prompt
18
+
19
+ models2 = [gr_Interface_load(f"models/{m}", live=False, preprocess=True, postprocess=False, hf_token=HF_TOKEN) for m in models]
20
+
21
+ def text_it1(inputs, text_gen1=text_gen1):
22
+ go_t1 = text_gen1(inputs)
23
+ return(go_t1)
24
+
25
+ def set_model(current_model):
26
+ current_model = models[current_model]
27
+ return gr.update(label=(f"{current_model}"))
28
+
29
+ def send_it1(inputs, model_choice, neg_input, height, width, steps, cfg, seed):
30
+ output1 = gen_fn(model_choice, inputs, neg_input, height, width, steps, cfg, seed)
31
+ return (output1)
32
+
33
+ # https://huggingface.co/docs/api-inference/detailed_parameters
34
+ # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
35
+ async def infer(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1, timeout=inference_timeout):
36
+ from pathlib import Path
37
+ kwargs = {}
38
+ if height is not None and height >= 256: kwargs["height"] = height
39
+ if width is not None and width >= 256: kwargs["width"] = width
40
+ if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
41
+ if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
42
+ noise = ""
43
+ if seed >= 0: kwargs["seed"] = seed
44
+ else:
45
+ rand = randint(1, 500)
46
+ for i in range(rand):
47
+ noise += " "
48
+ task = asyncio.create_task(asyncio.to_thread(models2[model_index].fn,
49
+ prompt=f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
50
+ await asyncio.sleep(0)
51
+ try:
52
+ result = await asyncio.wait_for(task, timeout=timeout)
53
+ except asyncio.TimeoutError as e:
54
+ print(e)
55
+ print(f"Task timed out: {models2[model_index]}")
56
+ if not task.done(): task.cancel()
57
+ result = None
58
+ raise Exception(f"Task timed out: {models2[model_index]}")
59
+ except Exception as e:
60
+ print(e)
61
+ if not task.done(): task.cancel()
62
+ result = None
63
+ raise Exception(e)
64
+ if task.done() and result is not None and not isinstance(result, tuple):
65
+ with lock:
66
+ png_path = "image.png"
67
+ result.save(png_path)
68
+ image = str(Path(png_path).resolve())
69
+ return image
70
+ return None
71
+
72
+ def gen_fn(model_index, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1):
73
+ try:
74
+ loop = asyncio.new_event_loop()
75
+ result = loop.run_until_complete(infer(model_index, prompt, nprompt,
76
+ height, width, steps, cfg, seed, inference_timeout))
77
+ except (Exception, asyncio.CancelledError) as e:
78
+ print(e)
79
+ print(f"Task aborted: {models2[model_index]}")
80
+ result = None
81
+ raise gr.Error(f"Task aborted: {models2[model_index]}, Error: {e}")
82
+ finally:
83
+ loop.close()
84
+ return result
85
+
86
+ css="""
87
+ .gradio-container {background-image: linear-gradient(#254150, #1e2f40, #182634) !important;
88
+ color: #ffaa66 !important; font-family: 'IBM Plex Sans', sans-serif !important;}
89
+ h1 {font-size: 6em; color: #ffc99f; margin-top: 30px; margin-bottom: 30px;
90
+ text-shadow: 3px 3px 0 rgba(0, 0, 0, 1) !important;}
91
+ h3 {color: #ffc99f; !important;}
92
+ h4 {display: inline-block; color: #ffffff !important;}
93
+ .wrapper img {font-size: 98% !important; white-space: nowrap !important; text-align: center !important;
94
+ display: inline-block !important; color: #ffffff !important;}
95
+ .wrapper {color: #ffffff !important;}
96
+ .gr-box {background-image: linear-gradient(#182634, #1e2f40, #254150) !important;
97
+ border-top-color: #000000 !important; border-right-color: #ffffff !important;
98
+ border-bottom-color: #ffffff !important; border-left-color: #000000 !important;}
99
+ """
100
+
101
+ with gr.Blocks(theme='Yntec/YntecDarkTheme', fill_width=True, css=css) as myface:
102
+ gr.HTML(f"""
103
+ <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
104
+ <div class="center"><h1>Blitz Diffusion</h1></div>
105
+ <p style="margin-bottom: 1px; color: #ffaa66;">
106
+ <h3>{int(len(models))} Stable Diffusion models, but why? For your enjoyment!</h3></p>
107
+ <br><div class="wrapper">9.3 <img src="https://huggingface.co/Yntec/DucHaitenLofi/resolve/main/NEW.webp" alt="NEW!" style="width:32px;height:16px;">This has become a legacy backup copy of old <u><a href="https://huggingface.co/spaces/Yntec/ToyWorld">ToyWorld</a></u>'s UI! Newer models added dailty over there! 25 new models since last update!</div>
108
+ <p style="margin-bottom: 1px; font-size: 98%">
109
+ <br><h4>If a model is already loaded each new image takes less than <b>10</b> seconds to generate!</h4></p>
110
+ <p style="margin-bottom: 1px; color: #ffffff;">
111
+ <br><div class="wrapper">Generate 6 images from 1 prompt at the <u><a href="https://huggingface.co/spaces/Yntec/PrintingPress">PrintingPress</a></u>, and use 6 different models at <u><a href="https://huggingface.co/spaces/Yntec/diffusion80xx">Huggingface Diffusion!</a></u>!
112
+ </p></p></div>
113
+ """, elem_classes="gr-box")
114
+ with gr.Row():
115
+ with gr.Column(scale=100):
116
+ # Model selection dropdown
117
+ model_name1 = gr.Dropdown(label="Select Model", choices=[m for m in models], type="index",
118
+ value=current_model, interactive=True, elem_classes=["gr-box", "gr-input"])
119
+ with gr.Row():
120
+ with gr.Column(scale=100):
121
+ with gr.Group():
122
+ magic1 = gr.Textbox(label="Your Prompt", lines=4, elem_classes=["gr-box", "gr-input"]) #Positive
123
+ with gr.Accordion("Advanced", open=False, visible=True):
124
+ neg_input = gr.Textbox(label='Negative prompt', lines=1, elem_classes=["gr-box", "gr-input"])
125
+ with gr.Row():
126
+ width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
127
+ height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0, elem_classes=["gr-box", "gr-input"])
128
+ with gr.Row():
129
+ steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0, elem_classes=["gr-box", "gr-input"])
130
+ cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0, elem_classes=["gr-box", "gr-input"])
131
+ seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1, elem_classes=["gr-box", "gr-input"])
132
+ run = gr.Button("Generate Image", variant="primary", elem_classes="gr-button")
133
+
134
+ with gr.Row():
135
+ with gr.Column():
136
+ output1 = gr.Image(label=(f"{current_model}"), show_download_button=True,
137
+ interactive=False, show_share_button=False, format=".png", elem_classes="gr-box")
138
+
139
+ with gr.Row():
140
+ with gr.Column(scale=50):
141
+ input_text=gr.Textbox(label="Use this box to extend an idea automagically, by typing some words and clicking Extend Idea", lines=2, elem_classes=["gr-box", "gr-input"])
142
+ see_prompts=gr.Button("Extend Idea -> overwrite the contents of the `Your Prompt´ box above", variant="primary", elem_classes="gr-button")
143
+ use_short=gr.Button("Copy the contents of this box to the `Your Prompt´ box above", variant="primary", elem_classes="gr-button")
144
+ def short_prompt(inputs):
145
+ return (inputs)
146
+
147
+ model_name1.change(set_model, inputs=model_name1, outputs=[output1])
148
+ gr.on(
149
+ triggers=[run.click, magic1.submit],
150
+ fn=send_it1,
151
+ inputs=[magic1, model_name1, neg_input, height, width, steps, cfg, seed],
152
+ outputs=[output1],
153
+ concurrency_limit=None,
154
+ queue=False,
155
+ )
156
+ use_short.click(short_prompt, inputs=[input_text], outputs=magic1, queue=False)
157
+ see_prompts.click(text_it1, inputs=[input_text], outputs=magic1, queue=False)
158
+
159
+ myface.queue(default_concurrency_limit=200, max_size=200)
160
+ myface.launch(show_api=False, max_threads=400)
161
+ # https://github.com/gradio-app/gradio/issues/6339