burhansyam commited on
Commit
ce820b3
·
verified ·
1 Parent(s): e33dd82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -104
app.py CHANGED
@@ -2,19 +2,9 @@ import os
2
  import gradio as gr
3
  from random import randint
4
  from all_models import models
5
- import uuid
6
- from fastapi.staticfiles import StaticFiles
7
- from PIL import Image
8
- import requests
9
- from io import BytesIO
10
- import tempfile
11
 
12
  css_code = os.getenv("DazDinGo_CSS")
13
 
14
- # Create a dedicated directory for images
15
- IMAGE_DIR = "/tmp/flux_images"
16
- os.makedirs(IMAGE_DIR, exist_ok=True)
17
-
18
  def load_fn(models):
19
  global models_load
20
  models_load = {}
@@ -28,108 +18,58 @@ def load_fn(models):
28
 
29
  load_fn(models)
30
 
31
- def process_image_output(image_data):
32
- """Handle various image output formats and save to temp directory"""
33
- if image_data is None:
34
- return None
35
-
36
- # If it's already a file path that exists, use it
37
- if isinstance(image_data, str) and os.path.isfile(image_data):
38
- return image_data
39
-
40
- # If it's a URL, download it
41
- if isinstance(image_data, str) and image_data.startswith(('http://', 'https://')):
42
- try:
43
- response = requests.get(image_data)
44
- img = Image.open(BytesIO(response.content))
45
- except:
46
- return None
47
- else:
48
- # Assume it's a PIL Image or numpy array
49
- img = image_data
50
-
51
- # Save to temp file
52
- filename = f"{uuid.uuid4()}.jpg"
53
- filepath = os.path.join(IMAGE_DIR, filename)
54
-
55
- try:
56
- if isinstance(img, Image.Image):
57
- img.save(filepath)
58
- else:
59
- # Handle numpy arrays or other formats
60
- Image.fromarray(img).save(filepath)
61
- return filepath
62
- except Exception as e:
63
- print(f"Error saving image: {e}")
64
- return None
65
 
66
  def gen_fn(model_str, prompt):
67
  if model_str == 'NA':
68
  return None
69
-
70
  noise = str(randint(0, 4294967296))
71
  klir = '| ultra detail, ultra elaboration, ultra quality, perfect'
72
- result = models_load[model_str](f'{prompt} {klir} {noise}')
73
-
74
- if isinstance(result, list):
75
- return [process_image_output(img) for img in result if img is not None]
76
- return process_image_output(result)
77
 
78
- def create_interface():
79
- with gr.Blocks(css=css_code) as demo:
80
- with gr.Row():
81
- with gr.Column(scale=4):
82
- txt_input = gr.Textbox(
83
- label='Your prompt:',
84
- lines=4,
85
- container=False,
86
- elem_id="custom_textbox",
87
- placeholder="Prompt"
88
- )
89
-
90
- with gr.Column(scale=1):
91
- gen_button = gr.Button('Generate images', elem_id="custom_gen_button")
92
- stop_button = gr.Button('Stop', variant='secondary', interactive=False, elem_id="custom_stop_button")
93
 
94
- with gr.Row():
95
- output = gr.Gallery(
96
- label="Generated Images",
97
- columns=3,
98
- height="auto",
99
- object_fit="contain",
100
- show_download_button=True,
101
- elem_id="custom_gallery"
102
- )
103
 
104
- model_selector = gr.Dropdown(
105
- models,
106
- label="Select LoRA Model",
107
- value=models[0] if models else None,
108
- multiselect=False,
109
- interactive=True,
110
- elem_id="custom_dropdown"
111
- )
112
-
113
- gen_event = gen_button.click(
114
- fn=gen_fn,
115
- inputs=[model_selector, txt_input],
116
- outputs=output
117
- )
118
-
119
- stop_button.click(
120
- fn=lambda: [gr.Button(interactive=True), gr.Button(interactive=False)],
121
- inputs=None,
122
- outputs=[gen_button, stop_button],
123
- cancels=[gen_event]
124
- )
125
-
126
- return demo
127
-
128
- demo = create_interface()
129
 
130
- # Configure static files serving
131
- app = demo.app
132
- app.mount("/file", StaticFiles(directory=IMAGE_DIR), name="static")
133
 
134
- if __name__ == "__main__":
135
- demo.queue(concurrency_count=50).launch()
 
2
  import gradio as gr
3
  from random import randint
4
  from all_models import models
 
 
 
 
 
 
5
 
6
  css_code = os.getenv("DazDinGo_CSS")
7
 
 
 
 
 
8
  def load_fn(models):
9
  global models_load
10
  models_load = {}
 
18
 
19
  load_fn(models)
20
 
21
+ num_models = len(models)
22
+ default_models = models[:num_models]
23
+
24
+ def extend_choices(choices):
25
+ return choices + (num_models - len(choices)) * ['NA']
26
+
27
+ def update_imgbox(choices):
28
+ choices_plus = extend_choices(choices)
29
+ return [gr.Image(None, label=m, visible=(m != 'NA'), elem_id="custom_image") for m in choices_plus]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  def gen_fn(model_str, prompt):
32
  if model_str == 'NA':
33
  return None
 
34
  noise = str(randint(0, 4294967296))
35
  klir = '| ultra detail, ultra elaboration, ultra quality, perfect'
36
+ return models_load[model_str](f'{prompt} {klir} {noise}')
 
 
 
 
37
 
38
+ def make_me():
39
+ with gr.Row():
40
+ with gr.Column(scale=4):
41
+ txt_input = gr.Textbox(label='Your prompt:', lines=4, container=False, elem_id="custom_textbox", placeholder="Prompt", height=250)
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ with gr.Column(scale=1):
44
+ gen_button = gr.Button('Generate images', elem_id="custom_gen_button")
45
+ stop_button = gr.Button('Stop', variant='secondary', interactive=False, elem_id="custom_stop_button")
 
 
 
 
 
 
46
 
47
+ def on_generate_click():
48
+ return gr.Button('Generate images', elem_id="custom_gen_button"), gr.Button('Stop', variant='secondary', interactive=True, elem_id="custom_stop_button")
49
+
50
+ def on_stop_click():
51
+ return gr.Button('Generate images', elem_id="custom_gen_button"), gr.Button('Stop', variant='secondary', interactive=False, elem_id="custom_stop_button")
52
+
53
+ gen_button.click(on_generate_click, inputs=None, outputs=[gen_button, stop_button])
54
+ stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button])
55
+
56
+ with gr.Row():
57
+ output = [gr.Image(label=m, width=512, max_height=768, elem_id="custom_image", show_label=True, interactive=False, show_share_button=False) for m in default_models]
58
+ current_models = [gr.Textbox(m, visible=False) for m in default_models]
59
+ for m, o in zip(current_models, output):
60
+ gen_event = gen_button.click(gen_fn, [m, txt_input], o)
61
+ stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button], cancels=[gen_event])
62
+
63
+ with gr.Accordion('Model selection', elem_id="custom_accordion"):
64
+ model_choice = gr.CheckboxGroup(models, label=f'{num_models} different models selected', value=default_models, interactive=True, elem_id="custom_checkbox_group")
65
+ model_choice.change(update_imgbox, model_choice, output)
66
+ model_choice.change(extend_choices, model_choice, current_models)
67
+
68
+ with gr.Row():
69
+ gr.HTML("")
 
 
70
 
71
+ with gr.Blocks(css=css_code) as demo:
72
+ make_me()
 
73
 
74
+ demo.queue(concurrency_count=50)
75
+ demo.launch()