### Install LandingAI SDK and Set Up Credentials Source: https://github.com/landing-ai/landingai-python/blob/main/examples/video-analytics-notebook/video-analytics.ipynb Installs the LandingAI SDK if not already present and sets up API credentials and endpoint configuration. Requires a runtime restart after installation. ```python api_key = "land_sk_aMemWbpd41yXnQ0tXvZMh59ISgRuKNRKjJEIUHnkiH32NBJAwf" endpoint_id = "067ce386-3958-4d98-be31-9a9af07e361a" video_file = "https://drive.google.com/uc?export=download&id=12I5r1siMRzcejuFxI-izRshBtmWRmVxQ" # Install LandingAI's SDK only if needed to avoid unnecessary restarts try: import landingai except ImportError: import os from IPython.display import display, Markdown display(Markdown("## Installing modules. You will need to restart runtime.")) !pip install landingai display(Markdown("## Please restart runtime.")) ``` -------------------------------- ### Run Video Inference Example Source: https://github.com/landing-ai/landingai-python/blob/main/examples/capture-service/README.md Execute this command to start the example application. The program captures frames, runs inference, and displays predictions overlaid on the image. Be mindful of the inference rate limits for free trial accounts. ```bash python examples/capture-service/run.py ``` -------------------------------- ### Install All Dependencies Source: https://github.com/landing-ai/landingai-python/blob/main/docs/contributing.md Installs all project dependencies, including optional extras, using Poetry. ```bash poetry install --all-extras ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/landing-ai/landingai-python/blob/main/docs/examples.md Install the necessary Python dependencies, including those for examples, using Poetry. ```bash poetry install --with examples ``` -------------------------------- ### Run RTSP Capture Example Source: https://github.com/landing-ai/landingai-python/blob/main/docs/examples.md Execute the streaming video capture example using Python. ```bash python landingai-python/examples/capture-service/run.py ``` -------------------------------- ### Run RTSP Capture Example Locally Source: https://github.com/landing-ai/landingai-python/blob/main/README.md Instructions for running the RTSP capture example locally using Git, Poetry, and Python. ```bash git clone https://github.com/landing-ai/landingai-python.git poetry install --with examples poetry shell python landingai-python/examples/capture-service/run.py ``` -------------------------------- ### Install Project Requirements Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/README.md Run this command in your terminal to install all necessary Python packages for the project. Ensure you have Python 3.9 or higher installed. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Requirements Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/object-tracking/README.md Install the necessary Python packages for the object tracking application. ```bash pip install -r examples/apps/object-tracking/requirements.txt ``` -------------------------------- ### Install LandingAI SDK Source: https://github.com/landing-ai/landingai-python/blob/main/examples/webcam-collab-notebook/webcam-collab-notebook.ipynb Installs the LandingAI Python SDK if it's not already present. This code block includes a mechanism to force a runtime restart if the installation is successful, which is necessary for the new package to be recognized. ```python # Install dependencies only if needed to avoid unnecessary restarts try: import landingai except ImportError: import os from IPython.display import display, Markdown display(Markdown("##Installing modules. You will need to restart runtime.")) %pip install landingai display(Markdown("##Stopping RUNTIME! Please restart runtime.")) os.kill(os.getpid(), 9) # This is a way to force a restart ``` -------------------------------- ### Install Poetry Source: https://github.com/landing-ai/landingai-python/blob/main/docs/contributing.md Installs Poetry, a dependency management tool, using a script. Specify a Python version if needed. ```bash curl -sSL https://install.python-poetry.org | python3 - ``` ```bash curl -sSL https://install.python-poetry.org | python3.10 - ``` -------------------------------- ### Complete Pipeline Example: Webcam Monitoring Source: https://context7.com/landing-ai/landingai-python/llms.txt An end-to-end example demonstrating webcam monitoring with defect detection. It acquires frames, runs inference, overlays predictions, and saves images when defects are found. ```python from landingai.pipeline.image_source import Webcam, VideoFile from landingai.pipeline.frameset import Frame, FrameSet from landingai.predict import Predictor import os # Set API key via environment variable os.environ["LANDINGAI_API_KEY"] = "land_sk_your_api_key" # Initialize predictor predictor = Predictor(endpoint_id="your-endpoint-id") # Example 1: Webcam monitoring with defect detection with Webcam(fps=1) as webcam: for frame in webcam: frame.resize(width=640) frame.run_predict(predictor=predictor) if "defect" in frame.predictions: frame.overlay_predictions() frame.save_image("/tmp/defect_detected.png", include_predictions=True) print(f"Defect detected! {len(frame.predictions)} issues found") # Break after 10 frames for this example break ``` -------------------------------- ### Install landingai and Download Video Source: https://github.com/landing-ai/landingai-python/blob/main/examples/license-plate-ocr-notebook/license_plate_ocr.ipynb Installs the necessary landingai python package and downloads a sample video file for processing. Ensure you have the correct file path for the downloaded video. ```python !pip install landingai gdown !gdown "https://drive.google.com/uc?id=16iwE7mcz9zHqKCw2ilx0QEwSCjDdXEW4" -O /tmp/license-plates.mov ``` -------------------------------- ### Install Landing AI Python Library Source: https://github.com/landing-ai/landingai-python/blob/main/examples/post-processings/farmland-coverage/farmland-coverage.ipynb This section shows the output of a successful installation of the landingai Python package. It also provides a notice about a new pip release and how to upgrade. ```text Requirement already satisfied: pyOpenSSL<24.0.0,>=16.2.0 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from snowflake-connector-python==3.0.*->landingai==0.0.40) (23.1.1)\nRequirement already satisfied: asn1crypto<2.0.0,>0.24.0 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from snowflake-connector-python==3.0.*->landingai==0.0.40) (1.5.1)\nRequirement already satisfied: idna<4,>=2.5 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from snowflake-connector-python==3.0.*->landingai==0.0.40) (3.4)\nRequirement already satisfied: cffi<2.0.0,>=1.9 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from snowflake-connector-python==3.0.*->landingai==0.0.40) (1.15.1)\nRequirement already satisfied: matplotlib>=3.4.2 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (3.7.1)\nRequirement already satisfied: python-dotenv>=0.10.4 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from pydantic[dotenv]->landingai==0.0.40) (1.0.0)\nRequirement already satisfied: pycparser in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from cffi<2.0.0,>=1.9->snowflake-connector-python==3.0.*->landingai==0.0.40) (2.21)\nRequirement already satisfied: fonttools>=4.22.0 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (4.39.4)\nRequirement already satisfied: pyparsing>=2.3.1 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (3.0.9)\nRequirement already satisfied: python-dateutil>=2.7 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (2.8.2)\nRequirement already satisfied: cycler>=0.10 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (0.11.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (1.4.4)\nRequirement already satisfied: contourpy>=1.0.1 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (1.0.7)\nRequirement already satisfied: six>=1.5 in /Users/asia/Library/Caches/pypoetry/virtualenvs/landingai-_c3uY8Dq-py3.10/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib>=3.4.2->segmentation-mask-overlay<0.4.0,>=0.3.4->landingai==0.0.40) (1.16.0)\nBuilding wheels for collected packages: landingai\n Building editable for landingai (pyproject.toml) ... [?25ldone\n[?25h Created wheel for landingai: filename=landingai-0.0.40-py3-none-any.whl size=4424 sha256=e5c9f30990144126234944e03bc8ddc721f91bade3f58f517a50b570205a2ba4\n Stored in directory: /private/var/folders/cv/kdkz6y_55z1blffx_f42w6zh0000gn/T/pip-ephem-wheel-cache-qw6dcxys/wheels/57/df/6e/917cfef370ef8a31e12c5b0a81541f8aa462c4f83c9ade0780\nSuccessfully built landingai\nInstalling collected packages: landingai\n Attempting uninstall: landingai\n Found existing installation: landingai 0.0.40\n Uninstalling landingai-0.0.40:\n Successfully uninstalled landingai-0.0.40\nSuccessfully installed landingai-0.0.40\n\n[notice] A new release of pip available: 22.3.1 -> 23.1.2\n[notice] To update, run: pip install --upgrade pip ``` -------------------------------- ### Install LandingAI Python Library Source: https://github.com/landing-ai/landingai-python/blob/main/docs/index.md Install the LandingAI Python library using pip. Ensure you are using a compatible version. ```bash pip install landingai~=0.3.0 ``` -------------------------------- ### Run Streamlit App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/object-tracking/README.md Launch the Streamlit application to start the object detection on a live stream. ```bash streamlit run examples/apps/object-tracking/main.py ``` -------------------------------- ### Install Dependencies (Windows) Source: https://github.com/landing-ai/landingai-python/blob/main/examples/edge-models/README.md Installs project dependencies on Windows systems. Note that tflite-runtime is not available for Windows; Tensorflow is recommended. ```bash pip install -r requirements_win.txt ``` -------------------------------- ### Install Dependencies for Image Folder App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/image-folder-support/README.md Use this command to install the necessary Python packages for the image folder support application. ```bash pip install -r examples/apps/image-folder-support/requirements.txt ``` -------------------------------- ### Install Requirements Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/surfer-count/README.md Install the necessary Python packages for the Streamlit app. Ensure you have a requirements.txt file in the specified directory. ```bash pip install -r examples/apps/surfer-count/requirements.txt ``` -------------------------------- ### Install OCR App Dependencies Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/ocr/README.md Install the necessary Python packages for the OCR app by running this command in your terminal. ```bash pip install -r examples/apps/ocr/requirements.txt ``` -------------------------------- ### Launch Streamlit App for Image Folder Inference Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/image-folder-support/README.md Run this command to start the Streamlit application for local image folder inference. ```bash streamlit run examples/apps/image-folder-support/app.py ``` -------------------------------- ### Initialize Object Detection Predictor Source: https://github.com/landing-ai/landingai-python/blob/main/examples/webcam-collab-notebook/webcam-collab-notebook.ipynb Sets up the Predictor object with a model endpoint and API key. These variables should be configured according to your LandingLens model setup. ```python #@title Set the following variables as needed for your setup # These keys correspond to a public LandingLens model api_key = "land_sk_aMemWbpd41yXnQ0tXvZMh59ISgRuKNRKjJEIUHnkiH32NBJAwf" #@param {type:"string"} model_endpoint = "0b3ad59c-80ca-481b-977f-f2470cbe83e3" #@param {type:"string"} ``` ```python from landingai.predict import Predictor from landingai.visualize import overlay_predictions predictor = Predictor(model_endpoint, api_key=api_key) # Run prediction and show raw results results = predictor.predict(frame) display(results) ``` -------------------------------- ### Configure Stream URL and Credentials Source: https://github.com/landing-ai/landingai-python/blob/main/examples/capture-service/README.md Update these variables in the `run.py` file with your specific API key, endpoint ID, and RTSP stream URL to customize the example for your camera and deployed model. ```python api_key = "YOUR_API_KEY" endpoint_id = "YOUR_ENDPOINT_ID" stream_url = "YOUR_RTSP_STREAM_URL" ``` -------------------------------- ### Install LandingAI with Snowflake Optionals Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/snowflake-native-app.md Install the landingai package with the snowflake optionals to enable the SnowflakeNativeAppPredictor class. This is required for running inference with Snowflake Native Apps. ```sh pip install "landingai[snowflake]" ``` -------------------------------- ### Run Streamlit App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/surfer-count/README.md Execute the Streamlit application to start the live object detection. This command launches the app in your web browser. ```bash streamlit run examples/apps/surfer-count/main.py ``` -------------------------------- ### Run Edge Model with Hardware Acceleration Source: https://github.com/landing-ai/landingai-python/blob/main/examples/edge-models/README.md Executes an edge model bundle with hardware acceleration enabled. The delegate library path is an example and should be replaced with your actual library path. ```bash python run_bundle_cls.py published_model_bundle.zip image.png /usr/lib/libvx_delegate.so ``` -------------------------------- ### Run Inference with Predictor Source: https://context7.com/landing-ai/landingai-python/llms.txt Load an image into a Frame object and run prediction using the initialized predictor. This example shows the basic inference process and how to access the number of predictions. ```python frame = Frame.from_image("/path/to/image.jpg") frame.run_predict(predictor=predictor) print(f"Predictions: {len(frame.predictions)}") ``` -------------------------------- ### Configure API Key and Endpoint ID Source: https://github.com/landing-ai/landingai-python/blob/main/examples/post-processings/farmland-coverage/farmland-coverage.ipynb Set the api_key and endpoint_id variables to access your deployed Visual Prompting model in LandingLens. Ensure these are correctly configured for your setup. ```python #@title Set the following variables as needed for your setup\napi_key = "land_sk_aMemWbpd41yXnQ0tXvZMh59ISgRuKNRKjJEIUHnkiH32NBJAwf"\nendpoint_id = "63035608-9d24-4342-8042-e4b08e084fde" ``` -------------------------------- ### OCR Inference Output Example Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/ocr.md This is an example of the expected output format when running OCR inference, showing the extracted text and its associated confidence score. ```text Hi From (Confidence: 0.9179285764694214) Landing.AI (Confidence: 0.7755413055419922) ``` -------------------------------- ### Use SnowflakeNativeAppPredictor for Inference Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/snowflake-native-app.md Example of initializing and using the SnowflakeNativeAppPredictor for inference. Ensure you have the correct endpoint ID, native app URL, and Snowflake credentials. Authentication via private key is recommended for production. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import SnowflakeNativeAppPredictor endpoint_id = "c4344971-fc3c-4cb8-8fd5-5144d25cbd74" url = "https://focq4dkf-rkwerpo-your-account.snowflakecomputing.app" predictor = SnowflakeNativeAppPredictor( endpoint_id=endpoint_id, # (1)! native_app_url=url, # (2)! snowflake_account="your-snowflake-account-locator", # (3)! snowflake_user="your-snowflake-user", # (4)! snowflake_private_key="your-snowflake-user-private-key", # (5)! ) frame = Frame.from_image("/home/user/dataset/some-class/image-1.png") frame.run_predict(predictor=predictor) print(frame.predictions) # [ # ClassificationPrediction( # score=0.9957893490791321, # label_name='some-class', # label_index=0 # ) # ] ``` -------------------------------- ### Initialize Media Client and List Media Source: https://github.com/landing-ai/landingai-python/blob/main/docs/metadata.md Initialize the `Media` client with your project ID and API key. Use the `ls()` method to list all media with metadata from a project. Pagination can be controlled using `offset` and `limit` parameters. ```python from landingai.data_management import Media YOUR_API_KEY = "land_sk_12345" YOUR_PROJECT_ID = 1190 media_client = Media(YOUR_PROJECT_ID, YOUR_API_KEY) media_client.ls() ``` ```python media_client.ls(offset=0, limit=100) ``` ```python media_client.ls(split="train") ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/landing-ai/landingai-python/blob/main/docs/_README.md Run this command to serve the documentation locally. Open http://127.0.0.1:8000/ in your browser to view it. ```bash poetry run mkdocs serve -f mkdocs.yml ``` -------------------------------- ### Initialize Media Client Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/5_data_management.md Initialize the Media client with your project ID and API key to interact with LandingLens media management features. ```python from landingai.data_management import Media # Provide API Key and project ID YOUR_API_KEY = "land_sk_12345" YOUR_PROJECT_ID = 1190 # Lists all medias with metadata from a project media_client = Media(YOUR_PROJECT_ID, YOUR_API_KEY) ``` -------------------------------- ### List Images in Project Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Initialize the Media client for a specific project and list images using offset and limit parameters for pagination. ```python from landingai.data_management import Media project_id = 45412657190923 # List images media_client = Media(project_id, api_key) media_client.ls(offset=0, limit=2) ``` -------------------------------- ### Initialize Predictor and Run Inference on Webcam Stream Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/4_pipelines.md Initializes a `Predictor` with your endpoint ID and API key. It then captures frames from a webcam at 1 FPS, resizes them, runs predictions, and saves the resulting image with an overlay of the predictions. ```python predictor = Predictor(endpoint_id="abcde-1234-xxxx", api_key="land_sk_xxxx") # Get images from Webcam at a 1 FPS rate, run predictions on it and save results. with Webcam(fps=1) as webcam: for frame in webcam: frame .downsize(width=512) .run_predict(predictor=predictor) .save_image(f"/tmp/detected-object", image_src="overlay") ``` -------------------------------- ### Install Requirements for Crack Measurer Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/crack-measurer/README.md Installs the necessary Python packages for the crack measurer application. Ensure you are in the project's root directory. ```bash pip install -r examples/apps/crack-measurer/requirements.txt ``` -------------------------------- ### Load Images from URIs Source: https://github.com/landing-ai/landingai-python/blob/main/examples/post-processings/farmland-coverage/farmland-coverage.ipynb Fetches image data from provided URIs and opens them using Pillow. Ensure Pillow is installed (`pip install Pillow`). ```python from PIL import Image as PILImage from landingai.storage.data_access import fetch_from_uri img_paths = [ fetch_from_uri("https://drive.google.com/uc?id=1z7KiNcXmfbNQL-rz6NMv7eVTBh-CnpAs"), fetch_from_uri("https://drive.google.com/uc?id=1Vfbrdj8UFI03dv9fncw2OWWaadGeWBDq"), fetch_from_uri("https://drive.google.com/uc?id=1kauz5WyB3rJb0_9qM1MukVmHkNJ9t1vQ"), ] images = [PILImage.open(path) for path in img_paths] ``` -------------------------------- ### Install Requirements for License Plate OCR App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/license-plate-ocr/README.md Install the necessary Python packages for the license plate OCR Streamlit app by running this command. ```bash pip install -r examples/apps/license-plate-ocr/requirements.txt ``` -------------------------------- ### Run Edge Model (Basic) Source: https://github.com/landing-ai/landingai-python/blob/main/examples/edge-models/README.md Executes an edge model bundle with a specified image. This is the basic execution command. ```bash python run_bundle_cls.py published_model_bundle.zip image.png ``` -------------------------------- ### Run the Streamlit Application Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/README.md Execute this command to launch the Landing AI application using Streamlit. The application will open in your web browser. You may need to grant camera permissions. ```bash streamlit run app.py ``` -------------------------------- ### Set Python Version with Poetry Source: https://github.com/landing-ai/landingai-python/blob/main/docs/contributing.md Activates a specific Python version for your Poetry environment after Poetry has been installed. ```bash poetry env use 3.10 ``` -------------------------------- ### List Media with Default Pagination Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/5_data_management.md List all media assets in a project with default pagination settings. The output includes metadata for each media item. ```python media_client.ls() # Output: # { medias: [{'id': 4358352, 'mediaType': 'image', 'srcType': 'user', 'srcName': 'Michal', 'properties': {'width': 258, 'height': 176}, 'name': 'n01443537_501.JPEG', 'uploadTime': '2020-09-15T22:29:01.338Z', 'metadata': {'split': 'train', 'source': 'prod'}, 'media_status': 'raw'}, ...], # num_requested: 1000, # count: 300, # offset: 0, # limit: 1000 } ``` -------------------------------- ### Capture and Resize Desktop Screenshots to Video Source: https://github.com/landing-ai/landingai-python/blob/main/docs/image-acquisition/screenshots.md Capture the first 20 frames from your desktop, resize each frame to a width of 512 pixels while maintaining aspect ratio, and save the processed frames as a video file. Ensure you have the necessary imports and initialize `FrameSet` before capturing. ```python from landingai.pipeline.image_source import Screenshot from landingai.pipeline.frameset import FrameSet import time frameset = FrameSet() # (1)! with Screenshot() as screenshots: # (2)! for i, frame in enumerate(screenshots): # (3)! if i >= 20: break frame.resize(width=512) # (4)! frameset.append(frame) # (5)! time.sleep(0.5) # (6)! frameset.save_video("/tmp/resized-video.mp4") # (7)! ``` -------------------------------- ### Import Core SDK Components Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Import necessary modules from the LandingAI Python SDK for camera, prediction, and image operations. ```python from landingai.pipeline.image_source import NetworkedCamera from landingai.predict import Predictor from landingai.image_source_ops import take_photo_from_webcam from landingai.visualize import overlay_bboxes ``` -------------------------------- ### Acquire Image from File Source: https://github.com/landing-ai/landingai-python/blob/main/README.md Load an image from a file path, resize it, and save the resized image. Ensure the image file exists at the specified path. ```python from landingai.pipeline.frameset import Frame frame = Frame.from_image("/path/to/your/image.jpg") frame.resize(width=512, height=512) frame.save_image("/tmp/resized-image.png") ``` -------------------------------- ### Run Inference on Single Image with FrameSet Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Process a single image file using the FrameSet class for inference. This example demonstrates chaining operations for prediction, visualization, and display. ```python from landingai.pipeline.frameset import FrameSet # Run inference on a single image frs = FrameSet.from_image("image.jpg") frs.run_predict(predictor=model).overlay_predictions().show_image().show_image(image_src="overlay") ``` -------------------------------- ### Run Inference on Webcam Frames with LandingAI SDK Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/frames-inference.md This snippet demonstrates how to capture frames from a webcam, resize them, and run predictions using the LandingAI SDK. It checks for a specific label ('coffee-mug') in the predictions and prints them if found. Ensure you have your API key and endpoint ID. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import Predictor predictor = Predictor( endpoint_id="", api_key="", ) with Webcam(fps=0.5) as webcam: for frame in webcam: frame.resize(width=512) frame.run_predict(predictor=predictor) if "coffee-mug" in frame.predictions: print(frame.predictions) ``` -------------------------------- ### Iterate, Resize, and Save Video Frames Source: https://github.com/landing-ai/landingai-python/blob/main/docs/image-acquisition/video-file.md Use `landingai.image_source.VideoFile` to iterate over video frames. Resize each frame and collect them in a `FrameSet` before saving to a new video file. Specify `samples_per_second` when opening the video file. ```python from landingai.pipeline.image_source import VideoFile from landingai.pipeline.frameset import FrameSet frameset = FrameSet() # (1)! with VideoFile("/path/to/your/file.mp4", samples_per_second=5) as video_file: # (2)! for frame in video_file: # (3)! frame.resize(width=256) # (4)! frameset.append(frame) # (5)! frameset.save_video("/tmp/resized-video.mp4") # (6)! ``` -------------------------------- ### Get Label Map for Segmentation Masks Source: https://github.com/landing-ai/landingai-python/blob/main/docs/metadata.md Use the `Label` API to retrieve the label map required for uploading segmentation masks. This map associates pixel values with class names and should be saved to a JSON file. ```python client = Label(project_id, api_key) client.get_label_map() {'0': 'ok', '1': 'cat', '2': 'dog'} # then write this map to a JSON file locally ``` -------------------------------- ### Clone Repository with Git Source: https://github.com/landing-ai/landingai-python/blob/main/docs/examples.md Use this command to clone the LandingAI Python SDK repository to your local machine. ```bash git clone https://github.com/landing-ai/landingai-python.git ``` -------------------------------- ### Filter Predictions by Confidence Score using LandingAI SDK Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/frames-inference.md This example demonstrates how to filter predictions to include only those with a confidence score greater than 0.95 for the 'coffee-mug' label. It prints a message if such a prediction is found, indicating high confidence. ```python with Webcam(fps=0.5) as webcam: for frame in webcam: frame.run_predict(predictor=predictor) if "coffee-mug" in frame.predictions.filter_threshold(0.95): print(f"I'm super sure I found a coffee-mug in the frame!") ``` -------------------------------- ### Run Inference with EdgePredictor Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/docker-deployment.md Use `EdgePredictor` to send images to a Docker container for inference. Specify the host and port of your running container. This example captures frames from a webcam, runs predictions, overlays them, and saves an image if a 'coffee-mug' is detected. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import EdgePredictor predictor = EdgePredictor(host="localhost", port=8000) # (1)! with Webcam(fps=15) as webcam: # (2)! for frame in webcam: frame.run_predict(predictor=predictor) # (3)! frame.overlay_predictions() if "coffee-mug" in frame.predictions: # (4)! frame.save_image( "/tmp/latest-webcam-image.png", include_predictions=True ) ``` -------------------------------- ### List and Query Media in LandingLens Source: https://context7.com/landing-ai/landingai-python/llms.txt Provides functionality to list and filter media within a LandingLens project. Supports pagination, filtering by status, metadata, and updating split assignments. ```python from landingai.data_management.media import Media media_client = Media(project_id=12345, api_key="land_sk_your_api_key") # List all medias (with pagination) result = media_client.ls(offset=0, limit=100) print(f"Found {result['count']} medias") for media in result['medias']: print(f"ID: {media['id']}, Name: {media['name']}") # Filter by media status result = media_client.ls(media_status="approved") result = media_client.ls(media_status=["approved", "raw"]) # Filter by metadata result = media_client.ls(batch_id="batch_001", camera_id="camera_A") # Update split assignments media_ids = [1001, 1002, 1003] media_client.update_split_key(media_ids, split_key="test") # Remove from split (set to unassigned) media_client.update_split_key(media_ids, split_key="") ``` -------------------------------- ### Display an Image Source: https://github.com/landing-ai/landingai-python/blob/main/examples/post-processings/farmland-coverage/farmland-coverage.ipynb Displays the first image loaded from the specified paths. This is useful for a quick visual check. ```python display(images[0]) ``` -------------------------------- ### Initialize SnowflakeNativeAppPredictor with Private Key Source: https://context7.com/landing-ai/landingai-python/llms.txt Initialize the SnowflakeNativeAppPredictor using Snowflake account credentials and a private key for authentication. This is an alternative to password authentication. Ensure the private key is correctly formatted. ```python predictor = SnowflakeNativeAppPredictor( endpoint_id="your-endpoint-id", snowflake_account="your_account.region", snowflake_user="your_username", snowflake_private_key="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", native_app_url="https://your-native-app-url.snowflakecomputing.app" ) ``` -------------------------------- ### List Media Information Source: https://github.com/landing-ai/landingai-python/blob/main/docs/metadata.md Use the media_client.ls() function to retrieve a list of media items within a project, including their IDs, metadata, and upload times. ```python media_client.ls() >>> { medias: [ { 'id': 4358352, 'mediaType': 'image', 'srcType': 'user', 'srcName': 'Michal', 'properties': {'width': 258 'height': 176}, 'name': 'n01443537_501.JPEG', 'uploadTime': '2020-09-15T22:29:01.338Z', 'metadata': {'split': 'train' 'source': 'prod'}, 'media_status': 'raw' }, ... ], num_requested: 1000, count: 300, offset: 0, limit: 1000 } ``` -------------------------------- ### Overlay Predictions on Webcam Feed Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/overlaying-predictions.md Initializes a Predictor, iterates through webcam frames, runs inference, overlays predictions, and saves the frame if a specific object is detected. Ensure your endpoint ID and API key are correctly set. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import Predictor predictor = Predictor( # (1)! endpoint_id="", api_key="", ) with Webcam(fps=0.5) as webcam: for frame in webcam: # (2)! frame.resize(width=512) frame.run_predict(predictor=predictor) # (3)! frame.overlay_predictions() # (4)! if "coffee-mug" in frame.predictions: frame.save_image( path="frame-with-overlay.png", include_predictions=True, # (5)! ) ``` -------------------------------- ### Upload Folder of Images Source: https://github.com/landing-ai/landingai-python/blob/main/docs/metadata.md Upload an entire folder of images to your project. Assign all uploaded images to a specified split, such as 'train'. ```python media_client.upload("/Users/tom/Downloads/images", split="train") ``` -------------------------------- ### Run Inference on Webcam Frames Source: https://github.com/landing-ai/landingai-python/blob/main/docs/index.md Capture frames from a webcam, send them for inference to a deployed LandingLens model, and save images with predictions if a specific object is detected. Resizing frames before inference can save bandwidth. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import Predictor predictor = Predictor( # (1)! endpoint_id="abcdef01-abcd-abcd-abcd-01234567890", # (2)! api_key="land_sk_xxxxxx", # (3)! ) with Webcam(fps=0.5) as webcam: for frame in webcam: frame.resize(width=512) # (4)! frame.run_predict(predictor=predictor) # (5)! frame.overlay_predictions() if "coffee-mug" in frame.predictions: # (6)! frame.save_image("/tmp/latest-webcam-image.png", include_predictions=True) # (7)! ``` -------------------------------- ### Create Snowflake User with Private Key Authentication Source: https://github.com/landing-ai/landingai-python/blob/main/docs/inferences/snowflake-native-app.md SQL commands to create a Snowflake user and role for LandingAI library integration, using RSA public key for authentication. This is the preferred method for production environments. ```sql CREATE OR REPLACE USER LANDING_LIBRARY_USER LOGIN_NAME = 'LANDING_LIBRARY_USER' DISPLAY_NAME = 'LandingAI Library User' COMMENT = 'User for LandingAI library' RSA_PUBLIC_KEY = 'MIIBI...'; -- Replace this with your public key CREATE ROLE LANDINGLENS_EXTERNAL_ACCESS; GRANT ROLE LANDINGLENS_EXTERNAL_ACCESS TO USER LANDING_LIBRARY_USER; GRANT APPLICATION ROLE llens_snw_production.LLENS_PUBLIC TO ROLE LANDINGLENS_EXTERNAL_ACCESS; ``` -------------------------------- ### Assign Metadata Values to Images Source: https://github.com/landing-ai/landingai-python/blob/main/docs/metadata.md Use the Metadata client to assign values to predefined metadata keys for specific images. Ensure metadata keys are created in the LandingLens UI beforehand. ```python from landingai.data_management import Metadata # Provide the API key and project ID YOUR_API_KEY = "land_sk_12345" YOUR_PROJECT_ID = 1190 metadata_client = Metadata(YOUR_PROJECT_ID, YOUR_API_KEY) # Set three metadata values ('timestamp', 'country' and 'labeler') for images with IDs 123 and 124 metadata_client.update(media_ids=[123, 124], timestamp=12345, country="us", labeler="tom") # Output: # { # project_id: 1190, # metadata: {"country": "us", "timestamp": "12345", labeler="tom"}, # media_ids: [123, 124] # } ``` -------------------------------- ### Acquire Images from Webcam Source: https://github.com/landing-ai/landingai-python/blob/main/README.md Continuously capture frames from a webcam, resize them, and save each frame as an image. Adjust the FPS for desired capture rate. ```python from landingai.pipeline.image_source import Webcam with Webcam(fps=0.5) as webcam: for frame in webcam: frame.resize(width=512, height=512) frame.save_image("/tmp/webcam-image.png") ``` -------------------------------- ### Predict with Webcam Image Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Capture an image from your webcam and perform inference using the initialized predictor. The results are overlaid on the image. ```python # Grab a frame frome your webcam and run predict on it image = take_photo_from_webcam() prediction = model.predict(image) overlay_bboxes(prediction, image) ``` -------------------------------- ### Run Inference on Webcam Feed Source: https://github.com/landing-ai/landingai-python/blob/main/README.md Capture frames from a webcam, resize them, and send them for inference to a deployed LandingLens model. Requires an endpoint ID and API key. Predictions are overlaid and saved if a specific object is detected. ```python from landingai.pipeline.image_source import Webcam from landingai.predict import Predictor predictor = Predictor( endpoint_id="abcdef01-abcd-abcd-abcd-01234567890", api_key="land_sk_xxxxxx", ) with Webcam(fps=0.5) as webcam: for frame in webcam: frame.resize(width=512) frame.run_predict(predictor=predictor) frame.overlay_predictions() if "coffee-mug" in frame.predictions: frame.save_image("/tmp/latest-webcam-image.png", include_predictions=True) ``` -------------------------------- ### Upload Folder of Images Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/5_data_management.md Upload an entire folder of images to LandingLens. All images within the folder will be uploaded and assigned to the specified split. ```python # upload a folder of images and assign them to the 'train' split media_client.upload("/Users/tom/Downloads/images", split="train") ``` -------------------------------- ### Activate Poetry Shell Source: https://github.com/landing-ai/landingai-python/blob/main/docs/examples.md Activate the virtual environment created by Poetry to manage project dependencies. ```bash poetry shell ``` -------------------------------- ### Upload Image to Project Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Upload a local image file to your LandingAI project, specifying the desired split (e.g., 'dev'). This requires the asyncio loop to be applied, especially in Jupyter environments. ```python # This code is needed to run asyncio loops in jupyter notebooks, it is not needed if # you are running python from the terminal. import nest_asyncio nest_asyncio.apply() # Upload image, make sure you have an image in your local directory called image.jpg media_client.upload("image.jpg", split="dev") ``` -------------------------------- ### List Media Items Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/5_data_management.md Retrieve a list of media items within a project using the media_client.ls() function. This can be used to find media IDs for other operations. ```python media_client.ls() >>> { medias: [{'id': 4358352, 'mediaType': 'image', 'srcType': 'user', 'srcName': 'Michal', 'properties': {'width': 258 'height': 176}, 'name': 'n01443537_501.JPEG', 'uploadTime': '2020-09-15T22:29:01.338Z', 'metadata': {'split': 'train' 'source': 'prod'}, 'media_status': 'raw'}, ...], num_requested: 1000, count: 300, offset: 0, limit: 1000 } ``` -------------------------------- ### Create and Use LandingAI FrameSet Source: https://context7.com/landing-ai/landingai-python/llms.txt Create a FrameSet, a collection for multiple frames, from an image or numpy array. Supports iteration and accessing individual frames. ```python from landingai.pipeline.frameset import Frame, FrameSet # Create a FrameSet from an image frameset = FrameSet.from_image("/path/to/image.jpg") print(f"Number of frames: {len(frameset)}") # Create FrameSet from numpy array frameset = FrameSet.from_array(numpy_array, is_bgr=True) # Iterate over frames for frame in frameset: print(frame.image.size) # Access individual frames first_frame = frameset[0] ``` -------------------------------- ### List Media with Custom Pagination Source: https://github.com/landing-ai/landingai-python/blob/main/pdocs/user_guide/5_data_management.md Paginate through media assets using custom offset and limit values to control the number of items retrieved per request. ```python # paginate with a custom page size media_client.ls(offset=0, limit=100) ``` -------------------------------- ### Launch OCR App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/ocr/README.md Run the Streamlit OCR application from your terminal using this command. ```bash streamlit run examples/apps/ocr/app.py ``` -------------------------------- ### Run Inference with Predictor Source: https://github.com/landing-ai/landingai-python/blob/main/examples/post-processings/farmland-coverage/farmland-coverage.ipynb Initializes a Predictor with an endpoint ID and API key, then runs predictions on a list of images. The results are aggregated into a single list. ```python from landingai.predict import Predictor predictor = Predictor(endpoint_id, api_key=api_key) predictions = [] for img in images: predictions.extend(predictor.predict(img)) ``` -------------------------------- ### Run Crack Measurer Streamlit App Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/crack-measurer/README.md Launches the Streamlit application for the crack measurer. This command should be run from the project's root directory. ```bash streamlit run examples/apps/crack-measurer/app.py ``` -------------------------------- ### Set API Key and Model Endpoint Source: https://github.com/landing-ai/landingai-python/blob/main/examples/rtsp-capture-notebook/rtsp-capture.ipynb Configure your LandingLens API key and model endpoint. Ensure these are correctly set for authentication and model access. ```python #@title Set the following variables as needed for your setup api_key = "land_sk_aMemWbpd41yXnQ0tXvZMh59ISgRuKNRKjJEIUHnkiH32NBJAwf" #@param {type:"string"} model_endpoint = "881e04f4-1a16-4728-b19c-a6900d0b8d98" #@param {type:"string"} ``` -------------------------------- ### Acquire Image from URI Source: https://github.com/landing-ai/landingai-python/blob/main/examples/rtsp-capture-notebook/rtsp-capture.ipynb Fetches an image from a given URI. This can be a direct image file URL or a Google Drive link. For real-time video, set camera_url to 0 for webcam or a specific RTSP stream URL. ```python from landingai.storage.data_access import fetch_from_uri # Below are some sample images for you to try out. img_paths = [ str(fetch_from_uri("https://drive.google.com/uc?id=1hA1npgptlvdRvLGewMNRqPjfclHHOiZ9")), str(fetch_from_uri("https://drive.google.com/uc?id=1vv48yWe0_SwcgX8AgfYg9lxqQ8aNxz0I")), str(fetch_from_uri("https://drive.google.com/uc?id=14RKAe-PioJwMf6DZP0Nk03YESJ0h7jb3")), str(fetch_from_uri("https://drive.google.com/uc?id=1Q1Y6oM2_63gj35z6h8Qu3j7CVr-bfLtt")), ] # In order to find the URL for your camera, this is a good start https://www.ispyconnect.com/cameras # camera_url = "rtsp://172.25.101.151/ch0_0.h264" #@param {type:"string"} camera_url = img_paths[0] # Use sample images # camera_url = 0 # Connect to local webcam ``` -------------------------------- ### Inspect Model Bundle CLI Source: https://github.com/landing-ai/landingai-python/blob/main/examples/edge-torch-models/README.md Use this script to inspect published model bundles. It supports detailed analysis of models and state dictionaries, and works with both .pth and .pt files. ```bash python inspect_model_bundle.py --bundle_path /path/to/published_model_bundle ``` ```bash python inspect_model_bundle.py --bundle_path /path/to/bundle --model_name qat_eval-saved_model ``` ```bash python inspect_model_bundle.py --bundle_path /path/to/bundle --detailed --show_weights ``` ```bash python inspect_model_bundle.py \ --bundle_path /path/to/published_model_bundle \ --model_name qat_eval-saved_model \ --detailed ``` ```bash python inspect_model_bundle.py \ --bundle_path /path/to/published_model_bundle \ --detailed \ --show_weights ``` -------------------------------- ### Initialize Predictor Object Source: https://github.com/landing-ai/landingai-python/blob/main/examples/apps/zoom-app/Zoom_Demo.ipynb Create a Predictor instance using your endpoint ID and API key to interact with your deployed model. ```python # Build the predictor object for your model model = Predictor(endpoint_id, api_key=api_key) ``` -------------------------------- ### Capture and Resize Webcam Frames to Video Source: https://github.com/landing-ai/landingai-python/blob/main/docs/image-acquisition/webcam.md Use this snippet to capture frames from your local webcam, resize them, and save them into a new video file. Ensure you have the necessary imports. ```python from landingai.pipeline.image_source import Webcam from landingai.pipeline.frameset import FrameSet frameset = FrameSet() # (1)! with Webcam(fps=1) as camera: # (2)! for i, frame in enumerate(camera): # (3)! if i >= 100: break frame.resize(width=256) # (4)! frameset.append(frame) # (5)! frameset.save_video("/tmp/resized-video.mp4") # (6)! ``` -------------------------------- ### Create LandingAI Frame from Image File Source: https://context7.com/landing-ai/landingai-python/llms.txt Create a Frame object from an image file path. Supports common image formats. Can also create from local or remote URIs. ```python from landingai.pipeline.frameset import Frame import numpy as np # Create a Frame from an image file (supports jpg, png, bmp, etc.) frame = Frame.from_image("/path/to/image.jpg") print(f"Image size: {frame.image.size}") # Create a Frame from a local or remote URI frame = Frame.from_image("https://example.com/image.png") # Create a Frame from a numpy array (e.g., from OpenCV) # By default assumes BGR format (OpenCV standard) img_array = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) frame = Frame.from_array(img_array, is_bgr=True) # Create a Frame with custom metadata frame = Frame.from_image( "/path/to/image.jpg", metadata={"camera_id": "cam_01", "timestamp": "2024-01-15T10:30:00"} ) print(frame.metadata) # {'camera_id': 'cam_01', 'timestamp': '2024-01-15T10:30:00'} ``` -------------------------------- ### Initialize SnowflakeNativeAppPredictor with Password Source: https://context7.com/landing-ai/landingai-python/llms.txt Initialize the SnowflakeNativeAppPredictor using Snowflake account credentials and a password for authentication. Ensure you have the necessary Snowflake account details and endpoint ID. ```python predictor = SnowflakeNativeAppPredictor( endpoint_id="your-endpoint-id", snowflake_account="your_account.region", snowflake_user="your_username", snowflake_password="your_password", # Or use private key below native_app_url="https://your-native-app-url.snowflakecomputing.app" ) ```