wujunqiang commited on
Commit
f5f5d29
1 Parent(s): 9ab4bf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +272 -116
app.py CHANGED
@@ -1,154 +1,310 @@
 
 
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,
28
- seed,
29
- randomize_seed,
30
- width,
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;
63
- max-width: 640px;
 
 
 
 
 
 
 
 
 
 
 
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 os
2
+ import cv2
3
  import gradio as gr
4
  import numpy as np
5
  import random
6
+ import base64
7
+ import requests
8
+ import json
9
+ import time
10
 
11
+
12
+ def character_gen(prompt, person_img, seed, randomize_seed, height, width, faceFidelity, refFidelity):
13
+ post_start_time = time.time()
14
+ if person_img is None:
15
+ gr.Warning("Empty Person image")
16
+ return None, None, "Empty image"
17
+ if prompt is None:
18
+ gr.Warning("Empty prompt")
19
+ return None, None, "Empty prompt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  if randomize_seed:
21
  seed = random.randint(0, MAX_SEED)
22
+ encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
23
+ encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
24
 
25
+ url = "http://" + os.environ['character_url'] + "Submit"
26
+ token = os.environ['token']
27
+ referer = os.environ['referer']
28
+ headers = {'Content-Type': 'application/json', 'token': token, 'referer': referer}
29
+ data = {
30
+ "humanImage": encoded_person_img,
31
+ "seed": seed,
32
+ "prompt": prompt,
33
+ "width": width,
34
+ "height": height,
35
+ "faceFidelity": faceFidelity,
36
+ "refFidelity": refFidelity
37
+ }
38
+ try:
39
+ response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
40
+ # print("post response code", response.status_code)
41
+ if response.status_code == 200:
42
+ result = response.json()['result']
43
+ status = result['status']
44
+ if status == "success":
45
+ uuid = result['result']
46
+ # print(uuid)
47
+ except Exception as err:
48
+ print(f"Post Exception Error: {err}")
49
+ raise gr.Error("Too many users, please try again later")
50
+ post_end_time = time.time()
51
+ print(f"post time used: {post_end_time-post_start_time}")
52
 
53
+ get_start_time =time.time()
54
+ time.sleep(9)
55
+ Max_Retry = 12
56
+ result_img = None
57
+ info = ""
58
+ err_log = ""
59
+ for i in range(Max_Retry):
60
+ try:
61
+ url = "http://" + os.environ['character_url'] + "Query?taskId=" + uuid
62
+ response = requests.get(url, headers=headers, timeout=20)
63
+ # print("get response code", response.status_code)
64
+ if response.status_code == 200:
65
+ result = response.json()['result']
66
+ status = result['status']
67
+ if status == "success":
68
+ result = base64.b64decode(result['result'])
69
+ result_np = np.frombuffer(result, np.uint8)
70
+ result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
71
+ result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
72
+ info = "Success"
73
+ break
74
+ elif status == "error":
75
+ err_log = f"Status is Error"
76
+ info = "Error"
77
+ break
78
+ else:
79
+ # print(response.text)
80
+ err_log = "URL error, pleace contact the admin"
81
+ info = "URL error, pleace contact the admin"
82
+ break
83
+ except requests.exceptions.ReadTimeout:
84
+ err_log = "Http Timeout"
85
+ info = "Http Timeout, please try again later"
86
+ except Exception as err:
87
+ err_log = f"Get Exception Error: {err}"
88
+ time.sleep(1)
89
+ get_end_time = time.time()
90
+ print(f"get time used: {get_end_time-get_start_time}")
91
+ print(f"all time used: {get_end_time-get_start_time+post_end_time-post_start_time}")
92
+ if info == "":
93
+ err_log = f"No image after {Max_Retry} retries"
94
+ info = "Too many users, please try again later"
95
+ if info != "Success":
96
+ print(f"Error Log: {err_log}")
97
+ gr.Warning("Too many users, please try again later")
98
 
99
+ return result_img, seed, info
100
 
101
 
102
+ MAX_SEED = 999999
103
+
104
+ example_path = os.path.join(os.path.dirname(__file__), 'assets')
105
+
106
+ garm_list_path = []
107
+
108
+ human_list_path = []
109
 
110
+ css="""
111
+ #col-left {
112
  margin: 0 auto;
113
+ max-width: 400px;
114
+ }
115
+ #col-right {
116
+ margin: 0 auto;
117
+ max-width: 600px;
118
+ }
119
+ #col-showcase {
120
+ margin: 0 auto;
121
+ max-width: 1100;
122
+ }
123
+ #button {
124
+ color: blue;
125
  }
126
  """
127
 
128
+ assets_root_path = os.path.join(os.path.dirname(__file__), 'assets')
 
 
129
 
130
+ # example_list_path = [assets_root_path + '/' + x for x in os.listdir(os.path.join(assets_root_path)) if 'jpg' in x or 'png' in x ]
131
+
132
+ example_list_path = [
133
+ assets_root_path + '/demo11.png',
134
+ assets_root_path + '/demo12.png',
135
+ assets_root_path + '/demo6.png',
136
+ assets_root_path + '/demo9.png',
137
+
138
+
139
+ assets_root_path + '/demo5.jpg',
140
+ assets_root_path + '/demo2.png',
141
+ assets_root_path + '/demo4.jpg',
142
+ assets_root_path + '/demo1.jpg',
143
+
144
+ ]
145
+
146
+ prompt_exampler_lists = [
147
+ "A Young 20-year-old human drinking coffee, full body shot, high quality, sharp focus, luxury cafe decoration",
148
+ "A beautiful 20-year-old human playing with a grey puppy, full body shot, black sofa in the background, high quality, ultra high",
149
+ "A photo of a young human reading outdoors. She is sitting on a wooden bench, holding a book in both hands. The background is an autumn city street, with leaves showing rich yellow and orange colors, adding a warm tone to the picture. ",
150
+ ]
151
+
152
+
153
+ def load_description(fp):
154
+ with open(fp, 'r', encoding='utf-8') as f:
155
+ content = f.read()
156
+ return content
157
 
158
+ def change_imgs(image1, image2):
159
+ return image1, image2
160
 
161
+ with gr.Blocks(css=css) as Character:
162
+ gr.HTML(load_description("title.md"))
163
+ gr.HTML("""
164
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
165
+ <div>
166
+ </div>
167
+ <div>
168
+ </div>
169
+ </div>
170
+ """)
171
+
172
+ with gr.Row():
173
+
174
+ with gr.Column(elem_id="col-left"):
175
 
176
+ gr.HTML("""
177
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
178
+ <div>
179
+ Step 1. Upload a character image ⬇️
180
+ </div>
181
+ </div>
182
+ """)
183
+
184
+ image = gr.Image(label="Image", type="numpy", width=400)
185
+
186
+ example = gr.Examples(
187
+ inputs= image,
188
+ examples_per_page= 9,
189
+ examples=example_list_path
190
  )
191
 
192
+ gr.HTML("""
193
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
194
+ <div>
195
+
196
+ </div>
197
+ <div>
198
+ Step 2. Enter your prompt ⬇️
199
+ </div>
200
+
201
+ </div>
202
+ """)
203
+
204
+ prompt = gr.Textbox(
205
+ label="Prompt",
206
+ placeholder="Enter your prompt",
207
+ lines=2
208
  )
209
+
210
+ gr.Examples(examples=prompt_exampler_lists, inputs= prompt, examples_per_page= 6 )
211
+
212
 
213
+ with gr.Column(elem_id="col-right"):
214
+
215
+ gr.HTML("""
216
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
217
+ <div>
218
+ Step 3. Press “Run” to get results ⬇️
219
+ </div>
220
+ </div>
221
+ """)
222
+
223
+ result = gr.Image(label="Result", show_label=False)
224
 
225
+
226
  with gr.Row():
 
 
 
 
 
 
 
 
227
  height = gr.Slider(
228
  label="Height",
229
+ minimum=0,
230
+ maximum=1344,
231
+ step=64,
232
+ value=1024,
233
+ )
234
+ width = gr.Slider(
235
+ label="Width",
236
+ minimum=0,
237
+ maximum=1344,
238
+ step=64,
239
+ value=1024,
240
  )
241
 
242
+
243
  with gr.Row():
244
+ face_scale = gr.Slider(
245
+ label="Face_scale",
246
  minimum=0.0,
247
+ maximum=1.0,
248
+ step=0.05,
249
+ value=0.8,
250
+ )
251
+ ref_scale = gr.Slider(
252
+ label="Ref_scale",
253
+ minimum=0.0,
254
+ maximum=1.0,
255
+ step=0.05,
256
+ value=0.8,
257
  )
258
 
259
+
260
+ with gr.Row():
261
+ seed = gr.Slider(
262
+ label="Seed",
263
+ minimum=0,
264
+ maximum=MAX_SEED,
265
  step=1,
266
+ value=0,
267
  )
268
+ randomize_seed = gr.Checkbox(label="Random seed", value=True)
269
+ with gr.Row():
270
+ seed_used = gr.Number(label="Seed used")
271
+ result_info = gr.Text(label="Response")
272
+
273
+ with gr.Row():
274
+ button = gr.Button("Run", elem_id="button")
275
+
276
+
277
+ button.click(
278
+ fn = character_gen,
279
+ inputs = [ prompt, image, seed, randomize_seed, height, width, face_scale, ref_scale ],
280
+ outputs = [result, seed_used]
 
 
 
281
  )
282
 
283
+
284
+
285
+ with gr.Column(elem_id = "col-showcase"):
286
+ gr.HTML("""
287
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
288
+ <div> </div>
289
+ <br>
290
+ <div>
291
+ Character examples in pairs of character images and prompt
292
+ </div>
293
+ </div>
294
+ """)
295
+
296
+ show_case = gr.Examples(
297
+ examples=[
298
+ ["assets/demo9.png", "A photo of a young human reading outdoors. He is sitting on a wooden bench, holding a book in both hands, reading attentively. The background is an autumn city street, with leaves showing rich yellow and orange colors, adding a warm tone to the picture. The streets are lined with classical-style buildings, black street lamps and road signs are clearly visible, and some pedestrians and vehicles can be seen in the distance, giving people a peaceful living atmosphere. The sun shines in from the left, illuminating the entire scene, making both the characters and the background appear very clear and bright. The whole image has soft colors, moderate saturation, uniform lighting, and accurate white balance, creating a harmonious and natural visual effect.", "assets/results/res_demo9.png"],
299
+ ["assets/demo12.png", "A Young human drinking coffee, full body shot, high quality, sharp focus, luxury cafe decoration", "assets/results/res_demo12.png"],
300
+ ["assets/demo1.jpg", "Indoor photo showing a woman sitting on a chair, her legs crossed, her left hand resting naturally on her thigh, her right hand slightly raised, fingers touching the side of her cheek. The chair she sits on is in classic style, covered in beige fabric, with a wooden frame decorated with gold rivets on the back and armrests. The chair is placed on a light wooden floor, and the light coming in from the window on the right illuminates the entire scene, making the environment warm and bright. The curtains can be seen in the background, the color is light gray, similar to the color of the wall, and the overall tone is soft. There is a green plant planted in a woven basket on the left, adding a natural atmosphere. The sunlight outside the window shines in through the white gauze curtain, forming a soft light and shadow effect, enhancing the three-dimensional sense of the picture. The person becomes the visual focus, while the surrounding furniture and decorations set off an elegant and peaceful atmosphere. In terms of color, it is mainly warm, with beige, light gray and brown as the main colors, and the overall color saturation is moderate, with sufficient brightness but not overexposed. The exposure level is just right, so that the details are clearly visible, and there are no obvious dark or bright areas. This photo has a typical realistic style of indoor life.", "assets/results/res_demo1.png"],
301
+ ["assets/demo4.jpg", "A young beautiful woman, full_body, stands in front of the Paris Tower, XS, masterpiece, best quality,high resolution,unity 8k wallpaper, perfect lighting,extremely detailed CG,finely detail,extremely detailed,soft lighting and shadow,soft yet striking lighting, skin pores, detailed skin texture , Detailed face, depth of field.", "assets/results/res_demo4.png"],
302
+ ["assets/demo5.jpg", "A woman sits on a black leather sofa, holding a gray poodle in her arms. The woman gently hugs the dog with her left hand and puts her right hand on her knees, with a calm and natural expression. The poodle is medium-sized, with dark gray fur, curly and fluffy, and looks very soft. The dog's mouth is slightly open, with its tongue sticking out, looking very cute and relaxed. The background is a pure white wall with no other decorations, which makes the subject stand out more. The overall color tone is fresh and bright, and the light is even and soft, highlighting the details and texture of the person and the pet.", "assets/results/res_demo5.png"],
303
+ ],
304
+ inputs=[image, prompt, result],
305
+ label=None
306
+ )
307
+
308
+
309
+
310
+ Character.queue().launch(debug=True)