0% found this document useful (0 votes)
14 views29 pages

App Explanation Request

The document contains Python code for a Flask web application that utilizes a ViolenceDetector class to analyze video frames for signs of violence. It sets up a video feed from a webcam, processes the frames to detect violence, and sends alerts via Telegram and WebSocket clients when high confidence of violence is detected. The application also includes routes for serving the video feed and stopping the camera, along with proper resource cleanup on exit.

Uploaded by

Whatsapp backup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views29 pages

App Explanation Request

The document contains Python code for a Flask web application that utilizes a ViolenceDetector class to analyze video frames for signs of violence. It sets up a video feed from a webcam, processes the frames to detect violence, and sends alerts via Telegram and WebSocket clients when high confidence of violence is detected. The application also includes routes for serving the video feed and stopping the camera, along with proper resource cleanup on exit.

Uploaded by

Whatsapp backup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

App.

py Explanation Request

app.py-
from flask import Flask, Response, render_template
import cv2
import asyncio
import websockets
import threading
import json
import os
from dotenv import load_dotenv
from detector import ViolenceDetector

# Load environment variables


load_dotenv()

app = Flask(__name__)

# Initialize detector
DETECTOR = ViolenceDetector(
model_path=os.getenv("MODEL_PATH"),
telegram_token=os.getenv("TELEGRAM_TOKEN"),
chat_id=int(os.getenv("CHAT_ID"))
)

# Global variables
clients = set() # WebSocket clients
camera = None # Global camera instance
websocket_server = None

class WebApp:
def __init__(self, detector):
self.detector = detector
self.running = True
global camera
if camera is None:
camera = cv2.VideoCapture(0)

def generate_frames(self):
global camera
while self.running:
success, frame = camera.read()
if not success:
break

confidence = self.detector.process_frame(frame)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/29
text = f"Confidence: {confidence:.2f}%"
color = (0, 255, 0) if confidence < 50 else (0, 0, 255)
cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)

if confidence > 90:


🚨
print(f" Alert Triggered! Confidence: {confidence:.2f}%")

# Send alert asynchronously


threading.Thread(target=self.detector.send_alert, args=(frame, confidence),
daemon=True).start()

# Notify WebSocket clients via detector's asyncio loop


self.detector.notify_websocket_clients({"alert": True, "confidence": confidence})

ret, buffer = cv2.imencode('.jpg', frame)


frame = buffer.tobytes()

yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

def stop(self):
"""Stop video processing."""
self.running = False
global camera
if camera is not None:
camera.release()
camera = None
print("🔴 Camera stopped.")

webapp = WebApp(DETECTOR) # Create web app instance

@app.route('/')
def index():
return render_template('index.html')

@app.route('/video_feed')
def video_feed():
return Response(webapp.generate_frames(), mimetype='multipart/x-mixed-replace;
boundary=frame')

@app.route('/stop_camera')
def stop_camera():
webapp.stop()
return "Camera Stopped"

async def websocket_handler(websocket, path):


global clients
clients.add(websocket)
try:
async for message in websocket:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/29
# Handle any incoming messages if needed
pass
finally:
clients.remove(websocket)

def start_websocket_server():
"""
Starts the WebSocket server in the detector's event loop
"""
global websocket_server
DETECTOR.start_websocket_server(websocket_handler)

def cleanup():
"""Clean up resources on shutdown"""
webapp.stop()
DETECTOR.shutdown()

if __name__ == '__main__':
# Start WebSocket server
start_websocket_server()

# Register cleanup function to be called on exit


import atexit
atexit.register(cleanup)

# Start Flask app


app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)

detector.py-
import cv2
from flask import json
import numpy as np
import pickle
import time
import asyncio
import telegram
from threading import Thread
import websockets

class ViolenceDetector:
def __init__(self, model_path, telegram_token, chat_id):
with open(model_path, 'rb') as f:
self.model = pickle.load(f)
self.bot = telegram.Bot(token=telegram_token)
self.chat_id = chat_id
self.last_alert_time = 0
self.alert_cooldown = 5 # Send alert every 5 seconds max

# Initialize async loop properly


self.loop = asyncio.new_event_loop()
self.thread = Thread(target=self.run_loop, daemon=True)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/29
self.thread.start()

# WebSocket variables
self.clients = set()
self.websocket_server = None

def run_loop(self):
"""Run the asyncio event loop in a separate thread"""
asyncio.set_event_loop(self.loop)
self.loop.run_forever()

def send_alert(self, frame, confidence):


"""Send alert to Telegram"""
current_time = time.time()
if current_time - self.last_alert_time < self.alert_cooldown:
cooldown_remaining = int(self.alert_cooldown - (current_time - self.last_alert_time))

print(f" Cooldown active! Alert skipped. Wait {cooldown_remaining} seconds.")
return

alert_image_path = 'alert.jpg'
cv2.imwrite(alert_image_path, frame)

message = f" ⚠️ VIOLENCE DETECTED! Confidence: {confidence:.2f}%"


# Use loop.create_task in a thread-safe way
self.loop.call_soon_threadsafe(lambda: self.loop.create_task(
self._async_send_alert(alert_image_path, message)
))

self.last_alert_time = time.time()

async def _async_send_alert(self, image_path, message):


"""Internal async method to send alert to Telegram"""
try:
# Using with statement for automatic cleanup
async with telegram.Bot(token=self.bot.token) as bot:
with open(image_path, 'rb') as photo:
await bot.send_photo(chat_id=self.chat_id, photo=photo, caption=message)
print(f"✅ Alert sent to Telegram!")
except telegram.error.BadRequest as e:

print(f" Telegram API Error: {e}")
except Exception as e:

print(f" Unexpected Error: {e}")

def process_frame(self, frame):


"""Process video frame and return violence confidence score"""
frame = cv2.resize(frame, (160, 160))
frame = frame.astype('float32') / 255.0
frame = np.expand_dims(frame, axis=0)

prediction = self.model.predict(frame)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/29
confidence = float(prediction[0][0]) * 100

return confidence

def start_websocket_server(self, handler_func):


async def wrapped_handler(websocket, path):
self.clients.add(websocket)
try:
await handler_func(websocket, path)
finally:
self.clients.remove(websocket)

async def start_server():


return await websockets.serve(wrapped_handler, '0.0.0.0', 5678)

# Schedule the server creation in the detector's event loop


future = asyncio.run_coroutine_threadsafe(start_server(), self.loop)
try:
self.websocket_server = future.result(timeout=5)
print("WebSocket server started on port 5678")
except Exception as e:
print(f"Error starting WebSocket server: {e}")

def notify_websocket_clients(self, message):


"""Notify all connected WebSocket clients"""
async def notify():
if not self.clients:
return

await asyncio.gather(*[
client.send(json.dumps(message))
for client in self.clients
])

# Schedule the notify coroutine in the detector's event loop


future = asyncio.run_coroutine_threadsafe(notify(), self.loop)
try:
# Wait for a short timeout
future.result(timeout=1)
except asyncio.TimeoutError:
print("WebSocket notification timed out")
except Exception as e:
print(f"WebSocket notification error: {e}")

def shutdown(self):
"""Clean up resources"""
# Close the websocket server if it exists
if self.websocket_server and not self.websocket_server.done():
self.websocket_server.cancel()

# Stop the event loop


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/29
if self.loop and self.loop.is_running():
self.loop.call_soon_threadsafe(self.loop.stop)

# Join the thread if it's still alive


if self.thread and self.thread.is_alive():
self.thread.join(timeout=1)

print("Detector resources cleaned up")

explain each line one by one

Great! Let's go through each line of both `app.py` and `detector.py`, step by step, in simple and
professional English. We'll start with `app.py`.

📄 `app.py`

python

`from flask import Flask, Response, render_template


`

Imports necessary parts of Flask:

`Flask`: to create the app.


`Response`: to stream video data.

`render_template`: to render HTML templates.

python

`import cv2
`

Imports OpenCV, used for handling video and image processing.

python

`import asyncio
import websockets
import threading
import json
import os
`

`asyncio`: For asynchronous operations (non-blocking).


`websockets`: For real-time communication with clients.

`threading`: To run functions in separate threads.

`json`: To encode/decode data for WebSockets.


`os`: For accessing environment variables or file paths.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/29
python

`from dotenv import load_dotenv


`

Loads variables from a `.env` file into the system environment.

python

`from detector import ViolenceDetector


`

Imports the `ViolenceDetector` class from `detector.py`, which handles violence detection and
alerts.

python

`# Load environment variables


load_dotenv()
`

Loads `.env` values like `MODEL_PATH`, `TELEGRAM_TOKEN`, and `CHAT_ID`.

python

`app = Flask(__name__)
`

Creates the Flask web app.

python

`# Initialize detector
DETECTOR = ViolenceDetector(
model_path=os.getenv("MODEL_PATH"),
telegram_token=os.getenv("TELEGRAM_TOKEN"),
chat_id=int(os.getenv("CHAT_ID"))
)
`

Creates a `ViolenceDetector` object with the ML model path and Telegram bot credentials.

python

`# Global variables
clients = set() # WebSocket clients
camera = None # Global camera instance
websocket_server = None
`

`clients`: Stores all WebSocket-connected clients.

`camera`: Shared camera object (for capturing video).

`websocket_server`: To store the WebSocket server instance.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/29
📦 `class WebApp`

python

`class WebApp:
def __init__(self, detector):
`

This class manages the video stream and detection.

python

` self.detector = detector
self.running = True
`

Stores the detector instance and sets a flag to keep the camera running.

python

` global camera
if camera is None:
camera = cv2.VideoCapture(0)
`

Initializes the webcam only once (if not already created).

📸 `generate_frames()`

python

` def generate_frames(self):
`

Starts generating frames from the webcam.

python

` global camera
while self.running:
`

Loops as long as the camera is active.

python

` success, frame = camera.read()


if not success:
break
`

Reads a frame from the camera. If reading fails, the loop breaks.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/29
python

` confidence = self.detector.process_frame(frame)
`

Sends the frame to the detector and gets back a confidence score for violence.

python

` text = f"Confidence: {confidence:.2f}%"


color = (0, 255, 0) if confidence < 50 else (0, 0, 255)
cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
`

Draws the confidence score on the frame.

Green if < 50%, red if >= 50%.

python

` if confidence > 90:


`

If high confidence of violence detected:

python

`
`
print(f" 🚨 Alert Triggered! Confidence: {confidence:.2f}%")

Logs the alert.

python

` threading.Thread(target=self.detector.send_alert, args=(frame, confidence), daemon=


`

Sends Telegram alert in a background thread.

python

` self.detector.notify_websocket_clients({"alert": True, "confidence": confidence})


`

Sends alert info to connected WebSocket clients.

python

` ret, buffer = cv2.imencode('.jpg', frame)


frame = buffer.tobytes()
`

Converts the frame into JPEG format to send over HTTP.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/29
python

` yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
`

Streams the JPEG frame to the browser using multipart response.

⏹️ `stop()` method

python

` def stop(self):
`

Stops the camera and cleans up.

python

` self.running = False
global camera
if camera is not None:
camera.release()
camera = None
`

Releases the camera.

python

`
`
print(" 🔴 Camera stopped.")

Logs that camera is stopped.

python

`webapp = WebApp(DETECTOR) # Create web app instance


`

Creates an instance of `WebApp` using the detector.

🌐 Flask Routes
python

`@app.route('/')
def index():
return render_template('index.html')
`

Serves the home page (HTML template).


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/29
python

`@app.route('/video_feed')
def video_feed():
return Response(webapp.generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
`

Serves the live video stream as an HTTP response.

python

`@app.route('/stop_camera')
def stop_camera():
webapp.stop()
return "Camera Stopped"
`

API to manually stop the camera.

🔌 WebSocket Handler
python

`async def websocket_handler(websocket, path):


`

Handles WebSocket client connections.

python

` global clients
clients.add(websocket)
`

Adds client to the list.

python

` try:
async for message in websocket:
pass
finally:
clients.remove(websocket)
`

Keeps the client connected until it disconnects.

python

`def start_websocket_server():
DETECTOR.start_websocket_server(websocket_handler)
`

Starts the WebSocket server using the detector’s async event loop.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/29
🧹 Cleanup
python

`def cleanup():
webapp.stop()
DETECTOR.shutdown()
`

Stops the camera and closes background processes.

▶️ App Start
python

`if __name__ == '__main__':


`

Entry point for the script.

python

` start_websocket_server()
`

Starts the WebSocket server.

python

` import atexit
atexit.register(cleanup)
`

Ensures cleanup function runs when the app exits.

python

` app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)


`

Starts the Flask web server.

✅ This covers `app.py`.


Would you like me to explain `detector.py` next in the same way?

it is basic explain each line one by one

Perfect, Dip! Let's now go line by line and explain each line of `app.py` in a very basic and clear way.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/29
🔹 `app.py` — Line-by-Line Explanation
python

`from flask import Flask, Response, render_template


`

Import tools from Flask:


`Flask`: To create the web app.
`Response`: To send video to the browser.

`render_template`: To show HTML pages.

python

`import cv2
`

Import OpenCV library (used to access and process the webcam/video).

python

`import asyncio
import websockets
import threading
import json
import os
`

`asyncio`: For running async code (non-blocking).


`websockets`: To send messages to browser in real-time.
`threading`: To run some functions in background.

`json`: To format data (example: convert Python dictionary to string).


`os`: To access environment variables like paths or tokens.

python

`from dotenv import load_dotenv


`

Load values from a `.env` file (this file stores secret keys like model path, Telegram token, etc.)

python

`from detector import ViolenceDetector


`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/29
Import the ViolenceDetector class from `detector.py`. This class does the main work: model
prediction and Telegram alert.

python

`# Load environment variables


load_dotenv()
`

This reads the `.env` file and makes the variables inside available to use.

python

`app = Flask(__name__)
`

Creates the main Flask web app.

python

`DETECTOR = ViolenceDetector(
model_path=os.getenv("MODEL_PATH"),
telegram_token=os.getenv("TELEGRAM_TOKEN"),
chat_id=int(os.getenv("CHAT_ID"))
)
`

Create a `ViolenceDetector` object using values from `.env` file:


The path to the model file.

The Telegram bot token.


The Telegram chat ID to send alerts.

python

`clients = set() # WebSocket clients


camera = None # Global camera instance
websocket_server = None
`

These are global variables:


`clients`: List of WebSocket users connected.

`camera`: Webcam stream object.


`websocket_server`: The WebSocket server object.

🔸 Class: `WebApp`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/29
python

`class WebApp:
`

Define a class named `WebApp` that will handle the webcam and frame processing.

python

` def __init__(self, detector):


`

This is the constructor. It runs when the class is created.

python

` self.detector = detector
self.running = True
`

Save the detector object.


Set the `running` flag to `True`. Used to control the loop.

python

` global camera
if camera is None:
camera = cv2.VideoCapture(0)
`

Use the global `camera`.


If camera is not already started, start it with `cv2.VideoCapture(0)` (0 means default webcam).

📸 `generate_frames` Method

python

` def generate_frames(self):
`

This function gives video frames one by one.

python

` global camera
`

Use the global camera object.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/29
python

` while self.running:
`

Loop continues until `self.running` is set to `False`.

python

` success, frame = camera.read()


if not success:
break
`

Read a frame from the camera.


If failed, exit the loop.

python

` confidence = self.detector.process_frame(frame)
`

Send the frame to the model.


Get back the confidence score (how sure it is that there is violence).

python

` text = f"Confidence: {confidence:.2f}%"


color = (0, 255, 0) if confidence < 50 else (0, 0, 255)
`

Create a string like `"Confidence: 95.22%"`.

If confidence < 50, use green color.


Else use red color.

python

` cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)


`

Draw the confidence text on the video frame using OpenCV.

python

` if confidence > 90:


`

If violence confidence is very high (above 90%):

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/29
python

`
`
print(f" 🚨 Alert Triggered! Confidence: {confidence:.2f}%")

Print a message in the terminal.

python

` threading.Thread(target=self.detector.send_alert, args=(frame, confidence), daemon=


`

Run `send_alert()` function in a background thread to avoid blocking the video stream.

python

` self.detector.notify_websocket_clients({"alert": True, "confidence": confidence})


`

Send real-time alert to all WebSocket users.

python

` ret, buffer = cv2.imencode('.jpg', frame)


frame = buffer.tobytes()
`

Convert the video frame to JPEG format.

Convert it to bytes so it can be sent over the internet.

python

` yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
`

Yield (send) the image to the browser in a streaming format.

⏹ `stop()` Method

python

` def stop(self):
`

Function to stop the camera.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/29
python

` self.running = False
`

Set the flag to false to stop the loop.

python

` global camera
if camera is not None:
camera.release()
camera = None
`

Release the webcam so it's not locked.

python

`
`
print(" 🔴 Camera stopped.")

Print in terminal that camera has stopped.

python

`webapp = WebApp(DETECTOR)
`

Create a `WebApp` object that starts the camera and detection.

🌐 Flask Routes
python

`@app.route('/')
def index():
return render_template('index.html')
`

Show the home page (`index.html`) when the user opens the site.

python

`@app.route('/video_feed')
def video_feed():
return Response(webapp.generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
`

Route to send the video stream to the browser.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/29
python

`@app.route('/stop_camera')
def stop_camera():
webapp.stop()
return "Camera Stopped"
`

Route to stop the camera using a URL.

🔌 WebSocket Functions
python

`async def websocket_handler(websocket, path):


`

Function to manage new WebSocket connections.

python

` global clients
clients.add(websocket)
`

Add the new client to the list.

python

` try:
async for message in websocket:
pass
finally:
clients.remove(websocket)
`

Keeps listening to the client until they disconnect.

When they disconnect, remove them.

python

`def start_websocket_server():
DETECTOR.start_websocket_server(websocket_handler)
`

Start the WebSocket server using the detector's internal method.

🧹 Cleanup Function
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/29
python

`def cleanup():
webapp.stop()
DETECTOR.shutdown()
`

Stop everything properly when the app is closed.

▶️ Run the App


python

`if __name__ == '__main__':


`

If this script is run directly:

python

` start_websocket_server()
`

Start the WebSocket server first.

python

` import atexit
atexit.register(cleanup)
`

Tell Python to call `cleanup()` when the program is exiting.

python

` app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)


`

Start the Flask server:


Host: `0.0.0.0` allows access from other devices on the network.

Port: `5000`
Debug: `True` (for development).

`use_reloader=False`: Prevents double-starting the app.

✅ That’s a complete line-by-line explanation of `app.py`.

Would you like to continue with `detector.py` in the same way?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/29
yes

Great! Let’s now do the line-by-line explanation of `detector.py` — just like we did for `app.py`. This
file is mainly responsible for model prediction, Telegram alerts, and WebSocket communication.

🔹 `detector.py` — Line-by-Line Explanation


python

`import cv2
`

Import OpenCV library to work with images and video frames.

python

`from flask import json


`

Import the `json` module from Flask (used to convert data to JSON format, e.g. sending alerts).

python

`import numpy as np
`

Import NumPy to handle image arrays and preprocessing.

python

`import pickle
`

`pickle` is used to load the machine learning model that was saved earlier.

python

`import time
`

Provides functions related to time (used for cooldown logic between alerts).

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/29
python

`import asyncio
`

Helps to run async functions like WebSocket and Telegram alert sending.

python

`import telegram
`

This is the `python-telegram-bot` library to send messages or photos to Telegram.

python

`from threading import Thread


`

Used to run tasks in a separate thread so they don’t block the main app.

python

`import websockets
`

Used to run a WebSocket server and send real-time data to clients.

🔸 Class: `ViolenceDetector`

python

`class ViolenceDetector:
`

Define a class named `ViolenceDetector` which handles model loading, prediction, Telegram
alerting, and WebSocket messaging.

🔸 `__init__()` Constructor

python

` def __init__(self, model_path, telegram_token, chat_id):


`

This function runs when the object is created.


Takes 3 values: model file path, Telegram token, and chat ID.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/29
python

` with open(model_path, 'rb') as f:


self.model = pickle.load(f)
`

Open the saved ML model file in read-binary mode.


Load the model using `pickle`.

python

` self.bot = telegram.Bot(token=telegram_token)
`

Create a Telegram bot using the token.

python

` self.chat_id = chat_id
`

Save the Telegram chat ID to send alerts to that user or group.

python

` self.last_alert_time = 0
self.alert_cooldown = 5
`

`last_alert_time`: Keeps track of when the last alert was sent.


`alert_cooldown`: Wait at least 5 seconds before sending the next alert.

⚙️ Async Setup
python

` self.loop = asyncio.new_event_loop()
self.thread = Thread(target=self.run_loop, daemon=True)
self.thread.start()
`

Create a new async event loop (used to run async tasks).


Start the event loop in a background thread so it doesn't block the main app.

🌐 WebSocket Setup
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/29
python

` self.clients = set()
self.websocket_server = None
`

`clients`: A list of connected WebSocket clients.


`websocket_server`: To hold the server instance.

🌀 Run Async Loop


python

` def run_loop(self):
asyncio.set_event_loop(self.loop)
self.loop.run_forever()
`

This function runs the async event loop continuously in the background thread.

🚨 Send Alert to Telegram


python

` def send_alert(self, frame, confidence):


`

This function is called when violence is detected and sends an alert to Telegram.

python

` current_time = time.time()
if current_time - self.last_alert_time < self.alert_cooldown:
`

Get current time and check if enough time has passed since last alert.

python

`
print(f"
return

cooldown_remaining = int(self.alert_cooldown - (current_time - self.last_alert_time))
Cooldown active! Alert skipped. Wait {cooldown_remaining} seconds.")

If still in cooldown, skip sending the alert and show a message.

python

` alert_image_path = 'alert.jpg'
cv2.imwrite(alert_image_path, frame)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/29
`

Save the current frame as an image file called `alert.jpg`.

python

` message = f"⚠️VIOLENCE DETECTED! Confidence: {confidence:.2f}%"


`

Create the alert message to be sent with the photo.

python

` self.loop.call_soon_threadsafe(lambda: self.loop.create_task(
self._async_send_alert(alert_image_path, message)
))
`

Schedule the `_async_send_alert()` function to run in the async loop without blocking the current
thread.

python

` self.last_alert_time = time.time()
`

Update the `last_alert_time` to the current time.

📤 Async Function to Send Alert


python

` async def _async_send_alert(self, image_path, message):


`

This is an internal async function to send the image and message to Telegram.

python

` try:
async with telegram.Bot(token=self.bot.token) as bot:
with open(image_path, 'rb') as photo:

`
print(f" ✅
await bot.send_photo(chat_id=self.chat_id, photo=photo, caption=message)
Alert sent to Telegram!")

Open the bot and image, then send the photo with the alert message.
Show success message in terminal.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/29
python

`

except telegram.error.BadRequest as e:
print(f" Telegram API Error: {e}")

`
print(f"❌
except Exception as e:
Unexpected Error: {e}")

Catch and print any error messages if sending fails.

🔍 Frame Processing
python

` def process_frame(self, frame):


`

This function prepares the video frame and sends it to the ML model.

python

` frame = cv2.resize(frame, (160, 160))


`

Resize the frame to match the input size the model expects.

python

` frame = frame.astype('float32') / 255.0


`

Normalize pixel values from 0–255 to 0–1.

python

` frame = np.expand_dims(frame, axis=0)


`

Add a batch dimension, so shape becomes (1, 160, 160, 3).

python

` prediction = self.model.predict(frame)
`

Send the frame to the model and get prediction.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/29
python

` confidence = float(prediction[0][0]) * 100


return confidence
`

Convert model output to percentage confidence and return it.

🌐 Start WebSocket Server


python

` def start_websocket_server(self, handler_func):


`

Starts a WebSocket server using a handler function.

python

` async def wrapped_handler(websocket, path):


self.clients.add(websocket)
try:
await handler_func(websocket, path)
finally:
self.clients.remove(websocket)
`

Handle each new WebSocket connection and track them.

python

` async def start_server():


return await websockets.serve(wrapped_handler, '0.0.0.0', 5678)
`

Create a WebSocket server on port `5678`.

python

` future = asyncio.run_coroutine_threadsafe(start_server(), self.loop)


`

Start the server in the background async loop.

python

` try:
self.websocket_server = future.result(timeout=5)
print("WebSocket server started on port 5678")
except Exception as e:
print(f"Error starting WebSocket server: {e}")
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/29
Wait for server to start. If it starts, print message; otherwise show error.

📡 Send Messages to Web Clients


python

` def notify_websocket_clients(self, message):


`

Send a message to all WebSocket clients.

python

` async def notify():


if not self.clients:
return
await asyncio.gather(*[
client.send(json.dumps(message))
for client in self.clients
])
`

Convert the message to JSON and send to each client using `gather()` to run in parallel.

python

` future = asyncio.run_coroutine_threadsafe(notify(), self.loop)


try:
future.result(timeout=1)
except asyncio.TimeoutError:
print("WebSocket notification timed out")
except Exception as e:
print(f"WebSocket notification error: {e}")
`

Run the async notify function in the background and catch any errors.

🧹 Clean Up Resources
python

` def shutdown(self):
`

This function is called when app exits. It stops everything safely.

python

` if self.websocket_server and not self.websocket_server.done():


self.websocket_server.cancel()
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/29
Stop the WebSocket server if it's still running.

python

` if self.loop and self.loop.is_running():


self.loop.call_soon_threadsafe(self.loop.stop)
`

Stop the async loop safely.

python

` if self.thread and self.thread.is_alive():


self.thread.join(timeout=1)
`

Wait for the thread to finish.

python

` print("Detector resources cleaned up")


`

Print cleanup done message.

✅ That’s the full explanation of `detector.py` — in a beginner-friendly, line-by-line way!

Would you like me to now explain the `.env` file and how to run the full app?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/29

You might also like