diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1868917741b342e9dcedd920c63bcdd3d854f344 --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +*.egg +dist/ +build/ +*.so + +# Virtual Environment +venv/ +.venv/ +env/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# Model Weights (large files) +weights/ +*.pth +*.ckpt +*.safetensors +*.bin + +# OneDrive +.~lock.* +~$* + +# OS +.DS_Store +Thumbs.db +desktop.ini + +# Logs & Outputs +outputs/ +logs/ +*.log + +# Temporary +/tmp/ +*.tmp diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1445a01a5b937a944e919a75667436854e5635aa --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM nvidia/cuda:12.4.0-runtime-ubuntu22.04 + +WORKDIR /app + +# System dependencies +RUN apt-get update && apt-get install -y \ + python3 python3-pip python3-venv \ + libgl1-mesa-glx libglib2.0-0 && \ + rm -rf /var/lib/apt/lists/* + +# Python dependencies +COPY requirements.txt . +RUN pip3 install --no-cache-dir -r requirements.txt + +# Application code +COPY src/ ./src/ +COPY libs/ ./libs/ +COPY weights/ ./weights/ + +# Entry point +EXPOSE 8501 +CMD ["python3", "-m", "streamlit", "run", "src/ai_image_dashboard/app/streamlit_app.py", "--server.address", "0.0.0.0", "--server.port", "8501"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..666bd0df71bd56c721b44cb1af83aab03c016689 --- /dev/null +++ b/README.md @@ -0,0 +1,428 @@ +

+ Creator AI Banner +

+ +

+ A professional-grade AI image processing suite powered by 12+ state-of-the-art deep learning models. +

+ +

+ Python + PyTorch + CUDA + Streamlit + LOC +

+ +--- + +## ๐ŸŽฏ What is Creator AI? + +**Creator AI** is an intelligent image processing platform that combines **12+ deep learning models** into a unified, interactive dashboard. Instead of running each AI model separately, Creator AI orchestrates them through **smart adaptive pipelines** that automatically analyze your image and activate only the models that are needed. + +### The Problem +Traditional AI image tools either: +- Run a single model (limited quality) +- Run everything blindly (slow, wastes GPU) +- Require command-line expertise + +### The Solution +Creator AI provides a **one-click Streamlit dashboard** with 5 professional tools, each backed by multi-stage AI pipelines that **dynamically route** processing based on image quality analysis. + +--- + +## โœจ Features + +| Tool | What It Does | AI Models Used | +|------|-------------|----------------| +| ๐Ÿ” **Super Resolution** | Upscale images 2xโ€“4x with smart quality analysis | RealESRGAN, CodeFormer, SwinIR, Stable Diffusion | +| ๐Ÿ”ค **Text Removal** | Detect and erase text from any image | CRAFT, SAM, LaMa, Stable Diffusion Inpainting | +| ๐ŸŽจ **Color Correction** | Fix exposure, white balance, and color grading | Zero-DCE, Restormer | +| โœ‚๏ธ **Object Removal** | Remove objects using natural language prompts | GroundingDINO, YOLOv8, SAM, LaMa, MiDaS | +| ๐Ÿ–ผ๏ธ **Background Removal** | Adaptive 5-stage background removal | BiRefNet, SAM, MODNet | + +--- + +## ๐Ÿ—๏ธ Architecture + +### System Overview + +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Streamlit Dashboard โ”‚ +โ”‚ (ai_image_dashboard/app/) โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ Pipeline Wrappers โ”‚ +โ”‚ (ai_image_dashboard/pipelines/) โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ Super โ”‚ Text โ”‚ Color โ”‚ Object โ”‚ Background โ”‚ +โ”‚Resolutionโ”‚ Removal โ”‚Correctionโ”‚ Removal โ”‚ Removal โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ Shared Utilities โ”‚ +โ”‚ (shared/logging_config, image_utils) โ”‚ +โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค +โ”‚ Model Weights (weights/) โ”‚ +โ”‚ libs/ (CodeFormer, BasicSR architectures) โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +``` + +### Project Structure + +``` +Creator AI/ +โ”‚ +โ”œโ”€โ”€ src/ +โ”‚ โ”œโ”€โ”€ ai_image_dashboard/ # ๐Ÿ–ฅ๏ธ Streamlit UI Layer +โ”‚ โ”‚ โ”œโ”€โ”€ app/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ streamlit_app.py # Main dashboard (750+ lines) +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ config.py # UI configuration +โ”‚ โ”‚ โ”œโ”€โ”€ pipelines/ # Thin wrappers connecting UI โ†’ engines +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ super_resolution_pipeline.py +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ text_removal_pipeline.py +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ color_pipeline.py +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ object_pipeline.py +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ background_pipeline.py +โ”‚ โ”‚ โ””โ”€โ”€ utils/ +โ”‚ โ”‚ โ””โ”€โ”€ image_utils.py +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ ai_super_resolution/ # ๐Ÿ” Smart Adaptive SR Engine +โ”‚ โ”‚ โ”œโ”€โ”€ sr_pipeline.py # 10-stage orchestrator with quality analysis +โ”‚ โ”‚ โ”œโ”€โ”€ stages/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ quality_analyzer.py # Image quality metrics (blur/noise/detail/face) +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ input_validator.py # Smart resize & validation +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ denoiser.py # Edge-preserving denoising +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ tile_engine.py # Overlapping tile split/fuse with Gaussian blending +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ color_matcher.py # LAB histogram matching +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ post_processor.py # Adaptive unsharp mask +โ”‚ โ”‚ โ”œโ”€โ”€ models/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ upsampler.py # RealESRGAN (via spandrel) +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ codeformer_enhancer.py # CodeFormer face restoration +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ swinir_refiner.py # SwinIR transformer refinement +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ diffusion_refiner.py # Stable Diffusion x4 upscaler +โ”‚ โ”‚ โ””โ”€โ”€ configs/ +โ”‚ โ”‚ โ””โ”€โ”€ config.yaml # Pipeline configuration & quality thresholds +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ ai_text_removal/ # ๐Ÿ”ค Text Detection & Inpainting Engine +โ”‚ โ”‚ โ”œโ”€โ”€ tr_pipeline.py # Multi-stage text removal orchestrator +โ”‚ โ”‚ โ”œโ”€โ”€ tr_pipelines/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ detect_text.py # CRAFT text detection +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ segment_mask.py # SAM mask segmentation +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ refine_mask.py # Morphological mask refinement +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ inpaint.py # LaMa inpainting +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ diffusion_refine.py # SD inpainting refinement +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ post_process.py # Seam blending & cleanup +โ”‚ โ”‚ โ””โ”€โ”€ configs/ +โ”‚ โ”‚ โ””โ”€โ”€ config.yaml +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ background_removal/ # ๐Ÿ–ผ๏ธ Adaptive Background Removal Engine +โ”‚ โ”‚ โ”œโ”€โ”€ inference/ +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ engine.py # 5-stage adaptive orchestrator +โ”‚ โ”‚ โ”œโ”€โ”€ bg_pipeline/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ scene_analyzer.py # Scene complexity detection +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ salient_detection.py # BiRefNet salient object detection +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ segmentation.py # SAM instance segmentation +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ matting.py # MODNet alpha matting +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ preprocessing.py # Input normalization +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ postprocessing.py # Edge refinement & compositing +โ”‚ โ”‚ โ”œโ”€โ”€ bg_models/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ sod/ # BiRefNet model +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ sam/ # SAM model +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ modnet/ # MODNet model + MobileNetV2 arch +โ”‚ โ”‚ โ””โ”€โ”€ configs/ +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ hybrid_color_correction/ # ๐ŸŽจ Color & Exposure Correction Engine +โ”‚ โ”‚ โ”œโ”€โ”€ hc_pipeline/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ enhance.py # Zero-DCE + Restormer pipeline +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ preprocess.py # Color space conversion +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ postprocess.py # Tone mapping +โ”‚ โ”‚ โ””โ”€โ”€ hc_models/ +โ”‚ โ”‚ โ”œโ”€โ”€ zero_dce/ # Zero-DCE light enhancement +โ”‚ โ”‚ โ””โ”€โ”€ restormer/ # Restormer detail recovery +โ”‚ โ”‚ +โ”‚ โ”œโ”€โ”€ object_removal_ai/ # โœ‚๏ธ Object Removal Engine +โ”‚ โ”‚ โ”œโ”€โ”€ main_pipeline.py # Multi-model orchestrator +โ”‚ โ”‚ โ”œโ”€โ”€ models/ +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ groundingdino_detector.py # Text-guided detection +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ yolo_detector.py # YOLOv8 fallback detection +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ sam_segmenter.py # SAM mask generation +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ lama_inpainter.py # LaMa inpainting +โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ midas_depth.py # Depth estimation +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ diffusion_refiner.py # SD inpainting refinement +โ”‚ โ”‚ โ””โ”€โ”€ or_pipeline/ +โ”‚ โ”‚ โ”œโ”€โ”€ mask_refiner.py # Multi-stage mask refinement +โ”‚ โ”‚ โ”œโ”€โ”€ context_expansion.py # Inpainting context window +โ”‚ โ”‚ โ””โ”€โ”€ postprocess.py # Seam removal & blending +โ”‚ โ”‚ +โ”‚ โ””โ”€โ”€ shared/ # ๐Ÿ”ง Shared Utilities +โ”‚ โ”œโ”€โ”€ logging_config.py # Centralized structured logging +โ”‚ โ””โ”€โ”€ image_utils.py # Common image operations +โ”‚ +โ”œโ”€โ”€ libs/ # ๐Ÿ“ฆ Local Model Architectures +โ”‚ โ”œโ”€โ”€ CodeFormer/ # CodeFormer network definitions +โ”‚ โ””โ”€โ”€ BasicSR/ # Basic image restoration utilities +โ”‚ +โ”œโ”€โ”€ weights/ # โš–๏ธ Model Weights (auto-downloaded) +โ”œโ”€โ”€ tests/ # ๐Ÿงช Test Suite +โ”œโ”€โ”€ assets/ # ๐ŸŽจ Project assets +โ”œโ”€โ”€ requirements.txt # ๐Ÿ“‹ Python dependencies +โ”œโ”€โ”€ Dockerfile # ๐Ÿณ Container deployment +โ”œโ”€โ”€ download_weights.py # โฌ‡๏ธ Weight download utility +โ””โ”€โ”€ .gitignore +``` + +> **110 Python files ยท 8,700+ lines of code ยท 12+ AI models** + +--- + +## ๐Ÿ” Deep Dive: Super Resolution Pipeline + +The flagship feature uses a **smart adaptive architecture** that dynamically selects which AI models to run based on image quality analysis. + +### How It Works + +``` +Input Image (e.g. 1024ร—1024) + โ”‚ + โ–ผ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Quality Analyzer โ”‚ โ† Runs in <100ms on CPU +โ”‚ โ€ข blur_score โ”‚ Uses Laplacian variance, Canny edges, +โ”‚ โ€ข noise_level โ”‚ Gaussian difference, RetinaFace +โ”‚ โ€ข detail_score โ”‚ +โ”‚ โ€ข face_detected โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Conditional Router โ”‚ โ† Decides which models to activate +โ”‚ โ”‚ +โ”‚ if noise > 0.6: โ”‚ โœ… Denoise +โ”‚ if face_detected: โ”‚ โœ… CodeFormer +โ”‚ if detail < 0.5: โ”‚ โœ… SwinIR (Balanced/HD only) +โ”‚ if blur > 0.7: โ”‚ โœ… Diffusion (HD only) +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ RealESRGAN (4x Upscale) โ”‚ +โ”‚ Tiled: 512ร—512 with 64px overlap โ”‚ +โ”‚ Gaussian-weighted seamless fusion โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ (if face detected) +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ CodeFormer Face Restoration โ”‚ +โ”‚ Identity-preserving face enhancement โ”‚ +โ”‚ fidelity_weight=0.7 for natural look โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ (if detail is low โ€” Balanced/HD) +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ SwinIR Transformer Refinement โ”‚ +โ”‚ Recovers fine textures (skin, fabric) โ”‚ +โ”‚ FP16 autocast for 2x speed โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ (if extremely degraded โ€” HD only) +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Stable Diffusion x4 Upscaler โ”‚ +โ”‚ Generates photorealistic textures โ”‚ +โ”‚ Tiled inference to prevent OOM โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Color Matching (LAB histogram) + Sharpeningโ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”‚ + โ–ผ + Output Image (4096ร—4096) +``` + +### Performance Modes + +| Mode | Modules Activated | Speed | Quality | +|------|------------------|-------|---------| +| โšก **Fast** | RealESRGAN + CodeFormer (auto) + Sharpen | ~15s | โ˜…โ˜…โ˜…โ˜†โ˜† | +| โš–๏ธ **Balanced** | + SwinIR (if detail is low) | ~45s | โ˜…โ˜…โ˜…โ˜…โ˜† | +| ๐ŸŽจ **HD** | + SwinIR + Diffusion (if degraded) | ~3min | โ˜…โ˜…โ˜…โ˜…โ˜… | + +> **Key Innovation:** Unlike traditional upscalers that blindly run all models, Creator AI's Quality Analyzer inspects the image first and skips unnecessary stages. A clean, sharp portrait in Fast mode completes in **15 seconds** instead of 3 minutes. + +--- + +## ๐Ÿ–ผ๏ธ Other Pipelines + +### Text Removal +Detects text regions using **CRAFT** (Character Region Awareness for Text), segments precise masks with **SAM**, and fills the regions using **LaMa** inpainting with optional **Stable Diffusion** refinement. Includes morphological mask expansion and seam blending for invisible repairs. + +### Object Removal +Accepts **natural language prompts** (e.g., "remove the car") via **GroundingDINO** text-guided detection, with **YOLOv8** as a fallback. Masks are refined through multi-stage dilation/erosion, and inpainting uses **LaMa** with **MiDaS** depth-aware context for realistic results. + +### Color Correction +Combines **Zero-DCE** (Zero-Reference Deep Curve Estimation) for exposure correction with **Restormer** for detail recovery. Processes images through a preprocess โ†’ enhance โ†’ postprocess pipeline with LAB color space normalization. + +### Background Removal +A 5-stage adaptive engine that analyzes scene complexity to select the optimal model combination: +- **Simple scenes** (portraits): MODNet alpha matting for fast, clean edges +- **Complex scenes** (products, multi-object): BiRefNet + SAM segmentation +- Includes trimap generation, edge refinement, and alpha compositing + +--- + +## ๐Ÿง  Memory Management + +Creator AI is designed to run on **consumer GPUs with as little as 4GB VRAM** (e.g., RTX 3050): + +| Technique | Description | +|-----------|-------------| +| **Sequential Model Loading** | Only one heavy model in VRAM at a time | +| **Tiled Inference** | 512ร—512 overlapping tiles for large images | +| **FP16 Autocast** | Halves activation memory on RTX cards | +| **CPU Offloading** | Large tensors kept on CPU, only tiles sent to GPU | +| **Lazy Loading** | Stable Diffusion loads only when needed | +| **Aggressive Cleanup** | `torch.cuda.empty_cache()` + `gc.collect()` between stages | + +--- + +## ๐Ÿš€ Getting Started + +### Prerequisites + +- **Python** 3.10 or higher +- **NVIDIA GPU** with 4GB+ VRAM and CUDA 12.x +- **16GB+ System RAM** (recommended) + +### Installation + +```bash +# 1. Clone the repository +git clone https://github.com/yourusername/creator-ai.git +cd creator-ai + +# 2. Create and activate virtual environment +python -m venv venv + +# Windows +venv\Scripts\activate + +# Linux/macOS +source venv/bin/activate + +# 3. Install PyTorch with CUDA support +pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 + +# 4. Install dependencies +pip install -r requirements.txt + +# 5. Download model weights (auto-downloads on first use, or pre-download) +python download_weights.py +``` + +### Launch the Dashboard + +```bash +cd src/ai_image_dashboard +python -m streamlit run app/streamlit_app.py +``` + +The dashboard will open at `http://localhost:8501`. + +### Docker Deployment + +```bash +docker build -t creator-ai . +docker run --gpus all -p 8501:8501 creator-ai +``` + +--- + +## โš™๏ธ Configuration + +All pipeline settings are controlled via YAML configuration files: + +```yaml +# src/ai_super_resolution/configs/config.yaml + +pipeline: + device: "cuda" + image_size_limit: 4096 + +modules: + quality_analysis: + blur_threshold: 0.7 # Above โ†’ activates Diffusion + detail_threshold: 0.5 # Below โ†’ activates SwinIR + noise_threshold: 0.6 # Above โ†’ activates denoiser + + face_enhancement: + fidelity_weight: 0.7 # 0.0 = max quality, 1.0 = max identity + + swinir_refinement: + tile_size: 512 # Larger = more VRAM, faster + + diffusion_refinement: + num_inference_steps: 20 # 20 = fast, 50 = max quality + guidance_scale: 4.0 # 4.0 = subtle, 7.5 = strong +``` + +--- + +## ๐Ÿงช Testing + +```bash +# Run the test suite +python -m pytest tests/ -v + +# Quick smoke test for SR pipeline +python -c " +from ai_super_resolution.sr_pipeline import SuperResolutionPipeline +import yaml, numpy as np + +config = yaml.safe_load(open('src/ai_super_resolution/configs/config.yaml')) +pipeline = SuperResolutionPipeline(config) + +# Test with a random image +test_img = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8) +result = pipeline.run(test_img, scale=2, mode='fast') +print(f'Input: 256x256 โ†’ Output: {result.shape[1]}x{result.shape[0]}') +" +``` + +--- + +## ๐Ÿ“Š Technical Specifications + +| Component | Details | +|-----------|---------| +| **Language** | Python 3.10+ | +| **Framework** | PyTorch 2.0+ | +| **UI** | Streamlit | +| **Codebase** | 110 files ยท 8,700+ lines | +| **AI Models** | 12+ (RealESRGAN, CodeFormer, SwinIR, SD, CRAFT, SAM, LaMa, GroundingDINO, YOLOv8, MiDaS, BiRefNet, MODNet, Zero-DCE, Restormer) | +| **Min GPU** | 4GB VRAM (RTX 3050) | +| **Max Output** | 8K resolution (8192ร—8192) | +| **Inference** | Tiled, FP16, sequential model loading | +| **Logging** | Structured Python logging | + +--- + +## ๐Ÿ—บ๏ธ Roadmap + +- [ ] Batch processing support +- [ ] API endpoint (FastAPI) +- [ ] Video super-resolution +- [ ] Custom model fine-tuning interface +- [ ] Cloud deployment (AWS/GCP) +- [ ] Plugin system for custom pipelines + +--- + +## ๐Ÿ“„ License + +This project is proprietary. All rights reserved. + +--- + +

+ Built with โค๏ธ using PyTorch, Streamlit, and 12+ state-of-the-art AI models +

diff --git a/assets/banner.png b/assets/banner.png new file mode 100644 index 0000000000000000000000000000000000000000..df08bb2701367796f7d4c7f804b3277149d93905 Binary files /dev/null and b/assets/banner.png differ diff --git a/download_weights.py b/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5cc245020b63fa5e668d599f1274c0628eb555 --- /dev/null +++ b/download_weights.py @@ -0,0 +1,19 @@ +import urllib.request +import os + +weights_dir = r"c:\Users\raj08\OneDrive\Documents\Machine Models\Text Removal\weights" +os.makedirs(weights_dir, exist_ok=True) + +urls = { + 'sam_vit_b_01ec64.pth': 'https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth', + 'modnet_photographic_portrait_matting.ckpt': 'https://huggingface.co/DavG25/modnet-pretrained-models/resolve/main/models/modnet_photographic_portrait_matting.ckpt' +} + +for name, url in urls.items(): + path = os.path.join(weights_dir, name) + print(f"Downloading {name}...") + try: + urllib.request.urlretrieve(url, path) + print(f"Downloaded {name} successfully. Size: {os.path.getsize(path)} bytes") + except Exception as e: + print(f"Failed to download {name}: {e}") diff --git a/libs/BasicSR b/libs/BasicSR new file mode 160000 index 0000000000000000000000000000000000000000..8d56e3a045f9fb3e1d8872f92ee4a4f07f886b0a --- /dev/null +++ b/libs/BasicSR @@ -0,0 +1 @@ +Subproject commit 8d56e3a045f9fb3e1d8872f92ee4a4f07f886b0a diff --git a/libs/CodeFormer b/libs/CodeFormer new file mode 160000 index 0000000000000000000000000000000000000000..b33cc7d639d6545bfcccc7e0bc6ae51f24e79c2b --- /dev/null +++ b/libs/CodeFormer @@ -0,0 +1 @@ +Subproject commit b33cc7d639d6545bfcccc7e0bc6ae51f24e79c2b diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7e61c3f36cb63643fd9e1a75865a8d7e00263f62 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,42 @@ +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Creator AI โ€” Dependencies +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + +# Core +torch>=2.0.0 +torchvision>=0.15.0 +numpy>=1.24.0 +opencv-python>=4.8.0 +Pillow>=10.0.0 +pyyaml>=6.0 + +# Dashboard +streamlit>=1.30.0 + +# Super Resolution +spandrel>=0.3.0 # Model loading (RealESRGAN, SwinIR) +facexlib>=0.3.0 # Face detection + restoration helpers +lpips>=0.1.4 # Perceptual loss (CodeFormer dependency) +diffusers>=0.25.0 # Stable Diffusion upscaler +transformers>=4.35.0 # HuggingFace models +accelerate>=0.25.0 # Model loading optimization +safetensors>=0.4.0 # Safe model format + +# Text Removal +craft-text-detector>=0.4.3 # Text detection + +# Object Removal +groundingdino-py>=0.4.0 # Object detection +ultralytics>=8.0.0 # YOLOv8 fallback detector + +# Background Removal +kornia>=0.6.0 # Geometry / vision utilities + +# Color Correction +# (uses models included in libs/) + +# Utilities +huggingface-hub>=0.20.0 # Weight downloads +scipy>=1.10.0 # Signal processing +scikit-image>=0.21.0 # Image metrics +tqdm>=4.65.0 # Progress bars diff --git a/src/ai_image_dashboard/__init__.py b/src/ai_image_dashboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..42ce2fc0762d645d57d0638e09ccc0e10a8835ed --- /dev/null +++ b/src/ai_image_dashboard/__init__.py @@ -0,0 +1 @@ +# AI Image Dashboard diff --git a/src/ai_image_dashboard/app/__init__.py b/src/ai_image_dashboard/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e78f39e54bc0ebcb22c60980a8112d9abf7cc704 --- /dev/null +++ b/src/ai_image_dashboard/app/__init__.py @@ -0,0 +1 @@ +# App subpackage diff --git a/src/ai_image_dashboard/app/config.py b/src/ai_image_dashboard/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7888265b28418d9ca9c00fd8486a45749d711623 --- /dev/null +++ b/src/ai_image_dashboard/app/config.py @@ -0,0 +1,54 @@ +""" +Centralized configuration for the AI Image Dashboard. +""" +import os + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Path Resolution +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +DASHBOARD_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC_DIR = os.path.dirname(DASHBOARD_DIR) +PROJECT_ROOT = os.path.dirname(SRC_DIR) +WEIGHTS_DIR = os.path.join(PROJECT_ROOT, "weights") + +# Sibling project directories +SUPER_RES_DIR = os.path.join(SRC_DIR, "ai_super_resolution") +TEXT_REMOVAL_DIR = os.path.join(SRC_DIR, "ai_text_removal") +COLOR_CORRECTION_DIR = os.path.join(SRC_DIR, "hybrid_color_correction") +OBJECT_REMOVAL_DIR = os.path.join(SRC_DIR, "object_removal_ai") + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Tool Definitions +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +TOOLS = { + "super_resolution": { + "name": "AI Super Resolution", + "icon": "๐Ÿ”", + "description": "Upscale images 2xโ€“4x with RealESRGAN + GFPGAN face enhancement", + "color": "#6C5CE7", + }, + "text_removal": { + "name": "AI Text Removal", + "icon": "๐Ÿ”ค", + "description": "Detect and remove text from images using EasyOCR + Big-LaMa inpainting", + "color": "#00B894", + }, + "color_correction": { + "name": "Color Correction", + "icon": "๐ŸŽจ", + "description": "Auto exposure + color balance (Zero-DCE++) with detail refinement (Restormer)", + "color": "#FDCB6E", + }, + "object_removal": { + "name": "Object Removal", + "icon": "โœ‚๏ธ", + "description": "Describe an object to auto-detect and remove it with GroundingDINO + SAM + LaMa", + "color": "#E17055", + }, + "background_removal": { + "name": "Background Removal", + "icon": "๐Ÿ–ผ๏ธ", + "description": "Adaptive 5-stage pipeline โ€” BiRefNet + SAM + MODNet with scene-aware routing", + "color": "#0984E3", + }, +} diff --git a/src/ai_image_dashboard/app/streamlit_app.py b/src/ai_image_dashboard/app/streamlit_app.py new file mode 100644 index 0000000000000000000000000000000000000000..82a1e5ac65180f3aaa90da0961b5e8a7cc815a48 --- /dev/null +++ b/src/ai_image_dashboard/app/streamlit_app.py @@ -0,0 +1,752 @@ +""" +CreatorAI โ€” Unified AI Image Processing Studio +""" +import streamlit as st +import os +import sys +import time +import numpy as np +import cv2 +import torch + +# โ”€โ”€ Path Setup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +DASHBOARD_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC_DIR = os.path.dirname(DASHBOARD_DIR) +PROJECT_ROOT = os.path.dirname(SRC_DIR) + +if DASHBOARD_DIR not in sys.path: + sys.path.insert(0, DASHBOARD_DIR) + +from utils.image_utils import bytes_to_rgb, rgb_to_png_bytes, resize_safe +from app.config import TOOLS + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Page Config +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +st.set_page_config( + page_title="CreatorAI Studio", + page_icon="๐Ÿš€", + layout="wide", + initial_sidebar_state="expanded", +) + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Premium CSS +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +st.markdown(""" + +""", unsafe_allow_html=True) + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Session State +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +if "current_tool" not in st.session_state: + st.session_state.current_tool = None +if "original_image" not in st.session_state: + st.session_state.original_image = None +if "processed_image" not in st.session_state: + st.session_state.processed_image = None +if "history" not in st.session_state: + st.session_state.history = [] +if "process_time" not in st.session_state: + st.session_state.process_time = 0.0 + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Cached Model Loaders +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +@st.cache_resource +def load_super_resolution(): + from pipelines import super_resolution_pipeline + return super_resolution_pipeline.get_pipeline() + +@st.cache_resource +def load_text_removal(): + from pipelines import text_removal_pipeline + return text_removal_pipeline.get_pipeline() + +@st.cache_resource +def load_color_correction(): + from pipelines import color_pipeline + return color_pipeline.get_pipeline() + +@st.cache_resource +def load_object_removal(): + from pipelines import object_pipeline + return object_pipeline.get_pipeline() + +@st.cache_resource +def load_background_removal(): + from pipelines import background_pipeline + return background_pipeline.get_pipeline() + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# SIDEBAR +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +with st.sidebar: + # โ”€โ”€ Brand โ”€โ”€ + st.markdown(""" + + + """, unsafe_allow_html=True) + + # โ”€โ”€ GPU Status โ”€โ”€ + gpu_available = torch.cuda.is_available() + if gpu_available: + gpu_name = torch.cuda.get_device_name(0) + vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3) + dot_class = "dot" + status_text = f"{gpu_name} โ€ข {vram_gb:.1f}GB" + else: + dot_class = "dot cpu" + status_text = "CPU Mode" + + st.markdown(f""" +
+
+ {status_text} +
+ """, unsafe_allow_html=True) + + st.markdown("") # spacer + + # โ”€โ”€ Tool Selection โ”€โ”€ + st.markdown('', unsafe_allow_html=True) + st.markdown('', unsafe_allow_html=True) + + for tool_key, tool_info in TOOLS.items(): + is_active = st.session_state.current_tool == tool_key + container_class = "active-tool-btn" if is_active else "" + + with st.container(): + if is_active: + st.markdown(f'
', unsafe_allow_html=True) + if st.button( + f"{tool_info['icon']} {tool_info['name']}", + key=f"tool_{tool_key}", + width='stretch', + ): + st.session_state.current_tool = tool_key + st.session_state.processed_image = None + st.session_state.process_time = 0.0 + st.rerun() + if is_active: + st.markdown('
', unsafe_allow_html=True) + + + + # โ”€โ”€ History โ”€โ”€ + if st.session_state.history: + st.markdown("") + st.markdown("") + st.markdown('', unsafe_allow_html=True) + st.markdown('', unsafe_allow_html=True) + + for entry in reversed(st.session_state.history[-4:]): + st.markdown(f"  {entry['tool_icon']} {entry['tool_name']} โ€” *{entry['time']}*") + + st.markdown("") + if st.button("โ†ฉ๏ธ Undo Last", width='stretch', key="undo_btn"): + if st.session_state.history: + last = st.session_state.history.pop() + st.session_state.processed_image = last.get("prev_image") + st.rerun() + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# MAIN CONTENT +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + +if st.session_state.current_tool is None: + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Landing Page + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + st.markdown(""" +
+

๐Ÿš€ CreatorAI Studio

+
+ Production-grade AI image processing. Select a tool from the sidebar to begin. +
+
+ """, unsafe_allow_html=True) + + cols = st.columns(5, gap="medium") + for i, (key, info) in enumerate(TOOLS.items()): + with cols[i]: + st.markdown(f""" +
+
{info['icon']}
+
{info['name']}
+
{info['description']}
+
+ """, unsafe_allow_html=True) + +else: + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Tool Processing Page + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + tool = TOOLS[st.session_state.current_tool] + + # โ”€โ”€ Mini Header โ”€โ”€ + st.markdown(f""" +
+ {tool['icon']} +
+
{tool['name']}
+
{tool['description']}
+
+
+ """, unsafe_allow_html=True) + + # โ”€โ”€ Default Tool Settings โ”€โ”€ + sr_scale = 4 + sr_mode = "fast" + cc_restormer = True + or_prompt = "" + bg_mode = "auto" + bg_show_metrics = False + + # โ”€โ”€ Tool-Specific Settings UI โ”€โ”€ + if st.session_state.current_tool in ["super_resolution", "color_correction", "object_removal", "background_removal"]: + with st.container(border=True): + st.markdown("##### โš™๏ธ Settings") + if st.session_state.current_tool == "super_resolution": + sc_col1, sc_col2 = st.columns(2) + with sc_col1: + sr_scale = st.select_slider("Upscale Factor", options=[2, 4], value=4) + with sc_col2: + sr_mode = st.selectbox( + "๐Ÿง  Processing Mode", + options=["fast", "balanced", "hd"], + index=0, + format_func=lambda x: {"fast": "โšก Fast (~15s)", "balanced": "โš–๏ธ Balanced (~45s)", "hd": "๐ŸŽจ HD (~3min)"}[x], + help="Fast: RealESRGAN + auto face restore | Balanced: + SwinIR if needed | HD: + Diffusion for extreme detail", + ) + elif st.session_state.current_tool == "color_correction": + cc_restormer = st.toggle("โœจ Restormer Refinement", value=True, help="Sharper details, less noise โ€” uses more VRAM") + elif st.session_state.current_tool == "object_removal": + or_prompt = st.text_input("๐ŸŽฏ Describe the object", placeholder="person, car, sign, etc.", help="What should CreatorAI remove from the image?") + elif st.session_state.current_tool == "background_removal": + bg_col1, bg_col2 = st.columns(2) + with bg_col1: + bg_mode = st.selectbox( + "๐Ÿง  Pipeline Mode", + options=["auto", "simple", "complex"], + index=0, + help="Auto: adapts per scene | Simple: portraits (fast) | Complex: products (precise)", + ) + with bg_col2: + st.markdown("
", unsafe_allow_html=True) + bg_show_metrics = st.toggle("๐Ÿ“Š Show Latency Metrics", value=True, help="Display per-stage timing breakdown") + st.markdown("
", unsafe_allow_html=True) + + # โ”€โ”€ Upload โ”€โ”€ + uploaded = st.file_uploader( + "Drop your image here", + type=["jpg", "jpeg", "png", "bmp", "webp"], + key="uploader", + label_visibility="collapsed", + ) + + if uploaded is not None: + image_bytes = uploaded.read() + img_rgb = bytes_to_rgb(image_bytes) + st.session_state.original_image = img_rgb + + # โ”€โ”€ Action Bar โ”€โ”€ + act_col1, act_col2, act_col3, act_col4 = st.columns([3, 1.2, 1.2, 1.5]) + + with act_col1: + st.markdown('
', unsafe_allow_html=True) + process_btn = st.button( + f"โšก Process with {tool['name']}", + width='stretch', + key="process_btn", + ) + st.markdown('
', unsafe_allow_html=True) + + with act_col2: + st.markdown('
', unsafe_allow_html=True) + reset_btn = st.button("๐Ÿ”„ Reset", width='stretch', key="reset_btn") + st.markdown('
', unsafe_allow_html=True) + + with act_col3: + if st.session_state.processed_image is not None: + processed = st.session_state.processed_image + # Handle RGBA (background removal) + if len(processed.shape) == 3 and processed.shape[2] == 4: + # Encode as PNG with alpha + success, buf = cv2.imencode(".png", cv2.cvtColor(processed, cv2.COLOR_RGBA2BGRA)) + dl_bytes = buf.tobytes() if success else b"" + else: + dl_bytes = rgb_to_png_bytes(processed) + st.download_button( + "๐Ÿ“ฅ Download", + data=dl_bytes, + file_name=f"creatorai_{st.session_state.current_tool}.png", + mime="image/png", + width='stretch', + key="dl_btn", + ) + + with act_col4: + if st.session_state.process_time > 0: + st.markdown(f""" +
+ + {st.session_state.process_time:.1f}s + +
+ + Process Time + +
+ """, unsafe_allow_html=True) + + # โ”€โ”€ Reset Logic โ”€โ”€ + if reset_btn: + st.session_state.processed_image = None + st.session_state.process_time = 0.0 + st.session_state.last_processed_tool = None + st.rerun() + + # โ”€โ”€ Processing Logic โ”€โ”€ + if process_btn: + with st.spinner(f"๐Ÿ”ฎ CreatorAI is processing your image..."): + start = time.time() + prev_image = st.session_state.processed_image + last_tool = st.session_state.get("last_processed_tool", None) + + # Chain: if already processed BY A DIFFERENT TOOL, use that as input + if prev_image is not None and last_tool != st.session_state.current_tool: + input_img = prev_image + else: + input_img = img_rgb + + # Handle RGBA โ†’ RGB for chaining (if previous was bg removal) + if len(input_img.shape) == 3 and input_img.shape[2] == 4: + input_img = cv2.cvtColor(input_img, cv2.COLOR_RGBA2RGB) + + try: + result = None + + if st.session_state.current_tool == "super_resolution": + pipeline = load_super_resolution() + from pipelines import super_resolution_pipeline + result = super_resolution_pipeline.process( + pipeline, input_img, + scale=sr_scale, mode=sr_mode + ) + + elif st.session_state.current_tool == "text_removal": + pipeline = load_text_removal() + from pipelines import text_removal_pipeline + result = text_removal_pipeline.process(pipeline, input_img) + + elif st.session_state.current_tool == "color_correction": + pipeline = load_color_correction() + from pipelines import color_pipeline + result = color_pipeline.process( + pipeline, input_img, use_restormer=cc_restormer + ) + + elif st.session_state.current_tool == "object_removal": + if not or_prompt: + st.warning("โš ๏ธ Please describe the object to remove in the sidebar.") + else: + pipeline = load_object_removal() + from pipelines import object_pipeline + result = object_pipeline.process(pipeline, input_img, prompt=or_prompt) + + elif st.session_state.current_tool == "background_removal": + pipeline = load_background_removal() + from pipelines import background_pipeline + result, bg_metrics = background_pipeline.process( + pipeline, input_img, mode=bg_mode, return_metrics=True + ) + st.session_state.bg_metrics = bg_metrics + st.session_state.bg_scene_type = bg_metrics.get("scene_type", "") + + elapsed = time.time() - start + + if result is not None: + st.session_state.processed_image = result + st.session_state.process_time = elapsed + st.session_state.last_processed_tool = st.session_state.current_tool + st.session_state.history.append({ + "tool_name": tool["name"], + "tool_icon": tool["icon"], + "time": f"{elapsed:.1f}s", + "prev_image": prev_image, + }) + st.rerun() + + except Exception as e: + st.error(f"โŒ Processing failed: {str(e)}") + with st.expander("๐Ÿ” Error Details"): + st.exception(e) + + # โ”€โ”€ Image Display โ”€โ”€ + st.markdown("---") + + if st.session_state.processed_image is not None: + # โ”€โ”€ Before / After โ”€โ”€ + col1, col2 = st.columns(2, gap="medium") + + with col1: + st.markdown('
๐Ÿ“ท Original
', unsafe_allow_html=True) + st.markdown('
', unsafe_allow_html=True) + st.image(img_rgb, width='stretch') + st.markdown('
', unsafe_allow_html=True) + oh, ow = img_rgb.shape[:2] + st.caption(f"{ow} ร— {oh} px") + + with col2: + st.markdown('
โœจ Processed
', unsafe_allow_html=True) + st.markdown('
', unsafe_allow_html=True) + processed = st.session_state.processed_image + st.image(processed, width='stretch') + st.markdown('
', unsafe_allow_html=True) + ph, pw = processed.shape[:2] + ch = "RGBA" if (len(processed.shape) == 3 and processed.shape[2] == 4) else "RGB" + st.caption(f"{pw} ร— {ph} px โ€ข {ch}") + + # โ”€โ”€ Background Removal Metrics โ”€โ”€ + if (st.session_state.current_tool == "background_removal" + and bg_show_metrics + and hasattr(st.session_state, "bg_metrics") + and st.session_state.bg_metrics): + m = st.session_state.bg_metrics + scene_type = m.get("scene_type", "N/A") + scene_color = "#10B981" if scene_type == "SIMPLE" else "#F59E0B" + st.markdown(f""" +
+
+ Pipeline Metrics + {scene_type} +
+
+
+
{m.get('stage2_birefnet_ms', 0):.0f}ms
+
BiRefNet SOD
+
+
+
{m.get('stage3_routing_ms', 0):.1f}ms
+
Scene Routing
+
+
+
{m.get('stage3b_sam_ms', 0):.0f}ms
+
SAM Segment
+
+
+
{m.get('stage4_matting_ms', 0):.0f}ms
+
MODNet Alpha
+
+
+
{m.get('stage5_postprocess_ms', 0):.0f}ms
+
Postprocess
+
+
+
+ """, unsafe_allow_html=True) + + else: + # โ”€โ”€ Just show the uploaded image โ”€โ”€ + st.markdown('
๐Ÿ“ท Uploaded Image
', unsafe_allow_html=True) + st.markdown('
', unsafe_allow_html=True) + st.image(img_rgb, width='stretch') + st.markdown('
', unsafe_allow_html=True) + oh, ow = img_rgb.shape[:2] + st.caption(f"{ow} ร— {oh} px โ€ข Ready to process") + + else: + # โ”€โ”€ Empty state โ”€โ”€ + st.markdown(""" +
+
๐Ÿ“
+
+ Upload an image to get started +
+
+ Supports JPG, PNG, BMP, WEBP โ€” up to 200MB +
+
+ """, unsafe_allow_html=True) diff --git a/src/ai_image_dashboard/pipelines/__init__.py b/src/ai_image_dashboard/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a80b5d231345f5d04d25a5c8fd700d38a2afd18f --- /dev/null +++ b/src/ai_image_dashboard/pipelines/__init__.py @@ -0,0 +1 @@ +# Pipelines subpackage diff --git a/src/ai_image_dashboard/pipelines/background_pipeline.py b/src/ai_image_dashboard/pipelines/background_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..45bcc5ff4b0e5bacb51c012aa5728ab8a8e81ced --- /dev/null +++ b/src/ai_image_dashboard/pipelines/background_pipeline.py @@ -0,0 +1,56 @@ +""" +Background Removal Pipeline โ€” 5-Stage Adaptive Engine +Uses BiRefNet (SOD) + SAM ViT-B (segmentation) + MODNet (alpha matting) +in a unified pipeline that adapts processing based on scene complexity. + +Replaces the previous rembg/Uยฒ-Net implementation with a production-grade +Photoroom-style adaptive pipeline. +""" +import sys +import os +import numpy as np + +# Inject background_removal package into sys.path +_BG_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "background_removal") +_BG_DIR = os.path.abspath(_BG_DIR) +if _BG_DIR not in sys.path: + sys.path.insert(0, _BG_DIR) + + +def get_pipeline(): + """ + Returns the BackgroundRemovalEngine (designed for @st.cache_resource). + All 3 models (~1.2GB total) are loaded into VRAM once and reused. + """ + from inference.engine import BackgroundRemovalEngine + engine = BackgroundRemovalEngine(load_sam=True) + engine.load() + return engine + + +def process(pipeline, image_rgb: np.ndarray, mode: str = "auto", + return_metrics: bool = False) -> np.ndarray: + """ + Remove background from an RGB image using the 5-stage adaptive pipeline. + + Args: + pipeline: Cached BackgroundRemovalEngine instance + image_rgb: Input image (H, W, 3) uint8 RGB + mode: Pipeline mode โ€” "auto" (adaptive), "simple" (portrait), "complex" (product) + return_metrics: If True, returns (rgba, metrics) tuple instead of just rgba + + Returns: + RGBA image with background removed (H, W, 4) uint8 + OR (RGBA, metrics_dict) if return_metrics=True + """ + # Map mode to force_mode parameter + force_mode = None if mode == "auto" else mode + + result = pipeline.run(image_rgb, force_mode=force_mode) + + if return_metrics: + metrics = result["metrics"] + metrics["scene_type"] = result["scene_type"] + return result["rgba"], metrics + + return result["rgba"] diff --git a/src/ai_image_dashboard/pipelines/color_pipeline.py b/src/ai_image_dashboard/pipelines/color_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..1940f44bed7904ecf970efb3379ac5cf25d95cd2 --- /dev/null +++ b/src/ai_image_dashboard/pipelines/color_pipeline.py @@ -0,0 +1,46 @@ +""" +Color Correction Pipeline Wrapper +Delegates to: src/hybrid_color_correction/pipeline/enhance.HybridEnhancer +""" +import sys +import os +import numpy as np +import torch + +# Inject sibling project into sys.path +_CC_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "hybrid_color_correction") +_CC_DIR = os.path.abspath(_CC_DIR) +if _CC_DIR not in sys.path: + sys.path.insert(0, _CC_DIR) + + +def get_pipeline(): + """Lazily creates the HybridEnhancer (designed for @st.cache_resource).""" + from hc_pipeline.enhance import HybridEnhancer + device = "cuda" if torch.cuda.is_available() else "cpu" + return HybridEnhancer(device=device) + + +def process(pipeline, image_rgb: np.ndarray, use_restormer: bool = True) -> np.ndarray: + """ + Run hybrid color correction on an RGB image. + + Args: + pipeline: Cached HybridEnhancer instance + image_rgb: Input image (H, W, 3) uint8 RGB + use_restormer: Enable Restormer detail refinement + + Returns: + Color-corrected RGB image + """ + from hc_pipeline.preprocess import preprocess_image + from hc_pipeline.postprocess import postprocess_tensor + + # Preprocess: resize to max 512px and convert to tensor + tensor = preprocess_image(image_rgb, max_size=512) + + # Enhance + out_tensor = pipeline.enhance(tensor, use_restormer=use_restormer) + + # Postprocess: tensor -> uint8 numpy + return postprocess_tensor(out_tensor) diff --git a/src/ai_image_dashboard/pipelines/object_pipeline.py b/src/ai_image_dashboard/pipelines/object_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..b3222225e1f19053149daad3e89b031bf1c16f46 --- /dev/null +++ b/src/ai_image_dashboard/pipelines/object_pipeline.py @@ -0,0 +1,35 @@ +""" +Object Removal Pipeline Wrapper +Delegates to: src/object_removal_ai/main_pipeline.ObjectRemovalPipeline +""" +import sys +import os +import numpy as np + +# Inject sibling project into sys.path +_OR_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "object_removal_ai") +_OR_DIR = os.path.abspath(_OR_DIR) +if _OR_DIR not in sys.path: + sys.path.insert(0, _OR_DIR) + + +def get_pipeline(): + """Lazily creates the ObjectRemovalPipeline (designed for @st.cache_resource).""" + from main_pipeline import ObjectRemovalPipeline + return ObjectRemovalPipeline() + + +def process(pipeline, image_rgb: np.ndarray, prompt: str = "object") -> np.ndarray: + """ + Remove described objects from an RGB image. + + Args: + pipeline: Cached ObjectRemovalPipeline instance + image_rgb: Input image (H, W, 3) uint8 RGB + prompt: Text prompt describing what to remove (e.g. "person", "car") + + Returns: + Cleaned RGB image with objects removed + """ + result = pipeline.run(image_rgb, prompt=prompt) + return result["result"] diff --git a/src/ai_image_dashboard/pipelines/super_resolution_pipeline.py b/src/ai_image_dashboard/pipelines/super_resolution_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..650c7b50e24092964d59983cfe219e70213be239 --- /dev/null +++ b/src/ai_image_dashboard/pipelines/super_resolution_pipeline.py @@ -0,0 +1,48 @@ +""" +Super Resolution Pipeline Wrapper +Delegates to: src/ai_super_resolution/sr_pipeline.SuperResolutionPipeline +""" +import sys +import os +import yaml +import numpy as np + +# Inject sibling project into sys.path +_SR_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "ai_super_resolution") +_SR_DIR = os.path.abspath(_SR_DIR) +if _SR_DIR not in sys.path: + sys.path.insert(0, _SR_DIR) + +_PROJECT_ROOT = os.path.abspath(os.path.join(_SR_DIR, "..", "..")) + + +def _load_config(): + config_path = os.path.join(_SR_DIR, "configs", "config.yaml") + with open(config_path, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + config["paths"]["weights_dir"] = os.path.join(_PROJECT_ROOT, config["paths"]["weights_dir"]) + return config + + +def get_pipeline(): + """Lazily creates the SuperResolutionPipeline (designed for @st.cache_resource).""" + from sr_pipeline import SuperResolutionPipeline + config = _load_config() + return SuperResolutionPipeline(config) + + +def process(pipeline, image_rgb: np.ndarray, scale: int = 4, + mode: str = "fast") -> np.ndarray: + """ + Run super-resolution on an RGB image. + + Args: + pipeline: Cached SuperResolutionPipeline instance + image_rgb: Input image (H, W, 3) uint8 RGB + scale: Upscale factor (2 or 4) + mode: "fast", "balanced", or "hd" + + Returns: + Upscaled RGB image + """ + return pipeline.run(image_rgb, scale=scale, mode=mode) diff --git a/src/ai_image_dashboard/pipelines/text_removal_pipeline.py b/src/ai_image_dashboard/pipelines/text_removal_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..6de285cf165b747515869f9da43a66e9e4efd1c0 --- /dev/null +++ b/src/ai_image_dashboard/pipelines/text_removal_pipeline.py @@ -0,0 +1,34 @@ +""" +Text Removal Pipeline Wrapper +Delegates to: src/ai_text_removal/tr_pipeline.TextRemovalPipeline +""" +import sys +import os +import numpy as np + +# Inject sibling project into sys.path +_TR_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "ai_text_removal") +_TR_DIR = os.path.abspath(_TR_DIR) +if _TR_DIR not in sys.path: + sys.path.insert(0, _TR_DIR) + + +def get_pipeline(): + """Lazily creates the TextRemovalPipeline (designed for @st.cache_resource).""" + from tr_pipeline import TextRemovalPipeline + return TextRemovalPipeline() + + +def process(pipeline, image_rgb: np.ndarray) -> np.ndarray: + """ + Remove text from an RGB image. + + Args: + pipeline: Cached TextRemovalPipeline instance + image_rgb: Input image (H, W, 3) uint8 RGB + + Returns: + Cleaned RGB image with text removed + """ + result = pipeline.run(image_rgb, enable_diffusion=True) + return result["result"] diff --git a/src/ai_image_dashboard/utils/__init__.py b/src/ai_image_dashboard/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5878af70d17842d495284aae604ae8f5da3468 --- /dev/null +++ b/src/ai_image_dashboard/utils/__init__.py @@ -0,0 +1 @@ +# Utils subpackage diff --git a/src/ai_image_dashboard/utils/image_utils.py b/src/ai_image_dashboard/utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2212f5ca7ec4afc0337311e6749fb81a33a7a6 --- /dev/null +++ b/src/ai_image_dashboard/utils/image_utils.py @@ -0,0 +1,34 @@ +""" +Unified image utilities for the AI Image Dashboard. +""" +import cv2 +import numpy as np + + +def bytes_to_rgb(image_bytes: bytes) -> np.ndarray: + """Convert uploaded file bytes to an RGB numpy array.""" + nparr = np.frombuffer(image_bytes, np.uint8) + image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR) + if image_bgr is None: + raise ValueError("Could not decode uploaded image.") + return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + + +def rgb_to_png_bytes(image_rgb: np.ndarray) -> bytes: + """Convert an RGB numpy array to PNG bytes for Streamlit download.""" + image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) + success, buffer = cv2.imencode(".png", image_bgr) + if not success: + raise ValueError("Failed to encode image to PNG.") + return buffer.tobytes() + + +def resize_safe(image: np.ndarray, max_size: int = 1024) -> np.ndarray: + """Resize an image so the longest side is at most max_size, preserving aspect ratio.""" + h, w = image.shape[:2] + if max(h, w) <= max_size: + return image + scale = max_size / max(h, w) + new_w = max(8, int(w * scale) // 8 * 8) + new_h = max(8, int(h * scale) // 8 * 8) + return cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) diff --git a/src/ai_super_resolution/configs/config.yaml b/src/ai_super_resolution/configs/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a0f136cb41a11f51a4ae204ba70b8dbf4dfd88b --- /dev/null +++ b/src/ai_super_resolution/configs/config.yaml @@ -0,0 +1,66 @@ +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Smart Adaptive AI Super-Resolution โ€” Master Configuration +# Quality-Aware Pipeline (RealESRGAN + CodeFormer + SwinIR + SD) +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + +pipeline: + device: "cuda" + image_size_limit: 4096 # Max input dimension before safety downscale + +paths: + weights_dir: "weights" + output_dir: "outputs/upscaled" + +# โ”€โ”€ Module Toggles โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +modules: + input_validation: + enabled: true + + # Quality Analysis โ€” drives conditional routing + quality_analysis: + blur_threshold: 0.7 # Above โ†’ run Diffusion (HD mode only) + detail_threshold: 0.5 # Below โ†’ run SwinIR (Balanced/HD mode) + noise_threshold: 0.6 # Above โ†’ auto-denoise + + denoiser: + enabled: true # Edge-preserving denoising + strength: 5 + + tile_engine: + enabled: true + tile_size: 512 + overlap: 64 # Overlap for Gaussian fusion + + upscaling: + enabled: true + model_name: "RealESRGAN_x4plus" + default_scale: 4 + + # CodeFormer โ€” auto-activated when face detected + face_enhancement: + enabled: true + model: "codeformer" + fidelity_weight: 0.7 # 0.0 = max quality, 1.0 = max identity + face_weight: 0.7 # Blending weight for face paste-back + + # SwinIR โ€” activated in Balanced/HD mode if detail is low + swinir_refinement: + enabled: true + model_name: "SwinIR_large_x4" + tile_size: 512 + + # Stable Diffusion โ€” activated in HD mode if image is very blurry + diffusion_refinement: + enabled: true + num_inference_steps: 20 # 20 = fast, 50 = max quality + guidance_scale: 4.0 # 4.0 = subtle, 7.5 = strong + + color_matching: + enabled: true + method: "histogram" # histogram matching in LAB space + + post_processing: + enabled: true + sharpen: true + sharpen_strength: 0.3 + edge_aware_smooth: true # Bilateral filter for GAN artifact removal diff --git a/src/ai_super_resolution/inference.py b/src/ai_super_resolution/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c284a2b6e6b555b587e4f572c9b1ac4c185f15 --- /dev/null +++ b/src/ai_super_resolution/inference.py @@ -0,0 +1,81 @@ +""" +AI Super-Resolution โ€” CLI Entry Point + +Usage: + python inference.py -i photo.jpg --scale 4 --face-enhance + python inference.py -i photo.jpg --scale 2 --no-denoise +""" +import os +import sys +import argparse +import yaml +import time + +# Add current dir to path for imports +script_dir = os.path.dirname(os.path.abspath(__file__)) +if script_dir not in sys.path: + sys.path.insert(0, script_dir) + +from utils.image_utils import load_image, save_image +from sr_pipeline import SuperResolutionPipeline + + +def main(): + parser = argparse.ArgumentParser(description="Production AI Super-Resolution CLI") + parser.add_argument("--input", "-i", type=str, required=True, help="Input image path") + parser.add_argument("--output", "-o", type=str, default=None, help="Output image path") + parser.add_argument("--scale", "-s", type=int, choices=[2, 4, 8], default=4, help="Upscale factor") + parser.add_argument("--config", "-c", type=str, + default=os.path.join(script_dir, "configs", "config.yaml"), + help="Path to config file") + parser.add_argument("--no-denoise", action="store_true", help="Skip pre-restoration denoising") + parser.add_argument("--face-enhance", action="store_true", help="Enable GFPGAN face reconstruction") + args = parser.parse_args() + + # โ”€โ”€ Load config โ”€โ”€ + if not os.path.exists(args.config): + print(f"Error: Config not found at {args.config}") + return + + with open(args.config, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + + # Resolve weights dir to absolute path + project_root = os.path.abspath(os.path.join(script_dir, "..", "..")) + config["paths"]["weights_dir"] = os.path.join(project_root, config["paths"]["weights_dir"]) + + # โ”€โ”€ Initialize Pipeline โ”€โ”€ + sr_pipeline = SuperResolutionPipeline(config) + + # โ”€โ”€ Load Image โ”€โ”€ + print(f"\nLoading: {args.input}") + try: + image = load_image(args.input) + except Exception as e: + print(f"Error loading image: {e}") + return + + # โ”€โ”€ Run Pipeline โ”€โ”€ + upscaled = sr_pipeline.run( + image, + scale=args.scale, + denoise=not args.no_denoise, + face_enhance=args.face_enhance, + ) + + # โ”€โ”€ Save Output โ”€โ”€ + out_dir = os.path.join(project_root, config["paths"]["output_dir"]) + os.makedirs(out_dir, exist_ok=True) + + if args.output: + out_path = args.output + else: + name, ext = os.path.splitext(os.path.basename(args.input)) + out_path = os.path.join(out_dir, f"{name}_x{args.scale}{ext}") + + save_image(upscaled, out_path) + print(f"\n โ†’ Saved to: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/src/ai_super_resolution/models/__init__.py b/src/ai_super_resolution/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9408b62e8b806d4d0131b6bd6a2e4e2d114722 --- /dev/null +++ b/src/ai_super_resolution/models/__init__.py @@ -0,0 +1 @@ +# AI Super-Resolution โ€” Model Wrappers diff --git a/src/ai_super_resolution/models/codeformer_enhancer.py b/src/ai_super_resolution/models/codeformer_enhancer.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b6a6a030b5efae2b9c27c665fae63b3a08aaa0 --- /dev/null +++ b/src/ai_super_resolution/models/codeformer_enhancer.py @@ -0,0 +1,244 @@ +""" +CodeFormer Face Restoration Module + +Replaces GFPGAN with CodeFormer for superior identity-preserving face restoration. +Uses facexlib for face detection/alignment and CodeFormer for restoration. + +Auto-downloads weights on first use. +""" +import os +import cv2 +import torch +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.codeformer_enhancer") + +try: + from facexlib.utils.face_restoration_helper import FaceRestoreHelper + HAS_FACEXLIB = True +except ImportError: + HAS_FACEXLIB = False + +try: + from huggingface_hub import hf_hub_download + HAS_HF_HUB = True +except ImportError: + HAS_HF_HUB = False + + +def _download_codeformer_weights(weights_dir: str) -> str: + """Download CodeFormer weights from HuggingFace if not present.""" + weight_path = os.path.join(weights_dir, "codeformer.pth") + if os.path.exists(weight_path): + return weight_path + + if not HAS_HF_HUB: + logger.info("[CodeFormer] huggingface_hub not installed. Cannot download weights.") + return None + + logger.info("[CodeFormer] Downloading codeformer.pth from HuggingFace...") + try: + downloaded = hf_hub_download( + repo_id="sczhou/CodeFormer", + filename="CodeFormer/codeformer.pth", + local_dir=weights_dir, + local_dir_use_symlinks=False, + ) + # Move to expected location if nested + if downloaded != weight_path and os.path.exists(downloaded): + os.makedirs(os.path.dirname(weight_path), exist_ok=True) + os.rename(downloaded, weight_path) + logger.info(f"[CodeFormer] Saved weights to {weight_path}") + return weight_path + except Exception as e: + logger.info(f"[CodeFormer] HuggingFace download failed: {e}") + # Fallback to direct download + try: + from urllib.request import urlretrieve + url = "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth" + logger.info(f"[CodeFormer] Trying direct download from GitHub releases...") + urlretrieve(url, weight_path) + logger.info(f"[CodeFormer] Saved weights to {weight_path}") + return weight_path + except Exception as e2: + logger.info(f"[CodeFormer] Direct download also failed: {e2}") + return None + + +class CodeFormerEnhancer: + """ + CodeFormer-based face restoration. + + Better identity preservation than GFPGAN due to codebook-based + discrete representation learning. Supports fidelity_weight to + balance quality vs. identity. + """ + + def __init__(self, weights_dir: str, fidelity_weight: float = 0.7, + face_weight: float = 0.7, upscale: int = 4, device: str = "cuda"): + """ + Args: + weights_dir: Directory containing/to-download codeformer.pth + fidelity_weight: 0.0 = max quality, 1.0 = max fidelity (identity) + face_weight: Blending weight when pasting face back (0-1) + upscale: Upscale factor for face helper + device: 'cuda' or 'cpu' + """ + self.device = torch.device(device if torch.cuda.is_available() else "cpu") + self.fidelity_weight = fidelity_weight + self.face_weight = face_weight + self.upscale = upscale + self.model = None + self.face_helper = None + + if not HAS_FACEXLIB: + logger.info("[CodeFormer] โš  facexlib not installed. Face enhancement disabled.") + return + + # Download weights if needed + weight_path = _download_codeformer_weights(weights_dir) + if weight_path is None or not os.path.exists(weight_path): + logger.info("[CodeFormer] โš  Weights not available. Face enhancement disabled.") + return + + try: + # Patch collections for basicsr in Python 3.10+ (Iterable was removed) + import collections + import collections.abc + for attr in ['Iterable', 'Mapping', 'MutableSet', 'MutableMapping', 'Sequence']: + if not hasattr(collections, attr): + setattr(collections, attr, getattr(collections.abc, attr)) + + # Add local BasicSR + CodeFormer repos to sys.path + import sys + basicsr_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "libs", "BasicSR")) + codeformer_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "libs", "CodeFormer")) + + # CRITICAL: Flush any pip-installed basicsr from the module cache. + # The pip version (1.4.2) doesn't have codeformer_arch.py. + # We must force Python to re-import from our local libs/ copy. + mods_to_remove = [k for k in sys.modules if k == "basicsr" or k.startswith("basicsr.")] + for mod in mods_to_remove: + del sys.modules[mod] + + # Now inject our local paths BEFORE pip site-packages + if basicsr_path not in sys.path: + sys.path.insert(0, basicsr_path) + if codeformer_path not in sys.path: + sys.path.insert(1, codeformer_path) + + import basicsr.archs.codeformer_arch # This registers CodeFormer in ARCH_REGISTRY + from basicsr.utils.registry import ARCH_REGISTRY + + + # Load CodeFormer model + self.model = ARCH_REGISTRY.get("CodeFormer")( + dim_embd=512, codebook_size=1024, n_head=8, + n_layers=9, connect_list=["32", "64", "128", "256"], + ).to(self.device) + + ckpt = torch.load(weight_path, map_location="cpu", weights_only=True) + self.model.load_state_dict( + ckpt.get("params_ema", ckpt.get("params", ckpt)), + strict=True + ) + self.model.eval() + + # Init face helper for detection + alignment + paste-back + self.face_helper = FaceRestoreHelper( + upscale_factor=1, # Image is already upscaled by RealESRGAN + face_size=512, + crop_ratio=(1, 1), + det_model="retinaface_resnet50", + save_ext="png", + use_parse=True, + device=self.device, + ) + + logger.info(f"[CodeFormer] โœ… Loaded on {self.device} " + f"(fidelity={fidelity_weight}, face_weight={face_weight})") + except Exception as e: + logger.warning(f"[CodeFormer] โš  Failed to load: {e}. Face enhancement disabled.") + self.model = None + self.face_helper = None + + @property + def available(self) -> bool: + return self.model is not None and self.face_helper is not None + + @torch.no_grad() + def enhance(self, image_bgr: np.ndarray) -> np.ndarray: + """ + Detect faces, restore with CodeFormer, and paste back. + + Args: + image_bgr: BGR uint8 (H, W, 3) + + Returns: + Enhanced BGR image with restored faces + """ + if not self.available: + logger.info("[CodeFormer] Not available, returning input unchanged.") + return image_bgr + + try: + self.face_helper.clean_all() + self.face_helper.read_image(image_bgr) + + # Detect and align faces + num_faces = self.face_helper.get_face_landmarks_5( + only_center_face=False, resize=640, eye_dist_threshold=5 + ) + self.face_helper.align_warp_face() + + if num_faces == 0: + logger.info("[CodeFormer] No faces detected. Returning input unchanged.") + return image_bgr + + logger.info(f"[CodeFormer] Processing {num_faces} face(s)...") + + # Restore each face + for idx, cropped_face in enumerate(self.face_helper.cropped_faces): + # Preprocess: BGR -> RGB, HWC -> BCHW, normalize to [-1, 1] + face_t = torch.from_numpy( + cropped_face.astype(np.float32) / 255.0 + ).permute(2, 0, 1).unsqueeze(0).to(self.device) + + # Run CodeFormer + with torch.amp.autocast(device_type="cuda", enabled=(self.device.type == "cuda")): + output = self.model(face_t, w=self.fidelity_weight, adain=True)[0] + + # Postprocess: BCHW -> HWC, denormalize + restored_face = output.squeeze(0).clamp(0, 1).permute(1, 2, 0).cpu().numpy() + restored_face = (restored_face * 255.0).round().astype(np.uint8) + + self.face_helper.add_restored_face(restored_face) + + # Paste faces back using face_weight for blending + self.face_helper.get_inverse_affine(None) + + # Use bg_upsampler=None since image is already upscaled by RealESRGAN + restored_img = self.face_helper.paste_faces_to_input_image( + save_path=None, + upsample_img=image_bgr + ) + + logger.info(f"[CodeFormer] โœ… Restored {num_faces} face(s).") + return restored_img + + except Exception as e: + logger.info(f"[CodeFormer] Error during enhancement: {e}. Returning input unchanged.") + return image_bgr + + def unload(self): + """Free GPU memory.""" + if self.model is not None: + del self.model + self.model = None + if self.face_helper is not None: + del self.face_helper + self.face_helper = None + if torch.cuda.is_available(): + torch.cuda.empty_cache() + logger.info("[CodeFormer] Unloaded from GPU.") diff --git a/src/ai_super_resolution/models/diffusion_refiner.py b/src/ai_super_resolution/models/diffusion_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..14ecf1563dbfc4943c7e36a9f630720ac00329a0 --- /dev/null +++ b/src/ai_super_resolution/models/diffusion_refiner.py @@ -0,0 +1,210 @@ +""" +Stable Diffusion x4 Upscaler โ€” Texture Reconstruction Module + +Uses StableDiffusionUpscalePipeline to generate photorealistic textures +on top of the GAN+Transformer refined output. + +This is the final refinement stage before color matching and post-processing. +Auto-downloads the model on first use (~1.7GB). +""" +import os +import cv2 +import torch +import numpy as np +from PIL import Image +import logging + +logger = logging.getLogger("creator_ai.diffusion_refiner") + +try: + from diffusers import StableDiffusionUpscalePipeline + HAS_DIFFUSERS = True +except ImportError: + HAS_DIFFUSERS = False + + +class DiffusionTextureRefiner: + """ + Stable Diffusion x4 Upscaler for photorealistic texture generation. + + Unlike the inpainting variant used in text/object removal, this uses + StableDiffusionUpscalePipeline which is specifically designed for + super-resolution with texture generation. + + Key features: + - Generates realistic textures (skin pores, fabric weave, hair strands) + - Fills in detail that GANs hallucinate or over-smooth + - Operates at low inference steps (20) for speed + - Uses FP16 + attention slicing for 4GB VRAM compatibility + """ + + MODEL_ID = "stabilityai/stable-diffusion-x4-upscaler" + + def __init__(self, weights_dir: str = None, num_inference_steps: int = 20, + guidance_scale: float = 4.0, device: str = "cuda"): + """ + Args: + weights_dir: Optional local cache path for model weights + num_inference_steps: Diffusion steps (20 = fast, 50 = max quality) + guidance_scale: CFG scale (4.0 = subtle, 7.5 = strong) + device: 'cuda' or 'cpu' + """ + self.device = device if torch.cuda.is_available() and device == "cuda" else "cpu" + self.num_inference_steps = num_inference_steps + self.guidance_scale = guidance_scale + self.pipe = None + self._weights_dir = weights_dir + + if not HAS_DIFFUSERS: + logger.info("[DiffusionRefiner] โš  diffusers not installed. Texture refinement disabled.") + return + + # Don't load the model at init time โ€” lazy load on first use + # This saves VRAM when other models need to run first + logger.info(f"[DiffusionRefiner] Ready (will load {self.MODEL_ID} on first use)") + + def _ensure_loaded(self): + """Lazy-load the diffusion model on first actual use.""" + if self.pipe is not None: + return True + + if not HAS_DIFFUSERS: + return False + + try: + logger.info(f"[DiffusionRefiner] Loading {self.MODEL_ID}...") + cache_dir = os.path.join(self._weights_dir, "sd_upscaler") if self._weights_dir else None + + self.pipe = StableDiffusionUpscalePipeline.from_pretrained( + self.MODEL_ID, + torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, + cache_dir=cache_dir, + ) + self.pipe = self.pipe.to(self.device) + + # Memory optimizations for 4GB VRAM + self.pipe.enable_attention_slicing(1) + try: + self.pipe.enable_xformers_memory_efficient_attention() + except Exception: + pass # xformers not available, attention slicing is enough + + logger.info(f"[DiffusionRefiner] โœ… Loaded on {self.device}") + return True + except Exception as e: + logger.warning(f"[DiffusionRefiner] โš  Failed to load: {e}. Texture refinement disabled.") + self.pipe = None + return False + + @property + def available(self) -> bool: + """Check if diffusers is installed (model loads lazily).""" + return HAS_DIFFUSERS + + @torch.no_grad() + def refine(self, image_bgr: np.ndarray, prompt: str = "high quality, detailed, sharp") -> np.ndarray: + """ + Apply diffusion-based texture enhancement to a BGR image. + + The SD x4 upscaler expects a LOW-RES input and produces 4x output. + We process the large image in tiles (512x512) to avoid OOM. + For each tile: + 1. Downscale by 4x + 2. Feed to SD upscaler + 3. Blend SD output with original tile + + Args: + image_bgr: BGR uint8 (H, W, 3) โ€” already upscaled image + prompt: Text conditioning for texture generation + + Returns: + Texture-enhanced BGR uint8 image (same resolution) + """ + if not self._ensure_loaded(): + logger.info("[DiffusionRefiner] Not available, returning input unchanged.") + return image_bgr + + try: + h, w = image_bgr.shape[:2] + + # Import our TileEngine to process this large image in chunks + from stages.tile_engine import TileEngine + + # 512x512 tile is ideal. Downscaled 4x = 128x128 input to SD Upscaler. + tile_engine = TileEngine(tile_size=512, overlap=64) + + tiles = tile_engine.split(image_bgr) + processed_tiles = [] + + logger.info(f"[DiffusionRefiner] Processing {w}ร—{h} in {len(tiles)} tiles (512x512) to prevent OOM...") + + for i, t in enumerate(tiles): + tile_bgr = t['tile'] + th, tw = tile_bgr.shape[:2] + tile_rgb = cv2.cvtColor(tile_bgr, cv2.COLOR_BGR2RGB) + + # Downscale by 4x to create "low-res" input for SD upscaler + small_h = max(32, th // 4) + small_w = max(32, tw // 4) + # Ensure divisible by 8 + small_h = (small_h // 8) * 8 + small_w = (small_w // 8) * 8 + + small_img = cv2.resize(tile_rgb, (small_w, small_h), interpolation=cv2.INTER_AREA) + pil_small = Image.fromarray(small_img) + + logger.info(f" Tile {i+1}/{len(tiles)}") + + # Run SD upscaler + result = self.pipe( + prompt=prompt, + image=pil_small, + num_inference_steps=self.num_inference_steps, + guidance_scale=self.guidance_scale, + noise_level=20, # Low noise = preserve structure, add texture + ).images[0] + + result_np = np.array(result) + + # Resize SD output to match original tile dimensions + sd_resized = cv2.resize(result_np, (tw, th), interpolation=cv2.INTER_LANCZOS4) + + # Blend: use SD for texture detail, original for structure + blend_weight = 0.3 + blended = cv2.addWeighted( + tile_rgb, 1.0 - blend_weight, + sd_resized, blend_weight, + 0 + ) + + processed_tiles.append({ + "tile": cv2.cvtColor(blended, cv2.COLOR_RGB2BGR), + "x": t["x"], + "y": t["y"], + "w": tw, + "h": th, + }) + + + # Fuse back together + output_bgr = tile_engine.fuse(processed_tiles, (h, w, 3)) + logger.info(f"[DiffusionRefiner] โœ… Texture-enhanced {w}ร—{h} image.") + return output_bgr + + except torch.cuda.OutOfMemoryError: + logger.info("[DiffusionRefiner] โš  CUDA OOM even with tiles. Skipping texture refinement.") + if torch.cuda.is_available(): + torch.cuda.empty_cache() + return image_bgr + except Exception as e: + logger.error(f"[DiffusionRefiner] Error: {e}. Returning input unchanged.") + return image_bgr + + def unload(self): + """Free GPU memory by unloading the diffusion pipeline.""" + if self.pipe is not None: + del self.pipe + self.pipe = None + if torch.cuda.is_available(): + torch.cuda.empty_cache() + logger.info("[DiffusionRefiner] Unloaded from GPU.") diff --git a/src/ai_super_resolution/models/swinir_refiner.py b/src/ai_super_resolution/models/swinir_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..15c5b81a7540576ade87ad9897ffe136c485bb88 --- /dev/null +++ b/src/ai_super_resolution/models/swinir_refiner.py @@ -0,0 +1,255 @@ +""" +SwinIR Transformer Refinement Module + +Applies SwinIR (Image Restoration Using Swin Transformer) after +GAN upscaling to recover fine details and fix over-smoothing. + +Uses spandrel for model loading (same pattern as upsampler.py). +Auto-downloads weights on first use. +""" +import os +import cv2 +import torch +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.swinir_refiner") + +try: + from spandrel import ModelLoader + HAS_SPANDREL = True +except ImportError: + HAS_SPANDREL = False + +try: + from huggingface_hub import hf_hub_download + HAS_HF_HUB = True +except ImportError: + HAS_HF_HUB = False + + +def _download_swinir_weights(weights_dir: str, model_name: str) -> str: + """Download SwinIR weights from HuggingFace if not present.""" + weight_path = os.path.join(weights_dir, f"{model_name}.pth") + if os.path.exists(weight_path): + return weight_path + + if not HAS_HF_HUB: + logger.info("[SwinIR] huggingface_hub not installed. Cannot download weights.") + return None + + logger.info(f"[SwinIR] Downloading {model_name}.pth from HuggingFace...") + try: + # SwinIR large model for real-world SR x4 + downloaded = hf_hub_download( + repo_id="eugenesiow/SwinIR", + filename=f"{model_name}.pth", + local_dir=weights_dir, + local_dir_use_symlinks=False, + ) + if downloaded != weight_path and os.path.exists(downloaded): + os.rename(downloaded, weight_path) + logger.info(f"[SwinIR] Saved weights to {weight_path}") + return weight_path + except Exception as e: + logger.info(f"[SwinIR] HuggingFace download failed: {e}") + # Fallback: try direct URL + try: + from urllib.request import urlretrieve + + url = ( + "https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/" + "003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth" + ) + logger.info(f"[SwinIR] Trying direct download from GitHub releases...") + urlretrieve(url, weight_path) + logger.info(f"[SwinIR] Saved weights to {weight_path}") + return weight_path + except Exception as e2: + logger.info(f"[SwinIR] Direct download also failed: {e2}") + return None + + +class SwinIRRefiner: + """ + SwinIR-based detail refinement after GAN upscaling. + + SwinIR uses Swin Transformer blocks with shifted window attention + to recover fine details that GANs over-smooth. It excels at: + - Restoring texture detail (skin, fabric, hair) + - Sharpening edges without ringing artifacts + - Reducing GAN hallucination artifacts + + Operates as a 1x refinement pass (no resolution change). + """ + + def __init__(self, weights_dir: str, model_name: str = "SwinIR_large_x4", + tile_size: int = 512, device: str = "cuda"): + """ + Args: + weights_dir: Directory containing/to-download SwinIR weights + model_name: Weight filename (without .pth) + tile_size: Tile size for processing (larger = more VRAM) + device: 'cuda' or 'cpu' + """ + self.device = torch.device(device if torch.cuda.is_available() else "cpu") + self.model = None + self.tile_size = tile_size + self.tile_pad = 16 + + if not HAS_SPANDREL: + logger.info("[SwinIR] โš  spandrel not installed. SwinIR refinement disabled.") + return + + # Download weights if needed + weight_path = _download_swinir_weights(weights_dir, model_name) + self._weight_path = weight_path + if weight_path is None or not os.path.exists(weight_path): + logger.info("[SwinIR] โš  Weights not available. SwinIR refinement disabled.") + return + + try: + loader = ModelLoader(device=self.device) + self.model = loader.load_from_file(weight_path) + self.model.eval() + + # Use FP32 (default) to avoid scalar type Half expected errors with spandrel + # if self.device.type == "cuda": + # self.model.model.half() + + logger.info(f"[SwinIR] โœ… Loaded {model_name} via spandrel on {self.device}") + except Exception as e: + logger.warning(f"[SwinIR] โš  Failed to load: {e}. SwinIR refinement disabled.") + self.model = None + + @property + def available(self) -> bool: + return self.model is not None + + def _load_model(self): + """Reload model from saved weight path (after unload).""" + if not self._weight_path or not os.path.exists(self._weight_path): + return + try: + loader = ModelLoader(device=self.device) + self.model = loader.load_from_file(self._weight_path) + self.model.eval() + logger.info(f"[SwinIR] โœ… Reloaded on {self.device}") + except Exception as e: + logger.warning(f"[SwinIR] โš  Reload failed: {e}") + self.model = None + + @torch.no_grad() + def refine(self, image_bgr: np.ndarray) -> np.ndarray: + """ + Refine a BGR image using SwinIR for detail recovery. + + This is a 1x pass โ€” the output has the same resolution as input. + SwinIR acts as a detail enhancer / denoiser on the upscaled image. + + Args: + image_bgr: BGR uint8 (H, W, 3) + + Returns: + Refined BGR uint8 image (same resolution) + """ + if not self.available: + # Try to reload if we previously unloaded + if self._weight_path and not self.model: + self._load_model() + if not self.available: + logger.info("[SwinIR] Not available, returning input unchanged.") + return image_bgr + + try: + h, w = image_bgr.shape[:2] + + # BGR -> RGB, uint8 -> float32, HWC -> BCHW + img_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + img_t = torch.from_numpy(img_rgb.astype(np.float32) / 255.0) + img_t = img_t.permute(2, 0, 1).unsqueeze(0) # Keep on CPU for tile loop! + + # if self.device.type == "cuda": + # img_t = img_t.half() + + # Tiled inference for VRAM safety + if h > self.tile_size or w > self.tile_size: + output_t = self._tiled_inference(img_t) + else: + output_t = self.model(img_t) + + # BCHW -> HWC, clamp, uint8 + # (output_t is already on CPU if it came from _tiled_inference) + output = output_t.squeeze(0).float().clamp(0, 1).cpu().numpy() + output = (output.transpose(1, 2, 0) * 255.0).round().astype(np.uint8) + output_bgr = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + + # Ensure same size as input (SwinIR may change resolution slightly) + out_h, out_w = output_bgr.shape[:2] + if abs(out_h - h) > 2 or abs(out_w - w) > 2: + output_bgr = cv2.resize(output_bgr, (w, h), interpolation=cv2.INTER_LANCZOS4) + + logger.info(f"[SwinIR] โœ… Refined {w}ร—{h} image.") + return output_bgr + + except Exception as e: + logger.error(f"[SwinIR] Error: {e}. Returning input unchanged.") + if torch.cuda.is_available(): + torch.cuda.empty_cache() + return image_bgr + + def _tiled_inference(self, img_t: torch.Tensor) -> torch.Tensor: + """Process image in tiles to avoid GPU OOM.""" + _, c, h, w = img_t.shape + tile = self.tile_size + pad = self.tile_pad + + # Keep massive output tensor on CPU to save ~400MB of VRAM + output = torch.zeros_like(img_t) + + tiles_y = max(1, (h + tile - 1) // tile) + tiles_x = max(1, (w + tile - 1) // tile) + total_tiles = tiles_y * tiles_x + current_tile = 0 + + for ty in range(tiles_y): + for tx in range(tiles_x): + current_tile += 1 + logger.info(f" Tile {current_tile}/{total_tiles}") + + y0 = ty * tile + x0 = tx * tile + y1 = min(y0 + tile, h) + x1 = min(x0 + tile, w) + + # Add padding + y0p = max(y0 - pad, 0) + x0p = max(x0 - pad, 0) + y1p = min(y1 + pad, h) + x1p = min(x1 + pad, w) + + input_tile = img_t[:, :, y0p:y1p, x0p:x1p].to(self.device) + + # Use autocast to halve activation memory and run 2x faster on RTX cards + with torch.amp.autocast(device_type="cuda", enabled=(self.device.type == "cuda")): + output_tile = self.model(input_tile) + + # Remove padding from output and move back to CPU + oy0 = y0 - y0p + ox0 = x0 - x0p + oy1 = oy0 + (y1 - y0) + ox1 = ox0 + (x1 - x0) + + output[:, :, y0:y1, x0:x1] = output_tile[:, :, oy0:oy1, ox0:ox1].cpu() + + # Clear the carriage return line + return output + + def unload(self): + """Free GPU memory.""" + if self.model is not None: + del self.model + self.model = None + if torch.cuda.is_available(): + torch.cuda.empty_cache() + logger.info("[SwinIR] Unloaded from GPU.") diff --git a/src/ai_super_resolution/models/upsampler.py b/src/ai_super_resolution/models/upsampler.py new file mode 100644 index 0000000000000000000000000000000000000000..ef21e609dc5e85215a3f7b3e380fd0383b77e83b --- /dev/null +++ b/src/ai_super_resolution/models/upsampler.py @@ -0,0 +1,171 @@ +""" +Module 7 โ€” RealESRGAN Upsampler (spandrel-based) + +Uses spandrel to load RealESRGAN weights directly, bypassing the +basicsr dependency that's incompatible with Python 3.13. +""" +import os +import cv2 +import torch +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.upsampler") + +try: + from spandrel import ModelLoader + HAS_SPANDREL = True +except ImportError: + HAS_SPANDREL = False + + +class Upsampler: + """ + RealESRGAN-based upsampler using spandrel for model loading. + + spandrel auto-detects the model architecture (RRDBNet, SRVGGNet, etc.) + from the .pth weights file โ€” no manual architecture config needed. + + """ + + def __init__(self, weights_dir: str, model_name: str = "RealESRGAN_x4plus", + tile_size: int = 0, tile_pad: int = 10, device: str = "cuda"): + self.device = torch.device(device if torch.cuda.is_available() else "cpu") + self.model_name = model_name + self.model = None + self.netscale = 4 + self.tile_size = tile_size + self.tile_pad = tile_pad + + model_path = os.path.join(weights_dir, f"{model_name}.pth") + + if not os.path.exists(model_path): + logger.warning(f"[Upsampler] โš  Weights not found at {model_path}. Using Lanczos fallback.") + return + + if not HAS_SPANDREL: + logger.info("[Upsampler] โš  spandrel not installed. Using Lanczos fallback.") + return + + try: + loader = ModelLoader(device=self.device) + self.model = loader.load_from_file(model_path) + self.model.eval() + + # Use half precision on CUDA + if self.device.type == "cuda": + self.model.model.half() + + # Detect scale from model + if hasattr(self.model, 'scale'): + self.netscale = self.model.scale + logger.info(f"[Upsampler] Loaded {model_name} via spandrel on {self.device} (scale={self.netscale}x)") + except Exception as e: + logger.warning(f"[Upsampler] โš  Failed to load model: {e}. Using Lanczos fallback.") + self.model = None + + @property + def upsampler(self): + """Compatibility property for face_enhancer that checks if model is loaded.""" + return self.model + + def enhance(self, image_bgr: np.ndarray, outscale: int = 4) -> np.ndarray: + """ + Upscale a BGR image using the loaded AI model. + + Args: + image_bgr: BGR uint8 (H, W, 3) + outscale: Output scale factor (2 or 4) + + Returns: + Upscaled BGR image uint8 + """ + if self.model is None: + return self._lanczos_fallback(image_bgr, outscale) + + try: + return self._inference(image_bgr, outscale) + except Exception as e: + logger.info(f"[Upsampler] Error during inference: {e}. Using Lanczos fallback.") + return self._lanczos_fallback(image_bgr, outscale) + + def _inference(self, image_bgr: np.ndarray, outscale: int) -> np.ndarray: + """Run the actual AI super-resolution inference.""" + h, w = image_bgr.shape[:2] + + # BGR -> RGB, uint8 -> float32 [0,1], HWC -> BCHW + img_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + img_t = torch.from_numpy(img_rgb.astype(np.float32) / 255.0) + img_t = img_t.permute(2, 0, 1).unsqueeze(0) # [1, 3, H, W] + img_t = img_t.to(self.device) + + if self.device.type == "cuda": + img_t = img_t.half() + + # Tiled inference for large images + if self.tile_size > 0 and (h > self.tile_size or w > self.tile_size): + output_t = self._tiled_inference(img_t) + else: + with torch.no_grad(): + output_t = self.model(img_t) + + # BCHW -> HWC, float32 [0,1] -> uint8, RGB -> BGR + output = output_t.squeeze(0).float().clamp(0, 1).cpu().numpy() + output = (output.transpose(1, 2, 0) * 255.0).round().astype(np.uint8) + output_bgr = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + + # If model scale != requested scale, resize to target + out_h, out_w = output_bgr.shape[:2] + target_h, target_w = h * outscale, w * outscale + + if abs(out_h - target_h) > 2 or abs(out_w - target_w) > 2: + output_bgr = cv2.resize(output_bgr, (target_w, target_h), interpolation=cv2.INTER_LANCZOS4) + + return output_bgr + + def _tiled_inference(self, img_t: torch.Tensor) -> torch.Tensor: + """Process image in tiles to avoid GPU OOM on large images.""" + _, c, h, w = img_t.shape + tile = self.tile_size + pad = self.tile_pad + scale = self.netscale + + out_h, out_w = h * scale, w * scale + output = torch.zeros((1, c, out_h, out_w), dtype=img_t.dtype, device=img_t.device) + + tiles_y = (h + tile - 1) // tile + tiles_x = (w + tile - 1) // tile + + for ty in range(tiles_y): + for tx in range(tiles_x): + # Input tile with padding + y0 = ty * tile + x0 = tx * tile + y1 = min(y0 + tile, h) + x1 = min(x0 + tile, w) + + y0p = max(y0 - pad, 0) + x0p = max(x0 - pad, 0) + y1p = min(y1 + pad, h) + x1p = min(x1 + pad, w) + + input_tile = img_t[:, :, y0p:y1p, x0p:x1p] + + with torch.no_grad(): + output_tile = self.model(input_tile) + + # Remove padding from output + oy0 = (y0 - y0p) * scale + ox0 = (x0 - x0p) * scale + oy1 = oy0 + (y1 - y0) * scale + ox1 = ox0 + (x1 - x0) * scale + + output[:, :, y0*scale:y1*scale, x0*scale:x1*scale] = output_tile[:, :, oy0:oy1, ox0:ox1] + + return output + + def _lanczos_fallback(self, image: np.ndarray, scale: int) -> np.ndarray: + """Bicubic/Lanczos fallback when GPU inference is not available.""" + h, w = image.shape[:2] + logger.info(f"[Upsampler] WARNING: Using Lanczos fallback (no AI enhancement)") + return cv2.resize(image, (w * scale, h * scale), interpolation=cv2.INTER_LANCZOS4) diff --git a/src/ai_super_resolution/sr_pipeline.py b/src/ai_super_resolution/sr_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3e1c112aa29bb1890256bc4a85bb97d4576991 --- /dev/null +++ b/src/ai_super_resolution/sr_pipeline.py @@ -0,0 +1,357 @@ +""" +Smart Adaptive AI Super-Resolution Pipeline + +Dynamically selects processing modules based on image quality analysis. +Three performance modes: Fast, Balanced, HD. + +Pipeline flow: + Input โ†’ Validation โ†’ Quality Analysis โ†’ Conditional Routing + โ†’ Tile Gen โ†’ RealESRGAN โ†’ CodeFormer(auto) โ†’ SwinIR(conditional) + โ†’ Diffusion(conditional) โ†’ Tile Fusion โ†’ Color Match โ†’ Sharpen โ†’ Output +""" +import os +import gc +import cv2 +import torch +import numpy as np +import time + +# Stage imports +from stages.input_validator import InputValidator +from stages.denoiser import Denoiser +from stages.tile_engine import TileEngine +from stages.color_matcher import ColorMatcher +from stages.post_processor import PostProcessor +from stages.quality_analyzer import QualityAnalyzer + +# Model imports +from models.upsampler import Upsampler +from models.codeformer_enhancer import CodeFormerEnhancer +from models.swinir_refiner import SwinIRRefiner +from models.diffusion_refiner import DiffusionTextureRefiner +import logging + +logger = logging.getLogger("creator_ai.sr_pipeline") + + + +class SuperResolutionPipeline: + """ + Smart adaptive super-resolution pipeline. + + Modes: + โšก fast โ€” RealESRGAN + CodeFormer(auto) + Sharpening (~15s) + โš–๏ธ balanced โ€” + SwinIR if detail_score is low (~45s) + ๐ŸŽจ hd โ€” + SwinIR + Diffusion if image is degraded (~3min) + """ + + def __init__(self, config: dict): + self.config = config + self.modules = config.get("modules", {}) + + device_str = config["pipeline"]["device"] + self.device = device_str if torch.cuda.is_available() and device_str == "cuda" else "cpu" + self.weights_dir = config["paths"]["weights_dir"] + + logger.info("=" * 60) + logger.info(" Smart Adaptive Super-Resolution โ€” Initializing") + logger.info("=" * 60) + + self._init_stages() + self._init_models() + self._print_status() + logger.info("=" * 60) + + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Initialization + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + def _init_stages(self): + m = self.modules + size_limit = self.config["pipeline"].get("image_size_limit", 4096) + + self.input_validator = InputValidator(image_size_limit=size_limit) + + # Quality Analyzer (always on) + qa_cfg = m.get("quality_analysis", {}) + self.quality_analyzer = QualityAnalyzer(qa_cfg) + + # Denoiser + d_cfg = m.get("denoiser", {}) + self.denoiser = Denoiser( + strength=d_cfg.get("strength", 5), + use_learned_model=d_cfg.get("use_learned_model", False), + ) if d_cfg.get("enabled", False) else None + + # Tile Engine + tile_cfg = m.get("tile_engine", {}) + self.tile_engine = TileEngine( + tile_size=tile_cfg.get("tile_size", 512), + overlap=tile_cfg.get("overlap", 64), + ) if tile_cfg.get("enabled", True) else None + + # Color Matcher + color_cfg = m.get("color_matching", {}) + self.color_matcher = ColorMatcher( + method=color_cfg.get("method", "histogram") + ) if color_cfg.get("enabled", False) else None + + # Post Processor + pp_cfg = m.get("post_processing", {}) + self.post_processor = PostProcessor( + sharpen=pp_cfg.get("sharpen", True), + sharpen_strength=pp_cfg.get("sharpen_strength", 0.3), + edge_aware_smooth=pp_cfg.get("edge_aware_smooth", True), + ) if pp_cfg.get("enabled", True) else None + + def _init_models(self): + m = self.modules + + # RealESRGAN (always loaded) + up_cfg = m.get("upscaling", {}) + internal_tile = 0 if self.tile_engine else 512 + self.upsampler = Upsampler( + weights_dir=self.weights_dir, + model_name=up_cfg.get("model_name", "RealESRGAN_x4plus"), + tile_size=internal_tile, + device=self.device, + ) + + # CodeFormer (loaded eagerly โ€” used in all modes when face detected) + face_cfg = m.get("face_enhancement", {}) + self.codeformer = None + if face_cfg.get("enabled", True): + self.codeformer = CodeFormerEnhancer( + weights_dir=self.weights_dir, + fidelity_weight=face_cfg.get("fidelity_weight", 0.7), + face_weight=face_cfg.get("face_weight", 0.7), + upscale=1, # Image is already upscaled by RealESRGAN + device=self.device, + ) + + # SwinIR (loaded eagerly โ€” small model) + swinir_cfg = m.get("swinir_refinement", {}) + self.swinir = None + if swinir_cfg.get("enabled", True): + self.swinir = SwinIRRefiner( + weights_dir=self.weights_dir, + model_name=swinir_cfg.get("model_name", "SwinIR_large_x4"), + tile_size=swinir_cfg.get("tile_size", 512), + device=self.device, + ) + + # Diffusion (lazy-loaded โ€” biggest model) + diff_cfg = m.get("diffusion_refinement", {}) + self.diffusion_refiner = None + if diff_cfg.get("enabled", True): + self.diffusion_refiner = DiffusionTextureRefiner( + weights_dir=self.weights_dir, + num_inference_steps=diff_cfg.get("num_inference_steps", 20), + guidance_scale=diff_cfg.get("guidance_scale", 4.0), + device=self.device, + ) + + def _print_status(self): + status = { + "Input Validation": "โœ…", + "Quality Analyzer": "โœ…", + "Denoising": "โœ…" if self.denoiser else "โฌœ (auto)", + "Tile Engine": "โœ…" if self.tile_engine else "โฌœ", + "RealESRGAN Upscaler": "โœ…" if self.upsampler.upsampler else "โš ", + "CodeFormer Face": "โœ…" if (self.codeformer and self.codeformer.available) else "โฌœ", + "SwinIR Refiner": "โœ…" if (self.swinir and self.swinir.available) else "โฌœ", + "SD Texture": "โœ…" if (self.diffusion_refiner and self.diffusion_refiner.available) else "โฌœ (lazy)", + "Color Matching": "โœ…" if self.color_matcher else "โฌœ", + "Post Processing": "โœ…" if self.post_processor else "โฌœ", + } + logger.info("\n Module Status:") + for name, state in status.items(): + logger.info(f" {state} {name}") + + + def _free_vram(self): + if torch.cuda.is_available(): + torch.cuda.empty_cache() + gc.collect() + + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Main Run + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + def run(self, image_rgb: np.ndarray, scale: int = None, + mode: str = "fast") -> np.ndarray: + """ + Run the smart adaptive super-resolution pipeline. + + Args: + image_rgb: Input RGB uint8 (H, W, 3) + scale: Upscale factor (2 or 4) + mode: "fast", "balanced", or "hd" + """ + if scale is None: + scale = self.modules.get("upscaling", {}).get("default_scale", 4) + + mode = mode.lower() + mode_labels = {"fast": "โšก Fast", "balanced": "โš–๏ธ Balanced", "hd": "๐ŸŽจ HD"} + logger.info(f"\n{'=' * 60}") + logger.info(f" Mode: {mode_labels.get(mode, mode)}") + logger.info(f"{'=' * 60}") + + total_start = time.time() + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 1: Input Validation + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + logger.info("\nโ”€โ”€ Stage 1: Input Validation โ”€โ”€") + validated = self.input_validator(image_rgb, target_scale=scale) + image = validated["image"] + effective_scale = validated["effective_scale"] + reference_image = image.copy() + + if effective_scale != scale: + logger.info(f"[Pipeline] Adjusted scale: {scale}x โ†’ {effective_scale}x") + scale = effective_scale + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 2: Quality Analysis + Routing + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + logger.info("\nโ”€โ”€ Stage 2: Quality Analysis โ”€โ”€") + metrics = self.quality_analyzer.analyze(image) + routing = self.quality_analyzer.get_routing(metrics, mode) + + # Print routing decision + active = [k for k, v in routing.items() if v] + skipped = [k for k, v in routing.items() if not v] + logger.info(f"[Routing] Active: {', '.join(active) if active else 'base only'}") + logger.info(f"[Routing] Skipped: {', '.join(skipped) if skipped else 'none'}") + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 3: Conditional Pre-Denoising + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if routing["denoise"]: + logger.info("\nโ”€โ”€ Stage 3: Pre-Denoising (auto-triggered) โ”€โ”€") + if self.denoiser: + image = self.denoiser(image) + else: + strength = self.modules.get("denoiser", {}).get("strength", 5) + image = cv2.fastNlMeansDenoisingColored( + image, None, strength, strength, 7, 21 + ) + logger.info(f"[Denoiser] Applied cv2 denoising (strength={strength})") + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 4-5: Tile โ†’ RealESRGAN โ†’ Fuse + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + logger.info(f"\nโ”€โ”€ Stage 4-5: RealESRGAN Upscale ({scale}x) โ”€โ”€") + img_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + + if self.tile_engine: + result_bgr = self._tiled_upscale(img_bgr, scale) + else: + result_bgr = self.upsampler.enhance(img_bgr, outscale=scale) + + self._free_vram() + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 6: CodeFormer Face Restoration (auto) + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if routing["face_restore"]: + logger.info("\nโ”€โ”€ Stage 6: CodeFormer Face Restoration โ”€โ”€") + if self.codeformer and self.codeformer.available: + result_bgr = self.codeformer.enhance(result_bgr) + else: + logger.info("[Pipeline] CodeFormer not available. Skipping.") + self._free_vram() + else: + logger.info("\nโ”€โ”€ Stage 6: Face Restoration โ€” SKIPPED (no face detected) โ”€โ”€") + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 7: SwinIR Detail Refinement (conditional) + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if routing["swinir"]: + logger.info("\nโ”€โ”€ Stage 7: SwinIR Detail Refinement โ”€โ”€") + if self.swinir and self.swinir.available: + result_bgr = self.swinir.refine(result_bgr) + self.swinir.unload() + self._free_vram() + else: + logger.info("[Pipeline] SwinIR not available. Skipping.") + else: + reason = "mode=fast" if mode == "fast" else f"detail={metrics['detail_score']:.2f} (sufficient)" + logger.info(f"\nโ”€โ”€ Stage 7: SwinIR โ€” SKIPPED ({reason}) โ”€โ”€") + # Unload to free VRAM for later stages + if self.swinir: + self.swinir.unload() + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 8: Diffusion Texture Enhancement (conditional) + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if routing["diffusion"]: + logger.info("\nโ”€โ”€ Stage 8: Diffusion Texture Enhancement โ”€โ”€") + if self.diffusion_refiner and self.diffusion_refiner.available: + result_bgr = self.diffusion_refiner.refine( + result_bgr, prompt="high quality, detailed, sharp" + ) + self.diffusion_refiner.unload() + self._free_vram() + else: + logger.info("[Pipeline] Diffusion refiner not available. Skipping.") + else: + reason = "modeโ‰ hd" if mode != "hd" else f"blur={metrics['blur_score']:.2f} (acceptable)" + logger.info(f"\nโ”€โ”€ Stage 8: Diffusion โ€” SKIPPED ({reason}) โ”€โ”€") + if self.diffusion_refiner: + self.diffusion_refiner.unload() + self._free_vram() + + # Convert to RGB for remaining stages + result = cv2.cvtColor(result_bgr, cv2.COLOR_BGR2RGB) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 9: Histogram Color Matching + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if self.color_matcher: + logger.info("\nโ”€โ”€ Stage 9: Color Preservation โ”€โ”€") + result = self.color_matcher(result, reference_image) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # Stage 10: Adaptive Post-Processing + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + if self.post_processor: + logger.info("\nโ”€โ”€ Stage 10: Adaptive Sharpening โ”€โ”€") + result = self.post_processor(result) + + elapsed = time.time() - total_start + h, w = result.shape[:2] + logger.info(f"\n{'=' * 60}") + logger.info(f" โœ… Pipeline complete: {w}ร—{h} in {elapsed:.2f}s [{mode_labels.get(mode, mode)}]") + logger.info(f"{'=' * 60}") + + self._free_vram() + return result + + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Tiled Upscaling + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + def _tiled_upscale(self, image_bgr: np.ndarray, scale: int) -> np.ndarray: + h, w = image_bgr.shape[:2] + tiles = self.tile_engine.split(image_bgr) + + processed_tiles = [] + for i, t in enumerate(tiles): + logger.info(f" Tile {i + 1}/{len(tiles)}") + tile_bgr = t["tile"] + upscaled_tile = self.upsampler.enhance(tile_bgr, outscale=scale) + + processed_tiles.append({ + "tile": upscaled_tile, + "x": t["x"] * scale, + "y": t["y"] * scale, + "w": upscaled_tile.shape[1], + "h": upscaled_tile.shape[0], + }) + + + output_shape = (h * scale, w * scale, 3) + fused = self.tile_engine.fuse(processed_tiles, output_shape) + return fused diff --git a/src/ai_super_resolution/stages/__init__.py b/src/ai_super_resolution/stages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef122a7c82d8f8685e070bfd78c25d4f0d04bb3 --- /dev/null +++ b/src/ai_super_resolution/stages/__init__.py @@ -0,0 +1 @@ +# AI Super-Resolution โ€” Pipeline Stages diff --git a/src/ai_super_resolution/stages/color_matcher.py b/src/ai_super_resolution/stages/color_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac6b3167f926a1b02dd8efb56caf9c8e0099821 --- /dev/null +++ b/src/ai_super_resolution/stages/color_matcher.py @@ -0,0 +1,106 @@ +""" +Module 11 โ€” Color Preservation (Histogram Matching) + +Prevents GAN-induced color shifts by matching the output's +color distribution to the original input in LAB color space. +""" +import cv2 +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.color_matcher") + + + +class ColorMatcher: + """ + Matches the color distribution of a GAN-upscaled image to the + original input to preserve the photographer's intended color grading. + + Works in LAB color space to independently correct luminance and chrominance, + preventing the common GAN issue where warm tones shift cold or vice versa. + """ + + def __init__(self, method: str = "histogram"): + """ + Args: + method: 'histogram' for full histogram matching, + 'mean_std' for faster mean/std transfer + """ + self.method = method + + def __call__(self, output: np.ndarray, reference: np.ndarray) -> np.ndarray: + """ + Match colors of output to reference. + + Args: + output: GAN-upscaled image (H1, W1, 3) RGB uint8 + reference: Original input image (H2, W2, 3) RGB uint8 + + Returns: + Color-corrected output (H1, W1, 3) RGB uint8 + """ + if self.method == "histogram": + result = self._histogram_match_lab(output, reference) + else: + result = self._mean_std_transfer(output, reference) + + logger.info(f"[ColorMatcher] Applied {self.method} color matching in LAB space") + return result + + def _histogram_match_lab(self, output: np.ndarray, reference: np.ndarray) -> np.ndarray: + """ + Per-channel histogram matching in LAB color space. + + LAB separates luminance (L) from color (A, B), so we can + correct color drift without destroying the AI's enhanced luminance detail. + """ + # Convert to LAB + out_lab = cv2.cvtColor(output, cv2.COLOR_RGB2LAB).astype(np.float32) + ref_lab = cv2.cvtColor(reference, cv2.COLOR_RGB2LAB).astype(np.float32) + + # Match each channel independently + for ch in range(3): + out_lab[:, :, ch] = self._match_channel(out_lab[:, :, ch], ref_lab[:, :, ch]) + + # Convert back to RGB + out_lab = np.clip(out_lab, 0, 255).astype(np.uint8) + return cv2.cvtColor(out_lab, cv2.COLOR_LAB2RGB) + + def _match_channel(self, source: np.ndarray, reference: np.ndarray) -> np.ndarray: + """ + Match the histogram of a single channel using CDF mapping. + """ + src_flat = source.flatten() + ref_flat = reference.flatten() + + # Compute CDFs + src_values, src_idx, src_counts = np.unique(src_flat, return_inverse=True, return_counts=True) + ref_values, ref_counts = np.unique(ref_flat, return_counts=True) + + src_cdf = np.cumsum(src_counts).astype(np.float64) + src_cdf /= src_cdf[-1] + + ref_cdf = np.cumsum(ref_counts).astype(np.float64) + ref_cdf /= ref_cdf[-1] + + # Map source values to reference values via CDF interpolation + mapped_values = np.interp(src_cdf, ref_cdf, ref_values) + return mapped_values[src_idx].reshape(source.shape) + + def _mean_std_transfer(self, output: np.ndarray, reference: np.ndarray) -> np.ndarray: + """ + Faster alternative: transfer mean and std from reference to output. + """ + out_lab = cv2.cvtColor(output, cv2.COLOR_RGB2LAB).astype(np.float32) + ref_lab = cv2.cvtColor(reference, cv2.COLOR_RGB2LAB).astype(np.float32) + + for ch in range(3): + out_mean, out_std = out_lab[:, :, ch].mean(), out_lab[:, :, ch].std() + ref_mean, ref_std = ref_lab[:, :, ch].mean(), ref_lab[:, :, ch].std() + + if out_std > 1e-6: + out_lab[:, :, ch] = (out_lab[:, :, ch] - out_mean) * (ref_std / out_std) + ref_mean + + out_lab = np.clip(out_lab, 0, 255).astype(np.uint8) + return cv2.cvtColor(out_lab, cv2.COLOR_LAB2RGB) diff --git a/src/ai_super_resolution/stages/denoiser.py b/src/ai_super_resolution/stages/denoiser.py new file mode 100644 index 0000000000000000000000000000000000000000..99d4984bf300cc84569593121fa5848f21d7f062 --- /dev/null +++ b/src/ai_super_resolution/stages/denoiser.py @@ -0,0 +1,65 @@ +""" +Module 4 โ€” Noise & Artifact Removal (Learned Denoiser) + +Uses an AI model rather than classic OpenCV filters to clean +input images before upscaling, preventing noise amplification +without destroying fine texture. +""" +import cv2 +import torch +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.denoiser") + + +# For Phase 2, we implement a fallback to a smarter OpenCV structural +# filter, and structure the wrapper to allow plugging in DnCNN/RIDNet later. + +class Denoiser: + """ + Intelligent denoising stage. + + Currently implements Edge-Preserving Filter (Domain Transform) + as a much higher quality alternative to fastNlMeansDenoising Colored. + It removes compression artifacts and noise while better preserving + sharp structural edges. + """ + + def __init__(self, strength: int = 5, use_learned_model: bool = False): + self.strength = strength + self.use_learned = use_learned_model + + if self.use_learned: + logger.info("[Denoiser] Note: Learned models (DnCNN/RIDNet) not yet downloaded. Using EPF fallback.") + + def __call__(self, image: np.ndarray) -> np.ndarray: + """ + Denoise the image. + + Args: + image: RGB uint8 (H, W, 3) + + Returns: + Denoised RGB uint8 (H, W, 3) + """ + # We use Domain Transform Edge Preserving Filter: + # sigma_s controls spatial smoothing + # sigma_r controls color/range smoothing (how much edges stop smoothing) + + # Scale parameters based on requested strength 1-10 + sigma_s = min(200, self.strength * 10) + sigma_r = min(1.0, self.strength * 0.05) + + bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + + # Normconv is faster than Recursive and yields similar results + denoised_bgr = cv2.edgePreservingFilter( + bgr, + flags=cv2.RECURS_FILTER, + sigma_s=sigma_s, + sigma_r=sigma_r + ) + + logger.info(f"[Denoiser] Applied Edge Preserving Denoising (strength={self.strength})") + return cv2.cvtColor(denoised_bgr, cv2.COLOR_BGR2RGB) diff --git a/src/ai_super_resolution/stages/input_validator.py b/src/ai_super_resolution/stages/input_validator.py new file mode 100644 index 0000000000000000000000000000000000000000..4705344996876a2ce142fe6ced0552ee3c737589 --- /dev/null +++ b/src/ai_super_resolution/stages/input_validator.py @@ -0,0 +1,134 @@ +""" +Module 1 -- Input Validation + +Validates and normalizes input images for safe GPU processing. +Detects resolution, color space, bit depth. + +SMART RESIZE: Instead of blindly downscaling large images, computes +the optimal working resolution based on the target output scale +and GPU capacity. This prevents the catastrophic case where a +high-res input gets downscaled then upscaled back to a SMALLER size. +""" +import cv2 +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.input_validator") + + + +class InputValidator: + """ + Validates input images and normalizes them for the SR pipeline. + + Key intelligence: + - If input is already large AND sharp, recommends scale=2 instead of 4 + - Computes working_resolution so that output >= original resolution + - Preserves the original image for final compositing + """ + + def __init__(self, image_size_limit: int = 4096): + self.image_size_limit = image_size_limit + + def __call__(self, image: np.ndarray, target_scale: int = 4) -> dict: + """ + Validate and normalize the input image. + + Args: + image: Input image (H, W, 3), RGB, uint8 + target_scale: Requested upscale factor (2, 4, 8) + + Returns: + dict with keys: + 'image': working image (may be resized) + 'original_image': untouched original (full-res) + 'original_shape': (H, W) of original + 'was_resized': bool + 'effective_scale': actual scale to use (may differ from target) + 'info': detected properties dict + """ + h, w = image.shape[:2] + original_shape = (h, w) + was_resized = False + original_image = image.copy() + + # Detect properties + info = { + "resolution": f"{w}x{h}", + "megapixels": round((w * h) / 1e6, 2), + "channels": image.shape[2] if image.ndim == 3 else 1, + "dtype": str(image.dtype), + "bit_depth": 8 if image.dtype == np.uint8 else (16 if image.dtype == np.uint16 else 32), + } + + logger.info(f"[InputValidator] Resolution: {info['resolution']} ({info['megapixels']}MP)") + logger.info(f"[InputValidator] Channels: {info['channels']}, Bit Depth: {info['bit_depth']}") + + # Ensure 3-channel RGB + if image.ndim == 2: + image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) + elif image.shape[2] == 4: + image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB) + + # Convert to uint8 if needed + if image.dtype == np.uint16: + image = (image / 256).astype(np.uint8) + elif image.dtype == np.float32 or image.dtype == np.float64: + image = np.clip(image * 255, 0, 255).astype(np.uint8) + + # โ”€โ”€ Smart Scale Computation โ”€โ”€ + # The output should be: working_dim * scale + # We want: output_dim >= original_dim (never produce a smaller image!) + # So: working_dim >= original_dim / scale + # + # GPU limit means: working_dim <= image_size_limit + # Therefore: effective_scale = ceil(original_max / image_size_limit) + # but at least target_scale, at most 4 + + effective_scale = target_scale + max_dim = max(h, w) + + # If the image is already large, compute the working resolution + # so that output >= original + max_working = self.image_size_limit # GPU-safe working resolution + target_output = max_dim * target_scale # What user wants + + if max_dim > max_working: + # Image is too large to process at native res + # Downscale to max_working, but ensure output >= original + # output = max_working * effective_scale >= max_dim + # effective_scale >= max_dim / max_working + needed_scale = max_dim / max_working + if needed_scale <= 2: + effective_scale = 2 + elif needed_scale <= 4: + effective_scale = 4 + else: + # Even 4x won't recover original size, limit working to max_dim/4 + max_working = max(512, max_dim // 4) + effective_scale = 4 + + scale_f = max_working / max_dim + new_w = int(w * scale_f) + new_h = int(h * scale_f) + image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) + was_resized = True + + output_dim = max(new_w, new_h) * effective_scale + logger.info(f"[InputValidator] Smart resize: {w}x{h} -> {new_w}x{new_h} (working)") + logger.info(f"[InputValidator] Output will be: ~{new_w*effective_scale}x{new_h*effective_scale} " + f"(scale={effective_scale}x)") + if output_dim < max_dim: + logger.info(f"[InputValidator] WARNING: Output ({output_dim}px) < Original ({max_dim}px)") + logger.info(f"[InputValidator] Consider using --scale {int(np.ceil(max_dim / max_working) * 2)}") + else: + logger.info(f"[InputValidator] Image fits in GPU memory. Using {effective_scale}x directly.") + + return { + "image": image, + "original_image": original_image, + "original_shape": original_shape, + "was_resized": was_resized, + "effective_scale": effective_scale, + "info": info, + } diff --git a/src/ai_super_resolution/stages/post_processor.py b/src/ai_super_resolution/stages/post_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..504bc2fcafa1364f198211ca0fb73beac32687a2 --- /dev/null +++ b/src/ai_super_resolution/stages/post_processor.py @@ -0,0 +1,85 @@ +""" +Module 12 โ€” Adaptive Post-Processing + +Final polishing stage with edge-aware smoothing and controlled sharpening. +Replaces the old destructive cv2.addWeighted approach. +""" +import cv2 +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.post_processor") + + + +class PostProcessor: + """ + Applies final post-processing to the upscaled image. + + Features: + - Edge-aware bilateral smoothing to remove GAN micro-artifacts + - Adaptive unsharp mask with safe strength limits + - No destructive filters (strength is capped) + """ + + def __init__(self, sharpen: bool = True, sharpen_strength: float = 0.15, + edge_aware_smooth: bool = True): + self.sharpen = sharpen + self.sharpen_strength = min(sharpen_strength, 0.4) # Hard cap + self.edge_aware_smooth = edge_aware_smooth + + def __call__(self, image: np.ndarray) -> np.ndarray: + """ + Apply post-processing pipeline. + + Args: + image: RGB uint8 (H, W, 3) + + Returns: + Post-processed image (H, W, 3) uint8 + """ + result = image.copy() + + # 1. Edge-aware smoothing (bilateral filter) + if self.edge_aware_smooth: + result = self._edge_aware_smooth(result) + + # 2. Adaptive sharpening + if self.sharpen: + result = self._adaptive_sharpen(result) + + return result + + def _edge_aware_smooth(self, image: np.ndarray) -> np.ndarray: + """ + Bilateral filter that smooths flat areas (removing GAN checkerboard + artifacts) while preserving sharp edges. + + Parameters are deliberately conservative to avoid over-smoothing. + """ + # d=5: small neighborhood, sigmaColor=30: moderate color sensitivity + # sigmaSpace=30: moderate spatial sensitivity + smoothed = cv2.bilateralFilter(image, d=5, sigmaColor=30, sigmaSpace=30) + logger.info(f"[PostProcessor] Applied edge-aware bilateral smoothing") + return smoothed + + def _adaptive_sharpen(self, image: np.ndarray) -> np.ndarray: + """ + Adaptive unsharp mask that sharpens edges without amplifying noise. + + Uses a larger Gaussian sigma (3.0) to target structural edges + rather than pixel-level noise. + """ + # Gaussian blur with sigma=3.0 for structural sharpening + gaussian = cv2.GaussianBlur(image, (0, 0), 3.0) + + # Unsharp mask: result = original + strength * (original - blurred) + sharpened = cv2.addWeighted( + image, 1.0 + self.sharpen_strength, + gaussian, -self.sharpen_strength, + 0 + ) + + result = np.clip(sharpened, 0, 255).astype(np.uint8) + logger.info(f"[PostProcessor] Applied adaptive sharpening (strength={self.sharpen_strength})") + return result diff --git a/src/ai_super_resolution/stages/quality_analyzer.py b/src/ai_super_resolution/stages/quality_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e789001f5b2a855c0fedfedff994a6b82030a8 --- /dev/null +++ b/src/ai_super_resolution/stages/quality_analyzer.py @@ -0,0 +1,173 @@ +""" +Image Quality Analyzer โ€” Smart Routing for Super-Resolution + +Lightweight analysis module that extracts quality metrics from an input +image to determine which pipeline stages are necessary: + + - blur_score: 0.0 (sharp) โ†’ 1.0 (very blurry) + - noise_level: 0.0 (clean) โ†’ 1.0 (very noisy) + - detail_score: 0.0 (flat) โ†’ 1.0 (highly detailed) + - face_detected: bool + +Runs in <100ms on CPU. Zero GPU usage. +""" +import cv2 +import numpy as np +import logging + +logger = logging.getLogger("creator_ai.quality_analyzer") + + +class QualityAnalyzer: + """Analyze image quality to drive conditional routing.""" + + def __init__(self, config: dict = None): + cfg = config or {} + self.blur_threshold = cfg.get("blur_threshold", 0.7) + self.detail_threshold = cfg.get("detail_threshold", 0.5) + self.noise_threshold = cfg.get("noise_threshold", 0.6) + + # Face detection โ€” reuse facexlib if available, else OpenCV cascade + self._face_detector = None + try: + from facexlib.detection import init_detection_model + import torch + device = torch.device("cpu") # Detection on CPU is fast enough + self._face_detector = init_detection_model( + "retinaface_resnet50", half=False, device=device + ) + self._det_method = "retinaface" + except Exception: + # Fallback to OpenCV Haar cascade + cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml" + self._face_detector = cv2.CascadeClassifier(cascade_path) + self._det_method = "haar" + + def analyze(self, image_rgb: np.ndarray) -> dict: + """ + Analyze image quality. + + Args: + image_rgb: RGB uint8 (H, W, 3) + + Returns: + dict with blur_score, noise_level, detail_score, face_detected + """ + # Work on a small version for speed + h, w = image_rgb.shape[:2] + max_dim = 512 + if max(h, w) > max_dim: + scale = max_dim / max(h, w) + small = cv2.resize(image_rgb, (int(w * scale), int(h * scale)), + interpolation=cv2.INTER_AREA) + else: + small = image_rgb + + gray = cv2.cvtColor(small, cv2.COLOR_RGB2GRAY) + + blur = self._compute_blur(gray) + noise = self._compute_noise(gray) + detail = self._compute_detail(gray) + face = self._detect_face(small) + + result = { + "blur_score": round(blur, 3), + "noise_level": round(noise, 3), + "detail_score": round(detail, 3), + "face_detected": face, + } + + # Print a compact summary + face_icon = "๐Ÿ‘ค" if face else "โ€”" + logger.info(f"[QualityAnalyzer] blur={blur:.2f} noise={noise:.2f} " + f"detail={detail:.2f} face={face_icon}") + + return result + + # โ”€โ”€ Metric Implementations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + @staticmethod + def _compute_blur(gray: np.ndarray) -> float: + """ + Laplacian variance โ†’ blur score. + Low variance = blurry image. + Returns 0.0 (sharp) โ†’ 1.0 (very blurry). + """ + lap_var = cv2.Laplacian(gray, cv2.CV_64F).var() + # Typical range: 0 (flat) to ~2000+ (crisp) + # Map: <50 โ†’ very blurry (1.0), >500 โ†’ sharp (0.0) + score = 1.0 - min(lap_var / 500.0, 1.0) + return max(0.0, min(score, 1.0)) + + @staticmethod + def _compute_noise(gray: np.ndarray) -> float: + """ + High-frequency energy via Gaussian difference. + Returns 0.0 (clean) โ†’ 1.0 (very noisy). + """ + blurred = cv2.GaussianBlur(gray, (5, 5), 0) + diff = cv2.absdiff(gray, blurred).astype(np.float32) + noise_energy = diff.std() + # Typical range: 2โ€“20 for clean, 20โ€“50 for noisy + score = min(noise_energy / 30.0, 1.0) + return max(0.0, min(score, 1.0)) + + @staticmethod + def _compute_detail(gray: np.ndarray) -> float: + """ + Edge density via Canny. + Returns 0.0 (flat/smooth) โ†’ 1.0 (highly detailed). + """ + edges = cv2.Canny(gray, 50, 150) + edge_density = np.count_nonzero(edges) / edges.size + # Typical: 0.01 (smooth) to 0.15+ (very detailed) + score = min(edge_density / 0.10, 1.0) + return max(0.0, min(score, 1.0)) + + def _detect_face(self, image_rgb: np.ndarray) -> bool: + """Detect if any face is present in the image.""" + try: + if self._det_method == "retinaface": + import torch + img_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) + with torch.no_grad(): + bboxes = self._face_detector.detect_faces(img_bgr, 0.5) + return len(bboxes) > 0 + else: + # OpenCV Haar cascade fallback + gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) + faces = self._face_detector.detectMultiScale( + gray, scaleFactor=1.1, minNeighbors=4, minSize=(30, 30) + ) + return len(faces) > 0 + except Exception: + return False + + def get_routing(self, metrics: dict, mode: str = "fast") -> dict: + """ + Determine which pipeline modules to activate. + + Args: + metrics: Output from analyze() + mode: "fast", "balanced", or "hd" + + Returns: + dict of booleans for each optional stage + """ + routing = { + "denoise": metrics["noise_level"] > self.noise_threshold, + "face_restore": metrics["face_detected"], + "swinir": False, + "diffusion": False, + } + + if mode == "balanced": + # SwinIR only if the image lacks detail + routing["swinir"] = metrics["detail_score"] < self.detail_threshold + + elif mode == "hd": + # SwinIR if detail is low, Diffusion if very blurry + routing["swinir"] = metrics["detail_score"] < self.detail_threshold + routing["diffusion"] = metrics["blur_score"] > self.blur_threshold + + return routing diff --git a/src/ai_super_resolution/stages/tile_engine.py b/src/ai_super_resolution/stages/tile_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..2d53fd3597a56f0bb27572e8a0849b2190f61cc0 --- /dev/null +++ b/src/ai_super_resolution/stages/tile_engine.py @@ -0,0 +1,144 @@ +""" +Module 5/6 โ€” Tile Generation & Fusion Engine + +Splits large images into overlapping tiles for GPU-safe processing, +then fuses them back using Gaussian-weighted blending to eliminate seams. +""" +import cv2 +import numpy as np +import math +import logging + +logger = logging.getLogger("creator_ai.tile_engine") + + + +class TileEngine: + """ + Handles tile splitting and Gaussian-weighted fusion for seamless + large-image super-resolution processing. + + The overlap region uses a raised-cosine (Gaussian-like) window + so that tile boundaries are invisible in the final output. + """ + + def __init__(self, tile_size: int = 512, overlap: int = 64): + self.tile_size = tile_size + self.overlap = overlap + + def split(self, image: np.ndarray) -> list: + """ + Split image into overlapping tiles. + + Args: + image: (H, W, 3) uint8 RGB + + Returns: + List of dicts, each with: + 'tile': cropped tile array + 'x': left coordinate in original image + 'y': top coordinate in original image + 'w': tile width + 'h': tile height + """ + h, w = image.shape[:2] + step = self.tile_size - self.overlap + tiles = [] + + # Calculate grid positions + y_positions = list(range(0, h, step)) + x_positions = list(range(0, w, step)) + + # Ensure last tile covers the edge + if y_positions[-1] + self.tile_size < h: + y_positions.append(h - self.tile_size) + if x_positions[-1] + self.tile_size < w: + x_positions.append(w - self.tile_size) + + for y in y_positions: + for x in x_positions: + # Clamp to image boundaries + y1 = max(0, y) + x1 = max(0, x) + y2 = min(h, y1 + self.tile_size) + x2 = min(w, x1 + self.tile_size) + + tile = image[y1:y2, x1:x2].copy() + tiles.append({ + "tile": tile, + "x": x1, + "y": y1, + "w": x2 - x1, + "h": y2 - y1, + }) + + logger.info(f"[TileEngine] Split {w}x{h} image โ†’ {len(tiles)} tiles " + f"(size={self.tile_size}, overlap={self.overlap})") + return tiles + + def fuse(self, tiles: list, output_shape: tuple) -> np.ndarray: + """ + Fuse processed tiles back into a single image using Gaussian blending. + + Args: + tiles: List of dicts from split(), but with 'tile' replaced by processed result. + The tiles may have been upscaled, so their dimensions may differ. + output_shape: (H, W, 3) โ€” the expected final image dimensions. + + Returns: + Fused image (H, W, 3) uint8 + """ + out_h, out_w = output_shape[:2] + accumulator = np.zeros((out_h, out_w, 3), dtype=np.float64) + weight_map = np.zeros((out_h, out_w), dtype=np.float64) + + for t in tiles: + tile = t["tile"] + x, y = t["x"], t["y"] + th, tw = tile.shape[:2] + + # Ensure tile fits in output + th = min(th, out_h - y) + tw = min(tw, out_w - x) + tile = tile[:th, :tw] + + # Create 2D Gaussian weight window + w_window = self._gaussian_window(tw, th) + + # Accumulate weighted tile + accumulator[y:y+th, x:x+tw] += tile.astype(np.float64) * w_window[:, :, np.newaxis] + weight_map[y:y+th, x:x+tw] += w_window + + # Normalize by weight + weight_map = np.maximum(weight_map, 1e-8) # avoid division by zero + result = accumulator / weight_map[:, :, np.newaxis] + + logger.info(f"[TileEngine] Fused {len(tiles)} tiles โ†’ {out_w}x{out_h} image") + return np.clip(result, 0, 255).astype(np.uint8) + + def _gaussian_window(self, width: int, height: int) -> np.ndarray: + """ + Create a 2D Gaussian-like blending window using raised cosine. + + The window is 1.0 in the center and tapers smoothly to ~0 at + the edges over the overlap region. This ensures seamless blending. + """ + def _1d_window(size: int) -> np.ndarray: + if size <= 1: + return np.ones(size) + # Raised cosine window (Hann window) + x = np.linspace(0, 1, size) + window = np.ones(size) + + fade = min(self.overlap, size // 2) + if fade > 0: + # Left taper + window[:fade] = 0.5 * (1 - np.cos(np.pi * np.arange(fade) / fade)) + # Right taper + window[-fade:] = 0.5 * (1 - np.cos(np.pi * np.arange(fade, 0, -1) / fade)) + + return window + + w_x = _1d_window(width) + w_y = _1d_window(height) + return np.outer(w_y, w_x) diff --git a/src/ai_super_resolution/utils/image_utils.py b/src/ai_super_resolution/utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3177dc0b16297c5fa0483cfca3bdcb7164b7ae --- /dev/null +++ b/src/ai_super_resolution/utils/image_utils.py @@ -0,0 +1,31 @@ +import cv2 +import numpy as np +import os +from PIL import Image + +def load_image(image_path): + """Load image and return as RGB numpy array.""" + if not os.path.exists(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + img = cv2.imread(str(image_path)) + if img is None: + raise ValueError(f"Could not read image: {image_path}") + + return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + +def save_image(image_rgb, output_path): + """Save RGB numpy array as image.""" + os.makedirs(os.path.dirname(output_path), exist_ok=True) + img_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(str(output_path), img_bgr) + +def resize_image(image, max_size=1024): + """Resize image preserving aspect ratio if it exceeds max_size.""" + h, w = image.shape[:2] + if max(h, w) <= max_size: + return image + + scale = max_size / max(h, w) + nh, nw = int(h * scale), int(w * scale) + return cv2.resize(image, (nw, nh), interpolation=cv2.INTER_LANCZOS4) diff --git a/src/ai_text_removal/README.md b/src/ai_text_removal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..546b3fd1ba415da53f6526b1e9e88cc1fa4e5816 --- /dev/null +++ b/src/ai_text_removal/README.md @@ -0,0 +1,42 @@ +# AI Text Removal โ€” Production Pipeline + +A high-performance text removal system that combines structural reconstruction (LaMa) with generative refinement (Stable Diffusion) for studio-quality results. + +## ๐Ÿš€ Quick Start + +### 1. Install Dependencies +```bash +pip install -r requirements.txt +pip install diffusers transformers accelerate +``` + +### 2. Required Weights +The pipeline looks for weights in the `weights/` directory: +- `weights/yolov8n.pt` (Detection) +- `weights/sam_vit_l_0b3195.pth` (Segmentation) +- `weights/big-lama.pt` (Inpainting structure) +- Stable Diffusion weights are automatically downloaded on first run via `diffusers`. + +### 3. Usage +Run on your image (replace `your_image.jpg` with your actual filename): +```bash +python inference.py --input your_image.jpg +``` + +> [!TIP] +> **Processing Speed:** By default, Stable Diffusion is **disabled** to make processing instant (~2-5 seconds). To enable high-resolution generative refinement, change `strength` to `0.75` in `configs/config.yaml`. + +**Advanced Options:** +- `--save-artifacts`: Save intermediate masks and edge maps (useful for debugging). +- `--config configs/config.yaml`: Use a custom configuration. + +## ๐Ÿ› ๏ธ Architecture +1. **Detection (CRAFT/YOLO)**: Locates text boxes. +2. **Segmentation (SAM)**: Creates precise pixel-level masks. +3. **Edge Extraction (Canny)**: Guides the inpainter with background structural lines. +4. **Multi-Scale Inpainting (LaMa)**: Refills background at 256/512/768px resolutions. +5. **Generative Refinement (SD)**: Adds photorealistic textures to the inpainted area. +6. **Poisson Blending**: Seamlessly merges the new patch with zero visible seams. + +--- +*Optimized for RTX GPU (4GB+ VRAM recommended).* diff --git a/src/ai_text_removal/configs/config.yaml b/src/ai_text_removal/configs/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3f9da58e29c38aa89b14bd354d631577c7e6e4e --- /dev/null +++ b/src/ai_text_removal/configs/config.yaml @@ -0,0 +1,35 @@ +pipeline: + device: "cuda" + image_size: 1024 + +paths: + weights: + # Text detection handled by EasyOCR (auto-downloads CRAFT weights) + inpainting: "big-lama.pt" + diffusion: "runwayml/stable-diffusion-inpainting" + + output: + dir: "text_output" + +parameters: + mask_refinement: + dilate_kernel: 7 # Gentle dilation for anti-aliased text edges + dilate_iterations: 2 + gaussian_blur: 5 # Slight feather + + edge_extraction: + canny_low: 30 + canny_high: 100 + + inpainting: + multi_scale: false + scales: [512] + + post_processing: + use_poisson: false + + diffusion: + prompt: "clean natural background, realistic texture, seamless, high quality" + negative_prompt: "text, letters, characters, watermark, writing, words, signature, logo, noise, artifacts, blurry" + num_inference_steps: 25 + strength: 0.0 # Disabled. LaMa alone produces best results at native resolution. diff --git a/src/ai_text_removal/inference.py b/src/ai_text_removal/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..6297c6f8ed83751bfcde72840d2ad7c0afff0bdf --- /dev/null +++ b/src/ai_text_removal/inference.py @@ -0,0 +1,205 @@ +""" +AI Text Removal Pipeline โ€” Inference CLI + +Pipeline: + Image โ†’ EasyOCR(CRAFT) Detection โ†’ Polygon Mask โ†’ Refine Mask โ†’ + Edge Extraction โ†’ Big-LaMa Inpaint โ†’ SD Diffusion Refinement โ†’ + Post-Processing โ†’ Clean Image +""" +import os +import sys +import argparse +import yaml +import time + +# Ensure project root is in sys.path for robust imports +script_dir = os.path.dirname(os.path.abspath(__file__)) +if script_dir not in sys.path: + sys.path.insert(0, script_dir) + +from tr_utils.image_utils import load_image, save_image, resize_image +from tr_pipelines.detect_text import TextDetector +from tr_pipelines.segment_mask import TextMaskGenerator +from tr_pipelines.refine_mask import MaskRefiner +from tr_pipelines.edge_extract import EdgeExtractor +from tr_pipelines.inpaint import LaMaInpainter +from tr_pipelines.diffusion_refine import DiffusionRefiner +from tr_pipelines.post_process import PostProcessor + + +def resolve_weight_path(p: str, script_dir: str) -> str: + """Resolve a weight path: try local, then universal weights dir.""" + if not p or os.path.isabs(p) or p.startswith("runwayml/"): + return p + # Try relative to script + local = os.path.abspath(os.path.join(script_dir, p)) + if os.path.exists(local): + return local + # Try universal weights folder + workspace_root = os.path.abspath(os.path.join(script_dir, "..", "..")) + universal = os.path.join(workspace_root, "weights", os.path.basename(p)) + if os.path.exists(universal): + return universal + return local + + +def main(): + parser = argparse.ArgumentParser(description="AI Text Removal Pipeline") + parser.add_argument("--input", "-i", type=str, required=True, help="Input image path") + parser.add_argument("--output", "-o", type=str, default=None, help="Output image path") + parser.add_argument("--config", "-c", type=str, + default=os.path.join(script_dir, "configs", "config.yaml"), + help="Config file path") + parser.add_argument("--save-artifacts", action="store_true", + help="Save intermediate masks and edge maps") + parser.add_argument("--no-diffusion", action="store_true", + help="Skip diffusion refinement for faster processing") + args = parser.parse_args() + + # โ”€โ”€ Load Config โ”€โ”€ + with open(args.config, "r") as f: + config = yaml.safe_load(f) + + device = config["pipeline"]["device"] + weights = config["paths"]["weights"] + params = config["parameters"] + + # Resolve weight paths + inpaint_path = resolve_weight_path(weights.get("inpainting", ""), script_dir) + std_inpaint_path = resolve_weight_path(weights.get("std_inpainting", "lama.pt"), script_dir) + diffusion_id = weights.get("diffusion", "runwayml/stable-diffusion-inpainting") + + start_time = time.time() + print("=" * 60) + print(" AI Text Removal Pipeline") + print("=" * 60) + + # โ”€โ”€ Step 1: Initialize Modules โ”€โ”€ + print("\n[1/7] Initializing modules...") + detector = TextDetector(device=device) + mask_gen = TextMaskGenerator() + + mr = params.get("mask_refinement", {}) + refiner = MaskRefiner( + dilate_kernel=mr.get("dilate_kernel", 7), + dilate_iter=mr.get("dilate_iterations", 3), + blur_kernel=mr.get("gaussian_blur", 3), + ) + + edge_params = params.get("edge_extraction", {}) + edge_extractor = EdgeExtractor( + canny_low=edge_params.get("canny_low", 30), + canny_high=edge_params.get("canny_high", 100), + ) + + print("[1.1/7] Loading LaMa inpainter models...") + inpainter = LaMaInpainter( + model_path=inpaint_path, + std_model_path=std_inpaint_path, + device=device + ) + + diff_params = params.get("diffusion", {}) + diffusion_refiner = None + if not args.no_diffusion and diff_params.get("strength", 0.0) > 0: + print("[1.2/7] Loading Diffusion Refiner...") + diffusion_refiner = DiffusionRefiner(model_id=diffusion_id, device=device) + + pp = params.get("post_processing", {}) + post_processor = PostProcessor(use_poisson=pp.get("use_poisson", True)) + + # โ”€โ”€ Step 2: Load & Preprocess โ”€โ”€ + print("\n[2/7] Loading image...") + image = load_image(args.input) + # Preserve the un-resized original for full-res compositing + true_original = image.copy() + + max_size = config["pipeline"].get("image_size", 1024) + image = resize_image(image, max_size=max_size) + print(f" Image size: {image.shape[1]}x{image.shape[0]}") + + # โ”€โ”€ Step 3: Detect Text โ”€โ”€ + print("\n[3/7] Detecting text regions...") + polygons = detector(image) + print(f" Found {len(polygons)} text regions.") + + if len(polygons) == 0: + print("\n โš ๏ธ No text detected. Saving original image.") + out_dir = config["paths"]["output"].get("dir", "text_output") + os.makedirs(out_dir, exist_ok=True) + name, ext = os.path.splitext(os.path.basename(args.input)) + out_path = args.output or os.path.join(out_dir, f"{name}_clean{ext}") + save_image(image, out_path) + print(f" โ†’ Saved: {out_path}") + return + + # โ”€โ”€ Step 4: Generate Text Mask โ”€โ”€ + print("\n[4/7] Generating text mask (polygon fill)...") + mask = mask_gen(image, polygons) + + # โ”€โ”€ Step 5: Refine Mask โ”€โ”€ + print("[5/7] Refining mask (dilation + smoothing)...") + refined_mask = refiner(mask) + + # โ”€โ”€ Step 6: Extract Structure โ”€โ”€ + print("[6/7] Extracting edge structure map...") + edge_map = edge_extractor(image, refined_mask) + + # โ”€โ”€ Step 7: Inpaint โ”€โ”€ + inp = params.get("inpainting", {}) + print("[7/7] Running structure-guided inpainting (Big-LaMa)...") + clean_image = inpainter( + image, refined_mask, + edge_map=edge_map, + multi_scale=inp.get("multi_scale", True), + scales=inp.get("scales", [256, 512, 768]), + ) + + # โ”€โ”€ Step 7.5: Diffusion Refinement (optional) โ”€โ”€ + if diffusion_refiner is not None and diff_params.get("strength", 0.0) > 0: + print(" Running generative refinement (Stable Diffusion)...") + import torch + torch.cuda.empty_cache() + clean_image = diffusion_refiner( + image=clean_image, + mask=refined_mask, + prompt=diff_params.get("prompt", "clean background, no text"), + negative_prompt=diff_params.get("negative_prompt", "text, artifacts"), + steps=diff_params.get("num_inference_steps", 25), + strength=diff_params.get("strength", 0.30), + ) + + # โ”€โ”€ Step 8: Post-Process โ”€โ”€ + print(" Post-processing (native-res full compositing + color match)...") + final_image = post_processor( + true_original=true_original, + inpainted=clean_image, + mask=refined_mask, + alpha_mask=None + ) + + # โ”€โ”€ Save โ”€โ”€ + elapsed = time.time() - start_time + print(f"\n{'=' * 60}") + print(f" โœ… Text removal completed in {elapsed:.2f}s") + print(f"{'=' * 60}") + + out_dir = config["paths"]["output"].get("dir", "text_output") + os.makedirs(out_dir, exist_ok=True) + + name, ext = os.path.splitext(os.path.basename(args.input)) + out_path = args.output or os.path.join(out_dir, f"{name}_clean{ext}") + + if args.save_artifacts: + import cv2 + cv2.imwrite(os.path.join(out_dir, f"{name}_mask.png"), refined_mask) + cv2.imwrite(os.path.join(out_dir, f"{name}_edges.png"), edge_map) + print(f" โ†’ Mask: {os.path.join(out_dir, f'{name}_mask.png')}") + print(f" โ†’ Edges: {os.path.join(out_dir, f'{name}_edges.png')}") + + save_image(final_image, out_path) + print(f" โ†’ Clean: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/src/ai_text_removal/requirements.txt b/src/ai_text_removal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d058615893696ac3f91b7ebd31c8ba3be8ba1a92 --- /dev/null +++ b/src/ai_text_removal/requirements.txt @@ -0,0 +1,26 @@ +# Install torch/torchvision with CUDA support: +# pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124 +torch>=2.0.0 +torchvision>=0.15.0 +# Use the headless variant if no display server is available +opencv-python-headless>=4.8.0 +numpy>=1.24.0 +Pillow>=10.0.0 +scikit-image>=0.21.0 +matplotlib>=3.7.0 +tqdm>=4.65.0 +diffusers>=0.21.0 +transformers>=4.33.0 +accelerate>=0.23.0 +onnxruntime>=1.15.0 +craft-text-detector>=0.4.2 +segment-anything>=1.0 +gdown>=4.6.0 + +# --- Object Removal Pipeline Specific --- +ultralytics>=8.0.0 # YOLOv8 for Object Detection +MobileSAM>=1.0.0 # Fast alternative to SAM for Object Segmentation +timm>=0.6.12 # Required for MiDaS Depth Estimation +omegaconf>=2.1.1 # Required for Big-LaMa configuration parsing +pytorch-lightning>=1.5.0 # Required for Big-LaMa training/inference logic +kornia>=0.6.0 # Geometry routines sometimes used by LaMa diff --git a/src/ai_text_removal/tr_pipeline.py b/src/ai_text_removal/tr_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..62515d8089d2b51f56e90df45b919e0fda3f9c8b --- /dev/null +++ b/src/ai_text_removal/tr_pipeline.py @@ -0,0 +1,222 @@ +""" +Production AI Text Removal Pipeline. + +Pipeline: EasyOCR โ†’ Polygon Mask โ†’ Gentle Refinement โ†’ + Big-LaMa (structure) โ†’ SD Inpainting (texture) โ†’ + STRICT Masked Compositing + +GUARANTEE: Non-text pixels are pixel-perfect identical to the original. +""" +import os +import cv2 +import yaml +import numpy as np + +from tr_utils.image_utils import load_image, resize_image +from tr_pipelines.detect_text import TextDetector +from tr_pipelines.segment_mask import TextMaskGenerator +from tr_pipelines.refine_mask import MaskRefiner +from tr_pipelines.inpaint import LaMaInpainter +from tr_pipelines.diffusion_refine import DiffusionRefiner + + +class TextRemovalPipeline: + def __init__(self, config_path: str = None): + script_dir = os.path.dirname(os.path.abspath(__file__)) + if config_path is None: + config_path = os.path.join(script_dir, "configs", "config.yaml") + + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + self.device = config["pipeline"]["device"] + self.params = config["parameters"] + + weights = config["paths"]["weights"] + inpaint_path = weights.get("inpainting", "big-lama.pt") + std_inpaint_path = weights.get("std_inpainting", "lama.pt") + + workspace_root = os.path.abspath(os.path.join(script_dir, "..", "..")) + + def resolve_model_path(path): + local_path = os.path.join(script_dir, path) + universal_path = os.path.join(workspace_root, "weights", os.path.basename(path)) + if os.path.exists(universal_path): + return universal_path + elif os.path.exists(local_path): + return local_path + return None + + inpaint_path = resolve_model_path(inpaint_path) + std_inpaint_path = resolve_model_path(std_inpaint_path) + + print("[TextRemovalPipeline] Initializing models...") + + # Stage 1: Detection + self.detector = TextDetector(device=self.device) + self.mask_gen = TextMaskGenerator() + + mr = self.params.get("mask_refinement", {}) + self.refiner = MaskRefiner( + dilate_kernel=mr.get("dilate_kernel", 7), + dilate_iter=mr.get("dilate_iterations", 2), + blur_kernel=mr.get("gaussian_blur", 5), + ) + + # Stage 2: LaMa Structure Reconstruction + self.inpainter = LaMaInpainter( + model_path=inpaint_path, + std_model_path=std_inpaint_path, + device=self.device + ) + + # Stage 3: SD Texture Refinement (optional) + self.diffusion = None + diff_params = self.params.get("diffusion", {}) + if diff_params.get("strength", 0.0) > 0: + diff_id = weights.get("diffusion", "runwayml/stable-diffusion-inpainting") + self.diffusion = DiffusionRefiner(model_id=diff_id, device=self.device) + + print("[TextRemovalPipeline] โœ… Ready.") + + def run(self, image_rgb: np.ndarray, enable_diffusion: bool = True) -> dict: + """ + Run text removal pipeline. + + STRICT GUARANTEES: + 1. Non-text pixels are pixel-perfect identical to the original + 2. Only detected text regions are modified + 3. No global blur, no global noise, no full-image regeneration + """ + original = image_rgb.copy() + h_orig, w_orig = original.shape[:2] + print(f"[Pipeline] Input: {w_orig}ร—{h_orig}", flush=True) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # STEP 1: Detect text regions + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + max_detect = 1024 + detect_scale = 1.0 + if max(h_orig, w_orig) > max_detect: + detect_scale = max_detect / max(h_orig, w_orig) + detect_img = cv2.resize(image_rgb, None, fx=detect_scale, fy=detect_scale, + interpolation=cv2.INTER_AREA) + else: + detect_img = image_rgb + + polygons = self.detector(detect_img) + if len(polygons) == 0: + print("[Pipeline] No text detected.", flush=True) + return {"result": original, "mask": np.zeros((h_orig, w_orig), dtype=np.uint8)} + + # Scale polygons back to original resolution + if detect_scale < 1.0: + polygons = [(np.array(p, dtype=np.float64) / detect_scale).astype(np.int32) + for p in polygons] + + print(f"[Pipeline] Detected {len(polygons)} text regions.", flush=True) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # STEP 2: Create binary mask at native resolution + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + raw_mask = self.mask_gen(original, polygons) + refined = self.refiner(raw_mask) + _, binary_mask = cv2.threshold(refined, 127, 255, cv2.THRESH_BINARY) + + mask_pct = np.count_nonzero(binary_mask > 127) / (h_orig * w_orig) * 100 + print(f"[Pipeline] Mask: {mask_pct:.1f}% coverage", flush=True) + + # DEBUG: Verify mask integrity + print(f"[Pipeline] Mask min={binary_mask.min()}, max={binary_mask.max()}, " + f"shape={binary_mask.shape}", flush=True) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # STEP 3: LaMa structural inpainting (native resolution) + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + print("[Pipeline] Running LaMa inpainting...", flush=True) + lama_output = self.inpainter(original, binary_mask) + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # STEP 4: SD Inpainting refinement (MASKED ONLY) + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + diff_params = self.params.get("diffusion", {}) + sd_strength = diff_params.get("strength", 0.0) + + if enable_diffusion and self.diffusion is not None and sd_strength > 0: + print(f"[Pipeline] Running SD Inpainting (strength={sd_strength})...", flush=True) + # SD refines the LaMa output โ€” only inside the mask + sd_output = self.diffusion( + image=lama_output, # โ† LaMa output as base + mask=binary_mask, # โ† restrict to masked region + prompt=diff_params.get("prompt", "clean natural background, realistic texture"), + negative_prompt=diff_params.get("negative_prompt", "text, letters, artifacts"), + steps=diff_params.get("num_inference_steps", 25), + strength=sd_strength, + ) + inpainted = sd_output + else: + print("[Pipeline] SD refinement disabled. Using LaMa output directly.", flush=True) + inpainted = lama_output + + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + # STEP 5: STRICT MASKED COMPOSITING + # Non-masked pixels = pixel-perfect original + # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + result = self._strict_composite(original, inpainted, binary_mask) + + # Verification + non_masked = binary_mask == 0 + changed = np.count_nonzero(np.any(result != original, axis=-1)) + masked_px = np.count_nonzero(binary_mask > 127) + identical = np.array_equal(result[non_masked], original[non_masked]) + print(f"[Pipeline] Changed: {changed}px / Masked: {masked_px}px / " + f"Non-masked identical: {identical}", flush=True) + print(f"[Pipeline] โœ… Text removal complete.", flush=True) + + return {"result": result, "mask": binary_mask} + + @staticmethod + def _strict_composite(original: np.ndarray, inpainted: np.ndarray, + mask: np.ndarray) -> np.ndarray: + """ + STRICT masked compositing. + + - Interior mask pixels: 100% from inpainted (LaMa/SD output) + - Thin border ring (3px): alpha-blended for seamless edges + - Exterior pixels: 100% from original (pixel-perfect) + """ + result = original.copy() + binary = (mask > 127).astype(np.uint8) + + # Erode to find safe interior (fully inside text region) + erode_k = np.ones((5, 5), np.uint8) + interior = cv2.erode(binary, erode_k, iterations=1) + + # Border ring = mask - eroded interior + border = binary - interior + + # 1. Hard-copy interior from inpainted + interior_bool = interior.astype(bool) + result[interior_bool] = inpainted[interior_bool] + + # 2. Alpha-blend the thin border for seamless transition + border_f = cv2.GaussianBlur(border.astype(np.float32), (5, 5), 1.0) + if border_f.max() > 0: + border_f = border_f / border_f.max() + + border_area = border_f > 0.01 + if np.any(border_area): + bf3 = np.expand_dims(border_f, -1) + blended = (original.astype(np.float32) * (1.0 - bf3) + + inpainted.astype(np.float32) * bf3) + # Apply only where border > 0 + for c in range(3): + result[:, :, c] = np.where(border_area, + blended[:, :, c].astype(np.uint8), + result[:, :, c]) + + # 3. ABSOLUTE SAFETY: force non-masked = original + non_masked = ~binary.astype(bool) + result[non_masked] = original[non_masked] + + return result diff --git a/src/ai_text_removal/tr_pipelines/__init__.py b/src/ai_text_removal/tr_pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/ai_text_removal/tr_pipelines/detect_text.py b/src/ai_text_removal/tr_pipelines/detect_text.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4aa53766647a537e54ebe8bfca59314b5bf62e --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/detect_text.py @@ -0,0 +1,117 @@ +""" +Text Detector โ€” EasyOCR-based (bundles CRAFT internally). + +EasyOCR uses CRAFT for text detection and a recognition head for reading. +We only need the detection stage (bounding boxes), not recognition. + +Fallback: If EasyOCR fails, we use OpenCV morphological text detection. +""" +import numpy as np +import cv2 + +try: + import easyocr +except ImportError: + easyocr = None + + +class TextDetector: + """ + Detects text regions using EasyOCR (CRAFT-based) with morphological fallback. + Returns polygon coordinates for each detected text region. + """ + + def __init__(self, device: str = "cuda", languages: list = None, **kwargs): + self.reader = None + self.languages = languages or ["en"] + + if easyocr is None: + print("[TextDetector] easyocr not installed. Using morphological fallback.") + return + + gpu = device == "cuda" + try: + self.reader = easyocr.Reader( + self.languages, gpu=gpu, verbose=False + ) + print(f"[TextDetector] EasyOCR (CRAFT) initialized (GPU: {gpu}).") + except Exception as e: + print(f"[TextDetector] EasyOCR init failed: {e}. Using fallback.") + + def __call__(self, image: np.ndarray) -> list: + """ + Detect text in an image. + + Args: + image: RGB image (H, W, 3), uint8. + + Returns: + List of polygons. Each polygon is an np.ndarray of shape (N, 2). + For rectangular detections N=4. + """ + polygons = [] + + # --- Primary: EasyOCR (CRAFT-based) --- + if self.reader is not None: + try: + # EasyOCR returns: [ ([x1,y1],[x2,y2],[x3,y3],[x4,y4]), text, conf ] + # We convert RGBโ†’BGR since easyocr expects BGR or file path + results = self.reader.readtext( + cv2.cvtColor(image, cv2.COLOR_RGB2BGR), + detail=1, + paragraph=False, + text_threshold=0.5, # Lower = catches faint text + low_text=0.3, # Lower = catches faint strokes + mag_ratio=1.5 # Slight magnification + ) + for (bbox, text, conf) in results: + poly = np.array(bbox, dtype=np.int32) + polygons.append(poly) + + if len(polygons) > 0: + print(f" [CRAFT/EasyOCR] Found {len(polygons)} text regions.") + return polygons + except Exception as e: + print(f" [CRAFT/EasyOCR] Detection failed: {e}. Trying fallback...") + + # --- Fallback: Morphological text detection --- + polygons = self._morphological_detect(image) + print(f" [Morphological Fallback] Found {len(polygons)} text regions.") + return polygons + + def _morphological_detect(self, image: np.ndarray) -> list: + """ + Simple morphological text detection using edge density. + Works for large, high-contrast text on walls/signs. + """ + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + + # Adaptive threshold to find dark text on light backgrounds + binary = cv2.adaptiveThreshold( + gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 15 + ) + + # Connect nearby characters into text blocks + kernel_h = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 3)) + kernel_v = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 15)) + connected = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel_h) + connected = cv2.morphologyEx(connected, cv2.MORPH_CLOSE, kernel_v) + connected = cv2.dilate(connected, np.ones((5, 5), np.uint8), iterations=2) + + contours, _ = cv2.findContours( + connected, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) + + h, w = image.shape[:2] + min_area = (h * w) * 0.001 # At least 0.1% of image + max_area = (h * w) * 0.5 # At most 50% of image + + polygons = [] + for cnt in contours: + area = cv2.contourArea(cnt) + if min_area < area < max_area: + rect = cv2.minAreaRect(cnt) + box = cv2.boxPoints(rect).astype(np.int32) + polygons.append(box) + + return polygons diff --git a/src/ai_text_removal/tr_pipelines/diffusion_refine.py b/src/ai_text_removal/tr_pipelines/diffusion_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e99120953ce08a655c2f59c022575b13650672 --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/diffusion_refine.py @@ -0,0 +1,128 @@ +""" +Stable Diffusion Inpainting Refiner โ€” MASKED ONLY. + +Uses StableDiffusionInpaintPipeline with mask_image to refine +ONLY the masked regions. Non-masked pixels are untouched by design. +""" +import numpy as np +import cv2 +import torch +from PIL import Image + +try: + from diffusers import StableDiffusionInpaintPipeline +except ImportError: + StableDiffusionInpaintPipeline = None + + +class DiffusionRefiner: + """ + Stable Diffusion Inpainting for texture refinement. + + CORRECT USAGE: + - Uses StableDiffusionInpaintPipeline (NOT img2img) + - Passes mask_image to restrict generation to masked region + - Low strength (0.25-0.35) to preserve LaMa structure + - Non-masked pixels are NEVER modified + """ + + def __init__(self, model_id: str = "runwayml/stable-diffusion-inpainting", device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.pipe = None + + if StableDiffusionInpaintPipeline is None: + print("[DiffusionRefiner] diffusers not installed. Skipping.") + return + + try: + self.pipe = StableDiffusionInpaintPipeline.from_pretrained( + model_id, + torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, + ).to(self.device) + + # Memory optimization + self.pipe.enable_attention_slicing() + try: + self.pipe.enable_xformers_memory_efficient_attention() + except Exception: + pass + + print(f"[DiffusionRefiner] โœ… Loaded StableDiffusionInpaintPipeline on {self.device}") + except Exception as e: + print(f"[DiffusionRefiner] Failed to load: {e}") + + def __call__( + self, + image: np.ndarray, + mask: np.ndarray, + prompt: str = "clean natural background, realistic texture, seamless", + negative_prompt: str = "text, letters, watermark, artifacts, blurry", + steps: int = 25, + strength: float = 0.30, + ) -> np.ndarray: + """ + Refine inpainted image using SD Inpainting (masked only). + + Args: + image: RGB uint8 (H, W, 3) โ€” the LaMa output + mask: Binary uint8 (H, W), 255 = region to refine + strength: 0.25-0.35 recommended. >0.5 WILL destroy the image. + Returns: + Refined RGB uint8 (H, W, 3) โ€” only masked region modified + """ + if self.pipe is None: + print("[DiffusionRefiner] No pipeline loaded. Skipping refinement.") + return image + + # Clamp strength to safe range + strength = max(0.15, min(strength, 0.40)) + + h, w = image.shape[:2] + + # Scale down for SD to prevent CUDA OOM on smaller GPUs (e.g., 4GB VRAM) + # We limit the max dimension to 512 (SD's native training resolution) + max_dim = 512 + scale = min(max_dim / max(h, w), 1.0) + + new_w = int(w * scale) + new_h = int(h * scale) + + # SD requires dimensions divisible by 8 + new_w = max(8, (new_w // 8) * 8) + new_h = max(8, (new_h // 8) * 8) + + # Convert to PIL + pil_image = Image.fromarray(image).resize((new_w, new_h), Image.Resampling.LANCZOS) + pil_mask = Image.fromarray(mask).resize((new_w, new_h), Image.Resampling.NEAREST) + + # DEBUG: Verify mask integrity + mask_np = np.array(pil_mask) + mask_coverage = np.mean(mask_np > 127) * 100 + print(f"[DiffusionRefiner] Mask: min={mask_np.min()}, max={mask_np.max()}, " + f"coverage={mask_coverage:.1f}%, strength={strength}", flush=True) + + if mask_coverage > 50: + print(f"[DiffusionRefiner] โš  Mask covers {mask_coverage:.1f}% โ€” too large! Reducing strength.", flush=True) + strength = 0.20 + + if mask_coverage < 1: + print("[DiffusionRefiner] Mask is nearly empty. Skipping refinement.", flush=True) + return image + + # Run SD Inpainting โ€” CORRECT: passes mask_image + result = self.pipe( + prompt=prompt, + negative_prompt=negative_prompt, + image=pil_image, # โ† LaMa output as base + mask_image=pil_mask, # โ† CRITICAL: restricts to masked region + height=new_h, + width=new_w, + strength=strength, # โ† Low strength preserves LaMa structure + guidance_scale=6.0, + num_inference_steps=steps, + ).images[0] + + # Convert back to numpy at original resolution + result_np = np.array(result.resize((w, h), Image.Resampling.LANCZOS)) + + return result_np diff --git a/src/ai_text_removal/tr_pipelines/edge_extract.py b/src/ai_text_removal/tr_pipelines/edge_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..2701d39e903ae3dc151a1f6fef8f0efb40533407 --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/edge_extract.py @@ -0,0 +1,51 @@ +import cv2 +import numpy as np + + +class EdgeExtractor: + """ + Extracts structural edge information from the image using Canny edge detection. + The edge map is masked to remove text edges, leaving only the surrounding + structure to guide inpainting reconstruction. + + This implements the "Structure-Guided Inpainting" technique used in + research models like EdgeConnect and MTRNet++. + """ + + def __init__(self, canny_low: int = 50, canny_high: int = 150): + self.canny_low = canny_low + self.canny_high = canny_high + + def __call__(self, image: np.ndarray, mask: np.ndarray) -> np.ndarray: + """ + Extract edges from the image and zero-out edges inside the text mask. + + Args: + image (np.ndarray): RGB image (H, W, 3). + mask (np.ndarray): Binary mask where 255 = text region. + + Returns: + np.ndarray: Edge map (H, W), uint8, with text-region edges removed. + """ + # Convert to grayscale for edge detection + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + + # Apply Canny edge detection + edges = cv2.Canny(gray, self.canny_low, self.canny_high) + + # Ensure mask is binary (0 or 255) and 2D + if len(mask.shape) > 2: + mask = mask[:, :, 0] + mask_binary = (mask > 127).astype(np.uint8) + + # Zero out edges that fall inside the text mask. + # We only want structural edges from the *surrounding* background + # so the inpainter knows how to continue lines/textures. + structure_map = edges * (1 - mask_binary) + + # Optionally dilate the surviving edges slightly so the inpainter + # has a stronger structural signal at mask boundaries. + kernel = np.ones((3, 3), np.uint8) + structure_map = cv2.dilate(structure_map, kernel, iterations=1) + + return structure_map diff --git a/src/ai_text_removal/tr_pipelines/inpaint.py b/src/ai_text_removal/tr_pipelines/inpaint.py new file mode 100644 index 0000000000000000000000000000000000000000..8f9f7b60e2494b52fa37dd1e0e86d618708c9079 --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/inpaint.py @@ -0,0 +1,88 @@ +""" +LaMa Inpainting โ€” Pure structural reconstruction. + +Returns raw LaMa output for the FULL image. +Compositing is handled by the pipeline orchestrator. +""" +import os +import cv2 +import numpy as np +import torch + + +class LaMaInpainter: + """ + Big-LaMa inpainting model. Reconstructs structure in masked regions. + Returns the raw LaMa output โ€” compositing is done externally. + """ + + def __init__(self, model_path: str, std_model_path: str = None, device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.model = None + + def load_model(path, name): + if path and os.path.exists(path): + try: + m = torch.jit.load(path, map_location=self.device) + m.eval() + print(f"[Inpaint] โœ… Loaded {name} on {self.device}") + return m + except Exception as e: + print(f"[Inpaint] โš  Failed to load {name}: {e}") + return None + + self.model = load_model(model_path, "Big-LaMa") + if self.model is None and std_model_path: + self.model = load_model(std_model_path, "Standard LaMa") + + if self.model is None: + print("[Inpaint] โš  No LaMa model. Using OpenCV fallback.") + + def __call__(self, image: np.ndarray, mask: np.ndarray) -> np.ndarray: + """ + Inpaint masked regions. + + Args: + image: RGB uint8 (H, W, 3) + mask: Binary uint8 (H, W), 255 = fill + Returns: + Full inpainted image RGB uint8 (H, W, 3) + """ + if self.model is None: + return self._cv2_inpaint(image, mask) + return self._lama_forward(image, mask) + + def _lama_forward(self, image: np.ndarray, mask: np.ndarray) -> np.ndarray: + """Run LaMa at native resolution with proper padding.""" + h, w = image.shape[:2] + + # Pad to multiples of 8 (FFC requirement) + pad_h = (8 - (h % 8)) % 8 + pad_w = (8 - (w % 8)) % 8 + + if pad_h > 0 or pad_w > 0: + img_p = np.pad(image, ((0, pad_h), (0, pad_w), (0, 0)), mode='reflect') + msk_p = np.pad(mask, ((0, pad_h), (0, pad_w)), mode='constant', constant_values=0) + else: + img_p = image + msk_p = mask + + _, msk_p = cv2.threshold(msk_p, 127, 255, cv2.THRESH_BINARY) + + img_t = (torch.from_numpy(img_p.astype(np.float32)) + .permute(2, 0, 1).unsqueeze(0) / 255.0).to(self.device) + msk_t = (torch.from_numpy(msk_p.astype(np.float32)) + .unsqueeze(0).unsqueeze(0) / 255.0).to(self.device) + + with torch.no_grad(): + out_t = self.model(img_t, msk_t) + + out = out_t.squeeze(0).permute(1, 2, 0).cpu().numpy() + out = np.clip(out * 255, 0, 255).astype(np.uint8) + return out[:h, :w] + + def _cv2_inpaint(self, image: np.ndarray, mask: np.ndarray) -> np.ndarray: + bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + _, m = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY) + result = cv2.inpaint(bgr, m, inpaintRadius=5, flags=cv2.INPAINT_NS) + return cv2.cvtColor(result, cv2.COLOR_BGR2RGB) diff --git a/src/ai_text_removal/tr_pipelines/post_process.py b/src/ai_text_removal/tr_pipelines/post_process.py new file mode 100644 index 0000000000000000000000000000000000000000..3acc8cdf64fa9dd2581f01a27fec92f6dada6eb1 --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/post_process.py @@ -0,0 +1,119 @@ +import cv2 +import numpy as np + + +class PostProcessor: + """ + Final post-processing stage: Full-Resolution Compositing & Denoising. + 1. Extracts the inpainted patch + 2. Upscales it to match the native resolution of the original image + 3. Denoisies the patch to remove SD hallucination artifacts + 4. Seamlessly blends it into the pristine original image (0% bg quality loss) + """ + + def __init__(self, use_poisson: bool = True): + self.use_poisson = use_poisson + + def __call__( + self, + true_original: np.ndarray, + inpainted: np.ndarray, + mask: np.ndarray, + alpha_mask: np.ndarray = None + ) -> np.ndarray: + """ + Args: + true_original: Original un-resized RGB image (H_orig, W_orig, 3). + inpainted: Inpainted/Generated RGB image (H_work, W_work, 3). + mask: Hard binary mask (H_work, W_work), 255 = generated region. + alpha_mask: Soft alpha mask (H_work, W_work), 0-1 float32. + """ + # 1. Clean up the generated patch (Spatially denoise SD artifacts) + inpainted_clean = self._denoise_and_sharpen(inpainted) + + # 2. Find bounding box of the modified region in the working resolution + coords = cv2.findNonZero(mask) + if coords is None: + # If nothing was modified, return exactly the original image + return true_original + + x, y, w, h = cv2.boundingRect(coords) + + # Ensure box is strictly within working bounds + x = max(0, x) + y = max(0, y) + w = min(mask.shape[1] - x, w) + h = min(mask.shape[0] - y, h) + + # Extract the modified patch + patch = inpainted_clean[y:y+h, x:x+w] + + # 3. Calculate mapping from working res to native res + orig_h, orig_w = true_original.shape[:2] + work_h, work_w = inpainted.shape[:2] + + # Compute exact bounding box in the original high-res image + scale_x = orig_w / work_w + scale_y = orig_h / work_h + + nx = int(x * scale_x) + ny = int(y * scale_y) + nw = int(w * scale_x) + nh = int(h * scale_y) + + # Ensure bounds are safe + nx = max(0, nx) + ny = max(0, ny) + nw = min(orig_w - nx, nw) + nh = min(orig_h - ny, nh) + + # Upscale patch to native resolution + patch_hires = cv2.resize(patch, (nw, nh), interpolation=cv2.INTER_CUBIC) + + # Upscale mask to native resolution + patch_mask = mask[y:y+h, x:x+w] + patch_mask_hires = cv2.resize(patch_mask, (nw, nh), interpolation=cv2.INTER_NEAREST) + + # Ensure mask boundary has no harsh black edges by dilating slightly into patch + patch_mask_hires = cv2.dilate(patch_mask_hires, np.ones((5,5), np.uint8), iterations=2) + + # 4. Composite safely + output = true_original.copy() + try: + if self.use_poisson: + center = (nx + nw // 2, ny + nh // 2) + # Poisson blending for seamless illumination + output = cv2.seamlessClone( + patch_hires, + output, + patch_mask_hires, + center, + cv2.NORMAL_CLONE + ) + else: + # Soft alpha fallback + if alpha_mask is None: + # Generate a seamless alpha soft-mask on the fly + soft = cv2.GaussianBlur(mask, (15, 15), 0).astype(np.float32) / 255.0 + patch_alpha = soft[y:y+h, x:x+w] + else: + patch_alpha = alpha_mask[y:y+h, x:x+w] + + patch_alpha_hires = cv2.resize(patch_alpha, (nw, nh), interpolation=cv2.INTER_LINEAR) + patch_alpha_hires = np.expand_dims(patch_alpha_hires, -1) + + roi = output[ny:ny+nh, nx:nx+nw] + blended = (patch_hires * patch_alpha_hires) + (roi * (1 - patch_alpha_hires)) + output[ny:ny+nh, nx:nx+nw] = blended.astype(np.uint8) + + except Exception as e: + print(f"[PostProcessor] Blending failed, using hard copy fallback: {e}") + roi = output[ny:ny+nh, nx:nx+nw] + bin_mask = (patch_mask_hires > 127).astype(bool) + roi[bin_mask] = patch_hires[bin_mask] + + return output + + def _denoise_and_sharpen(self, img: np.ndarray) -> np.ndarray: + """Pass-through to preserve LaMa's natural texture generation.""" + return img diff --git a/src/ai_text_removal/tr_pipelines/preprocess.py b/src/ai_text_removal/tr_pipelines/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..2e36c20e79882a47cc084621331784ffc66aa707 --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/preprocess.py @@ -0,0 +1,22 @@ +import numpy as np +from tr_utils.image_utils import resize_image, normalize_to_tensor +import torch + +class ImagePreprocessor: + """ + Preprocess image step: Resizing and potentially normalizing + for downstream models. + """ + def __init__(self, max_size: int = 1024, device: str = "cuda"): + self.max_size = max_size + self.device = device + + def __call__(self, image: np.ndarray) -> tuple[np.ndarray, torch.Tensor]: + """ + Returns: + - resized_image (np.ndarray): resized to max_size, maintaining aspect ratio. + - tensor_image (torch.Tensor): normalized and moved to device. + """ + resized_img = resize_image(image, max_size=self.max_size) + tensor_img = normalize_to_tensor(resized_img, device=self.device) + return resized_img, tensor_img diff --git a/src/ai_text_removal/tr_pipelines/refine_mask.py b/src/ai_text_removal/tr_pipelines/refine_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..053996483e6d9a626417af38b3bf5fc91a0e513e --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/refine_mask.py @@ -0,0 +1,26 @@ +import numpy as np +from tr_utils.mask_utils import refine_mask + +class MaskRefiner: + """ + Pipeline step to refine a continuous/binary mask. + """ + def __init__(self, dilate_kernel: int = 5, dilate_iter: int = 2, blur_kernel: int = 3): + self.dilate_kernel = dilate_kernel + self.dilate_iter = dilate_iter + self.blur_kernel = blur_kernel + + def __call__(self, mask: np.ndarray) -> np.ndarray: + """ + Refines the mask. + Args: + mask (np.ndarray): The binary mask from SAM. + Returns: + np.ndarray: Refined mask. + """ + return refine_mask( + mask, + dilate_kernel=self.dilate_kernel, + dilate_iter=self.dilate_iter, + blur_kernel=self.blur_kernel + ) diff --git a/src/ai_text_removal/tr_pipelines/segment_mask.py b/src/ai_text_removal/tr_pipelines/segment_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..176858581623aa35705c34f82804fc7a082deb8a --- /dev/null +++ b/src/ai_text_removal/tr_pipelines/segment_mask.py @@ -0,0 +1,78 @@ +""" +Text Mask Generator โ€” Polygon Fill. + +For text regions, the detected text polygons from CRAFT/EasyOCR tightly wrap the text. +We simply fill these polygons to create the binary mask. +LaMa handles reconstructing the background within these regions. +""" +import cv2 +import numpy as np + + +class TextMaskGenerator: + """ + Converts detected text polygons into a precise stroke-level binary mask. + Uses Otsu's thresholding to separate text from background, reducing the mask size + drastically to preserve the original image. Applies dilation to cover anti-aliased + edges and prevent "ghost" letters. + """ + + def __init__(self): + pass + + def __call__(self, image: np.ndarray, polygons: list) -> np.ndarray: + """ + Generate a binary mask from text detection polygons. + """ + h, w = image.shape[:2] + global_mask = np.zeros((h, w), dtype=np.uint8) + + if len(polygons) == 0: + return global_mask + + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + + for poly in polygons: + pts = np.array(poly, dtype=np.int32) + if pts.ndim == 1: + continue + + x, y, pw, ph = cv2.boundingRect(pts) + x, y = max(0, x), max(0, y) + pw = min(w - x, pw) + ph = min(h - y, ph) + + if pw < 2 or ph < 2: + continue + + roi = gray[y:y+ph, x:x+pw] + + try: + # Otsu thresholding to find strokes + _, t1 = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + _, t2 = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) + except cv2.error: + cv2.fillPoly(global_mask, [pts], 255) + continue + + # Text usually occupies less area than background in a tight bounding box + if np.count_nonzero(t1) < np.count_nonzero(t2): + stroke_mask = t1 + else: + stroke_mask = t2 + + # CRITICAL: Dilate the strokes to cover the 2-3px anti-aliased halos! + # The higher iterations (e.g. 4) ensure all faint ghost boundaries are swallowed. + kernel = np.ones((5, 5), np.uint8) + dilated_strokes = cv2.dilate(stroke_mask, kernel, iterations=4) + + # Constrain to the original polygon + poly_shifted = pts - [x, y] + poly_mask = np.zeros_like(roi) + cv2.fillPoly(poly_mask, [poly_shifted], 255) + + final_roi_mask = cv2.bitwise_and(dilated_strokes, poly_mask) + + global_mask[y:y+ph, x:x+pw] = cv2.bitwise_or(global_mask[y:y+ph, x:x+pw], final_roi_mask) + + return global_mask diff --git a/src/ai_text_removal/tr_utils/__init__.py b/src/ai_text_removal/tr_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/ai_text_removal/tr_utils/image_utils.py b/src/ai_text_removal/tr_utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..136915a1f635ea4a3f3e08c6f7f8386b7dedb8bf --- /dev/null +++ b/src/ai_text_removal/tr_utils/image_utils.py @@ -0,0 +1,58 @@ +import cv2 +import numpy as np +import torch +from PIL import Image + +def load_image(image_path: str) -> np.ndarray: + """ + Loads an image from path using OpenCV. + Converts from BGR (OpenCV default) to RGB. + Returns: numpy array of shape (H, W, 3) in RGB format. + """ + image = cv2.imread(image_path) + if image is None: + raise ValueError(f"Could not load image at {image_path}") + return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + +def resize_image(image: np.ndarray, max_size: int = 1024) -> np.ndarray: + """ + Resizes an image while preserving the aspect ratio, + ensuring the longest side is at most `max_size`. + """ + h, w = image.shape[:2] + if max(h, w) > max_size: + scale = max_size / max(h, w) + new_w, new_h = int(w * scale), int(h * scale) + # Ensure dimensions are multiples of 8 for model compatibility + new_w = new_w - (new_w % 8) + new_h = new_h - (new_h % 8) + image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) + return image + +def normalize_to_tensor(image: np.ndarray, device: str = "cpu") -> torch.Tensor: + """ + Normalizes an image [0, 255] to [0.0, 1.0] and converts to a PyTorch Tensor + of shape (1, C, H, W). + """ + img_tensor = torch.from_numpy(image).float() / 255.0 + if len(img_tensor.shape) == 3: + img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0) # (H, W, C) -> (1, C, H, W) + elif len(img_tensor.shape) == 2: + img_tensor = img_tensor.unsqueeze(0).unsqueeze(0) # (H, W) -> (1, 1, H, W) + + return img_tensor.to(device) + +def tensor_to_image(tensor: torch.Tensor) -> np.ndarray: + """ + Converts a normalized PyTorch Tensor (1, C, H, W) back to a numpy array [0, 255] in (H, W, C). + """ + img = tensor.squeeze(0).cpu().detach().permute(1, 2, 0).numpy() + img = np.clip(img * 255, 0, 255).astype(np.uint8) + return img + +def save_image(image: np.ndarray, output_path: str): + """ + Saves an RGB numpy array to disk. + """ + image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + cv2.imwrite(output_path, image_bgr) diff --git a/src/ai_text_removal/tr_utils/mask_utils.py b/src/ai_text_removal/tr_utils/mask_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..139c3f756884d1162613692f679d234e01fa0875 --- /dev/null +++ b/src/ai_text_removal/tr_utils/mask_utils.py @@ -0,0 +1,47 @@ +import cv2 +import numpy as np + +def refine_mask(mask: np.ndarray, dilate_kernel: int = 5, dilate_iter: int = 2, blur_kernel: int = 3) -> np.ndarray: + """ + Refine a binary mask through morphological operations and smoothing. + + Args: + mask (np.ndarray): Binary mask, where 255 is the region to remove. + dilate_kernel (int): Kernel size for dilation. + dilate_iter (int): Number of dilation iterations. + blur_kernel (int): Kernel size for Gaussian blur smoothing. + + Returns: + np.ndarray: The refined mask. + """ + # Ensure mask is 2D + if len(mask.shape) > 2: + mask = mask[:, :, 0] + + # Ensure background is 0 and text is 255 + # (If the mask from upstream happens to be boolean, convert it) + if mask.dtype == bool: + mask = (mask * 255).astype(np.uint8) + + kernel = np.ones((dilate_kernel, dilate_kernel), np.uint8) + + # 1. Dilation: Expands the mask slightly to ensure text edges are covered completely + if dilate_iter > 0: + mask = cv2.dilate(mask, kernel, iterations=dilate_iter) + + # 2. Closing: Fills in small holes inside the text mask + mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) + + # 3. Smoothing: Gaussian blur to soften the hard edges of the mask + # This creates a soft feathered edge, which is critical for seamless inpainting + if blur_kernel > 0: + # Must be an odd number + if blur_kernel % 2 == 0: + blur_kernel += 1 + mask = cv2.GaussianBlur(mask, (blur_kernel, blur_kernel), 0) + + # We deliberately DO NOT threshold back to binary. + # Returning a soft mask (values from 0 to 255) ensures gradual blending + # at the boundary between inpainted and original pixels. + + return mask diff --git a/src/ai_text_removal/tr_utils/metrics.py b/src/ai_text_removal/tr_utils/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b19e9b0f5c643b8b86049167f956c36dc325d4 --- /dev/null +++ b/src/ai_text_removal/tr_utils/metrics.py @@ -0,0 +1,63 @@ +import torch +import numpy as np +from skimage.metrics import peak_signal_noise_ratio as compute_psnr +from skimage.metrics import structural_similarity as compute_ssim +try: + import lpips +except ImportError: + lpips = None + +# Initialize LPIPS model lazily if installed +_lpips_vgg = None + +def get_psnr(image_true: np.ndarray, image_test: np.ndarray) -> float: + """ + Computes Peak Signal-to-Noise Ratio. + Higher is better. + """ + return compute_psnr(image_true, image_test, data_range=255) + +def get_ssim(image_true: np.ndarray, image_test: np.ndarray) -> float: + """ + Computes Structural Similarity Index. + Higher (closer to 1) is better. + """ + # Using smaller win_size for smaller images if necessary, + # but 7 is standard for skimage SSIM with multichannel + min_dim = min(image_true.shape[0], image_true.shape[1]) + win_size = min(7, min_dim) + if win_size % 2 == 0: + win_size -= 1 + + return compute_ssim(image_true, image_test, channel_axis=-1, data_range=255, win_size=win_size) + +def get_lpips(image_true: torch.Tensor, image_test: torch.Tensor, device: str = "cpu") -> float: + """ + Computes Learned Perceptual Image Patch Similarity (LPIPS). + Lower is better. + + Requires inputs to be [1, C, H, W] Tensors in range [-1, 1]. + (If passed as [0, 1] normalized, we convert it here). + """ + global _lpips_vgg + if lpips is None: + print("LPIPS package not installed. Returning 0.0.") + return 0.0 + + if _lpips_vgg is None: + _lpips_vgg = lpips.LPIPS(net='vgg').to(device) + + # Ensure inputs are normalized [-1, 1] for LPIPS as expected by the library + # Assuming input is [0.0, 1.0] + if image_true.max() <= 1.0: + img_true = image_true * 2.0 - 1.0 + img_test = image_test * 2.0 - 1.0 + else: + # Assuming input is [0, 255] + img_true = (image_true / 255.0) * 2.0 - 1.0 + img_test = (image_test / 255.0) * 2.0 - 1.0 + + with torch.no_grad(): + score = _lpips_vgg(img_true.to(device), img_test.to(device)) + + return score.item() diff --git a/src/background_removal/__init__.py b/src/background_removal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..095c529ff5e270639de1e684fee6fc18eca9981a --- /dev/null +++ b/src/background_removal/__init__.py @@ -0,0 +1 @@ +# BackGround-Removal โ€” Production-grade adaptive AI background removal engine diff --git a/src/background_removal/bg_models/__init__.py b/src/background_removal/bg_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fea6220a21a4e402daa7c9e1e9137b5009b88ec --- /dev/null +++ b/src/background_removal/bg_models/__init__.py @@ -0,0 +1 @@ +# Models subpackage diff --git a/src/background_removal/bg_models/base_model.py b/src/background_removal/bg_models/base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..70d15a0af276584280fbe6ca86fdcdd30eb78120 --- /dev/null +++ b/src/background_removal/bg_models/base_model.py @@ -0,0 +1,45 @@ +""" +Abstract base class for all AI models in the background removal pipeline. +Provides a consistent load + predict interface. +""" +from abc import ABC, abstractmethod +import torch +import logging + +logger = logging.getLogger(__name__) + + +def get_device() -> torch.device: + """Auto-detect the best available device: CUDA โ†’ MPS โ†’ CPU.""" + if torch.cuda.is_available(): + return torch.device("cuda") + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return torch.device("mps") + return torch.device("cpu") + + +class BaseModel(ABC): + """Abstract base for pipeline AI models.""" + + def __init__(self): + self.device = get_device() + self.model = None + self._loaded = False + + @abstractmethod + def load(self): + """Load model weights into memory.""" + ... + + @abstractmethod + def predict(self, *args, **kwargs): + """Run inference on the input.""" + ... + + def ensure_loaded(self): + """Lazily load model on first use.""" + if not self._loaded: + logger.info(f"Loading {self.__class__.__name__} on {self.device}...") + self.load() + self._loaded = True + logger.info(f"{self.__class__.__name__} loaded successfully.") diff --git a/src/background_removal/bg_models/modnet/__init__.py b/src/background_removal/bg_models/modnet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..343508bef24a5b7cd98cafa3edea690deadf304f --- /dev/null +++ b/src/background_removal/bg_models/modnet/__init__.py @@ -0,0 +1 @@ +# MODNet (Alpha Matting) subpackage diff --git a/src/background_removal/bg_models/modnet/arch/__init__.py b/src/background_removal/bg_models/modnet/arch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65374c63488655fcd784b2a35d87980014674356 --- /dev/null +++ b/src/background_removal/bg_models/modnet/arch/__init__.py @@ -0,0 +1 @@ +# MODNet architecture definitions diff --git a/src/background_removal/bg_models/modnet/arch/mobilenetv2.py b/src/background_removal/bg_models/modnet/arch/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..7cbce03a4e8a82e47907dd353abe4907a441fac8 --- /dev/null +++ b/src/background_removal/bg_models/modnet/arch/mobilenetv2.py @@ -0,0 +1,139 @@ +""" +MobileNetV2 Backbone for MODNet. +Provides the feature extraction backbone used by the MODNet architecture. +""" +import torch +import torch.nn as nn +import math + + +def _make_divisible(v, divisor, min_value=None): + """Ensure a value is divisible by the divisor.""" + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + if new_v < 0.9 * v: + new_v += divisor + return new_v + + +class ConvBNReLU(nn.Sequential): + """Convolution + BatchNorm + ReLU6 block.""" + def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): + padding = (kernel_size - 1) // 2 + super().__init__( + nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), + nn.BatchNorm2d(out_planes), + nn.ReLU6(inplace=True), + ) + + +class InvertedResidual(nn.Module): + """MobileNetV2 inverted residual block.""" + def __init__(self, inp, oup, stride, expand_ratio): + super().__init__() + self.stride = stride + assert stride in [1, 2] + + hidden_dim = int(round(inp * expand_ratio)) + self.use_res_connect = self.stride == 1 and inp == oup + + layers = [] + if expand_ratio != 1: + layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1)) + layers.extend([ + ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim), + nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), + nn.BatchNorm2d(oup), + ]) + self.conv = nn.Sequential(*layers) + + def forward(self, x): + if self.use_res_connect: + return x + self.conv(x) + return self.conv(x) + + +class MobileNetV2(nn.Module): + """MobileNetV2 backbone for MODNet.""" + def __init__(self, width_mult=1.0): + super().__init__() + + input_channel = 32 + last_channel = 1280 + + # MobileNetV2 inverted residual setting + inverted_residual_setting = [ + # t (expand ratio), c (channels), n (repetitions), s (stride) + [1, 16, 1, 1], + [6, 24, 2, 2], + [6, 32, 3, 2], + [6, 64, 4, 2], + [6, 96, 3, 1], + [6, 160, 3, 2], + [6, 320, 1, 1], + ] + + input_channel = _make_divisible(input_channel * width_mult, 8) + self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), 8) + + features = [ConvBNReLU(3, input_channel, stride=2)] + + # Store intermediate feature channels for skip connections + self.feat_channels = [] + + for t, c, n, s in inverted_residual_setting: + output_channel = _make_divisible(c * width_mult, 8) + for i in range(n): + stride = s if i == 0 else 1 + features.append(InvertedResidual(input_channel, output_channel, stride, expand_ratio=t)) + input_channel = output_channel + self.feat_channels.append(output_channel) + + features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1)) + self.features = nn.Sequential(*features) + + self._initialize_weights() + + def _initialize_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + m.weight.data.normal_(0, math.sqrt(2.0 / n)) + if m.bias is not None: + m.bias.data.zero_() + elif isinstance(m, nn.BatchNorm2d): + m.weight.data.fill_(1) + m.bias.data.zero_() + + def forward(self, x): + """Extract multi-scale features for MODNet.""" + enc_features = [] + # features[0] is the initial conv + x = self.features[0](x) # stride 2 โ†’ H/2 + + # Group blocks by stride stages + block_idx = 1 + stage_configs = [ + (1, 1), # 1 block, stride 1 within + (2, 2), # 2 blocks + (3, 2), # 3 blocks + (4, 2), # 4 blocks + (3, 1), # 3 blocks + (3, 2), # 3 blocks + (1, 1), # 1 block + ] + + for n_blocks, _ in stage_configs: + for _ in range(n_blocks): + if block_idx < len(self.features) - 1: + x = self.features[block_idx](x) + block_idx += 1 + enc_features.append(x) + + # Final conv + if block_idx < len(self.features): + x = self.features[block_idx](x) + enc_features.append(x) + + return enc_features diff --git a/src/background_removal/bg_models/modnet/arch/modnet.py b/src/background_removal/bg_models/modnet/arch/modnet.py new file mode 100644 index 0000000000000000000000000000000000000000..94e18ca4da99335b0ee7e4ec6bb0f5e44c92a865 --- /dev/null +++ b/src/background_removal/bg_models/modnet/arch/modnet.py @@ -0,0 +1,122 @@ +""" +MODNet โ€” Matting Objective Decomposition Network +Produces fine-grained alpha transparency for hair, fur, glass, etc. + +Uses a MobileNetV2 backbone with three branches: + S-branch (Semantic), D-branch (Detail), F-branch (Fusion) +""" +import torch +import torch.nn as nn +import torch.nn.functional as F + +from bg_models.modnet.arch.mobilenetv2 import MobileNetV2 +from bg_models.modnet.arch.wrapper import Conv2dIBNormRelu, SEBlock, GaussianBlurLayer + + +class MODNet(nn.Module): + """ + MODNet architecture for portrait/alpha matting. + Three-branch design: Semantic (S), Detail (D), Fusion (F). + """ + + def __init__(self, in_channels=3, hr_channels=32, backbone_pretrained=False): + super().__init__() + + self.in_channels = in_channels + self.hr_channels = hr_channels + + # โ”€โ”€ Backbone โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + self.backbone = MobileNetV2() + + # โ”€โ”€ S-Branch (Semantic Estimation) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + self.se_block = SEBlock(self.backbone.last_channel, reduction=4) + self.s_head = nn.Sequential( + nn.Conv2d(self.backbone.last_channel, 1, kernel_size=1), + nn.Sigmoid(), + ) + + # โ”€โ”€ D-Branch (Detail Estimation) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + self.d_conv1 = Conv2dIBNormRelu(in_channels + 1, hr_channels, 3, padding=1) + self.d_conv2 = Conv2dIBNormRelu(hr_channels + self.backbone.last_channel, hr_channels, 3, padding=1) + self.d_conv3 = Conv2dIBNormRelu(hr_channels, hr_channels, 3, padding=1) + self.d_conv4 = Conv2dIBNormRelu(hr_channels, hr_channels, 3, padding=1) + self.d_conv5 = nn.Sequential( + nn.Conv2d(hr_channels, 1, kernel_size=3, padding=1), + nn.Sigmoid(), + ) + + # โ”€โ”€ F-Branch (Fusion) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + self.f_conv1 = Conv2dIBNormRelu(in_channels + 2 + hr_channels, hr_channels, 3, padding=1) + self.f_conv2 = Conv2dIBNormRelu(hr_channels, hr_channels, 3, padding=1) + self.f_conv3 = nn.Sequential( + nn.Conv2d(hr_channels, 1, kernel_size=3, padding=1), + nn.Sigmoid(), + ) + + # Gaussian blur for S-branch supervision + self.blur = GaussianBlurLayer(1, kernel_size=3) + + def forward(self, x, inference=False): + """ + Forward pass. + + Args: + x: Input tensor [B, 3, H, W] normalized to [-1, 1] + inference: If True, only return the fused alpha matte + + Returns: + If inference=True: alpha matte [B, 1, H, W] + If inference=False: (semantic, detail, matte) tuple + """ + # โ”€โ”€ Backbone features โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + enc_features = self.backbone(x) + enc2x = enc_features[0] # stride 2 + enc4x = enc_features[1] # stride 4 + enc32x = enc_features[-1] # stride 32 (deepest) + + # โ”€โ”€ S-Branch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + s = self.se_block(enc32x) + s = self.s_head(s) # [B, 1, H/32, W/32] + + # Upsample semantic prediction to full resolution + s_full = F.interpolate(s, scale_factor=32, mode="bilinear", align_corners=False) + + if inference: + # โ”€โ”€ D-Branch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + d = torch.cat([x, s_full], dim=1) # [B, 4, H, W] + d = self.d_conv1(d) + + # Incorporate deep features + enc32x_up = F.interpolate(enc32x, size=d.shape[2:], mode="bilinear", align_corners=False) + d = torch.cat([d, enc32x_up], dim=1) + d = self.d_conv2(d) + d = self.d_conv3(d) + d_feat = self.d_conv4(d) + d_out = self.d_conv5(d_feat) # [B, 1, H, W] + + # โ”€โ”€ F-Branch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + f = torch.cat([x, s_full, d_out, d_feat], dim=1) + f = self.f_conv1(f) + f = self.f_conv2(f) + matte = self.f_conv3(f) # [B, 1, H, W] + + return matte + + # Training: return all three outputs + # D-Branch + d = torch.cat([x, s_full.detach()], dim=1) + d = self.d_conv1(d) + enc32x_up = F.interpolate(enc32x, size=d.shape[2:], mode="bilinear", align_corners=False) + d = torch.cat([d, enc32x_up], dim=1) + d = self.d_conv2(d) + d = self.d_conv3(d) + d_feat = self.d_conv4(d) + d_out = self.d_conv5(d_feat) + + # F-Branch + f = torch.cat([x, s_full.detach(), d_out.detach(), d_feat.detach()], dim=1) + f = self.f_conv1(f) + f = self.f_conv2(f) + matte = self.f_conv3(f) + + return s, d_out, matte diff --git a/src/background_removal/bg_models/modnet/arch/wrapper.py b/src/background_removal/bg_models/modnet/arch/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..1a358b872cb72ead271c5f104b41ae951aaf9a62 --- /dev/null +++ b/src/background_removal/bg_models/modnet/arch/wrapper.py @@ -0,0 +1,96 @@ +""" +Wrapper utilities for MODNet architecture. +""" +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class IBNorm(nn.Module): + """Instance-Batch Normalization block.""" + def __init__(self, in_channels): + super().__init__() + self.half = in_channels // 2 + self.IN = nn.InstanceNorm2d(self.half, affine=True) + self.BN = nn.BatchNorm2d(in_channels - self.half) + + def forward(self, x): + split = torch.split(x, [self.half, x.size(1) - self.half], dim=1) + out1 = self.IN(split[0].contiguous()) + out2 = self.BN(split[1].contiguous()) + return torch.cat((out1, out2), 1) + +class Conv2dIBNormRelu(nn.Module): + """Conv2d + (IBNorm or BatchNorm) + LeakyReLU block.""" + def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, + dilation=1, groups=1, bias=True, with_ibn=True, with_relu=True): + super().__init__() + + layers = [ + nn.Conv2d(in_channels, out_channels, kernel_size, + stride=stride, padding=padding, dilation=dilation, + groups=groups, bias=bias) + ] + + if with_ibn: + layers.append(IBNorm(out_channels)) + else: + layers.append(nn.BatchNorm2d(out_channels)) + + if with_relu: + layers.append(nn.LeakyReLU(0.2, inplace=True)) + + self.layers = nn.Sequential(*layers) + + def forward(self, x): + return self.layers(x) + + +class SEBlock(nn.Module): + """Squeeze-and-Excitation block for channel attention.""" + def __init__(self, in_channels, reduction=16): + super().__init__() + self.pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Sequential( + nn.Linear(in_channels, in_channels // reduction, bias=False), + nn.ReLU(inplace=True), + nn.Linear(in_channels // reduction, in_channels, bias=False), + nn.Sigmoid(), + ) + + def forward(self, x): + b, c, _, _ = x.size() + y = self.pool(x).view(b, c) + y = self.fc(y).view(b, c, 1, 1) + return x * y.expand_as(x) + + +class GaussianBlurLayer(nn.Module): + """Apply Gaussian blur to a tensor (used for smoothing trimaps).""" + def __init__(self, channels, kernel_size=15): + super().__init__() + self.channels = channels + self.kernel_size = kernel_size + assert kernel_size % 2 != 0, "Kernel size must be odd" + + # Create Gaussian kernel + sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8 + kernel = torch.zeros(kernel_size) + center = kernel_size // 2 + for i in range(kernel_size): + kernel[i] = -(i - center) ** 2 / (2 * sigma ** 2) + kernel = torch.exp(kernel) + kernel = kernel / kernel.sum() + + # 2D kernel from outer product + kernel_2d = kernel.unsqueeze(1) @ kernel.unsqueeze(0) + kernel_2d = kernel_2d.unsqueeze(0).unsqueeze(0) + kernel_2d = kernel_2d.repeat(channels, 1, 1, 1) + + self.weight = nn.Parameter(data=kernel_2d, requires_grad=False) + self.padding = kernel_size // 2 + + def forward(self, x): + if x.shape[1] != self.channels: + raise ValueError(f"Expected {self.channels} channels, got {x.shape[1]}") + return F.conv2d(x, self.weight, padding=self.padding, groups=self.channels) diff --git a/src/background_removal/bg_models/modnet/config.py b/src/background_removal/bg_models/modnet/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d633c871e045be91fcb7da39445c375d1690cc3c --- /dev/null +++ b/src/background_removal/bg_models/modnet/config.py @@ -0,0 +1,46 @@ +""" +MODNet โ€” Device/path configuration. +""" +import os +import torch +import yaml + +# โ”€โ”€ Device Detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +def get_device() -> torch.device: + if torch.cuda.is_available(): + return torch.device("cuda") + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return torch.device("mps") + return torch.device("cpu") + + +DEVICE = get_device() + +# โ”€โ”€ Config from YAML โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +_CONFIG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "configs") +_MODNET_YAML = os.path.join(_CONFIG_DIR, "modnet.yaml") + +if os.path.exists(_MODNET_YAML): + with open(_MODNET_YAML, "r") as f: + _cfg = yaml.safe_load(f) +else: + _cfg = {} + +CHECKPOINT_NAME = _cfg.get("model", {}).get("checkpoint", "modnet_photographic_portrait_matting.ckpt") + +# Weight paths +_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +WEIGHTS_DIR = os.path.join(_PROJECT_ROOT, "weights") +CHECKPOINT_PATH = os.path.join(WEIGHTS_DIR, CHECKPOINT_NAME) + +# Preprocessing parameters +_preprocess = _cfg.get("preprocessing", {}) +REF_SIZE = _preprocess.get("ref_size", 512) +MAX_INFERENCE_SIZE = _preprocess.get("max_inference_size", 2048) +NORMALIZE_MEAN = _preprocess.get("normalize_mean", 0.5) +NORMALIZE_STD = _preprocess.get("normalize_std", 0.5) + +# Matting thresholds +_matting = _cfg.get("matting", {}) +FOREGROUND_THRESHOLD = _matting.get("foreground_threshold", 0.92) +BACKGROUND_THRESHOLD = _matting.get("background_threshold", 0.08) diff --git a/src/background_removal/bg_models/modnet/modnet_infer.py b/src/background_removal/bg_models/modnet/modnet_infer.py new file mode 100644 index 0000000000000000000000000000000000000000..fad06d33643542ca7cd2b0de161f361b58dda0ba --- /dev/null +++ b/src/background_removal/bg_models/modnet/modnet_infer.py @@ -0,0 +1,122 @@ +""" +MODNet Alpha Matting Inference +Provides the ModNetMatting class for running alpha matting predictions. +Key design: processes the FULL image (not a tight crop) for global context. +""" +import torch +import torch.nn.functional as F +import numpy as np +import logging + +from bg_models.modnet.modnet_loader import load_modnet_model +from bg_models.modnet.config import ( + DEVICE, REF_SIZE, MAX_INFERENCE_SIZE, + NORMALIZE_MEAN, NORMALIZE_STD, +) + +logger = logging.getLogger(__name__) + + +class ModNetMatting: + """ + MODNet alpha matting inference wrapper. + Caps inference at 2048px to preserve hair details on 4K+ images. + """ + + def __init__(self): + self.model = None + self._loaded = False + + def load(self): + """Load MODNet model.""" + self.model = load_modnet_model() + self._loaded = True + logger.info("ModNetMatting ready.") + + def ensure_loaded(self): + if not self._loaded: + self.load() + + def _preprocess(self, image_rgb: np.ndarray) -> tuple: + """ + Preprocess image for MODNet inference. + - Scale to ref_size, pad to div-by-32, normalize (x โˆ’ 0.5) / 0.5 + + Args: + image_rgb: Input image (H, W, 3) uint8 + + Returns: + (tensor, padding_info) for postprocessing + """ + h, w = image_rgb.shape[:2] + + # Cap at max inference size (preserves hair details on 4K+) + if max(h, w) > MAX_INFERENCE_SIZE: + scale = MAX_INFERENCE_SIZE / max(h, w) + new_h, new_w = int(h * scale), int(w * scale) + elif min(h, w) < REF_SIZE: + scale = REF_SIZE / min(h, w) + new_h, new_w = int(h * scale), int(w * scale) + else: + new_h, new_w = h, w + + # Pad to divisible by 32 + pad_h = (32 - new_h % 32) % 32 + pad_w = (32 - new_w % 32) % 32 + padded_h = new_h + pad_h + padded_w = new_w + pad_w + + # Resize + import cv2 + resized = cv2.resize(image_rgb, (new_w, new_h), interpolation=cv2.INTER_AREA) + + # Normalize: (x / 255.0 - 0.5) / 0.5 + tensor = resized.astype(np.float32) / 255.0 + tensor = (tensor - NORMALIZE_MEAN) / NORMALIZE_STD + + # HWC โ†’ CHW + tensor = tensor.transpose(2, 0, 1) + tensor = torch.from_numpy(tensor).unsqueeze(0).float() + + # Pad + if pad_h > 0 or pad_w > 0: + tensor = F.pad(tensor, (0, pad_w, 0, pad_h), mode="reflect") + + return tensor, { + "original_size": (h, w), + "resized_size": (new_h, new_w), + "padded_size": (padded_h, padded_w), + } + + def predict(self, image_rgb: np.ndarray) -> np.ndarray: + """ + Run MODNet alpha matting on the full image. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + + Returns: + Alpha matte (H, W) in [0.0, 1.0] + """ + self.ensure_loaded() + + tensor, meta = self._preprocess(image_rgb) + tensor = tensor.to(device=DEVICE, dtype=next(self.model.parameters()).dtype) + + with torch.no_grad(): + # MODNet inference mode + alpha = self.model(tensor, inference=True) # [1, 1, H, W] + + # Remove padding + orig_h, orig_w = meta["original_size"] + res_h, res_w = meta["resized_size"] + alpha = alpha[:, :, :res_h, :res_w] + + # Resize back to original + alpha = F.interpolate( + alpha, size=(orig_h, orig_w), + mode="bilinear", align_corners=False, + ) + + alpha = alpha.squeeze().cpu().numpy() + return np.clip(alpha, 0.0, 1.0).astype(np.float32) diff --git a/src/background_removal/bg_models/modnet/modnet_loader.py b/src/background_removal/bg_models/modnet/modnet_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..ea897e96323d26c6853264a8c314f538d1648ad1 --- /dev/null +++ b/src/background_removal/bg_models/modnet/modnet_loader.py @@ -0,0 +1,50 @@ +""" +MODNet Weight Loader โ€” Handles DataParallel prefix stripping. +""" +import torch +import logging +import os +from collections import OrderedDict + +from bg_models.modnet.arch.modnet import MODNet +from bg_models.modnet.config import CHECKPOINT_PATH, DEVICE + +logger = logging.getLogger(__name__) + + +def load_modnet_model() -> MODNet: + """ + Load MODNet model from checkpoint. + Handles DataParallel prefix stripping (weights saved with nn.DataParallel + have 'module.' prefix on all keys). + + Returns: + MODNet model loaded on the appropriate device. + """ + if not os.path.exists(CHECKPOINT_PATH): + raise FileNotFoundError( + f"MODNet checkpoint not found at: {CHECKPOINT_PATH}\n" + f"Download modnet_photographic_portrait_matting.ckpt from " + f"https://github.com/ZHKKKe/MODNet and place it in the weights/ directory." + ) + + logger.info(f"Loading MODNet from {CHECKPOINT_PATH} on {DEVICE}") + + # Create model + modnet = MODNet(in_channels=3, hr_channels=32, backbone_pretrained=False) + + # Load weights + state_dict = torch.load(CHECKPOINT_PATH, map_location=DEVICE, weights_only=False) + + # Strip 'module.' prefix from DataParallel-saved weights + new_state_dict = OrderedDict() + for key, value in state_dict.items(): + new_key = key.replace("module.", "") + new_state_dict[new_key] = value + + modnet.load_state_dict(new_state_dict, strict=False) + modnet.to(DEVICE) + modnet.eval() + + logger.info(f"MODNet loaded successfully on {DEVICE}") + return modnet diff --git a/src/background_removal/bg_models/sam/__init__.py b/src/background_removal/bg_models/sam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa48001a40b85a504c18b30ba224159bceff5e6 --- /dev/null +++ b/src/background_removal/bg_models/sam/__init__.py @@ -0,0 +1 @@ +# SAM (Segment Anything Model) subpackage diff --git a/src/background_removal/bg_models/sam/config.py b/src/background_removal/bg_models/sam/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c717b35607050b00e60e332eefc1336da364cae6 --- /dev/null +++ b/src/background_removal/bg_models/sam/config.py @@ -0,0 +1,51 @@ +""" +SAM (Segment Anything Model) โ€” Device/path configuration. +""" +import os +import torch +import yaml +import logging + +logger = logging.getLogger(__name__) + +# โ”€โ”€ Device Detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +def get_device() -> torch.device: + if torch.cuda.is_available(): + return torch.device("cuda") + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return torch.device("mps") + return torch.device("cpu") + + +DEVICE = get_device() + +# โ”€โ”€ Config from YAML โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +_CONFIG_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "configs") +_SAM_YAML = os.path.join(_CONFIG_DIR, "sam.yaml") + +if os.path.exists(_SAM_YAML): + with open(_SAM_YAML, "r") as f: + _cfg = yaml.safe_load(f) +else: + _cfg = {} + +MODEL_TYPE = _cfg.get("model", {}).get("type", "vit_b") +CHECKPOINT_NAME = _cfg.get("model", {}).get("checkpoint", "sam_vit_b_01ec64.pth") + +# Weight search paths (project weights/ directory) +_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +WEIGHTS_DIR = os.path.join(_PROJECT_ROOT, "weights") +CHECKPOINT_PATH = os.path.join(WEIGHTS_DIR, CHECKPOINT_NAME) + +# Per-device tuning +_device_key = DEVICE.type +_device_cfg = _cfg.get(_device_key, {}) +POINTS_PER_BATCH = _device_cfg.get("points_per_batch", 16) +USE_FP16 = _device_cfg.get("use_fp16", False) + +# Auto-segmentation parameters +_auto_cfg = _cfg.get("auto", {}) +POINTS_PER_SIDE = _auto_cfg.get("points_per_side", 32) +PRED_IOU_THRESH = _auto_cfg.get("pred_iou_thresh", 0.86) +STABILITY_SCORE_THRESH = _auto_cfg.get("stability_score_thresh", 0.92) +MIN_MASK_REGION_AREA = _auto_cfg.get("min_mask_region_area", 1000) diff --git a/src/background_removal/bg_models/sam/sam_loader.py b/src/background_removal/bg_models/sam/sam_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4c0b4ba7a0bcd231a99db0a3a8e59daedcb801 --- /dev/null +++ b/src/background_removal/bg_models/sam/sam_loader.py @@ -0,0 +1,44 @@ +""" +SAM Model Loader โ€” Registry-based loading with FP16 support for CUDA. +""" +import torch +import logging +from segment_anything import sam_model_registry + +from bg_models.sam.config import MODEL_TYPE, CHECKPOINT_PATH, DEVICE, USE_FP16 + +logger = logging.getLogger(__name__) + + +def load_sam_model(): + """ + Load SAM model from checkpoint using the registry. + + Returns: + SAM model loaded on the appropriate device. + """ + import os + if not os.path.exists(CHECKPOINT_PATH): + raise FileNotFoundError( + f"SAM checkpoint not found at: {CHECKPOINT_PATH}\n" + f"Download sam_vit_b_01ec64.pth from https://github.com/facebookresearch/segment-anything " + f"and place it in the weights/ directory." + ) + + logger.info(f"Loading SAM ({MODEL_TYPE}) from {CHECKPOINT_PATH} on {DEVICE}") + + # MPS workaround: force float32 default dtype (float64 crashes MPS) + if DEVICE.type == "mps": + torch.set_default_dtype(torch.float32) + + sam = sam_model_registry[MODEL_TYPE](checkpoint=CHECKPOINT_PATH) + sam.to(device=DEVICE) + + # CUDA optimization: half-precision + if USE_FP16 and DEVICE.type == "cuda": + sam = sam.half() + logger.info("SAM loaded with FP16 half-precision (CUDA)") + + sam.eval() + logger.info(f"SAM model loaded successfully on {DEVICE}") + return sam diff --git a/src/background_removal/bg_models/sam/sam_predictor.py b/src/background_removal/bg_models/sam/sam_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7a17981fa9b7d3aeefab13343e63c76ba36513 --- /dev/null +++ b/src/background_removal/bg_models/sam/sam_predictor.py @@ -0,0 +1,138 @@ +""" +SAM Segmenter โ€” Box-prompted, click-prompted, and auto-segmentation +with embedding caching for efficient multi-prediction. +""" +import numpy as np +import torch +import logging +from segment_anything import SamPredictor, SamAutomaticMaskGenerator + +from bg_models.sam.sam_loader import load_sam_model +from bg_models.sam.config import ( + DEVICE, POINTS_PER_SIDE, PRED_IOU_THRESH, + STABILITY_SCORE_THRESH, MIN_MASK_REGION_AREA, POINTS_PER_BATCH, +) + +logger = logging.getLogger(__name__) + + +class SamSegmenter: + """ + SAM segmentation with 3 modes: box, click, auto. + Uses embedding caching โ€” heavy ViT encoder runs once (~120ms), + subsequent predictions reuse the cached embedding (<30ms each). + """ + + def __init__(self): + self.sam_model = None + self.predictor = None + self.auto_generator = None + self._loaded = False + self._current_embedding_hash = None + + def load(self): + """Load SAM model and create predictor.""" + self.sam_model = load_sam_model() + self.predictor = SamPredictor(self.sam_model) + self._loaded = True + logger.info("SamSegmenter ready.") + + def ensure_loaded(self): + if not self._loaded: + self.load() + + def set_image(self, image_rgb: np.ndarray): + """ + Set the image and compute embeddings (heavy operation, ~120ms). + Cached โ€” only recomputes if the image changes. + """ + self.ensure_loaded() + img_hash = hash(image_rgb.tobytes()) + if img_hash != self._current_embedding_hash: + self.predictor.set_image(image_rgb) + self._current_embedding_hash = img_hash + logger.debug("SAM embeddings computed for new image.") + + def predict_box(self, image_rgb: np.ndarray, box: np.ndarray) -> np.ndarray: + """ + Predict mask from a bounding box prompt. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + box: Bounding box [x1, y1, x2, y2] + + Returns: + Binary mask (H, W) as bool + """ + self.set_image(image_rgb) + masks, scores, _ = self.predictor.predict( + box=box, + multimask_output=True, + ) + # Return the highest-scoring mask + best_idx = np.argmax(scores) + return masks[best_idx] + + def predict_click(self, image_rgb: np.ndarray, point: np.ndarray, label: int = 1) -> np.ndarray: + """ + Predict mask from a click point prompt. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + point: Click point [x, y] + label: 1 = foreground, 0 = background + + Returns: + Binary mask (H, W) as bool + """ + self.set_image(image_rgb) + masks, scores, _ = self.predictor.predict( + point_coords=np.array([point]), + point_labels=np.array([label]), + multimask_output=True, + ) + best_idx = np.argmax(scores) + return masks[best_idx] + + def predict_auto(self, image_rgb: np.ndarray) -> list: + """ + Automatic mask generation โ€” finds all objects in the image. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + + Returns: + List of mask dicts with 'segmentation', 'area', 'bbox', etc. + """ + self.ensure_loaded() + if self.auto_generator is None: + self.auto_generator = SamAutomaticMaskGenerator( + model=self.sam_model, + points_per_side=POINTS_PER_SIDE, + pred_iou_thresh=PRED_IOU_THRESH, + stability_score_thresh=STABILITY_SCORE_THRESH, + min_mask_region_area=MIN_MASK_REGION_AREA, + points_per_batch=POINTS_PER_BATCH, + ) + return self.auto_generator.generate(image_rgb) + + def predict_boxes(self, image_rgb: np.ndarray, boxes: list) -> np.ndarray: + """ + Predict and union masks from multiple bounding boxes. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + boxes: List of [x1, y1, x2, y2] bounding boxes + + Returns: + Union binary mask (H, W) as bool + """ + self.set_image(image_rgb) + h, w = image_rgb.shape[:2] + union_mask = np.zeros((h, w), dtype=bool) + + for box in boxes: + mask = self.predict_box(image_rgb, np.array(box)) + union_mask = union_mask | mask + + return union_mask diff --git a/src/background_removal/bg_models/sod/__init__.py b/src/background_removal/bg_models/sod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef8023f2c001321b7cbdde0fc966c24615f3be5 --- /dev/null +++ b/src/background_removal/bg_models/sod/__init__.py @@ -0,0 +1 @@ +# SOD (Salient Object Detection) subpackage diff --git a/src/background_removal/bg_models/sod/birefnet_model.py b/src/background_removal/bg_models/sod/birefnet_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8dd76789a193737f4046f836cc193119143ee2 --- /dev/null +++ b/src/background_removal/bg_models/sod/birefnet_model.py @@ -0,0 +1,94 @@ +""" +BiRefNet โ€” 2024 SOTA Salient Object Detection Model +Loaded from HuggingFace: ZhengPeng7/BiRefNet + +Uses the OFFICIAL inference pipeline exactly as documented: + 1. Resize to 1024x1024 (no padding) + 2. ToTensor + ImageNet normalize + 3. Forward pass โ†’ outputs[-1].sigmoid() + 4. Resize mask back to original size +""" +import torch +import numpy as np +import logging +from PIL import Image +from torchvision import transforms + +from bg_models.base_model import BaseModel + +logger = logging.getLogger(__name__) + + +class BiRefNetModel(BaseModel): + """BiRefNet Salient Object Detection โ€” finds the main subject(s) in an image.""" + + def __init__(self): + super().__init__() + self._transform = transforms.Compose([ + transforms.Resize((1024, 1024)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + def load(self): + """Load BiRefNet from HuggingFace (~800MB, auto-downloaded on first use).""" + from transformers import AutoModelForImageSegmentation + + model_id = "ZhengPeng7/BiRefNet" + logger.info(f"Downloading/loading BiRefNet from HuggingFace: {model_id}") + + self.model = AutoModelForImageSegmentation.from_pretrained( + model_id, trust_remote_code=True + ) + self.model.to(self.device) + self.model.eval() + + # Use half precision on CUDA for speed + if self.device.type == "cuda": + self.model.half() + + self._loaded = True + + def predict(self, tensor_input: torch.Tensor, original_size: tuple) -> np.ndarray: + """ + Run BiRefNet inference on a preprocessed tensor. + + Args: + tensor_input: Preprocessed tensor [1, 3, 1024, 1024] + original_size: (W, H) of the original image (PIL convention) + + Returns: + Soft probability map as numpy array [H, W] in [0.0, 1.0] + """ + self.ensure_loaded() + + with torch.no_grad(): + # Match model dtype (float16 on CUDA, float32 on CPU) + dtype = next(self.model.parameters()).dtype + tensor_input = tensor_input.to(device=self.device, dtype=dtype) + + preds = self.model(tensor_input)[-1].sigmoid().cpu() + pred = preds[0].squeeze() + + # Convert to PIL and resize to original image dimensions + pred_pil = transforms.ToPILImage()(pred) + mask_pil = pred_pil.resize(original_size, Image.BILINEAR) + + return np.array(mask_pil).astype(np.float32) / 255.0 + + def predict_from_pil(self, pil_image: Image.Image) -> np.ndarray: + """ + Convenience method: run BiRefNet on a PIL image directly. + This is the OFFICIAL way to use BiRefNet. + + Args: + pil_image: Input PIL Image (RGB) + + Returns: + Soft probability map [H, W] in [0.0, 1.0] + """ + self.ensure_loaded() + original_size = pil_image.size # (W, H) + + tensor_input = self._transform(pil_image).unsqueeze(0) + return self.predict(tensor_input, original_size) diff --git a/src/background_removal/bg_pipeline/__init__.py b/src/background_removal/bg_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6bc41a8b15705dca4eb55e8a7236eec44e12985 --- /dev/null +++ b/src/background_removal/bg_pipeline/__init__.py @@ -0,0 +1 @@ +# Pipeline stages subpackage diff --git a/src/background_removal/bg_pipeline/matting.py b/src/background_removal/bg_pipeline/matting.py new file mode 100644 index 0000000000000000000000000000000000000000..1b9d9b867ce112987aeab2590de979b7e123e873 --- /dev/null +++ b/src/background_removal/bg_pipeline/matting.py @@ -0,0 +1,98 @@ +""" +Stage 4 โ€” Alpha Matting (MODNet) +Uses a Soft Trimap Architecture derived from BiRefNet's confidence map. + +Key design: MODNet runs on the FULL image (not a tight crop) so it has +global context to distinguish sky from hair. +""" +import numpy as np +import time +import logging + +from bg_models.modnet.modnet_infer import ModNetMatting +from bg_models.modnet.config import FOREGROUND_THRESHOLD, BACKGROUND_THRESHOLD + +logger = logging.getLogger(__name__) + + +class AlphaMatting: + """ + Stage 4: Produces fine-grained alpha transparency using MODNet. + + Soft Trimap zones: + - Definite Foreground (mask โ‰ฅ 0.92): 100% opaque + - Edge Zone / Uncertain (0.08 < mask < 0.92): MODNet decides + - Definite Background (mask โ‰ค 0.08): 0% opaque + + Final alpha: combined = inner_body + (MODNet_alpha ร— edge_zone) + """ + + def __init__(self): + self.modnet = ModNetMatting() + + def load(self): + """Eagerly load MODNet.""" + self.modnet.ensure_loaded() + + def _build_soft_trimap(self, mask: np.ndarray) -> dict: + """ + Build a soft trimap from BiRefNet's confidence map. + + Args: + mask: Soft mask [H, W] in [0.0, 1.0] + + Returns: + dict with 'foreground', 'background', 'uncertain' boolean masks + """ + foreground = mask >= FOREGROUND_THRESHOLD # Definite FG (inner body) + background = mask <= BACKGROUND_THRESHOLD # Definite BG + uncertain = ~foreground & ~background # Edge zone + + logger.debug( + f"Trimap zones โ€” FG: {foreground.sum()}, " + f"BG: {background.sum()}, Uncertain: {uncertain.sum()}" + ) + + return { + "foreground": foreground, + "background": background, + "uncertain": uncertain, + } + + def matte(self, image_rgb: np.ndarray, mask: np.ndarray) -> tuple: + """ + Run alpha matting with soft trimap. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + mask: Confidence mask [H, W] in [0.0, 1.0] (from BiRefNet or SAM+BiRefNet) + + Returns: + (alpha, latency_ms) where: + alpha: Combined alpha matte [H, W] in [0.0, 1.0] + latency_ms: float + """ + start = time.time() + + # Build soft trimap + trimap = self._build_soft_trimap(mask) + + # Run MODNet on full image + modnet_alpha = self.modnet.predict(image_rgb) + + # Combine using trimap zones + # inner_body is 100% opaque + # edge_zone uses MODNet alpha + # background is 0% + combined = np.zeros_like(mask, dtype=np.float32) + combined[trimap["foreground"]] = 1.0 + combined[trimap["uncertain"]] = modnet_alpha[trimap["uncertain"]] + combined[trimap["background"]] = 0.0 + + # Ensure values stay in [0, 1] + combined = np.clip(combined, 0.0, 1.0) + + latency_ms = (time.time() - start) * 1000 + logger.info(f"Stage 4 (Alpha Matting): {latency_ms:.0f}ms") + + return combined, latency_ms diff --git a/src/background_removal/bg_pipeline/postprocessing.py b/src/background_removal/bg_pipeline/postprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..657d3d69cb6d311f7475f545fb935ff551b3cc55 --- /dev/null +++ b/src/background_removal/bg_pipeline/postprocessing.py @@ -0,0 +1,162 @@ +""" +Stage 5 โ€” Postprocessing +Sharpen, guided filter, defringe, and composite the final RGBA output. +""" +import numpy as np +import cv2 +import time +import logging + +logger = logging.getLogger(__name__) + + +class Postprocessor: + """ + Stage 5: Refine the alpha matte and produce the final RGBA composite. + + Steps: + 1. Sigmoid sharpening (strength=1.8) โ€” counteracts MODNet softness + 2. Island removal โ€” connected-component cleaning of artifacts + 3. Color despill/defringe โ€” removes background color bleed from edges + 4. Guided filter (radius=2, ฮต=1e-6) โ€” edge-aware smoothing + 5. Interior enforcement โ€” re-enforces definite interior โ‰ฅ 50% opaque + 6. RGBA composite โ€” merges defringed RGB + refined alpha + """ + + # Configuration + SHARPEN_STRENGTH = 1.8 + GUIDED_FILTER_RADIUS = 2 + GUIDED_FILTER_EPS = 1e-6 + ISLAND_MIN_AREA = 100 + INTERIOR_THRESHOLD = 0.5 + + def _sigmoid_sharpen(self, alpha: np.ndarray) -> np.ndarray: + """ + Apply sigmoid sharpening to counteract MODNet's natural softness. + Maps alpha values through a steep sigmoid centered at 0.5. + """ + # Sigmoid: 1 / (1 + exp(-strength * (x - 0.5))) + x = self.SHARPEN_STRENGTH * (alpha - 0.5) + sharpened = 1.0 / (1.0 + np.exp(-x)) + return sharpened.astype(np.float32) + + def _remove_islands(self, alpha: np.ndarray) -> np.ndarray: + """Remove small disconnected islands (artifacts) from the alpha mask.""" + binary = (alpha > 0.5).astype(np.uint8) + num_components, labels, stats, _ = cv2.connectedComponentsWithStats( + binary, connectivity=8 + ) + + # Keep only components larger than threshold + cleaned = alpha.copy() + for i in range(1, num_components): + if stats[i, cv2.CC_STAT_AREA] < self.ISLAND_MIN_AREA: + cleaned[labels == i] = 0.0 + + return cleaned + + def _color_despill(self, image_rgb: np.ndarray, alpha: np.ndarray) -> np.ndarray: + """ + Remove background color bleed from semi-transparent edges. + Non-destructive: only affects pixels with alpha < 1.0. + """ + result = image_rgb.copy().astype(np.float32) + h, w = alpha.shape + + # Edge zone: pixels with partial transparency + edge_mask = (alpha > 0.05) & (alpha < 0.95) + + if edge_mask.sum() == 0: + return result.astype(np.uint8) + + # Estimate background color from low-alpha pixels + very_low_alpha = alpha < 0.15 + if very_low_alpha.sum() > 100: + bg_color = np.mean(result[very_low_alpha], axis=0) + else: + # Fallback: use image border pixels + border_pixels = np.concatenate([ + result[0, :], result[-1, :], result[:, 0], result[:, -1] + ]) + bg_color = np.mean(border_pixels, axis=0) + + # Remove background color contribution from edge pixels + # Formula: defringed = (pixel - bg_color * (1 - alpha)) / alpha + for c in range(3): + channel = result[:, :, c] + a = np.clip(alpha, 0.01, 1.0) # avoid division by zero + defringed = (channel - bg_color[c] * (1.0 - a)) / a + channel[edge_mask] = defringed[edge_mask] + result[:, :, c] = np.clip(channel, 0, 255) + + return result.astype(np.uint8) + + def _guided_filter(self, guide: np.ndarray, src: np.ndarray) -> np.ndarray: + """ + Edge-aware smoothing using guided filter. + Falls back to Gaussian blur if cv2.ximgproc is not available. + """ + try: + guided = cv2.ximgproc.guidedFilter( + guide=guide.astype(np.float32), + src=src.astype(np.float32), + radius=self.GUIDED_FILTER_RADIUS, + eps=self.GUIDED_FILTER_EPS, + ) + return guided + except (AttributeError, cv2.error): + # Fallback: Gaussian blur + logger.debug("cv2.ximgproc not available, using Gaussian blur fallback") + ksize = self.GUIDED_FILTER_RADIUS * 2 + 1 + return cv2.GaussianBlur(src, (ksize, ksize), 0) + + def _enforce_interior(self, alpha: np.ndarray, original_mask: np.ndarray) -> np.ndarray: + """Re-enforce that definite interior stays โ‰ฅ 50% opaque.""" + interior = original_mask >= 0.92 + result = alpha.copy() + result[interior] = np.maximum(result[interior], self.INTERIOR_THRESHOLD) + return result + + def process(self, image_rgb: np.ndarray, alpha: np.ndarray, + original_mask: np.ndarray = None) -> tuple: + """ + Full postprocessing pipeline. + + Args: + image_rgb: Original image (H, W, 3) uint8 RGB + alpha: Alpha matte [H, W] in [0.0, 1.0] + original_mask: Original BiRefNet mask for interior enforcement + + Returns: + (rgba_image, latency_ms) where: + rgba_image: Final RGBA image (H, W, 4) uint8 + latency_ms: float + """ + start = time.time() + + # Step 1: Sigmoid sharpening + alpha = self._sigmoid_sharpen(alpha) + + # Step 2: Island removal + alpha = self._remove_islands(alpha) + + # Step 3: Color despill/defringe + defringed_rgb = self._color_despill(image_rgb, alpha) + + # Step 4: Guided filter (edge-aware smoothing) + gray_guide = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0 + alpha = self._guided_filter(gray_guide, alpha) + alpha = np.clip(alpha, 0.0, 1.0) + + # Step 5: Interior enforcement + if original_mask is not None: + alpha = self._enforce_interior(alpha, original_mask) + + # Step 6: RGBA composite + alpha_uint8 = (alpha * 255).astype(np.uint8) + rgba = np.dstack([defringed_rgb, alpha_uint8]) # (H, W, 4) + + latency_ms = (time.time() - start) * 1000 + logger.info(f"Stage 5 (Postprocessing): {latency_ms:.0f}ms") + + return rgba, latency_ms diff --git a/src/background_removal/bg_pipeline/preprocessing.py b/src/background_removal/bg_pipeline/preprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3cb5b266348db8cf6a054f0afa75ae9e3aa89d --- /dev/null +++ b/src/background_removal/bg_pipeline/preprocessing.py @@ -0,0 +1,87 @@ +""" +Stage 1 โ€” Preprocessing +Scale, pad, normalize images for BiRefNet inference. +""" +import torch +import numpy as np +from PIL import Image +import logging + +logger = logging.getLogger(__name__) + +# ImageNet normalization constants +IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32) +IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32) +TARGET_SIZE = 1024 + + +def preprocess_for_birefnet(image, target_size: int = TARGET_SIZE) -> tuple: + """ + Preprocess an image for BiRefNet inference. + + Steps: + 1. Aspect-ratio scaling (longest side โ†’ 1024px, LANCZOS downscale) + 2. ImageNet normalization + 3. HWC โ†’ CHW conversion + unsqueeze to [1, 3, H, W] + 4. Zero-padding to exactly 1024ร—1024 + + Args: + image: PIL Image or numpy array (H, W, 3) RGB uint8 + target_size: Target size for padding (default 1024) + + Returns: + (tensor, metadata_dict) where: + tensor: torch.Tensor [1, 3, target_size, target_size] + metadata: dict with 'original_size', 'scaled_size' for un-padding later + """ + # Convert to numpy if PIL + if isinstance(image, Image.Image): + img_np = np.array(image) + else: + img_np = image.copy() + + orig_h, orig_w = img_np.shape[:2] + + # Step 1: Aspect-ratio scaling (longest side โ†’ target_size) + max_side = max(orig_h, orig_w) + if max_side > target_size: + scale = target_size / max_side + new_h = int(orig_h * scale) + new_w = int(orig_w * scale) + from PIL import Image as PILImage + pil_img = PILImage.fromarray(img_np) + pil_img = pil_img.resize((new_w, new_h), PILImage.LANCZOS) + img_np = np.array(pil_img) + else: + new_h, new_w = orig_h, orig_w + + # Step 2: ImageNet normalization + img_float = img_np.astype(np.float32) / 255.0 + img_norm = (img_float - IMAGENET_MEAN) / IMAGENET_STD + + # Step 3: HWC โ†’ CHW + img_chw = img_norm.transpose(2, 0, 1) # [3, H, W] + + # Step 4: Zero-padding to target_size ร— target_size + pad_h = target_size - new_h + pad_w = target_size - new_w + + if pad_h > 0 or pad_w > 0: + img_chw = np.pad( + img_chw, + ((0, 0), (0, pad_h), (0, pad_w)), + mode="constant", + constant_values=0, + ) + + tensor = torch.from_numpy(img_chw).unsqueeze(0).float() # [1, 3, 1024, 1024] + + metadata = { + "original_size": (orig_h, orig_w), + "scaled_size": (new_h, new_w), + "target_size": target_size, + "pad_h": pad_h, + "pad_w": pad_w, + } + + return tensor, metadata diff --git a/src/background_removal/bg_pipeline/salient_detection.py b/src/background_removal/bg_pipeline/salient_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..588507044a80958c0c9b5178dbf5ccadcc85e092 --- /dev/null +++ b/src/background_removal/bg_pipeline/salient_detection.py @@ -0,0 +1,48 @@ +""" +Stage 2 โ€” Salient Object Detection (BiRefNet) +Wraps the BiRefNet model for use in the pipeline. +""" +import numpy as np +import time +import logging +from PIL import Image + +from bg_models.sod.birefnet_model import BiRefNetModel + +logger = logging.getLogger(__name__) + + +class SalientDetector: + """ + Stage 2: Runs BiRefNet to produce a soft probability map. + Output is [H, W] float32 in [0.0, 1.0] โ€” NOT a binary mask. + """ + + def __init__(self): + self.model = BiRefNetModel() + + def load(self): + """Eagerly load the model.""" + self.model.ensure_loaded() + + def predict(self, image_rgb: np.ndarray) -> tuple: + """ + Run salient object detection on an RGB image. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + + Returns: + (soft_mask, latency_ms) where: + soft_mask: np.ndarray [H, W] in [0.0, 1.0] + latency_ms: float โ€” inference time in milliseconds + """ + start = time.time() + + pil_image = Image.fromarray(image_rgb) + soft_mask = self.model.predict_from_pil(pil_image) + + latency_ms = (time.time() - start) * 1000 + logger.info(f"Stage 2 (BiRefNet SOD): {latency_ms:.0f}ms") + + return soft_mask, latency_ms diff --git a/src/background_removal/bg_pipeline/scene_analyzer.py b/src/background_removal/bg_pipeline/scene_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c75afe7a51adba3c725be97cf08ba4f0585afbc --- /dev/null +++ b/src/background_removal/bg_pipeline/scene_analyzer.py @@ -0,0 +1,135 @@ +""" +Stage 3 โ€” Adaptive Scene Routing +Zero-cost router (<5ms) that classifies scenes as SIMPLE or COMPLEX +using 4 heuristics and a voting system. + +SIMPLE (portraits, clean backgrounds): bypass SAM entirely +COMPLEX (products, multi-subject, cluttered): use SAM segmentation +""" +import numpy as np +import cv2 +import time +import logging +from enum import Enum + +logger = logging.getLogger(__name__) + + +class SceneType(Enum): + SIMPLE = "SIMPLE" + COMPLEX = "COMPLEX" + + +class SceneAnalyzer: + """ + Stage 3: Adaptive scene router using 4 heuristics. + + Heuristics: + H1: Multi-subject detection (>1 blob with area > 2% of image) + H2: Background edge density (>12% Canny edge density in BG) + H3: Confidence spread (ฯƒ(soft_mask) < 0.28) + H4: Subject size ratio (FG < 15% of image) + + Decision: โ‰ฅ 2 votes โ†’ COMPLEX, otherwise โ†’ SIMPLE + """ + + # Tunable thresholds + MULTI_SUBJECT_AREA_THRESH = 0.02 # H1: min 2% of image per blob + EDGE_DENSITY_THRESH = 0.12 # H2: 12% Canny edge density + CONFIDENCE_SPREAD_THRESH = 0.28 # H3: ฯƒ threshold + SUBJECT_SIZE_THRESH = 0.15 # H4: FG < 15% of image + VOTE_THRESHOLD = 2 # โ‰ฅ 2 votes โ†’ COMPLEX + + def analyze(self, soft_mask: np.ndarray, image_rgb: np.ndarray = None) -> tuple: + """ + Classify the scene as SIMPLE or COMPLEX. + + Args: + soft_mask: Soft probability map [H, W] in [0.0, 1.0] from BiRefNet + image_rgb: Optional original image for edge density analysis + + Returns: + (scene_type, vote_details, latency_ms) where: + scene_type: SceneType.SIMPLE or SceneType.COMPLEX + vote_details: dict with individual heuristic results + latency_ms: float + """ + start = time.time() + votes = 0 + details = {} + + # Binary mask for spatial analysis + binary_mask = (soft_mask > 0.5).astype(np.uint8) + h, w = soft_mask.shape + total_pixels = h * w + + # โ”€โ”€ H1: Multi-subject detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + num_components, labels, stats, _ = cv2.connectedComponentsWithStats( + binary_mask, connectivity=8 + ) + # Count blobs with area > 2% of image (exclude background label 0) + large_blobs = 0 + for i in range(1, num_components): + blob_area = stats[i, cv2.CC_STAT_AREA] + if blob_area / total_pixels > self.MULTI_SUBJECT_AREA_THRESH: + large_blobs += 1 + + h1_complex = large_blobs > 1 + if h1_complex: + votes += 1 + details["H1_multi_subject"] = { + "large_blobs": large_blobs, + "complex": h1_complex, + } + + # โ”€โ”€ H2: Background edge density โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + if image_rgb is not None: + gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY) + edges = cv2.Canny(gray, 50, 150) + bg_mask = (1 - binary_mask).astype(bool) + bg_pixels = bg_mask.sum() + if bg_pixels > 0: + bg_edge_density = edges[bg_mask].sum() / (255.0 * bg_pixels) + else: + bg_edge_density = 0.0 + else: + bg_edge_density = 0.0 + + h2_complex = bg_edge_density > self.EDGE_DENSITY_THRESH + if h2_complex: + votes += 1 + details["H2_edge_density"] = { + "density": float(bg_edge_density), + "complex": h2_complex, + } + + # โ”€โ”€ H3: Confidence spread โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + confidence_std = float(np.std(soft_mask)) + h3_complex = confidence_std < self.CONFIDENCE_SPREAD_THRESH + if h3_complex: + votes += 1 + details["H3_confidence_spread"] = { + "std": confidence_std, + "complex": h3_complex, + } + + # โ”€โ”€ H4: Subject size ratio โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + fg_ratio = float(binary_mask.sum()) / total_pixels + h4_complex = fg_ratio < self.SUBJECT_SIZE_THRESH + if h4_complex: + votes += 1 + details["H4_subject_size"] = { + "fg_ratio": fg_ratio, + "complex": h4_complex, + } + + # โ”€โ”€ Decision โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + scene_type = SceneType.COMPLEX if votes >= self.VOTE_THRESHOLD else SceneType.SIMPLE + latency_ms = (time.time() - start) * 1000 + + logger.info( + f"Stage 3 (Scene Analyzer): {scene_type.value} " + f"({votes}/{4} votes, {latency_ms:.1f}ms)" + ) + + return scene_type, details, latency_ms diff --git a/src/background_removal/bg_pipeline/segmentation.py b/src/background_removal/bg_pipeline/segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..07b641a29a87fc3de6bdb22b36cbd6bdf4837cb8 --- /dev/null +++ b/src/background_removal/bg_pipeline/segmentation.py @@ -0,0 +1,114 @@ +""" +Stage 3b โ€” SAM Box-Prompted Segmentation (COMPLEX path) +Extracts bounding boxes from BiRefNet's coarse mask and prompts SAM +for pixel-perfect binary masks per subject. +""" +import numpy as np +import cv2 +import time +import logging + +from bg_models.sam.sam_predictor import SamSegmenter + +logger = logging.getLogger(__name__) + + +class SegmentationRefiner: + """ + Stage 3b: SAM-based segmentation for COMPLEX scenes. + + Workflow: + 1. Extract individual bounding boxes from BiRefNet's coarse mask + 2. Prompt SAM with each bounding box โ†’ pixel-perfect binary mask per subject + 3. Union all per-subject masks + 4. Failsafe: union with BiRefNet binary mask (ensures no subjects are lost) + """ + + def __init__(self): + self.sam = SamSegmenter() + + def load(self): + """Eagerly load SAM model.""" + self.sam.ensure_loaded() + + def _extract_bboxes(self, soft_mask: np.ndarray, min_area_ratio: float = 0.005) -> list: + """ + Extract bounding boxes from BiRefNet's coarse mask using connected components. + + Args: + soft_mask: Soft probability mask [H, W] in [0.0, 1.0] + min_area_ratio: Minimum blob area as ratio of total image size + + Returns: + List of [x1, y1, x2, y2] bounding boxes + """ + binary = (soft_mask > 0.5).astype(np.uint8) + h, w = binary.shape + total_area = h * w + + # Morphological cleanup + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) + binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=2) + + num_components, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8) + + bboxes = [] + for i in range(1, num_components): # Skip background (label 0) + area = stats[i, cv2.CC_STAT_AREA] + if area / total_area < min_area_ratio: + continue + + x = stats[i, cv2.CC_STAT_LEFT] + y = stats[i, cv2.CC_STAT_TOP] + bw = stats[i, cv2.CC_STAT_WIDTH] + bh = stats[i, cv2.CC_STAT_HEIGHT] + + # Add padding (10% of bbox size) + pad_x = int(bw * 0.1) + pad_y = int(bh * 0.1) + x1 = max(0, x - pad_x) + y1 = max(0, y - pad_y) + x2 = min(w, x + bw + pad_x) + y2 = min(h, y + bh + pad_y) + + bboxes.append([x1, y1, x2, y2]) + + logger.info(f"Extracted {len(bboxes)} bounding boxes from BiRefNet mask") + return bboxes + + def refine(self, image_rgb: np.ndarray, soft_mask: np.ndarray) -> tuple: + """ + Run SAM box-prompted segmentation on COMPLEX scenes. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + soft_mask: BiRefNet's soft probability mask [H, W] + + Returns: + (refined_mask, latency_ms) where: + refined_mask: Binary mask (H, W) float32 in [0.0, 1.0] + latency_ms: float + """ + start = time.time() + + # Step 1: Extract bounding boxes from BiRefNet mask + bboxes = self._extract_bboxes(soft_mask) + + if not bboxes: + # Fallback: use BiRefNet binary mask directly + logger.warning("No bounding boxes extracted โ€” using BiRefNet mask directly") + binary = (soft_mask > 0.5).astype(np.float32) + latency_ms = (time.time() - start) * 1000 + return binary, latency_ms + + # Step 2-3: SAM predict per-box and union all masks + sam_mask = self.sam.predict_boxes(image_rgb, bboxes) + + # Step 4: Failsafe โ€” union with BiRefNet binary mask + birefnet_binary = soft_mask > 0.5 + final_mask = (sam_mask | birefnet_binary).astype(np.float32) + + latency_ms = (time.time() - start) * 1000 + logger.info(f"Stage 3b (SAM Segmentation): {latency_ms:.0f}ms ({len(bboxes)} boxes)") + + return final_mask, latency_ms diff --git a/src/background_removal/configs/__init__.py b/src/background_removal/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..82a4977ef802ab6729fa343594cf28db571f1729 --- /dev/null +++ b/src/background_removal/configs/__init__.py @@ -0,0 +1 @@ +# Configs subpackage diff --git a/src/background_removal/configs/modnet.yaml b/src/background_removal/configs/modnet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e3e9d379bdf260b745318104a4f9e3ecf4091c7 --- /dev/null +++ b/src/background_removal/configs/modnet.yaml @@ -0,0 +1,16 @@ +# MODNet (Alpha Matting) Configuration +# Model: MODNet with MobileNetV2 backbone + +model: + checkpoint: "modnet_photographic_portrait_matting.ckpt" + +preprocessing: + ref_size: 512 + max_inference_size: 2048 + normalize_mean: 0.5 + normalize_std: 0.5 + +# Alpha matting thresholds +matting: + foreground_threshold: 0.92 + background_threshold: 0.08 diff --git a/src/background_removal/configs/sam.yaml b/src/background_removal/configs/sam.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5a76ebe8f25f79a574c462dbaae0fb83cfad3875 --- /dev/null +++ b/src/background_removal/configs/sam.yaml @@ -0,0 +1,26 @@ +# SAM (Segment Anything Model) Configuration +# Model: SAM ViT-B โ€” balanced speed/quality trade-off + +model: + type: "vit_b" + checkpoint: "sam_vit_b_01ec64.pth" + +# Auto-segmentation parameters +auto: + points_per_side: 32 + pred_iou_thresh: 0.86 + stability_score_thresh: 0.92 + min_mask_region_area: 1000 + +# Performance tuning (per-device) +cuda: + points_per_batch: 64 + use_fp16: true + +mps: + points_per_batch: 16 + use_fp16: false + +cpu: + points_per_batch: 16 + use_fp16: false diff --git a/src/background_removal/inference/__init__.py b/src/background_removal/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae856e13f62948e3f762196d58ee488545fe468b --- /dev/null +++ b/src/background_removal/inference/__init__.py @@ -0,0 +1 @@ +# Inference subpackage diff --git a/src/background_removal/inference/engine.py b/src/background_removal/inference/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..34e69795714e3ef177d32642600dc7edc69a1b0f --- /dev/null +++ b/src/background_removal/inference/engine.py @@ -0,0 +1,192 @@ +""" +BackgroundRemovalEngine โ€” Production-grade background removal using BiRefNet. + +Uses the official BiRefNet inference pipeline: + 1. BiRefNet โ†’ high-quality soft probability mask + 2. Refinement โ†’ small-island removal + edge smoothing + 3. Compositing โ†’ RGBA with transparent background + edge defringe +""" +import numpy as np +import cv2 +import time +import logging +import sys +import os + +_BG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if _BG_DIR not in sys.path: + sys.path.insert(0, _BG_DIR) + +from bg_pipeline.salient_detection import SalientDetector + +logger = logging.getLogger(__name__) + + +class BackgroundRemovalEngine: + """ + Production-grade background removal engine using BiRefNet. + + Usage: + engine = BackgroundRemovalEngine() + result = engine.run(image_rgb) + rgba = result["rgba"] + """ + + def __init__(self, load_sam: bool = False): + self.salient_detector = SalientDetector() + self._loaded = False + + def load(self): + """Load models into VRAM.""" + logger.info("Loading Background Removal Engine...") + start = time.time() + self.salient_detector.load() + load_time = time.time() - start + logger.info(f"Engine loaded in {load_time:.1f}s") + self._loaded = True + + def ensure_loaded(self): + if not self._loaded: + self.load() + + def _refine_mask(self, mask: np.ndarray) -> np.ndarray: + """ + Refine BiRefNet's soft mask into a clean alpha matte. + + Steps: + 1. Threshold sharpening โ€” push uncertain pixels toward 0/1 + 2. Small island removal (foreground noise) + 3. Small hole filling (background holes in foreground) + 4. Gaussian edge smoothing + """ + alpha = mask.copy().astype(np.float32) + + # 1. Threshold sharpen โ€” clean up boundary uncertainty + # Pixels > 0.5 are foreground, < 0.5 are background + strength = 8.0 + x = strength * (alpha - 0.5) + alpha = 1.0 / (1.0 + np.exp(-x)) + + # CRITICAL FIX: The sigmoid function never reaches true 0.0 or 1.0. + # This meant the background hovered around ~2% opacity causing dirty patches! + # We must clamp definite background and foreground to exact absolute values. + alpha[alpha < 0.05] = 0.0 + alpha[alpha > 0.95] = 1.0 + + alpha = alpha.astype(np.float32) + + # 2. Remove small foreground islands (noise) + binary_fg = (alpha > 0.5).astype(np.uint8) + min_area = max(200, int(mask.shape[0] * mask.shape[1] * 0.001)) + num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(binary_fg, connectivity=8) + for i in range(1, num_labels): + if stats[i, cv2.CC_STAT_AREA] < min_area: + alpha[labels == i] = 0.0 + + # 3. Fill small background holes inside foreground + binary_bg = (alpha <= 0.5).astype(np.uint8) + num_labels_bg, labels_bg, stats_bg, _ = cv2.connectedComponentsWithStats(binary_bg, connectivity=8) + for i in range(1, num_labels_bg): + if stats_bg[i, cv2.CC_STAT_AREA] < min_area: + alpha[labels_bg == i] = 1.0 + + # 4. Subtle edge smoothing + smoothed = cv2.GaussianBlur(alpha, (5, 5), 0.8) + edge_zone = (alpha > 0.05) & (alpha < 0.95) + alpha[edge_zone] = smoothed[edge_zone] + + return np.clip(alpha, 0.0, 1.0).astype(np.float32) + + def _defringe(self, image_rgb: np.ndarray, alpha: np.ndarray) -> np.ndarray: + """ + Remove background color bleed from semi-transparent edges. + This prevents halos around the subject. + """ + result = image_rgb.copy().astype(np.float32) + edge_mask = (alpha > 0.02) & (alpha < 0.95) + + if edge_mask.sum() == 0: + return result.astype(np.uint8) + + # Estimate background color from definite background pixels + bg_mask = alpha < 0.05 + if bg_mask.sum() > 50: + bg_color = np.median(result[bg_mask], axis=0) + else: + # Fallback: use image border pixels + border = np.concatenate([ + result[0, :], result[-1, :], result[:, 0], result[:, -1] + ]) + bg_color = np.median(border, axis=0) + + # Unpremultiply: remove background color contribution from edge pixels + for c in range(3): + a = np.clip(alpha, 0.01, 1.0) + defringed = (result[:, :, c] - bg_color[c] * (1.0 - a)) / a + result[:, :, c] = np.where(edge_mask, np.clip(defringed, 0, 255), result[:, :, c]) + + return np.clip(result, 0, 255).astype(np.uint8) + + def _composite_rgba(self, image_rgb: np.ndarray, alpha: np.ndarray) -> np.ndarray: + """Create final RGBA output with transparent background.""" + defringed = self._defringe(image_rgb, alpha) + alpha_uint8 = (alpha * 255).astype(np.uint8) + rgba = np.dstack([defringed, alpha_uint8]) + return rgba + + def run(self, image_rgb: np.ndarray, force_mode: str = None) -> dict: + """ + Run background removal on an RGB image. + + Args: + image_rgb: Input image (H, W, 3) uint8 RGB + force_mode: Ignored (kept for API compatibility) + + Returns: + dict with "rgba", "alpha", "soft_mask", "scene_type", "metrics" + """ + self.ensure_loaded() + total_start = time.time() + metrics = {} + h, w = image_rgb.shape[:2] + + # Stage 1: BiRefNet salient object detection โ†’ soft mask [0.0, 1.0] + soft_mask, birefnet_ms = self.salient_detector.predict(image_rgb) + metrics["stage2_birefnet_ms"] = birefnet_ms + + logger.info( + f"BiRefNet mask stats: min={soft_mask.min():.3f}, max={soft_mask.max():.3f}, " + f"mean={soft_mask.mean():.3f}, shape={soft_mask.shape}" + ) + + # Stage 2: Refine mask โ†’ clean alpha + refine_start = time.time() + alpha = self._refine_mask(soft_mask) + metrics["stage4_matting_ms"] = (time.time() - refine_start) * 1000 + metrics["stage3_routing_ms"] = 0.0 + metrics["stage3b_sam_ms"] = 0.0 + + # Stage 3: Composite RGBA + composite_start = time.time() + rgba = self._composite_rgba(image_rgb, alpha) + metrics["stage5_postprocess_ms"] = (time.time() - composite_start) * 1000 + + total_ms = (time.time() - total_start) * 1000 + metrics["total_ms"] = total_ms + + logger.info(f"Background removal complete: {total_ms:.0f}ms ({h}x{w})") + + return { + "rgba": rgba, + "alpha": alpha, + "soft_mask": soft_mask, + "scene_type": "BIREFNET", + "scene_details": {}, + "metrics": metrics, + } + + def run_simple(self, image_rgb: np.ndarray) -> dict: + return self.run(image_rgb) + + def run_complex(self, image_rgb: np.ndarray) -> dict: + return self.run(image_rgb) diff --git a/src/background_removal/utils/__init__.py b/src/background_removal/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af16d1b7cdd9f1201e8619b9a7f3eb9c8fa88cc3 --- /dev/null +++ b/src/background_removal/utils/__init__.py @@ -0,0 +1 @@ +# Background removal utilities diff --git a/src/background_removal/utils/image_utils.py b/src/background_removal/utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9f8c5a54417f0cfe5a4e4a1e95053d1dac6d7fc2 --- /dev/null +++ b/src/background_removal/utils/image_utils.py @@ -0,0 +1,57 @@ +""" +Image I/O utilities for the background removal pipeline. +Supports HEIC, PNG, JPG, WEBP input formats. +""" +import numpy as np +import cv2 +from PIL import Image +import io +import logging + +logger = logging.getLogger(__name__) + + +def load_image(path: str) -> np.ndarray: + """ + Load an image from file path. Supports HEIC, PNG, JPG, WEBP. + + Returns: + RGB numpy array (H, W, 3) uint8 + """ + # Try HEIC support + if path.lower().endswith((".heic", ".heif")): + try: + import pillow_heif + pillow_heif.register_heif_opener() + except ImportError: + raise ImportError("Install pillow-heif for HEIC support: pip install pillow-heif") + + img = Image.open(path).convert("RGB") + return np.array(img) + + +def load_image_from_bytes(image_bytes: bytes) -> np.ndarray: + """Load an image from bytes. Returns RGB numpy array.""" + nparr = np.frombuffer(image_bytes, np.uint8) + image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR) + if image_bgr is None: + raise ValueError("Could not decode image bytes.") + return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + + +def save_rgba_png(image_rgba: np.ndarray, path: str): + """Save an RGBA image as PNG with transparency.""" + img = Image.fromarray(image_rgba, "RGBA") + img.save(path, "PNG") + logger.info(f"Saved RGBA PNG: {path}") + + +def resize_for_display(image: np.ndarray, max_size: int = 1024) -> np.ndarray: + """Resize an image for display purposes.""" + h, w = image.shape[:2] + if max(h, w) <= max_size: + return image + scale = max_size / max(h, w) + new_w = int(w * scale) + new_h = int(h * scale) + return cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) diff --git a/src/background_removal/utils/mask_utils.py b/src/background_removal/utils/mask_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6569f2af404989c97db102d2dd3efce59eba1d4a --- /dev/null +++ b/src/background_removal/utils/mask_utils.py @@ -0,0 +1,43 @@ +""" +Mask utilities โ€” morphological refinement, hole fill, island removal. +""" +import numpy as np +import cv2 + + +def morphological_refine(mask: np.ndarray, kernel_size: int = 5, iterations: int = 1) -> np.ndarray: + """Apply morphological closing then opening to clean a binary mask.""" + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) + cleaned = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, kernel, iterations=iterations) + cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_OPEN, kernel, iterations=iterations) + return cleaned.astype(np.float32) + + +def fill_holes(mask: np.ndarray) -> np.ndarray: + """Fill holes in a binary mask using flood fill.""" + binary = (mask > 0.5).astype(np.uint8) + h, w = binary.shape + flood = binary.copy() + flood_mask = np.zeros((h + 2, w + 2), np.uint8) + cv2.floodFill(flood, flood_mask, (0, 0), 1) + filled = binary | (~flood.astype(bool)).astype(np.uint8) + return filled.astype(np.float32) + + +def remove_small_components(mask: np.ndarray, min_area: int = 100) -> np.ndarray: + """Remove connected components smaller than min_area.""" + binary = (mask > 0.5).astype(np.uint8) + num_components, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8) + + cleaned = np.zeros_like(binary) + for i in range(1, num_components): + if stats[i, cv2.CC_STAT_AREA] >= min_area: + cleaned[labels == i] = 1 + + return cleaned.astype(np.float32) + + +def smooth_edges(mask: np.ndarray, blur_size: int = 5) -> np.ndarray: + """Smooth mask edges with Gaussian blur.""" + smoothed = cv2.GaussianBlur(mask.astype(np.float32), (blur_size, blur_size), 0) + return smoothed diff --git a/src/background_removal/utils/trimap.py b/src/background_removal/utils/trimap.py new file mode 100644 index 0000000000000000000000000000000000000000..a35177601859b663e442b4b3cf93d1c4454405c0 --- /dev/null +++ b/src/background_removal/utils/trimap.py @@ -0,0 +1,61 @@ +""" +Trimap generation โ€” erode/dilate to create FG/BG/Unknown zones. +""" +import numpy as np +import cv2 + + +def generate_trimap(mask: np.ndarray, erode_size: int = 10, dilate_size: int = 20) -> np.ndarray: + """ + Generate a trimap from a binary/soft mask. + + Trimap values: + 0 = Definite Background + 128 = Unknown (edge zone) + 255 = Definite Foreground + + Args: + mask: Input mask [H, W] in [0.0, 1.0] or uint8 + erode_size: Kernel size for erosion (shrink foreground โ†’ definite FG) + dilate_size: Kernel size for dilation (expand foreground โ†’ include edges) + + Returns: + Trimap (H, W) uint8 with values {0, 128, 255} + """ + # Convert to binary uint8 + if mask.dtype == np.float32 or mask.dtype == np.float64: + binary = (mask > 0.5).astype(np.uint8) * 255 + else: + binary = mask.copy() + + # Erode โ†’ definite foreground + erode_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (erode_size, erode_size)) + fg = cv2.erode(binary, erode_kernel) + + # Dilate โ†’ extend beyond edges + dilate_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (dilate_size, dilate_size)) + expanded = cv2.dilate(binary, dilate_kernel) + + # Build trimap + trimap = np.zeros_like(binary, dtype=np.uint8) + trimap[expanded > 0] = 128 # Unknown (expanded region) + trimap[fg > 0] = 255 # Definite foreground (eroded inner) + + return trimap + + +def soft_trimap_from_confidence(confidence_map: np.ndarray, + fg_thresh: float = 0.92, + bg_thresh: float = 0.08) -> dict: + """ + Build a soft trimap directly from BiRefNet's confidence map. + No morphological operations โ€” pure threshold-based. + + Returns: + dict with 'foreground', 'background', 'uncertain' boolean arrays + """ + return { + "foreground": confidence_map >= fg_thresh, + "background": confidence_map <= bg_thresh, + "uncertain": (confidence_map > bg_thresh) & (confidence_map < fg_thresh), + } diff --git a/src/background_removal/utils/visualization.py b/src/background_removal/utils/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7b297d413d5f628e8b93238e7606d71e08f33d --- /dev/null +++ b/src/background_removal/utils/visualization.py @@ -0,0 +1,80 @@ +""" +Debug visualization utilities โ€” overlay mask, show trimap. +""" +import numpy as np +import cv2 + + +def overlay_mask(image_rgb: np.ndarray, mask: np.ndarray, + color: tuple = (0, 255, 0), alpha: float = 0.4) -> np.ndarray: + """ + Overlay a mask on the image with a colored tint. + + Args: + image_rgb: Input image (H, W, 3) uint8 + mask: Mask [H, W] in [0.0, 1.0] or bool + color: RGB color for the overlay + alpha: Transparency of the overlay + + Returns: + Image with mask overlay (H, W, 3) uint8 + """ + overlay = image_rgb.copy() + mask_bool = mask > 0.5 if mask.dtype in [np.float32, np.float64] else mask.astype(bool) + + colored = np.zeros_like(image_rgb) + colored[:] = color + + overlay[mask_bool] = cv2.addWeighted( + overlay[mask_bool], 1 - alpha, + colored[mask_bool], alpha, 0, + ) + return overlay + + +def visualize_trimap(trimap: np.ndarray) -> np.ndarray: + """ + Visualize a trimap as a colored image. + FG = Green, BG = Red, Unknown = Yellow + + Args: + trimap: Trimap (H, W) uint8 with values {0, 128, 255} + + Returns: + Colored visualization (H, W, 3) uint8 + """ + vis = np.zeros((*trimap.shape, 3), dtype=np.uint8) + vis[trimap == 0] = [200, 50, 50] # BG โ†’ Red + vis[trimap == 128] = [255, 255, 50] # Unknown โ†’ Yellow + vis[trimap == 255] = [50, 200, 50] # FG โ†’ Green + return vis + + +def show_alpha_checkerboard(image_rgba: np.ndarray, check_size: int = 16) -> np.ndarray: + """ + Create a checkerboard background for RGBA preview. + + Args: + image_rgba: RGBA image (H, W, 4) uint8 + check_size: Size of checkerboard squares + + Returns: + RGB preview image (H, W, 3) uint8 + """ + h, w = image_rgba.shape[:2] + + # Create checkerboard + checker = np.zeros((h, w, 3), dtype=np.uint8) + for y in range(0, h, check_size): + for x in range(0, w, check_size): + if ((y // check_size) + (x // check_size)) % 2 == 0: + checker[y:y+check_size, x:x+check_size] = [240, 240, 240] + else: + checker[y:y+check_size, x:x+check_size] = [200, 200, 200] + + # Composite + alpha = image_rgba[:, :, 3:4].astype(np.float32) / 255.0 + rgb = image_rgba[:, :, :3].astype(np.float32) + result = rgb * alpha + checker.astype(np.float32) * (1.0 - alpha) + + return result.astype(np.uint8) diff --git a/src/hybrid_color_correction/app/__init__.py b/src/hybrid_color_correction/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e78f39e54bc0ebcb22c60980a8112d9abf7cc704 --- /dev/null +++ b/src/hybrid_color_correction/app/__init__.py @@ -0,0 +1 @@ +# App subpackage diff --git a/src/hybrid_color_correction/app/streamlit_app.py b/src/hybrid_color_correction/app/streamlit_app.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5720fe3fe3a184b24e366fbf6c36b5274538a1 --- /dev/null +++ b/src/hybrid_color_correction/app/streamlit_app.py @@ -0,0 +1,69 @@ +import streamlit as st +import os +import sys +import torch +import cv2 +import numpy as np + +# Ensure parent directory is in path +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from pipeline.enhance import HybridEnhancer +from pipeline.preprocess import preprocess_image +from pipeline.postprocess import postprocess_tensor +from utils.image_utils import bytes_to_image + +# Page config +st.set_page_config(page_title="AI Hybrid Color Correction", layout="wide") +st.title("๐ŸŒŸ AI Hybrid Color Correction System") +st.caption("Powered by Pretrained Zero-DCE++ (Exposure) & Restormer (Details) | Optimized for Mid-Range GPUs") + +# Initialize models +@st.cache_resource +def load_enhancer(): + device = "cuda" if torch.cuda.is_available() else "cpu" + return HybridEnhancer(device=device) + +enhancer = load_enhancer() + +# Sidebar options +st.sidebar.header("Settings") +use_restormer = st.sidebar.checkbox("Enable Restormer (Detail Refinement)", value=True, help="Refines details and removes noise, but requires more VRAM and compute time.") + +# Main UI +uploaded_file = st.file_uploader("Upload an Image (JPG, PNG)", type=["jpg", "jpeg", "png"]) + +if uploaded_file is not None: + # Convert uploaded file to numpy array + img_rgb = bytes_to_image(uploaded_file.read()) + + st.write(f"**Original Size:** {img_rgb.shape[1]}x{img_rgb.shape[0]}") + + if st.button("Enhance Image ๐Ÿš€", use_container_width=True): + with st.spinner("Processing... Please wait."): + # 1. Preprocess + tensor = preprocess_image(img_rgb, max_size=512) + + # 2. Enhance + out_tensor = enhancer.enhance(tensor, use_restormer=use_restormer) + + # 3. Postprocess + out_rgb = postprocess_tensor(out_tensor) + + # Display side-by-side + col1, col2 = st.columns(2) + with col1: + st.image(img_rgb, caption="Original Image", use_column_width=True) + with col2: + st.image(out_rgb, caption="Enhanced Image", use_column_width=True) + + # Download button + st.success("Enhancement Complete!") + is_success, buffer = cv2.imencode(".png", cv2.cvtColor(out_rgb, cv2.COLOR_RGB2BGR)) + if is_success: + st.download_button( + label="๐Ÿ“ฅ Download Enhanced Image", + data=buffer.tobytes(), + file_name="enhanced_image.png", + mime="image/png", + use_container_width=True + ) diff --git a/src/hybrid_color_correction/hc_models/__init__.py b/src/hybrid_color_correction/hc_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1fea6220a21a4e402daa7c9e1e9137b5009b88ec --- /dev/null +++ b/src/hybrid_color_correction/hc_models/__init__.py @@ -0,0 +1 @@ +# Models subpackage diff --git a/src/hybrid_color_correction/hc_models/restormer/__init__.py b/src/hybrid_color_correction/hc_models/restormer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b44277336f4693b46b1989153ff78918e84d887 --- /dev/null +++ b/src/hybrid_color_correction/hc_models/restormer/__init__.py @@ -0,0 +1,2 @@ +from .model import load_restormer_model +from .restormer_arch import Restormer diff --git a/src/hybrid_color_correction/hc_models/restormer/model.py b/src/hybrid_color_correction/hc_models/restormer/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5085ac1b05a26b63de4d647c8c8c3e1ab43b59 --- /dev/null +++ b/src/hybrid_color_correction/hc_models/restormer/model.py @@ -0,0 +1,44 @@ +import os +import torch +import urllib.request +from .restormer_arch import Restormer + +DEFAULT_WEIGHTS = os.path.join(os.path.dirname(__file__), '../../weights/restormer_real_denoising.pth') + +def load_restormer_model(device="cuda", weights_path=DEFAULT_WEIGHTS): + """Loads the Restormer model and downloads weights if missing.""" + model = Restormer( + inp_channels=3, + out_channels=3, + dim=48, + num_blocks=[4,6,6,8], + num_refinement_blocks=4, + heads=[1,2,4,8], + ffn_expansion_factor=2.66, + bias=False, + LayerNorm_type='BiasFree' + ) + + os.makedirs(os.path.dirname(weights_path), exist_ok=True) + + if not os.path.exists(weights_path): + print(f"[Restormer] Downloading weights to {weights_path}...") + url = "https://github.com/swz30/Restormer/releases/download/v1.0/real_denoising.pth" + try: + req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) + with urllib.request.urlopen(req) as response, open(weights_path, 'wb') as out_file: + out_file.write(response.read()) + print("[Restormer] Pretrained weights downloaded successfully!") + except Exception as e: + print(f"[Restormer] Failed to download weights: {e}") + print(f"[Restormer] Please download 'real_denoising.pth' manually to {weights_path}") + + if os.path.exists(weights_path): + state_dict = torch.load(weights_path, map_location="cpu") + if "params" in state_dict: + state_dict = state_dict["params"] + model.load_state_dict(state_dict, strict=True) + + model = model.to(device) + model.eval() + return model diff --git a/src/hybrid_color_correction/hc_models/restormer/restormer_arch.py b/src/hybrid_color_correction/hc_models/restormer/restormer_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..f0289099019683c160497f6a298847979f32c4ac --- /dev/null +++ b/src/hybrid_color_correction/hc_models/restormer/restormer_arch.py @@ -0,0 +1,213 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numbers +from einops import rearrange + +def to_3d(x): + return rearrange(x, 'b c h w -> b (h w) c') + +def to_4d(x,h,w): + return rearrange(x, 'b (h w) c -> b c h w',h=h,w=w) + +class BiasFree_LayerNorm(nn.Module): + def __init__(self, normalized_shape): + super(BiasFree_LayerNorm, self).__init__() + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = (normalized_shape,) + normalized_shape = torch.Size(normalized_shape) + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.normalized_shape = normalized_shape + + def forward(self, x): + sigma = x.var(-1, keepdim=True, unbiased=False) + return x / torch.sqrt(sigma+1e-5) * self.weight + +class WithBias_LayerNorm(nn.Module): + def __init__(self, normalized_shape): + super(WithBias_LayerNorm, self).__init__() + if isinstance(normalized_shape, numbers.Integral): + normalized_shape = (normalized_shape,) + normalized_shape = torch.Size(normalized_shape) + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.bias = nn.Parameter(torch.zeros(normalized_shape)) + self.normalized_shape = normalized_shape + + def forward(self, x): + mu = x.mean(-1, keepdim=True) + sigma = x.var(-1, keepdim=True, unbiased=False) + return (x - mu) / torch.sqrt(sigma+1e-5) * self.weight + self.bias + +class LayerNorm(nn.Module): + def __init__(self, dim, LayerNorm_type): + super(LayerNorm, self).__init__() + if LayerNorm_type =='BiasFree': + self.body = BiasFree_LayerNorm(dim) + else: + self.body = WithBias_LayerNorm(dim) + + def forward(self, x): + h, w = x.shape[-2:] + return to_4d(self.body(to_3d(x)), h, w) + +# -------------------------------------------------------------------------------- +# Gated-Dconv Feed-Forward Network (GDFN) +class FeedForward(nn.Module): + def __init__(self, dim, ffn_expansion_factor, bias): + super(FeedForward, self).__init__() + hidden_features = int(dim*ffn_expansion_factor) + self.project_in = nn.Conv2d(dim, hidden_features*2, kernel_size=1, bias=bias) + self.dwconv = nn.Conv2d(hidden_features*2, hidden_features*2, kernel_size=3, stride=1, padding=1, groups=hidden_features*2, bias=bias) + self.project_out = nn.Conv2d(hidden_features, dim, kernel_size=1, bias=bias) + def forward(self, x): + x = self.project_in(x) + x1, x2 = self.dwconv(x).chunk(2, dim=1) + x = F.gelu(x1) * x2 + x = self.project_out(x) + return x + +# -------------------------------------------------------------------------------- +# Multi-Dconv Head Transposed Self-Attention (MDTA) +class Attention(nn.Module): + def __init__(self, dim, num_heads, bias): + super(Attention, self).__init__() + self.num_heads = num_heads + self.temperature = nn.Parameter(torch.ones(num_heads, 1, 1)) + + self.qkv = nn.Conv2d(dim, dim*3, kernel_size=1, bias=bias) + self.qkv_dwconv = nn.Conv2d(dim*3, dim*3, kernel_size=3, stride=1, padding=1, groups=dim*3, bias=bias) + self.project_out = nn.Conv2d(dim, dim, kernel_size=1, bias=bias) + + def forward(self, x): + b,c,h,w = x.shape + qkv = self.qkv_dwconv(self.qkv(x)) + q,k,v = qkv.chunk(3, dim=1) + + q = rearrange(q, 'b (head c) h w -> b head c (h w)', head=self.num_heads) + k = rearrange(k, 'b (head c) h w -> b head c (h w)', head=self.num_heads) + v = rearrange(v, 'b (head c) h w -> b head c (h w)', head=self.num_heads) + + q = torch.nn.functional.normalize(q, dim=-1) + k = torch.nn.functional.normalize(k, dim=-1) + + attn = (q @ k.transpose(-2, -1)) * self.temperature + attn = attn.softmax(dim=-1) + + out = (attn @ v) + + out = rearrange(out, 'b head c (h w) -> b (head c) h w', head=self.num_heads, h=h, w=w) + out = self.project_out(out) + return out + +# -------------------------------------------------------------------------------- +# Transformer Block +class TransformerBlock(nn.Module): + def __init__(self, dim, num_heads, ffn_expansion_factor, bias, LayerNorm_type): + super(TransformerBlock, self).__init__() + self.norm1 = LayerNorm(dim, LayerNorm_type) + self.attn = Attention(dim, num_heads, bias) + self.norm2 = LayerNorm(dim, LayerNorm_type) + self.ffn = FeedForward(dim, ffn_expansion_factor, bias) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.ffn(self.norm2(x)) + return x + +# Overlapping Image Patch Embedding +class OverlapPatchEmbed(nn.Module): + def __init__(self, in_c=3, embed_dim=48, bias=False): + super(OverlapPatchEmbed, self).__init__() + self.proj = nn.Conv2d(in_c, embed_dim, kernel_size=3, stride=1, padding=1, bias=bias) + def forward(self, x): + x = self.proj(x) + return x + +# Downsample +class Downsample(nn.Module): + def __init__(self, n_feat): + super(Downsample, self).__init__() + self.body = nn.Sequential(nn.Conv2d(n_feat, n_feat//2, kernel_size=3, stride=1, padding=1, bias=False), + nn.PixelUnshuffle(2)) + def forward(self, x): + return self.body(x) + +# Upsample +class Upsample(nn.Module): + def __init__(self, n_feat): + super(Upsample, self).__init__() + self.body = nn.Sequential(nn.Conv2d(n_feat, n_feat*2, kernel_size=3, stride=1, padding=1, bias=False), + nn.PixelShuffle(2)) + def forward(self, x): + return self.body(x) + +# Main Restormer Model +class Restormer(nn.Module): + def __init__(self, + inp_channels=3, + out_channels=3, + dim=48, + num_blocks=[4,6,6,8], + num_refinement_blocks=4, + heads=[1,2,4,8], + ffn_expansion_factor=2.66, + bias=False, + LayerNorm_type='WithBias'): + + super(Restormer, self).__init__() + + self.patch_embed = OverlapPatchEmbed(inp_channels, dim) + + self.encoder_level1 = nn.Sequential(*[TransformerBlock(dim=dim, num_heads=heads[0], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[0])]) + self.down1_2 = Downsample(dim) + self.encoder_level2 = nn.Sequential(*[TransformerBlock(dim=int(dim*2**1), num_heads=heads[1], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[1])]) + self.down2_3 = Downsample(int(dim*2**1)) + self.encoder_level3 = nn.Sequential(*[TransformerBlock(dim=int(dim*2**2), num_heads=heads[2], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[2])]) + self.down3_4 = Downsample(int(dim*2**2)) + self.latent = nn.Sequential(*[TransformerBlock(dim=int(dim*2**3), num_heads=heads[3], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[3])]) + + self.up4_3 = Upsample(int(dim*2**3)) + self.reduce_chan_level3 = nn.Conv2d(int(dim*2**3), int(dim*2**2), kernel_size=1, bias=bias) + self.decoder_level3 = nn.Sequential(*[TransformerBlock(dim=int(dim*2**2), num_heads=heads[2], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[2])]) + + self.up3_2 = Upsample(int(dim*2**2)) + self.reduce_chan_level2 = nn.Conv2d(int(dim*2**2), int(dim*2**1), kernel_size=1, bias=bias) + self.decoder_level2 = nn.Sequential(*[TransformerBlock(dim=int(dim*2**1), num_heads=heads[1], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[1])]) + + self.up2_1 = Upsample(int(dim*2**1)) + self.decoder_level1 = nn.Sequential(*[TransformerBlock(dim=int(dim*2**1), num_heads=heads[0], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_blocks[0])]) + + self.refinement = nn.Sequential(*[TransformerBlock(dim=int(dim*2**1), num_heads=heads[0], ffn_expansion_factor=ffn_expansion_factor, bias=bias, LayerNorm_type=LayerNorm_type) for i in range(num_refinement_blocks)]) + self.output = nn.Conv2d(int(dim*2**1), out_channels, kernel_size=3, stride=1, padding=1, bias=bias) + + def forward(self, inp_img): + inp_enc_level1 = self.patch_embed(inp_img) + out_enc_level1 = self.encoder_level1(inp_enc_level1) + + inp_enc_level2 = self.down1_2(out_enc_level1) + out_enc_level2 = self.encoder_level2(inp_enc_level2) + + inp_enc_level3 = self.down2_3(out_enc_level2) + out_enc_level3 = self.encoder_level3(inp_enc_level3) + + inp_enc_level4 = self.down3_4(out_enc_level3) + out_enc_level4 = self.latent(inp_enc_level4) + + out_dec_level3 = self.up4_3(out_enc_level4) + inp_dec_level3 = torch.cat([out_dec_level3, out_enc_level3], 1) + inp_dec_level3 = self.reduce_chan_level3(inp_dec_level3) + out_dec_level3 = self.decoder_level3(inp_dec_level3) + + out_dec_level2 = self.up3_2(out_dec_level3) + inp_dec_level2 = torch.cat([out_dec_level2, out_enc_level2], 1) + inp_dec_level2 = self.reduce_chan_level2(inp_dec_level2) + out_dec_level2 = self.decoder_level2(inp_dec_level2) + + out_dec_level1 = self.up2_1(out_dec_level2) + inp_dec_level1 = torch.cat([out_dec_level1, out_enc_level1], 1) + out_dec_level1 = self.decoder_level1(inp_dec_level1) + + out_dec_level1 = self.refinement(out_dec_level1) + + out_img = self.output(out_dec_level1) + inp_img + return out_img diff --git a/src/hybrid_color_correction/hc_models/zero_dce/__init__.py b/src/hybrid_color_correction/hc_models/zero_dce/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f1f1a6825ce8f712ffa8a87bb8e48e9de83a89 --- /dev/null +++ b/src/hybrid_color_correction/hc_models/zero_dce/__init__.py @@ -0,0 +1,2 @@ +# Re-export models for simpler imports +from .model import load_zero_dce_model, ZeroDCEPlusPlus diff --git a/src/hybrid_color_correction/hc_models/zero_dce/model.py b/src/hybrid_color_correction/hc_models/zero_dce/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2526d9254184da421ebf1d65d9fab9240f361a70 --- /dev/null +++ b/src/hybrid_color_correction/hc_models/zero_dce/model.py @@ -0,0 +1,107 @@ +import os +import torch +import torch.nn as nn +import torch.nn.functional as F +import urllib.request + +class DSConv(nn.Module): + def __init__(self, in_ch, out_ch): + super(DSConv, self).__init__() + self.depth_conv = nn.Conv2d( + in_channels=in_ch, + out_channels=in_ch, + kernel_size=3, + stride=1, + padding=1, + groups=in_ch + ) + self.point_conv = nn.Conv2d( + in_channels=in_ch, + out_channels=out_ch, + kernel_size=1, + stride=1, + padding=0, + groups=1 + ) + + def forward(self, input_x): + out = self.depth_conv(input_x) + out = self.point_conv(out) + return out + +class ZeroDCEPlusPlus(nn.Module): + def __init__(self): + super(ZeroDCEPlusPlus, self).__init__() + self.relu = nn.ReLU(inplace=True) + number_f = 32 + + self.e_conv1 = DSConv(3, number_f) + self.e_conv2 = DSConv(number_f, number_f) + self.e_conv3 = DSConv(number_f, number_f) + self.e_conv4 = DSConv(number_f, number_f) + self.e_conv5 = DSConv(number_f * 2, number_f) + self.e_conv6 = DSConv(number_f * 2, number_f) + self.e_conv7 = DSConv(number_f * 2, 24) + + def forward(self, x): + x1 = self.relu(self.e_conv1(x)) + x2 = self.relu(self.e_conv2(x1)) + x3 = self.relu(self.e_conv3(x2)) + x4 = self.relu(self.e_conv4(x3)) + + x5 = self.relu(self.e_conv5(torch.cat([x3, x4], 1))) + x6 = self.relu(self.e_conv6(torch.cat([x2, x5], 1))) + + # Curve parameters (24 channels for 8 iterations * 3 RGB) + x_r = torch.tanh(self.e_conv7(torch.cat([x1, x6], 1))) + + r1, r2, r3, r4, r5, r6, r7, r8 = torch.split(x_r, 3, dim=1) + + # Iterative curve application + x = x + r1 * (torch.pow(x, 2) - x) + x = x + r2 * (torch.pow(x, 2) - x) + x = x + r3 * (torch.pow(x, 2) - x) + enhanced_image_1 = x + r4 * (torch.pow(x, 2) - x) + + x = enhanced_image_1 + r5 * (torch.pow(enhanced_image_1, 2) - enhanced_image_1) + x = x + r6 * (torch.pow(x, 2) - x) + x = x + r7 * (torch.pow(x, 2) - x) + enhance_image = x + r8 * (torch.pow(x, 2) - x) + + return enhance_image + +DEFAULT_WEIGHTS = os.path.join(os.path.dirname(__file__), '../../weights/ZeroDCE++.pth') + +def load_zero_dce_model(device="cuda", weights_path=DEFAULT_WEIGHTS): + """Loads the ZeroDCE++ model and downloads weights if missing.""" + model = ZeroDCEPlusPlus() + os.makedirs(os.path.dirname(weights_path), exist_ok=True) + + # Check if weights exist, otherwise download from known mirror + if not os.path.exists(weights_path): + print(f"[Zero-DCE++] Downloading weights to {weights_path}...") + url = "https://huggingface.co/IanNathaniel/Zero-DCE/resolve/main/Epoch99.pth" + try: + req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) + with urllib.request.urlopen(req) as response, open(weights_path, 'wb') as out_file: + out_file.write(response.read()) + print("[Zero-DCE++] Pretrained weights downloaded successfully!") + except Exception as e: + print(f"[Zero-DCE++] Failed to download weights: {e}") + print("[Zero-DCE++] Please place standard ZeroDCE++ weights in weights directory.") + + if os.path.exists(weights_path): + state_dict = torch.load(weights_path, map_location="cpu", weights_only=True) + # Handle state dict wrapped in another dict (common in some repos) + if hasattr(state_dict, "keys") and "state_dict" in state_dict: + state_dict = state_dict["state_dict"] + # Handle "module." prefix from DataParallel + new_state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} + try: + model.load_state_dict(new_state_dict, strict=False) + except Exception as e: + print(f"[Zero-DCE++] Warning during weight load: {e}") + + model = model.to(device) + model.eval() + return model diff --git a/src/hybrid_color_correction/hc_pipeline/__init__.py b/src/hybrid_color_correction/hc_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5027acda8484a29c172c12f2981c726d9c9347 --- /dev/null +++ b/src/hybrid_color_correction/hc_pipeline/__init__.py @@ -0,0 +1 @@ +# Pipeline subpackage diff --git a/src/hybrid_color_correction/hc_pipeline/enhance.py b/src/hybrid_color_correction/hc_pipeline/enhance.py new file mode 100644 index 0000000000000000000000000000000000000000..f741db1acf959750c22e6c06f9c0ca1098aeffeb --- /dev/null +++ b/src/hybrid_color_correction/hc_pipeline/enhance.py @@ -0,0 +1,118 @@ +import torch +import gc +import torchvision.transforms.functional as F_t +from hc_models.zero_dce import load_zero_dce_model +from hc_models.restormer import load_restormer_model + +class HybridEnhancer: + def __init__(self, device="cuda"): + self.device = device if torch.cuda.is_available() and device == "cuda" else "cpu" + print(f"[Pipeline] Initializing Hybrid Enhancer on {self.device}...") + + # Load models + self.zero_dce = load_zero_dce_model(device=self.device) + self.restormer = load_restormer_model(device=self.device) + + def detect_line_art(self, img_tensor, variance_threshold=0.05): + """ + Detect if image is grayscale/low color variance by computing std across RGB channels. + """ + std_across_channels = img_tensor.std(dim=1) # shape (1, H, W) + mean_variance = std_across_channels.mean().item() + + is_line_art = mean_variance < variance_threshold + print(f"[Pipeline] Color variance: {mean_variance:.4f} | Line-art detected: {is_line_art}") + return is_line_art + + def histogram_stretch(self, img_tensor): + """ + Normalize contrast using min-max scaling to stretch entire dynamic range. + Removes gray backgrounds natively. + """ + img_min = img_tensor.min() + img_max = img_tensor.max() + if img_max > img_min: + stretched = (img_tensor - img_min) / ((img_max - img_min) + 1e-6) + else: + stretched = img_tensor + return stretched + + def enhance_zero_dce(self, img_tensor): + """Zero-DCE++ for Exposure and Color Balance""" + return self.zero_dce(img_tensor) + + def refine_restormer(self, img_tensor): + """Restormer for Detail enhancement and Denoising""" + # Save VRAM by using mixed precision on GPU + with torch.amp.autocast(device_type="cuda", enabled=(self.device == "cuda")): + refined = self.restormer(img_tensor) + return refined + + def sharpen_edges(self, img_tensor, alpha=0.3): + """ + Enhance line clarity using Unsharp Mask (image + alpha * (image - blur(image))) + """ + blurred = F_t.gaussian_blur(img_tensor, kernel_size=[3, 3], sigma=[1.0, 1.0]) + sharpened = img_tensor + alpha * (img_tensor - blurred) + return torch.clamp(sharpened, 0.0, 1.0) + + def correct_black_white(self, img_tensor): + """ + Force true whites and true blacks by clipping very bright and very dark pixels. + """ + corrected = (img_tensor - 0.02) / (0.98 - 0.02) + return torch.clamp(corrected, 0.0, 1.0) + + @torch.no_grad() + def enhance(self, img_tensor, use_restormer=True): + """ + Runs the advanced hybrid color correction pipeline. + Args: + img_tensor: Tensor of shape (1, C, H, W) normalized [0,1] + use_restormer: Boolean to toggle Restormer refinement + Returns: + Enhanced tensor of same shape + """ + img_tensor = img_tensor.to(self.device).float() + + # 1. Line-Art Detection (SMART FEATURE) + is_line_art = self.detect_line_art(img_tensor) + + # Determine adaptive strengths + alpha_sharp = 0.5 if is_line_art else 0.2 + + # 2. Histogram Stretching (MANDATORY) + img_tensor = self.histogram_stretch(img_tensor) + + # 3. Zero-DCE++ (Exposure and Color Balance) + enhanced_tensor = self.enhance_zero_dce(img_tensor) + + # If line art, reduce color enhancement impact by blending with original after stretch + if is_line_art: + enhanced_tensor = 0.7 * enhanced_tensor + 0.3 * img_tensor + + # 4. Restormer (Detail enhancement, Denoising) + if use_restormer: + refined_tensor = self.refine_restormer(enhanced_tensor).float() + else: + refined_tensor = enhanced_tensor.float() + + # 5. Edge Sharpening (CRITICAL) + sharpened_tensor = self.sharpen_edges(refined_tensor, alpha=alpha_sharp) + + # 6. Black & White Point Correction (VERY IMPORTANT) + final_tensor = self.correct_black_white(sharpened_tensor) + + # Free memory aggressively inside process loop + if self.device == "cuda": + torch.cuda.empty_cache() + + return final_tensor + + def unload(self): + """Frees GPU memory explicitly if needed.""" + del self.zero_dce + del self.restormer + if self.device == "cuda": + torch.cuda.empty_cache() + gc.collect() diff --git a/src/hybrid_color_correction/hc_pipeline/postprocess.py b/src/hybrid_color_correction/hc_pipeline/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..271196d825af68d7de925090a49f2b8cf0c80f9a --- /dev/null +++ b/src/hybrid_color_correction/hc_pipeline/postprocess.py @@ -0,0 +1,21 @@ +import torch +import numpy as np + +def postprocess_tensor(tensor): + """ + Converts a normalized PyTorch tensor back to a uint8 NumPy array. + Applies clipping to [0, 1] before conversion to [0, 255]. + """ + # Remove batch dimension: (1, C, H, W) -> (C, H, W) + tensor = tensor.squeeze(0).cpu().float() + + # Clip values to valid range + tensor = torch.clamp(tensor, 0.0, 1.0) + + # Convert to NumPy (H, W, C) + img_np = tensor.permute(1, 2, 0).numpy() + + # Scale to 0-255 uint8 + img_uint8 = (img_np * 255.0).round().astype(np.uint8) + + return img_uint8 diff --git a/src/hybrid_color_correction/hc_pipeline/preprocess.py b/src/hybrid_color_correction/hc_pipeline/preprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..42e8754537a9d7bcdbb68f3353cd0ac69befb121 --- /dev/null +++ b/src/hybrid_color_correction/hc_pipeline/preprocess.py @@ -0,0 +1,36 @@ +import cv2 +import torch +import numpy as np + +def preprocess_image(image_np, max_size=512): + """ + Resizes image to heavily restrict max dimension to `max_size` (maintain aspect ratio) + and converts it to a normalized PyTorch tensor. + """ + h, w = image_np.shape[:2] + + # Calculate resize ratio if exceeding max size + if max(h, w) > max_size: + ratio = max_size / max(h, w) + new_w, new_h = int(w * ratio), int(h * ratio) + + # Models often require padding or dimensions divisible by 8 or 16 + # To keep it simple and safe for Restormer, we pad or ensure it's mod 8 + new_w = (new_w // 8) * 8 + new_h = (new_h // 8) * 8 + + image_np = cv2.resize(image_np, (new_w, new_h), interpolation=cv2.INTER_AREA) + else: + # Just ensure dimensions are multiples of 8 for Restormer + new_w = (w // 8) * 8 + new_h = (h // 8) * 8 + if new_w != w or new_h != h: + image_np = cv2.resize(image_np, (new_w, new_h), interpolation=cv2.INTER_AREA) + + # Normalize to [0, 1] + image_float = image_np.astype(np.float32) / 255.0 + + # Convert to Tensor, shape: (1, C, H, W) + image_tensor = torch.from_numpy(image_float).permute(2, 0, 1).unsqueeze(0) + + return image_tensor diff --git a/src/hybrid_color_correction/main.py b/src/hybrid_color_correction/main.py new file mode 100644 index 0000000000000000000000000000000000000000..55875eb6852871628f05b0ccaff2461dbf214cd8 --- /dev/null +++ b/src/hybrid_color_correction/main.py @@ -0,0 +1,62 @@ +import os +import argparse +from glob import glob +from utils.image_utils import load_image, save_image +from pipeline.preprocess import preprocess_image +from pipeline.enhance import HybridEnhancer +from pipeline.postprocess import postprocess_tensor + +def process_image(enhancer, input_path, output_path, use_restormer): + print(f"Processing: {input_path}") + + # 1. Load and Preprocess (Max 512px) + img_np = load_image(input_path) + img_tensor = preprocess_image(img_np, max_size=512) + + # 2. Enhance + output_tensor = enhancer.enhance(img_tensor, use_restormer=use_restormer) + + # 3. Postprocess and Save + out_np = postprocess_tensor(output_tensor) + save_image(out_np, output_path) + print(f"Saved to: {output_path}") + +def main(): + parser = argparse.ArgumentParser(description="Hybrid Auto Color Correction Pipeline") + parser.add_argument("-i", "--input", type=str, required=True, help="Input image or directory") + parser.add_argument("-o", "--output", type=str, default="outputs", help="Output directory") + parser.add_argument("--disable-restormer", action="store_true", help="Disable Restormer refinement (faster, less VRAM)") + parser.add_argument("--device", type=str, default="cuda", choices=["cuda", "cpu"]) + args = parser.parse_args() + + # Setup + os.makedirs(args.output, exist_ok=True) + use_restormer = not args.disable_restormer + + # Load Enhancer + enhancer = HybridEnhancer(device=args.device) + + if os.path.isfile(args.input): + filename = os.path.basename(args.input) + out_path = os.path.join(args.output, f"enhanced_{filename}") + process_image(enhancer, args.input, out_path, use_restormer) + elif os.path.isdir(args.input): + extensions = ["*.jpg", "*.jpeg", "*.png", "*.bmp"] + image_files = [] + for ext in extensions: + image_files.extend(glob(os.path.join(args.input, ext))) + image_files.extend(glob(os.path.join(args.input, ext.upper()))) + + print(f"Found {len(image_files)} images in directory.") + for img_path in image_files: + filename = os.path.basename(img_path) + out_path = os.path.join(args.output, f"enhanced_{filename}") + try: + process_image(enhancer, img_path, out_path, use_restormer) + except Exception as e: + print(f"Failed processing {img_path}: {e}") + else: + print(f"Input path {args.input} does not exist.") + +if __name__ == "__main__": + main() diff --git a/src/hybrid_color_correction/requirements.txt b/src/hybrid_color_correction/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f592f6e497be6552cba879c0628e6baa1cc11ea2 --- /dev/null +++ b/src/hybrid_color_correction/requirements.txt @@ -0,0 +1,7 @@ +torch>=2.0.0 +torchvision>=0.15.0 +opencv-python>=4.8.0 +Pillow>=9.5.0 +streamlit>=1.28.0 +einops>=0.7.0 +numpy>=1.24.0 diff --git a/src/hybrid_color_correction/utils/__init__.py b/src/hybrid_color_correction/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5878af70d17842d495284aae604ae8f5da3468 --- /dev/null +++ b/src/hybrid_color_correction/utils/__init__.py @@ -0,0 +1 @@ +# Utils subpackage diff --git a/src/hybrid_color_correction/utils/image_utils.py b/src/hybrid_color_correction/utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..affb5772e1505b5cf8a9d879bf9186969ee3889f --- /dev/null +++ b/src/hybrid_color_correction/utils/image_utils.py @@ -0,0 +1,26 @@ +import cv2 +import numpy as np +import os +from PIL import Image + +def load_image(image_path): + """Loads an image via OpenCV and converts it to RGB.""" + if not os.path.exists(image_path): + raise FileNotFoundError(f"Image not found at {image_path}") + image = cv2.imread(image_path) + if image is None: + raise ValueError(f"Failed to load image at {image_path}") + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + return image + +def save_image(image_rgb, output_path): + """Saves an RGB NumPy array as an image.""" + os.makedirs(os.path.dirname(output_path), exist_ok=True) + image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(output_path, image_bgr) + +def bytes_to_image(image_bytes): + """Converts uploaded bytes (Streamlit) to a NumPy RGB array.""" + nparr = np.frombuffer(image_bytes, np.uint8) + image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR) + return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) diff --git a/src/object_removal_ai/README.md b/src/object_removal_ai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55ce469ba9074b82a6d86d0828ac88b64d705482 --- /dev/null +++ b/src/object_removal_ai/README.md @@ -0,0 +1,105 @@ +# AI Object Removal Pipeline + +Production-quality object removal system powered by **GroundingDINO** (zero-shot detection), **MobileSAM** (segmentation), and **LaMa** (inpainting). + +## Features + +- ๐ŸŽฏ **Text-guided removal** โ€” Describe what to remove ("person", "car", "deer") +- ๐Ÿ–Œ๏ธ **Mask-based removal** โ€” Provide your own binary mask +- ๐ŸŒ **FastAPI service** โ€” REST API for web integration +- โšก **GPU accelerated** โ€” CUDA inference with GroundingDINO + LaMa +- ๐Ÿณ **Docker ready** โ€” One-command deployment + +## Quick Start + +### CLI โ€” Remove by text prompt +```bash +python object_removal_ai/main_pipeline.py -i photo.jpg -p "person" --save-artifacts +``` + +### CLI โ€” Remove by mask +```bash +python object_removal_ai/main_pipeline.py -i photo.jpg -m mask.png --save-artifacts +``` + +### FastAPI Server +```bash +pip install fastapi uvicorn python-multipart +uvicorn object_removal_ai.api.main_api:app --host 0.0.0.0 --port 8000 +``` + +Then send requests: +```bash +# Remove by prompt +curl -X POST http://localhost:8000/remove-object \ + -F "image=@photo.jpg" \ + -F "prompt=person" \ + -o cleaned.jpg + +# Remove by mask +curl -X POST http://localhost:8000/remove-object \ + -F "image=@photo.jpg" \ + -F "mask=@mask.png" \ + -o cleaned.jpg +``` + +### Docker +```bash +docker build -t object-removal . +docker run --gpus all -p 8000:8000 object-removal +``` + +## Architecture + +``` +INPUT IMAGE โ†’ GroundingDINO (detect) โ†’ MobileSAM (segment) โ†’ Mask Refinement โ†’ LaMa (inpaint) โ†’ Post-Processing โ†’ OUTPUT +``` + +| Stage | Model | Purpose | +|-------|-------|---------| +| Detection | GroundingDINO / YOLOv8 | Find objects by text prompt | +| Segmentation | MobileSAM | Pixel-precise object masks | +| Mask Refinement | OpenCV morphology | Clean edges, fill holes | +| Inpainting | LaMa | Fill removed regions naturally | +| Post-Processing | Poisson + Color Match | Seamless blending | + +## Required Weights + +Place these in `../weights/` (relative to `object_removal_ai/`): + +| File | Model | Download | +|------|-------|----------| +| `big-lama.pt` | LaMa inpainter | [HuggingFace](https://huggingface.co/smartywu/big-lama) | +| `mobilesam.pt` | MobileSAM | [GitHub](https://github.com/ChaoningZhang/MobileSAM) | +| `yolov8n.pt` | YOLOv8 fallback | Auto-downloaded by ultralytics | + +GroundingDINO is loaded from HuggingFace Hub automatically. + +## Testing + +```bash +python tests/test_pipeline.py +``` + +## Project Structure + +``` +object_removal_ai/ +โ”œโ”€โ”€ api/ +โ”‚ โ””โ”€โ”€ main_api.py # FastAPI service +โ”œโ”€โ”€ configs/ +โ”‚ โ””โ”€โ”€ model_config.yaml # Model paths + parameters +โ”œโ”€โ”€ models/ +โ”‚ โ”œโ”€โ”€ groundingdino_detector.py +โ”‚ โ”œโ”€โ”€ sam_segmenter.py +โ”‚ โ”œโ”€โ”€ lama_inpainter.py +โ”‚ โ””โ”€โ”€ yolo_detector.py +โ”œโ”€โ”€ pipeline/ +โ”‚ โ”œโ”€โ”€ mask_refiner.py +โ”‚ โ”œโ”€โ”€ edge_extractor.py +โ”‚ โ”œโ”€โ”€ context_expansion.py +โ”‚ โ””โ”€โ”€ postprocess.py +โ”œโ”€โ”€ utils/ +โ”‚ โ””โ”€โ”€ image_utils.py +โ””โ”€โ”€ main_pipeline.py # CLI + ObjectRemovalPipeline class +``` diff --git a/src/object_removal_ai/api/__init__.py b/src/object_removal_ai/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6055d42635150a891004389ec87668c4b84f661e --- /dev/null +++ b/src/object_removal_ai/api/__init__.py @@ -0,0 +1 @@ +# API package init diff --git a/src/object_removal_ai/api/main_api.py b/src/object_removal_ai/api/main_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c6805c9149553ffbfe5aa53050653b5ba8652b25 --- /dev/null +++ b/src/object_removal_ai/api/main_api.py @@ -0,0 +1,222 @@ +""" +FastAPI service for AI Object Removal. + +Usage: + uvicorn object_removal_ai.api.main_api:app --host 0.0.0.0 --port 8000 + +Endpoints: + POST /remove-object โ€” Remove objects from images + POST /remove-text โ€” Remove text from images + GET /health โ€” Health check +""" + +import io +import os +import sys +import cv2 +import numpy as np +from fastapi import FastAPI, UploadFile, File, Form, HTTPException +from fastapi.responses import StreamingResponse, JSONResponse + +# Ensure both 'object_removal_ai' and 'src' are in sys.path +obj_rem_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +src_dir = os.path.dirname(obj_rem_dir) +if obj_rem_dir not in sys.path: + sys.path.insert(0, obj_rem_dir) +if src_dir not in sys.path: + sys.path.insert(0, src_dir) + +from main_pipeline import ObjectRemovalPipeline +try: + from ai_text_removal.pipeline import TextRemovalPipeline +except ImportError: + TextRemovalPipeline = None + +try: + from ai_super_resolution.pipeline import SuperResolutionPipeline +except ImportError: + SuperResolutionPipeline = None + +# โ”€โ”€โ”€ App โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +app = FastAPI( + title="AI Object Removal API", + description="Production-quality object removal powered by GroundingDINO + MobileSAM + LaMa", + version="2.0.0", +) + +# โ”€โ”€โ”€ Lazy-load pipeline on first request โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +_pipeline = None + +def get_pipeline() -> ObjectRemovalPipeline: + global _pipeline + if _pipeline is None: + config_path = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "configs", "model_config.yaml" + ) + _pipeline = ObjectRemovalPipeline(config_path=config_path) + return _pipeline + +_text_pipeline = None + +def get_text_pipeline() -> TextRemovalPipeline: + global _text_pipeline + if _text_pipeline is None and TextRemovalPipeline is not None: + _text_pipeline = TextRemovalPipeline() + return _text_pipeline + +_sr_pipeline = None + +def get_sr_pipeline() -> SuperResolutionPipeline: + global _sr_pipeline + if _sr_pipeline is None and SuperResolutionPipeline is not None: + import yaml + config_path = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "..", "ai_super_resolution", "configs", "config.yaml" + ) + with open(config_path, "r") as f: + config = yaml.safe_load(f) + _sr_pipeline = SuperResolutionPipeline(config) + return _sr_pipeline + + +# โ”€โ”€โ”€ Endpoints โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +@app.get("/health") +async def health(): + return {"status": "ok", "models_loaded": _pipeline is not None} + + +@app.post("/remove-object") +async def remove_object( + image: UploadFile = File(..., description="Input image (JPEG/PNG)"), + mask: UploadFile = File(None, description="Optional binary mask (white=remove, black=keep)"), + prompt: str = Form(None, description="Text prompt describing what to remove (e.g. 'person', 'deer')"), +): + """ + Remove objects from an image. + + Provide either: + - `prompt` for automatic detection (e.g. "person", "deer", "car") + - `mask` for manual selection (binary mask, white=remove) + - Both `prompt` and `mask` (mask takes priority) + """ + if not prompt and mask is None: + raise HTTPException(400, "Either 'prompt' or 'mask' must be provided.") + + # Read image + img_bytes = await image.read() + img_np = np.frombuffer(img_bytes, dtype=np.uint8) + img_bgr = cv2.imdecode(img_np, cv2.IMREAD_COLOR) + if img_bgr is None: + raise HTTPException(400, "Invalid image file.") + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + + # Read mask if provided + user_mask = None + if mask is not None: + mask_bytes = await mask.read() + mask_np = np.frombuffer(mask_bytes, dtype=np.uint8) + user_mask = cv2.imdecode(mask_np, cv2.IMREAD_GRAYSCALE) + if user_mask is None: + raise HTTPException(400, "Invalid mask file.") + + # Run pipeline + pipeline = get_pipeline() + try: + result = pipeline.run(img_rgb, prompt=prompt, mask=user_mask) + except Exception as e: + raise HTTPException(500, f"Pipeline error: {str(e)}") + + # Encode result as JPEG + result_bgr = cv2.cvtColor(result["result"], cv2.COLOR_RGB2BGR) + _, buffer = cv2.imencode(".jpg", result_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95]) + + return StreamingResponse( + io.BytesIO(buffer.tobytes()), + media_type="image/jpeg", + headers={"Content-Disposition": "attachment; filename=cleaned.jpg"} + ) + + +@app.post("/remove-text") +async def remove_text( + image: UploadFile = File(..., description="Input image (JPEG/PNG)"), + enable_diffusion: bool = Form(True, description="Enable Stable Diffusion refinement (slower but better quality)"), +): + """ + Automatically detect and remove all text from an image. + Uses an ensemble of CRAFT (EasyOCR) and structural inpainting. + """ + if TextRemovalPipeline is None: + raise HTTPException(502, "Text removal module not correctly installed/configured.") + + # Read image + img_bytes = await image.read() + img_np = np.frombuffer(img_bytes, dtype=np.uint8) + img_bgr = cv2.imdecode(img_np, cv2.IMREAD_COLOR) + if img_bgr is None: + raise HTTPException(400, "Invalid image file.") + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + + # Run pipeline + pipeline = get_text_pipeline() + if pipeline is None: + raise HTTPException(500, "Failed to initialize Text Removal Pipeline.") + + try: + result = pipeline.run(img_rgb, enable_diffusion=enable_diffusion) + except Exception as e: + raise HTTPException(500, f"Text removal error: {str(e)}") + + # Encode result as JPEG + result_bgr = cv2.cvtColor(result["result"], cv2.COLOR_RGB2BGR) + _, buffer = cv2.imencode(".jpg", result_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95]) + + return StreamingResponse( + io.BytesIO(buffer.tobytes()), + media_type="image/jpeg", + headers={"Content-Disposition": "attachment; filename=text_cleaned.jpg"} + ) + + +@app.post("/upscale") +async def upscale( + image: UploadFile = File(..., description="Input image (JPEG/PNG)"), + scale: int = Form(4, description="Upscale factor (2, 4, 8)"), + denoise: bool = Form(True, description="Enable pre-restoration denoising"), +): + """ + Production-grade AI Image Upscaling. + Powered by RealESRGAN + Tiled Inference + Pre-restoration. + """ + if SuperResolutionPipeline is None: + raise HTTPException(502, "Super-Resolution module not correctly installed.") + + # Read image + img_bytes = await image.read() + img_np = np.frombuffer(img_bytes, dtype=np.uint8) + img_bgr = cv2.imdecode(img_np, cv2.IMREAD_COLOR) + if img_bgr is None: + raise HTTPException(400, "Invalid image file.") + img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) + + # Run pipeline + pipeline = get_sr_pipeline() + if pipeline is None: + raise HTTPException(500, "Failed to initialize Super-Resolution Pipeline.") + + try: + result = pipeline.run(img_rgb, scale=scale, denoise=denoise) + except Exception as e: + raise HTTPException(500, f"Upscaling error: {str(e)}") + + # Encode result as JPEG + result_bgr = cv2.cvtColor(result, cv2.COLOR_RGB2BGR) + _, buffer = cv2.imencode(".jpg", result_bgr, [cv2.IMWRITE_JPEG_QUALITY, 95]) + + return StreamingResponse( + io.BytesIO(buffer.tobytes()), + media_type="image/jpeg", + headers={"Content-Disposition": "attachment; filename=upscaled.jpg"} + ) diff --git a/src/object_removal_ai/configs/GroundingDINO_SwinT_OGC.py b/src/object_removal_ai/configs/GroundingDINO_SwinT_OGC.py new file mode 100644 index 0000000000000000000000000000000000000000..9158d5f6260ec74bded95377d382387430d7cd70 --- /dev/null +++ b/src/object_removal_ai/configs/GroundingDINO_SwinT_OGC.py @@ -0,0 +1,43 @@ +batch_size = 1 +modelname = "groundingdino" +backbone = "swin_T_224_1k" +position_embedding = "sine" +pe_temperatureH = 20 +pe_temperatureW = 20 +return_interm_indices = [1, 2, 3] +backbone_freeze_keywords = None +enc_layers = 6 +dec_layers = 6 +pre_norm = False +dim_feedforward = 2048 +hidden_dim = 256 +dropout = 0.0 +nheads = 8 +num_queries = 900 +query_dim = 4 +num_patterns = 0 +num_feature_levels = 4 +enc_n_points = 4 +dec_n_points = 4 +two_stage_type = "standard" +two_stage_bbox_embed_share = False +two_stage_class_embed_share = False +transformer_activation = "relu" +dec_pred_bbox_embed_share = True +dn_box_noise_scale = 1.0 +dn_label_noise_ratio = 0.5 +dn_label_coef = 1.0 +dn_bbox_coef = 1.0 +embed_init_tgt = True +dn_labelbook_size = 2000 +max_text_len = 256 +text_encoder_type = "bert-base-uncased" +use_text_enhancer = True +use_fusion_layer = True +use_checkpoint = True +use_transformer_ckpt = True +use_text_cross_attention = True +text_dropout = 0.0 +fusion_dropout = 0.0 +fusion_droppath = 0.1 +sub_sentence_present = True diff --git a/src/object_removal_ai/configs/model_config.yaml b/src/object_removal_ai/configs/model_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..170bfe572623c7240aabfb16f5562565285b26d2 --- /dev/null +++ b/src/object_removal_ai/configs/model_config.yaml @@ -0,0 +1,50 @@ +pipeline: + device: "cuda" + image_size: 1024 + +paths: + weights: + detection: "groundingdino_swint_ogc.pth" + segmentation: "mobilesam.pt" + depth: "midas_v21_small.pt" + inpainting: "big-lama.pt" + diffusion: "runwayml/stable-diffusion-inpainting" + output: + dir: "output" + +parameters: + detection: + config_path: "configs/GroundingDINO_SwinT_OGC.py" + box_threshold: 0.3 + text_threshold: 0.25 + + context_expansion: + expansion_factor: 1.5 + min_padding: 30 + + mask_refinement: + dilate_kernel: 7 + dilate_iterations: 2 + close_kernel: 5 + gaussian_blur: 5 + + edge_extraction: + canny_low: 50 + canny_high: 150 + + inpainting: + multi_scale: true + scales: [256, 512, 768] + + depth: + enabled: true + model_type: "MiDaS_v21_small" + + post_processing: + use_poisson: false # Disabling poisson to prevent harsh edge color shifts + + diffusion: + prompt: "A clean natural landscape, realistic reconstruction with no artifacts" + negative_prompt: "artifacts, blurry, distorted, noisy patches, low quality, human, text, person" + num_inference_steps: 30 + strength: 0.0 # Properly disabled SD to rely purely on LaMa diff --git a/src/object_removal_ai/main_pipeline.py b/src/object_removal_ai/main_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a630d5c88c1fbbdfad47674114274e508cc6b683 --- /dev/null +++ b/src/object_removal_ai/main_pipeline.py @@ -0,0 +1,326 @@ +import os +import sys +import argparse +import yaml +import time +import cv2 +import numpy as np +import torch + +# Ensure project root is in sys.path for robust imports +script_dir = os.path.dirname(os.path.abspath(__file__)) +if script_dir not in sys.path: + sys.path.insert(0, script_dir) + +from or_utils.image_utils import load_image, save_image, resize_max +from or_models.groundingdino_detector import GroundingDINODetector +from or_models.sam_segmenter import MobileSamSegmenter +from or_models.midas_depth import MidasDepthEstimator +from or_models.lama_inpainter import LaMaInpainter +from or_models.diffusion_refiner import DiffusionRefiner +from or_pipeline.mask_refiner import MaskRefiner +from or_pipeline.edge_extractor import EdgeExtractor +from or_pipeline.context_expansion import ContextExpander +from or_pipeline.postprocess import PostProcessor +from or_models.yolo_detector import YoloDetector + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# Path Resolution +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) +# Look for weights in Text Removal/weights as the universal location +WEIGHTS_DIR = os.path.abspath(os.path.join(PROJECT_DIR, "..", "..", "weights")) + + +def resolve_weight_path(p: str) -> str: + """Resolve a weight path: try local, then universal weights folder.""" + if not p or os.path.isabs(p) or p.startswith("runwayml/"): + return p + # 1. Try relative to project dir + local = os.path.abspath(os.path.join(PROJECT_DIR, p)) + if os.path.exists(local): + return local + # 2. Try universal weights folder + universal = os.path.join(WEIGHTS_DIR, os.path.basename(p)) + if os.path.exists(universal): + return universal + # 3. Return local (will fail at model load with clear error) + return local + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# ObjectRemovalPipeline โ€” Reusable Class +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +class ObjectRemovalPipeline: + """ + Production-quality object removal pipeline. + + Usage: + pipeline = ObjectRemovalPipeline("configs/model_config.yaml") + result = pipeline.run(image, prompt="person") # auto-detect + result = pipeline.run(image, mask=user_mask) # user-provided mask + """ + + def __init__(self, config_path: str = None): + if config_path is None: + config_path = os.path.join(PROJECT_DIR, "configs", "model_config.yaml") + + with open(config_path, "r") as f: + config = yaml.safe_load(f) + + self.config = config + self.device = "cuda" + self.params = config["parameters"] + + # Resolve weight paths + weights = {k: resolve_weight_path(v) for k, v in config["paths"]["weights"].items()} + self.weights = weights + + print("=" * 60) + print(" AI Object Removal Pipeline โ€” Initializing") + print("=" * 60) + + # โ”€โ”€ Detector (GroundingDINO โ†’ YOLOv8 fallback) โ”€โ”€ + self.detector = None + try: + print("[Init] Loading GroundingDINO...") + self.detector = GroundingDINODetector( + config_path=self.params.get("detection", {}).get("config_path", ""), + model_path=weights.get("detection", ""), + device=self.device + ) + except Exception as e: + print(f"[Init] GroundingDINO failed: {e}") + print("[Init] Falling back to YOLOv8...") + yolo_path = weights.get("yolo", resolve_weight_path("yolov8n.pt")) + self.detector = YoloDetector(model_path=yolo_path, device=self.device) + + # โ”€โ”€ Segmenter (MobileSAM) โ”€โ”€ + print("[Init] Loading MobileSAM...") + self.segmenter = MobileSamSegmenter(model_path=weights["segmentation"], device=self.device) + + # โ”€โ”€ Mask Refiner โ”€โ”€ + mask_params = self.params["mask_refinement"] + self.mask_refiner = MaskRefiner( + dilate_kernel=mask_params["dilate_kernel"], + dilate_iter=mask_params["dilate_iterations"], + close_kernel=mask_params["close_kernel"], + blur_kernel=mask_params["gaussian_blur"], + ) + + # โ”€โ”€ Edge Extractor โ”€โ”€ + edge_params = self.params["edge_extraction"] + self.edge_extractor = EdgeExtractor( + canny_low=edge_params["canny_low"], + canny_high=edge_params["canny_high"] + ) + + # โ”€โ”€ Inpainter (LaMa) โ”€โ”€ + print("[Init] Loading LaMa inpainter...") + self.inpainter = LaMaInpainter(model_path=weights["inpainting"], device=self.device) + + # โ”€โ”€ Diffusion Refiner โ”€โ”€ + diffusion_params = self.params.get("diffusion", {}) + self.diffusion_refiner = None + if diffusion_params.get("strength", 0.0) > 0.0: + print("[Init] Loading Diffusion Refiner...") + self.diffusion_refiner = DiffusionRefiner( + model_id=weights.get("diffusion", "runwayml/stable-diffusion-inpainting"), + device=self.device + ) + + # โ”€โ”€ Post-Processor โ”€โ”€ + self.post_processor = PostProcessor( + use_poisson=self.params.get("post_processing", {}).get("use_poisson", True) + ) + + print("=" * 60) + print(" Pipeline ready!") + print("=" * 60) + + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + # Public API + # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + def run( + self, + image: np.ndarray, + prompt: str = None, + mask: np.ndarray = None, + save_artifacts: bool = False, + output_dir: str = "output", + ) -> dict: + """ + Run object removal. + + Args: + image: RGB image (H, W, 3), uint8 + prompt: Text prompt for auto-detection (e.g. "person", "deer") + mask: User-provided binary mask (H, W), 255 = region to remove + save_artifacts: Whether to save intermediate masks/edges + output_dir: Directory for saving artifacts + + Returns: + dict with keys: 'result' (cleaned image), 'mask', 'edge_map', 'boxes' + """ + start_time = time.time() + + # Preserve the un-resized original for full-res compositing + true_original = image.copy() + + image_size = self.config["pipeline"]["image_size"] + image = resize_max(image, image_size) + original = image.copy() + + artifacts = {"boxes": [], "mask": None, "edge_map": None} + + # โ”€โ”€ Step 1: Get mask (auto-detect or user-provided) โ”€โ”€ + if mask is not None: + print("[1/5] Using user-provided mask.") + # Resize mask to match image + if mask.shape[:2] != image.shape[:2]: + mask = cv2.resize(mask, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_NEAREST) + raw_mask = mask + elif prompt: + print(f"[1/5] Auto-detecting: '{prompt}'...") + box_t = self.params.get("detection", {}).get("box_threshold", 0.3) + boxes = self.detector(image, text_prompt=prompt, box_threshold=box_t) + artifacts["boxes"] = boxes + print(f" Found {len(boxes)} object(s).") + + if not boxes: + print(" No objects detected. Returning original.") + return {"result": original, **artifacts} + + print("[2/5] Segmenting objects (MobileSAM)...") + raw_mask = self.segmenter(image, boxes) + else: + raise ValueError("Either 'prompt' or 'mask' must be provided.") + + # โ”€โ”€ Step 2: Refine mask โ”€โ”€ + print("[3/5] Refining mask & calculating context...") + refined_mask, alpha_mask = self.mask_refiner(raw_mask) + artifacts["mask"] = refined_mask + artifacts["alpha_mask"] = alpha_mask + + # Calculate object size percentage for dynamic routing + mask_area = np.count_nonzero(refined_mask) + total_area = refined_mask.shape[0] * refined_mask.shape[1] + area_pct = (mask_area / total_area) * 100 + print(f" Object covers {area_pct:.1f}% of image.") + if area_pct > 15.0: + print(" Large object detected -> Routing to Big-LaMa capability.") + else: + print(" Small object detected -> Standard inpainting logic.") + + # โ”€โ”€ Step 3: Extract edges โ”€โ”€ + print("[4/5] Extracting edge structure...") + edge_map = self.edge_extractor(image, refined_mask) + artifacts["edge_map"] = edge_map + + # โ”€โ”€ Step 4: Inpaint โ”€โ”€ + inpaint_params = self.params.get("inpainting", {}) + print("[5/5] Inpainting (LaMa)...") + clean_image = self.inpainter( + image, refined_mask, + edge_map=edge_map, + multi_scale=inpaint_params.get("multi_scale", True), + scales=inpaint_params.get("scales", [256, 512, max(image.shape[:2])]), # Added native resolution to scales + ) + + # โ”€โ”€ Step 4.5: Diffusion Generative Refinement โ”€โ”€ + diffusion_params = self.params.get("diffusion", {}) + if self.diffusion_refiner is not None and diffusion_params.get("strength", 0.0) > 0.0: + print("[5.5/5] Generative Texture Refinement (Stable Diffusion)...") + + # Free VRAM before diffusion + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + clean_image = self.diffusion_refiner( + image=clean_image, + mask=refined_mask, + prompt=diffusion_params.get("prompt", "clean natural background, high quality photo"), + negative_prompt=diffusion_params.get("negative_prompt", "artifacts, blurry, distorted"), + steps=diffusion_params.get("num_inference_steps", 20), + strength=diffusion_params.get("strength", 0.35) + ) + + # Free VRAM after diffusion + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + # โ”€โ”€ Step 5: Post-process โ”€โ”€ + print(" Post-processing (native-res full compositing + color match)...") + # Pass the original un-resized image and the working-res modified mask/patch + final_image = self.post_processor( + true_original=true_original, # Important: The un-scaled input image + inpainted=clean_image, + mask=refined_mask, + alpha_mask=alpha_mask + ) + + elapsed = time.time() - start_time + print(f"\n โœ… Done in {elapsed:.2f}s") + + # Save artifacts if requested + if save_artifacts: + os.makedirs(output_dir, exist_ok=True) + cv2.imwrite(os.path.join(output_dir, "mask.png"), refined_mask) + # Save alpha mask visualizing the gradient + cv2.imwrite(os.path.join(output_dir, "alpha_mask.png"), (alpha_mask * 255).astype(np.uint8)) + cv2.imwrite(os.path.join(output_dir, "edges.png"), edge_map) + + return {"result": final_image, **artifacts} + + +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +# CLI Entry Point +# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• +def main(): + parser = argparse.ArgumentParser(description="AI Object Removal Pipeline") + parser.add_argument("--input", "-i", type=str, required=True, help="Input image path") + parser.add_argument("--output", "-o", type=str, default=None, help="Output image path") + parser.add_argument("--config", "-c", type=str, + default=os.path.join(PROJECT_DIR, "configs", "model_config.yaml"), + help="Config file") + parser.add_argument("--prompt", "-p", type=str, default=None, + help="Text prompt describing what to remove (e.g., 'person', 'deer')") + parser.add_argument("--mask", "-m", type=str, default=None, + help="Path to user-provided binary mask (white=remove)") + parser.add_argument("--save-artifacts", action="store_true", + help="Save intermediate masks and edge maps") + args = parser.parse_args() + + if not args.prompt and not args.mask: + parser.error("Either --prompt or --mask must be provided.") + + # Initialize pipeline + pipeline = ObjectRemovalPipeline(config_path=args.config) + + # Load image + image = load_image(args.input) + + # Load user mask if provided + user_mask = None + if args.mask: + user_mask = cv2.imread(args.mask, cv2.IMREAD_GRAYSCALE) + if user_mask is None: + raise FileNotFoundError(f"Could not load mask: {args.mask}") + + # Run + out_dir = pipeline.config["paths"]["output"].get("dir", "output") + result = pipeline.run( + image, prompt=args.prompt, mask=user_mask, + save_artifacts=args.save_artifacts, output_dir=out_dir, + ) + + # Save output + os.makedirs(out_dir, exist_ok=True) + name, ext = os.path.splitext(os.path.basename(args.input)) + out_path = args.output if args.output else os.path.join(out_dir, f"{name}_clean{ext}") + save_image(result["result"], out_path) + + +if __name__ == "__main__": + main() diff --git a/src/object_removal_ai/or_models/__init__.py b/src/object_removal_ai/or_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3c159a665535afa10f8749a7c189adbf36f741fb --- /dev/null +++ b/src/object_removal_ai/or_models/__init__.py @@ -0,0 +1 @@ +# models package diff --git a/src/object_removal_ai/or_models/diffusion_refiner.py b/src/object_removal_ai/or_models/diffusion_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..fb956587d9c8ffc1e54a18c32339259ec08de795 --- /dev/null +++ b/src/object_removal_ai/or_models/diffusion_refiner.py @@ -0,0 +1,89 @@ +import os +import numpy as np +import cv2 +import torch +from PIL import Image + +class DiffusionRefiner: + """ + Stable Diffusion Inpainting Refiner. + Enhances LaMa output with generative textures for photorealism. + Loaded lazily to save VRAM when not needed. + """ + + def __init__(self, model_id: str = "runwayml/stable-diffusion-inpainting", device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.model_id = model_id + self.pipe = None + + try: + from diffusers import StableDiffusionInpaintPipeline + self.pipe = StableDiffusionInpaintPipeline.from_pretrained( + model_id, + torch_dtype=torch.float16 if self.device == "cuda" else torch.float32, + ) + self.pipe = self.pipe.to(self.device) + # Enable memory-efficient attention if available + try: + self.pipe.enable_xformers_memory_efficient_attention() + except Exception: + pass + print(f"[DiffusionRefiner] Loaded {model_id} on {self.device}.") + except Exception as e: + print(f"[DiffusionRefiner] Failed to load: {e}. Diffusion refinement disabled.") + + def __call__( + self, + image: np.ndarray, + mask: np.ndarray, + prompt: str = "clean natural background, high quality photo", + negative_prompt: str = "artifacts, blurry, distorted", + steps: int = 30, + strength: float = 0.75, + ) -> np.ndarray: + """ + Args: + image: RGB image (H, W, 3), uint8 + mask: Binary mask (H, W), 255 = region to refine + prompt: Conditioning text for generation + negative_prompt: Negative conditioning + steps: Number of diffusion steps + strength: How much to alter the image (0.0 = none, 1.0 = full) + Returns: + Refined RGB image (H, W, 3), uint8 + """ + if self.pipe is None: + return image + + h, w = image.shape[:2] + + # Convert to PIL and ensure dimensions are multiples of 8 (required for SD) + # We resize slightly to the nearest multiple of 8 to avoid aspect ratio distortion + new_w = (w // 8) * 8 + new_h = (h // 8) * 8 + + # If it's too large for standard SD Inpainting, maybe bound it, but pipeline already resize_max(512) + pil_image = Image.fromarray(image).resize((new_w, new_h), Image.Resampling.LANCZOS) + pil_mask = Image.fromarray(mask).resize((new_w, new_h), Image.Resampling.NEAREST) + + result = self.pipe( + prompt=prompt, + negative_prompt=negative_prompt, + image=pil_image, + mask_image=pil_mask, + height=new_h, + width=new_w, + num_inference_steps=steps, + strength=strength, + ).images[0] + + # Resize back to original exact dimensions + result_np = np.array(result.resize((w, h), Image.Resampling.LANCZOS)) + + # Only overwrite the masked area to preserve original image sharp pixels (like people's faces) + # We use a soft blur on the mask to ensure seamless blending without hard circles + soft_mask = cv2.GaussianBlur(mask, (15, 15), 0).astype(np.float32) / 255.0 + soft_mask_3d = np.expand_dims(soft_mask, axis=-1) + + final_image = (image.astype(np.float32) * (1 - soft_mask_3d) + result_np.astype(np.float32) * soft_mask_3d) + return np.clip(final_image, 0, 255).astype(np.uint8) diff --git a/src/object_removal_ai/or_models/groundingdino_detector.py b/src/object_removal_ai/or_models/groundingdino_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..4908f8bda619eaf9a39f52fa8005f2a077ceb0a0 --- /dev/null +++ b/src/object_removal_ai/or_models/groundingdino_detector.py @@ -0,0 +1,75 @@ +import os +import torch +import numpy as np +import cv2 +from typing import List, Tuple +from PIL import Image + +class GroundingDINODetector: + """ + Open-vocabulary object detector using GroundingDINO. + Allows detecting objects using zero-shot text prompts instead of fixed classes. + """ + def __init__(self, config_path: str, model_path: str, device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.processor = None + self.model = None + + try: + from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection + model_id = "IDEA-Research/grounding-dino-tiny" + print(f"[GroundingDINO] Loading HF model {model_id} on {self.device}...") + self.processor = AutoProcessor.from_pretrained(model_id) + self.model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(self.device) + print("[GroundingDINO] Successfully loaded via transformers.") + except Exception as e: + print(f"[GroundingDINO] Initialization failed: {e}") + raise # Don't silently fail โ€” let the caller handle fallback + + def __call__(self, image: np.ndarray, text_prompt: str, box_threshold: float = 0.3, **kwargs) -> List[Tuple[int, int, int, int]]: + """ + Args: + image: RGB image (H, W, 3) + text_prompt: What object to find (e.g., "person. dog. car.") + box_threshold: Minimum confidence for detection + Returns: + List of bounding boxes [x1, y1, x2, y2]. + """ + if self.model is None or not text_prompt: + raise RuntimeError("[GroundingDINO] Model not loaded or prompt is empty.") + + # GroundingDINO requires "." separator in prompt + if not text_prompt.endswith("."): + text_prompt = text_prompt + "." + + pil_img = Image.fromarray(image) + + inputs = self.processor(images=pil_img, text=text_prompt, return_tensors="pt").to(self.device) + + with torch.no_grad(): + outputs = self.model(**inputs) + + h, w = image.shape[:2] + + results = self.processor.post_process_grounded_object_detection( + outputs, + inputs.input_ids, + threshold=box_threshold, + target_sizes=[(h, w)] + ) + + boxes_list = [] + if len(results) > 0: + boxes = results[0]["boxes"] + scores = results[0]["scores"] + labels = results[0]["labels"] + + for box, score, label in zip(boxes, scores, labels): + x1, y1, x2, y2 = box.tolist() + x1, y1 = max(0, int(x1)), max(0, int(y1)) + x2, y2 = min(w, int(x2)), min(h, int(y2)) + + print(f"[GroundingDINO] Detected '{label}' (conf={score:.2f}) at [{x1},{y1},{x2},{y2}]") + boxes_list.append((x1, y1, x2, y2)) + + return boxes_list diff --git a/src/object_removal_ai/or_models/lama_inpainter.py b/src/object_removal_ai/or_models/lama_inpainter.py new file mode 100644 index 0000000000000000000000000000000000000000..da96119144229765110ba7f5d578ba725d2d60fa --- /dev/null +++ b/src/object_removal_ai/or_models/lama_inpainter.py @@ -0,0 +1,186 @@ +import os +import cv2 +import numpy as np +import torch + + +class LaMaInpainter: + """ + LaMa (Large Mask Inpainting) with multi-scale and structure-guided support. + Uses Fast Fourier Convolutions for resolution-robust inpainting. + """ + + def __init__(self, model_path: str, device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.model = None + + if not os.path.exists(model_path): + print(f"[LaMa] WARNING: Weights not found at {model_path}.") + print(f"[LaMa] โš ๏ธ Will use OpenCV TELEA fallback โ€” quality will be lower.") + return + + try: + self.model = torch.jit.load(model_path, map_location=self.device) + self.model.eval() + # Note: LaMa uses FFT convolutions which require float32 (cuFFT doesn't support fp16) + print(f"[LaMa] Loaded weights from {model_path} onto {self.device}.") + except Exception as e: + print(f"[LaMa] Failed to load: {e}. Using OpenCV TELEA fallback.") + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + def __call__( + self, + image: np.ndarray, + mask: np.ndarray, + edge_map: np.ndarray = None, + depth_map: np.ndarray = None, + multi_scale: bool = True, + scales: list = None, + ) -> np.ndarray: + """ + Structure-guided, multi-scale inpainting. + + Args: + image : RGB image (H, W, 3), uint8 + mask : Binary mask (H, W), 255 = region to fill + edge_map : Optional edge structure map + depth_map : Optional depth map (from MiDaS) + multi_scale: Whether to run multi-scale fusion + scales : Resolutions for multi-scale (default [256, 512]) + Returns: + Inpainted RGB image (H, W, 3), uint8 + """ + if scales is None: + scales = [256, 512] + + if multi_scale: + return self._multi_scale_inpaint(image, mask, edge_map, scales) + return self._single_inpaint(image, mask, edge_map) + + # ------------------------------------------------------------------ + # Single-resolution inpainting + # ------------------------------------------------------------------ + def _single_inpaint( + self, image: np.ndarray, mask: np.ndarray, edge_map: np.ndarray = None + ) -> np.ndarray: + + if self.model is None: + return self._cv2_fallback(image, mask, edge_map) + + h, w = image.shape[:2] + + def pad32(s): + return (32 - (s % 32)) % 32 + + pad_h, pad_w = pad32(h), pad32(w) + + img_padded = ( + np.pad(image, ((0, pad_h), (0, pad_w), (0, 0)), mode="reflect") + if (pad_h or pad_w) + else image + ) + mask_padded = ( + np.pad(mask, ((0, pad_h), (0, pad_w)), mode="constant") + if (pad_h or pad_w) + else mask + ) + + img_t = ( + torch.from_numpy(img_padded) + .float() + .permute(2, 0, 1) + .unsqueeze(0) + .to(self.device) + / 255.0 + ) + mask_t = ( + torch.from_numpy(mask_padded) + .float() + .unsqueeze(0) + .unsqueeze(0) + .to(self.device) + / 255.0 + ) + + with torch.no_grad(): + out = self.model(img_t, mask_t) + + out_np = out.squeeze(0).permute(1, 2, 0).float().cpu().numpy() + out_np = np.clip(out_np * 255, 0, 255).astype(np.uint8) + + return out_np[:h, :w] if (pad_h or pad_w) else out_np + + # ------------------------------------------------------------------ + # Multi-scale inpainting with Gaussian-weighted fusion + # ------------------------------------------------------------------ + def _multi_scale_inpaint( + self, + image: np.ndarray, + mask: np.ndarray, + edge_map: np.ndarray = None, + scales: list = None, + ) -> np.ndarray: + if scales is None: + scales = [256, 512] + + h, w = image.shape[:2] + accumulator = np.zeros_like(image, dtype=np.float64) + weight_sum = 0.0 + all_scales = scales + [max(h, w)] + + for i, target_size in enumerate(all_scales): + sf = target_size / max(h, w) + if sf >= 1.0: + s_img, s_mask, s_edge = image, mask, edge_map + else: + nw = max(8, int(w * sf) // 8 * 8) + nh = max(8, int(h * sf) // 8 * 8) + s_img = cv2.resize(image, (nw, nh), interpolation=cv2.INTER_AREA) + s_mask = cv2.resize(mask, (nw, nh), interpolation=cv2.INTER_NEAREST) + s_edge = ( + cv2.resize(edge_map, (nw, nh), interpolation=cv2.INTER_NEAREST) + if edge_map is not None + else None + ) + + result = self._single_inpaint(s_img, s_mask, s_edge) + if result.shape[:2] != (h, w): + result = cv2.resize(result, (w, h), interpolation=cv2.INTER_CUBIC) + + # Higher weight for higher resolution passes (more detail) + weight = 2.0 ** i + accumulator += result.astype(np.float64) * weight + weight_sum += weight + + blended = (accumulator / weight_sum).astype(np.uint8) + + # Only replace pixels within the mask + mask_3d = np.expand_dims((mask > 127).astype(np.uint8), axis=2) + return (image * (1 - mask_3d) + blended * mask_3d).astype(np.uint8) + + # ------------------------------------------------------------------ + # OpenCV fallback (improved: TELEA + larger radius) + # ------------------------------------------------------------------ + def _cv2_fallback( + self, image: np.ndarray, mask: np.ndarray, edge_map: np.ndarray = None + ) -> np.ndarray: + print("[LaMa] โš ๏ธ Using OpenCV TELEA fallback (lower quality).") + img_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + + if edge_map is not None: + kernel = np.ones((5, 5), np.uint8) + dilated = cv2.dilate(mask, kernel, iterations=1) + border = cv2.subtract(dilated, mask) + border_edges = cv2.bitwise_and(edge_map, edge_map, mask=border) + edge_3d = cv2.cvtColor(border_edges, cv2.COLOR_GRAY2BGR) + hint_mask = border_edges > 0 + img_bgr[hint_mask] = ( + img_bgr[hint_mask].astype(np.float32) * 0.5 + + edge_3d[hint_mask].astype(np.float32) * 0.5 + ).astype(np.uint8) + + # TELEA is generally better than Navier-Stokes for larger regions + inpainted = cv2.inpaint(img_bgr, mask, inpaintRadius=7, flags=cv2.INPAINT_TELEA) + return cv2.cvtColor(inpainted, cv2.COLOR_BGR2RGB) diff --git a/src/object_removal_ai/or_models/midas_depth.py b/src/object_removal_ai/or_models/midas_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..0a612e386ba7ba172e65c78b00dd7c529147b29c --- /dev/null +++ b/src/object_removal_ai/or_models/midas_depth.py @@ -0,0 +1,62 @@ +import torch +import cv2 +import numpy as np +import os + +class MidasDepthEstimator: + """ + MiDaS Depth Estimation model to understand the structure of the scene. + Provides a depth map which can be used to guide structure-aware inpainting. + """ + def __init__(self, model_type="MiDaS_v21_small", device="cuda"): + self.device = torch.device(device if torch.cuda.is_available() else "cpu") + self.model_type = model_type + + try: + # We load from PyTorch Hub for ease of use in this pipeline. + # Local weights could be loaded if `model_path` is passed. + self.model = torch.hub.load("intel-isl/MiDaS", self.model_type) + self.model.to(self.device) + self.model.eval() + + midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms") + if "small" in self.model_type: + self.transform = midas_transforms.small_transform + else: + self.transform = midas_transforms.default_transform + + print(f"[MiDaS] Loaded model {model_type} on {self.device}.") + except Exception as e: + print(f"[MiDaS] Failed to load model: {e}") + self.model = None + + def __call__(self, image: np.ndarray) -> np.ndarray: + """ + Estimate depth map from RGB image. + Args: + image: RGB image (H, W, 3). + Returns: + Depth map normalized 0-255 (H, W). + """ + if self.model is None: + return np.zeros(image.shape[:2], dtype=np.uint8) + + # Apply MiDaS transforms + input_batch = self.transform(image).to(self.device) + + with torch.no_grad(): + prediction = self.model(input_batch) + + # Resize the prediction to match the original image resolution + prediction = torch.nn.functional.interpolate( + prediction.unsqueeze(1), + size=image.shape[:2], + mode="bicubic", + align_corners=False, + ).squeeze() + + # Normalize to 0-255 for standard imaging + depth_map = prediction.cpu().numpy() + depth_map = cv2.normalize(depth_map, None, 0, 255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U) + + return depth_map diff --git a/src/object_removal_ai/or_models/sam_segmenter.py b/src/object_removal_ai/or_models/sam_segmenter.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f766925217db9768216bf638fb05531d49851e --- /dev/null +++ b/src/object_removal_ai/or_models/sam_segmenter.py @@ -0,0 +1,60 @@ +import os +import torch +import numpy as np +import cv2 +from typing import List, Tuple +from mobile_sam import sam_model_registry, SamPredictor + +class MobileSamSegmenter: + """ + MobileSAM instance segmentation. + Fast alternative to standard SAM for Object Segmentation. + """ + def __init__(self, model_path: str, device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + + if not os.path.exists(model_path): + raise FileNotFoundError( + f"[MobileSAM] CRITICAL: Weights not found at {model_path}. " + f"Download from: https://github.com/ChaoningZhang/MobileSAM/raw/master/weights/mobile_sam.pt" + ) + + sam = sam_model_registry["vit_t"](checkpoint=model_path) + sam.to(device=self.device) + sam.eval() + self.predictor = SamPredictor(sam) + print(f"[MobileSAM] Loaded weights from {model_path} onto {self.device}.") + + def __call__(self, image: np.ndarray, boxes: List[Tuple[int, int, int, int]]) -> np.ndarray: + """ + Takes an RGB image and a list of bounding boxes, returns a binary mask. + Args: + image: RGB image (H, W, 3). + boxes: List of bounding boxes [x1, y1, x2, y2]. + Returns: + Binary mask (H, W) where 255 indicates the object. + """ + h, w = image.shape[:2] + final_mask = np.zeros((h, w), dtype=np.uint8) + + if not boxes: + return final_mask + + self.predictor.set_image(image) + + input_boxes = torch.tensor(boxes, device=self.predictor.device) + transformed_boxes = self.predictor.transform.apply_boxes_torch(input_boxes, image.shape[:2]) + + masks, _, _ = self.predictor.predict_torch( + point_coords=None, + point_labels=None, + boxes=transformed_boxes, + multimask_output=False, + ) + + # Combine all instance masks into one binary mask + for i in range(masks.shape[0]): + instance_mask = masks[i, 0].cpu().numpy() + final_mask[instance_mask > 0] = 255 + + return final_mask diff --git a/src/object_removal_ai/or_models/yolo_detector.py b/src/object_removal_ai/or_models/yolo_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..a8f98fdf84c4c643da6c5c0394e6b2c88ebdbf4a --- /dev/null +++ b/src/object_removal_ai/or_models/yolo_detector.py @@ -0,0 +1,105 @@ +import torch +import numpy as np +from ultralytics import YOLO +from typing import List, Tuple + +# COCO class names for fuzzy matching +COCO_CLASSES = [ + 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', + 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', + 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', + 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', + 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', + 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', + 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', + 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', + 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', + 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', + 'hair drier', 'toothbrush' +] + +# Fuzzy synonym map: user query -> COCO classes to match +SYNONYM_MAP = { + 'deer': ['horse', 'cow', 'sheep', 'giraffe'], + 'animal': ['dog', 'cat', 'horse', 'cow', 'sheep', 'bird', 'bear', 'elephant', 'zebra', 'giraffe'], + 'vehicle': ['car', 'truck', 'bus', 'motorcycle', 'bicycle', 'train', 'airplane', 'boat'], + 'furniture': ['chair', 'couch', 'bed', 'dining table'], + 'human': ['person'], + 'people': ['person'], + 'man': ['person'], + 'woman': ['person'], + 'child': ['person'], + 'kid': ['person'], + 'food': ['banana', 'apple', 'sandwich', 'orange', 'pizza', 'donut', 'cake', 'hot dog'], + 'plant': ['potted plant'], + 'tree': ['potted plant'], + 'phone': ['cell phone'], + 'computer': ['laptop'], + 'monitor': ['tv'], + 'screen': ['tv', 'laptop'], + 'sofa': ['couch'], + 'table': ['dining table'], +} + +class YoloDetector: + """ + Standard object detector using YOLOv8 with fuzzy label matching. + Supports synonym-based matching so "deer" can match nearby COCO classes. + """ + def __init__(self, model_path: str, device: str = "cuda"): + self.device = "cuda" if torch.cuda.is_available() and device == "cuda" else "cpu" + self.model = YOLO(model_path).to(self.device) + print(f"[YOLOv8] Loaded weights from {model_path} onto {self.device}.") + + def _get_matching_classes(self, text_prompt: str) -> set: + """Find all COCO class IDs that match the user's text prompt.""" + prompt_lower = text_prompt.lower().strip().rstrip(".") + matching_labels = set() + + # Direct match: check if any COCO class contains the prompt or vice versa + for coco_cls in COCO_CLASSES: + if prompt_lower in coco_cls or coco_cls in prompt_lower: + matching_labels.add(coco_cls) + + # Synonym match: check each word in the prompt against synonym map + for word in prompt_lower.split(): + word = word.strip() + if word in SYNONYM_MAP: + matching_labels.update(SYNONYM_MAP[word]) + + # If nothing matched, accept ALL detections as a last resort + if not matching_labels: + print(f"[YOLOv8] WARNING: No COCO class matches '{text_prompt}'. Accepting all detections.") + matching_labels = set(COCO_CLASSES) + else: + print(f"[YOLOv8] Matching '{text_prompt}' โ†’ classes: {matching_labels}") + + return matching_labels + + def __call__(self, image: np.ndarray, text_prompt: str, box_threshold: float = 0.3, **kwargs) -> List[Tuple[int, int, int, int]]: + """ + Args: + image: RGB image (H, W, 3) + text_prompt: Object name (e.g., "person", "deer", "white deer") + box_threshold: Minimum confidence + Returns: + List of bounding boxes [x1, y1, x2, y2]. + """ + matching_labels = self._get_matching_classes(text_prompt) + + results = self.model(image, conf=box_threshold, verbose=False) + + boxes_list = [] + if len(results) > 0: + for box in results[0].boxes: + cls_id = int(box.cls[0]) + label = self.model.names[cls_id] + conf = float(box.conf[0]) + + if label in matching_labels: + x1, y1, x2, y2 = box.xyxy[0].tolist() + print(f"[YOLOv8] Detected '{label}' (conf={conf:.2f}) at [{int(x1)},{int(y1)},{int(x2)},{int(y2)}]") + boxes_list.append((int(x1), int(y1), int(x2), int(y2))) + + return boxes_list diff --git a/src/object_removal_ai/or_pipeline/__init__.py b/src/object_removal_ai/or_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d14609c16b52e7b94e94b43f6e3ea358477b7e3a --- /dev/null +++ b/src/object_removal_ai/or_pipeline/__init__.py @@ -0,0 +1 @@ +# pipeline package diff --git a/src/object_removal_ai/or_pipeline/context_expansion.py b/src/object_removal_ai/or_pipeline/context_expansion.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8ca2e82557636711e72844081728604d659af6 --- /dev/null +++ b/src/object_removal_ai/or_pipeline/context_expansion.py @@ -0,0 +1,55 @@ +import numpy as np +import cv2 +from typing import Tuple + +class ContextExpander: + """ + Expands the bounding box of an object to capture surrounding global context. + This gives inpainting models like LaMa context to reconstruct geometry and textures correctly. + """ + def __init__(self, expansion_factor: float = 1.5, min_padding: int = 30): + self.expansion_factor = expansion_factor + self.min_padding = min_padding + + def expand_box( + self, + box: Tuple[int, int, int, int], + image_shape: Tuple[int, int] + ) -> Tuple[int, int, int, int]: + """ + Args: + box: (x1, y1, x2, y2) + image_shape: (H, W) + Returns: + Expanded box (new_x1, new_y1, new_x2, new_y2) clamped to image boundaries. + """ + x1, y1, x2, y2 = box + img_h, img_w = image_shape + + width = x2 - x1 + height = y2 - y1 + + # Calculate padding needed to reach expansion factor, or minimum padding + pad_x = max(int((width * self.expansion_factor - width) / 2), self.min_padding) + pad_y = max(int((height * self.expansion_factor - height) / 2), self.min_padding) + + new_x1 = max(0, x1 - pad_x) + new_y1 = max(0, y1 - pad_y) + new_x2 = min(img_w, x2 + pad_x) + new_y2 = min(img_h, y2 + pad_y) + + return (new_x1, new_y1, new_x2, new_y2) + + def crop_context(self, image: np.ndarray, mask: np.ndarray, box: Tuple[int, int, int, int]): + """ + Crops the image and mask to the expanded bounding box for focused processing. + Returns the cropped image, cropped mask, and the expanded box used. + """ + h, w = image.shape[:2] + expanded_box = self.expand_box(box, (h, w)) + ex1, ey1, ex2, ey2 = expanded_box + + crop_img = image[ey1:ey2, ex1:ex2] + crop_mask = mask[ey1:ey2, ex1:ex2] + + return crop_img, crop_mask, expanded_box diff --git a/src/object_removal_ai/or_pipeline/edge_extractor.py b/src/object_removal_ai/or_pipeline/edge_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..13c95073e1ed581f2baa1a35e345959bcca09c8c --- /dev/null +++ b/src/object_removal_ai/or_pipeline/edge_extractor.py @@ -0,0 +1,34 @@ +import cv2 +import numpy as np + + +class EdgeExtractor: + """ + Extracts structural edge maps from the image (excluding the masked area). + Supports Canny and optionally HED (Holistically-Nested Edge Detection). + These maps guide the inpainting model to reconstruct geometric structures + like walls, roads, and table edges correctly. + """ + + def __init__(self, canny_low: int = 50, canny_high: int = 150, use_hed: bool = False): + self.canny_low = canny_low + self.canny_high = canny_high + self.use_hed = use_hed + + def __call__(self, image: np.ndarray, mask: np.ndarray) -> np.ndarray: + """ + Args: + image: RGB image (H, W, 3). + mask: Binary mask (H, W), 255 = object to remove. + Returns: + Edge map (H, W), uint8, edges = 255. + """ + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + + # Apply Canny edge detection + edges = cv2.Canny(gray, self.canny_low, self.canny_high) + + # Zero-out edges inside the mask so only background structure remains + edges[mask > 127] = 0 + + return edges diff --git a/src/object_removal_ai/or_pipeline/mask_refiner.py b/src/object_removal_ai/or_pipeline/mask_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..a22359b5280fd4b1527f4529feec91781c2c176c --- /dev/null +++ b/src/object_removal_ai/or_pipeline/mask_refiner.py @@ -0,0 +1,56 @@ +import cv2 +import numpy as np + + +class MaskRefiner: + """ + Refines raw segmentation masks using morphological operations. + Ensures smooth edges and slightly expanded coverage to prevent + leftover object outline artifacts after inpainting. + """ + + def __init__( + self, + dilate_kernel: int = 15, + dilate_iter: int = 10, # Increased for massive context padding + close_kernel: int = 11, + blur_kernel: int = 31, # Large blur for soft alpha mask + ): + self.dilate_kernel = dilate_kernel + self.dilate_iter = dilate_iter + self.close_kernel = close_kernel + self.blur_kernel = blur_kernel + + def __call__(self, mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """ + Args: + mask: Binary mask (H, W), 255 = object. + Returns: + Tuple of: + - binary_mask: Expanded hard mask for LaMa inpainting + - alpha_mask: Soft blurred mask (0-1 float32) for edge blending + """ + # 1. Morphological closing โ€” fill tiny holes inside the mask + close_k = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, (self.close_kernel, self.close_kernel) + ) + closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_k) + + # 2. Dilation โ€” expand mask substantially for context padding + dilate_k = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, (self.dilate_kernel, self.dilate_kernel) + ) + expanded_mask = cv2.dilate(closed, dilate_k, iterations=self.dilate_iter) + + # Ensure binary hard mask for LaMa + _, binary_mask = cv2.threshold(expanded_mask, 127, 255, cv2.THRESH_BINARY) + + # 3. Soft Alpha Mask โ€” generated from the expanded mask for seamless edge blending + if self.blur_kernel > 0: + ksize = self.blur_kernel | 1 # ensure odd + soft_blurred = cv2.GaussianBlur(expanded_mask, (ksize, ksize), 0) + alpha_mask = soft_blurred.astype(np.float32) / 255.0 + else: + alpha_mask = binary_mask.astype(np.float32) / 255.0 + + return binary_mask, alpha_mask diff --git a/src/object_removal_ai/or_pipeline/postprocess.py b/src/object_removal_ai/or_pipeline/postprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..9ecdc009a5a3a54b1dc29cf193698208294e8be1 --- /dev/null +++ b/src/object_removal_ai/or_pipeline/postprocess.py @@ -0,0 +1,114 @@ +import cv2 +import numpy as np + + +class PostProcessor: + """ + Final post-processing stage: Full-Resolution Compositing & Denoising. + 1. Extracts the inpainted patch + 2. Upscales it to match the native resolution of the original image + 3. Denoisies the patch to remove SD hallucination artifacts + 4. Seamlessly blends it into the pristine original image (0% bg quality loss) + """ + + def __init__(self, use_poisson: bool = True): + self.use_poisson = use_poisson + + def __call__( + self, + true_original: np.ndarray, + inpainted: np.ndarray, + mask: np.ndarray, + alpha_mask: np.ndarray = None + ) -> np.ndarray: + """ + Args: + true_original: Original un-resized RGB image (H_orig, W_orig, 3). + inpainted: Inpainted/Generated RGB image (H_work, W_work, 3). + mask: Hard binary mask (H_work, W_work), 255 = generated region. + alpha_mask: Soft alpha mask (H_work, W_work), 0-1 float32. + """ + # 1. Clean up the generated patch (Spatially denoise SD artifacts) + inpainted_clean = self._denoise_and_sharpen(inpainted) + + # 2. Find bounding box of the modified region in the working resolution + coords = cv2.findNonZero(mask) + if coords is None: + # If nothing was modified, return exactly the original image + return true_original + + x, y, w, h = cv2.boundingRect(coords) + + # Ensure box is strictly within working bounds + x = max(0, x) + y = max(0, y) + w = min(mask.shape[1] - x, w) + h = min(mask.shape[0] - y, h) + + # Extract the modified patch + patch = inpainted_clean[y:y+h, x:x+w] + + # 3. Calculate mapping from working res to native res + orig_h, orig_w = true_original.shape[:2] + work_h, work_w = inpainted.shape[:2] + + # Compute exact bounding box in the original high-res image + scale_x = orig_w / work_w + scale_y = orig_h / work_h + + nx = int(x * scale_x) + ny = int(y * scale_y) + nw = int(w * scale_x) + nh = int(h * scale_y) + + # Ensure bounds are safe + nx = max(0, nx) + ny = max(0, ny) + nw = min(orig_w - nx, nw) + nh = min(orig_h - ny, nh) + + # Upscale patch to native resolution + patch_hires = cv2.resize(patch, (nw, nh), interpolation=cv2.INTER_CUBIC) + + # Upscale mask to native resolution + patch_mask = mask[y:y+h, x:x+w] + patch_mask_hires = cv2.resize(patch_mask, (nw, nh), interpolation=cv2.INTER_NEAREST) + + # Ensure mask boundary has no harsh black edges by dilating slightly into patch + patch_mask_hires = cv2.dilate(patch_mask_hires, np.ones((5,5), np.uint8), iterations=2) + + # 4. Composite safely + output = true_original.copy() + try: + if self.use_poisson: + center = (nx + nw // 2, ny + nh // 2) + # Poisson blending for seamless illumination + output = cv2.seamlessClone( + patch_hires, + output, + patch_mask_hires, + center, + cv2.NORMAL_CLONE + ) + else: + # Soft alpha fallback + patch_alpha = alpha_mask[y:y+h, x:x+w] + patch_alpha_hires = cv2.resize(patch_alpha, (nw, nh), interpolation=cv2.INTER_LINEAR) + patch_alpha_hires = np.expand_dims(patch_alpha_hires, -1) + + roi = output[ny:ny+nh, nx:nx+nw] + blended = (patch_hires * patch_alpha_hires) + (roi * (1 - patch_alpha_hires)) + output[ny:ny+nh, nx:nx+nw] = blended.astype(np.uint8) + + except Exception as e: + print(f"[PostProcessor] Blending failed, using hard copy fallback: {e}") + roi = output[ny:ny+nh, nx:nx+nw] + bin_mask = (patch_mask_hires > 127).astype(bool) + roi[bin_mask] = patch_hires[bin_mask] + + return output + + def _denoise_and_sharpen(self, img: np.ndarray) -> np.ndarray: + """Pass-through to preserve LaMa's natural texture generation.""" + return img + diff --git a/src/object_removal_ai/or_utils/__init__.py b/src/object_removal_ai/or_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db3e3278dabf73020f4a939cd10bdded2bc377e8 --- /dev/null +++ b/src/object_removal_ai/or_utils/__init__.py @@ -0,0 +1 @@ +# utils package diff --git a/src/object_removal_ai/or_utils/image_utils.py b/src/object_removal_ai/or_utils/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b58bafb37552bd36ecc8f4d76d1f09b084262f1 --- /dev/null +++ b/src/object_removal_ai/or_utils/image_utils.py @@ -0,0 +1,28 @@ +import cv2 +import numpy as np +from PIL import Image + + +def load_image(path: str) -> np.ndarray: + """Load an image from disk as RGB numpy array.""" + img = cv2.imread(path, cv2.IMREAD_COLOR) + if img is None: + raise FileNotFoundError(f"Could not load image: {path}") + return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + + +def save_image(image: np.ndarray, path: str) -> None: + """Save an RGB numpy array to disk.""" + bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + cv2.imwrite(path, bgr) + print(f" โ†’ Saved: {path}") + + +def resize_max(image: np.ndarray, max_size: int = 1024) -> np.ndarray: + """Resize image so that the longest side is at most max_size.""" + h, w = image.shape[:2] + if max(h, w) <= max_size: + return image + scale = max_size / max(h, w) + new_w, new_h = int(w * scale), int(h * scale) + return cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) diff --git a/src/shared/__init__.py b/src/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a48d523f37659c5f760f4e82c2138913303542cb --- /dev/null +++ b/src/shared/__init__.py @@ -0,0 +1 @@ +"""Shared utilities for all Creator AI pipelines.""" diff --git a/src/shared/image_utils.py b/src/shared/image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5cac695029bda37c5e3d1e104c133facb52b20e1 --- /dev/null +++ b/src/shared/image_utils.py @@ -0,0 +1,120 @@ +""" +Shared Image Utilities for Creator AI + +Consolidates common image operations used across all pipelines: +- Format conversion (RGB/BGR, uint8/float32) +- Safe resizing with aspect ratio preservation +- Image validation and normalization +""" +import cv2 +import numpy as np +from typing import Tuple, Optional + + +def rgb_to_bgr(image: np.ndarray) -> np.ndarray: + """Convert RGB image to BGR.""" + return cv2.cvtColor(image, cv2.COLOR_RGB2BGR) + + +def bgr_to_rgb(image: np.ndarray) -> np.ndarray: + """Convert BGR image to RGB.""" + return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + + +def ensure_rgb(image: np.ndarray) -> np.ndarray: + """Ensure image is RGB uint8 with 3 channels.""" + if image.ndim == 2: + image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) + elif image.shape[2] == 4: + image = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB) + + if image.dtype == np.uint16: + image = (image / 256).astype(np.uint8) + elif image.dtype in (np.float32, np.float64): + image = np.clip(image * 255, 0, 255).astype(np.uint8) + + return image + + +def ensure_uint8(image: np.ndarray) -> np.ndarray: + """Convert float image [0,1] to uint8 [0,255].""" + if image.dtype in (np.float32, np.float64): + return np.clip(image * 255, 0, 255).astype(np.uint8) + return image + + +def ensure_float32(image: np.ndarray) -> np.ndarray: + """Convert uint8 image [0,255] to float32 [0,1].""" + if image.dtype == np.uint8: + return image.astype(np.float32) / 255.0 + return image.astype(np.float32) + + +def safe_resize( + image: np.ndarray, + target_size: Tuple[int, int], + interpolation: int = cv2.INTER_LANCZOS4, +) -> np.ndarray: + """ + Resize image to target_size (width, height) safely. + + Uses INTER_AREA for downscaling and INTER_LANCZOS4 for upscaling + to avoid artifacts. + """ + h, w = image.shape[:2] + tw, th = target_size + + if tw < w or th < h: + interpolation = cv2.INTER_AREA + + return cv2.resize(image, (tw, th), interpolation=interpolation) + + +def resize_max_dim( + image: np.ndarray, + max_dim: int, + interpolation: int = cv2.INTER_AREA, +) -> np.ndarray: + """Resize image so its largest dimension equals max_dim, preserving aspect ratio.""" + h, w = image.shape[:2] + if max(h, w) <= max_dim: + return image + + scale = max_dim / max(h, w) + new_w = int(w * scale) + new_h = int(h * scale) + return cv2.resize(image, (new_w, new_h), interpolation=interpolation) + + +def pad_to_multiple( + image: np.ndarray, + multiple: int = 8, + pad_value: int = 0, +) -> Tuple[np.ndarray, Tuple[int, int]]: + """ + Pad image so dimensions are multiples of `multiple`. + + Returns: + (padded_image, (pad_h, pad_w)) โ€” padding amounts for unpadding later + """ + h, w = image.shape[:2] + pad_h = (multiple - h % multiple) % multiple + pad_w = (multiple - w % multiple) % multiple + + if pad_h == 0 and pad_w == 0: + return image, (0, 0) + + padded = cv2.copyMakeBorder( + image, 0, pad_h, 0, pad_w, + cv2.BORDER_REFLECT_101, + ) + return padded, (pad_h, pad_w) + + +def unpad(image: np.ndarray, padding: Tuple[int, int]) -> np.ndarray: + """Remove padding added by pad_to_multiple.""" + pad_h, pad_w = padding + if pad_h == 0 and pad_w == 0: + return image + h, w = image.shape[:2] + return image[:h - pad_h, :w - pad_w] diff --git a/src/shared/logging_config.py b/src/shared/logging_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c3fbb44189c39aec54948a3176c26e667acd3995 --- /dev/null +++ b/src/shared/logging_config.py @@ -0,0 +1,54 @@ +""" +Centralized Logging Configuration for Creator AI + +Usage: + from shared.logging_config import get_logger + logger = get_logger(__name__) + logger.info("Pipeline started") + logger.warning("GPU memory low") + logger.error("Model failed to load") +""" +import logging +import sys + + +_INITIALIZED = False + + +def _init_logging(): + """Initialize the root logger once.""" + global _INITIALIZED + if _INITIALIZED: + return + + root = logging.getLogger("creator_ai") + root.setLevel(logging.DEBUG) + + # Console handler with clean format + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.INFO) + formatter = logging.Formatter( + "[%(name)s] %(message)s", + datefmt="%H:%M:%S", + ) + handler.setFormatter(formatter) + root.addHandler(handler) + + _INITIALIZED = True + + +def get_logger(name: str) -> logging.Logger: + """ + Get a logger for a module. + + Args: + name: Module name (typically __name__) + + Returns: + Configured logger instance + """ + _init_logging() + # Prefix with creator_ai for namespace isolation + if not name.startswith("creator_ai"): + name = f"creator_ai.{name}" + return logging.getLogger(name) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..1410c2c134cdcb56aae74a6efed3bed0c6b42324 --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,141 @@ +""" +Integration tests for the Object Removal Pipeline. + +Usage: + python -m pytest tests/test_pipeline.py -v + OR + python tests/test_pipeline.py +""" + +import os +import sys +import cv2 +import numpy as np + +# Ensure imports work +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from object_removal_ai.main_pipeline import ObjectRemovalPipeline, resolve_weight_path +from object_removal_ai.pipeline.mask_refiner import MaskRefiner +from object_removal_ai.pipeline.edge_extractor import EdgeExtractor +from object_removal_ai.pipeline.postprocess import PostProcessor + + +def test_mask_refiner(): + """Test that MaskRefiner properly dilates and smooths a mask.""" + refiner = MaskRefiner(dilate_kernel=15, dilate_iter=3, close_kernel=9, blur_kernel=5) + + # Create a small binary mask + mask = np.zeros((100, 100), dtype=np.uint8) + mask[30:70, 30:70] = 255 # 40x40 white square + + refined = refiner(mask) + + assert refined.shape == (100, 100), f"Shape mismatch: {refined.shape}" + assert refined.dtype == np.uint8, f"Dtype mismatch: {refined.dtype}" + assert refined.sum() > mask.sum(), "Refined mask should be larger after dilation" + print("โœ… test_mask_refiner passed") + + +def test_edge_extractor(): + """Test that EdgeExtractor produces edges and zeroes the masked region.""" + extractor = EdgeExtractor(canny_low=50, canny_high=150) + + # Create a test image with clear edges (gradient) + image = np.zeros((100, 100, 3), dtype=np.uint8) + image[:, 50:] = 255 # Black/White vertical split + + mask = np.zeros((100, 100), dtype=np.uint8) + mask[40:60, 40:60] = 255 # Mask the center + + edges = extractor(image, mask) + + assert edges.shape == (100, 100), f"Shape mismatch: {edges.shape}" + assert edges[50, 50] == 0, "Edges inside mask should be zero" + print("โœ… test_edge_extractor passed") + + +def test_post_processor_alpha(): + """Test alpha blending mode.""" + processor = PostProcessor(use_poisson=False) + + original = np.full((100, 100, 3), 128, dtype=np.uint8) # Gray + inpainted = np.full((100, 100, 3), 200, dtype=np.uint8) # Light + mask = np.zeros((100, 100), dtype=np.uint8) + mask[30:70, 30:70] = 255 + + result = processor(original, inpainted, mask) + + assert result.shape == (100, 100, 3), f"Shape mismatch: {result.shape}" + assert result.dtype == np.uint8 + print("โœ… test_post_processor_alpha passed") + + +def test_resolve_weight_path(): + """Test that weight path resolution works for universal and local paths.""" + # Absolute paths should pass through + abs_path = os.path.abspath("model.pt") + p = resolve_weight_path(abs_path) + assert p == abs_path + + # HuggingFace model IDs should pass through + p = resolve_weight_path("runwayml/stable-diffusion-inpainting") + assert p == "runwayml/stable-diffusion-inpainting" + + print("โœ… test_resolve_weight_path passed") + + +def test_pipeline_with_mask(): + """Integration test: run pipeline with a user-provided mask on a synthetic image.""" + # Create synthetic test image (gradient background with a white square "object") + image = np.zeros((256, 256, 3), dtype=np.uint8) + # Gradient background + for i in range(256): + image[i, :] = [i, 128, 255 - i] + # White square "object" + image[80:180, 80:180] = [255, 255, 255] + + # Create mask for the object + mask = np.zeros((256, 256), dtype=np.uint8) + mask[80:180, 80:180] = 255 + + # Save test files + os.makedirs("test_output", exist_ok=True) + cv2.imwrite("test_output/synthetic_input.jpg", cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + cv2.imwrite("test_output/synthetic_mask.png", mask) + + try: + pipeline = ObjectRemovalPipeline() + result = pipeline.run(image, mask=mask) + + assert result["result"].shape == image.shape[:2] + (3,), "Output shape mismatch" + assert result["mask"] is not None, "Mask artifact should be present" + + # The object area should NOT be pure white anymore after inpainting + result_region = result["result"][100:160, 100:160] + assert not np.all(result_region == 255), "Inpainted region should not be pure white" + + cv2.imwrite("test_output/synthetic_clean.jpg", cv2.cvtColor(result["result"], cv2.COLOR_RGB2BGR)) + print("โœ… test_pipeline_with_mask passed") + print(f" Output saved: test_output/synthetic_clean.jpg") + except FileNotFoundError as e: + print(f"โš ๏ธ test_pipeline_with_mask skipped (missing weights): {e}") + except Exception as e: + print(f"โŒ test_pipeline_with_mask failed: {e}") + raise + + +if __name__ == "__main__": + print("=" * 50) + print(" Running Object Removal Pipeline Tests") + print("=" * 50) + + test_mask_refiner() + test_edge_extractor() + test_post_processor_alpha() + test_resolve_weight_path() + test_pipeline_with_mask() + + print("\n" + "=" * 50) + print(" All tests completed!") + print("=" * 50) diff --git a/tests/test_text_removal.py b/tests/test_text_removal.py new file mode 100644 index 0000000000000000000000000000000000000000..17e9de48db3da6bc36acc8ad5683f466bc83121a --- /dev/null +++ b/tests/test_text_removal.py @@ -0,0 +1,66 @@ +import os +import sys +import numpy as np +import cv2 + +# Ensure project root is in sys.path +script_dir = os.path.dirname(os.path.abspath(__file__)) +workspace_root = os.path.abspath(os.path.join(script_dir, "..")) +if workspace_root not in sys.path: + sys.path.insert(0, workspace_root) +ai_text_dir = os.path.join(workspace_root, "ai_text_removal") +if ai_text_dir not in sys.path: + sys.path.insert(0, ai_text_dir) + +from ai_text_removal.pipeline import TextRemovalPipeline +from ai_text_removal.pipelines.inpaint import LaMaInpainter +from ai_text_removal.utils.mask_utils import refine_mask + +def test_mask_generation(): + print("Running test: Mask Generation (Soft Edge)...") + # Simulate a hard binary mask + h, w = 200, 200 + hard_mask = np.zeros((h, w), dtype=np.uint8) + hard_mask[50:150, 50:150] = 255 + + # Run through refiner + soft_mask = refine_mask(hard_mask, dilate_kernel=11, dilate_iter=3, blur_kernel=15) + + # Check if soft + unique_vals = np.unique(soft_mask) + assert len(unique_vals) > 2, "Mask should be soft, but only found binary-like values." + print("โœ… Mask generation is properly softened.") + +def test_inpaint_routing(): + print("Running test: Inpaint Routing logic...") + # Mock LaMaInpainter simply logs if no models load. + # Instantiate without models to just test the flow + inpainter = LaMaInpainter(model_path="", std_model_path="", device="cpu") + + # The image is 1000x1000, 1M pixels + img = np.zeros((1000, 1000, 3), dtype=np.uint8) + + # Case 1: Mask is 2% (Standard LaMa) + small_mask = np.zeros((1000, 1000), dtype=np.uint8) + small_mask[0:100, 0:200] = 255 # 20,000 px = 2% + + # Case 2: Mask is 10% (Big LaMa) + large_mask = np.zeros((1000, 1000), dtype=np.uint8) + large_mask[0:300, 0:333] = 255 # ~100k px = 10% + + try: + # We expect fallback cv2 to trigger, we just want to ensure + # it doesn't crash computing the mask_ratio. + res1 = inpainter(img, small_mask, multi_scale=False) + res2 = inpainter(img, large_mask, multi_scale=False) + assert res1.shape == img.shape + assert res2.shape == img.shape + print("โœ… Inpaint logic processes varying mask sizes successfully.") + except Exception as e: + print(f"โŒ Inpaint routing failed: {e}") + raise + +if __name__ == "__main__": + test_mask_generation() + test_inpaint_routing() + print("\nAll unit tests passed successfully!")