|
from flask import Flask, render_template, Response, request |
|
from flask_cors import CORS |
|
import base64 |
|
from threading import Lock |
|
|
|
app = Flask(__name__) |
|
CORS(app) |
|
|
|
|
|
latest_frame = None |
|
frame_lock = Lock() |
|
|
|
@app.route('/') |
|
def index(): |
|
return render_template('index.html') |
|
|
|
@app.route('/receive_frame', methods=['POST']) |
|
def receive_frame(): |
|
global latest_frame |
|
try: |
|
frame_data = request.get_json()['frame'] |
|
with frame_lock: |
|
latest_frame = frame_data |
|
return {'status': 'success'}, 200 |
|
except Exception as e: |
|
return {'status': 'error', 'message': str(e)}, 400 |
|
|
|
@app.route('/video_feed') |
|
def video_feed(): |
|
def generate_frames(): |
|
global latest_frame |
|
while True: |
|
with frame_lock: |
|
current_frame = latest_frame |
|
|
|
if current_frame: |
|
try: |
|
|
|
frame_data = current_frame.split(',')[1].encode() |
|
yield (b'--frame\r\n' |
|
b'Content-Type: image/jpeg\r\n\r\n' + |
|
base64.b64decode(frame_data) + b'\r\n') |
|
except Exception: |
|
continue |
|
|
|
return Response(generate_frames(), |
|
mimetype='multipart/x-mixed-replace; boundary=frame') |
|
|
|
if __name__ == '__main__': |
|
app.run(debug=True, threaded=True) |