Spaces:
Runtime error
Runtime error
hamzaanwar12 commited on
Commit ·
401d683
1
Parent(s): 3707550
Some more changes
Browse files
app.py
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
import torch
|
|
@@ -20,10 +26,19 @@ from pydantic import BaseModel
|
|
| 20 |
# ENVIRONMENT SETUP
|
| 21 |
# ===========================
|
| 22 |
# Disable telemetry and set environment
|
|
|
|
|
|
|
| 23 |
os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
|
| 24 |
os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
|
| 25 |
os.environ['HF_HOME'] = '/tmp/huggingface_cache'
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
print("🚀 Starting CFLD Pose Transfer Application...")
|
| 28 |
print(f"Python version: {sys.version}")
|
| 29 |
print(f"PyTorch version: {torch.__version__}")
|
|
@@ -237,8 +252,11 @@ def load_models_gpu():
|
|
| 237 |
# ===========================
|
| 238 |
# INFERENCE FUNCTION
|
| 239 |
# ===========================
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
| 242 |
global model_state
|
| 243 |
|
| 244 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
@@ -249,20 +267,30 @@ def perform_inference(img_from_array, random_index=None):
|
|
| 249 |
if not model_state.is_loaded:
|
| 250 |
success = load_models_gpu()
|
| 251 |
if not success:
|
| 252 |
-
return None, "Failed to load models"
|
| 253 |
|
| 254 |
# Convert numpy array back to PIL Image
|
| 255 |
img_from = Image.fromarray(img_from_array.astype(np.uint8))
|
| 256 |
|
| 257 |
-
# Handle
|
| 258 |
-
if
|
| 259 |
-
|
| 260 |
else:
|
| 261 |
-
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
| 265 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
# Preprocess source image
|
| 267 |
trans = transforms.Compose([
|
| 268 |
transforms.Resize([256, 256], interpolation=transforms.InterpolationMode.BICUBIC, antialias=True),
|
|
@@ -271,27 +299,24 @@ def perform_inference(img_from_array, random_index=None):
|
|
| 271 |
])
|
| 272 |
img_from_tensor = trans(img_from).unsqueeze(0).to(device)
|
| 273 |
|
| 274 |
-
# Build pose image tensor
|
| 275 |
pose_img_tensor = build_pose_img(
|
| 276 |
model_state.annotation_file, img_to_path, device
|
| 277 |
).unsqueeze(0)
|
| 278 |
|
| 279 |
print("🚀 Running inference...")
|
| 280 |
|
| 281 |
-
# Main inference
|
| 282 |
with torch.no_grad():
|
| 283 |
-
# Get conditioning
|
| 284 |
c_new, down_block_additional_residuals, up_block_additional_residuals = model_state.model({
|
| 285 |
"img_cond": img_from_tensor,
|
| 286 |
"pose_img": pose_img_tensor
|
| 287 |
})
|
| 288 |
|
| 289 |
-
# Prepare noise
|
| 290 |
noisy_latents = torch.randn((1, 4, 64, 64), device=device)
|
| 291 |
weight_dtype = torch.float32
|
| 292 |
bsz = 1
|
| 293 |
|
| 294 |
-
# Prepare conditioning for guidance
|
| 295 |
c_new = torch.cat([c_new[:bsz], c_new[:bsz], c_new[bsz:]])
|
| 296 |
down_block_additional_residuals = [
|
| 297 |
torch.cat([torch.zeros_like(sample), sample, sample]).to(dtype=weight_dtype)
|
|
@@ -302,10 +327,9 @@ def perform_inference(img_from_array, random_index=None):
|
|
| 302 |
for k, v in up_block_additional_residuals.items()
|
| 303 |
}
|
| 304 |
|
| 305 |
-
# Denoising loop
|
| 306 |
model_state.noise_scheduler.set_timesteps(cfg.TEST.NUM_INFERENCE_STEPS)
|
| 307 |
for i, t in enumerate(model_state.noise_scheduler.timesteps):
|
| 308 |
-
if i % 10 == 0:
|
| 309 |
print(f"Denoising step {i}/{len(model_state.noise_scheduler.timesteps)}")
|
| 310 |
|
| 311 |
inputs = torch.cat([noisy_latents, noisy_latents, noisy_latents], dim=0)
|
|
@@ -331,50 +355,47 @@ def perform_inference(img_from_array, random_index=None):
|
|
| 331 |
sampling_imgs = model_state.vae.decode(noisy_latents) * 0.5 + 0.5
|
| 332 |
sampling_imgs = sampling_imgs.clamp(0, 1)
|
| 333 |
|
| 334 |
-
# Convert to numpy array for gradio
|
| 335 |
output_array = (sampling_imgs[0] * 255.).permute((1, 2, 0)).cpu().numpy().astype(np.uint8)
|
| 336 |
|
| 337 |
print("✅ Inference completed successfully!")
|
| 338 |
-
return output_array, f"Success! Used
|
| 339 |
|
| 340 |
except Exception as e:
|
| 341 |
print(f"❌ Error in inference: {e}")
|
| 342 |
traceback.print_exc()
|
| 343 |
-
return None, f"Error: {str(e)}", None
|
| 344 |
|
| 345 |
# ===========================
|
| 346 |
-
# GRADIO INTERFACE FUNCTIONS
|
| 347 |
# ===========================
|
| 348 |
-
def gradio_inference(img_from,
|
| 349 |
"""Gradio-compatible inference function"""
|
| 350 |
if img_from is None:
|
| 351 |
-
return None, "❌ Please upload an image first!", None
|
| 352 |
|
| 353 |
try:
|
| 354 |
# Convert PIL to numpy for GPU function
|
| 355 |
img_array = np.array(img_from)
|
| 356 |
-
result_array, message,
|
| 357 |
|
| 358 |
if result_array is None:
|
| 359 |
-
return None, message, None
|
| 360 |
|
| 361 |
# Convert back to PIL for gradio display
|
| 362 |
result_image = Image.fromarray(result_array)
|
| 363 |
|
| 364 |
-
|
| 365 |
-
if pose_img_path:
|
| 366 |
-
pose_img_full_path = os.path.join(model_state.model_dir, "fashion", pose_img_path)
|
| 367 |
-
if os.path.exists(pose_img_full_path):
|
| 368 |
-
pose_image = Image.open(pose_img_full_path)
|
| 369 |
-
return result_image, message, pose_image
|
| 370 |
-
|
| 371 |
-
return result_image, message, None
|
| 372 |
|
| 373 |
except Exception as e:
|
| 374 |
error_msg = f"❌ Inference failed: {str(e)}"
|
| 375 |
print(error_msg)
|
| 376 |
traceback.print_exc()
|
| 377 |
-
return None, error_msg, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
def check_model_status():
|
| 380 |
"""Check if models are loaded"""
|
|
@@ -484,10 +505,7 @@ def create_interface():
|
|
| 484 |
gr.Markdown("""
|
| 485 |
# 🎭 CFLD Pose Transfer - Professional Demo
|
| 486 |
|
| 487 |
-
**
|
| 488 |
-
|
| 489 |
-
Upload a person's image and transfer their pose using our advanced CFLD model.
|
| 490 |
-
This demo runs on Hugging Face Spaces with NVIDIA T4 GPU acceleration.
|
| 491 |
|
| 492 |
---
|
| 493 |
""")
|
|
@@ -523,13 +541,19 @@ def create_interface():
|
|
| 523 |
sources=["upload", "webcam"]
|
| 524 |
)
|
| 525 |
|
| 526 |
-
|
| 527 |
-
label="
|
| 528 |
-
value=
|
| 529 |
precision=0,
|
| 530 |
minimum=0,
|
| 531 |
maximum=4499,
|
| 532 |
-
info="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
)
|
| 534 |
|
| 535 |
generate_btn = gr.Button(
|
|
@@ -537,14 +561,6 @@ def create_interface():
|
|
| 537 |
variant="primary",
|
| 538 |
size="lg"
|
| 539 |
)
|
| 540 |
-
|
| 541 |
-
gr.Markdown("""
|
| 542 |
-
### 💡 Pro Tips:
|
| 543 |
-
- **Best results:** Full-body or upper-body shots with clear pose
|
| 544 |
-
- **Image quality:** High resolution, good lighting
|
| 545 |
-
- **Pose variety:** Try different indices (0-4499) for diverse poses
|
| 546 |
-
- **Processing time:** ~30-60 seconds on NVIDIA T4 GPU
|
| 547 |
-
""")
|
| 548 |
|
| 549 |
# Output column
|
| 550 |
with gr.Column(scale=1):
|
|
@@ -566,15 +582,20 @@ def create_interface():
|
|
| 566 |
gr.Markdown("### 🎯 Reference Pose")
|
| 567 |
|
| 568 |
reference_image = gr.Image(
|
| 569 |
-
label="Reference Pose Image",
|
| 570 |
height=300,
|
| 571 |
interactive=False
|
| 572 |
)
|
| 573 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
gr.Markdown("""
|
| 575 |
### ℹ️ About Reference Pose
|
| 576 |
-
This shows the pose
|
| 577 |
-
The pose is selected
|
| 578 |
""")
|
| 579 |
|
| 580 |
# Event handlers
|
|
@@ -590,10 +611,38 @@ def create_interface():
|
|
| 590 |
show_progress=True
|
| 591 |
)
|
| 592 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
generate_btn.click(
|
| 594 |
fn=gradio_inference,
|
| 595 |
-
inputs=[input_image,
|
| 596 |
-
outputs=[output_image, result_info, reference_image],
|
| 597 |
show_progress=True
|
| 598 |
)
|
| 599 |
|
|
@@ -607,10 +656,11 @@ def create_interface():
|
|
| 607 |
# Footer
|
| 608 |
gr.Markdown("""
|
| 609 |
---
|
| 610 |
-
**
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
|
|
|
| 614 |
""")
|
| 615 |
|
| 616 |
return demo
|
|
|
|
| 1 |
+
# common
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# ====================================>GPT
|
| 5 |
+
|
| 6 |
+
|
| 7 |
import os
|
| 8 |
import sys
|
| 9 |
import torch
|
|
|
|
| 26 |
# ENVIRONMENT SETUP
|
| 27 |
# ===========================
|
| 28 |
# Disable telemetry and set environment
|
| 29 |
+
|
| 30 |
+
|
| 31 |
os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
|
| 32 |
os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
|
| 33 |
os.environ['HF_HOME'] = '/tmp/huggingface_cache'
|
| 34 |
|
| 35 |
+
max_threads = min(multiprocessing.cpu_count(), 2)
|
| 36 |
+
os.environ["OMP_NUM_THREADS"] = str(max_threads)
|
| 37 |
+
os.environ["MKL_NUM_THREADS"] = str(max_threads)
|
| 38 |
+
os.environ["OPENBLAS_NUM_THREADS"] = str(max_threads)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
print("🚀 Starting CFLD Pose Transfer Application...")
|
| 43 |
print(f"Python version: {sys.version}")
|
| 44 |
print(f"PyTorch version: {torch.__version__}")
|
|
|
|
| 252 |
# ===========================
|
| 253 |
# INFERENCE FUNCTION
|
| 254 |
# ===========================
|
| 255 |
+
# ===========================
|
| 256 |
+
# INFERENCE FUNCTION (Modified)
|
| 257 |
+
# ===========================
|
| 258 |
+
def perform_inference(img_from_array, pair_index=None):
|
| 259 |
+
"""Perform pose transfer inference using test pair reference"""
|
| 260 |
global model_state
|
| 261 |
|
| 262 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
|
|
| 267 |
if not model_state.is_loaded:
|
| 268 |
success = load_models_gpu()
|
| 269 |
if not success:
|
| 270 |
+
return None, "Failed to load models", None, None
|
| 271 |
|
| 272 |
# Convert numpy array back to PIL Image
|
| 273 |
img_from = Image.fromarray(img_from_array.astype(np.uint8))
|
| 274 |
|
| 275 |
+
# Handle pair index
|
| 276 |
+
if pair_index is None or pair_index < 0:
|
| 277 |
+
pair_index = random.choice(range(len(model_state.test_pairs)))
|
| 278 |
else:
|
| 279 |
+
pair_index = min(int(pair_index), len(model_state.test_pairs) - 1)
|
| 280 |
|
| 281 |
+
# Get the test pair
|
| 282 |
+
pair = model_state.test_pairs.iloc[pair_index]
|
| 283 |
+
img_from_path, img_to_path = pair["from"], pair["to"]
|
| 284 |
+
|
| 285 |
+
print(f"🎯 Using test pair {pair_index}: {img_from_path} -> {img_to_path}")
|
| 286 |
|
| 287 |
+
# Load reference image from test_highres
|
| 288 |
+
ref_image_path = os.path.join(model_state.model_dir, "fashion", "test_highres", img_to_path)
|
| 289 |
+
if not os.path.exists(ref_image_path):
|
| 290 |
+
return None, f"Reference image not found: {ref_image_path}", None, None
|
| 291 |
+
|
| 292 |
+
ref_image = Image.open(ref_image_path).convert("RGB")
|
| 293 |
+
|
| 294 |
# Preprocess source image
|
| 295 |
trans = transforms.Compose([
|
| 296 |
transforms.Resize([256, 256], interpolation=transforms.InterpolationMode.BICUBIC, antialias=True),
|
|
|
|
| 299 |
])
|
| 300 |
img_from_tensor = trans(img_from).unsqueeze(0).to(device)
|
| 301 |
|
| 302 |
+
# Build pose image tensor from reference image path
|
| 303 |
pose_img_tensor = build_pose_img(
|
| 304 |
model_state.annotation_file, img_to_path, device
|
| 305 |
).unsqueeze(0)
|
| 306 |
|
| 307 |
print("🚀 Running inference...")
|
| 308 |
|
| 309 |
+
# Main inference (same as before)
|
| 310 |
with torch.no_grad():
|
|
|
|
| 311 |
c_new, down_block_additional_residuals, up_block_additional_residuals = model_state.model({
|
| 312 |
"img_cond": img_from_tensor,
|
| 313 |
"pose_img": pose_img_tensor
|
| 314 |
})
|
| 315 |
|
|
|
|
| 316 |
noisy_latents = torch.randn((1, 4, 64, 64), device=device)
|
| 317 |
weight_dtype = torch.float32
|
| 318 |
bsz = 1
|
| 319 |
|
|
|
|
| 320 |
c_new = torch.cat([c_new[:bsz], c_new[:bsz], c_new[bsz:]])
|
| 321 |
down_block_additional_residuals = [
|
| 322 |
torch.cat([torch.zeros_like(sample), sample, sample]).to(dtype=weight_dtype)
|
|
|
|
| 327 |
for k, v in up_block_additional_residuals.items()
|
| 328 |
}
|
| 329 |
|
|
|
|
| 330 |
model_state.noise_scheduler.set_timesteps(cfg.TEST.NUM_INFERENCE_STEPS)
|
| 331 |
for i, t in enumerate(model_state.noise_scheduler.timesteps):
|
| 332 |
+
if i % 10 == 0:
|
| 333 |
print(f"Denoising step {i}/{len(model_state.noise_scheduler.timesteps)}")
|
| 334 |
|
| 335 |
inputs = torch.cat([noisy_latents, noisy_latents, noisy_latents], dim=0)
|
|
|
|
| 355 |
sampling_imgs = model_state.vae.decode(noisy_latents) * 0.5 + 0.5
|
| 356 |
sampling_imgs = sampling_imgs.clamp(0, 1)
|
| 357 |
|
|
|
|
| 358 |
output_array = (sampling_imgs[0] * 255.).permute((1, 2, 0)).cpu().numpy().astype(np.uint8)
|
| 359 |
|
| 360 |
print("✅ Inference completed successfully!")
|
| 361 |
+
return output_array, f"Success! Used test pair: {pair_index}", ref_image, img_to_path
|
| 362 |
|
| 363 |
except Exception as e:
|
| 364 |
print(f"❌ Error in inference: {e}")
|
| 365 |
traceback.print_exc()
|
| 366 |
+
return None, f"Error: {str(e)}", None, None
|
| 367 |
|
| 368 |
# ===========================
|
| 369 |
+
# GRADIO INTERFACE FUNCTIONS (Modified)
|
| 370 |
# ===========================
|
| 371 |
+
def gradio_inference(img_from, pair_index):
|
| 372 |
"""Gradio-compatible inference function"""
|
| 373 |
if img_from is None:
|
| 374 |
+
return None, "❌ Please upload an image first!", None, None
|
| 375 |
|
| 376 |
try:
|
| 377 |
# Convert PIL to numpy for GPU function
|
| 378 |
img_array = np.array(img_from)
|
| 379 |
+
result_array, message, ref_image, ref_path = perform_inference(img_array, pair_index)
|
| 380 |
|
| 381 |
if result_array is None:
|
| 382 |
+
return None, message, None, None
|
| 383 |
|
| 384 |
# Convert back to PIL for gradio display
|
| 385 |
result_image = Image.fromarray(result_array)
|
| 386 |
|
| 387 |
+
return result_image, message, ref_image, ref_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
|
| 389 |
except Exception as e:
|
| 390 |
error_msg = f"❌ Inference failed: {str(e)}"
|
| 391 |
print(error_msg)
|
| 392 |
traceback.print_exc()
|
| 393 |
+
return None, error_msg, None, None
|
| 394 |
+
|
| 395 |
+
# ===========================
|
| 396 |
+
# GRADIO INTERFACE (Modified)
|
| 397 |
+
# ===========================
|
| 398 |
+
|
| 399 |
|
| 400 |
def check_model_status():
|
| 401 |
"""Check if models are loaded"""
|
|
|
|
| 505 |
gr.Markdown("""
|
| 506 |
# 🎭 CFLD Pose Transfer - Professional Demo
|
| 507 |
|
| 508 |
+
**Upload source image + select reference pose from test pairs**
|
|
|
|
|
|
|
|
|
|
| 509 |
|
| 510 |
---
|
| 511 |
""")
|
|
|
|
| 541 |
sources=["upload", "webcam"]
|
| 542 |
)
|
| 543 |
|
| 544 |
+
pair_index = gr.Number(
|
| 545 |
+
label="Test Pair Index (0-4499)",
|
| 546 |
+
value=0,
|
| 547 |
precision=0,
|
| 548 |
minimum=0,
|
| 549 |
maximum=4499,
|
| 550 |
+
info="Select which test pair to use as reference pose"
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
# Preview button for test pairs
|
| 554 |
+
preview_btn = gr.Button(
|
| 555 |
+
"👀 Preview Test Pair",
|
| 556 |
+
variant="secondary"
|
| 557 |
)
|
| 558 |
|
| 559 |
generate_btn = gr.Button(
|
|
|
|
| 561 |
variant="primary",
|
| 562 |
size="lg"
|
| 563 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
|
| 565 |
# Output column
|
| 566 |
with gr.Column(scale=1):
|
|
|
|
| 582 |
gr.Markdown("### 🎯 Reference Pose")
|
| 583 |
|
| 584 |
reference_image = gr.Image(
|
| 585 |
+
label="Reference Pose Image (from test_highres)",
|
| 586 |
height=300,
|
| 587 |
interactive=False
|
| 588 |
)
|
| 589 |
|
| 590 |
+
ref_path_display = gr.Textbox(
|
| 591 |
+
label="Reference Image Path",
|
| 592 |
+
interactive=False
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
gr.Markdown("""
|
| 596 |
### ℹ️ About Reference Pose
|
| 597 |
+
This shows the reference pose image from the test_highres dataset.
|
| 598 |
+
The pose is selected based on the test pair index you provide.
|
| 599 |
""")
|
| 600 |
|
| 601 |
# Event handlers
|
|
|
|
| 611 |
show_progress=True
|
| 612 |
)
|
| 613 |
|
| 614 |
+
# Preview test pair
|
| 615 |
+
def preview_test_pair(pair_index):
|
| 616 |
+
"""Preview the test pair without running inference"""
|
| 617 |
+
try:
|
| 618 |
+
if not model_state.is_downloaded:
|
| 619 |
+
return None, "Download models first!", None
|
| 620 |
+
|
| 621 |
+
pair_index = min(int(pair_index), len(model_state.test_pairs) - 1)
|
| 622 |
+
pair = model_state.test_pairs.iloc[pair_index]
|
| 623 |
+
img_to_path = pair["to"]
|
| 624 |
+
|
| 625 |
+
ref_image_path = os.path.join(model_state.model_dir, "fashion", "test_highres", img_to_path)
|
| 626 |
+
if os.path.exists(ref_image_path):
|
| 627 |
+
ref_image = Image.open(ref_image_path).convert("RGB")
|
| 628 |
+
return ref_image, f"Preview: Test pair {pair_index}", img_to_path
|
| 629 |
+
else:
|
| 630 |
+
return None, f"Reference image not found: {img_to_path}", None
|
| 631 |
+
|
| 632 |
+
except Exception as e:
|
| 633 |
+
return None, f"Preview error: {str(e)}", None
|
| 634 |
+
|
| 635 |
+
preview_btn.click(
|
| 636 |
+
fn=preview_test_pair,
|
| 637 |
+
inputs=[pair_index],
|
| 638 |
+
outputs=[reference_image, result_info, ref_path_display],
|
| 639 |
+
show_progress=True
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
generate_btn.click(
|
| 643 |
fn=gradio_inference,
|
| 644 |
+
inputs=[input_image, pair_index],
|
| 645 |
+
outputs=[output_image, result_info, reference_image, ref_path_display],
|
| 646 |
show_progress=True
|
| 647 |
)
|
| 648 |
|
|
|
|
| 656 |
# Footer
|
| 657 |
gr.Markdown("""
|
| 658 |
---
|
| 659 |
+
**How it works:**
|
| 660 |
+
1. Upload your source image
|
| 661 |
+
2. Select a test pair index (0-4499) for reference pose
|
| 662 |
+
3. Click generate to transfer the pose
|
| 663 |
+
4. Use preview to see the reference pose first
|
| 664 |
""")
|
| 665 |
|
| 666 |
return demo
|