App Explanation Request
App Explanation Request
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
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)
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.")
@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"
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()
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
# 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()
alert_image_path = 'alert.jpg'
cv2.imwrite(alert_image_path, frame)
self.last_alert_time = time.time()
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
await asyncio.gather(*[
client.send(json.dumps(message))
for client in self.clients
])
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()
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
python
`import cv2
`
python
`import asyncio
import websockets
import threading
import json
import os
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/29
python
python
Imports the `ViolenceDetector` class from `detector.py`, which handles violence detection and
alerts.
python
python
`app = Flask(__name__)
`
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
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/29
📦 `class WebApp`
python
`class WebApp:
def __init__(self, detector):
`
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)
`
📸 `generate_frames()`
python
` def generate_frames(self):
`
python
` global camera
while self.running:
`
python
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
python
python
`
`
print(f" 🚨 Alert Triggered! Confidence: {confidence:.2f}%")
python
python
python
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')
`
⏹️ `stop()` method
python
` def stop(self):
`
python
` self.running = False
global camera
if camera is not None:
camera.release()
camera = None
`
python
`
`
print(" 🔴 Camera stopped.")
python
🌐 Flask Routes
python
`@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')
`
python
`@app.route('/stop_camera')
def stop_camera():
webapp.stop()
return "Camera Stopped"
`
🔌 WebSocket Handler
python
python
` global clients
clients.add(websocket)
`
python
` try:
async for message in websocket:
pass
finally:
clients.remove(websocket)
`
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()
`
▶️ App Start
python
python
` start_websocket_server()
`
python
` import atexit
atexit.register(cleanup)
`
python
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
python
`import cv2
`
python
`import asyncio
import websockets
import threading
import json
import os
`
python
Load values from a `.env` file (this file stores secret keys like model path, Telegram token, etc.)
python
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
This reads the `.env` file and makes the variables inside available to use.
python
`app = Flask(__name__)
`
python
`DETECTOR = ViolenceDetector(
model_path=os.getenv("MODEL_PATH"),
telegram_token=os.getenv("TELEGRAM_TOKEN"),
chat_id=int(os.getenv("CHAT_ID"))
)
`
python
🔸 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
python
` self.detector = detector
self.running = True
`
python
` global camera
if camera is None:
camera = cv2.VideoCapture(0)
`
📸 `generate_frames` Method
python
` def generate_frames(self):
`
python
` global camera
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/29
python
` while self.running:
`
python
python
` confidence = self.detector.process_frame(frame)
`
python
python
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/29
python
`
`
print(f" 🚨 Alert Triggered! Confidence: {confidence:.2f}%")
python
Run `send_alert()` function in a background thread to avoid blocking the video stream.
python
python
python
` yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
`
⏹ `stop()` Method
python
` def stop(self):
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/29
python
` self.running = False
`
python
` global camera
if camera is not None:
camera.release()
camera = None
`
python
`
`
print(" 🔴 Camera stopped.")
python
`webapp = WebApp(DETECTOR)
`
🌐 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')
`
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"
`
🔌 WebSocket Functions
python
python
` global clients
clients.add(websocket)
`
python
` try:
async for message in websocket:
pass
finally:
clients.remove(websocket)
`
python
`def start_websocket_server():
DETECTOR.start_websocket_server(websocket_handler)
`
🧹 Cleanup Function
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/29
python
`def cleanup():
webapp.stop()
DETECTOR.shutdown()
`
python
` start_websocket_server()
`
python
` import atexit
atexit.register(cleanup)
`
python
Port: `5000`
Debug: `True` (for development).
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.
`import cv2
`
python
Import the `json` module from Flask (used to convert data to JSON format, e.g. sending alerts).
python
`import numpy as np
`
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
`
python
Used to run tasks in a separate thread so they don’t block the main app.
python
`import websockets
`
🔸 Class: `ViolenceDetector`
python
`class ViolenceDetector:
`
Define a class named `ViolenceDetector` which handles model loading, prediction, Telegram
alerting, and WebSocket messaging.
🔸 `__init__()` Constructor
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/29
python
python
` self.bot = telegram.Bot(token=telegram_token)
`
python
` self.chat_id = chat_id
`
python
` self.last_alert_time = 0
self.alert_cooldown = 5
`
⚙️ Async Setup
python
` self.loop = asyncio.new_event_loop()
self.thread = Thread(target=self.run_loop, daemon=True)
self.thread.start()
`
🌐 WebSocket Setup
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/29
python
` self.clients = set()
self.websocket_server = None
`
` 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.
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.")
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
`
python
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()
`
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}")
🔍 Frame Processing
python
This function prepares the video frame and sends it to the ML model.
python
Resize the frame to match the input size the model expects.
python
python
python
` prediction = self.model.predict(frame)
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/29
python
python
python
python
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.
python
Convert the message to JSON and send to each client using `gather()` to run in parallel.
python
Run the async notify function in the background and catch any errors.
🧹 Clean Up Resources
python
` def shutdown(self):
`
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/29
Stop the WebSocket server if it's still running.
python
python
python
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