Spaces:
Paused
Paused
File size: 9,244 Bytes
60d0fe5 677fa33 60d0fe5 677fa33 60d0fe5 677fa33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | ---
title: Forest Fire Detection FirenetCNN
emoji: π₯
colorFrom: red
colorTo: pink
sdk: gradio
app_file: app.py
pinned: false
license: mit
python_version: "3.12"
short_description: Forest fire and smoke detection with CNN + Grad-CAM
---
# Forest Fire Detection Using FirenetCNN and XAI Techniques
[](https://deepwiki.com/OpelSpeedster/Forest-Fire-Detection-Using-FirenetCNN-and-XAI-Techniques)
This project implements a Convolutional Neural Network (CNN) to detect and classify forest fires from images and videos. The model leverages transfer learning with the MobileNetV2 architecture and is trained to distinguish between three classes: 'fire', 'smoke', and 'no_fire'.
To enhance model interpretability and trustworthiness, the project incorporates Explainable AI (XAI) using Grad-CAM (Gradient-weighted Class Activation Mapping). This technique generates heatmaps that visualize the specific regions in an image the model focuses on to make its predictions.
## Key Features
* **Multi-Class Classification:** Classifies input into 'fire', 'smoke', or 'no_fire' categories.
* **Transfer Learning:** Utilizes a pre-trained MobileNetV2 model, fine-tuned for the specific task of fire detection.
* **Data Augmentation:** Employs various image augmentation techniques (rotation, shifting, shearing, zooming, and flipping).
* **Versatile Prediction:** Capable of performing predictions on static images, pre-recorded videos, and live webcam feeds.
* **Explainable AI (XAI):** Implements Grad-CAM to produce heatmaps, providing visual insight into the model's decisions.
* **Web Interface:** Gradio-based web application for easy deployment and demo.
* **Docker Support:** Containerized deployment for production use.
## Model Performance
The model was evaluated on a test set of 405 images, achieving an overall accuracy of 82%.
```
precision recall f1-score support
fire 0.92 0.81 0.86 121
no_fire 0.76 0.98 0.86 146
smoke 0.84 0.67 0.75 138
accuracy 0.82 405
macro avg 0.84 0.82 0.82 405
weighted avg 0.83 0.82 0.82 405
```
## Project Structure
```
βββ src/ # Python package (core functionality)
β βββ __init__.py # Package exports
β βββ model.py # Model definition and utilities
β βββ gradcam.py # Grad-CAM implementation
β βββ inference.py # Unified inference engine
β βββ training.py # Training pipeline
βββ models/ # Trained model files
β βββ FirenetCNN1.h5 # Primary trained model
β βββ FirenetCNN.h5 # Alternative model version
β βββ firenet_model.h5 # Base model
βββ app.py # Gradio web application
βββ config.py # Project configuration
βββ Dockerfile # Docker build file
βββ docker-compose.yml # Docker Compose configuration
βββ pyproject.toml # Python package configuration
βββ requirements.txt # Dependencies
βββ Fire_PredCopy.ipynb # Original training notebook (reference)
```
## Installation & Setup
### Prerequisites
- Python 3.10+
- [uv](https://docs.astral.sh/uv/) (recommended) or pip
- A webcam for live detection (optional)
### Option 1: Using uv (Recommended)
```bash
# Clone the repository
git clone https://github.com/OpelSpeedster/Forest-Fire-Detection-Using-FirenetCNN-and-XAI-Techniques.git
cd Forest-Fire-Detection-Using-FirenetCNN-and-XAI-Techniques
# Install dependencies
uv pip install -r requirements.txt
# Run the application
uv run python app.py
```
### Option 2: Using pip
```bash
# Clone and install
git clone https://github.com/OpelSpeedster/Forest-Fire-Detection-Using-FirenetCNN-and-XAI-Techniques.git
cd Forest-Fire-Detection-Using-FirenetCNN-and-XAI-Techniques
pip install -r requirements.txt
python app.py
```
### Option 3: Docker
```bash
# Build and run with Docker Compose
docker compose up --build
# Or build manually
docker build -t fire-detection .
docker run -p 7860:7860 -v ./models:/app/models fire-detection
```
### Download the Dataset
This project uses the [Forest Fire Classifier Dataset](https://www.kaggle.com/datasets/google-brain/forest-fire-detection-from-satellite-images). Download and structure as:
```
data/
βββ forestfire-classifier-dataset/
βββ train/
β βββ fire/
β βββ nofire/
β βββ smoke/
βββ val/
β βββ fire/
β βββ nofire/
β βββ smoke/
βββ test/
βββ fire/
βββ nofire/
βββ smoke/
```
**Note:** The dataset folder is named `nofire` (without underscore), which matches the trained model's class ordering.
## Usage
### Web Interface
```bash
uv run python app.py
```
This launches a Gradio web interface at http://localhost:7860 with:
1. **π· Image Classification** - Upload images for fire/smoke/no_fire detection with Grad-CAM visualization
2. **π₯ Video Analysis** - Upload videos for frame-by-frame analysis with class distribution statistics
3. **πΉ Webcam Inference** - Live webcam detection (via Python API)
4. **π Model Information** - Architecture details and performance metrics
### Python API
```python
from src.inference import FireNetInference
# Initialize inference engine
engine = FireNetInference("models/FirenetCNN1.h5")
# Predict on a single image
result = engine.predict_image("path/to/image.jpg")
print(f"Prediction: {result['label']} ({result['confidence']*100:.2f}%)")
# Process a video
stats = engine.predict_video("path/to/video.mp4", output_path="output.mp4")
print(f"Processed {stats['processed_frames']} frames")
# Grad-CAM demo for all classes
demo = engine.create_gradcam_demo_image("path/to/image.jpg")
```
### Training
```bash
# Train a new model
uv run python -m src.training \
--train-dir data/forestfire-classifier-dataset/train \
--val-dir data/forestfire-classifier-dataset/val \
--model-path models/FirenetCNN.keras \
--epochs 100
# With fine-tuning
uv run python -m src.training \
--train-dir data/forestfire-classifier-dataset/train \
--val-dir data/forestfire-classifier-dataset/val \
--epochs 50 --fine-tune --fine-tune-epochs 20
```
### Evaluation
```python
from src.inference import FireNetInference
results = FireNetInference.evaluate_model_on_dataset(
"models/FirenetCNN1.h5",
"data/forestfire-classifier-dataset/test",
output_report="evaluation_report.txt"
)
print(f"Accuracy: {results['accuracy']:.2f}")
print(f"F1 Score: {results['weighted_avg_f1']:.2f}")
```
## Deploying to Hugging Face Spaces (ZeroGPU)
This app is preconfigured to deploy as a Gradio Space with [ZeroGPU](https://huggingface.co/docs/hub/spaces-zerogpu) hardware.
1. Create a new Space at https://huggingface.co/new-space with **SDK: Gradio**.
2. Upload only the files the Space needs (skip large media/notebooks/office docs):
```bash
pip install -U "huggingface_hub[cli]"
huggingface-cli login
huggingface-cli upload <your-username>/<space-name> . --repo-type=space \
--include "app.py" "config.py" "requirements.txt" "packages.txt" "README.md" \
--include "src/**" "models/FirenetCNN1.h5"
```
3. In the Space's **Settings** tab, set **Hardware** to **ZeroGPU**.
4. The app loads `models/FirenetCNN1.h5` by default (override with the `MODEL_PATH` variable/secret in Space Settings if you rename it).
**Note on TensorFlow + ZeroGPU:** Hugging Face's ZeroGPU is officially validated for PyTorch workloads. This app still requests a ZeroGPU slot per prediction via `@spaces.GPU`, and TensorFlow will use the GPU automatically if it's visible inside that worker process; if not, TensorFlow transparently falls back to CPU (no crash), so the Space stays fully functional either way.
## Model Files
| File | Format | Size | Description |
|------|--------|------|-------------|
| `FirenetCNN1.h5` | HDF5 | ~24 MB | Primary trained model |
| `FirenetCNN.h5` | HDF5 | ~24 MB | Alternative version |
| `firenet_model.h5` | HDF5 | ~2 MB | Base model |
The inference engine tries `.keras` format first, then falls back to `.h5`.
## Class Labels
| Index | Label | Description |
|-------|-------|-------------|
| 0 | `fire` | Active fire detected |
| 1 | `no_fire` | No fire detected |
| 2 | `smoke` | Smoke detected |
## Key Technical Details
- **Architecture:** MobileNetV2 + custom classifier head (GlobalAveragePooling2D β Dense(1024) β Dropout(0.5) β Dense(3))
- **Input Size:** 224x224x3
- **Grad-CAM Layer:** `out_relu` (last convolutional layer of MobileNetV2)
- **Preprocessing:** Rescaling to [0, 1], no mean subtraction
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
## Credit
The original model was trained by Vishal S V. This version provides a modern, deployable interface for the FirenetCNN model with Gradio web app, Docker support, and comprehensive Python API.
|