from flask import Flask, Response, render_template_string, request
import threading

app = Flask(__name__)

frame = None
lock = threading.Lock()

@app.route('/upload_frame', methods=['POST'])
def upload_frame():
    global frame
    with lock:
        frame = request.data
    return '', 204

def generate():
    global frame
    while True:
        with lock:
            if frame is None:
                continue
            img = frame
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + img + b'\r\n')
        
@app.route('/stream')
def stream():
    return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    # page simple avec le stream vidéo
    return render_template_string('''
        <html>
            <body>
                <h1>Stream d'écran</h1>
                <img src="{{ url_for('stream') }}" width="80%">
            </body>
        </html>
    ''')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
