File size: 13,482 Bytes
f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 960755b f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 90aea0d f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 1a025f2 f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 ee3001a 6ac6fd8 0d96fc2 f5f5d29 6ac6fd8 0d96fc2 f5f5d29 ee3001a f5f5d29 960755b 6ac6fd8 a9345aa f5f5d29 ee3001a f5f5d29 ee3001a f5f5d29 960755b 1a025f2 ee3001a f5f5d29 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
import os
import cv2
import gradio as gr
import numpy as np
import random
import base64
import requests
import json
import time
def character_gen(prompt, person_img, seed, randomize_seed, height, width):
faceFidelity = 0.8
refFidelity = 0.8
post_start_time = time.time()
if person_img is None:
gr.Warning("Empty Person image")
return None, None, "Empty image"
if prompt is None:
gr.Warning("Empty prompt")
return None, None, "Empty prompt"
if randomize_seed:
seed = random.randint(0, MAX_SEED)
encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
url = "http://" + os.environ['character_url'] + "Submit"
token = os.environ['token']
referer = os.environ['referer']
headers = {'Content-Type': 'application/json', 'token': token, 'referer': referer}
data = {
"humanImage": encoded_person_img,
"seed": seed,
"prompt": prompt,
"width": width,
"height": height,
"faceFidelity": faceFidelity,
"refFidelity": refFidelity
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
# print("post response code", response.status_code)
if response.status_code == 200:
result = response.json()['result']
status = result['status']
if status == "success":
uuid = result['result']
# print(uuid)
except Exception as err:
print(f"Post Exception Error: {err}")
raise gr.Error("Too many users, please try again later")
post_end_time = time.time()
print(f"post time used: {post_end_time-post_start_time}")
get_start_time =time.time()
time.sleep(9)
Max_Retry = 22
result_img = None
info = ""
err_log = ""
for i in range(Max_Retry):
try:
url = "http://" + os.environ['character_url'] + "Query?taskId=" + uuid
response = requests.get(url, headers=headers, timeout=20)
# print("get response code", response.status_code)
if response.status_code == 200:
result = response.json()['result']
status = result['status']
if status == "success":
result = base64.b64decode(result['result'])
result_np = np.frombuffer(result, np.uint8)
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
info = "Success"
break
elif status == "error":
err_log = f"Status is Error"
info = "Error"
break
else:
# print(response.text)
err_log = "URL error, pleace contact the admin"
info = "URL error, pleace contact the admin"
break
except requests.exceptions.ReadTimeout:
err_log = "Http Timeout"
info = "Http Timeout, please try again later"
except Exception as err:
err_log = f"Get Exception Error: {err}"
time.sleep(1)
get_end_time = time.time()
print(f"get time used: {get_end_time-get_start_time}")
print(f"all time used: {get_end_time-get_start_time+post_end_time-post_start_time}")
if info == "":
err_log = f"No image after {Max_Retry} retries"
info = "Too many users, please try again later"
if info != "Success":
print(f"Error Log: {err_log}")
gr.Warning("Too many users, please try again later")
return result_img, seed, info
MAX_SEED = 999999
example_path = os.path.join(os.path.dirname(__file__), 'assets')
garm_list_path = []
human_list_path = []
css="""
#col-left {
margin: 0 auto;
max-width: 400px;
}
#col-right {
margin: 0 auto;
max-width: 600px;
}
#col-showcase {
margin: 0 auto;
max-width: 1100px;
}
#button {
color: blue;
}
"""
assets_root_path = os.path.join(os.path.dirname(__file__), 'assets')
# 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 ]
example_list_path = [
assets_root_path + '/demo11.png',
assets_root_path + '/demo12.png',
assets_root_path + '/demo6.png',
assets_root_path + '/demo9.png',
assets_root_path + '/demo5.jpg',
assets_root_path + '/demo2.png',
assets_root_path + '/demo4.jpg',
assets_root_path + '/demo1.jpg',
]
prompt_exampler_lists = [
"A Young 20-year-old human drinking coffee, full body shot, high quality, sharp focus, luxury cafe decoration",
"A beautiful 20-year-old human playing with a grey puppy, full body shot, black sofa in the background, high quality, ultra high",
"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. ",
]
def load_description(fp):
with open(fp, 'r', encoding='utf-8') as f:
content = f.read()
return content
def change_imgs(image1, image2):
return image1, image2
with gr.Blocks(css=css) as Character:
gr.HTML(load_description("title.md"))
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
</div>
<div>
</div>
</div>
""")
with gr.Row():
with gr.Column(elem_id="col-left"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 1. Upload a character image ⬇️
</div>
</div>
""")
image = gr.Image(label="Image", type="numpy", width=400)
example = gr.Examples(
inputs= image,
examples_per_page= 9,
examples=example_list_path
)
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
</div>
<div>
Step 2. Enter your prompt ⬇️
</div>
</div>
""")
prompt = gr.Textbox(
label="Prompt",
placeholder="Enter your prompt",
lines=2
)
gr.Examples(examples=prompt_exampler_lists, inputs= prompt, examples_per_page= 6 )
with gr.Column(elem_id="col-right"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 3. Press “Run” to get results ⬇️
</div>
</div>
""")
result = gr.Image(label="Result", show_label=False)
with gr.Row():
height = gr.Slider(
label="Height",
minimum=768,
maximum=1024,
step=64,
value=1024,
)
width = gr.Slider(
label="Width",
minimum=768,
maximum=1024,
step=64,
value=1024,
)
# with gr.Row():
# face_scale = gr.Slider(
# label="Face_scale",
# minimum=0.3,
# maximum=1.0,
# step=0.05,
# value=0.8,
# interactive=False,
# )
# ref_scale = gr.Slider(
# label="Ref_scale",
# minimum=0.3,
# maximum=1.0,
# step=0.05,
# value=0.8,
# interactive=False,
# )
# face_scale = 0.8
# ref_scale = 0.8
with gr.Row():
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Random seed", value=True)
with gr.Row():
seed_used = gr.Number(label="Seed used")
result_info = gr.Text(label="Response")
with gr.Row():
button = gr.Button("Run", elem_id="button")
button.click(
fn = character_gen,
inputs = [ prompt, image, seed, randomize_seed, height, width ],
outputs = [result, seed_used, result_info]
)
with gr.Column(elem_id = "col-showcase"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div> </div>
<br>
<div>
Character examples in pairs of character images and prompt
</div>
</div>
""")
show_case = gr.Examples(
examples=[
["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"],
["assets/demo12.png", "A Young human drinking coffee, full body shot, high quality, sharp focus, luxury cafe decoration", "assets/results/res_demo12.png"],
["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"],
["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"],
["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"],
],
inputs=[image, prompt, result],
label=None
)
Character.queue().launch(debug=True)
|