-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfashn_viton.py
More file actions
237 lines (198 loc) · 8.68 KB
/
Copy pathfashn_viton.py
File metadata and controls
237 lines (198 loc) · 8.68 KB
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
import base64
import os
import time
from io import BytesIO
import numpy as np
import requests
import torch
from PIL import Image
from comfy.utils import ProgressBar
class FASHN:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_image": ("IMAGE",),
"garment_image": ("IMAGE",),
},
"optional": {
"category": (["tops", "bottoms", "one-pieces", "auto"], {"default": "auto"}),
"mode": (["performance", "balanced", "quality"], {"default": "balanced"}),
"garment_photo_type": (["auto", "model", "flat-lay"], {"default": "auto"}),
"moderation_level": (["none", "permissive", "conservative"], {"default": "permissive"}),
"segmentation_free": ("BOOLEAN", {"default": True}),
"seed": ("INT", {"default": 42}),
"num_samples": ("INT", {"default": 1, "min": 1, "max": 4, "step": 1}),
"fashn_api_key": ("STRING", {"multiline": False}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "fashn_tryon"
CATEGORY = "FASHN AI"
@staticmethod
def encode_img_to_base64(img):
"""Resizes and encodes an image as a JPEG in Base64 format."""
# Resize to max 2000px on largest dimension (only downsample, never upscale)
width, height = img.size
if max(width, height) > 2000:
if height > width:
new_height = 2000
new_width = int(width * 2000 / height)
else:
new_width = 2000
new_height = int(height * 2000 / width)
img = img.resize((new_width, new_height), Image.LANCZOS)
buffered = BytesIO()
img.save(buffered, format="JPEG", quality=95)
img_str = base64.b64encode(buffered.getvalue()).decode()
return f"data:image/jpeg;base64,{img_str}"
@staticmethod
def loadimage_to_pil(img_tensor_bhwc: torch.Tensor):
img_np = img_tensor_bhwc.squeeze(0).numpy()
return Image.fromarray((img_np * 255).astype(np.uint8))
@staticmethod
def pil_load_image_from_http(session, url: str) -> Image.Image:
response = session.get(url, stream=True)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
if not content_type.startswith("image/"):
raise ValueError(f"The URL's Content-Type is not an image. Content-Type: {content_type}")
img_bytes = BytesIO(response.content)
with Image.open(img_bytes) as img:
img.load()
return img.copy()
@staticmethod
def pil_to_torch_hwc(img: Image.Image):
img = np.array(img)
img = torch.from_numpy(img).to(dtype=torch.float32) / 255.0
return img
@staticmethod
def shorten_string(s: str, max_len: int = 50):
return s[:max_len] + "..." if len(s) > max_len else s
@staticmethod
def make_api_request(session, url, headers, data=None, method="GET", max_retries=3, timeout=60):
for attempt in range(max_retries):
try:
if method.upper() == "GET":
response = session.get(url, headers=headers, timeout=timeout)
elif method.upper() == "POST":
response = session.post(url, headers=headers, json=data, timeout=timeout)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise Exception(f"API call failed after {max_retries} attempts: {str(e)}") from e
print(f"Attempt {attempt + 1} failed. Retrying...")
time.sleep(2)
def fashn_tryon(
self,
model_image,
garment_image,
model_name="tryon-v1.6",
category="auto",
mode="balanced",
garment_photo_type="auto",
moderation_level="permissive",
segmentation_free=True,
seed=42,
num_samples=1,
fashn_api_key=None,
):
ENDPOINT_URL = os.getenv("FASHN_ENDPOINT_URL", "https://api.fashn.ai/v1")
API_KEY = fashn_api_key or os.getenv("FASHN_API_KEY")
if not API_KEY:
raise ValueError("FASHN_API_KEY must be set in environment variables or provided as fashn_api_key.")
def process_image(image):
if isinstance(image, str) and (image.startswith("http://") or image.startswith("https://")):
return image
else:
img = self.loadimage_to_pil(image)
return self.encode_img_to_base64(img)
model_image = process_image(model_image)
garment_image = process_image(garment_image)
if seed > 2**32:
seed = int(seed & 0xFFFFFFFF)
# Prepare API request
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
}
inputs = {
"model_image": model_image,
"garment_image": garment_image,
"category": category,
"mode": mode,
"garment_photo_type": garment_photo_type,
"moderation_level": moderation_level,
"segmentation_free": segmentation_free,
"seed": seed,
"num_samples": num_samples,
}
# Prepare API request data
api_data = {
"model_name": model_name,
"inputs": inputs
}
# Estimate processing time and initialize progress bar
if mode == "performance":
base_time = 7
elif mode == "quality":
base_time = 19
else: # balanced or default
base_time = 10
# Estimate poll time: base_time * (n+2)/3, ensure minimum of 1s
estimated_poll_time = max(1.0, base_time * (num_samples + 2) / 3.0)
pbar = ProgressBar(100) # Progress bar represents percentage
# Make API request
session = requests.Session()
try:
response_data = self.make_api_request(
session, f"{ENDPOINT_URL}/run", headers=headers, data=api_data, method="POST"
)
pred_id = response_data.get("id")
except Exception as e:
# Shorten image strings for error reporting
error_data = api_data.copy()
error_data["inputs"]["model_image"] = self.shorten_string(error_data["inputs"]["model_image"])
error_data["inputs"]["garment_image"] = self.shorten_string(error_data["inputs"]["garment_image"])
raise Exception(f"API call failed: {str(e)} - Req Body: {error_data}") from e
# Poll the status of the prediction
start_poll_time = time.time()
while True:
# Check timeout relative to polling start time
if time.time() - start_poll_time > 180: # 3 minutes timeout
raise Exception("Maximum polling time exceeded.")
try:
status_data = self.make_api_request(
session, f"{ENDPOINT_URL}/status/{pred_id}", headers=headers, method="GET"
)
except Exception as e:
raise Exception(f"Status check failed: {str(e)}") from e
if status_data["status"] == "completed":
break
elif status_data["status"] not in ["starting", "in_queue", "processing"]:
raise Exception(f"Prediction failed with id {pred_id}: {status_data.get('error')}. Inputs: {api_data['inputs']}")
# Update progress bar based on elapsed time vs estimated time
elapsed_poll_time = time.time() - start_poll_time
# Ensure progress doesn't exceed 99% during polling to leave room for final step
expected_progress = min(99, int((elapsed_poll_time / estimated_poll_time) * 100))
increment = expected_progress - pbar.current
if increment > 0:
pbar.update(increment)
time.sleep(2) # Original sleep interval
# Ensure pbar reaches 100% on successful completion
if pbar.current < 100:
pbar.update(100 - pbar.current)
# Get the result images
urls = status_data["output"]
result_imgs = []
for output_url in urls:
pil_img = self.pil_load_image_from_http(session, output_url)
result_imgs.append(self.pil_to_torch_hwc(pil_img))
session.close()
result_tensor = torch.stack(result_imgs, dim=0)
return (result_tensor,)
NODE_CLASS_MAPPINGS = {"FASHN": FASHN}
NODE_DISPLAY_NAME_MAPPINGS = {"FASHN": "FASHN Virtual Try-On"}