# sunil-s2004/animal-intrusion-detection-and-alert-system architecture

> Architecture diagram of the GitHub repository sunil-s2004/animal-intrusion-detection-and-alert-system, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-02-27). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/sunil-s2004/animal-intrusion-detection-and-alert-system
- Repository: https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system

## Overview

##### What this project is (based on *this repo’s actual contents*)
From the file tree, this is primarily an **AI/ML + alerting prototype** composed of two main tracks:

##### Real-time animal detection + alerting
- `yolov8_firebase_files/best.pt` → a trained **YOLOv8** model weight file
- `yolov8_firebase_files/animaldetectionandfirebase.py` → detection + **Firebase** integration
- `yolov8_firebase_files/animaldectionandtwillio.py` → detection + **Twilio** SMS/alert integration

##### Analytics / prediction (offline, notebook-driven)
- `Animal_intrusion_analysis_prediction/animal_conflict_updated_dataset.csv` → historical dataset
- `Animal_intrusion_analysis_prediction/EDA_animal.ipynb` + `Exploratory Data Analysis.docx` → EDA/reporting
- `Animal_intrusion_analysis_prediction/lstm_prediction.ipynb` + `animal_intrusion_lstm_model.keras` → an **LSTM forecasting model** artifact and its training/inference notebook

Include:
- **Camera / Video Sources** (CCTV, RTSP stream, file video feed—whatever your scripts support)
- **Firebase** (external managed service)
- **Twilio** (external managed service)
- **End Users** (farmers/forest officers)
- *(Optional, if matching README vision)* “Mobile App / Dashboard” as an external consumer of Firebase data

- Video Stream → Detection System
- Detection Events/Images/Metadata → Firebase
- Alert Requests → Twilio → SMS/Call/WhatsApp → Users

Split the system into containers that map to actual artifacts:

**Container 1: YOLOv8 Detection Runtime (Python)**
- Inputs: video frames

**Container 2: Firebase Publisher (Python integration inside script)**
- Writes: detection logs, image URLs, timestamps, geo fields (if available)

**Container 3: Twilio Notifier (Python integration inside script)**
- Sends SMS/calls when detection threshold is met

**Container 4: Analytics / Prediction Workspace (Jupyter + model artifact)**
- Reads historical CSV
- Produces EDA outputs (docx/notebook)
- Trains/loads `animal_intrusion_lstm_model.keras`
- Outputs forecasts (risk score / predicted intrusion time windows)

**Data store (local repo assets)**
- `best.pt` (YOLO model weights)
- `animal_conflict_updated_dataset.csv` (historical data)
- `animal_intrusion_lstm_model.keras` (LSTM model)

- `best.pt` → YOLOv8 Runtime (model load)
- YOLOv8 Runtime → Firebase (event data)
- YOLOv8 Runtime → Twilio (notification trigger)
- CSV → EDA Notebook / LSTM Notebook
- LSTM Model (.keras) → Prediction Notebook (inference)

Because the repo is script/notebook-driven, represent internal components as functional blocks rather than modules:

For `animaldetectionandfirebase.py` / `animaldectionandtwillio.py`:
- **Frame Ingestor** (OpenCV capture / video read)
- **Preprocessing** (resize, normalize, batching)
- **YOLOv8 Inference** (Ultralytics runtime)
- **Postprocessing** (NMS, class filtering, confidence threshold)
- **Decision / Policy Engine**
- “alert if animal in {X} and confidence > T and cooldown elapsed”
- **Evidence Builder**
- annotated frame snapshot, metadata payload
- **Publishers**
- Firebase writer
- Twilio sender
- **Observability (if any)**
- logs, counters (even if just console logging—show it)

For the notebooks:
- **Data Loading / Cleaning**
- **Feature Engineering**
- **Train/Test Split**
- **LSTM Training**
- **Evaluation**
- **Forecast Generation**

This level is where you show *exactly* how detection becomes an alert and a stored event.

##### Video input
- Protocol: RTSP/WebRTC/file (label what you actually support)
- Data: frames

##### Inference output
- Data: `{timestamp, animal_label, confidence, bbox[], frame_snapshot?}`

##### Firebase write
- Data: detection event + optional image upload

##### Twilio alert
- Data: alert message with animal type, location, time, severity

##### `.keras` artifact → prediction generation → “risk windows / risk score”
4. *(Optional integration)* risk outputs stored back in Firebase so the same client (mobile/dashboard) can consume both realtime + predictive data

##### Architectural patterns to highlight (as they apply here)

- **Event-driven alerting**: detection event triggers notification
- **Separation of concerns**:
- Inference vs notification vs persistence
- **Model artifact lifecycle**:
- **Two-speed architecture**:
- “hot path” (real-time detection) vs “cold path” (batch analytics/prediction)

Grounded by repo:
- YOLOv8 (`best.pt`, detection scripts)
- Python + OpenCV (implied by YOLO video pipeline; if your scripts import cv2, reflect that)
- Firebase integration (script name strongly indicates it)
- Twilio integration (script name strongly indicates it)
- TensorFlow/Keras for LSTM (`.keras` model)
- Jupyter notebooks for EDA/training

Mentioned in README but not present (optional “future” lane):
- Flutter mobile app
- Backend API (Flask/FastAPI)
- PostgreSQL
- PowerBI/Tableau dashboards

##### Practical way to “not overthink it” but still be very detailed

- `best.pt` → “YOLO weights”
- `animaldetectionandfirebase.py` → “Detector + Firebase writer”
- `animaldectionandtwillio.py` → “Detector + Twilio notifier”
- `animal_conflict_updated_dataset.csv` → “Historical dataset”
- `EDA_animal.ipynb` + `Exploratory Data Analysis.docx` → “EDA pipeline + report”
- `lstm_prediction.ipynb` + `.keras` → “Prediction pipeline + trained model”

- weights → detector
- detector → firebase/twilio
- dataset → eda/lstm training → model → prediction outputs

**Step 3: Add external actors**
- cameras → detector
- users ← twilio
- users/app/dashboard ← firebase (if applicable)

**Step 4: Only then add “README vision” components as optional**

## Diagram (Mermaid)

```mermaid
flowchart TD

%% =========================
%% Level 0: System Context
%% =========================
subgraph "System Context (Level 0)"
  direction TB

  VS["Camera / Video Sources\n(RTSP / CCTV / File)"]:::external
  SYS["Detection & Alert System\n(this repo)"]:::system
  FB["Firebase\n(DB + Storage)"]:::cloud
  TW["Twilio\n(SMS/Call/WhatsApp API)"]:::cloud
  U["End Users\n(Farmers / Forest Officers)"]:::external
  CL["Mobile App / Dashboard\n(Optional consumer of Firebase)"]:::planned

  VS -->|"video_frames"| SYS
  SYS -->|"detection_events + images"| FB
  SYS -->|"alert_requests"| TW
  TW -->|"SMS/Call/WhatsApp"| U
  U <-->|"views_events & acknowledges"| CL
  CL <-->|"reads/writes"| FB
end

%% =========================
%% Level 1: Containers (Repo-accurate)
%% =========================
subgraph "Containers (Level 1) — What exists in this repo"
  direction TB

  subgraph "Hot Path: Real-time detection + alerting"
    direction TB
    YW[("YOLOv8 Model Weights\nbest.pt")]:::artifact
    RTFB["YOLOv8 Detector + Firebase Publisher\n(Python runtime)"]:::runtime
    RTTW["YOLOv8 Detector + Twilio Notifier\n(Python runtime)"]:::runtime
    COOL["Cooldown / Rate Limiting\n(prevent SMS spam)"]:::policy
  end

  subgraph "Cold Path: Offline analytics / prediction"
    direction TB
    CSV[("Historical Dataset\nanimal_conflict_updated_dataset.csv")]:::datastore
    EDA["EDA Notebook\n(Jupyter)"]:::notebook
    DOC["EDA Report\n(Word doc)"]:::doc
    LSTMNB["LSTM Training/Prediction Notebook\n(Jupyter)"]:::notebook
    KERAS[("Trained LSTM Model Artifact\nanimal_intrusion_lstm_model.keras")]:::artifact
    FORE["Forecast Output\n(risk_score / risk_windows)"]:::output
  end
end

%% =========================
%% Level 2: Components (inside scripts)
%% =========================
subgraph "Components (Level 2) — Inside detection scripts"
  direction TB

  subgraph "animaldetectionandfirebase.py"
    direction TB
    FB_Ingest["Frame Ingestor\n(OpenCV capture/read)"]:::component
    FB_Pre["Preprocessing\n(resize/normalize/batch)"]:::component
    FB_YOLO["YOLOv8 Inference\n(Ultralytics runtime)"]:::component
    FB_Post["Postprocessing\n(NMS + class/conf filter)"]:::component
    FB_Policy["Decision / Policy Engine\n(threshold + cooldown)"]:::policy
    FB_Evid["Evidence Builder\n(annotated snapshot + metadata)"]:::component
    FB_Pub["Firebase Writer\n(event + image upload)"]:::component
    FB_Log["Observability\n(console logs)"]:::obs
  end

  subgraph "animaldectionandtwillio.py"
    direction TB
    TW_Ingest["Frame Ingestor\n(OpenCV capture/read)"]:::component
    TW_Pre["Preprocessing\n(resize/normalize/batch)"]:::component
    TW_YOLO["YOLOv8 Inference\n(Ultralytics runtime)"]:::component
    TW_Post["Postprocessing\n(NMS + class/conf filter)"]:::component
    TW_Policy["Decision / Policy Engine\n(threshold + cooldown)"]:::policy
    TW_Evid["Evidence Builder\n(message payload fields)"]:::component
    TW_Send["Twilio Sender\n(SMS/call trigger)"]:::component
    TW_Log["Observability\n(console logs)"]:::obs
  end
end

subgraph "Components (Level 2) — Inside notebooks"
  direction TB
  NB_Load["Data Loading / Cleaning"]:::component
  NB_FE["Feature Engineering"]:::component
  NB_Split["Train/Test Split"]:::component
  NB_Train["LSTM Training\n(TensorFlow/Keras)"]:::component
  NB_Eval["Evaluation"]:::component
  NB_Fore["Forecast Generation"]:::component
end

%% =========================
%% Optional / Planned (README vision)
%% =========================
subgraph "Planned / Out of repo scope (README vision)"
  direction TB
  README["README Vision\n(full-stack system description)"]:::planned
  API["Backend API\n(Flask/FastAPI)"]:::planned
  PG[("PostgreSQL")]:::plannedDB
  APP["Flutter Mobile App"]:::planned
  BI["Dashboards\n(PowerBI/Tableau)"]:::planned
end

%% =========================
%% Connections: Context -> Containers
%% =========================
VS -->|"frames"| RTFB
VS -->|"frames"| RTTW

RTFB -->|"publishes_event {ts,label,conf,bbox}\n+ uploads_image"| FB
RTTW -->|"sends_alert_message\n(animal,time,severity,location?)"| COOL
COOL -->|"rate_limited_alert"| TW
TW -->|"notifies"| U

%% =========================
%% Connections: Artifacts/Stores -> Containers
%% =========================
YW -->|"model_load (weights)"| RTFB
YW -->|"model_load (weights)"| RTTW

CSV -->|"reads"| EDA
EDA -->|"findings"| DOC

CSV -->|"reads"| LSTMNB
LSTMNB -->|"trains/exports"| KERAS
KERAS -->|"loads_for_inference"| LSTMNB
LSTMNB -->|"generates"| FORE
FORE -.->|"optional_publish_predictions"| FB

%% =========================
%% Connections: Containers -> Components (detailed hot path)
%% =========================
RTFB -->|"implements"| FB_Ingest
FB_Ingest -->|"frames"| FB_Pre
FB_Pre -->|"tensor"| FB_YOLO
FB_YOLO -->|"raw_detections"| FB_Post
FB_Post -->|"filtered_detections"| FB_Policy
FB_Policy -->|"if_triggered"| FB_Evid
FB_Evid -->|"event_payload + image"| FB_Pub
FB_Pub -->|"writes"| FB_Log
FB_Pub -->|"event+image"| FB

RTTW -->|"implements"| TW_Ingest
TW_Ingest -->|"frames"| TW_Pre
TW_Pre -->|"tensor"| TW_YOLO
TW_YOLO -->|"raw_detections"| TW_Post
TW_Post -->|"filtered_detections"| TW_Policy
TW_Policy -->|"if_triggered"| TW_Evid
TW_Evid -->|"alert_payload"| TW_Send
TW_Send -->|"requests"| COOL
TW_Send -->|"writes"| TW_Log

%% =========================
%% Connections: Notebooks -> Components (detailed cold path)
%% =========================
EDA -->|"pipeline_steps"| NB_Load
NB_Load --> NB_FE --> NB_Split --> NB_Train --> NB_Eval
NB_Eval -->|"insights"| DOC

LSTMNB -->|"pipeline_steps"| NB_Load
NB_Load --> NB_FE --> NB_Split --> NB_Train --> NB_Eval --> NB_Fore
NB_Fore -->|"risk_score / risk_windows"| FORE

%% =========================
%% Planned section wiring (kept separate & dashed intent)
%% =========================
README -.->|"describes"| API
API -.->|"stores"| PG
APP -.->|"calls"| API
BI -.->|"reads"| PG
APP -.->|"reads/writes_events"| FB
BI -.->|"optional_reads"| FB

%% =========================
%% Click Events (from component_mapping)
%% =========================
click YW "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/yolov8_firebase_files/best.pt"
click RTFB "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/yolov8_firebase_files/animaldetectionandfirebase.py"
click RTTW "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/yolov8_firebase_files/animaldectionandtwillio.py"
click CSV "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/Animal_intrusion_analysis_prediction/animal_conflict_updated_dataset.csv"
click EDA "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/Animal_intrusion_analysis_prediction/EDA_animal.ipynb"
click DOC "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/Animal_intrusion_analysis_prediction/Exploratory Data Analysis.docx"
click KERAS "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/Animal_intrusion_analysis_prediction/animal_intrusion_lstm_model.keras"
click LSTMNB "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/Animal_intrusion_analysis_prediction/lstm_prediction.ipynb"
click README "https://github.com/sunil-s2004/animal-intrusion-detection-and-alert-system/blob/main/README.md"

%% =========================
%% Styles (color is mandatory)
%% =========================
classDef external fill:#f3f4f6,stroke:#374151,stroke-width:1px,color:#111827;
classDef system fill:#dbeafe,stroke:#1d4ed8,stroke-width:1.5px,color:#0b1b3a;
classDef cloud fill:#e0f2fe,stroke:#0284c7,stroke-width:1.5px,color:#0b1b3a;
classDef runtime fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#052e16;
classDef component fill:#ecfeff,stroke:#0891b2,stroke-width:1px,color:#083344;
classDef policy fill:#fff7ed,stroke:#f97316,stroke-width:1.5px,color:#431407;
classDef obs fill:#fefce8,stroke:#ca8a04,stroke-width:1px,color:#3f2a00;
classDef datastore fill:#fae8ff,stroke:#a21caf,stroke-width:1.5px,color:#2e0a3a;
classDef artifact fill:#ede9fe,stroke:#6d28d9,stroke-width:1.5px,color:#1f1147;
classDef notebook fill:#ffe4e6,stroke:#be123c,stroke-width:1.5px,color:#4a0616;
classDef doc fill:#fff1f2,stroke:#9f1239,stroke-width:1px,color:#4a0616;
classDef output fill:#f0fdf4,stroke:#22c55e,stroke-width:1px,color:#052e16;

classDef planned fill:#ffffff,stroke:#94a3b8,stroke-width:1.5px,color:#334155,stroke-dasharray: 6 4;
classDef plannedDB fill:#ffffff,stroke:#94a3b8,stroke-width:1.5px,color:#334155,stroke-dasharray: 6 4;
```
