From 3d6584e41807ce980e836c5b04d3a0e8d54a6d3d Mon Sep 17 00:00:00 2001 From: yihong1120 Date: Sun, 26 May 2024 01:31:46 +0800 Subject: [PATCH] Refactors --- examples/Stream-Web/app.py | 144 ++--------------------- examples/Stream-Web/routes.py | 73 ++++++++++++ examples/Stream-Web/sockets.py | 44 +++++++ examples/Stream-Web/static/js/label.js | 43 +++++++ examples/Stream-Web/templates/label.html | 22 ++++ examples/Stream-Web/utils.py | 33 ++++++ 6 files changed, 222 insertions(+), 137 deletions(-) create mode 100644 examples/Stream-Web/routes.py create mode 100644 examples/Stream-Web/sockets.py create mode 100644 examples/Stream-Web/static/js/label.js create mode 100644 examples/Stream-Web/templates/label.html create mode 100644 examples/Stream-Web/utils.py diff --git a/examples/Stream-Web/app.py b/examples/Stream-Web/app.py index 70760d5..bcf0d6c 100644 --- a/examples/Stream-Web/app.py +++ b/examples/Stream-Web/app.py @@ -1,13 +1,11 @@ -import base64 -from flask import Flask, abort, render_template, make_response, Response +import threading +from flask import Flask from flask_limiter import Limiter from flask_limiter.util import get_remote_address import redis -from flask_socketio import SocketIO, emit +from flask_socketio import SocketIO from flask_cors import CORS -from typing import List, Tuple -# Connect to Redis r = redis.Redis(host='localhost', port=6379, db=0) app = Flask(__name__) @@ -15,139 +13,11 @@ socketio = SocketIO(app, cors_allowed_origins="*") # Allow all origins for WebSocket connections limiter = Limiter(key_func=get_remote_address) -CACHE_DURATION = 60 # Cache duration in seconds +from .routes import register_routes +from .sockets import register_sockets -def get_labels() -> List[str]: - """ - Retrieve and decode all unique labels from Redis keys. - - Returns: - list: Sorted list of unique labels. - """ - cursor, keys = r.scan() - decoded_keys = [key.decode('utf-8') for key in keys] - labels = {key.split('_')[0] for key in decoded_keys if key.count('_') == 1 and not key.startswith('_') and not key.endswith('_')} - return sorted(labels) - -def get_image_data(label: str) -> List[Tuple[str, str]]: - """ - Retrieve and process image data for a specific label. - - Args: - label (str): The label/category of the images. - - Returns: - list: List of tuples containing base64 encoded images and their names. - """ - cursor, keys = r.scan(match=f'{label}_*') - image_data = [(base64.b64encode(r.get(key)).decode('utf-8'), key.decode('utf-8').split('_')[1]) for key in keys] - return sorted(image_data, key=lambda x: x[1]) - -@app.route('/') -@limiter.limit("60 per minute") -def index() -> str: - """ - Serve the index page with a dynamically generated list of labels from Redis. - - Returns: - str: The rendered 'index.html' page. - """ - labels = get_labels() - return render_template('index.html', labels=labels) - -@app.route('/label/