Spaces:
Sleeping
Sleeping
# Flask Backend (app.py) | |
from flask import Flask, render_template, Response, jsonify | |
import psutil | |
import cv2 | |
import numpy as np | |
from ultralytics import YOLO | |
import threading | |
import queue | |
app = Flask(__name__) | |
modelName = "yolov9c-seg.pt" | |
model = YOLO(modelName) | |
# Global variables for frame handling | |
frame_queue = queue.Queue(maxsize=2) | |
processed_frame_queue = queue.Queue(maxsize=2) | |
current_frame = None | |
processing_active = False | |
def process_frames(): | |
global processing_active | |
while processing_active: | |
if not frame_queue.empty(): | |
frame = frame_queue.get() | |
results = model( | |
frame, | |
show=False, | |
save=False, | |
show_boxes=True, | |
show_labels=True, | |
imgsz=640, | |
iou=0.1, | |
max_det=20, | |
) | |
processed_frame = results[0].plot() | |
processed_frame = cv2.cvtColor(np.array(processed_frame), cv2.COLOR_RGB2BGR) | |
if processed_frame_queue.full(): | |
processed_frame_queue.get() # Remove old frame | |
processed_frame_queue.put(processed_frame) | |
def home(): | |
return render_template("index.html") | |
def sysInfo(): | |
ram = psutil.virtual_memory() | |
ram_usage = ram.percent | |
cpu_usage = psutil.cpu_percent(interval=1) | |
data = {"ram": ram_usage, "cpu": cpu_usage} | |
return jsonify(data) | |
def generate_frames(): | |
global processing_active | |
while True: | |
if not processed_frame_queue.empty(): | |
frame = processed_frame_queue.get() | |
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 video_feed(): | |
return Response(generate_frames(), | |
mimetype='multipart/x-mixed-replace; boundary=frame') | |
def start_processing(): | |
global processing_active | |
if not processing_active: | |
processing_active = True | |
threading.Thread(target=process_frames, daemon=True).start() | |
return jsonify({"status": "started"}) | |
def stop_processing(): | |
global processing_active | |
processing_active = False | |
return jsonify({"status": "stopped"}) | |
def update_frame(): | |
global current_frame | |
data = request.get_json() | |
frame_data = np.array(data['frame']) | |
if frame_queue.full(): | |
frame_queue.get() # Remove old frame | |
frame_queue.put(frame_data) | |
return jsonify({"status": "success"}) | |
if __name__ == "__main__": | |
app.run(debug=True, host="0.0.0.0", port=7860) |