CoolFace
Apppublic

goatom/Image_Edits

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
App README

๐ŸŽจ Zero-Shot Image Editing Assistant

Upload an image โ†’ Describe your edit โ†’ Get AI-generated results Powered by Stable Diffusion img2img + LoRA Transfer Learning

Python 3.10+ Flask License


๐Ÿ“‹ Table of Contents


๐Ÿง  How It Works

  1. 1.User uploads a source image (PNG/JPG/WebP)
  2. 2.User writes a natural-language editing prompt
  3. 3.Prompt Parser extracts style keywords, intensity modifiers & object edits
  4. 4.Stable Diffusion img2img encodes the image into latent space, adds noise proportional to strength, and denoises guided by the text prompt
  5. 5.LoRA adapter (transfer learning) modulates the model's style behaviour
  6. 6.Result is displayed side-by-side with the original and can be downloaded

๐Ÿ— Architecture

Browser (HTML/CSS/JS)
    โ”‚
    โ”œโ”€โ”€ POST /upload     โ†’  Save image to static/uploads/
    โ”œโ”€โ”€ POST /generate   โ†’  Prompt Parser โ†’ Diffusion Pipeline โ†’ Output
    โ””โ”€โ”€ GET  /download   โ†’  Serve output file
          โ”‚
   Flask Server (app.py)
          โ”‚
          โ”œโ”€โ”€ utils/prompt_parser.py      โ† NLP-style prompt analysis
          โ””โ”€โ”€ utils/diffusion_pipeline.py โ† SD img2img + LoRA
                    โ”‚
             HuggingFace Diffusers
                    โ”‚
         runwayml/stable-diffusion-v1-5 (pre-trained)

๐Ÿ”ฌ Transfer Learning Explained

This project uses two levels of transfer learning โ€” neither trains a model from scratch:

Level 1: Pre-Trained Stable Diffusion

The base model (runwayml/stable-diffusion-v1-5) was trained on LAION-5B (~5 billion image-text pairs). We load these pre-trained weights directly โ€” this is the simplest form of transfer learning: feature reuse.

python
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16  # Half-precision for GPU efficiency
)
pipe = pipe.to("cuda")  # GPU acceleration

Level 2: LoRA (Low-Rank Adaptation)

LoRA is a parameter-efficient fine-tuning technique:

  • โ€”The base model's attention weight matrices W are frozen (not changed)
  • โ€”Two small matrices A (down-projection) and B (up-projection) are added: W' = W + scale ร— (B @ A)
  • โ€”LoRA weights are only a few MB vs. the full model's ~4 GB
  • โ€”They encode domain-specific knowledge (e.g., anime style, oil painting style)
  • โ€”We load pre-trained LoRA weights from HuggingFace Hub: pipe.load_lora_weights("lora-library/some-style")

Why this is transfer learning:

  • โ€”The base model's knowledge is transferred to new tasks
  • โ€”LoRA adapts the model to a new domain without retraining the full model
  • โ€”Inference is fast because only the small adapter weights change the model's behaviour

๐Ÿš€ Setup Instructions

Prerequisites

  • โ€”Python 3.10+
  • โ€”8 GB+ RAM (for CPU mode)
  • โ€”NVIDIA GPU with 4+ GB VRAM (recommended, not required)
  • โ€”Git installed

Step 1: Clone / Navigate to the project

bash
cd c:\Users\tomge\Desktop\ai_img

Step 2: Create a virtual environment (recommended)

bash
python -m venv venv

# Windows:
venv\Scripts\activate

# Linux/Mac:
source venv/bin/activate

Step 3: Install dependencies

bash
pip install -r requirements.txt

Step 4: Install PyTorch with CUDA (if you have an NVIDIA GPU)

bash
# Check your CUDA version first:
nvidia-smi

# Install matching PyTorch:
# CUDA 11.8:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118

# CUDA 12.1:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121

# CPU only (no GPU):
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu

Q

๐Ÿ–ฅ GPU Configuration

Check GPU availability

python
import torch
print(f"CUDA available: {torch.cuda.is_available()}")
print(f"GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'None'}")
print(f"VRAM: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB" if torch.cuda.is_available() else "")

Memory optimization (already enabled in the code)

TechniqueWhat It DoesVRAM Savings
torch.float16Half-precision computation~50%
enable_attention_slicing()Splits attention into chunks~40% peak reduction
enable_vae_slicing()Decodes latents in slices~30% peak reduction
safety_checker=NoneDisables NSFW classifier~300 MB

These are all enabled by default to keep your laptop cool.


๐Ÿ“ฅ Model Download

The model downloads automatically on the first generation request. No manual download needed.

WhatSizeWhen
Stable Diffusion v1.5~4 GBFirst /generate call
LoRA weights (if configured)~10-50 MBFirst /generate call

Models are cached in the models/ directory. Subsequent runs use the cache.

Manual download (optional)

python
from diffusers import StableDiffusionImg2ImgPipeline
StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", cache_dir="./models")

โ–ถ๏ธ Running the App

bash
python app.py

Open your browser at http://localhost:5000


๐Ÿ’ก Example Prompts

PromptStrengthEffect
make it look like an oil painting0.55Adds brush-stroke texture
transform into anime style, Studio Ghibli aesthetic0.65Anime-style conversion
add dramatic cyberpunk neon lighting0.50Neon glow + dark atmosphere
convert to pencil sketch with detailed shading0.70Graphite sketch look
make it look like a vintage photograph0.45Film grain + faded colours
slightly add sunset lighting0.30Subtle warm tones
dramatically change to watercolor painting0.80Heavy watercolor effect
transform into impressionist painting, Monet style0.60Soft brushstrokes

๐Ÿณ Docker Deployment

Build and run

bash
docker build -t zero-shot-editor .
docker run -p 5000:5000 zero-shot-editor

With GPU (NVIDIA Container Toolkit required)

bash
docker run --gpus all -p 5000:5000 zero-shot-editor

๐Ÿค— HuggingFace Spaces Deployment

  1. 1.Create a new Space at huggingface.co/spaces
  2. 2.Select Gradio or Docker SDK
  3. 3.Upload all project files
  4. 4.Set Space hardware to T4 GPU (free tier available)
  5. 5.The app will auto-build and deploy

For HuggingFace Spaces, you may need to change app.py's host:

python
app.run(host="0.0.0.0", port=7860)  # Spaces uses port 7860

๐Ÿ”ง Troubleshooting

ProblemSolution
CUDA out of memoryReduce image size in config.py (DEFAULT_IMAGE_SIZE = 384), or reduce DEFAULT_NUM_STEPS
Model download stuckCheck internet connection; try VPN if HuggingFace is blocked
RuntimeError: Expected Float16You're on CPU โ€” set DTYPE = torch.float32 in config.py
Very slow generationNormal for CPU (~2-5 min). Use GPU for ~20-30s generation
Laptop gets hotReduce DEFAULT_NUM_STEPS to 15-20, reduce DEFAULT_IMAGE_SIZE to 384
ModuleNotFoundErrorRun pip install -r requirements.txt in your virtual environment
Image looks distortedLower the strength (0.3-0.4) to preserve more structure
Output ignores promptIncrease guidance_scale (try 10-12) and strength (try 0.6-0.7)

โšก Performance Optimization

Speed improvements

  1. 1.Use GPU โ€” 10-20x faster than CPU
  2. 2.Reduce steps โ€” 15-20 steps gives decent quality much faster
  3. 3.Reduce image size โ€” 384px instead of 512px
  4. 4.Use float16 โ€” already enabled for GPU

Memory savings

  1. 1.Attention slicing โ€” already enabled
  2. 2.VAE slicing โ€” already enabled
  3. 3.CPU offload โ€” set ENABLE_CPU_OFFLOAD = True in config.py for very low VRAM GPUs
  4. 4.Reduce batch size โ€” this app processes one image at a time (optimal)

Quality tips

  1. 1.Increase steps to 40-50 for higher quality
  2. 2.Guidance scale of 7-9 is usually optimal
  3. 3.Strength of 0.4-0.6 preserves structure well
  4. 4.Negative prompts are auto-generated by the prompt parser

๐Ÿ“ Folder Structure

zero_shot_editor/
โ”‚
โ”œโ”€โ”€ app.py                          # Flask server (routes, API)
โ”œโ”€โ”€ config.py                       # All configuration in one place
โ”œโ”€โ”€ requirements.txt                # Python dependencies
โ”œโ”€โ”€ Dockerfile                      # Container deployment
โ”œโ”€โ”€ .dockerignore                   # Docker build exclusions
โ”œโ”€โ”€ README.md                       # This file
โ”‚
โ”œโ”€โ”€ models/                         # Cached model weights (auto-created)
โ”‚
โ”œโ”€โ”€ static/
โ”‚   โ”œโ”€โ”€ css/
โ”‚   โ”‚   โ””โ”€โ”€ style.css               # Dark glassmorphism UI
โ”‚   โ”œโ”€โ”€ js/
โ”‚   โ”‚   โ””โ”€โ”€ app.js                  # Frontend logic
โ”‚   โ”œโ”€โ”€ uploads/                    # User-uploaded images
โ”‚   โ””โ”€โ”€ outputs/                    # AI-generated outputs
โ”‚
โ”œโ”€โ”€ templates/
โ”‚   โ””โ”€โ”€ index.html                  # Main web interface
โ”‚
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ __init__.py
    โ”œโ”€โ”€ diffusion_pipeline.py       # SD img2img + LoRA pipeline
    โ””โ”€โ”€ prompt_parser.py            # NLP-style prompt analysis

๐Ÿ“„ License

MIT License โ€” Use freely for academic and personal projects.