HARRY07979 commited on
Commit
6f6de6b
·
verified ·
1 Parent(s): 79fee99

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -70
app.py CHANGED
@@ -1,46 +1,27 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
4
  from diffusers import DiffusionPipeline
5
  import torch
6
- import os
7
 
8
- # Thiết lập thiết bị và kiểu dữ liệu
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stable-diffusion-v1-5/stable-diffusion-v1-5" # hình Segmind/Tiny-SD
11
 
12
  if torch.cuda.is_available():
13
- dtype = torch.float16
14
  else:
15
- dtype = torch.float32
16
-
17
- # Thư mục cache để lưu trữ mô hình
18
- cache_dir = "./cache"
19
- os.makedirs(cache_dir, exist_ok=True)
20
-
21
- # Chỉ tải mô hình một lần
22
- pipe = None
23
-
24
- def load_model():
25
- global pipe
26
- if pipe is None:
27
- # Kiểm tra xem mô hình đã tồn tại trong cache chưa
28
- if not os.path.exists(os.path.join(cache_dir, "model_index.json")):
29
- print(f"Tải mô hình từ remote repository: {model_repo_id}")
30
- pipe = DiffusionPipeline.from_pretrained(
31
- model_repo_id,
32
- dtype=dtype, # Thay vì torch_dtype
33
- cache_dir=cache_dir
34
- )
35
- else:
36
- print("Tải mô hình từ local cache")
37
- pipe = DiffusionPipeline.from_pretrained(
38
- cache_dir,
39
- dtype=dtype
40
- )
41
- pipe.to(device)
42
- return pipe
43
 
 
 
 
 
 
44
  def infer(
45
  prompt,
46
  negative_prompt,
@@ -52,30 +33,24 @@ def infer(
52
  num_inference_steps,
53
  progress=gr.Progress(track_tqdm=True),
54
  ):
55
- # Đảm bảo mô hình đã được tải
56
- pipe = load_model()
57
-
58
  if randomize_seed:
59
- seed = random.randint(0, np.iinfo(np.int32).max)
60
-
61
- generator = torch.Generator(device=device).manual_seed(seed)
62
-
63
- try:
64
- image = pipe(
65
- prompt=prompt,
66
- negative_prompt=negative_prompt,
67
- guidance_scale=guidance_scale,
68
- num_inference_steps=num_inference_steps,
69
- width=width,
70
- height=height,
71
- generator=generator,
72
- ).images[0]
73
-
74
- return image, seed
75
- except Exception as e:
76
- return f"Error: {e}", seed
77
-
78
- # Examples
79
  examples = [
80
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
81
  "An astronaut riding a green horse",
@@ -91,7 +66,7 @@ css = """
91
 
92
  with gr.Blocks(css=css) as demo:
93
  with gr.Column(elem_id="col-container"):
94
- gr.Markdown("# StaGen: Make your dreams come true")
95
 
96
  with gr.Row():
97
  prompt = gr.Text(
@@ -102,7 +77,7 @@ with gr.Blocks(css=css) as demo:
102
  container=False,
103
  )
104
 
105
- run_button = gr.Button("Generate", scale=0, variant="primary")
106
 
107
  result = gr.Image(label="Result", show_label=False)
108
 
@@ -117,7 +92,7 @@ with gr.Blocks(css=css) as demo:
117
  seed = gr.Slider(
118
  label="Seed",
119
  minimum=0,
120
- maximum=np.iinfo(np.int32).max,
121
  step=1,
122
  value=0,
123
  )
@@ -128,17 +103,17 @@ with gr.Blocks(css=css) as demo:
128
  width = gr.Slider(
129
  label="Width",
130
  minimum=256,
131
- maximum=1024,
132
  step=32,
133
- value=1024,
134
  )
135
 
136
  height = gr.Slider(
137
  label="Height",
138
  minimum=256,
139
- maximum=1024,
140
  step=32,
141
- value=1024,
142
  )
143
 
144
  with gr.Row():
@@ -147,7 +122,7 @@ with gr.Blocks(css=css) as demo:
147
  minimum=0.0,
148
  maximum=10.0,
149
  step=0.1,
150
- value=5.0,
151
  )
152
 
153
  num_inference_steps = gr.Slider(
@@ -155,13 +130,12 @@ with gr.Blocks(css=css) as demo:
155
  minimum=1,
156
  maximum=50,
157
  step=1,
158
- value=35,
159
  )
160
 
161
  gr.Examples(examples=examples, inputs=[prompt])
162
-
163
- # Kết nối nút "Generate" với hàm infer
164
- run_button.click(
165
  fn=infer,
166
  inputs=[
167
  prompt,
@@ -173,9 +147,8 @@ with gr.Blocks(css=css) as demo:
173
  guidance_scale,
174
  num_inference_steps,
175
  ],
176
- outputs=[result, seed], # Cập nhật giá trị của slider seed
177
  )
178
 
179
  if __name__ == "__main__":
180
- # Khởi tạo queue và triển khai trên Hugging Face Spaces
181
- demo.queue(max_size=10).launch(share=True)
 
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 = "segmind/sd-tiny" # 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,
 
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",
 
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(
 
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
 
 
92
  seed = gr.Slider(
93
  label="Seed",
94
  minimum=0,
95
+ maximum=MAX_SEED,
96
  step=1,
97
  value=0,
98
  )
 
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():
 
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(
 
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,
140
  inputs=[
141
  prompt,
 
147
  guidance_scale,
148
  num_inference_steps,
149
  ],
150
+ outputs=[result, seed],
151
  )
152
 
153
  if __name__ == "__main__":
154
+ demo.launch()