import os import cv2 import gradio as gr import numpy as np import random import base64 import requests import json import time # Environment variables TRYON_URL = os.getenv('TRYON_URL') TOKEN = os.getenv('TOKEN') COOKIE = os.getenv('COOKIE') REFERER = os.getenv('REFERER') # Environment variables kontrolü if not all([TRYON_URL, TOKEN, COOKIE, REFERER]): print("Warning: Some environment variables are missing!") print(f"TRYON_URL: {'Set' if TRYON_URL else 'Missing'}") print(f"TOKEN: {'Set' if TOKEN else 'Missing'}") print(f"COOKIE: {'Set' if COOKIE else 'Missing'}") print(f"REFERER: {'Set' if REFERER else 'Missing'}") MAX_SEED = 999999 def tryon(person_img, garment_img, seed, randomize_seed): if not all([TRYON_URL, TOKEN, COOKIE, REFERER]): raise gr.Error("Server configuration is missing. Please contact administrator.") post_start_time = time.time() if person_img is None or garment_img is None: gr.Warning("Empty image") return None, None, "Empty image" if randomize_seed: seed = random.randint(0, MAX_SEED) try: # Resim kodlama 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 oluşturma if not TRYON_URL.startswith(('http://', 'https://')): base_url = f"https://{TRYON_URL}" else: base_url = TRYON_URL url = f"{base_url.rstrip('/')}/Submit" headers = { 'Content-Type': 'application/json', 'token': TOKEN, 'Cookie': COOKIE, 'referer': REFERER } data = { "clothImage": encoded_garment_img, "humanImage": encoded_person_img, "seed": seed } 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 = 12 result_img = None info = "" err_log = "" for i in range(Max_Retry): try: query_url = f"{base_url.rstrip('/')}/Query?taskId={uuid}" response = requests.get(query_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: err_log = "URL error, please contact the admin" info = "URL error, please 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 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') if not TRYON_URL.startswith(('http://', 'https://')): base_url = f"https://{TRYON_URL}" else: base_url = TRYON_URL 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: session = requests.Session() response = session.post(base_url, headers=headers, data=json.dumps(data), timeout=60) print("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" else: info = "Try again later" else: print(response.text) info = "URL error, please contact the admin" except requests.exceptions.ReadTimeout: print("timeout") info = "Too many users, please try again later" raise gr.Error("Too many users, please try again later") except Exception as err: print(f"Error: {err}") info = "Error, please contact the admin" end_time = time.time() print(f"time used: {end_time-start_time}") return result_img, seed, info 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 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("""