LandingAI Python Library

repository·main·Indexed 42 days ago

https://github.com/landing-ai/landingai-python

A helper library (version 0.3.50) for interacting with LandingLens. It provides tools to integrate computer vision models into applications, supporting image acquisition from files, webcams, and RTSP streams, running inference via deployed endpoints, and post-processing results. The library includes support for edge model inference, model bundle inspection, and various Streamlit-based example applications for OCR, object tracking, and segmentation.

Tokens
31.5K
Snippets
114
Records
134
Agent score
52%

What's inside LandingAI

  1. Explore LandingAI usage examples

    main

    The repository provides several example implementations categorized by type (Jupyter Notebooks for ease of use and Python applications for robust experiences):

    Jupyter Notebooks

    • Poker Card Suit Identification: Uses an object detection model from LandingLens to detect suits on playing cards via webcam.
    • Door Monitoring for Home Automation: Uses an object detection model to detect if a door is open or closed using an RTSP camera.
    • Satellite Images and Post-Processing: Uses a Visual Prompting model to identify objects in satellite images, including post-processing to calculate ground cover percentages.
    • License Plate Detection and Recognition: Extracts frames from video files and uses object detection and OCR to identify and recognize license plates.

    Python Applications

    • Streaming Video: A continuous inference application running on images extracted from a streaming RTSP video camera feed.
  2. Use landingai.predict for inference tasks

    main

    The landingai.predict module provides the primary entry points for running inference using LandingAI models. It is organized into specialized submodules depending on the execution environment and specific task requirements:

    • landingai.predict.cloud: For running inference on LandingAI's hosted cloud infrastructure.
    • landingai.predict.edge: For running inference locally on edge devices or local hardware.
    • landingai.predict.ocr: Specialized functions for Optical Character Recognition tasks.
    • landingai.predict.snowflake: Integration for running inference within Snowflake environments.
    • landingai.predict.utils: Utility functions supporting the prediction workflows.
  3. Acquire images using the LandingAI SDK

    main

    The LandingAI SDK supports multiple input sources for image acquisition. You can ingest data from:

    • Image files: Local or remote image files.
    • Video files: Processing frames from video files.
    • Webcam: Capturing live streams from a connected webcam.
    • Network cameras: Accessing IP cameras or network-attached video sources.
    • Screenshots: Capturing the current state of your screen.
  4. Use the landingai.postprocess module for inference results

    main

    The landingai.postprocess module provides APIs to transform and aggregate inference result data. Common post-processing tasks include:

    • Class Counting: Calculating the predicted class count across a set of image predictions.
    • Area/Coverage Calculation: Calculating the predicted pixel area (coverage) for predictions across a set of images.

    Refer to the landingai.postprocess module documentation for specific function signatures and implementation details.

  5. Understand `landingai` versioning and releases

    main

    The landingai library follows Semantic Versioning 2.0.0 (MAJOR.MINOR.PATCH). The version is defined in the version field of the pyproject.toml file.

    Versioning Rules

    • MAJOR: Increment for incompatible API changes.
    • MINOR: Increment for backward-compatible functionality additions (e.g., new features).
    • PATCH: Increment for backward-compatible bug fixes.

    Release Automation

    • PATCH updates: The CD pipeline automatically increments the PATCH version for every git commit.
    • MINOR/MAJOR updates: You must manually update the version field in pyproject.toml to bump the version number for these changes.
  6. How Vision Pipelines work in LandingAI

    main

    Vision Pipelines simplify complex vision tasks by applying a sequence of operations to images.

    • landingai.pipeline.frameset.Frame: Represents a single image.
    • landingai.pipeline.frameset.FrameSet: Represents a sequence of images (an iterator). Most image sources, even those providing a single image, return a FrameSet.

    Pipelines allow you to chain operations like resizing, running inference, and filtering results. For example, a NetworkedCamera can provide a FrameSet iterator that feeds into subsequent processing stages, which can then introduce new derived frames (like cropped regions of interest) into the pipeline.

  7. Identify API Key Versions (v1 vs v2)

    main

    When managing credentials, ensure you are using the correct version for the landingai Python package.

    FeatureAPI Key v1 (Legacy)API Key v2 (Current)
    PrefixNoneStarts with land_sk_
    FormatKey and Secret pairSingle string
    SDK SupportNot supported in landingai >= 0.1.0Required for landingai >= 0.1.0
    Generation DateBefore July 2023After July 2023
  8. Build vision pipelines using Frames and method chaining

    main

    For complex workflows (e.g., reading an RTSP stream, detecting motion, identifying objects, and classifying them), the library uses a Vision Pipeline concept.

    In this model, Frames produced by an image source are passed through various processing modules using method chaining. This allows you to compose multi-step computer vision operations into a single, cohesive pipeline.

  9. Expected structure of a published model bundle

    main

    Both the inspector and inference tools expect a model bundle organized in the following directory structure:

    published_model_bundle/
    ├── model/
    │   ├── before_train-saved_model.pth    # Pre-training PyTorch model
    │   ├── qat-saved_model.pt              # QAT training TorchScript model
    │   ├── qat_eval-saved_model.pt         # QAT evaluation TorchScript model
    │   └── saved_model.tflite              # (Not supported)
    ├── model_meta/
    │   ├── transforms.yaml                 # Image preprocessing (height/width)
    │   └── train.yaml                      # Training config (score threshold)
    ├── dm.json                             # Defect map (class labels)
    ├── meta.json                           # Model metadata
    └── original_dm.json                    # Original defect map

    Important: The inference tool specifically requires .pt (TorchScript) files. The model_meta/ directory is critical for the inference tool to correctly preprocess images and filter results.

  10. Acquire images using Webcam, Screenshot, or NetworkedCamera

    main

    You can use various data acquisition classes to feed images into a pipeline:

    • landingai.pipeline.image_source.Webcam: Collects images directly from the local device's webcam. Supports an fps parameter to control the capture rate.
    • landingai.pipeline.image_source.Screenshot: Captures screenshots of the current device.
    • landingai.pipeline.image_source.NetworkedCamera: Connects to a live video source and exposes it as a FrameSet iterator.
  11. How the Predictor class works for inference

    main

    The landingai.predict.Predictor class is the primary abstraction for getting inference results from models trained in LandingLens. It abstracts away the complexities of server communication, error handling, and result parsing.

    Key Mental Models:

    • Computation Location: The actual model inference computation does not happen within the Python library; it occurs on the model server (either a LandingLens Cloud Deployment or your own server via LandingEdge).
    • Deployment Support: The library currently supports Cloud Deployment. Edge Deployment support is planned for a future release.
    • Rate Limiting: When using Cloud Deployment, there is a limit of 40 inferences per minute per endpoint. If you exceed this, the server returns a 429 Too Many Requests status code. By default, the Predictor.predict() method will automatically wait 60 seconds and retry if it encounters a 429 error.
    from landingai.predict import Predictor
    
    # Initialize the predictor with your endpoint and API key
    predictor = Predictor(endpoint_id, api_key=api_key)
    
    # Run inference
    results = predictor.predict(img)
  12. Run OCR inference to extract text from images

    main

    You can extract text from images using the landingai.predict.OcrPredictor class. This class provides pre-trained OCR models that work with various font types and handwriting.

    Workflow

    1. Initialize the Predictor: Create an OcrPredictor instance using your API key. You can optionally specify a language parameter:
      • ch: Supports Chinese and English characters (default).
      • en: Supports only English characters; may provide better accuracy if you know the image is exclusively English.
    2. Prepare the Image: Create a Frame instance from an image source (e.g., a file path, webcam, or video).
    3. Run Inference: Call frame.run_predict(predictor) to process the frame.
    4. Access Results: Iterate through frame.predictions to access the extracted text and confidence scores.
    from landingai.predict import OcrPredictor
    from landingai.pipeline.image_source import Frame
    
    # 1. Initialize predictor with API key and optional language
    predictor = OcrPredictor(api_key="<insert your API key here>", language="en")
    
    # 2. Create a Frame from an image
    frame = Frame.from_image("/path/to/image.png")
    
    # 3. Run inference
    frame.run_predict(predictor)
    
    # 4. Iterate over predictions
    for prediction in frame.predictions:
        print(f"{prediction.text} (Confidence: {prediction.score})")