FirenetCNN / README.md
OpelSpeedster's picture
Update README.md
677fa33 verified
|
Raw
History Blame Contribute Delete
9.24 kB
---
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
[![Ask DeepWiki](https://devin.ai/assets/askdeepwiki.png)](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.