supli6669 commited on
Commit ·
56bfe80
1
Parent(s): ba0ebda
feat: integrate Real-ESRGAN background upscaling and face detection threshold
Browse filesFiles changed (4)
- app.py+18-1
- download_weights.py+2-1
- handover.md+12-5
- pipeline.py+73-6
172 unmodified lines17317417517617717866 unmodified lines245246247248249250251172 unmodified lineshelp="Scale factor for the output background image.")# Display active hardware deviceif pipeline is not None:device_str = "NVIDIA GPU (CUDA)" if "cuda" in str(pipeline.device) else "CPU"66 unmodified linesw=fidelity_weight,detection_model=face_detector,upscale=upscale_factor,blend_softness=blend_softness)process_duration = time.time() - start_timeexcept Exception as e:172 unmodified lines17317417517617717817918018118218318418518618718818919019119219366 unmodified lines260261262263264265266267268172 unmodified lineshelp="Scale factor for the output background image.")bg_upscale_toggle = st.sidebar.checkbox("Real-ESRGAN Background Upscale",value=False,help="Enable AI-based super-resolution for the background using Real-ESRGAN. If unchecked, standard bilinear resizing is used.")det_threshold = st.sidebar.slider("Face Detection Threshold",min_value=0.1,max_value=1.0,value=0.5,step=0.05,help="Confidence threshold for face detection. Lower values find more/blurry faces, higher values reduce false detections.")# Display active hardware deviceif pipeline is not None:device_str = "NVIDIA GPU (CUDA)" if "cuda" in str(pipeline.device) else "CPU"66 unmodified linesw=fidelity_weight,detection_model=face_detector,upscale=upscale_factor,blend_softness=blend_softness,bg_upsampler='realesrgan' if bg_upscale_toggle else None,det_threshold=det_threshold)process_duration = time.time() - start_timeexcept Exception as e:
33 unmodified lines3435363738394033 unmodified lines"weights/CodeFormer/codeformer.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth","weights/facelib/detection_Resnet50_Final.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth","weights/facelib/parsing_parsenet.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth","weights/facelib/yolov5l-face.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/yolov5l-face.pth"}for save_path, url in weights_to_download.items():33 unmodified lines343536373839404133 unmodified lines"weights/CodeFormer/codeformer.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth","weights/facelib/detection_Resnet50_Final.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/detection_Resnet50_Final.pth","weights/facelib/parsing_parsenet.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/parsing_parsenet.pth","weights/facelib/yolov5l-face.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/yolov5l-face.pth","weights/realesrgan/RealESRGAN_x2plus.pth": "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth"}for save_path, url in weights_to_download.items():
66 unmodified lines67686970717273747576777879808182838485868766 unmodified lines### Completed Operations- Created `app.py` containing the Streamlit web application.- Caching initialized `LocalAIEnhancerPipeline` resources via `@st.cache_resource` to avoid loading 370MB weights on every page rerun.- Designed a sidebar containing AI parameters (Fidelity Weight ($w$), Mask Blending Softness, Face Detector model, Background Upscale Factor).- Built a side-by-side Before (Original) vs. After (AI Restored) comparison section displaying image stats (dimensions, duration) and a high-speed download button.- Custom styled the UI using HTML/CSS markdown injection for a radial dark theme, gradient headers, and glassmorphic cards.- **Hugging Face Spaces Optimization (Docker SDK)**:- Modified [pipeline.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/pipeline.py) to automatically download model weights at runtime if they are missing.- Created [README.md](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/README.md) containing setup instructions.- Added [Dockerfile](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/Dockerfile) pre-configured with a CPU-only PyTorch setup to build fast, bypass size limits, and start the Streamlit server on port `7860`. This enables direct deployment via the Hugging Face **Docker SDK**.### Code Changes- [NEW] [app.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/app.py) (Streamlit User Interface script)- [MODIFY] [pipeline.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/pipeline.py) (Added automatic weight download triggers)- [NEW] [README.md](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/README.md) (Project documentation)- [NEW] [Dockerfile](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/Dockerfile) (Docker container environment setup)### Git Commit & Push Status- **Files Staged:** `Dockerfile`, `handover.md`- **Commit Message:** "chore: add Dockerfile for Hugging Face Spaces Docker SDK deployment"- **Remote Push:** Scheduled for execution.66 unmodified lines6768697071727374757677787980818283848586878889909192939466 unmodified lines### Completed Operations- Created `app.py` containing the Streamlit web application.- Caching initialized `LocalAIEnhancerPipeline` resources via `@st.cache_resource` to avoid loading 370MB weights on every page rerun.- Designed a sidebar containing AI parameters:- **Fidelity Weight ($w$)**: Slider from 0.0 to 1.0 (fine-tuning quality/hallucination vs likeness).- **Mask Blending Softness**: Slider from 0.0 to 1.0 (manually controlling feather/blur of edges).- **Face Detector Model**: Dropdown (`retinaface_resnet50`, `retinaface_mobile0.25`, `YOLOv5l`, `YOLOv5n`).- **Background Upscale Factor**: Slider to set scaling size.- **Real-ESRGAN Background Upscale**: Checkbox to toggle AI-based super-resolution for the background.- **Face Detection Threshold**: Slider from 0.1 to 1.0 (controls the confidence threshold of RetinaFace/YOLOv5 dynamically).- Built a side-by-side Before (Original) vs. After (AI Restored) comparison section displaying image stats (dimensions, duration) and a high-speed download button.- Custom styled the UI using HTML/CSS markdown injection for a radial dark theme, gradient headers, and glassmorphic cards.- **Hugging Face Spaces Optimization (Docker SDK)**:- Modified [pipeline.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/pipeline.py) to automatically download model weights (including Real-ESRGAN weights) at runtime if they are missing.- Created [README.md](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/README.md) containing setup instructions.- Added [Dockerfile](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/Dockerfile) pre-configured with a CPU-only PyTorch setup to build fast, bypass size limits, and start the Streamlit server on port `7860`. This enables direct deployment via the Hugging Face **Docker SDK**.### Code Changes- [NEW] [app.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/app.py) (Streamlit User Interface script)- [MODIFY] [pipeline.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/pipeline.py) (Added automatic weight download triggers and Real-ESRGAN & threshold handling)- [NEW] [README.md](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/README.md) (Project documentation)- [NEW] [Dockerfile](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/Dockerfile) (Docker container environment setup)- [MODIFY] [download_weights.py](file:///C:/Users/admin/.gemini/antigravity-ide/scratch/custom-ai-enhancer/download_weights.py) (Added RealESRGAN model weights to downloader)### Git Commit & Push Status- **Files Staged:** `app.py`, `pipeline.py`, `download_weights.py`, `handover.md`- **Commit Message:** "feat: integrate Real-ESRGAN background upscaling and face detection threshold"- **Remote Push:** Scheduled for execution.
53 unmodified lines545556575859603 unmodified lines64656667686912 unmodified lines82838485868788899091921 unmodified line94959697989910010125 unmodified lines12712812913013113213313413513613713813914014114214353 unmodified linesself.net.eval()print("[Pipeline] CodeFormer model loaded successfully.")def process_image(self, img, w=0.5, detection_model='retinaface_resnet50', upscale=2, blend_softness=0.5):"""Enhance an image using the local CodeFormer pipeline.3 unmodified linesdetection_model (str): Face detector model ('retinaface_resnet50', 'YOLOv5l', etc.).upscale (int): Upscale factor for output image.blend_softness (float): Blending mask softness (0.0 to 1.0).Returns:numpy.ndarray: Enhanced output image in BGR format.12 unmodified linesdevice=self.device)face_helper.clean_all()face_helper.read_image(img)# 1. Detect face landmarks and align/crop facesprint(f"[Pipeline] Running face detection model: {detection_model}...")num_det_faces = face_helper.get_face_landmarks_5(only_center_face=False,resize=640,1 unmodified line)print(f"[Pipeline] Detected {num_det_faces} faces.")if num_det_faces == 0:# Return resized background if no faces are detectedh, w_img, _ = img.shapereturn cv2.resize(img, (w_img * upscale, h * upscale), interpolation=cv2.INTER_LINEAR)25 unmodified linesenhanced_img = self.paste_faces_custom_blend(face_helper,upscale=upscale,blend_softness=blend_softness)return enhanced_imgdef paste_faces_custom_blend(self, face_helper, upscale, blend_softness):"""Custom implementation of face pasting with adjustable soft blending mask."""h, w, _ = face_helper.input_img.shapeh_up, w_up = int(h * upscale), int(w * upscale)# Initialize background image (upsampled background)upsample_img = cv2.resize(face_helper.input_img, (w_up, h_up), interpolation=cv2.INTER_LINEAR)for restored_face, inverse_affine in zip(face_helper.restored_faces, face_helper.inverse_affine_matrices):# Alignment offset53 unmodified lines545556575859603 unmodified lines646566676869707112 unmodified lines848586878889909192939495969798991001011021031041051061071081 unmodified line11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316425 unmodified lines19019119219319419519619719819920020120220320420520620720820921053 unmodified linesself.net.eval()print("[Pipeline] CodeFormer model loaded successfully.")def process_image(self, img, w=0.5, detection_model='retinaface_resnet50', upscale=2, blend_softness=0.5, bg_upsampler=None, det_threshold=0.5):"""Enhance an image using the local CodeFormer pipeline.3 unmodified linesdetection_model (str): Face detector model ('retinaface_resnet50', 'YOLOv5l', etc.).upscale (int): Upscale factor for output image.blend_softness (float): Blending mask softness (0.0 to 1.0).bg_upsampler (str): 'realesrgan' or None.det_threshold (float): Face detection confidence threshold.Returns:numpy.ndarray: Enhanced output image in BGR format.12 unmodified linesdevice=self.device)# Modify confidence threshold dynamically on the underlying detectorif hasattr(face_helper, 'face_detector'):detector = face_helper.face_detectorif hasattr(detector, 'detect_faces'):original_detect_faces = detector.detect_facesdef custom_detect_faces(image, *args, **kwargs):detector_class = detector.__class__.__name__if "Yolo" in detector_class:kwargs['conf_thres'] = det_thresholdelse:kwargs['conf_threshold'] = det_thresholdreturn original_detect_faces(image, *args, **kwargs)detector.detect_faces = custom_detect_facesface_helper.clean_all()face_helper.read_image(img)# 1. Detect face landmarks and align/crop facesprint(f"[Pipeline] Running face detection model: {detection_model} with threshold: {det_threshold}...")num_det_faces = face_helper.get_face_landmarks_5(only_center_face=False,resize=640,1 unmodified line)print(f"[Pipeline] Detected {num_det_faces} faces.")# Handle background upsampling firstbg_img = Noneif bg_upsampler == 'realesrgan':if not hasattr(self, 'bg_upsampler_instance') or self.bg_upsampler_instance is None:print("[Pipeline] Loading Real-ESRGAN background upsampler...")realesrgan_path = os.path.join(project_dir, "weights", "realesrgan", "RealESRGAN_x2plus.pth")if not os.path.exists(realesrgan_path):print("[Pipeline] Real-ESRGAN weights not found. Automatically downloading...")try:import download_weightsdownload_weights.download_file("https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/RealESRGAN_x2plus.pth", realesrgan_path)except Exception as e:print(f"[Pipeline] Error downloading Real-ESRGAN weights: {e}")raise FileNotFoundError(f"Real-ESRGAN weights not found at {realesrgan_path} and auto-download failed.")from basicsr.archs.rrdbnet_arch import RRDBNetfrom basicsr.utils.realesrgan_utils import RealESRGANeruse_half = Falseif self.device.type == 'cuda':no_half_gpu_list = ['1650', '1660']if not any(gpu in torch.cuda.get_device_name(0) for gpu in no_half_gpu_list):use_half = Truemodel = RRDBNet(num_in_ch=3,num_out_ch=3,num_feat=64,num_block=23,num_grow_ch=32,scale=2)self.bg_upsampler_instance = RealESRGANer(scale=2,model_path=realesrgan_path,model=model,tile=400,tile_pad=40,pre_pad=0,half=use_half)print("[Pipeline] Running Real-ESRGAN background super-resolution...")bg_img = self.bg_upsampler_instance.enhance(img, outscale=upscale)[0]if num_det_faces == 0:if bg_img is not None:return bg_img# Return resized background if no faces are detected and no AI upscaler usedh, w_img, _ = img.shapereturn cv2.resize(img, (w_img * upscale, h * upscale), interpolation=cv2.INTER_LINEAR)25 unmodified linesenhanced_img = self.paste_faces_custom_blend(face_helper,upscale=upscale,blend_softness=blend_softness,bg_img=bg_img)return enhanced_imgdef paste_faces_custom_blend(self, face_helper, upscale, blend_softness, bg_img=None):"""Custom implementation of face pasting with adjustable soft blending mask."""h, w, _ = face_helper.input_img.shapeh_up, w_up = int(h * upscale), int(w * upscale)# Initialize background image (upsampled background)if bg_img is None:upsample_img = cv2.resize(face_helper.input_img, (w_up, h_up), interpolation=cv2.INTER_LINEAR)else:upsample_img = cv2.resize(bg_img, (w_up, h_up), interpolation=cv2.INTER_LANCZOS4)for restored_face, inverse_affine in zip(face_helper.restored_faces, face_helper.inverse_affine_matrices):# Alignment offset
app.py+18-1
download_weights.py+2-1
handover.md+12-5
pipeline.py+73-6