Update app.py
Browse files
app.py
CHANGED
@@ -10,21 +10,29 @@ import gradio as gr
|
|
10 |
|
11 |
MAX_SEED = 999999
|
12 |
|
13 |
-
# β
Pixelcut API key
|
14 |
-
pixelcut_api_key = "
|
15 |
-
|
16 |
|
17 |
# π― Convert image to PNG format
|
18 |
def convert_to_png(image):
|
19 |
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
20 |
|
21 |
-
|
22 |
# π₯ Encode image to base64 PNG format
|
23 |
def encode_image(image):
|
24 |
image = convert_to_png(image)
|
25 |
_, buffer = cv2.imencode('.png', image)
|
26 |
return base64.b64encode(buffer).decode('utf-8')
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
# π Main try-on function using Pixelcut API
|
30 |
def tryon(person_img, garment_img, seed, randomize_seed):
|
@@ -39,70 +47,86 @@ def tryon(person_img, garment_img, seed, randomize_seed):
|
|
39 |
seed = random.randint(0, MAX_SEED)
|
40 |
|
41 |
# π₯ Convert images to base64 PNG
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
# π Setup Pixelcut API endpoint and headers
|
46 |
url = "https://api.developer.pixelcut.ai/v1/remove-background"
|
47 |
headers = {
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
}
|
52 |
|
53 |
-
#
|
54 |
person_data = {
|
55 |
-
"image_url":
|
|
|
|
|
|
|
|
|
|
|
56 |
"format": "png"
|
57 |
}
|
58 |
|
59 |
result_img = None
|
60 |
max_retries = 5
|
61 |
-
retry_delay =
|
62 |
|
63 |
try:
|
64 |
session = requests.Session()
|
65 |
|
66 |
-
#
|
67 |
for attempt in range(max_retries):
|
68 |
-
|
69 |
-
print("
|
70 |
-
|
71 |
-
# β
Success β
|
72 |
-
if
|
73 |
-
|
74 |
-
print("β
|
75 |
-
|
76 |
-
# Fetch the
|
77 |
-
if
|
78 |
-
|
79 |
-
|
80 |
-
result_img = cv2.imdecode(
|
81 |
-
info = "Success"
|
82 |
break
|
83 |
|
84 |
else:
|
85 |
-
# π₯
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
else:
|
92 |
-
# β If retries fail
|
93 |
-
info = "API still
|
94 |
|
95 |
-
# π Handle timeouts
|
96 |
except requests.exceptions.ReadTimeout:
|
97 |
print("Timeout!")
|
98 |
-
info = "
|
99 |
raise gr.Error("Too many users, please try again later")
|
100 |
|
101 |
-
# β
|
102 |
except Exception as err:
|
103 |
print(f"β Other error: {err}")
|
104 |
info = "Error, please contact the admin"
|
105 |
-
result_img = None
|
106 |
|
107 |
end_time = time.time()
|
108 |
print(f"β³ Time used: {end_time - start_time:.2f} seconds")
|
@@ -110,6 +134,7 @@ def tryon(person_img, garment_img, seed, randomize_seed):
|
|
110 |
return result_img, seed, info
|
111 |
|
112 |
|
|
|
113 |
example_path = os.path.join(os.path.dirname(__file__), 'assets')
|
114 |
|
115 |
garm_list = os.listdir(os.path.join(example_path,"cloth"))
|
|
|
10 |
|
11 |
MAX_SEED = 999999
|
12 |
|
13 |
+
# β
New Pixelcut API key
|
14 |
+
pixelcut_api_key = "YOUR_NEW_PIXELCUT_API_KEY"
|
|
|
15 |
|
16 |
# π― Convert image to PNG format
|
17 |
def convert_to_png(image):
|
18 |
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
19 |
|
|
|
20 |
# π₯ Encode image to base64 PNG format
|
21 |
def encode_image(image):
|
22 |
image = convert_to_png(image)
|
23 |
_, buffer = cv2.imencode('.png', image)
|
24 |
return base64.b64encode(buffer).decode('utf-8')
|
25 |
|
26 |
+
# π οΈ Upload images to a temporary hosting service
|
27 |
+
def upload_image(image_data):
|
28 |
+
files = {"file": ("image.png", image_data, "image/png")}
|
29 |
+
upload_response = requests.post("https://tmpfiles.org/api/v1/upload", files=files)
|
30 |
+
|
31 |
+
if upload_response.status_code == 200:
|
32 |
+
return upload_response.json().get("data", {}).get("url", None)
|
33 |
+
else:
|
34 |
+
print("β Image upload failed:", upload_response.text)
|
35 |
+
return None
|
36 |
|
37 |
# π Main try-on function using Pixelcut API
|
38 |
def tryon(person_img, garment_img, seed, randomize_seed):
|
|
|
47 |
seed = random.randint(0, MAX_SEED)
|
48 |
|
49 |
# π₯ Convert images to base64 PNG
|
50 |
+
_, person_encoded = cv2.imencode('.png', convert_to_png(person_img))
|
51 |
+
_, garment_encoded = cv2.imencode('.png', convert_to_png(garment_img))
|
52 |
+
|
53 |
+
# β
Upload person and garment images to get URLs
|
54 |
+
person_url = upload_image(person_encoded)
|
55 |
+
garment_url = upload_image(garment_encoded)
|
56 |
+
|
57 |
+
if not person_url or not garment_url:
|
58 |
+
return None, None, "Image upload failed"
|
59 |
|
60 |
# π Setup Pixelcut API endpoint and headers
|
61 |
url = "https://api.developer.pixelcut.ai/v1/remove-background"
|
62 |
headers = {
|
63 |
+
'Content-Type': 'application/json',
|
64 |
+
'Accept': 'application/json',
|
65 |
+
'X-API-KEY': pixelcut_api_key
|
66 |
}
|
67 |
|
68 |
+
# π§ Use uploaded URLs in the payload
|
69 |
person_data = {
|
70 |
+
"image_url": person_url,
|
71 |
+
"format": "png"
|
72 |
+
}
|
73 |
+
|
74 |
+
garment_data = {
|
75 |
+
"image_url": garment_url,
|
76 |
"format": "png"
|
77 |
}
|
78 |
|
79 |
result_img = None
|
80 |
max_retries = 5
|
81 |
+
retry_delay = 3 # Faster retries now!
|
82 |
|
83 |
try:
|
84 |
session = requests.Session()
|
85 |
|
86 |
+
# π Retry loop β smarter handling of "please try again later"
|
87 |
for attempt in range(max_retries):
|
88 |
+
response = session.post(url, headers=headers, json=person_data, timeout=60)
|
89 |
+
print("Response code:", response.status_code)
|
90 |
+
|
91 |
+
# β
Success β process the result
|
92 |
+
if response.status_code == 200:
|
93 |
+
result_url = response.json().get('result_url', '')
|
94 |
+
print("β
Success:", result_url)
|
95 |
+
|
96 |
+
# Fetch the final image
|
97 |
+
if result_url:
|
98 |
+
result_img_data = requests.get(result_url).content
|
99 |
+
result_np = np.frombuffer(result_img_data, np.uint8)
|
100 |
+
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
|
101 |
+
info = "β
Success"
|
102 |
break
|
103 |
|
104 |
else:
|
105 |
+
# π₯ Handle "please try again later" or other errors
|
106 |
+
error_response = response.json().get('error', '')
|
107 |
+
|
108 |
+
if "please try again later" in error_response.lower():
|
109 |
+
print(f"Attempt {attempt + 1}/{max_retries}: API said 'please try again later'. Retrying in {retry_delay} seconds...")
|
110 |
+
time.sleep(retry_delay)
|
111 |
+
retry_delay += 2 # Exponential backoff β retries longer each time
|
112 |
+
else:
|
113 |
+
info = f"β Error: {response.status_code} - {response.text}"
|
114 |
+
break
|
115 |
|
116 |
else:
|
117 |
+
# β If all retries fail
|
118 |
+
info = "API still says 'please try again later' β waited too long."
|
119 |
|
120 |
+
# π Handle timeouts specifically
|
121 |
except requests.exceptions.ReadTimeout:
|
122 |
print("Timeout!")
|
123 |
+
info = "β‘ Timeout β please try again later"
|
124 |
raise gr.Error("Too many users, please try again later")
|
125 |
|
126 |
+
# β Handle any other unexpected errors
|
127 |
except Exception as err:
|
128 |
print(f"β Other error: {err}")
|
129 |
info = "Error, please contact the admin"
|
|
|
130 |
|
131 |
end_time = time.time()
|
132 |
print(f"β³ Time used: {end_time - start_time:.2f} seconds")
|
|
|
134 |
return result_img, seed, info
|
135 |
|
136 |
|
137 |
+
|
138 |
example_path = os.path.join(os.path.dirname(__file__), 'assets')
|
139 |
|
140 |
garm_list = os.listdir(os.path.join(example_path,"cloth"))
|