import os import cv2 from PIL import Image import gradio as gr import numpy as np import random import base64 import requests import json import time def start_tryon(person_img, garment_img, seed, randomize_seed): start_time = time.time() if person_img is None or garment_img is None: return None, None, "Empty image" 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') encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes() encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8') url = "http://" + os.environ['tryon_url'] token = os.environ['token'] cookie = os.environ['Cookie'] referer = os.environ['referer'] headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer} data = { "clothImage": encoded_garment_img, "humanImage": encoded_person_img, "seed": seed } result_img = None try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=120) print("response code", response.status_code) if response.status_code == 200: result = response.json()['result'] print(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" else: info = "Try again latter" else: print(response.text) info = "URL error, pleace contact the admin" except requests.exceptions.ReadTimeout: print("timeout") info = "Too many users, please try again later" except Exception as err: print(f"其他错误: {err}") info = "Error, pleace contact the admin" end_time = time.time() print(f"time used: {end_time-start_time}") return result_img, seed, info MAX_SEED = 999999 example_path = os.path.join(os.path.dirname(__file__), 'assets') garm_list = os.listdir(os.path.join(example_path,"cloth")) garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list] human_list = os.listdir(os.path.join(example_path,"human")) human_list_path = [os.path.join(example_path,"human",human) for human in human_list] css=""" #col-left { margin: 0 auto; max-width: 430px; } #col-mid { margin: 0 auto; max-width: 430px; } #col-right { margin: 0 auto; max-width: 430px; } #col-showcase { margin: 0 auto; max-width: 1100px; } #button { color: blue; } """ 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 Tryon: gr.HTML(load_description("assets/title.md")) with gr.Row(): with gr.Column(elem_id = "col-left"): gr.HTML("""