HARRY07979 commited on
Commit
46b5bb6
·
verified ·
1 Parent(s): be4a63b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -68
app.py CHANGED
@@ -1,27 +1,48 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
  import torch
 
 
8
 
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  MAX_IMAGE_SIZE = 1024
22
 
 
 
 
 
 
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def infer(
26
  prompt,
27
  negative_prompt,
@@ -31,32 +52,60 @@ def infer(
31
  height,
32
  guidance_scale,
33
  num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
  ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
 
39
- generator = torch.Generator().manual_seed(seed)
40
 
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
 
51
- return image, seed
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
 
 
60
  css = """
61
  #col-container {
62
  margin: 0 auto;
@@ -66,18 +115,17 @@ css = """
66
 
67
  with gr.Blocks(css=css) as demo:
68
  with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
 
71
  with gr.Row():
72
  prompt = gr.Text(
73
  label="Prompt",
74
  show_label=False,
75
  max_lines=1,
76
- placeholder="Enter your prompt",
77
  container=False,
78
  )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
 
82
  result = gr.Image(label="Result", show_label=False)
83
 
@@ -86,54 +134,41 @@ with gr.Blocks(css=css) as demo:
86
  label="Negative prompt",
87
  max_lines=1,
88
  placeholder="Enter a negative prompt",
89
- visible=False,
90
  )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
 
102
  with gr.Row():
103
  width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
  )
110
-
111
  height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
  )
118
 
119
  with gr.Row():
120
  guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
  )
127
-
128
  num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
  )
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  gr.on(
138
  triggers=[run_button.click, prompt.submit],
139
  fn=infer,
@@ -146,6 +181,7 @@ with gr.Blocks(css=css) as demo:
146
  height,
147
  guidance_scale,
148
  num_inference_steps,
 
149
  ],
150
  outputs=[result, seed],
151
  )
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ from datetime import datetime
5
 
 
 
6
  import torch
7
+ from diffusers import DiffusionPipeline
8
+ from optimum.intel.openvino import OVStableDiffusionPipeline
9
 
10
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
 
11
 
12
  MAX_SEED = np.iinfo(np.int32).max
13
  MAX_IMAGE_SIZE = 1024
14
 
15
+ # Chọn mô hình từ dropdown
16
+ model_choices = {
17
+ "SD‑Turbo (stabilityai/sd-turbo)": "stabilityai/sd-turbo",
18
+ "Stable Diffusion 1.5 (runwayml/stable-diffusion-1.5)": "runwayml/stable-diffusion-1.5",
19
+ "OpenVINO version (HARRY07979/sd-v1-5-openvino)": "HARRY07979/sd-v1-5-openvino",
20
+ }
21
 
22
+ # Biến toàn cục để lưu model đang dùng
23
+ current_model_id = None
24
+ pipe = None
25
+
26
+ # ---------------------------------------------------------
27
+ # Hàm load mô hình
28
+ def load_pipeline(model_id):
29
+ print(f"[INFO] Loading model: {model_id}")
30
+ if "openvino" in model_id.lower():
31
+ # Mô hình OpenVINO dùng OVStableDiffusionPipeline
32
+ pipe = OVStableDiffusionPipeline.from_pretrained(model_id)
33
+ pipe.reshape(batch_size=1, height=512, width=512, num_images_per_prompt=1)
34
+ pipe.compile()
35
+ else:
36
+ if torch.cuda.is_available():
37
+ torch_dtype = torch.float16
38
+ else:
39
+ torch_dtype = torch.float32
40
+ pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch_dtype)
41
+ pipe = pipe.to(device)
42
+ return pipe
43
+
44
+ # ---------------------------------------------------------
45
+ # Hàm infer
46
  def infer(
47
  prompt,
48
  negative_prompt,
 
52
  height,
53
  guidance_scale,
54
  num_inference_steps,
55
+ model_selector,
56
  ):
57
+ global pipe, current_model_id
 
58
 
59
+ selected_model_id = model_choices[model_selector]
60
 
61
+ # Nếu đổi mô hình → load lại
62
+ if selected_model_id != current_model_id or pipe is None:
63
+ pipe = load_pipeline(selected_model_id)
64
+ current_model_id = selected_model_id
 
 
 
 
 
65
 
66
+ if randomize_seed:
67
+ seed = random.randint(0, MAX_SEED)
68
 
69
+ # Thời gian bắt đầu
70
+ t0 = datetime.now()
71
+
72
+ # Gọi pipeline theo loại
73
+ if "openvino" in selected_model_id.lower():
74
+ image = pipe(
75
+ prompt=prompt,
76
+ negative_prompt=negative_prompt,
77
+ guidance_scale=guidance_scale,
78
+ num_inference_steps=num_inference_steps,
79
+ ).images[0]
80
+ else:
81
+ generator = torch.Generator().manual_seed(seed)
82
+ image = pipe(
83
+ prompt=prompt,
84
+ negative_prompt=negative_prompt,
85
+ guidance_scale=guidance_scale,
86
+ num_inference_steps=num_inference_steps,
87
+ width=width,
88
+ height=height,
89
+ generator=generator,
90
+ ).images[0]
91
+
92
+ # Thời gian kết thúc
93
+ t1 = datetime.now()
94
+ delta = t1 - t0
95
+ total_seconds = delta.total_seconds()
96
+ days = delta.days
97
+ hours, rem = divmod(delta.seconds, 3600)
98
+ minutes, seconds = divmod(rem, 60)
99
+ microsecs = delta.microseconds
100
+
101
+ print(f"Start time: {t0.isoformat(sep=' ')}")
102
+ print(f"End time : {t1.isoformat(sep=' ')}")
103
+ print(f"Elapsed : {days}d {hours}h {minutes}m {seconds}s {microsecs}µs")
104
+ print(f"Total time: {total_seconds:.3f} seconds")
105
 
106
+ return image, seed
 
 
 
 
107
 
108
+ # ---------------------------------------------------------
109
  css = """
110
  #col-container {
111
  margin: 0 auto;
 
115
 
116
  with gr.Blocks(css=css) as demo:
117
  with gr.Column(elem_id="col-container"):
118
+ gr.Markdown("# Text-to-Image Generator (Supports SD-Turbo / SD 1.5 / OpenVINO)")
119
 
120
  with gr.Row():
121
  prompt = gr.Text(
122
  label="Prompt",
123
  show_label=False,
124
  max_lines=1,
125
+ placeholder="Enter your prompt here...",
126
  container=False,
127
  )
128
+ run_button = gr.Button("Generate", scale=0, variant="primary")
 
129
 
130
  result = gr.Image(label="Result", show_label=False)
131
 
 
134
  label="Negative prompt",
135
  max_lines=1,
136
  placeholder="Enter a negative prompt",
 
137
  )
138
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
 
 
 
 
 
 
 
 
139
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
140
 
141
  with gr.Row():
142
  width = gr.Slider(
143
+ label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=512
 
 
 
 
144
  )
 
145
  height = gr.Slider(
146
+ label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=512
 
 
 
 
147
  )
148
 
149
  with gr.Row():
150
  guidance_scale = gr.Slider(
151
+ label="Guidance scale", minimum=0.0, maximum=20.0, step=0.1, value=7.5
 
 
 
 
152
  )
 
153
  num_inference_steps = gr.Slider(
154
+ label="Inference steps", minimum=1, maximum=100, step=1, value=25
 
 
 
 
155
  )
156
 
157
+ model_selector = gr.Dropdown(
158
+ label="Select Model",
159
+ choices=list(model_choices.keys()),
160
+ value="SD‑Turbo (stabilityai/sd-turbo)",
161
+ )
162
+
163
+ gr.Examples(
164
+ examples=[
165
+ "Astronaut in a jungle, detailed, 8k",
166
+ "A cyberpunk dragon flying through neon city",
167
+ "A fantasy landscape with floating islands",
168
+ ],
169
+ inputs=[prompt],
170
+ )
171
+
172
  gr.on(
173
  triggers=[run_button.click, prompt.submit],
174
  fn=infer,
 
181
  height,
182
  guidance_scale,
183
  num_inference_steps,
184
+ model_selector,
185
  ],
186
  outputs=[result, seed],
187
  )