lisonallen commited on
Commit
407a5fa
·
1 Parent(s): 454e091

Add logging and error handling to app.py; update Gradio interface and fix JSON schema issue

Browse files
Files changed (2) hide show
  1. app.py +145 -96
  2. requirements.txt +1 -1
app.py CHANGED
@@ -1,6 +1,30 @@
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
@@ -9,18 +33,25 @@ import torch
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,
@@ -33,23 +64,31 @@ def infer(
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",
@@ -64,91 +103,101 @@ css = """
64
  }
65
  """
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
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
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,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ import logging
5
+ import sys
6
+
7
+ # 设置日志记录
8
+ logging.basicConfig(level=logging.INFO,
9
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
10
+ stream=sys.stdout)
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # 修复 Gradio JSON Schema 错误
14
+ try:
15
+ import gradio_client.utils
16
+ # 添加对布尔值的检查
17
+ original_get_type = gradio_client.utils.get_type
18
+ def patched_get_type(schema):
19
+ if isinstance(schema, bool):
20
+ return "bool"
21
+ if not isinstance(schema, dict):
22
+ return "any"
23
+ return original_get_type(schema)
24
+ gradio_client.utils.get_type = patched_get_type
25
+ logger.info("Successfully patched Gradio JSON schema processing")
26
+ except Exception as e:
27
+ logger.error(f"Failed to patch Gradio: {str(e)}")
28
 
29
  # import spaces #[uncomment to use ZeroGPU]
30
  from diffusers import DiffusionPipeline
 
33
  device = "cuda" if torch.cuda.is_available() else "cpu"
34
  model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
35
 
36
+ logger.info(f"Using device: {device}")
37
+ logger.info(f"Loading model: {model_repo_id}")
38
+
39
  if torch.cuda.is_available():
40
  torch_dtype = torch.float16
41
  else:
42
  torch_dtype = torch.float32
43
 
44
+ try:
45
+ pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
46
+ pipe = pipe.to(device)
47
+ logger.info("Model loaded successfully")
48
+ except Exception as e:
49
+ logger.error(f"Error loading model: {str(e)}")
50
+ raise
51
 
52
  MAX_SEED = np.iinfo(np.int32).max
53
  MAX_IMAGE_SIZE = 1024
54
 
 
55
  # @spaces.GPU #[uncomment to use ZeroGPU]
56
  def infer(
57
  prompt,
 
64
  num_inference_steps,
65
  progress=gr.Progress(track_tqdm=True),
66
  ):
67
+ try:
68
+ logger.info(f"Processing prompt: {prompt}")
69
+
70
+ if randomize_seed:
71
+ seed = random.randint(0, MAX_SEED)
72
+
73
+ logger.info(f"Using seed: {seed}, width: {width}, height: {height}")
74
+
75
+ generator = torch.Generator().manual_seed(seed)
76
+
77
+ image = pipe(
78
+ prompt=prompt,
79
+ negative_prompt=negative_prompt,
80
+ guidance_scale=guidance_scale,
81
+ num_inference_steps=num_inference_steps,
82
+ width=width,
83
+ height=height,
84
+ generator=generator,
85
+ ).images[0]
86
+
87
+ logger.info("Image generation successful")
88
+ return image, seed
89
+ except Exception as e:
90
+ logger.error(f"Error in inference: {str(e)}")
91
+ raise gr.Error(f"Error generating image: {str(e)}")
92
 
93
  examples = [
94
  "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
 
103
  }
104
  """
105
 
106
+ try:
107
+ with gr.Blocks(css=css) as demo:
108
+ with gr.Column(elem_id="col-container"):
109
+ gr.Markdown(" # Text-to-Image Gradio Template")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  with gr.Row():
112
+ prompt = gr.Text(
113
+ label="Prompt",
114
+ show_label=False,
115
+ max_lines=1,
116
+ placeholder="Enter your prompt",
117
+ container=False,
118
  )
119
 
120
+ run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
 
121
 
122
+ result = gr.Image(label="Result", show_label=False)
123
+
124
+ with gr.Accordion("Advanced Settings", open=False):
125
+ negative_prompt = gr.Text(
126
+ label="Negative prompt",
127
+ max_lines=1,
128
+ placeholder="Enter a negative prompt",
129
+ visible=True, # 改为可见
130
  )
131
 
132
+ seed = gr.Slider(
133
+ label="Seed",
134
+ minimum=0,
135
+ maximum=MAX_SEED,
136
  step=1,
137
+ value=0,
138
  )
139
 
140
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
141
+
142
+ with gr.Row():
143
+ width = gr.Slider(
144
+ label="Width",
145
+ minimum=256,
146
+ maximum=MAX_IMAGE_SIZE,
147
+ step=32,
148
+ value=1024,
149
+ )
150
+
151
+ height = gr.Slider(
152
+ label="Height",
153
+ minimum=256,
154
+ maximum=MAX_IMAGE_SIZE,
155
+ step=32,
156
+ value=1024,
157
+ )
158
+
159
+ with gr.Row():
160
+ guidance_scale = gr.Slider(
161
+ label="Guidance scale",
162
+ minimum=0.0,
163
+ maximum=10.0,
164
+ step=0.1,
165
+ value=0.0,
166
+ )
167
+
168
+ num_inference_steps = gr.Slider(
169
+ label="Number of inference steps",
170
+ minimum=1,
171
+ maximum=50,
172
+ step=1,
173
+ value=2,
174
+ )
175
+
176
+ gr.Examples(examples=examples, inputs=[prompt])
177
+ gr.on(
178
+ triggers=[run_button.click, prompt.submit],
179
+ fn=infer,
180
+ inputs=[
181
+ prompt,
182
+ negative_prompt,
183
+ seed,
184
+ randomize_seed,
185
+ width,
186
+ height,
187
+ guidance_scale,
188
+ num_inference_steps,
189
+ ],
190
+ outputs=[result, seed],
191
+ )
192
+
193
+ logger.info("Gradio interface created successfully")
194
+ except Exception as e:
195
+ logger.error(f"Error creating Gradio interface: {str(e)}")
196
+ raise
197
 
198
  if __name__ == "__main__":
199
+ try:
200
+ logger.info("Starting Gradio app")
201
+ demo.launch()
202
+ except Exception as e:
203
+ logger.error(f"Error launching app: {str(e)}")
requirements.txt CHANGED
@@ -4,4 +4,4 @@ invisible_watermark
4
  torch
5
  transformers
6
  xformers
7
- gradio==3.50.2
 
4
  torch
5
  transformers
6
  xformers
7
+ gradio==3.45.0