Metadata-Version: 2.1
Name: scale_sensor_fusion_io
Version: 0.6.2
Summary: Library for working with timestamp-based sensor fusion scenes
License: Apache-2.0
Author: Michael Choi
Author-email: michael.choi@scale.com
Requires-Python: >=3.10,<3.13
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Dist: dacite2 (>=2.0.0,<3.0.0)
Requires-Dist: ffmpeg-python (>=0.2.0,<0.3.0)
Requires-Dist: numpy (>=2.2.3,<2.5)
Requires-Dist: opencv-python (>=4.7.0.72,<5.0.0.0)
Requires-Dist: pandas (>=2.2.3,<3.0.0)
Requires-Dist: pyturbojpeg (>=1.7.1,<2.0.0)
Requires-Dist: scale-json-binary (>=0.0.7,<0.0.8)
Requires-Dist: scipy (>=1.10.1,<1.17)
Requires-Dist: sk-video (>=1.1.10,<2.0.0)
Requires-Dist: tqdm (>=4.65.0,<5.0.0)
Requires-Dist: typing-extensions (>=4.5.0,<5.0.0)
Requires-Dist: ujson (>=5.13.0,<6.0.0)
Description-Content-Type: text/markdown

# scale-sensor-fusion-io

Python SDK for building, reading and validating **Sensor Fusion Scene (SFS)** files, the `.sfs` format that Scale uses for lidar, radar and camera labeling tasks.

The full format specification (every sensor and annotation field, plus prelabels and task creation) is in the [Sensor Fusion Reference](https://scale.com/docs/api-reference/sensor-fusion-reference). This page covers the SDK.

## Installation

```bash
pip install scale-sensor-fusion-io
```

Supported Python versions: **3.10, 3.11 and 3.12**.

`scale-json-binary` (the `.sfs` encoder and decoder) is installed as a dependency.

Encoding or decoding camera video (`generate_video`, or reading frames from a loaded video camera) also needs an `ffmpeg` executable with `libx264` on your `PATH`. pip doesn't install it: the `ffmpeg-python` dependency is only a wrapper. Install it with your system package manager, for example `brew install ffmpeg` or `apt-get install ffmpeg`.

## Concepts

An SFS scene holds every sensor and annotation for one sequence on a single timeline:

- **Timestamps** are integers in **microseconds**, relative to the scene's `time_offset`. Store `absolute_time_us - time_offset`, not absolute times.
- **Poses** are `[x, y, z, qx, qy, qz, qw]`. The quaternion is **scalar-last**. Some libraries, such as `pyquaternion`, are scalar-first, so reorder before passing their values in.
- **Coordinates** default to `"world"`. Lidar and radar points are in world coordinates, and each sensor's `poses` give the sensor's pose in the world at each timestamp.
- Points use typed numpy arrays: `float32` positions with shape `(N, 3)`, `uint8` intensities and colors, and `uint32` per-point timestamps.
- Use `time_unit="microseconds"` (the default). The format also defines `"nanoseconds"` with `uint64` per-point timestamps, but this SDK's validation rejects both, so `validate_scene` and `parse_and_validate_scene` fail on such scenes.

The SDK has two representations of a scene:

| Representation        | Module                            | Use it to                                                                                                                                |
| --------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `sfio.Scene` (models) | `scale_sensor_fusion_io.models`   | Build and edit scenes. Paths such as `PosePath` and `CuboidPath` are pandas DataFrames indexed by timestamp, with interpolation helpers. |
| `SFS.Scene` (spec)    | `scale_sensor_fusion_io.spec.sfs` | Read and write files. Mirrors the on-disk format exactly.                                                                                |

Convert between them with `to_scene_spec_sfs` and `from_scene_spec_sfs` from `scale_sensor_fusion_io.model_converters`.

## Building a scene

```python
import numpy as np
import scale_sensor_fusion_io as sfio
from scale_sensor_fusion_io.model_converters import to_scene_spec_sfs
from scale_json_binary import JSONBinaryEncoder

time_offset = 1_700_000_000_000_000        # absolute start time, in microseconds
timestamps = [0, 100_000, 200_000]         # relative to time_offset: 3 frames at 10 Hz

# Ego poses in world coordinates: one [x, y, z, qx, qy, qz, qw] row per timestamp.
ego_poses = sfio.PosePath(
    data=[
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
        [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
    ],
    index=timestamps,
)

def load_points(ts):  # replace with your own loader; points must be in world coordinates
    rng = np.random.default_rng(ts)
    return rng.uniform(-20, 20, (1000, 3)).astype(np.float32), rng.integers(0, 255, 1000, dtype=np.uint8)

frames = []
for ts in timestamps:
    positions, intensities = load_points(ts)
    frames.append(
        sfio.LidarSensorFrame(
            timestamp=ts,
            points=sfio.LidarSensorPoints(positions=positions, intensities=intensities),
        )
    )

lidar = sfio.LidarSensor(id="lidar", poses=ego_poses, frames=frames)
odometry = sfio.OdometrySensor(id="odometry", poses=ego_poses)

# CuboidPath columns: x, y, z, yaw, pitch, roll, dx, dy, dz
# (center position in meters, rotation in radians, full dimensions in meters)
car = sfio.CuboidAnnotation(
    id="car-1",
    label="Car",
    path=sfio.CuboidPath(
        data=[[5.0 + i, 2.0, 0.8, 0.0, 0.0, 0.0, 4.5, 1.9, 1.6] for i in range(3)],
        index=timestamps,
    ),
)

scene = sfio.Scene(
    sensors=[lidar, odometry],
    annotations=[car],
    time_offset=time_offset,
    time_unit="microseconds",
)

JSONBinaryEncoder().write_file("scene.sfs", to_scene_spec_sfs(scene))
```

The model `CuboidPath` uses the column order above. The SFS file stores cuboids as `[dx, dy, dz, x, y, z, roll, pitch, yaw]`. `to_scene_spec_sfs` reorders the columns for you, so only use the file order when you write SFS dicts by hand.

`to_scene_spec_sfs` copies angles unchanged, and the Scale platform reads cuboid rotations in radians. However, `CuboidPath.as_matrix()` and `CuboidPath.from_matrix()` treat yaw, pitch and roll as **degrees**, and so does `utils.pose_helpers.transform_path` when it is applied to a `CuboidPath`. If you use those helpers, convert with `np.degrees` before and `np.radians` after, so the path you write still holds radians.

### Cameras

A camera needs a camera-to-world `PosePath`, intrinsics, and either JPEG images or an MP4 video. This example continues from the one above and uses two inputs you supply:

```python
# Your inputs: one JPEG path per timestamp, and the camera's pose in the world at each timestamp.
image_files = ["frames/000.jpg", "frames/001.jpg", "frames/002.jpg"]
camera_poses = sfio.PosePath(
    data=your_camera_to_world_poses,  # shape (3, 7): one [x, y, z, qx, qy, qz, qw] row per timestamp
    index=timestamps,
)

intrinsics = sfio.CameraIntrinsics(
    fx=1000.0, fy=1000.0, cx=960.0, cy=540.0, width=1920, height=1080,
    # Values in the parameter order of the model, here k1, k2, p1, p2, k3.
    distortion=sfio.CameraDistortion.from_values("brown_conrady", [-0.1, 0.01, 0.0, 0.0, 0.0]),
)

# Option 1: one JPEG per timestamp
images = []
for ts, path in zip(timestamps, image_files):
    with open(path, "rb") as f:
        images.append(
            sfio.CameraSensorImage(timestamp=ts, content=np.frombuffer(f.read(), dtype=np.uint8))
        )
camera = sfio.CameraSensor(id="front_camera", poses=camera_poses, intrinsics=intrinsics, images=images)

# Option 2: an MP4 (usually much smaller; see "Reducing file size").
# Needs the ffmpeg executable with libx264 (see Installation).
from scale_sensor_fusion_io.utils.video_helpers import generate_video

generate_video(image_files, "front_camera.mp4", fps=10)
with open("front_camera.mp4", "rb") as f:
    video = sfio.CameraSensorVideo(
        timestamps=timestamps, content=np.frombuffer(f.read(), dtype=np.uint8), fps=10
    )
camera = sfio.CameraSensor(id="front_camera", poses=camera_poses, intrinsics=intrinsics, video=video)
```

Supported distortion models: `brown_conrady`, `fisheye`, `mod_kannala`, `mod_equi_fish`, `cylindrical`, `omnidirectional`, `equirectangular`, `fisheye_rad_tan_prism`, `fisheye_radial_custom`, `ftheta`. You can also build a distortion from a dict with `sfio.CameraDistortion.from_dict({"model": "brown_conrady", "k1": -0.1, ...})`.

### Other sensors and annotations

- **Sensors:** `LidarSensor`, `RadarSensor`, `CameraSensor`, `OdometrySensor`, `PointsSensor` (a static point cloud) and `RobotSensor`.
- **Annotations:** cuboid, 2D box, 2D point, 2D polyline, 2D polygon, point, top-down point, points (keypoints), polygon, top-down polygon, polyline, event, text, labeled points, localization adjustment, object and link.
- **Scene-level attributes:** pass `sfio.AttributePath(name=..., timestamps=..., values=...)` in `Scene(attributes=[...])`.

The [Sensor Fusion Reference](https://scale.com/docs/api-reference/sensor-fusion-reference) documents the fields of each type.

## Loading a scene

`SFSLoader` takes a local file path. Expand `~` yourself, because the path is opened as given.

```python
from scale_sensor_fusion_io.loaders import SFSLoader

loader = SFSLoader("scene.sfs")

scene = loader.load()            # sfio.Scene (models): the easiest to work with
sfs_scene = loader.load_as_sfs() # SFS.Scene (spec): mirrors the file
raw = loader.load_unsafe()       # plain dict with no parsing: for repairing malformed files

# Already have the bytes (for example, from S3)?
sfs_scene = SFSLoader.load_from_bytes(raw_bytes)
```

## Validating a scene

Validate before you create a task. Validation catches structural problems such as missing fields, wrong array shapes, mismatched lengths and timestamps that don't increase. It does **not** catch semantic mistakes such as the wrong quaternion order, a world/ego mix-up, or cuboid rotations in a different unit from the one the platform expects (radians). Check those by loading the scene in a test task.

**A scene object:**

```python
from dataclasses import asdict
import scale_sensor_fusion_io as sfio

errors = sfio.validate_scene(scene)  # returns None when the scene is valid
if errors:
    print(asdict(errors))
```

**A `.sfs` file:**

```python
from dataclasses import asdict
from scale_json_binary import read_file
from scale_sensor_fusion_io.validation import parse_and_validate_scene

result = parse_and_validate_scene(read_file("scene.sfs"))
if result.success:
    print("Scene parsed and validated successfully")
else:
    print(asdict(result))
    # {'success': False,
    #  'details': [{'path': ['sensors', 0, 'poses'],
    #               'errors': ['missing value for field "poses"']}]}
```

## Reducing file size

Scenes that cover a long time span can grow to several GB, which makes them slow to load and can time out on upload. Two ways to shrink them:

- **Encode cameras as video.** Use `CameraSensorVideo` with `generate_video` instead of individual JPEGs. MP4 compresses far better, at a small cost in image quality, which is usually fine for 3D labeling.
- **Downsample point clouds.** For cuboid annotation, voxel-downsample with voxels of at most 20 mm. A good rule of thumb for efficient loading and labeling is to keep a scene under 100,000 points. For example, keep one point per voxel in each lidar frame:

  ```python
  def voxel_downsample(points: sfio.LidarSensorPoints, voxel_size: float) -> sfio.LidarSensorPoints:
      voxels = np.floor(points.positions / voxel_size).astype(np.int64)
      _, keep = np.unique(voxels, axis=0, return_index=True)
      keep.sort()
      pick = lambda a: None if a is None else a[keep]
      return sfio.LidarSensorPoints(
          positions=points.positions[keep],
          colors=pick(points.colors),
          intensities=pick(points.intensities),
          timestamps=pick(points.timestamps),
      )

  for frame in lidar.frames:
      frame.points = voxel_downsample(frame.points, voxel_size=0.02)
  ```

  `scale_sensor_fusion_io.utils.downsample` also has downsamplers, but they work on raw scene dicts and need intensities and per-point timestamps on every frame. `downsample_scene` also **keeps only the first 200 frames** of each lidar sensor, which truncates long scenes.

## Changelog

**0.6.1**

- Capped `numpy<2.5` and `scipy<1.17`. numpy 2.5 (Python 3.12 only) breaks every `SFSLoader` load and `parse_and_validate_scene` call with `TypeError: isinstance() arg 2 must be a type`. scipy 1.17 breaks single-`Pose` math (`Pose.as_transform`, `Pose @ Pose`, `interpolate_pose`). If you're on 0.6.0 or 0.5.x, upgrade, or pin those two packages yourself.

**0.6.0**

- Added the `point_2d`, `polyline_2d`, `polygon`, `point`, `point_topdown`, `link`, `text` and `points` annotation types.

## License

Apache-2.0

