# Pillow Dependency Fix

**Last Updated:** 2026-03-03  
**Status:** ✅ **FIXED**

## Problem

Scripts were failing with "Error: Pillow required. Run: pip install Pillow" when run with system Python instead of venv Python.

## Root Cause

The `_ensure_venv()` function was called inside `main()`, which happens **after** the script is already loaded. When running with system Python, the script would try to import PIL before switching to venv Python, causing the error.

## Solution

Moved `_ensure_venv()` call to module level (when script is run directly) so it executes **before** any imports that require venv packages.

### Changes Made

1. **optimize-blog-featured-image.py**
   - Added module-level `_ensure_venv()` call: `if __name__ == "__main__": _ensure_venv()`
   - Removed redundant call from `main()` function
   - Ensures venv switch happens before PIL import

2. **generate-blog-featured-image.py**
   - Added module-level `_ensure_venv()` call: `if __name__ == "__main__": _ensure_venv()`
   - Removed redundant call from `main()` function
   - Ensures venv switch happens before requests/Pillow imports

## How It Works

```python
def _ensure_venv() -> None:
    """Re-exec with project .venv if not already using it (for Pillow)."""
    venv_python = REPO_ROOT / ".venv" / "bin" / "python"
    if venv_python.exists() and Path(sys.executable).resolve() != venv_python.resolve():
        os.execv(str(venv_python), [str(venv_python), __file__] + sys.argv[1:])

# CRITICAL: Call at module level BEFORE any imports that require venv packages
if __name__ == "__main__":
    _ensure_venv()
```

**When script is run directly:**
1. Module loads
2. `_ensure_venv()` checks if using venv Python
3. If not, re-execs script with venv Python
4. Script continues with venv Python (which has Pillow installed)

**When script is imported:**
- `if __name__ == "__main__"` is False, so `_ensure_venv()` is not called
- Script can be imported without re-exec

## Verification

### Test with System Python
```bash
# Should automatically switch to venv
python3 v2/scripts/blog/generate-blog-featured-image.py --post=slug --category=lexikon --dry-run
```

### Test with Venv Python
```bash
# Should work directly
.venv/bin/python3 v2/scripts/blog/generate-blog-featured-image.py --post=slug --category=lexikon --dry-run
```

### Verify Pillow Installation
```bash
.venv/bin/python3 -c "import PIL; print('Pillow:', PIL.__version__)"
# Expected: Pillow: 12.1.1 (or similar)
```

## Dependencies

- **Pillow:** Listed in `requirements.txt` as `Pillow>=10.0.0`
- **Installation:** `pip install -r requirements.txt` (or `pip install Pillow`)
- **Location:** Installed in `.venv/` (virtual environment)

## Related Files

- `v2/scripts/blog/generate-blog-featured-image.py` - Image generation script
- `v2/scripts/blog/optimize-blog-featured-image.py` - WebP optimization script
- `requirements.txt` - Python dependencies (includes Pillow)
- `docs/content/blog/GEMINI_IMAGE_GENERATION_WORKFLOW.md` - Workflow documentation

## Status

✅ **Fixed** - Scripts now automatically use venv Python when run with system Python, preventing Pillow import errors.
