LightlyStudio

repository·main·Indexed 21 days ago

https://github.com/lightly-ai/lightly-studio

An open-source tool for unifying data workflows, including curation, annotation, model evaluation, and management. It features a Rust-powered backend for handling large datasets like COCO and ImageNet, a SvelteKit-powered frontend, and a Python API for indexing datasets (COCO, YOLO), adding custom annotations, and running object detection evaluations.

Tokens
74.9K
Snippets
215
Records
311
Agent score
74%

What's inside LightlyStudio

  1. Overview of Fast Track

    main

    Fast Track is a TypeScript package designed for the Fast Track Bot. It consists of two main components:

    1. Guardrails: Logic that judges a Pull Request (PR) and produces a machine-readable verdict.json.
    2. Bot: An automated agent that acts on the guardrail verdict.

    In a GitHub environment, the Fast Track Guardrails workflow judges non-draft PRs using a read-only token and uploads the verdict. The Fast Track Bot workflow then uses a short-lived App token to validate the artifact, maintain approval/status comments, and manage PR states.

    Key behaviors:

    • Opt-out: Add the no-fast-track label to a PR to defer to a human.
    • Security: The bot refuses fork PRs and revokes approval if a verdict is missing, invalid, or stale.
    • Execution: The package runs via tsx, meaning there is no build step or compiled artifact required.
  2. Overview of LightlyStudio

    main
    LightlyStudio is an open-source tool designed to unify data workflows, including curation, annotation, and management. It is built with Rust to ensure high performance, enabling users to work with large datasets like COCO and ImageNet even on consumer-grade hardware (e.g., a MacBook Pro with M1 and 16GB of memory).
  3. Understand the LightlyStudio Backend Architecture

    main

    The LightlyStudio backend is a Python package located in lightly_studio/src/lightly_studio. It functions as a local application, a FastAPI server, and a web UI host.

    Core Technology Stack

    • FastAPI: Handles the HTTP API and application lifecycle.
    • Pydantic: Manages request/response models, validation, and OpenAPI schema generation.
    • SQLModel: Provides typed database access and models on top of SQLAlchemy.
    • Uvicorn: The ASGI server used to run the backend.
    • Database Support: Supports DuckDB (default) and PostgreSQL (alternative).

    Layered Architecture and Request Flow

    Requests typically follow a specific flow to maintain separation of concerns: FastAPI route $\rightarrow$ optional service $\rightarrow$ resolver(s) $\rightarrow$ SQLModel / database.

    • Routes (api/): Translate HTTP input into typed models, wire dependencies, and map failures to HTTP responses. Note: Do not raise HTTPException directly in routes; raise specific exceptions and let the API layer handle the conversion.
    • Services (services/): An orchestration layer for workflows that span multiple resolvers or require branching business logic. Use these for cross-entity operations.
    • Resolvers (resolvers/): The layer responsible for database-facing query and mutation functions. This is where most persistence logic resides.
    • Models (models/): Contains SQLModel tables and Pydantic/SQLModel request/view models.
  4. Explore Image Datasets in the GUI

    main

    The LightlyStudio GUI provides two primary views for interacting with image datasets:

    Grid View

    The main view displays a grid of images. Key features include:

    • Filtering: Use the left panel to filter images by tags, annotations, or metadata.
    • Search: Use the search bar for similarity searches via text or image.
    • Embeddings: Use the Show Embeddings button to explore the data in embedding space.
    • Menu: Access plugins, sampling, classification, and export options via the Menu dropdown.

    Detail View

    Double-clicking an image in the Grid View opens the Detail View, where you can:

    • Annotate the image.
    • Add captions.
    • View image metadata.
  5. What is metadata and when to use it

    main

    Metadata allows you to store arbitrary key-value data for every sample in your dataset. It is used to attach context such as capture conditions (weather, lighting), GPS coordinates, sensor identifiers, production line IDs, or custom attributes.

    Note: For specific data types like embeddings, captions, annotations, predictions, or tags, use the dedicated built-in concepts instead of generic metadata.

  6. Understand LightlyStudio roles and permissions

    main

    LightlyStudio uses a role-based access control system to manage collaboration. Roles determine what actions a user can perform within the workspace:

    • Viewer: Can explore and export data but cannot modify anything.
    • Labeler: Can create tags and edit annotations.
    • Editor: Can perform all Labeler actions, plus configure workspace settings, use the Few-Shot Classifier, manage Sampling, and use Plugins.
    • Admin: Can perform all Editor actions, plus manage users and their roles.
  7. How to find outliers using Typicality

    main

    Typicality is a per-sample score derived from embeddings. Samples close to many others receive a high score (typical); outliers receive a low score.

    To find outliers, compute typicality metadata and then use metadata_weighting with a negative strength to prefer low-typicality samples. To find a diverse but representative subset, combine typicality with diversity sampling.

    import lightly_studio as ls
    
    dataset = ls.ImageDataset.load_or_create()
    dataset.add_images_from_path(path="/path/to/image_dataset")
    
    # Compute and store typicality scores as metadata.
    dataset.compute_typicality_metadata(metadata_name="typicality")
    
    # Sample the 5 most typical items.
    dataset.query().sampling().metadata_weighting(
        n_samples_to_select=5,
        sampling_result_tag_name="typical_sampling",
        metadata_key="typicality",
    )
    
    # Sample 5 outliers.
    dataset.query().sampling().metadata_weighting(
        n_samples_to_select=5,
        sampling_result_tag_name="outlier_sampling",
        metadata_key="typicality",
        strength=-1
    )
  8. Use TanStack Query with Svelte 5 runes

    main

    TanStack Query v6 is runes-based. To use it in hooks, you must use the .svelte.ts file extension.

    Crucial Pattern: For hooks wrapping TanStack Query, accept a getter function (thunk) for reactive parameters. Do not pass Svelte stores or $derived values directly, as TanStack Query v6 requires thunks for reactivity.

    Accessing Results: The query result is a reactive proxy. Access properties like query.isSuccess or query.data directly without the $ prefix.

    Example: Reactive Hook with Thunk

    // useFrames.svelte.ts
    export const useFrames = (
      getParams: () => { video_frame_collection_id: string; filter: VideoFrameFilter }
    ) => {
      const query = createInfiniteQuery(() => {
        const { video_frame_collection_id, filter } = getParams();
        return {
          // ... options
        };
      });
      return { query };
    };
    
    // Consumer (+page.svelte)
    const { query } = useFrames(() => ({
      video_frame_collection_id: collectionId,
      filter: currentFilter
    }));
    
    // Access directly (no $ prefix)
    if (query.isSuccess) { ... }
    // useFrames.svelte.ts
    export const useFrames = (
      getParams: () => { video_frame_collection_id: string; filter: VideoFrameFilter }
    ) => {
      const query = createInfiniteQuery(() => {
        const { video_frame_collection_id, filter } = getParams();
        return {
          ...getAllFramesInfiniteOptions({
            path: { video_frame_collection_id },
            body: { filter }
          }),
          getNextPageParam: (lastPage) => lastPage.nextCursor || undefined
        };
      });
      return { query };
    };
    
    // Consumer (+page.svelte)
    const { query } = useFrames(() => ({
      video_frame_collection_id: collectionId,
      filter: currentFilter
    }));
  9. Analyze Metadata Distributions

    main

    Metadata distributions allow you to inspect sample-level attributes. After selecting Metadata in the Distribution panel, you can choose a specific metadata key to visualize.

    Numeric Metadata

    Numeric fields (e.g., temperature, brightness, confidence, blur score) are displayed as histograms.

    • Adjust Detail: Change the number of bins to modify granularity.
    • Filtering: Click a bin or drag across multiple bins to filter the dataset to that specific range. Re-selecting the same range clears the filter.

    Categorical Metadata

    Categorical fields (e.g., city, camera ID, weather, or boolean values) are displayed as bar charts.

    • Filtering: Select one or more values to filter the dataset.
    • Missing: Represents samples where the selected key has no value.
    • Other: Groups less frequent values that are not explicitly shown in the chart (these cannot be selected for filtering).
  10. Understand LightlyStudio Enterprise vs Open-Source

    main

    LightlyStudio Enterprise is designed for scalable ML data management, curation, and annotation. Compared to the Open-Source version, Enterprise provides the following capabilities:

    • Multi-user Support: Enterprise supports multiple users with authentication and Single Sign-On (SSO), whereas Open-Source is limited to a single user.
    • Dataset Management: Enterprise allows managing multiple datasets with fine-grained access control. Open-Source only supports a single dataset.
    • Credential Management: In Enterprise, cloud credentials are centrally managed by an administrator. In Open-Source, they are managed via local environment variables.
    • GUI Access: The Enterprise GUI is always running on the server. The Open-Source GUI is started locally using ls.start_gui().
    • Python API Usage: The Python API remains the same, but in Enterprise, you must call ls.connect() to establish a connection to the server.
  11. Triage model evaluation errors in LightlyStudio

    main

    When evaluating a model, high False Positives (fp) or False Negatives (fn) do not always indicate a model failure. Use the following triage logic to determine the cause:

    SignalLikely causeAction
    High fp/fn, and the ground-truth box looks wrongMislabeled, missing, or shifted annotationFix the box in the ground_truth layer, or tag wrong_annotations to fix later
    High fp/fn, and the ground-truth box looks correctReal model gap: confused classes, hard scenes, objects the model never learnedTag by pattern (for example failure_small_objects) and group with embedding clusters
    High fn on a small, isolated clusterNot enough data to tell a real gap from noiseAdd and label more images like that cluster, then re-evaluate

    Note: Always re-run evaluation after fixing ground-truth annotations to ensure metrics reflect actual model performance rather than annotation noise.

  12. Understand LightlyStudio data security and storage

    main

    LightlyStudio is designed so that raw images and videos are never stored on Lightly servers.

    Depending on your deployment model, the data handling differs:

    • OSS: Only analytics data is sent to Lightly. The version can be run fully offline.
    • Lightly-Hosted: Lightly stores analytics, user account information, and dataset metadata (including annotations). Raw images and videos are streamed from your storage to the browser on demand but are not stored by Lightly.
    • On-Premise: No data is sent to Lightly. This deployment can be fully offline and air-gapped.