### Install and Launch PrintGuard via PyPI Source: https://context7.com/oliverbravery/printguard/llms.txt Install the pre-release version of PrintGuard using pip and start the server. The server will initially boot into setup mode. ```bash pip install --pre printguard ``` ```bash printguard # Output: WARNING: Starting in setup mode. Available at http://localhost:8000/setup ``` -------------------------------- ### Complete Setup Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Marks the initial setup process as complete, specifying the startup mode. ```APIDOC ## POST /setup/complete ### Description Mark setup as complete. ### Method POST ### Endpoint /setup/complete ### Parameters #### Request Body - **startup_mode** (string) - Required - The mode to start the application in: 'setup', 'local', or 'tunnel'. - **tunnel_provider** (string) - Optional - The tunnel provider if 'tunnel' startup mode is selected: 'ngrok' or 'cloudflare'. ### Response #### Success Response (200) - JSON confirmation message. ``` -------------------------------- ### Complete Setup Source: https://context7.com/oliverbravery/printguard/llms.txt Marks setup as complete and sets the startup mode for PrintGuard. ```APIDOC ## POST /setup/complete — Finalise setup and set startup mode ### Description Marks setup as complete. On the next launch, `run()` reads this mode and boots accordingly (`local` = HTTPS on LAN, `tunnel` = via reverse proxy). ### Method POST ### Endpoint http://localhost:8000/setup/complete ### Parameters #### Request Body - **startup_mode** (string) - Required - The desired startup mode ('local' or 'tunnel'). - **tunnel_provider** (string) - Optional - The tunnel provider if `startup_mode` is 'tunnel' (e.g., 'ngrok'). ### Request Example ```json # Local network mode { "startup_mode": "local" } # Tunnel mode via ngrok { "startup_mode": "tunnel", "tunnel_provider": "ngrok" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Setup complete. Restart PrintGuard to apply settings." } ``` -------------------------------- ### Install PrintGuard via PyPI Source: https://github.com/oliverbravery/printguard/blob/main/README.md Installs the latest pre-release version of PrintGuard using pip. Requires the `--pre` flag. After installation, run `printguard` to start the web interface. ```bash pip install --pre printguard ``` -------------------------------- ### Start PrintGuard Web Interface Source: https://github.com/oliverbravery/printguard/blob/main/README.md Command to launch the PrintGuard web interface after installation via pip. ```bash printguard ``` -------------------------------- ### Serve Setup Page Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the HTML content for the setup page. ```APIDOC ## GET /setup ### Description Serve the setup page. ### Method GET ### Endpoint /setup ### Response #### Success Response (200) - HTML content of the setup page. ``` -------------------------------- ### Complete Setup with Startup Mode Source: https://context7.com/oliverbravery/printguard/llms.txt Finalizes setup and sets the startup mode for PrintGuard. Use 'local' for LAN access or 'tunnel' for reverse proxy access. ```bash # Local network mode curl -X POST http://localhost:8000/setup/complete \ -H "Content-Type: application/json" \ -d '{ "startup_mode": "local" }' ``` ```bash # Tunnel mode via ngrok curl -X POST http://localhost:8000/setup/complete \ -H "Content-Type: application/json" \ -d '{ "startup_mode": "tunnel", "tunnel_provider": "ngrok" }' ``` -------------------------------- ### Complete Setup Configuration Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Mark the setup process as complete. Specify the startup mode and optionally the tunnel provider. ```json { "startup_mode": "setup | local | tunnel", "tunnel_provider": "ngrok | cloudflare (optional)" } ``` -------------------------------- ### Start Live Detection Source: https://context7.com/oliverbravery/printguard/llms.txt Starts real-time defect detection on a specified camera. ```APIDOC ## POST /detect/live/start — Start real-time defect detection on a camera ### Description Launches an async detection loop for the given camera. Each frame is preprocessed (greyscale, normalised), run through the prototypical network, and evaluated by majority vote before raising an alert. ### Method POST ### Endpoint https://printguard.example.com/detect/live/start ### Parameters #### Request Body - **camera_uuid** (string) - Required - The unique identifier for the camera. ### Request Example { "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" } ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Live detection started for camera 550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### Save Cloudflare OS Preferences and Get Setup Commands Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Save the operating system preference for Cloudflare tunnel setup. The response includes success status, tunnel token, operating system, and an array of setup commands. ```json { "success": "boolean", "tunnel_token": "string", "operating_system": "string", "setup_commands": [] } ``` -------------------------------- ### Start Live Detection Source: https://github.com/oliverbravery/printguard/blob/main/docs/overview.md Initiates the live detection process for a specific camera. This starts an asynchronous loop that captures frames, runs them through the inference model, and evaluates results to identify potential print failures. It also clears any previous detection history and errors for the selected camera. ```APIDOC ## Start Live Detection ### Description Initiates the live detection process for a specific camera, starting an asynchronous loop for frame analysis and failure detection. Clears previous detection history and errors for the camera. ### Method POST ### Endpoint `/cameras/{camera_id}/detect/start` ### Parameters #### Path Parameters - **camera_id** (string) - Required - The unique identifier of the camera to start detection for. ``` -------------------------------- ### Start Live Detection Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Initiates real-time object detection on a specified camera feed. ```APIDOC ## POST /detect/live/start ### Description Start live detection on a camera feed. ### Method POST ### Endpoint /detect/live/start ### Parameters #### Request Body - **camera_uuid** (string) - Required - The unique identifier of the camera to start detection on. ### Request Example ```json { "camera_uuid": "string" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation that live detection has started. ``` -------------------------------- ### Initialize UniversalInferenceEngine Source: https://context7.com/oliverbravery/printguard/llms.txt Sets up the UniversalInferenceEngine for backend-agnostic model inference, selecting between PyTorch and ONNX Runtime. It handles device setup and model loading. ```python from printguard.utils.inference_engine import UniversalInferenceEngine, InferenceBackend # Select PyTorch or ONNX Runtime backend engine = UniversalInferenceEngine(backend=InferenceBackend.ONNXRUNTIME) # 1. Set up compute device (auto-selects CUDA > MPS > CPU) device = engine.setup_device("cuda") # device -> "cuda" if available, otherwise "mps" or "cpu" # 2. Load model and preprocessing transform model, input_dims = engine.load_model( model_path="/data/model/model.onnx", options_path="/data/model/opt.json", device=device, ) transform = engine.get_transform() # 3. Compute class prototypes from support images # support_dir must contain subdirectories named per class, e.g.: # prototypes/success/*.jpg ``` -------------------------------- ### Start Live Defect Detection Source: https://context7.com/oliverbravery/printguard/llms.txt Launches an asynchronous detection loop for a given camera. Frames are preprocessed and evaluated by majority vote to raise alerts. ```bash curl -X POST https://printguard.example.com/detect/live/start \ -H "Content-Type: application/json" \ -d '{ "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` -------------------------------- ### Install and Launch PrintGuard via Docker Source: https://context7.com/oliverbravery/printguard/llms.txt Pull the latest Docker image from GitHub Container Registry and run it with persistent storage and camera access. The --privileged flag is required for host camera device access. ```bash docker pull ghcr.io/oliverbravery/printguard:latest ``` ```bash docker run \ -p 8000:8000 \ -v "$(pwd)/data:/data" \ --privileged \ ghcr.io/oliverbravery/printguard:latest ``` -------------------------------- ### Interactive Program Notice (GPL) Source: https://github.com/oliverbravery/printguard/blob/main/LICENSE.md This notice should be displayed by interactive programs when they start, informing users about the program's warranty status and redistribution conditions. ```text Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Initialize, Get, and Update Configuration Source: https://context7.com/oliverbravery/printguard/llms.txt Manages application configuration stored in `config.json`. Use `init_config` once at startup, `get_config` to read, and `update_config` to atomically modify settings. Configuration is thread-safe. ```python from printguard.utils.config import get_config, update_config, init_config from printguard.models import SavedConfig # Initialise (called once at app startup — creates file with defaults if missing) init_config() # Read the current config config = get_config() print(config.get(SavedConfig.STARTUP_MODE)) # "local" | "tunnel" | "setup" | None print(config.get(SavedConfig.SITE_DOMAIN)) # "https://printguard.example.com" print(config.get(SavedConfig.VAPID_PUBLIC_KEY)) # Update one or more keys atomically update_config({ SavedConfig.STARTUP_MODE: "tunnel", SavedConfig.TUNNEL_PROVIDER: "ngrok", SavedConfig.SITE_DOMAIN: "https://myprintguard.ngrok.app", }) ``` -------------------------------- ### GET /notification/debug Source: https://context7.com/oliverbravery/printguard/llms.txt Inspects the current push subscription and VAPID state for debugging purposes. ```APIDOC ## GET /notification/debug — Inspect subscription and VAPID state ### Description Useful for diagnosing push notification issues without exposing private key material. This endpoint provides details about active subscriptions and VAPID configuration. ### Method GET ### Endpoint https://printguard.example.com/notification/debug ### Response #### Success Response (200) - **subscriptions_count** (integer) - The total number of active subscriptions. - **subscriptions** (array) - A list of active subscriptions, each with an endpoint and a boolean indicating if keys are present. - **endpoint** (string) - The URL of the push subscription. - **has_keys** (boolean) - Whether the subscription has associated keys. - **vapid_config** (object) - Information about the VAPID configuration. - **has_public_key** (boolean) - Whether a public key is configured. - **has_subject** (boolean) - Whether a subject is configured. - **has_private_key** (boolean) - Whether a private key is configured. - **subject** (string) - The VAPID subject (e.g., mailto:). ``` -------------------------------- ### Get Camera State Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the current state and configuration details of a specific camera. ```APIDOC ## POST /camera/state ### Description Get the state of a camera. ### Method POST ### Endpoint /camera/state ### Parameters #### Request Body - **camera_uuid** (string) - Required - The unique identifier of the camera. ### Response #### Success Response (200) - **nickname** (string) - **start_time** (float) - **last_result** (string) - **last_time** (float) - **detection_times** (array) - **error** (string) - **live_detection_running** (boolean) - **brightness** (float) - **contrast** (float) - **focus** (float) - **countdown_time** (integer) - **majority_vote_threshold** (integer) - **majority_vote_window** (integer) - **current_alert_id** (string) - **sensitivity** (float) - **printer_id** (string) - **printer_config** (object) - **countdown_action** (string) ``` -------------------------------- ### POST /sse/start-polling — Begin polling printer state for a camera Source: https://context7.com/oliverbravery/printguard/llms.txt Starts a background task to periodically query the linked OctoPrint instance for its status and dispatch `printer_state` SSE packets. ```APIDOC ## POST /sse/start-polling — Begin polling printer state for a camera ### Description Starts a background asyncio task that queries the linked OctoPrint instance every `printer_stat_polling_rate_ms` milliseconds and dispatches `printer_state` SSE packets. ### Method POST ### Endpoint /sse/start-polling ### Parameters #### Request Body - **camera_uuid** (string) - Required - The unique identifier of the camera. ### Request Example ```bash curl -X POST https://printguard.example.com/sse/start-polling \ -H "Content-Type: application/json" \ -d '{ "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` ### Response #### Success Response (200 OK) - **message** (string) - Confirmation message indicating polling has started. ### Response Example ```json { "message": "Polling started for camera UUID 550e8400-e29b-41d4-a716-446655440000" } ``` ``` -------------------------------- ### Get Feed Settings Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the current configuration settings for the video feed and detection parameters. ```APIDOC ## GET /get-feed-settings ### Description Get the current feed settings. ### Method GET ### Endpoint /get-feed-settings ### Response #### Success Response (200) - **success** (boolean) - Indicates if the settings were retrieved successfully. - **settings** (object) - An object containing the current feed settings: - **stream_max_fps** (integer) - Maximum frames per second for the stream. - **stream_tunnel_fps** (integer) - Maximum frames per second for the tunnel stream. - **stream_jpeg_quality** (integer) - JPEG quality for the stream (0-100). - **stream_max_width** (integer) - Maximum width for the stream. - **detections_per_second** (integer) - Maximum number of detections allowed per second. - **detection_interval_ms** (integer) - Interval in milliseconds between detections. - **printer_stat_polling_rate_ms** (integer) - Rate in milliseconds for polling printer status. - **min_sse_dispatch_delay_ms** (integer) - Minimum delay in milliseconds for Server-Sent Events dispatch. ``` -------------------------------- ### Copyright Disclaimer Example Source: https://github.com/oliverbravery/printguard/blob/main/LICENSE.md A sample copyright disclaimer that an employer or institution can sign to disclaim copyright interest in a program written by an employee. ```text Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Moe Ghoul, President of Vice ``` -------------------------------- ### Save Cloudflare OS Preferences Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Saves the operating system preference for Cloudflare tunnel setup. ```APIDOC ## POST /setup/cloudflare/save-os ### Description Save Cloudflare OS preferences. ### Method POST ### Endpoint /setup/cloudflare/save-os ### Parameters #### Request Body - **operating_system** (string) - Required - The operating system: 'macos', 'windows', or 'linux'. ### Response #### Success Response (200) - **success** (boolean) - **tunnel_token** (string) - **operating_system** (string) - **setup_commands** (array) ``` -------------------------------- ### Get Camera State Source: https://context7.com/oliverbravery/printguard/llms.txt Retrieves all runtime metrics and configuration for a specified camera UUID. Includes detection history, live status, and printer information. ```bash curl -X POST https://printguard.example.com/camera/state \ -H "Content-Type: application/json" \ -d '{ "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` -------------------------------- ### Retrieve Current Feed Settings Source: https://context7.com/oliverbravery/printguard/llms.txt Fetches the current configuration for video streaming and detection performance. This GET request returns all active feed settings. ```bash curl https://printguard.example.com/get-feed-settings ``` -------------------------------- ### Get Backend Information Source: https://context7.com/oliverbravery/printguard/llms.txt Retrieves information about the backend inference engine being used. This can be useful for debugging or understanding the environment. ```python # 6. Inspect backend info info = engine.get_backend_info() # { # "backend": "onnxruntime", # "engine_class": "ONNXRuntimeInferenceEngine", # "available_devices": ["cpu"] # } ``` -------------------------------- ### Get Feed Settings Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the current feed settings for the camera. ```json { "success": "boolean", "settings": { "stream_max_fps": "integer", "stream_tunnel_fps": "integer", "stream_jpeg_quality": "integer", "stream_max_width": "integer", "detections_per_second": "integer", "detection_interval_ms": "integer", "printer_stat_polling_rate_ms": "integer", "min_sse_dispatch_delay_ms": "integer" } } ``` -------------------------------- ### GET /get-feed-settings Source: https://context7.com/oliverbravery/printguard/llms.txt Retrieves the current feed settings for streaming and detection performance. ```APIDOC ## GET /get-feed-settings — Retrieve current feed settings ### Description Fetches the current configuration for video stream and detection performance parameters. ### Method GET ### Endpoint https://printguard.example.com/get-feed-settings ### Response #### Success Response (200) - **success** (boolean) - Indicates if the settings were retrieved successfully. - **settings** (object) - An object containing the current feed settings. - **stream_max_fps** (integer) - Maximum frames per second for the video stream. - **stream_tunnel_fps** (integer) - Frames per second for the tunneled video stream. - **stream_jpeg_quality** (integer) - JPEG quality for the video stream (0-100). - **stream_max_width** (integer) - Maximum width of the video stream in pixels. - **detections_per_second** (integer) - Maximum number of detections to process per second. - **detection_interval_ms** (integer) - Minimum interval in milliseconds between detections. - **printer_stat_polling_rate_ms** (integer) - Rate in milliseconds at which printer statistics are polled. - **min_sse_dispatch_delay_ms** (integer) - Minimum delay in milliseconds before dispatching Server-Sent Events. ``` -------------------------------- ### Debug Push Notification Subscriptions Source: https://context7.com/oliverbravery/printguard/llms.txt Inspect the current subscription and VAPID state for diagnosing push notification issues. This GET request provides counts and details about active subscriptions and VAPID configuration. ```bash curl https://printguard.example.com/notification/debug ``` -------------------------------- ### Get Camera State Information Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieve the current state of a camera, including its nickname, detection history, error status, and configuration parameters. ```json { "nickname": "string", "start_time": "float", "last_result": "string", "last_time": "float", "detection_times": [], "error": "string", "live_detection_running": "boolean", "brightness": "float", "contrast": "float", "focus": "float", "countdown_time": "integer", "majority_vote_threshold": "integer", "majority_vote_window": "integer", "current_alert_id": "string", "sensitivity": "float", "printer_id": "string", "printer_config": {}, "countdown_action": "string" } ``` -------------------------------- ### Start Polling Printer State Source: https://context7.com/oliverbravery/printguard/llms.txt Initiates a background task to poll the OctoPrint instance for printer status updates at a specified interval. Requires the camera UUID. ```bash curl -X POST https://printguard.example.com/sse/start-polling \ -H "Content-Type: application/json" \ -d '{ "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` -------------------------------- ### Start Polling for Printer State Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Initiate polling for the printer state associated with a specific camera. Requires the camera's UUID. ```json { "camera_uuid": "string" } ``` -------------------------------- ### GET /sse — Subscribe to real-time server-sent events Source: https://context7.com/oliverbravery/printguard/llms.txt Opens a persistent SSE stream to receive real-time event updates such as defect detection, camera state changes, and printer status. ```APIDOC ## GET /sse — Subscribe to real-time server-sent events ### Description Opens a persistent SSE stream. The backend pushes three event types: `alert` (defect detected), `camera_state` (metrics update), and `printer_state` (OctoPrint status poll). The client web UI uses this to update the dashboard without polling. ### Method GET ### Endpoint /sse ### Response #### Success Response (200 OK) - **event** (string) - The type of event: "alert", "camera_state", or "printer_state". - **data** (object) - An event-specific payload. - For "alert": `id`, `snapshot` (base64), `title`, `countdown_time`, `camera_uuid`, `has_printer`. - For "camera_state": Camera metrics. - For "printer_state": OctoPrint status. ### Request Example ```javascript const evtSource = new EventSource("https://printguard.example.com/sse"); evtSource.onmessage = (event) => { const packet = JSON.parse(event.data); // packet.event: "alert" | "camera_state" | "printer_state" // packet.data: if (packet.event === "alert") { const alert = packet.data; console.log("Defect detected!", alert.title); } else if (packet.event === "camera_state") { updateCameraMetrics(packet.data); } else if (packet.event === "printer_state") { updatePrinterPanel(packet.data); } }; evtSource.onerror = () => console.error("SSE connection lost, retrying..."); ``` ``` -------------------------------- ### Get Cloudflare Organisation Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves information about the Cloudflare organisation. ```APIDOC ## GET /setup/cloudflare/organisation ### Description Get Cloudflare organisation. ### Method GET ### Endpoint /setup/cloudflare/organisation ### Response #### Success Response (200) - **success** (boolean) - **team_name** (string) - **site_domain** (string) ``` -------------------------------- ### Build PrintGuard from Source with Docker Source: https://context7.com/oliverbravery/printguard/llms.txt Build a multi-platform Docker image for PrintGuard from source and run it. This allows for local builds and deployment across different architectures. ```bash docker buildx build \ --platform linux/amd64,linux/arm64,linux/arm/v7 \ -t oliverbravery/printguard:local \ --load . docker run -p 8000:8000 -v "$(pwd)/data:/data" --privileged oliverbravery/printguard:local ``` -------------------------------- ### Get Active Alerts Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves a list of all currently active alerts. ```APIDOC ## GET /alert/active ### Description Get all active alerts. ### Method GET ### Endpoint /alert/active ### Response #### Success Response (200) - **active_alerts** (array) - A list of active alerts, each containing: - **id** (string) - The unique identifier of the alert. - **snapshot** (string) - Base64 encoded image snapshot associated with the alert. - **title** (string) - The title of the alert. - **message** (string) - A detailed message describing the alert. - **timestamp** (float) - The timestamp when the alert occurred. - **countdown_time** (float) - Remaining time for a countdown associated with the alert. - **camera_uuid** (string) - The unique identifier of the camera related to the alert. - **has_printer** (boolean) - Indicates if a printer is associated with this alert. - **countdown_action** (string) - The action to be performed when the countdown finishes. ``` -------------------------------- ### Get Camera Feed Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the live video stream from a specific camera. ```APIDOC ## GET /camera/feed/{camera_uuid} ### Description Get the camera feed. ### Method GET ### Endpoint /camera/feed/{camera_uuid} ### Parameters #### Path Parameters - **camera_uuid** (string) - Required - The unique identifier for the camera. ### Response #### Success Response A multipart response with the video stream. ``` -------------------------------- ### GET /alert/active Source: https://context7.com/oliverbravery/printguard/llms.txt Retrieves a list of all active alerts that require user acknowledgment or action. ```APIDOC ## GET /alert/active — Retrieve all active (unacknowledged) alerts ### Description Returns all alerts currently awaiting user action. Each alert includes a base64-encoded JPEG snapshot captured at the moment of detection and a countdown indicating when automatic action will be taken. ### Method GET ### Endpoint https://printguard.example.com/alert/active ### Response #### Success Response (200) - **active_alerts** (array) - A list of active alerts. - **id** (string) - The unique identifier for the alert. - **snapshot** (string) - A base64-encoded JPEG snapshot of the event. - **title** (string) - A title for the alert. - **message** (string) - A detailed message describing the alert. - **timestamp** (number) - The Unix timestamp when the alert occurred. - **countdown_time** (number) - The remaining time in seconds before an automatic action is taken. - **camera_uuid** (string) - The UUID of the camera that triggered the alert. - **has_printer** (boolean) - Indicates if the alert is associated with a printer. - **countdown_action** (string) - The action to be taken when the countdown reaches zero (e.g., 'pause_print'). ``` -------------------------------- ### Standard GPL Notice for Source Files Source: https://github.com/oliverbravery/printguard/blob/main/LICENSE.md Include this notice at the beginning of each source file to convey the exclusion of warranty and specify redistribution terms under the GPL. ```text Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see . ``` -------------------------------- ### Run PrintGuard Docker Container (Local Build) Source: https://github.com/oliverbravery/printguard/blob/main/README.md Runs the PrintGuard Docker container built from local source. Maps port 8000, mounts a local 'data' directory for persistence, and enables privileged access for camera devices. ```bash docker run \ -p 8000:8000 \ -v "$(pwd)/data:/data" \ --privileged \ oliverbravery/printguard:local ``` -------------------------------- ### Get Cloudflare Accounts and Zones Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves a list of Cloudflare accounts and associated zones. ```APIDOC ## GET /setup/cloudflare/accounts-zones ### Description Get Cloudflare accounts and zones. ### Method GET ### Endpoint /setup/cloudflare/accounts-zones ### Response #### Success Response (200) - **success** (boolean) - **accounts** (object) - **zones** (object) ``` -------------------------------- ### Build PrintGuard Docker Image Source: https://github.com/oliverbravery/printguard/blob/main/README.md Builds the Docker image from source for multiple platforms (amd64, arm64, arm/v7). Tags the image as `oliverbravery/printguard:local`. ```bash docker buildx build \ --platform linux/amd64,linux/arm64,linux/arm/v7 \ -t oliverbravery/printguard:local \ --load \ . ``` -------------------------------- ### Serve Cloudflare Add Device Page Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the HTML content for the Cloudflare add device page. ```APIDOC ## GET /setup/cloudflare/add-device ### Description Serve the Cloudflare add device page. ### Method GET ### Endpoint /setup/cloudflare/add-device ### Response #### Success Response (200) - HTML content of the add device page. ``` -------------------------------- ### Start Polling Printer State Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Initiates polling for the printer state associated with a specific camera. ```APIDOC ## POST /sse/start-polling ### Description Start polling for printer state for a given camera. ### Method POST ### Endpoint /sse/start-polling ### Parameters #### Request Body - **camera_uuid** (string) - Required - The unique identifier of the camera. ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating polling has started. ``` -------------------------------- ### Generate VAPID Keys for Web Push Source: https://context7.com/oliverbravery/printguard/llms.txt Use this endpoint to generate a new VAPID key pair. The public and private keys are returned in the response and should be saved using the /setup/save-vapid-settings endpoint. ```bash curl -X POST http://localhost:8000/setup/generate-vapid-keys ``` -------------------------------- ### Initialize Ngrok Tunnel Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Initializes an ngrok tunnel using the previously saved settings. ```APIDOC ## POST /setup/initialize-ngrok-tunnel ### Description Initialises a ngrok tunnel with the configured settings. ### Method POST ### Endpoint /setup/initialize-ngrok-tunnel ### Response #### Success Response (302) - Redirects to the setup page. ``` -------------------------------- ### Get Camera Feed Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the video stream from a specific camera. Returns a multipart response. ```http GET /camera/feed/{camera_uuid} ``` -------------------------------- ### Add Printer Configuration Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Configures a printer for a specific camera. Includes printer details and API credentials. ```json { "name": "string", "printer_type": "octoprint", "camera_uuid": "string", "base_url": "string", "api_key": "string" } ``` -------------------------------- ### Get Public Key for Push Notifications Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves the VAPID public key, which is necessary for setting up web push subscriptions. ```http GET /notification/public_key ``` -------------------------------- ### Configure Reverse-Proxy Tunnel Settings Source: https://context7.com/oliverbravery/printguard/llms.txt Stores credentials for a reverse-proxy tunnel provider (ngrok or Cloudflare Tunnel). The API token is saved to the system keyring. ```bash # ngrok curl -X POST http://localhost:8000/setup/save-tunnel-settings \ -H "Content-Type: application/json" \ -d '{ "provider": "ngrok", "token": "2abc123_ngrokAuthToken", "domain": "myprintguard.ngrok.app" }' ``` -------------------------------- ### Run PrintGuard Docker Container (GHCR) Source: https://github.com/oliverbravery/printguard/blob/main/README.md Runs the PrintGuard Docker container pulled from GHCR. Maps port 8000, mounts a local 'data' directory for persistence, and enables privileged access for camera devices. ```bash docker run \ -p 8000:8000 \ -v "$(pwd)/data:/data" \ --privileged \ ghcr.io/oliverbravery/printguard:latest ``` -------------------------------- ### Compute Prototypes and Predict Batch Source: https://context7.com/oliverbravery/printguard/llms.txt Compute prototypes from a model and support directory, then use them to predict defects in a batch of preprocessed tensors. Ensure the model, transform, and device are correctly initialized. ```python prototypes, class_names, defect_idx = engine.compute_prototypes( model=model, support_dir="/data/model/prototypes", transform=transform, device=device, success_label="success", use_cache=True, # skip recompute if cached ) # class_names -> ["success", "failure"] # defect_idx -> 1 import cv2, numpy as np frame = cv2.imread("frame.jpg") tensor = transform(frame).unsqueeze(0) # shape: (1, C, H, W) predictions = engine.predict_batch( model=model, batch_tensors=tensor, prototypes=prototypes, defect_idx=defect_idx, sensitivity=1.2, # values >1 increase defect sensitivity device=device, ) # predictions -> [0] (0 = success, 1 = defect) ``` -------------------------------- ### Establish SSE Connection Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Establishes a Server-Sent Events connection for real-time downstream communication. ```APIDOC ## GET /sse ### Description Establish a Server-Sent Events connection for downstream communication. ### Method GET ### Endpoint /sse ### Response #### Success Response (200) - A stream of events. ```json { "data": { "event": "alert | camera_state | printer_state", "data": { } } } ``` ``` -------------------------------- ### Get Active Alerts Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Retrieves a list of all currently active alerts, including details like snapshots, messages, and associated camera information. ```http GET /alert/active ``` -------------------------------- ### Upload Existing SSL Certificate Source: https://context7.com/oliverbravery/printguard/llms.txt Uploads an existing SSL certificate and private key file. This is an alternative to generating a self-signed certificate. ```bash curl -X POST http://localhost:8000/setup/upload-ssl-cert \ -F "cert_file=@/path/to/cert.pem" \ -F "key_file=@/path/to/key.pem" ``` -------------------------------- ### Generate Self-Signed SSL Certificate Source: https://context7.com/oliverbravery/printguard/llms.txt Creates a self-signed SSL certificate and private key using the `trustme` library. The certificate is saved to `cert.pem` and the private key is stored in the system keyring. ```bash curl -X POST http://localhost:8000/setup/generate-ssl-cert ``` -------------------------------- ### Generate a self-signed SSL certificate Source: https://context7.com/oliverbravery/printguard/llms.txt Uses the `trustme` library to issue a certificate for the configured domain. The certificate is written to `cert.pem` and the private key is stored in the system keyring. ```APIDOC ## POST /setup/generate-ssl-cert ### Description Generates a self-signed SSL certificate for the configured domain. ### Method POST ### Endpoint /setup/generate-ssl-cert ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful generation. ### Response Example ```json { "message": "SSL certificate generated successfully." } ``` ``` -------------------------------- ### Add Printer Configuration Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Configures and associates a printer with a specific camera. ```APIDOC ## POST /printer/add/{camera_uuid} ### Description Add and configure a printer for a camera. ### Method POST ### Endpoint /printer/add/{camera_uuid} ### Parameters #### Path Parameters - **camera_uuid** (string) - Required - The unique identifier of the camera to associate the printer with. #### Request Body - **name** (string) - Required - The name of the printer. - **printer_type** (string) - Required - The type of printer (e.g., 'octoprint'). - **camera_uuid** (string) - Required - The unique identifier of the camera. - **base_url** (string) - Required - The base URL for the printer. - **api_key** (string) - Required - The API key for accessing the printer. ### Request Example ```json { "name": "string", "printer_type": "octoprint", "camera_uuid": "string", "base_url": "string", "api_key": "string" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the printer was added successfully. - **printer_id** (string) - The unique identifier of the added printer. ``` -------------------------------- ### GET /notification/public_key — Retrieve VAPID public key Source: https://context7.com/oliverbravery/printguard/llms.txt Retrieves the VAPID public key necessary for clients to establish a secure push notification subscription. ```APIDOC ## GET /notification/public_key — Retrieve VAPID public key ### Description Returns the VAPID public key required by the browser to create a push subscription. The key is read from `config.json`. ### Method GET ### Endpoint /notification/public_key ### Response #### Success Response (200 OK) - **publicKey** (string) - The VAPID public key. ### Response Example ```json { "publicKey": "BNxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ``` ``` -------------------------------- ### Stop Live Defect Detection Source: https://context7.com/oliverbravery/printguard/llms.txt Gracefully terminates the real-time defect detection loop for a specified camera and updates its state. ```bash curl -X POST https://printguard.example.com/detect/live/stop \ -H "Content-Type: application/json" \ -d '{ "camera_uuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` -------------------------------- ### Save VAPID Settings Source: https://context7.com/oliverbravery/printguard/llms.txt Persist the generated VAPID public key and subject to `config.json`. The private key is stored securely in the system keyring. The `base_url` is crucial for constructing correct push payloads. ```bash curl -X POST http://localhost:8000/setup/save-vapid-settings \ -H "Content-Type: application/json" \ -d '{ "public_key": "BNxxxxxxxxxxxxxxx", "private_key": "xxxxxxxxxxxxxxxx", "subject": "mailto:admin@example.com", "base_url": "https://printguard.example.com" }' ``` -------------------------------- ### Upload an existing SSL certificate Source: https://context7.com/oliverbravery/printguard/llms.txt Accepts a `multipart/form-data` upload of an existing certificate and private key file. ```APIDOC ## POST /setup/upload-ssl-cert ### Description Uploads an existing SSL certificate and private key file. ### Method POST ### Endpoint /setup/upload-ssl-cert ### Parameters #### Request Body - **cert_file** (file) - Required - The SSL certificate file (e.g., `cert.pem`). - **key_file** (file) - Required - The SSL private key file (e.g., `key.pem`). ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful upload. ### Response Example ```json { "message": "SSL certificate uploaded successfully." } ``` ``` -------------------------------- ### Save Cloudflare Tunnel Settings Source: https://context7.com/oliverbravery/printguard/llms.txt Configure PrintGuard to use Cloudflare for tunnel management. Requires API token, domain, and email. ```bash curl -X POST http://localhost:8000/setup/save-tunnel-settings \ -H "Content-Type: application/json" \ -d '{ "provider": "cloudflare", "token": "cf_api_token_here", "domain": "printguard.example.com", "email": "user@example.com" }' ``` -------------------------------- ### Generate VAPID keys for Web Push Source: https://context7.com/oliverbravery/printguard/llms.txt Generates a fresh VAPID key pair. The returned keys are used to authenticate web push notifications and must be saved via `/setup/save-vapid-settings`. ```APIDOC ## POST /setup/generate-vapid-keys ### Description Generates a fresh VAPID key pair for authenticating web push notifications. ### Method POST ### Endpoint /setup/generate-vapid-keys ### Response #### Success Response (200) - **public_key** (string) - The public key for VAPID authentication. - **private_key** (string) - The private key for VAPID authentication. - **subject** (string) - The subject associated with the VAPID keys. ### Response Example ```json { "public_key": "BNxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "private_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "subject": "mailto:admin@example.com" } ``` ``` -------------------------------- ### Establish Ngrok Tunnel Source: https://github.com/oliverbravery/printguard/blob/main/docs/setup.md Use the ngrok python package to forward traffic from a public URL to your local server. Requires an authtoken and desired domain. ```python ngrok.forward(8000, authtoken=, domain=) ``` -------------------------------- ### POST /save-feed-settings Source: https://context7.com/oliverbravery/printguard/llms.txt Updates streaming and detection performance settings for the video feed. ```APIDOC ## POST /save-feed-settings — Update streaming and detection performance settings ### Description Controls bandwidth-critical parameters for the video stream and detection throughput. Changes take effect immediately without a server restart. ### Method POST ### Endpoint https://printguard.example.com/save-feed-settings ### Parameters #### Request Body - **stream_max_fps** (integer) - Optional - Maximum frames per second for the video stream. - **stream_tunnel_fps** (integer) - Optional - Frames per second for the tunneled video stream. - **stream_jpeg_quality** (integer) - Optional - JPEG quality for the video stream (0-100). - **stream_max_width** (integer) - Optional - Maximum width of the video stream in pixels. - **detections_per_second** (integer) - Optional - Maximum number of detections to process per second. - **detection_interval_ms** (integer) - Optional - Minimum interval in milliseconds between detections. - **printer_stat_polling_rate_ms** (integer) - Optional - Rate in milliseconds at which printer statistics are polled. - **min_sse_dispatch_delay_ms** (integer) - Optional - Minimum delay in milliseconds before dispatching Server-Sent Events. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the settings were saved successfully. - **message** (string) - A confirmation message. ``` -------------------------------- ### Generate Self-Signed SSL Certificate with trustme Source: https://github.com/oliverbravery/printguard/blob/main/docs/setup.md Create a self-signed SSL certificate for HTTPS using the trustme library. This is required for secure web push and SSE. The certificate and private key are saved to files and keyring respectively. ```python from trustme import CA ca = CA() cert = ca.issue_cert(domain) cert.save_pem('cert.pem') ca.save_private_key('private.key') ``` -------------------------------- ### Subscribe to Push Notifications Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Registers a client for receiving push notifications. ```APIDOC ## POST /notification/subscribe ### Description Subscribe to push notifications. ### Method POST ### Endpoint /notification/subscribe ### Parameters #### Request Body - **subscription** (object) - Required - The JSON Web Push subscription object. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the subscription was successful. ``` -------------------------------- ### Retrieve VAPID Public Key for Notifications Source: https://context7.com/oliverbravery/printguard/llms.txt Fetches the VAPID public key necessary for the browser to establish a push subscription. This key is read from the server's configuration. ```bash curl https://printguard.example.com/notification/public_key ``` -------------------------------- ### Update Feed Settings Source: https://context7.com/oliverbravery/printguard/llms.txt Adjusts streaming and detection performance parameters. These settings control bandwidth usage and detection throughput and take effect immediately. ```bash curl -X POST https://printguard.example.com/save-feed-settings \ -H "Content-Type: application/json" \ -d '{ "stream_max_fps": 30, "stream_tunnel_fps": 10, "stream_jpeg_quality": 85, "stream_max_width": 1280, "detections_per_second": 15, "detection_interval_ms": 67, "printer_stat_polling_rate_ms": 2000, "min_sse_dispatch_delay_ms": 100 }' ``` -------------------------------- ### Configure reverse-proxy tunnel credentials Source: https://context7.com/oliverbravery/printguard/llms.txt Stores tunnel provider, API token, and domain for either ngrok or Cloudflare Tunnel. The token is saved to the system keyring under `TUNNEL_API_KEY`. ```APIDOC ## POST /setup/save-tunnel-settings ### Description Configures reverse-proxy tunnel credentials for ngrok or Cloudflare Tunnel. ### Method POST ### Endpoint /setup/save-tunnel-settings ### Parameters #### Request Body - **provider** (string) - Required - The tunnel provider (e.g., "ngrok", "cloudflare"). - **token** (string) - Required - The API token for the tunnel provider. This is stored securely. - **domain** (string) - Required - The domain to be used for the tunnel. ### Request Example ```json { "provider": "ngrok", "token": "2abc123_ngrokAuthToken", "domain": "myprintguard.ngrok.app" } ``` ``` -------------------------------- ### Save Tunnel Settings Source: https://github.com/oliverbravery/printguard/blob/main/docs/api.md Saves the configuration for establishing a tunnel connection. ```APIDOC ## POST /setup/save-tunnel-settings ### Description Save tunnel settings. ### Method POST ### Endpoint /setup/save-tunnel-settings ### Parameters #### Request Body - **provider** (string) - Required - The tunnel provider: 'ngrok' or 'cloudflare'. - **token** (string) - Required - The authentication token for the tunnel provider. - **domain** (string) - Required - The domain to be used for the tunnel. - **email** (string) - Optional - Required for global API key only. The email associated with the tunnel provider account. ### Response #### Success Response (200) - JSON confirmation message. ``` -------------------------------- ### Manage Camera State Source: https://context7.com/oliverbravery/printguard/llms.txt Handles camera discovery, addition, removal, and state management. Camera state is stored in memory and persisted to `config.json`. Uses asyncio for asynchronous operations. ```python import asyncio from printguard.utils.camera_utils import ( add_camera, remove_camera, find_available_serial_cameras, get_camera_state, update_camera_state, ) async def demo(): # Discover local cameras (cross-platform: /dev/video* on Linux, index probing elsewhere) sources = find_available_serial_cameras() # Linux: ["/dev/video0", "/dev/video2"] # Windows: ["0", "1"] # Add a USB camera info = await add_camera(source=sources[0], nickname="Ender 3 - Cam 1") camera_uuid = info["camera_uuid"] # info -> {"camera_uuid": "uuid-...", "nickname": "Ender 3 - Cam 1", "source": "/dev/video0"} # Add an IP/RTSP camera rtsp_info = await add_camera( source="rtsp://192.168.1.50:554/stream", nickname="Voron 2.4 - IP Cam" ) # Read current state state = await get_camera_state(camera_uuid) print(state.live_detection_running) # False print(state.brightness) # 1.0 # Update camera settings await update_camera_state(camera_uuid, { "brightness": 1.2, "contrast": 1.1, "sensitivity": 1.5, "countdown_time": 90, "countdown_action": "pause_print", "majority_vote_threshold": 3, "majority_vote_window": 6, }) # Remove a camera success = await remove_camera(camera_uuid) # success -> True asyncio.run(demo()) ```