Spaces:
Runtime error
Runtime error
AbhishekBhardwaj commited on
Commit ·
cd66d8c
1
Parent(s): d443b64
Initialize Creator AI production architecture
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignoreAdded+44
- DockerfileAdded+22
- README.mdAdded+428
- assets/banner.pngAdded
- download_weights.pyAdded+19
- libs/BasicSRAdded+1
- libs/CodeFormerAdded+1
- requirements.txtAdded+42
- src/ai_image_dashboard/__init__.pyAdded+1
- src/ai_image_dashboard/app/__init__.pyAdded+1
- src/ai_image_dashboard/app/config.pyAdded+54
- src/ai_image_dashboard/app/streamlit_app.pyAdded+752
- src/ai_image_dashboard/pipelines/__init__.pyAdded+1
- src/ai_image_dashboard/pipelines/background_pipeline.pyAdded+56
- src/ai_image_dashboard/pipelines/color_pipeline.pyAdded+46
- src/ai_image_dashboard/pipelines/object_pipeline.pyAdded+35
- src/ai_image_dashboard/pipelines/super_resolution_pipeline.pyAdded+48
- src/ai_image_dashboard/pipelines/text_removal_pipeline.pyAdded+34
- src/ai_image_dashboard/utils/__init__.pyAdded+1
- src/ai_image_dashboard/utils/image_utils.pyAdded+34
- src/ai_super_resolution/configs/config.yamlAdded+66
- src/ai_super_resolution/inference.pyAdded+81
- src/ai_super_resolution/models/__init__.pyAdded+1
- src/ai_super_resolution/models/codeformer_enhancer.pyAdded+244
- src/ai_super_resolution/models/diffusion_refiner.pyAdded+210
- src/ai_super_resolution/models/swinir_refiner.pyAdded+255
- src/ai_super_resolution/models/upsampler.pyAdded+171
- src/ai_super_resolution/sr_pipeline.pyAdded+357
- src/ai_super_resolution/stages/__init__.pyAdded+1
- src/ai_super_resolution/stages/color_matcher.pyAdded+106
- src/ai_super_resolution/stages/denoiser.pyAdded+65
- src/ai_super_resolution/stages/input_validator.pyAdded+134
- src/ai_super_resolution/stages/post_processor.pyAdded+85
- src/ai_super_resolution/stages/quality_analyzer.pyAdded+173
- src/ai_super_resolution/stages/tile_engine.pyAdded+144
- src/ai_super_resolution/utils/image_utils.pyAdded+31
- src/ai_text_removal/README.mdAdded+42
- src/ai_text_removal/configs/config.yamlAdded+35
- src/ai_text_removal/inference.pyAdded+205
- src/ai_text_removal/requirements.txtAdded+26
- src/ai_text_removal/tr_pipeline.pyAdded+222
- src/ai_text_removal/tr_pipelines/__init__.pyAdded
- src/ai_text_removal/tr_pipelines/detect_text.pyAdded+117
- src/ai_text_removal/tr_pipelines/diffusion_refine.pyAdded+128
- src/ai_text_removal/tr_pipelines/edge_extract.pyAdded+51
- src/ai_text_removal/tr_pipelines/inpaint.pyAdded+88
- src/ai_text_removal/tr_pipelines/post_process.pyAdded+119
- src/ai_text_removal/tr_pipelines/preprocess.pyAdded+22
- src/ai_text_removal/tr_pipelines/refine_mask.pyAdded+26
- src/ai_text_removal/tr_pipelines/segment_mask.pyAdded+78
1234567891011121314151617181920212223242526272829303132333435363738394041424344# Python__pycache__/*.py[cod]*.egg-info/*.eggdist/build/*.so
# Virtual Environmentvenv/.venv/env/
# IDE.vscode/.idea/*.swp*.swo
# Model Weights (large files)weights/*.pth*.ckpt*.safetensors*.bin
# OneDrive.~lock.*~$*
# OS.DS_StoreThumbs.dbdesktop.ini
# Logs & Outputsoutputs/logs/*.log
# Temporary/tmp/*.tmp12345678910111213141516171819202122FROM nvidia/cuda:12.4.0-runtime-ubuntu22.04
WORKDIR /app
# System dependenciesRUN 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 dependenciesCOPY requirements.txt .RUN pip3 install --no-cache-dir -r requirements.txt
# Application codeCOPY src/ ./src/COPY libs/ ./libs/COPY weights/ ./weights/
# Entry pointEXPOSE 8501CMD ["python3", "-m", "streamlit", "run", "src/ai_image_dashboard/app/streamlit_app.py", "--server.address", "0.0.0.0", "--server.port", "8501"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428<p align="center"> <img src="assets/banner.png" alt="Creator AI Banner" width="100%"></p>
<p align="center"> <b>A professional-grade AI image processing suite powered by 12+ state-of-the-art deep learning models.</b></p>
<p align="center"> <img src="https://img.shields.io/badge/Python-3.10+-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python"> <img src="https://img.shields.io/badge/PyTorch-2.0+-EE4C2C?style=for-the-badge&logo=pytorch&logoColor=white" alt="PyTorch"> <img src="https://img.shields.io/badge/CUDA-12.x-76B900?style=for-the-badge&logo=nvidia&logoColor=white" alt="CUDA"> <img src="https://img.shields.io/badge/Streamlit-Dashboard-FF4B4B?style=for-the-badge&logo=streamlit&logoColor=white" alt="Streamlit"> <img src="https://img.shields.io/badge/Lines_of_Code-8.7K+-blue?style=for-the-badge" alt="LOC"></p>
---
## 🎯 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 ProblemTraditional AI image tools either:- Run a single model (limited quality)- Run everything blindly (slow, wastes GPU)- Require command-line expertise
### The SolutionCreator 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 RemovalDetects 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 RemovalAccepts **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 CorrectionCombines **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 RemovalA 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 repositorygit clone https://github.com/yourusername/creator-ai.gitcd creator-ai
# 2. Create and activate virtual environmentpython -m venv venv
# Windowsvenv\Scripts\activate
# Linux/macOSsource venv/bin/activate
# 3. Install PyTorch with CUDA supportpip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
# 4. Install dependenciespip install -r requirements.txt
# 5. Download model weights (auto-downloads on first use, or pre-download)python download_weights.py```
### Launch the Dashboard
```bashcd src/ai_image_dashboardpython -m streamlit run app/streamlit_app.py```
The dashboard will open at `http://localhost:8501`.
### Docker Deployment
```bashdocker 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 suitepython -m pytest tests/ -v
# Quick smoke test for SR pipelinepython -c "from ai_super_resolution.sr_pipeline import SuperResolutionPipelineimport yaml, numpy as np
config = yaml.safe_load(open('src/ai_super_resolution/configs/config.yaml'))pipeline = SuperResolutionPipeline(config)
# Test with a random imagetest_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.
---
<p align="center"> Built with ❤️ using PyTorch, Streamlit, and 12+ state-of-the-art AI models</p>12345678910111213141516171819import urllib.requestimport 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}")1Subproject commit 8d56e3a045f9fb3e1d8872f92ee4a4f07f886b0a1Subproject commit b33cc7d639d6545bfcccc7e0bc6ae51f24e79c2b123456789101112131415161718192021222324252627282930313233343536373839404142# ═══════════════════════════════════════════# Creator AI — Dependencies# ═══════════════════════════════════════════
# Coretorch>=2.0.0torchvision>=0.15.0numpy>=1.24.0opencv-python>=4.8.0Pillow>=10.0.0pyyaml>=6.0
# Dashboardstreamlit>=1.30.0
# Super Resolutionspandrel>=0.3.0 # Model loading (RealESRGAN, SwinIR)facexlib>=0.3.0 # Face detection + restoration helperslpips>=0.1.4 # Perceptual loss (CodeFormer dependency)diffusers>=0.25.0 # Stable Diffusion upscalertransformers>=4.35.0 # HuggingFace modelsaccelerate>=0.25.0 # Model loading optimizationsafetensors>=0.4.0 # Safe model format
# Text Removalcraft-text-detector>=0.4.3 # Text detection
# Object Removalgroundingdino-py>=0.4.0 # Object detectionultralytics>=8.0.0 # YOLOv8 fallback detector
# Background Removalkornia>=0.6.0 # Geometry / vision utilities
# Color Correction# (uses models included in libs/)
# Utilitieshuggingface-hub>=0.20.0 # Weight downloadsscipy>=1.10.0 # Signal processingscikit-image>=0.21.0 # Image metricstqdm>=4.65.0 # Progress bars1# AI Image Dashboard1# App subpackage123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""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 directoriesSUPER_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", },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752"""CreatorAI — Unified AI Image Processing Studio"""import streamlit as stimport osimport sysimport timeimport numpy as npimport cv2import 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_safefrom 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("""<style> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
/* ── Reset & Base ── */ .stApp { font-family: 'Inter', -apple-system, sans-serif; background: #0A0A0F; }
/* ── Sidebar ── */ section[data-testid="stSidebar"] { background: linear-gradient(180deg, #0D0D14 0%, #111118 100%) !important; border-right: 1px solid rgba(255,255,255,0.04) !important; width: 300px !important; } section[data-testid="stSidebar"] > div { padding-top: 1rem !important; }
/* ── Sidebar Brand ── */ .sidebar-brand { text-align: center; padding: 1.2rem 1rem 1rem; margin-bottom: 0.5rem; } .sidebar-brand h2 { margin: 0; font-size: 1.6rem; font-weight: 800; letter-spacing: -0.5px; background: linear-gradient(135deg, #A78BFA, #7C3AED, #EC4899); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .sidebar-brand p { margin: 0.3rem 0 0; font-size: 0.7rem; color: #4B5563; letter-spacing: 2px; text-transform: uppercase; font-weight: 500; }
/* ── Sidebar Dividers ── */ .sidebar-section-label { font-size: 0.65rem; color: #6B7280; text-transform: uppercase; letter-spacing: 1.5px; font-weight: 600; padding: 0.8rem 0 0.4rem; margin-top: 0.5rem; }
.sidebar-divider { border: none; height: 1px; background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.2), transparent); margin: 0.6rem 0; }
/* ── Tool Buttons (sidebar) ── */ section[data-testid="stSidebar"] .stButton > button { background: rgba(255,255,255,0.03) !important; border: 1px solid rgba(255,255,255,0.06) !important; border-radius: 10px !important; color: #9CA3AF !important; font-weight: 500 !important; font-size: 0.88rem !important; padding: 0.7rem 1rem !important; text-align: left !important; transition: all 0.25s ease !important; margin-bottom: 0.15rem !important; } section[data-testid="stSidebar"] .stButton > button:hover { background: rgba(139, 92, 246, 0.08) !important; border-color: rgba(139, 92, 246, 0.25) !important; color: #E5E7EB !important; transform: translateX(3px) !important; }
/* ── Active tool highlight ── */ .active-tool-btn > button { background: linear-gradient(135deg, rgba(139,92,246,0.15), rgba(236,72,153,0.08)) !important; border-color: rgba(139, 92, 246, 0.4) !important; color: #E5E7EB !important; box-shadow: 0 0 20px rgba(139, 92, 246, 0.1) !important; }
/* ── Main content buttons ── */ .main-action > button { background: linear-gradient(135deg, #7C3AED, #A78BFA) !important; color: white !important; border: none !important; border-radius: 12px !important; padding: 0.75rem 2rem !important; font-weight: 700 !important; font-size: 0.95rem !important; letter-spacing: 0.3px !important; box-shadow: 0 4px 20px rgba(124, 58, 237, 0.3) !important; transition: all 0.3s ease !important; } .main-action > button:hover { box-shadow: 0 6px 30px rgba(124, 58, 237, 0.45) !important; transform: translateY(-2px) !important; }
.secondary-btn > button { background: rgba(255,255,255,0.05) !important; color: #9CA3AF !important; border: 1px solid rgba(255,255,255,0.08) !important; border-radius: 10px !important; }
/* ── Header ── */ .main-header { background: linear-gradient(135deg, #0F0A1A 0%, #1A1025 50%, #0F0A1A 100%); border: 1px solid rgba(139, 92, 246, 0.15); border-radius: 20px; padding: 2.5rem 3rem; margin-bottom: 1.8rem; position: relative; overflow: hidden; } .main-header::before { content: ''; position: absolute; top: -50%; right: -20%; width: 300px; height: 300px; background: radial-gradient(circle, rgba(139, 92, 246, 0.08) 0%, transparent 70%); border-radius: 50%; } .main-header h1 { margin: 0; font-size: 2.2rem; font-weight: 800; background: linear-gradient(135deg, #C4B5FD, #A78BFA, #EC4899); -webkit-background-clip: text; -webkit-text-fill-color: transparent; position: relative; } .main-header .subtitle { color: #6B7280; font-size: 0.95rem; margin-top: 0.5rem; font-weight: 300; position: relative; }
/* ── Status Chip ── */ .status-chip { display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); border-radius: 100px; padding: 0.45rem 1rem; margin: 1rem 0 0.5rem; font-size: 0.78rem; color: #9CA3AF; } .status-chip .dot { width: 7px; height: 7px; border-radius: 50%; background: #10B981; box-shadow: 0 0 8px rgba(16, 185, 129, 0.5); } .status-chip .dot.cpu { background: #F59E0B; box-shadow: 0 0 8px rgba(245, 158, 11, 0.5); }
/* ── Card Container ── */ .feature-card { background: linear-gradient(145deg, rgba(255,255,255,0.02), rgba(255,255,255,0.01)); border: 1px solid rgba(255,255,255,0.05); border-radius: 16px; padding: 1.8rem; text-align: center; transition: all 0.3s ease; height: 200px; display: flex; flex-direction: column; justify-content: center; } .feature-card:hover { border-color: rgba(139, 92, 246, 0.2); transform: translateY(-4px); box-shadow: 0 12px 40px rgba(0,0,0,0.3); } .feature-card .icon { font-size: 2rem; margin-bottom: 0.6rem; } .feature-card .name { font-weight: 700; font-size: 0.95rem; color: #E5E7EB; margin-bottom: 0.3rem; } .feature-card .desc { font-size: 0.72rem; color: #6B7280; line-height: 1.4; }
/* ── Image Frame ── */ .img-frame { background: #0D0D12; border: 1px solid rgba(255,255,255,0.04); border-radius: 14px; padding: 0.6rem; margin: 0.5rem 0; } .img-label { font-size: 0.7rem; color: #6B7280; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; margin-bottom: 0.4rem; }
/* ── Metric boxes ── */ .metric-row { display: flex; gap: 0.8rem; margin: 0.8rem 0; } .metric-box { flex: 1; background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.04); border-radius: 10px; padding: 0.8rem; text-align: center; } .metric-box .value { font-size: 1.1rem; font-weight: 700; color: #A78BFA; } .metric-box .label { font-size: 0.65rem; color: #6B7280; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.2rem; }
/* ── Processing animation ── */ .proc-text { color: #A78BFA; font-weight: 600; font-size: 0.9rem; }
/* ── Hide Streamlit chrome (preserve sidebar toggle) ── */ #MainMenu {visibility: hidden;} footer {visibility: hidden;} .stDeployButton {display: none;} /* Keep header visible so sidebar toggle arrow works */ header[data-testid="stHeader"] { background: transparent !important; backdrop-filter: none !important; }
/* ── Spinner override ── */ .stSpinner > div { border-top-color: #7C3AED !important; }</style>""", unsafe_allow_html=True)
# ═══════════════════════════════════════════════════════════════# Session State# ═══════════════════════════════════════════════════════════════if "current_tool" not in st.session_state: st.session_state.current_tool = Noneif "original_image" not in st.session_state: st.session_state.original_image = Noneif "processed_image" not in st.session_state: st.session_state.processed_image = Noneif "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_resourcedef load_super_resolution(): from pipelines import super_resolution_pipeline return super_resolution_pipeline.get_pipeline()
@st.cache_resourcedef load_text_removal(): from pipelines import text_removal_pipeline return text_removal_pipeline.get_pipeline()
@st.cache_resourcedef load_color_correction(): from pipelines import color_pipeline return color_pipeline.get_pipeline()
@st.cache_resourcedef load_object_removal(): from pipelines import object_pipeline return object_pipeline.get_pipeline()
@st.cache_resourcedef load_background_removal(): from pipelines import background_pipeline return background_pipeline.get_pipeline()
# ═══════════════════════════════════════════════════════════════# SIDEBAR# ═══════════════════════════════════════════════════════════════with st.sidebar: # ── Brand ── st.markdown(""" <div class="sidebar-brand"> <h2>🚀 CreatorAI</h2> <p>Image Studio</p> </div> <hr class="sidebar-divider"> """, 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""" <div class="status-chip"> <div class="{dot_class}"></div> <span>{status_text}</span> </div> """, unsafe_allow_html=True)
st.markdown("") # spacer
# ── Tool Selection ── st.markdown('<div class="sidebar-section-label">🎯 AI Tools</div>', unsafe_allow_html=True) st.markdown('<hr class="sidebar-divider">', 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'<div class="active-tool-btn">', 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('</div>', unsafe_allow_html=True)
# ── History ── if st.session_state.history: st.markdown("") st.markdown("") st.markdown('<div class="sidebar-section-label">📜 Recent</div>', unsafe_allow_html=True) st.markdown('<hr class="sidebar-divider">', 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(""" <div class="main-header"> <h1>🚀 CreatorAI Studio</h1> <div class="subtitle"> Production-grade AI image processing. Select a tool from the sidebar to begin. </div> </div> """, unsafe_allow_html=True)
cols = st.columns(5, gap="medium") for i, (key, info) in enumerate(TOOLS.items()): with cols[i]: st.markdown(f""" <div class="feature-card"> <div class="icon">{info['icon']}</div> <div class="name">{info['name']}</div> <div class="desc">{info['description']}</div> </div> """, unsafe_allow_html=True)
else: # ────────────────────────────────────────────────────────── # Tool Processing Page # ────────────────────────────────────────────────────────── tool = TOOLS[st.session_state.current_tool]
# ── Mini Header ── st.markdown(f""" <div style="display:flex; align-items:center; gap:0.8rem; margin-bottom:1.2rem;"> <span style="font-size:1.8rem;">{tool['icon']}</span> <div> <div style="font-size:1.3rem; font-weight:700; color:#E5E7EB;">{tool['name']}</div> <div style="font-size:0.8rem; color:#6B7280;">{tool['description']}</div> </div> </div> """, 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("<br>", unsafe_allow_html=True) bg_show_metrics = st.toggle("📊 Show Latency Metrics", value=True, help="Display per-stage timing breakdown") st.markdown("<br>", 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('<div class="main-action">', unsafe_allow_html=True) process_btn = st.button( f"⚡ Process with {tool['name']}", width='stretch', key="process_btn", ) st.markdown('</div>', unsafe_allow_html=True)
with act_col2: st.markdown('<div class="secondary-btn">', unsafe_allow_html=True) reset_btn = st.button("🔄 Reset", width='stretch', key="reset_btn") st.markdown('</div>', 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""" <div style="text-align:center; padding:0.5rem;"> <span style="color:#10B981; font-weight:700; font-size:1.1rem;"> {st.session_state.process_time:.1f}s </span> <br> <span style="color:#6B7280; font-size:0.65rem; text-transform:uppercase; letter-spacing:1px;"> Process Time </span> </div> """, 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('<div class="img-label">📷 Original</div>', unsafe_allow_html=True) st.markdown('<div class="img-frame">', unsafe_allow_html=True) st.image(img_rgb, width='stretch') st.markdown('</div>', unsafe_allow_html=True) oh, ow = img_rgb.shape[:2] st.caption(f"{ow} × {oh} px")
with col2: st.markdown('<div class="img-label">✨ Processed</div>', unsafe_allow_html=True) st.markdown('<div class="img-frame">', unsafe_allow_html=True) processed = st.session_state.processed_image st.image(processed, width='stretch') st.markdown('</div>', 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""" <div style="margin-top:1.2rem;"> <div style="display:flex; align-items:center; gap:0.6rem; margin-bottom:0.8rem;"> <span style="font-size:0.75rem; font-weight:700; color:#6B7280; text-transform:uppercase; letter-spacing:1px;">Pipeline Metrics</span> <span style="background:{scene_color}22; border:1px solid {scene_color}44; color:{scene_color}; padding:0.2rem 0.7rem; border-radius:100px; font-size:0.7rem; font-weight:700;">{scene_type}</span> </div> <div class="metric-row"> <div class="metric-box"> <div class="value">{m.get('stage2_birefnet_ms', 0):.0f}ms</div> <div class="label">BiRefNet SOD</div> </div> <div class="metric-box"> <div class="value">{m.get('stage3_routing_ms', 0):.1f}ms</div> <div class="label">Scene Routing</div> </div> <div class="metric-box"> <div class="value">{m.get('stage3b_sam_ms', 0):.0f}ms</div> <div class="label">SAM Segment</div> </div> <div class="metric-box"> <div class="value">{m.get('stage4_matting_ms', 0):.0f}ms</div> <div class="label">MODNet Alpha</div> </div> <div class="metric-box"> <div class="value">{m.get('stage5_postprocess_ms', 0):.0f}ms</div> <div class="label">Postprocess</div> </div> </div> </div> """, unsafe_allow_html=True)
else: # ── Just show the uploaded image ── st.markdown('<div class="img-label">📷 Uploaded Image</div>', unsafe_allow_html=True) st.markdown('<div class="img-frame">', unsafe_allow_html=True) st.image(img_rgb, width='stretch') st.markdown('</div>', unsafe_allow_html=True) oh, ow = img_rgb.shape[:2] st.caption(f"{ow} × {oh} px • Ready to process")
else: # ── Empty state ── st.markdown(""" <div style="text-align:center; padding:4rem 2rem; color:#4B5563;"> <div style="font-size:3rem; margin-bottom:1rem;">📁</div> <div style="font-size:1.1rem; font-weight:600; color:#6B7280;"> Upload an image to get started </div> <div style="font-size:0.85rem; margin-top:0.5rem;"> Supports JPG, PNG, BMP, WEBP — up to 200MB </div> </div> """, unsafe_allow_html=True)1# Pipelines subpackage1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Background Removal Pipeline — 5-Stage Adaptive EngineUses 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-gradePhotoroom-style adaptive pipeline."""import sysimport osimport 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"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Color Correction Pipeline WrapperDelegates to: src/hybrid_color_correction/pipeline/enhance.HybridEnhancer"""import sysimport osimport numpy as npimport 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)1234567891011121314151617181920212223242526272829303132333435"""Object Removal Pipeline WrapperDelegates to: src/object_removal_ai/main_pipeline.ObjectRemovalPipeline"""import sysimport osimport 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"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Super Resolution Pipeline WrapperDelegates to: src/ai_super_resolution/sr_pipeline.SuperResolutionPipeline"""import sysimport osimport yamlimport 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)12345678910111213141516171819202122232425262728293031323334"""Text Removal Pipeline WrapperDelegates to: src/ai_text_removal/tr_pipeline.TextRemovalPipeline"""import sysimport osimport 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"]1# Utils subpackage12345678910111213141516171819202122232425262728293031323334"""Unified image utilities for the AI Image Dashboard."""import cv2import 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# ═══════════════════════════════════════════════════════════════# 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 removal123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""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 osimport sysimport argparseimport yamlimport time
# Add current dir to path for importsscript_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_imagefrom 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()1# AI Super-Resolution — Model Wrappers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""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 osimport cv2import torchimport numpy as npimport logging
logger = logging.getLogger("creator_ai.codeformer_enhancer")
try: from facexlib.utils.face_restoration_helper import FaceRestoreHelper HAS_FACEXLIB = Trueexcept ImportError: HAS_FACEXLIB = False
try: from huggingface_hub import hf_hub_download HAS_HF_HUB = Trueexcept 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.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""Stable Diffusion x4 Upscaler — Texture Reconstruction Module
Uses StableDiffusionUpscalePipeline to generate photorealistic textureson 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 osimport cv2import torchimport numpy as npfrom PIL import Imageimport logging
logger = logging.getLogger("creator_ai.diffusion_refiner")
try: from diffusers import StableDiffusionUpscalePipeline HAS_DIFFUSERS = Trueexcept 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.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""SwinIR Transformer Refinement Module
Applies SwinIR (Image Restoration Using Swin Transformer) afterGAN 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 osimport cv2import torchimport numpy as npimport logging
logger = logging.getLogger("creator_ai.swinir_refiner")
try: from spandrel import ModelLoader HAS_SPANDREL = Trueexcept ImportError: HAS_SPANDREL = False
try: from huggingface_hub import hf_hub_download HAS_HF_HUB = Trueexcept 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.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Module 7 — RealESRGAN Upsampler (spandrel-based)
Uses spandrel to load RealESRGAN weights directly, bypassing thebasicsr dependency that's incompatible with Python 3.13."""import osimport cv2import torchimport numpy as npimport logging
logger = logging.getLogger("creator_ai.upsampler")
try: from spandrel import ModelLoader HAS_SPANDREL = Trueexcept 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357"""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 osimport gcimport cv2import torchimport numpy as npimport time
# Stage importsfrom stages.input_validator import InputValidatorfrom stages.denoiser import Denoiserfrom stages.tile_engine import TileEnginefrom stages.color_matcher import ColorMatcherfrom stages.post_processor import PostProcessorfrom stages.quality_analyzer import QualityAnalyzer
# Model importsfrom models.upsampler import Upsamplerfrom models.codeformer_enhancer import CodeFormerEnhancerfrom models.swinir_refiner import SwinIRRefinerfrom models.diffusion_refiner import DiffusionTextureRefinerimport 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 fused1# AI Super-Resolution — Pipeline Stages123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Module 11 — Color Preservation (Histogram Matching)
Prevents GAN-induced color shifts by matching the output'scolor distribution to the original input in LAB color space."""import cv2import numpy as npimport 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Module 4 — Noise & Artifact Removal (Learned Denoiser)
Uses an AI model rather than classic OpenCV filters to cleaninput images before upscaling, preventing noise amplificationwithout destroying fine texture."""import cv2import torchimport numpy as npimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""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, computesthe optimal working resolution based on the target output scaleand GPU capacity. This prevents the catastrophic case where ahigh-res input gets downscaled then upscaled back to a SMALLER size."""import cv2import numpy as npimport 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, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Module 12 — Adaptive Post-Processing
Final polishing stage with edge-aware smoothing and controlled sharpening.Replaces the old destructive cv2.addWeighted approach."""import cv2import numpy as npimport 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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Image Quality Analyzer — Smart Routing for Super-Resolution
Lightweight analysis module that extracts quality metrics from an inputimage 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 cv2import numpy as npimport 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 routing123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""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 cv2import numpy as npimport mathimport 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)12345678910111213141516171819202122232425262728293031import cv2import numpy as npimport osfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142# 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```bashpip install -r requirements.txtpip install diffusers transformers accelerate```
### 2. Required WeightsThe 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. UsageRun on your image (replace `your_image.jpg` with your actual filename):```bashpython 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.
## 🛠️ Architecture1. **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).*1234567891011121314151617181920212223242526272829303132333435pipeline: 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""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 osimport sysimport argparseimport yamlimport time
# Ensure project root is in sys.path for robust importsscript_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_imagefrom tr_pipelines.detect_text import TextDetectorfrom tr_pipelines.segment_mask import TextMaskGeneratorfrom tr_pipelines.refine_mask import MaskRefinerfrom tr_pipelines.edge_extract import EdgeExtractorfrom tr_pipelines.inpaint import LaMaInpainterfrom tr_pipelines.diffusion_refine import DiffusionRefinerfrom 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()1234567891011121314151617181920212223242526# Install torch/torchvision with CUDA support:# pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124torch>=2.0.0torchvision>=0.15.0# Use the headless variant if no display server is availableopencv-python-headless>=4.8.0numpy>=1.24.0Pillow>=10.0.0scikit-image>=0.21.0matplotlib>=3.7.0tqdm>=4.65.0diffusers>=0.21.0transformers>=4.33.0accelerate>=0.23.0onnxruntime>=1.15.0craft-text-detector>=0.4.2segment-anything>=1.0gdown>=4.6.0
# --- Object Removal Pipeline Specific ---ultralytics>=8.0.0 # YOLOv8 for Object DetectionMobileSAM>=1.0.0 # Fast alternative to SAM for Object Segmentationtimm>=0.6.12 # Required for MiDaS Depth Estimationomegaconf>=2.1.1 # Required for Big-LaMa configuration parsingpytorch-lightning>=1.5.0 # Required for Big-LaMa training/inference logickornia>=0.6.0 # Geometry routines sometimes used by LaMa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""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 osimport cv2import yamlimport numpy as np
from tr_utils.image_utils import load_image, resize_imagefrom tr_pipelines.detect_text import TextDetectorfrom tr_pipelines.segment_mask import TextMaskGeneratorfrom tr_pipelines.refine_mask import MaskRefinerfrom tr_pipelines.inpaint import LaMaInpainterfrom 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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117"""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 npimport cv2
try: import easyocrexcept 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 polygons123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""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 npimport cv2import torchfrom PIL import Image
try: from diffusers import StableDiffusionInpaintPipelineexcept 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_np123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import cv2import 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_map12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""LaMa Inpainting — Pure structural reconstruction.
Returns raw LaMa output for the FULL image.Compositing is handled by the pipeline orchestrator."""import osimport cv2import numpy as npimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import cv2import 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 img12345678910111213141516171819202122import numpy as npfrom tr_utils.image_utils import resize_image, normalize_to_tensorimport 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_img1234567891011121314151617181920212223242526import numpy as npfrom 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 )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""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 cv2import 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.gitignoreAdded+44
DockerfileAdded+22
README.mdAdded+428
assets/banner.pngAdded

download_weights.pyAdded+19
libs/BasicSRAdded+1
libs/CodeFormerAdded+1
requirements.txtAdded+42
src/ai_image_dashboard/__init__.pyAdded+1
src/ai_image_dashboard/app/__init__.pyAdded+1
src/ai_image_dashboard/app/config.pyAdded+54
src/ai_image_dashboard/app/streamlit_app.pyAdded+752
src/ai_image_dashboard/pipelines/__init__.pyAdded+1
src/ai_image_dashboard/pipelines/background_pipeline.pyAdded+56
src/ai_image_dashboard/pipelines/color_pipeline.pyAdded+46
src/ai_image_dashboard/pipelines/object_pipeline.pyAdded+35
src/ai_image_dashboard/pipelines/super_resolution_pipeline.pyAdded+48
src/ai_image_dashboard/pipelines/text_removal_pipeline.pyAdded+34
src/ai_image_dashboard/utils/__init__.pyAdded+1
src/ai_image_dashboard/utils/image_utils.pyAdded+34
src/ai_super_resolution/configs/config.yamlAdded+66
src/ai_super_resolution/inference.pyAdded+81
src/ai_super_resolution/models/__init__.pyAdded+1
src/ai_super_resolution/models/codeformer_enhancer.pyAdded+244
src/ai_super_resolution/models/diffusion_refiner.pyAdded+210
src/ai_super_resolution/models/swinir_refiner.pyAdded+255
src/ai_super_resolution/models/upsampler.pyAdded+171
src/ai_super_resolution/sr_pipeline.pyAdded+357
src/ai_super_resolution/stages/__init__.pyAdded+1
src/ai_super_resolution/stages/color_matcher.pyAdded+106
src/ai_super_resolution/stages/denoiser.pyAdded+65
src/ai_super_resolution/stages/input_validator.pyAdded+134
src/ai_super_resolution/stages/post_processor.pyAdded+85
src/ai_super_resolution/stages/quality_analyzer.pyAdded+173
src/ai_super_resolution/stages/tile_engine.pyAdded+144
src/ai_super_resolution/utils/image_utils.pyAdded+31
src/ai_text_removal/README.mdAdded+42
src/ai_text_removal/configs/config.yamlAdded+35
src/ai_text_removal/inference.pyAdded+205
src/ai_text_removal/requirements.txtAdded+26
src/ai_text_removal/tr_pipeline.pyAdded+222
src/ai_text_removal/tr_pipelines/__init__.pyAdded
src/ai_text_removal/tr_pipelines/detect_text.pyAdded+117
src/ai_text_removal/tr_pipelines/diffusion_refine.pyAdded+128
src/ai_text_removal/tr_pipelines/edge_extract.pyAdded+51
src/ai_text_removal/tr_pipelines/inpaint.pyAdded+88
src/ai_text_removal/tr_pipelines/post_process.pyAdded+119
src/ai_text_removal/tr_pipelines/preprocess.pyAdded+22
src/ai_text_removal/tr_pipelines/refine_mask.pyAdded+26
src/ai_text_removal/tr_pipelines/segment_mask.pyAdded+78