from flask import Flask, Response
import cv2
import time

app = Flask(__name__)
camera = cv2.VideoCapture(11)  # cv2.CAP_V4L2 

def generate_frames():
    prev_time = time.time()
    while True:
        success, frame = camera.read()
        if not success:
            break

        # FPS calculation
        curr_time = time.time()
        fps = 1 / (curr_time - prev_time)
        prev_time = curr_time

        # frame_height, frame_width, _ = frame.shape
        # print(f"Frame size (width x height): {frame_width}x{frame_height}")
        # print(f"FPS: {fps:.2f}")

        # Encode frame as JPEG
        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()

        # Stream frame as multipart content
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video')
def video():
    return Response(generate_frames(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return "<h1>Live Camera Feed</h1><img src='/video'>"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)


