Hunsain Mazhar commited on
Commit Β·
39d25c5
1
Parent(s): 786d386
Improve model downloading and error handling; added robust download logic and enhanced memory management
Browse files123456789101112131415161 unmodified line1819202122238 unmodified lines323334353637382 unmodified lines414243444546474849505152535455565758596010 unmodified lines71727374757677787914 unmodified lines94959697989910010110210310410510610710876 unmodified lines185186187188189190191192193import sysimport osimport gc # <--- ADDED: Garbage Collection# --- 1. System Setup & Error Handling ---try:import detectron2except ImportError:os.system('pip install git+https://github.com/facebookresearch/detectron2.git')import requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util.retry import Retryimport gradio as grimport spacesfrom PIL import Image1 unmodified lineimport torchfrom torchvision import transformsfrom torchvision.transforms.functional import to_pil_imagesys.path.append('./')8 unmodified linesfrom detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientationimport apply_netexcept ImportError as e:raise ImportError(f"CRITICAL ERROR: Missing core modules. {e}")from transformers import (CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTextModel,2 unmodified linesfrom diffusers import DDPMScheduler, AutoencoderKL# ---------------------------------------------------------# 2. DOWNLOADER# ---------------------------------------------------------def download_file(url, path):if os.path.exists(path): return# ... (Keep existing downloader logic if you wish, or use the robust one from before)# For brevity, assuming files exist or you use the previous robust downloader code here.# If not, paste the 'download_file' function from the previous response here.print(f"Checking {path}...")if not os.path.exists(path):os.system(f"wget -O {path} {url}")def check_and_download_models():# ... (Same file list as before)pass # Call your download logic here# ---------------------------------------------------------# 3. LOAD MODELS10 unmodified linesvae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16)UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16)parsing_model = Parsing(0)openpose_model = OpenPose(0)UNet_Encoder.requires_grad_(False)image_encoder.requires_grad_(False)vae.requires_grad_(False)14 unmodified linestensor_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])# ---------------------------------------------------------# 4. INFERENCE (Fixed Memory Leak)# ---------------------------------------------------------# Increase duration to 120s to prevent timeouts@spaces.GPU(duration=120)def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed):device = "cuda"try:# Move models to GPUopenpose_model.preprocessor.body_estimation.model.to(device)pipe.to(device)pipe.unet_encoder.to(device)76 unmodified linesraise gr.Error(f"Error: {e}")finally:# --- CRITICAL MEMORY CLEANUP ---# This code runs no matter what, preventing the "3-4 run crash"print("Cleaning GPU memory...")try:del keypoints, model_parse, mask, pose_img, prompt_embeds, garm_tensorexcept:12345678910111213141516171 unmodified line192021222324258 unmodified lines343536373839402 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810910 unmodified lines12012112212312412512612712812913014 unmodified lines14514614714814915015115215315415515615776 unmodified lines234235236237238239240import sysimport osimport gcimport shutil# --- 1. System Setup & Error Handling ---# Force install detectron2 if missingtry:import detectron2except ImportError:print("β οΈ Detectron2 missing. Installing...")os.system('pip install git+https://github.com/facebookresearch/detectron2.git')import requestsimport gradio as grimport spacesfrom PIL import Image1 unmodified lineimport torchfrom torchvision import transformsfrom torchvision.transforms.functional import to_pil_imagefrom huggingface_hub import hf_hub_downloadsys.path.append('./')8 unmodified linesfrom detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientationimport apply_netexcept ImportError as e:raise ImportError(f"CRITICAL ERROR: Missing core modules. Error: {e}")from transformers import (CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTextModel,2 unmodified linesfrom diffusers import DDPMScheduler, AutoencoderKL# ---------------------------------------------------------# 2. ROBUST MODEL DOWNLOADER (The Fix)# ---------------------------------------------------------def download_model_robust(repo_id, filename, local_path):if os.path.exists(local_path):# Quick size check to ensure it's not an empty corrupt fileif os.path.getsize(local_path) > 1000:print(f"β Found {local_path}")returnelse:print(f"β οΈ Corrupt file found at {local_path}, redownloading...")os.remove(local_path)print(f"β¬οΈ Downloading {filename} to {local_path}...")try:# Create directoryos.makedirs(os.path.dirname(local_path), exist_ok=True)# Download using Hugging Face Hub (Fast & Cached)downloaded_file = hf_hub_download(repo_id=repo_id,filename=filename,local_dir=os.path.dirname(local_path),local_dir_use_symlinks=False)# If the filename in repo is different from target, rename it# (hf_hub_download saves to local_dir/filename)actual_download_path = os.path.join(os.path.dirname(local_path), filename)if actual_download_path != local_path:# Move it to the exact expected path if differentif os.path.exists(actual_download_path):shutil.move(actual_download_path, local_path)print(f"β Successfully downloaded {local_path}")except Exception as e:print(f"β Failed to download {filename}: {e}")# Manual Fallback for complex pathstry:url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"print(f"π Trying direct URL fallback: {url}")os.system(f"wget -O {local_path} {url}")except:passdef check_and_download_models():print("β³ VALIDATING MODELS...")# 1. Parsing & OpenPose (From Camenduru)download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_atr.onnx", "ckpt/humanparsing/parsing_atr.onnx")download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_lip.onnx", "ckpt/humanparsing/parsing_lip.onnx")download_model_robust("camenduru/IDM-VTON", "densepose/model_final_162be9.pkl", "ckpt/densepose/model_final_162be9.pkl")download_model_robust("camenduru/IDM-VTON", "openpose/ckpts/body_pose_model.pth", "ckpt/openpose/ckpts/body_pose_model.pth")# 2. IP Adapter (From h94)download_model_robust("h94/IP-Adapter", "sdxl_models/ip-adapter-plus_sdxl_vit-h.bin", "ckpt/ip_adapter/ip-adapter-plus_sdxl_vit-h.bin")download_model_robust("h94/IP-Adapter", "models/image_encoder/config.json", "ckpt/image_encoder/config.json")download_model_robust("h94/IP-Adapter", "models/image_encoder/pytorch_model.bin", "ckpt/image_encoder/pytorch_model.bin")# EXECUTE DOWNLOAD BEFORE LOADING ANYTHINGcheck_and_download_models()# ---------------------------------------------------------# 3. LOAD MODELS10 unmodified linesvae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16)UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16)# Initialize Preprocessorsparsing_model = Parsing(0)openpose_model = OpenPose(0)# Freeze WeightsUNet_Encoder.requires_grad_(False)image_encoder.requires_grad_(False)vae.requires_grad_(False)14 unmodified linestensor_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])# ---------------------------------------------------------# 4. INFERENCE# ---------------------------------------------------------@spaces.GPU(duration=120)def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed):device = "cuda"try:openpose_model.preprocessor.body_estimation.model.to(device)pipe.to(device)pipe.unet_encoder.to(device)76 unmodified linesraise gr.Error(f"Error: {e}")finally:# Memory Cleanuptry:del keypoints, model_parse, mask, pose_img, prompt_embeds, garm_tensorexcept:
app.py+68-21