Commit ·
dd1ad6f
1
Parent(s): 6060aa1
Initial upload
Browse files- .gitignore +97 -0
- README.md +128 -4
- app.py +367 -0
- requirements.txt +14 -0
.gitignore
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
build/
|
| 8 |
+
develop-eggs/
|
| 9 |
+
dist/
|
| 10 |
+
downloads/
|
| 11 |
+
eggs/
|
| 12 |
+
.eggs/
|
| 13 |
+
lib/
|
| 14 |
+
lib64/
|
| 15 |
+
parts/
|
| 16 |
+
sdist/
|
| 17 |
+
var/
|
| 18 |
+
wheels/
|
| 19 |
+
pip-wheel-metadata/
|
| 20 |
+
share/python-wheels/
|
| 21 |
+
*.egg-info/
|
| 22 |
+
.installed.cfg
|
| 23 |
+
*.egg
|
| 24 |
+
MANIFEST
|
| 25 |
+
|
| 26 |
+
# Virtual Environment
|
| 27 |
+
venv/
|
| 28 |
+
env/
|
| 29 |
+
ENV/
|
| 30 |
+
env.bak/
|
| 31 |
+
venv.bak/
|
| 32 |
+
|
| 33 |
+
# IDEs
|
| 34 |
+
.vscode/
|
| 35 |
+
.idea/
|
| 36 |
+
*.swp
|
| 37 |
+
*.swo
|
| 38 |
+
*~
|
| 39 |
+
.DS_Store
|
| 40 |
+
|
| 41 |
+
# Jupyter Notebook
|
| 42 |
+
.ipynb_checkpoints
|
| 43 |
+
*.ipynb
|
| 44 |
+
|
| 45 |
+
# Model cache and data
|
| 46 |
+
*.pt
|
| 47 |
+
*.pth
|
| 48 |
+
*.bin
|
| 49 |
+
*.safetensors
|
| 50 |
+
models/
|
| 51 |
+
checkpoints/
|
| 52 |
+
huggingface_cache/
|
| 53 |
+
|
| 54 |
+
# Gradio
|
| 55 |
+
gradio_cached_examples/
|
| 56 |
+
flagged/
|
| 57 |
+
*.db
|
| 58 |
+
|
| 59 |
+
# Temporary files
|
| 60 |
+
*.tmp
|
| 61 |
+
*.temp
|
| 62 |
+
tmp/
|
| 63 |
+
temp/
|
| 64 |
+
.cache/
|
| 65 |
+
|
| 66 |
+
# Output files
|
| 67 |
+
output/
|
| 68 |
+
results/
|
| 69 |
+
enhanced_images/
|
| 70 |
+
*.zip
|
| 71 |
+
*.7z
|
| 72 |
+
|
| 73 |
+
# Logs
|
| 74 |
+
*.log
|
| 75 |
+
logs/
|
| 76 |
+
|
| 77 |
+
# Environment variables
|
| 78 |
+
.env
|
| 79 |
+
.env.local
|
| 80 |
+
|
| 81 |
+
# OS
|
| 82 |
+
Thumbs.db
|
| 83 |
+
desktop.ini
|
| 84 |
+
|
| 85 |
+
# PyTorch
|
| 86 |
+
lightning_logs/
|
| 87 |
+
wandb/
|
| 88 |
+
|
| 89 |
+
# Test files
|
| 90 |
+
test_images/
|
| 91 |
+
test_output/
|
| 92 |
+
|
| 93 |
+
# Large files
|
| 94 |
+
*.ckpt
|
| 95 |
+
*.h5
|
| 96 |
+
*.pkl
|
| 97 |
+
*.pickle
|
README.md
CHANGED
|
@@ -1,12 +1,136 @@
|
|
| 1 |
---
|
| 2 |
title: Flux Microscopy Image Enhancement
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.3.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Flux Microscopy Image Enhancement
|
| 3 |
+
emoji: 🔬
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.3.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# 🔬 Flux Microscopy Image Enhancement
|
| 14 |
+
|
| 15 |
+
An AI-powered microscopy image enhancement tool using the FLUX.2 model. This application provides intelligent image enhancement while preserving cellular structures and fine details.
|
| 16 |
+
|
| 17 |
+
## ✨ Features
|
| 18 |
+
|
| 19 |
+
- **Batch Processing**: Process multiple images at once or entire archived folders
|
| 20 |
+
- **Archive Support**: Upload ZIP or 7Z files containing multiple images
|
| 21 |
+
- **Smart Enhancement**: AI-powered enhancement using FLUX.2-dev with quantization (4-bit)
|
| 22 |
+
- **Quality Metrics**: Automatic calculation of PSNR and SSIM to evaluate enhancement quality
|
| 23 |
+
- **Custom Prompts**: Customize the enhancement behavior with natural language prompts
|
| 24 |
+
- **Adjustable Parameters**: Fine-tune guidance scale and inference steps for optimal results
|
| 25 |
+
- **Structured Output**: Download results with `_flux` suffix maintaining original directory structure
|
| 26 |
+
|
| 27 |
+
## 🚀 Quick Start
|
| 28 |
+
|
| 29 |
+
1. **Upload Images**: Upload individual images (JPG, PNG, BMP, TIFF) or compressed archives (ZIP, 7Z)
|
| 30 |
+
2. **Customize (Optional)**: Adjust the enhancement prompt and parameters if needed
|
| 31 |
+
3. **Process**: Click "Enhance Images" and wait for processing to complete
|
| 32 |
+
4. **Download**: Get your enhanced images as a ZIP file with quality metrics
|
| 33 |
+
|
| 34 |
+
## 🖼️ Supported Formats
|
| 35 |
+
|
| 36 |
+
### Input Formats
|
| 37 |
+
- **Images**: `.jpg`, `.jpeg`, `.png`, `.bmp`, `.tiff`, `.tif`
|
| 38 |
+
- **Archives**: `.zip`, `.7z` (automatically extracts and processes all images inside)
|
| 39 |
+
|
| 40 |
+
### Output Format
|
| 41 |
+
- All enhanced images are saved with `_flux` suffix (e.g., `image.png` → `image_flux.png`)
|
| 42 |
+
- Results packaged in a ZIP file maintaining original folder structure
|
| 43 |
+
|
| 44 |
+
## 🎯 Default Enhancement Settings
|
| 45 |
+
|
| 46 |
+
- **Prompt**: "enhance microscopy image with subtle improvements, gently increase cellular boundary clarity, preserve original morphological structure, maintain authentic texture patterns, minimal noise reduction while keeping fine details intact"
|
| 47 |
+
- **Guidance Scale**: 2.0 (conservative for natural enhancement)
|
| 48 |
+
- **Inference Steps**: 30 (balanced quality and speed)
|
| 49 |
+
|
| 50 |
+
## 📊 Quality Metrics
|
| 51 |
+
|
| 52 |
+
The application automatically calculates two important metrics for each enhanced image:
|
| 53 |
+
|
| 54 |
+
- **PSNR** (Peak Signal-to-Noise Ratio): Measures pixel-level similarity
|
| 55 |
+
- Higher values indicate better quality
|
| 56 |
+
- > 30 dB is considered good
|
| 57 |
+
|
| 58 |
+
- **SSIM** (Structural Similarity Index): Measures structural similarity
|
| 59 |
+
- Values range from 0 to 1
|
| 60 |
+
- > 0.9 is considered excellent
|
| 61 |
+
- More aligned with human perception than PSNR
|
| 62 |
+
|
| 63 |
+
## 🔧 Parameters
|
| 64 |
+
|
| 65 |
+
### Guidance Scale (1.0 - 5.0)
|
| 66 |
+
Controls the strength of the enhancement:
|
| 67 |
+
- **Lower values** (1.0-2.0): More conservative, stays closer to original
|
| 68 |
+
- **Higher values** (3.0-5.0): More creative, stronger enhancements
|
| 69 |
+
- **Default**: 2.0
|
| 70 |
+
|
| 71 |
+
### Inference Steps (10 - 50)
|
| 72 |
+
Number of processing iterations:
|
| 73 |
+
- **Fewer steps** (10-20): Faster processing, lower quality
|
| 74 |
+
- **More steps** (30-50): Better quality, slower processing
|
| 75 |
+
- **Default**: 30
|
| 76 |
+
|
| 77 |
+
## 💻 Model Information
|
| 78 |
+
|
| 79 |
+
This application uses:
|
| 80 |
+
- **Model**: [diffusers/FLUX.2-dev-bnb-4bit](https://huggingface.co/diffusers/FLUX.2-dev-bnb-4bit)
|
| 81 |
+
- **Quantization**: 4-bit bitsandbytes quantization for efficient inference
|
| 82 |
+
- **Precision**: bfloat16 for optimal quality/performance balance
|
| 83 |
+
|
| 84 |
+
## 🛠️ Local Installation
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
# Clone the repository
|
| 88 |
+
git clone https://huggingface.co/spaces/YOUR_USERNAME/flux-image-enhance
|
| 89 |
+
cd flux-image-enhance
|
| 90 |
+
|
| 91 |
+
# Install dependencies
|
| 92 |
+
pip install -r requirements.txt
|
| 93 |
+
|
| 94 |
+
# Run the application
|
| 95 |
+
python app.py
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
## 📋 Requirements
|
| 99 |
+
|
| 100 |
+
- Python 3.8+
|
| 101 |
+
- CUDA-capable GPU (recommended) or CPU
|
| 102 |
+
- ~10GB GPU memory for model inference
|
| 103 |
+
- Dependencies listed in `requirements.txt`
|
| 104 |
+
|
| 105 |
+
## 🎓 Use Cases
|
| 106 |
+
|
| 107 |
+
- Microscopy image enhancement for research
|
| 108 |
+
- Cellular structure visualization
|
| 109 |
+
- Biological sample analysis
|
| 110 |
+
- Medical imaging preprocessing
|
| 111 |
+
- Scientific publication preparation
|
| 112 |
+
|
| 113 |
+
## ⚠️ Notes
|
| 114 |
+
|
| 115 |
+
- Processing time depends on image size, number of images, and selected parameters
|
| 116 |
+
- GPU acceleration is highly recommended for faster processing
|
| 117 |
+
- The model preserves original cellular structures while enhancing clarity
|
| 118 |
+
- First run may take longer due to model downloading and caching
|
| 119 |
+
|
| 120 |
+
## 📝 License
|
| 121 |
+
|
| 122 |
+
Apache 2.0
|
| 123 |
+
|
| 124 |
+
## 🤝 Contributing
|
| 125 |
+
|
| 126 |
+
Contributions, issues, and feature requests are welcome!
|
| 127 |
+
|
| 128 |
+
## 🔗 Links
|
| 129 |
+
|
| 130 |
+
- [FLUX.2 Model](https://huggingface.co/diffusers/FLUX.2-dev-bnb-4bit)
|
| 131 |
+
- [Diffusers Library](https://github.com/huggingface/diffusers)
|
| 132 |
+
- [Gradio Documentation](https://www.gradio.app/docs)
|
| 133 |
+
|
| 134 |
+
---
|
| 135 |
+
|
| 136 |
+
Built with ❤️ using Gradio and 🤗 Hugging Face
|
app.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from diffusers import Flux2Pipeline
|
| 4 |
+
from diffusers.utils import load_image
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import os
|
| 7 |
+
import zipfile
|
| 8 |
+
import py7zr
|
| 9 |
+
import tempfile
|
| 10 |
+
import shutil
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import numpy as np
|
| 13 |
+
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
|
| 14 |
+
from skimage.util import img_as_float
|
| 15 |
+
import io
|
| 16 |
+
|
| 17 |
+
# Load Flux model
|
| 18 |
+
print("Loading Flux model...")
|
| 19 |
+
pipe = Flux2Pipeline.from_pretrained(
|
| 20 |
+
"diffusers/FLUX.2-dev-bnb-4bit", torch_dtype=torch.bfloat16, fix_mistral_regex=True
|
| 21 |
+
)
|
| 22 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
pipe.to(device)
|
| 24 |
+
print("Model loaded successfully")
|
| 25 |
+
|
| 26 |
+
# Default enhancement prompt
|
| 27 |
+
DEFAULT_PROMPT = "enhance microscopy image with subtle improvements, gently increase cellular boundary clarity, preserve original morphological structure, maintain authentic texture patterns, minimal noise reduction while keeping fine details intact"
|
| 28 |
+
|
| 29 |
+
# Enhancement parameters
|
| 30 |
+
GUIDANCE_SCALE = 2.0
|
| 31 |
+
NUM_INFERENCE_STEPS = 30
|
| 32 |
+
|
| 33 |
+
# Supported image extensions
|
| 34 |
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def calculate_psnr_ssim(original, enhanced):
|
| 38 |
+
"""Calculate PSNR and SSIM between original and enhanced images"""
|
| 39 |
+
# Convert images to float arrays
|
| 40 |
+
orig_float = img_as_float(np.array(original))
|
| 41 |
+
enhanced_float = img_as_float(np.array(enhanced))
|
| 42 |
+
|
| 43 |
+
# Ensure both images have the same shape
|
| 44 |
+
if orig_float.shape != enhanced_float.shape:
|
| 45 |
+
min_h = min(orig_float.shape[0], enhanced_float.shape[0])
|
| 46 |
+
min_w = min(orig_float.shape[1], enhanced_float.shape[1])
|
| 47 |
+
orig_float = orig_float[:min_h, :min_w]
|
| 48 |
+
enhanced_float = enhanced_float[:min_h, :min_w]
|
| 49 |
+
|
| 50 |
+
# Calculate PSNR
|
| 51 |
+
psnr = peak_signal_noise_ratio(orig_float, enhanced_float, data_range=1.0)
|
| 52 |
+
|
| 53 |
+
# Calculate SSIM
|
| 54 |
+
if len(orig_float.shape) == 3: # Color image
|
| 55 |
+
ssim = structural_similarity(
|
| 56 |
+
orig_float, enhanced_float, data_range=1.0, channel_axis=-1
|
| 57 |
+
)
|
| 58 |
+
else: # Grayscale image
|
| 59 |
+
ssim = structural_similarity(orig_float, enhanced_float, data_range=1.0)
|
| 60 |
+
|
| 61 |
+
return psnr, ssim
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def extract_archive(archive_path, extract_to):
|
| 65 |
+
"""Extract zip or 7z archive"""
|
| 66 |
+
file_ext = Path(archive_path).suffix.lower()
|
| 67 |
+
|
| 68 |
+
if file_ext == ".zip":
|
| 69 |
+
with zipfile.ZipFile(archive_path, "r") as zip_ref:
|
| 70 |
+
zip_ref.extractall(extract_to)
|
| 71 |
+
elif file_ext == ".7z":
|
| 72 |
+
with py7zr.SevenZipFile(archive_path, mode="r") as archive:
|
| 73 |
+
archive.extractall(path=extract_to)
|
| 74 |
+
else:
|
| 75 |
+
raise ValueError(f"Unsupported archive format: {file_ext}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def find_images(directory):
|
| 79 |
+
"""Recursively find all images in directory"""
|
| 80 |
+
image_files = []
|
| 81 |
+
for root, dirs, files in os.walk(directory):
|
| 82 |
+
for file in files:
|
| 83 |
+
if Path(file).suffix.lower() in IMAGE_EXTENSIONS:
|
| 84 |
+
image_files.append(os.path.join(root, file))
|
| 85 |
+
return image_files
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def enhance_single_image(image, prompt, guidance_scale, num_steps):
|
| 89 |
+
"""Enhance a single image"""
|
| 90 |
+
if isinstance(image, str):
|
| 91 |
+
input_image = load_image(image)
|
| 92 |
+
else:
|
| 93 |
+
input_image = image
|
| 94 |
+
|
| 95 |
+
enhanced_image = pipe(
|
| 96 |
+
image=input_image,
|
| 97 |
+
prompt=prompt,
|
| 98 |
+
guidance_scale=guidance_scale,
|
| 99 |
+
num_inference_steps=num_steps,
|
| 100 |
+
).images[0]
|
| 101 |
+
|
| 102 |
+
return input_image, enhanced_image
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def process_images(files, prompt, guidance_scale, num_steps, progress=gr.Progress()):
|
| 106 |
+
"""Process uploaded files (images or archives)"""
|
| 107 |
+
if not files:
|
| 108 |
+
return None, None, "Please upload at least one file."
|
| 109 |
+
|
| 110 |
+
if not prompt or prompt.strip() == "":
|
| 111 |
+
prompt = DEFAULT_PROMPT
|
| 112 |
+
|
| 113 |
+
# Create temporary directories
|
| 114 |
+
temp_dir = tempfile.mkdtemp()
|
| 115 |
+
output_dir = tempfile.mkdtemp()
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
all_images = []
|
| 119 |
+
results = []
|
| 120 |
+
metrics_summary = []
|
| 121 |
+
|
| 122 |
+
progress(0, desc="Processing files...")
|
| 123 |
+
|
| 124 |
+
# Process each uploaded file
|
| 125 |
+
for file_obj in files:
|
| 126 |
+
file_path = file_obj.name if hasattr(file_obj, "name") else file_obj
|
| 127 |
+
file_ext = Path(file_path).suffix.lower()
|
| 128 |
+
|
| 129 |
+
# Check if it's an archive
|
| 130 |
+
if file_ext in [".zip", ".7z"]:
|
| 131 |
+
progress(0.1, desc=f"Extracting archive: {Path(file_path).name}...")
|
| 132 |
+
extract_dir = os.path.join(temp_dir, Path(file_path).stem)
|
| 133 |
+
extract_archive(file_path, extract_dir)
|
| 134 |
+
|
| 135 |
+
# Find all images in extracted directory
|
| 136 |
+
images = find_images(extract_dir)
|
| 137 |
+
|
| 138 |
+
for img_path in images:
|
| 139 |
+
# Get relative path to maintain directory structure
|
| 140 |
+
rel_path = os.path.relpath(img_path, extract_dir)
|
| 141 |
+
all_images.append((img_path, rel_path, extract_dir))
|
| 142 |
+
|
| 143 |
+
# Check if it's an image
|
| 144 |
+
elif file_ext in IMAGE_EXTENSIONS:
|
| 145 |
+
all_images.append((file_path, Path(file_path).name, None))
|
| 146 |
+
|
| 147 |
+
if not all_images:
|
| 148 |
+
return None, None, "No valid images found in uploaded files."
|
| 149 |
+
|
| 150 |
+
total_images = len(all_images)
|
| 151 |
+
progress(0.2, desc=f"Found {total_images} images. Starting enhancement...")
|
| 152 |
+
|
| 153 |
+
# Process each image
|
| 154 |
+
for idx, (img_path, rel_path, base_dir) in enumerate(all_images):
|
| 155 |
+
progress(
|
| 156 |
+
(0.2 + 0.7 * idx / total_images),
|
| 157 |
+
desc=f"Processing {idx + 1}/{total_images}: {Path(img_path).name}...",
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Enhance image
|
| 161 |
+
original, enhanced = enhance_single_image(
|
| 162 |
+
img_path, prompt, guidance_scale, num_steps
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# Calculate metrics
|
| 166 |
+
psnr, ssim = calculate_psnr_ssim(original, enhanced)
|
| 167 |
+
|
| 168 |
+
# Prepare output path
|
| 169 |
+
if base_dir:
|
| 170 |
+
# For archive images, maintain directory structure
|
| 171 |
+
output_rel_path = rel_path
|
| 172 |
+
output_path = os.path.join(output_dir, output_rel_path)
|
| 173 |
+
else:
|
| 174 |
+
# For standalone images
|
| 175 |
+
output_path = os.path.join(output_dir, rel_path)
|
| 176 |
+
|
| 177 |
+
# Create output directory if needed
|
| 178 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 179 |
+
|
| 180 |
+
# Add _flux suffix to filename
|
| 181 |
+
output_name = Path(output_path).stem + "_flux" + Path(output_path).suffix
|
| 182 |
+
output_path = os.path.join(os.path.dirname(output_path), output_name)
|
| 183 |
+
|
| 184 |
+
# Save enhanced image
|
| 185 |
+
enhanced.save(output_path)
|
| 186 |
+
|
| 187 |
+
results.append(
|
| 188 |
+
{
|
| 189 |
+
"original": original,
|
| 190 |
+
"enhanced": enhanced,
|
| 191 |
+
"filename": rel_path,
|
| 192 |
+
"output_path": output_path,
|
| 193 |
+
"psnr": psnr,
|
| 194 |
+
"ssim": ssim,
|
| 195 |
+
}
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
metrics_summary.append(f"{rel_path}: PSNR={psnr:.2f} dB, SSIM={ssim:.4f}")
|
| 199 |
+
|
| 200 |
+
progress(0.9, desc="Creating output package...")
|
| 201 |
+
|
| 202 |
+
# Create output zip file
|
| 203 |
+
output_zip_path = os.path.join(
|
| 204 |
+
tempfile.gettempdir(), "enhanced_images_flux.zip"
|
| 205 |
+
)
|
| 206 |
+
with zipfile.ZipFile(output_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 207 |
+
for root, dirs, files in os.walk(output_dir):
|
| 208 |
+
for file in files:
|
| 209 |
+
file_path = os.path.join(root, file)
|
| 210 |
+
arcname = os.path.relpath(file_path, output_dir)
|
| 211 |
+
zipf.write(file_path, arcname)
|
| 212 |
+
|
| 213 |
+
# Calculate average metrics
|
| 214 |
+
avg_psnr = np.mean([r["psnr"] for r in results])
|
| 215 |
+
avg_ssim = np.mean([r["ssim"] for r in results])
|
| 216 |
+
|
| 217 |
+
# Create summary text
|
| 218 |
+
summary = f"✅ Processing completed!\n\n"
|
| 219 |
+
summary += f"Total images processed: {total_images}\n"
|
| 220 |
+
summary += f"Average PSNR: {avg_psnr:.2f} dB\n"
|
| 221 |
+
summary += f"Average SSIM: {avg_ssim:.4f}\n\n"
|
| 222 |
+
summary += "Individual metrics:\n"
|
| 223 |
+
summary += "\n".join(metrics_summary)
|
| 224 |
+
|
| 225 |
+
progress(1.0, desc="Done!")
|
| 226 |
+
|
| 227 |
+
# For display in gallery, show first few results
|
| 228 |
+
gallery_images = []
|
| 229 |
+
for result in results[:10]: # Show first 10 results
|
| 230 |
+
gallery_images.append(
|
| 231 |
+
(result["original"], f"Original: {result['filename']}")
|
| 232 |
+
)
|
| 233 |
+
gallery_images.append(
|
| 234 |
+
(
|
| 235 |
+
result["enhanced"],
|
| 236 |
+
f"Enhanced: {result['filename']}\nPSNR: {result['psnr']:.2f} dB, SSIM: {result['ssim']:.4f}",
|
| 237 |
+
)
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
return gallery_images, output_zip_path, summary
|
| 241 |
+
|
| 242 |
+
except Exception as e:
|
| 243 |
+
return None, None, f"Error during processing: {str(e)}"
|
| 244 |
+
|
| 245 |
+
finally:
|
| 246 |
+
# Cleanup temporary directory
|
| 247 |
+
if os.path.exists(temp_dir):
|
| 248 |
+
shutil.rmtree(temp_dir)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# Create Gradio interface
|
| 252 |
+
with gr.Blocks(title="Flux Microscopy Image Enhancement") as demo:
|
| 253 |
+
gr.Markdown(
|
| 254 |
+
"""
|
| 255 |
+
# 🔬 Flux Microscopy Image Enhancement
|
| 256 |
+
|
| 257 |
+
Upload microscopy images (individual files or compressed archives) for AI-powered enhancement.
|
| 258 |
+
|
| 259 |
+
**Supported formats:**
|
| 260 |
+
- Images: JPG, PNG, BMP, TIFF
|
| 261 |
+
- Archives: ZIP, 7Z (will process all images inside)
|
| 262 |
+
|
| 263 |
+
**Features:**
|
| 264 |
+
- Batch processing support
|
| 265 |
+
- Custom enhancement prompts
|
| 266 |
+
- Quality metrics (PSNR & SSIM)
|
| 267 |
+
- Download results as ZIP with `_flux` suffix
|
| 268 |
+
"""
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
with gr.Row():
|
| 272 |
+
with gr.Column(scale=1):
|
| 273 |
+
# File upload
|
| 274 |
+
file_input = gr.File(
|
| 275 |
+
label="Upload Images or Archive (ZIP/7Z)",
|
| 276 |
+
file_count="multiple",
|
| 277 |
+
file_types=["image", ".zip", ".7z"],
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# Prompt input
|
| 281 |
+
prompt_input = gr.Textbox(
|
| 282 |
+
label="Enhancement Prompt",
|
| 283 |
+
placeholder="Enter custom prompt or leave empty for default",
|
| 284 |
+
value=DEFAULT_PROMPT,
|
| 285 |
+
lines=3,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Parameter controls
|
| 289 |
+
gr.Markdown("### Enhancement Parameters")
|
| 290 |
+
guidance_scale_input = gr.Slider(
|
| 291 |
+
minimum=1.0,
|
| 292 |
+
maximum=5.0,
|
| 293 |
+
value=GUIDANCE_SCALE,
|
| 294 |
+
step=0.1,
|
| 295 |
+
label="Guidance Scale",
|
| 296 |
+
info="Controls enhancement strength (lower = more conservative, higher = more creative)",
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
num_steps_input = gr.Slider(
|
| 300 |
+
minimum=10,
|
| 301 |
+
maximum=50,
|
| 302 |
+
value=NUM_INFERENCE_STEPS,
|
| 303 |
+
step=1,
|
| 304 |
+
label="Inference Steps",
|
| 305 |
+
info="Number of processing steps (more steps = better quality but slower)",
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
# Process button
|
| 309 |
+
process_btn = gr.Button("🚀 Enhance Images", variant="primary", size="lg")
|
| 310 |
+
|
| 311 |
+
# Example
|
| 312 |
+
gr.Markdown("### Example")
|
| 313 |
+
gr.Examples(
|
| 314 |
+
examples=[
|
| 315 |
+
[None, DEFAULT_PROMPT, GUIDANCE_SCALE, NUM_INFERENCE_STEPS],
|
| 316 |
+
],
|
| 317 |
+
inputs=[
|
| 318 |
+
file_input,
|
| 319 |
+
prompt_input,
|
| 320 |
+
guidance_scale_input,
|
| 321 |
+
num_steps_input,
|
| 322 |
+
],
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
with gr.Column(scale=2):
|
| 326 |
+
# Gallery for results
|
| 327 |
+
gallery_output = gr.Gallery(
|
| 328 |
+
label="Results Preview (Original vs Enhanced)",
|
| 329 |
+
columns=2,
|
| 330 |
+
rows=2,
|
| 331 |
+
height="auto",
|
| 332 |
+
object_fit="contain",
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
# Download button
|
| 336 |
+
download_output = gr.File(label="📥 Download All Enhanced Images (ZIP)")
|
| 337 |
+
|
| 338 |
+
# Metrics summary
|
| 339 |
+
summary_output = gr.Textbox(
|
| 340 |
+
label="Processing Summary & Metrics", lines=10, max_lines=20
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
# Process button click
|
| 344 |
+
process_btn.click(
|
| 345 |
+
fn=process_images,
|
| 346 |
+
inputs=[file_input, prompt_input, guidance_scale_input, num_steps_input],
|
| 347 |
+
outputs=[gallery_output, download_output, summary_output],
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
gr.Markdown(
|
| 351 |
+
"""
|
| 352 |
+
---
|
| 353 |
+
### Default Parameters
|
| 354 |
+
- **Guidance Scale**: 2.0 (conservative for natural enhancement)
|
| 355 |
+
- **Inference Steps**: 30 (balanced quality and speed)
|
| 356 |
+
|
| 357 |
+
💡 You can adjust these parameters above to customize the enhancement process.
|
| 358 |
+
|
| 359 |
+
### Quality Metrics
|
| 360 |
+
- **PSNR** (Peak Signal-to-Noise Ratio): Higher is better (>30 dB is good)
|
| 361 |
+
- **SSIM** (Structural Similarity Index): Closer to 1.0 is better (>0.9 is excellent)
|
| 362 |
+
"""
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Launch the app
|
| 366 |
+
if __name__ == "__main__":
|
| 367 |
+
demo.launch(share=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
diffusers
|
| 3 |
+
transformers
|
| 4 |
+
accelerate
|
| 5 |
+
huggingface_hub
|
| 6 |
+
matplotlib
|
| 7 |
+
Pillow
|
| 8 |
+
numpy
|
| 9 |
+
pathlib
|
| 10 |
+
scikit-image
|
| 11 |
+
jupyter
|
| 12 |
+
bitsandbytes
|
| 13 |
+
gradio
|
| 14 |
+
py7zr
|