### Install Groundlight Python SDK via Setuptools Source: https://github.com/groundlight/python-sdk/blob/main/generated/README.md Install the package using Setuptools. Use `--user` for user-specific installation or `sudo` for system-wide installation. ```sh python setup.py install --user ``` -------------------------------- ### Install Groundlight SDK on Raspberry Pi Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/5-raspberry-pi.md Use this command to install the Groundlight SDK via pip. An ARM-compatible version will be automatically installed. ```bash pip3 install groundlight ``` -------------------------------- ### Install Groundlight SDK and Dependencies Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/2-retail-analytics.md Install the Groundlight SDK, OpenCV, and Pillow libraries using pip. Ensure Python 3.9 or higher is installed. ```bash pip install groundlight opencv-python pillow ``` -------------------------------- ### Install Groundlight Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/README.md Install the Groundlight Python SDK using pip. This is the first step to using the SDK. ```bash pip install groundlight ``` -------------------------------- ### Install SDK Dependencies Source: https://github.com/groundlight/python-sdk/blob/main/DEVELOPING.md Installs the necessary dependencies for the Python SDK using poetry. ```shell make install ``` -------------------------------- ### Install and Preview Docs Locally Source: https://github.com/groundlight/python-sdk/blob/main/docs/README.md Navigate to the docs directory, install dependencies, and build the documentation site to preview changes locally. Ensure you have a recent version of npm. ```bash cd docs npm install cd .. make develop-docs-comprehensive ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/groundlight/python-sdk/blob/main/DEVELOPING.md Installs the pre-commit hooks to automatically format code before committing. ```shell make install-pre-commit ``` -------------------------------- ### Build and Run MNS from Source Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/other-ways-to-use/3-monitoring-notification-server.md Install Node.js and Python 3.9+, then install dependencies and run the development server. Access the application at http://localhost:3000. ```bash git clone https://github.com/groundlight/monitoring-notification-server cd monitoring-notification-server npm install npm run dev ``` -------------------------------- ### Install Python 3.9 and pip on Ubuntu 18.04 Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md This script installs Python 3.9 and pip, configures them as default, and then installs the Groundlight SDK. It's specifically for Ubuntu 18.04 which defaults to an older Python version. ```shell # Prepare Ubuntu to install things sudo apt-get update # Install the basics sudo apt-get install -y python3.9 python3.9-distutils curl # Configure `python3` to run python3.9 by default sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 10 # Download and install pip3.9 curl https://bootstrap.pypa.io/get-pip.py > /tmp/get-pip.py sudo python3.9 /tmp/get-pip.py # Configure `pip3` to run pip3.9 sudo update-alternatives --install /usr/bin/pip3 pip3 $(which pip3.9) 10 # Now we can install Groundlight! pip3 install groundlight ``` -------------------------------- ### Install Groundlight SDK and Dependencies Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/1-dog-on-couch.md Install the necessary Python libraries for the application. This includes the Groundlight SDK, OpenCV for image capture, Pillow for image manipulation, and PyAudio for sound playback. ```bash pip install groundlight opencv-python pillow pyaudio ``` -------------------------------- ### List Detector Rules - Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Provides an example of how to list all rules associated with a specific detector using the ActionsApi. This snippet demonstrates the initial setup for API client configuration and authentication. ```python configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = actions_api.ActionsApi(api_client) ``` -------------------------------- ### Update Detector Example (Python) Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Demonstrates how to update a detector using the Groundlight Python SDK. Includes examples for both required and optional parameters. Ensure ApiToken authentication is configured. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import detectors_api from groundlight_openapi_client.model.detector import Detector from groundlight_openapi_client.model.patched_detector_request import PatchedDetectorRequest from pprint import pprint # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = detectors_api.DetectorsApi(api_client) id = "id_example" # str | patched_detector_request = PatchedDetectorRequest( name="name_example", confidence_threshold=0.9, patience_time=30.0, status=None, escalation_type="escalation_type_example", ) # PatchedDetectorRequest | (optional) # example passing only required values which don't have defaults set try: api_response = api_instance.update_detector(id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling DetectorsApi->update_detector: %s\n" % e) # example passing only required values which don't have defaults set # and optional values try: api_response = api_instance.update_detector(id, patched_detector_request=patched_detector_request) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling DetectorsApi->update_detector: %s\n" % e) ``` -------------------------------- ### Install Groundlight Python SDK via pip Source: https://github.com/groundlight/python-sdk/blob/main/generated/README.md Install the package directly from a Git repository using pip. You may need root permissions. ```sh pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git ``` -------------------------------- ### Install Code Generator Source: https://github.com/groundlight/python-sdk/blob/main/DEVELOPING.md Installs the necessary tools to generate SDK code from the API specification. Requires npm to be installed. ```shell make install-generator ``` -------------------------------- ### Clone Monitoring Notification Server Repository Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/other-ways-to-use/3-monitoring-notification-server.md Clone the GitHub repository to get started with the Monitoring Notification Server. ```bash git clone https://github.com/groundlight/monitoring-notification-server.git cd monitoring-notification-server ``` -------------------------------- ### Install framegrab library Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/guide/2-grabbing-images.md Install the framegrab library with all optional dependencies to support various image sources. ```bash pip install framegrab[all] ``` -------------------------------- ### Import Groundlight Python SDK after pip install Source: https://github.com/groundlight/python-sdk/blob/main/generated/README.md Import the groundlight_openapi_client package after installation. ```python import groundlight_openapi_client ``` -------------------------------- ### Get Rule - Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Shows how to retrieve a specific rule by its ID using the ActionsApi. The example includes setting up the API client with authentication and handling potential API exceptions. The response is pretty-printed. ```python with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = actions_api.ActionsApi(api_client) id = 1 try: api_response = api_instance.get_rule(id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->get_rule: %s\n" % e) ``` -------------------------------- ### Install Python 3 on Fedora Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Use dnf to install the latest Python 3 version on Fedora-based systems. ```bash sudo dnf install python3 ``` -------------------------------- ### Install Python 3 on Arch Linux Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Use pacman to install the latest Python 3 version on Arch Linux. ```bash sudo pacman -S python ``` -------------------------------- ### List Detector Pipelines - Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Provides an example of listing all ML Pipelines associated with a detector using the Python SDK. Requires API key authentication. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import detectors_api from groundlight_openapi_client.model.paginated_ml_pipeline_list import PaginatedMLPipelineList from pprint import pprint configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' ``` -------------------------------- ### Initialize Groundlight and Create Detector Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/getting-started/getting-started.mdx Initialize the Groundlight client and get or create a detector for a specific visual question. This detector will be used to analyze images. ```python from framegrab import FrameGrabber from groundlight import Groundlight, Detector, ImageQuery gl = Groundlight() detector: Detector = gl.get_or_create_detector( name="eagle-detector", query="Are the baby eagles being fed??", ) ``` -------------------------------- ### Install Framegrab with YouTube Support Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/getting-started/getting-started.mdx Install the framegrab library with YouTube support. This library is used for capturing frames from various video sources, including YouTube livestreams. ```bash pip install "framegrab[youtube]" ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/groundlight/python-sdk/blob/main/docs/README.md Execute documentation tests after installing Python Poetry and make, and configuring an API token. This ensures code samples in the documentation are up-to-date. ```bash make test-docs ``` -------------------------------- ### Check Groundlight SDK Version Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Verify the installed Groundlight SDK version using a Python one-liner or the command-line tool. ```bash python -c "import groundlight; print(groundlight.__version__)" ``` ```bash groundlight --help ``` -------------------------------- ### Install Python 3 on Debian/Ubuntu Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Use apt to update package lists and install the latest Python 3 version on Debian or Ubuntu-based systems. ```bash sudo apt update sudo apt install python3 ``` -------------------------------- ### Get the First Available ML Answer Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/guide/4-submitting-image-queries.md Use `ask_ml` to get the fastest possible answer from Groundlight's machine learning models, without any waiting period or confidence check. ```python from groundlight import Groundlight gl = Groundlight() detector = gl.get_detector(id="det_abcdef...") # highlight-start image_query = gl.ask_ml(detector=detector, image="path/to/image.jpg") # highlight-end ``` -------------------------------- ### Check Groundlight SDK Version Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/3-windows.md Verify the installed Groundlight SDK version using this Python command. Ensure Python is in your PATH. ```python python -c "import groundlight; print(groundlight.__version__)" ``` -------------------------------- ### Alternative Docs Server Script Source: https://github.com/groundlight/python-sdk/blob/main/docs/README.md An alternative script to start the documentation server, which also rebuilds Sphinx docs on every change. This script is tested on MacOS with Homebrew. ```bash ./start_docs_server.sh ``` -------------------------------- ### Pull Groundlight Stream Container Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/3-streaming-with-alerts.md Use this command to download the groundlight/stream Docker image. Ensure Docker is installed. ```bash docker pull groundlight/stream ``` -------------------------------- ### Check Python Version Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Verify your installed Python version. The Groundlight SDK requires Python 3.9 or higher. ```bash python --version ``` -------------------------------- ### Run the Dog on Couch Detector Application Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/1-dog-on-couch.md Execute the Python script to start the dog detection application. Ensure the script is saved with a .py extension and that the 'get_off_couch.mp3' file is in the same directory or accessible. ```bash python dog_on_couch_detector.py ``` -------------------------------- ### Import Required Libraries for Retail Analytics Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/2-retail-analytics.md Imports necessary libraries for image capture, email, and Groundlight API interaction. Ensure these are installed in your environment. ```python import smtplib import time from datetime import datetime, timedelta from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import cv2 from PIL import Image from groundlight import Groundlight ``` -------------------------------- ### List Detector Rules (Python) Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Lists rules associated with a specific detector. Includes examples for both required parameters and optional pagination parameters. ```python import groundlight_openapi_client from groundlight_openapi_client.api import actions_api from pprint import pprint configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = actions_api.ActionsApi(api_client) detector_id = "detector_id_example" page = 1 page_size = 1 try: api_response = api_instance.list_detector_rules(detector_id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->list_detector_rules: %s\n" % e) try: api_response = api_instance.list_detector_rules(detector_id, page=page, page_size=page_size) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->list_detector_rules: %s\n" % e) ``` -------------------------------- ### Get Detector Metrics - Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Shows how to fetch metrics for a detector using the Python SDK. This is useful for understanding label counts and distributions. API key authentication is required. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import detectors_api from groundlight_openapi_client.model.inline_response200 import InlineResponse200 from pprint import pprint configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = detectors_api.DetectorsApi(api_client) detector_id = "detector_id_example" try: api_response = api_instance.get_detector_metrics(detector_id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling DetectorsApi->get_detector_metrics: %s\n" % e) ``` -------------------------------- ### Create Rule Source: https://github.com/groundlight/python-sdk/blob/main/generated/README.md This example demonstrates how to create a new rule for a detector using the `actions_api.create_rule` method. It includes setting up the API client, authentication, and defining the rule request object. ```APIDOC ## POST /detectors/{detector_id}/rules ### Description Creates a new rule for a given detector. ### Method POST ### Endpoint /detectors/{detector_id}/rules ### Parameters #### Path Parameters - **detector_id** (str) - Required - The ID of the detector to create the rule for. #### Request Body - **rule_request** (RuleRequest) - Required - The details of the rule to create. ### Request Example ```python import groundlight_openapi_client from groundlight_openapi_client.model.rule_request import RuleRequest from groundlight_openapi_client.model.condition_request import ConditionRequest from groundlight_openapi_client.model.webhook_action_request import WebhookActionRequest from dateutil.parser import dateutil_parser configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = groundlight_openapi_client.api.actions_api.ActionsApi(api_client) detector_id = "detector_id_example" rule_request = RuleRequest( name="name_example", enabled=True, snooze_time_enabled=False, snooze_time_value=0, snooze_time_unit=None, human_review_required=False, condition=ConditionRequest( verb="verb_example", parameters={ "key": None, }, ), action=None, webhook_action=[ WebhookActionRequest( url="url_example", include_image=True, payload_template=None, last_message_failed=True, last_failure_error="last_failure_error_example", last_failed_at=dateutil_parser('1970-01-01T00:00:00.00Z'), ), ], ) try: api_response = api_instance.create_rule(detector_id, rule_request) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->create_rule: %s\n" % e) ``` ### Response #### Success Response (200) - **Rule** (Rule) - The created rule object. ``` -------------------------------- ### Upgrade Groundlight SDK using pip Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/1-linux.md Use this command to upgrade the Groundlight SDK to the latest version. If you have both python2 and python3 installed, you may need to use pip3. ```bash pip install --upgrade groundlight ``` ```bash pip3 install --upgrade groundlight ``` -------------------------------- ### Submit OpenCV Image to Groundlight Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/guide/2-grabbing-images.md Send an OpenCV image (NumPy array in BGR format) directly to Groundlight using `submit_image_query`. This example initializes a camera capture and releases it afterward. ```python import cv2 cam = cv2.VideoCapture(0) # Initialize camera (0 is the default index) _, frame = cam.read() # Capture one frame gl.submit_image_query(detector, frame) # Send the frame to Groundlight cam.release() # Release the camera ``` -------------------------------- ### Create a Rule using Groundlight Python SDK Source: https://github.com/groundlight/python-sdk/blob/main/generated/README.md Example demonstrating how to configure the API client, instantiate the ActionsApi, and create a new rule for a detector. Ensure API key and host configuration are set correctly. Handles potential API exceptions. ```python import time import groundlight_openapi_client from pprint import pprint from groundlight_openapi_client.api import actions_api from groundlight_openapi_client.model.paginated_rule_list import PaginatedRuleList from groundlight_openapi_client.model.rule import Rule from groundlight_openapi_client.model.rule_request import RuleRequest # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = actions_api.ActionsApi(api_client) detector_id = "detector_id_example" # str | rule_request = RuleRequest( name="name_example", enabled=True, snooze_time_enabled=False, snooze_time_value=0, snooze_time_unit=None, human_review_required=False, condition=ConditionRequest( verb="verb_example", parameters={ "key": None, }, ), action=None, webhook_action=[ WebhookActionRequest( url="url_example", include_image=True, payload_template=None, last_message_failed=True, last_failure_error="last_failure_error_example", last_failed_at=dateutil_parser('1970-01-01T00:00:00.00Z'), ), ], ) # RuleRequest | try: api_response = api_instance.create_rule(detector_id, rule_request) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->create_rule: %s\n" % e) ``` -------------------------------- ### Initialize Groundlight with Direct Token Configuration Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/getting-started/5-api-tokens.md Configure the Groundlight client directly by providing an API token obtained from a secure location. Ensure the token is retrieved securely and not hardcoded. ```python from groundlight import Groundlight token = get_token_from_secure_location() gl = Groundlight(api_token=token) ``` -------------------------------- ### Install Python with Homebrew Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/installation/2-macos.md If you need to upgrade Python on macOS, you can use Homebrew to install the latest version. ```bash brew install python ``` -------------------------------- ### Basic Computer Vision with Groundlight Source: https://github.com/groundlight/python-sdk/blob/main/README.md Build a working computer vision system by initializing the Groundlight client, getting or creating a detector with a natural language query, and submitting an image for analysis. The image can be a file path or a Python object. ```python from groundlight import Groundlight gl = Groundlight() det = gl.get_or_create_detector(name="doorway", query="Is the doorway open?") img = "./docs/static/img/doorway.jpg" # Image can be a file or a Python object image_query = gl.submit_image_query(detector=det, image=img) print(f"The answer is {image_query.result}") ``` -------------------------------- ### Main Application Loop for Service Counter Monitoring Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/2-retail-analytics.md Initializes Groundlight, gets or creates a detector, and enters a loop to capture images, submit queries, and log results. It calculates hourly usage percentages and sends a daily summary email. Includes error handling for image capture and API queries. ```python gl = Groundlight() detector = gl.get_or_create_detector( name="counter-in-use", query="Is there a customer at the service counter?", # We can get away with relatively low confidence since we're aggregating across images confidence_threshold=0.8) DELAY = 60 log = [] daily_log = [] next_hourly_start = datetime.now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) while True: if not is_within_business_hours(): time.sleep(DELAY) continue image = capture_image() if not image: print("Failed to capture image") time.sleep(DELAY) continue try: iq = gl.submit_image_query(image=image, detector=detector, wait=60) except Exception as e: print(f"Error submitting image query: {e}") time.sleep(DELAY) continue answer = iq.result.label log.append(answer) if datetime.now() >= next_hourly_start: next_hourly_start += timedelta(hours=1) percent_in_use = (log.count("YES") / len(log)) * 100 current_time = datetime.now().replace(hour=START_OF_BUSINESS, minute=0, second=0) formatted_time = current_time.strftime("%I%p") # like 3pm msg = f"Hourly summary for {formatted_time}: {percent_in_use:.0f}% counter in use" print(msg) daily_log.append(msg) log = [] current_hour = datetime.now().hour if current_hour == END_OF_BUSINESS and not daily_log == []: daily_summary = "Daily summary:\n" for msg in daily_log: daily_summary += f"{msg}\n" print(daily_summary) send_email(sender="counterbot@example.com", receiver="manager@example.com", subject="Daily Service Counter Usage Log", body=daily_summary) daily_log = [] time.sleep(DELAY) ``` -------------------------------- ### Create Note with ApiKey Authentication Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/NotesApi.md Demonstrates how to create a new note for a detector using API key authentication. Includes examples for both required and optional parameters, such as content, pinning, and image uploads. Ensure to replace 'YOUR_API_KEY' and '/path/to/file' with actual values. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import notes_api from groundlight_openapi_client.model.note_request import NoteRequest from pprint import pprint # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = notes_api.NotesApi(api_client) detector_id = "detector_id_example" # str | the detector to associate the new note with note_request = NoteRequest( content="content_example", is_pinned=True, image=open('/path/to/file', 'rb'), ) # NoteRequest | (optional) # example passing only required values which don't have defaults set try: api_instance.create_note(detector_id) except groundlight_openapi_client.ApiException as e: print("Exception when calling NotesApi->create_note: %s\n" % e) # example passing only required values which don't have defaults set # and optional values try: api_instance.create_note(detector_id, note_request=note_request) except groundlight_openapi_client.ApiException as e: print("Exception when calling NotesApi->create_note: %s\n" % e) ``` -------------------------------- ### Get the First Confident Answer Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/guide/4-submitting-image-queries.md Use the `ask_confident` alias to get an answer that meets or exceeds the detector's confidence threshold, waiting if necessary. ```python from groundlight import Groundlight gl = Groundlight() detector = gl.get_detector(id="det_abcdef...") # highlight-start image_query = gl.ask_confident(detector=detector, image="path/to/image.jpg") # highlight-end ``` -------------------------------- ### Main Application Loop Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/1-dog-on-couch.md The core logic of the application. It continuously captures images, submits them to Groundlight for analysis, and plays a sound if the dog is detected on the couch. Includes error handling for API requests and image capture failures. ```python gl = Groundlight() detector = gl.get_or_create_detector("Dog on Couch Detector") while True: image = capture_image() if image: try: iq = gl.submit_image_query(image=image, detector=detector, wait=60) answer = iq.result.label if answer == "YES": print("Dog detected on the couch!") play_sound("get_off_couch.mp3") except ApiException as e: print(f"Error submitting image query: {e}") else: print("Failed to capture image") # Sleep for a minute before checking again time.sleep(60) ``` -------------------------------- ### Apply Kubernetes Configuration Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/other-ways-to-use/3-monitoring-notification-server.md Apply the Kubernetes configuration to set up the Monitoring Notification Server. Ensure you are in the directory containing the kubernetes.yaml file. ```bash kubectl apply -f kubernetes.yaml ``` -------------------------------- ### Initialize Groundlight with Environment Variable Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/getting-started/5-api-tokens.md This method automatically uses the `GROUNDLIGHT_API_TOKEN` environment variable for authentication. It's the recommended approach for security. ```python from groundlight import Groundlight # Automatically uses GROUNDLIGHT_API_TOKEN environment variable gl = Groundlight() ``` -------------------------------- ### Get Detector Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Retrieves a detector's details by its ID. ```APIDOC ## GET /detectors/{id} ### Description Retrieve a detector by its ID. ### Method GET ### Endpoint /detectors/{id} ### Parameters #### Path Parameters - **id** (str) - Required - Choose a detector by its ID. ### Return type [**Detector**](Detector.md) ### Authorization [ApiToken](../README.md#ApiToken) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ### HTTP response details | Status code | Description | |-------------|-------------| **200** | | ``` -------------------------------- ### Get Detector Groups Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorGroupsApi.md Retrieves a list of all detector groups. ```APIDOC ## GET /v1/detector-groups ### Description Retrieves a list of all detector groups. ### Method GET ### Endpoint /v1/detector-groups ### Parameters This endpoint does not require any parameters. ### Response #### Success Response (200) - **[DetectorGroup]** - A list of detector group objects. ### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get Priming Group Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/PrimingGroupsApi.md Retrieves a specific priming group by its ID. ```APIDOC ## GET /v1/priming-groups/{id} ### Description Get a specific priming group by its ID. ### Method GET ### Endpoint /v1/priming-groups/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the priming group to retrieve. ### Response #### Success Response (200) - **PrimingGroup** (PrimingGroup) - Details of the requested priming group. #### Response Example ```json { "id": "string", "name": "string", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z", "detector_mode": "string", "canonical_query": "string", "disable_shadow_pipelines": false, "cached_vizlogic_key": "string" } ``` ``` -------------------------------- ### Import Required Libraries Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/1-dog-on-couch.md Import all necessary modules for the dog-on-couch detector application. This includes libraries for camera capture, audio playback, time delays, image handling, and the Groundlight SDK. ```python import cv2 import pyaudio import time import wave from PIL import Image from groundlight import Groundlight, ApiException ``` -------------------------------- ### Get Detector Evaluation Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Retrieves evaluation results for a detector, including accuracy metrics. ```APIDOC ## GET /detectors/{id}/evaluation ### Description Get Detector evaluation results. The result is null if there isn't enough ground truth data to evaluate the detector. Returns the time of the evaulation, total ground truth labels, the ml based kfold accuracies, and the system accuracies at different confidence thresholds ### Method GET ### Endpoint /detectors/{id}/evaluation ### Parameters #### Path Parameters - **id** (str) - Required - Choose a detector by its ID. ### Return type [**InlineResponse2001**](InlineResponse2001.md) ### Authorization [ApiToken](../README.md#ApiToken) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ``` -------------------------------- ### Create Detector with API Key Authentication Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Demonstrates how to create a new detector using the DetectorsApi. Requires ApiKey authentication. Ensure your API key is correctly configured. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import detectors_api from groundlight_openapi_client.model.detector_creation_input_request import DetectorCreationInputRequest from groundlight_openapi_client.model.detector import Detector from pprint import pprint # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = detectors_api.DetectorsApi(api_client) detector_creation_input_request = DetectorCreationInputRequest( name="name_example", query="query_example", group_name="group_name_example", confidence_threshold=0.9, patience_time=30.0, pipeline_config="pipeline_config_example", edge_pipeline_config="edge_pipeline_config_example", metadata="metadata_example", mode=None, mode_configuration=None, priming_group_id="priming_group_id_example", ) # DetectorCreationInputRequest | # example passing only required values which don't have defaults set try: api_response = api_instance.create_detector(detector_creation_input_request) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling DetectorsApi->create_detector: %s\n" % e) ``` -------------------------------- ### Who Am I Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/UserApi.md Retrieves information about the currently authenticated user. This is a simple GET request that does not require any parameters. ```APIDOC ## GET /v1/me ### Description Retrieve the current user. ### Method GET ### Endpoint /v1/me ### Parameters This endpoint does not need any parameter. ### Request Example ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import user_api from groundlight_openapi_client.model.inline_response2002 import InlineResponse2002 from pprint import pprint # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = user_api.UserApi(api_client) # example, this endpoint has no required or optional parameters try: api_response = api_instance.who_am_i() pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling UserApi->who_am_i: %s\n" % e) ``` ### Response #### Success Response (200) - **InlineResponse2002** (InlineResponse2002) - Description of the response object. #### Response Example (Response example not provided in source) ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/getting-started/getting-started.mdx Create a virtual environment to isolate Groundlight dependencies. This is a standard Python practice for managing project-specific packages. ```bash python3 -m venv groundlight-env ``` -------------------------------- ### Get Rule Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Retrieves a specific rule by its ID. Returns the Rule object if found. ```APIDOC ## GET /rules/{id} ### Description Retrieves a specific rule by its ID. ### Method GET ### Endpoint /rules/{id} ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the rule to retrieve. ### Return type [**Rule**](Rule.md) ### Authorization [ApiToken](../README.md#ApiToken) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ### HTTP response details | Status code | Description | |-------------|-------------| | **200** | Rule object | ``` -------------------------------- ### Get Priming Group Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/PrimingGroupsApi.md Retrieves a priming group by its ID. Returns the details of the specified priming group. ```APIDOC ## GET /priming_groups/{id} ### Description Retrieve a priming group by its ID. ### Method GET ### Endpoint /priming_groups/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the priming group to retrieve. ### Response #### Success Response (200) - **PrimingGroup** (PrimingGroup) - Details of the priming group. ### Authorization [ApiToken](../README.md#ApiToken) ``` -------------------------------- ### Run Stream Container for Live Monitoring Source: https://github.com/groundlight/python-sdk/blob/main/docs/docs/sample-applications/3-streaming-with-alerts.md Process a live YouTube stream, submitting frames to Groundlight for analysis. Replace with your detector's ID. The -f 0.25 flag processes one frame every 4 seconds, and -m enables motion detection. ```bash docker run groundlight/stream \ -t "$GROUNDLIGHT_API_TOKEN" \ -d "" \ -s "https://www.youtube.com/watch?v=WtoxxHADnGk" \ -f 0.25 \ -m \ -v ``` -------------------------------- ### List All Rules (Python) Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Lists all rules across all detectors owned by the requester. Demonstrates API key authentication and the use of optional parameters like pagination and predictor ID filtering. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import actions_api from groundlight_openapi_client.model.paginated_rule_list import PaginatedRuleList from pprint import pprint configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = actions_api.ActionsApi(api_client) page = 1 page_size = 1 predictor_id = "predictor_id_example" try: api_response = api_instance.list_rules(page=page, page_size=page_size, predictor_id=predictor_id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->list_rules: %s\n" % e) ``` -------------------------------- ### get_model_urls Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/EdgeApi.md Gets time limited pre-authenticated URLs to download a detector's edge model and oodd model. ```APIDOC ## GET /v1/edge/fetch-model-urls/{detector_id}/ ### Description Gets time limited pre-authenticated URLs to download a detector's edge model and oodd model. ### Method GET ### Endpoint /v1/edge/fetch-model-urls/{detector_id}/ ### Parameters #### Path Parameters - **detector_id** (str) - Required - Description of the detector ID ### Request Example ```python import groundlight_openapi_client configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) configuration.api_key['ApiToken'] = 'YOUR_API_KEY' with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = groundlight_openapi_client.api.edge_api.EdgeApi(api_client) detector_id = "detector_id_example" try: api_response = api_instance.get_model_urls(detector_id) print(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling EdgeApi->get_model_urls: %s\n" % e) ``` ### Response #### Success Response (200) - **EdgeModelInfo** (EdgeModelInfo) - Description of the model information ``` -------------------------------- ### Get Notes for Detector Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/NotesApi.md Retrieves all notes associated with a given detector ID. Ensure the ApiClient is properly configured before use. ```python with groundlight_openapi_client.ApiClient(configuration) as api_client: api_instance = notes_api.NotesApi(api_client) detector_id = "detector_id_example" try: api_response = api_instance.get_notes(detector_id) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling NotesApi->get_notes: %s\n" % e) ``` -------------------------------- ### Create Rule with API Key Authentication Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/ActionsApi.md Demonstrates how to create a new rule for a detector using API key authentication. Ensure your API key is correctly configured. ```python import time import groundlight_openapi_client from groundlight_openapi_client.api import actions_api from groundlight_openapi_client.model.rule import Rule from groundlight_openapi_client.model.rule_request import RuleRequest from pprint import pprint # Defining the host is optional and defaults to https://api.groundlight.ai/device-api # See configuration.py for a list of all supported configuration parameters. configuration = groundlight_openapi_client.Configuration( host = "https://api.groundlight.ai/device-api" ) # The client must configure the authentication and authorization parameters # in accordance with the API server security policy. # Examples for each auth method are provided below, use the example that # satisfies your auth use case. # Configure API key authorization: ApiToken configuration.api_key['ApiToken'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # configuration.api_key_prefix['ApiToken'] = 'Bearer' # Enter a context with an instance of the API client with groundlight_openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class api_instance = actions_api.ActionsApi(api_client) detector_id = "detector_id_example" # str | rule_request = RuleRequest( name="name_example", enabled=True, snooze_time_enabled=False, snooze_time_value=0, snooze_time_unit=None, human_review_required=False, condition=ConditionRequest( verb="verb_example", parameters={ "key": None, }, ), action=None, webhook_action=[ WebhookActionRequest( url="url_example", include_image=True, payload_template=None, last_message_failed=True, last_failure_error="last_failure_error_example", last_failed_at=dateutil_parser('1970-01-01T00:00:00.00Z'), ), ], ) # RuleRequest | # example passing only required values which don't have defaults set try: api_response = api_instance.create_rule(detector_id, rule_request) pprint(api_response) except groundlight_openapi_client.ApiException as e: print("Exception when calling ActionsApi->create_rule: %s\n" % e) ``` -------------------------------- ### Get Detector Evaluation Source: https://github.com/groundlight/python-sdk/blob/main/generated/docs/DetectorsApi.md Retrieves a specific detector's evaluation by its ID. This is useful for checking the current state or results of a detector. ```APIDOC ## GET /detectors/{id}/evaluation ### Description Retrieves a specific detector's evaluation by its ID. ### Method GET ### Endpoint /detectors/{id}/evaluation ### Parameters #### Path Parameters - **id** (str) - Required - The unique identifier of the detector. ### Response #### Success Response (200) - **InlineResponse2001** - Details of the detector evaluation. ### Authorization [ApiToken](../README.md#ApiToken) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json ```