VisionSet probes media during ingest to record the information annotation and export need.
The ImageProcessor interface reads still images, reports their dimensions, and generates
JPEG previews. Point-cloud ingest has its own scanner for PCD and PLY files.
from visionset.kernel.services import WorkspaceService
with WorkspaceService.open("./road-signs") as workspace:
with open("photos/IMG_0043.jpg", "rb") as handle:
metadata = workspace.image_processor.probe(handle) # ImageMetadata(width=..., ...)
preview = workspace.image_processor.thumbnail(handle) # opaque JPEG bytesImageProcessor is the image port WorkspaceService composes, and it is named for stills
rather than for media because that is all it ever reads. Point-cloud scans have a port of their
own beside it - see Point-cloud scans. This process never decodes video: a
client materializes a clip into JPEG frames on its own machine and posts them here, and from that
point on each one is an ordinary image - decoded, hashed and thumbnailed by exactly the same
ImageProcessor a directory of photos goes through. See ingest.md for the session
that stages those frames, and sources.md for what a video source records once they
land. There used to be a second, parallel port here for a server-side video decoder; it is gone,
and nothing replaced it in this process - see "Video moved to the browser" below.
ImageProcessor takes an open binary stream, never a path: every caller already has one, a
source is read through a file handle and a blob in the blob store is opened the same way, so
nothing is lost by not accepting a bare path.
ImageFormat names everything a dataset may contain: JPEG and PNG, frozen. Acceptance is
deliberately wider. ImageProcessor.stills reads anything Pillow decodes - WebP, HEIC and HEIF
(what an iPhone writes), BMP, TIFF, GIF and the rest - and normalizes everything outside the two
into them at ingest, so a dataset consumer never needs a third decoder.
| You give VisionSet | The dataset holds |
|---|---|
| JPG / JPEG, PNG | your exact bytes, untouched |
| WebP, HEIC / HEIF, BMP, TIFF, anything else Pillow decodes | a JPEG, re-encoded at ingest |
| animated GIF, animated WebP | one PNG per frame, anim.gif#frame=3 |
| MP4, MOV, AVI, WebM, MKV, or anything a browser can demux | one JPEG per extracted frame, materialized client-side |
A converted or decomposed still keeps the original path in its uri, so provenance stays
legible: an asset at photo.heic whose format reads jpeg was transcoded on the way in, and
the original file on disk is untouched. Transcoding is repeatable within one Pillow build, not
across builds - the same caveat a browser's video materializer carries across its own versions.
Out of scope for this distribution: RAW camera formats (CR2, NEF, DNG), AVIF, and JPEG XL. A Live Photo is two files; the photo ingests as a still, and its clip may be registered as an ordinary video source.
The frozen enum is the promise that matters: VisionSet will decode, hash, thumbnail and export JPEG and PNG for as long as the workspaces written today are readable. What can be read may drift with the installed Pillow; what a dataset holds may not.
MPO is a special case worth knowing about and is not a third format. It is a
multi-picture JPEG container - what phones write in portrait and burst modes - so it is an
alias in the decoder's table, and its primary frame is what every viewer shows and what
VisionSet reads. Leaving it out would have rejected a large share of real camera output as
unsupported.
The bytes decide the format, not the filename. A .png holding JPEG bytes reports jpeg.
A suffix is a hint for choosing which files to look at; what a file is comes from decoding it.
The video side has no curated list at all: VideoMetadata.codec is a plain str recording
whatever a client's decoder read off the container, not a member of an enum this distribution
maintains.
The asymmetry is the argument. An image is an asset; a video is a source. Curating
ImageFormat buys something real, because those exact bytes enter the dataset and the promise
above is made about them. A video's bytes never do - they leave the decoder as JPEG frames - so a
closed list of codecs would gate nothing while going stale every time a camera vendor ships a new
profile. codec therefore records what was read instead of deciding what may be read, which
is the same split as DatasetChange.operation being a str while DatasetOperation is the enum
a writer picks from.
ImageMetadata.width and .height are as displayed. A 32×24 JPEG carrying EXIF orientation
6 probes as 24×32, and its thumbnail comes out 24×32 to match.
The alternative - report the stored dimensions and pass the tag along - pushes the rotation onto
every consumer, and the consumers are an annotation canvas, an exporter and a bounding box in
pixel coordinates. One of them forgetting is a dataset whose labels are ninety degrees off,
discovered by a model that will not converge. There is deliberately no orientation_applied
flag: a caller that could branch on it would be a caller who was handed the un-normalized case
after all, and nothing persists it.
Orientations 5 through 8 involve a quarter turn and swap the edges; 1 through 4 are identity, mirror and 180° and do not. An image with no EXIF at all - which is most images - reports its stored dimensions, and that is the ordinary path rather than a fallback.
The policy is format-independent. PNG carries EXIF in an eXIf chunk and is oriented on
exactly the same terms as JPEG, which is the case a hand-rolled tag-274 reader gets wrong.
It is modality-independent too, in the sense that a video frame arriving here has already had
the same problem solved before it ever reached ImageProcessor: a clip carries its turn in a
display matrix rather than in an EXIF tag, a phone held upright writes a landscape stream plus a
quarter turn, and the client materializing the clip applies that matrix before it ever encodes a
frame to JPEG. What lands on the asset is the swapped edges, on the same terms as VideoMetadata
reports them - see sources.md.
Every thumbnail() returns a JPEG, at most 256 pixels on its longest edge unless the caller
says otherwise, opaque, with the aspect ratio preserved and no metadata from the source. The
encoder arguments are fixed in one dict - quality 85, 4:4:4 chroma, no Huffman optimization, no
progressive scan - and each of those is a knob whose default has moved between library builds.
The format is fixed by the port, not chosen per call, because a thumbnail is meant to be content-addressed: the bytes are the cache key, so a per-call format would give one image several equally correct hashes. Changing any of these values invalidates every thumbnail ever stored - which is safe, they are a cache - but it is a decision, not an edit, and a test will make you make it on purpose.
Three behaviours worth stating outright:
- It never enlarges. An image already inside the box comes back at its own size. Inventing pixels to fill a preview is a lie the gallery would then have to display.
- Transparency is composited onto white, not flattened. JPEG has no alpha channel, and
convert("RGB")keeps whatever colour happened to sit under a fully transparent pixel - so a transparent red pixel comes out red, which is arbitrary and usually wrong. - The output is built on a fresh canvas. An ICC profile or a JFIF density riding along in the source would be a second input to bytes that are supposed to depend on nothing but the pixels.
Identical source bytes give identical thumbnail bytes, across runs, across processes and across two processor instances, on one machine with one installed Pillow. Nothing in the path reads a clock, a PID or a random source.
It does not hold across Pillow versions, libjpeg builds or platforms - resampling coefficients and SIMD kernels differ, and the same picture can legitimately encode to different bytes on a colleague's laptop. The consequence is the practical rule: assert repeatability, never a hardcoded hash.
What follows for anything built on top: a thumbnail hash is a cache key, not an identity. Two machines ingesting one image may store two thumbnail blobs, which costs a few kilobytes and nothing else. What must not be built on it is a release manifest recording a thumbnail hash, or a verification pass recomputing one - source-content hashes are reproducible, derived-artifact hashes are not, and conflating the two is how a "verified" release starts failing on a different machine.
asset.thumbnail_hash is where that cache key is recorded, and it holds itself to every word of
this paragraph: it is absent from Manifest, ReleaseService.verify does not touch it, and a
NULL there is an ordinary state rather than a fault. See ingest.md.
Two errors under one MediaError base, so an ingest can catch the family once, record the
failure against the item it was reading, and carry on with the next file.
| Error | Means | Remedy |
|---|---|---|
UnsupportedMedia |
an empty (0-byte) file, not an image at all, an image in a format outside ImageFormat, one declaring more pixels than the decoder will take, or - for a staged video frame - a declared width/height that disagrees with what the bytes decode to |
filter the input, convert the file, or ask for the format to be accepted |
CorruptMedia |
an accepted format whose bytes will not decode | re-fetch, re-export, or re-materialize the frame |
An empty file is refused with the reason the file is empty (0 bytes) rather than as an
unrecognizable image, so the report does not send anyone looking for a format problem. It is
UnsupportedMedia because no header claims an accepted format, the same answer the
point-cloud reader gives an empty scan, even though the usual remedy is to copy the file again.
A truncated JPEG or PNG is refused wherever the cut lands: inside the header, just into the
compressed pixel data, or at half the file. A cut among the header's markers or chunks can
come back as either error, depending on whether enough survives for Pillow to identify the
format; a cut anywhere in the pixel data is CorruptMedia. A refused file becomes no asset and
leaves no blob. One cut is not refused: a PNG missing only its last few bytes (the zlib and
chunk checksums and the IEND trailer) still decodes to every pixel, and is stored as it is.
The split is by remedy, which is the only thing an error hierarchy should branch on. "Your input folder contains a README" and "one of your JPEGs is truncated" have opposite answers, and collapsing them into one error gives an ingest summary where ordinary operator noise buries real data loss.
It is deliberately not three. A ThumbnailFailed would have no independent cause - a thumbnail
fails exactly when the decode fails. And splitting UnsupportedMedia into "not an image" versus
"unaccepted format" asks the decoder a question it cannot answer: an unidentifiable container
and an exotic one both come back as I do not know what this is.
The family is named for media, not images, for a reason that outlived the server-side video
decoder that first justified it: VideoImportService runs every posted video frame through this
same ImageProcessor before it is staged, so a malformed frame from a browser's materializer
raises exactly one of these two, on the same terms a bad file on disk would. See
ingest.md.
A missing file is a FileNotFoundError, and a max_edge < 1 passed to thumbnail() is a
ValueError - both sit outside the family on purpose, because neither is a property of any
media.
MediaError is the only error in the kernel with a constructor, and it carries two attributes
so that a per-file report is a table rather than a list of sentences:
try:
metadata = workspace.image_processor.probe(handle, name=str(path))
except MediaError as exc:
report.append({"item": exc.name, "kind": type(exc).__name__, "reason": exc.reason})reasonnever repeats the name. The name is a column.nameis reporting, never identity. Nothing looks a file up by it. A caller that already knows which item it was iterating should key its report on that.- An explicit
name=wins; otherwise the stream's own filename is used when it has one.Nonestays an honest answer rather than a fabricated one - an in-memory frame genuinely has no filename, and a handle from the blob store has one that is true and useless.
Nothing here trusts a header. A file is accepted only once its pixels have actually come out,
because a dataset that admits an asset on a convincing header is a dataset that discovers the
truth during a training run. That is why probing pays for a full decode per file instead of
sniffing, and why Image.verify() is never called - it walks checksums without producing
pixels, and it leaves the image in a state where a later load() raises AssertionError, which
is neither a media error nor catchable as one.
The adapter also leaves Pillow's process-wide globals alone. MAX_IMAGE_PIXELS stays at its
default, so a header claiming forty thousand pixels a side is refused for free before a decoder
runs; raising that limit is the embedding program's call, not a library's. And
LOAD_TRUNCATED_IMAGES stays False - setting it turns this file is corrupt into here is
half an image and no error, which is the silent failure these ports exist to prevent.
Both methods read from the beginning and do not close what they were given. That first rule is what lets an ingest hash, probe and thumbnail one open handle in any order with no position bookkeeping; without it, hashing a file and then probing the same handle reports a perfectly good JPEG as corrupt - a bug that looks exactly like the feature working.
A non-seekable stream (a pipe) works, and serves exactly one call: it cannot be rewound, so the second call sees nothing. A test says so, rather than leaving it to be discovered.
ImageProcessor is the fourth port on WorkspaceService, reached as workspace.image_processor
and built by a zero-argument image_processor_factory on both init and open - the shape the
event bus uses, because it is not derived from the workspace path. One per open
workspace, never a module-level singleton, and nothing to close: the decoder holds no state at
all.
A new port is appended last to WorkspaceService.__init__, never inserted: both classmethods
bind those arguments positionally, so a parameter added in the middle silently re-binds every one
after it.
No service below the composition point ever names PillowImageProcessor. That is the rule
workspaces.md describes, and it is what makes swapping the decoder a change to
two functions and to nowhere else.
PointCloudProcessor reads single point-cloud scans, the way ImageProcessor reads stills, and
is a separate port because a scan has no pixels: every image method would be one a scan
implementation raised from. It is reached as workspace.point_cloud_processor, built by a
zero-argument point_cloud_processor_factory, appended last on WorkspaceService. The default
adapter, StdlibPointCloudProcessor, uses the standard library to parse and Pillow to draw.
from visionset.kernel.domain import ScanFrame
with open("scans/000042.pcd", "rb") as handle:
metadata = workspace.point_cloud_processor.probe(
handle
) # PointCloudMetadata(format="pcd", ...)
preview = workspace.point_cloud_processor.thumbnail(handle, frame=ScanFrame.LIDAR_FLU)The bytes decide, never the suffix, as for images: the header is sniffed, so a .bin holding
a PCD is read as one. KITTI's headerless .bin cannot be sniffed and is a format importer's job:
the kitti import stores each as a binary PCD of the same bytes, as the
nuscenes import does with LIDAR_TOP's .pcd.bin, which is headerless too despite its name.
| Format | Encodings read |
|---|---|
| PCD | DATA ascii, binary and binary_compressed (LZF) |
| PLY | ascii, binary_little_endian and binary_big_endian; the vertex element is read, and faces, tristrips and other elements are skipped |
x, y and z must be float fields. intensity, and colour as a four-byte PCD rgb or rgba
or PLY red/green/blue, are recorded in fields when present - a PCD colour field of another
width is not, since it is never read as one; anything else is ignored, including
PCD padding (_). A point with a non-finite coordinate - an organized cloud's empty pixel - is
dropped and not counted.
probe decodes every point before it answers, so a refused scan never leaves a blob or an asset
behind. It returns PointCloudMetadata: the format, the point_count kept, the axis-aligned
bounds of those points, and the fields.
| Refusal | When |
|---|---|
UNSUPPORTED_MEDIA |
not a PCD or PLY header; an encoding not read; no float x, y, z; more than 10 million points declared, or more than 512 MiB of point data, counting what a PLY holds before its vertices |
CORRUPT_MEDIA |
a recognisable header whose data is truncated or malformed, a header that contradicts itself (a SIZE below 1, a negative COUNT, POINTS other than WIDTH x HEIGHT, a PLY property named twice, an element before the vertices declaring an implausible count), an ascii row over 64 KiB, a damaged LZF stream, or no finite point at all |
What a PLY holds before its vertices is bounded by its vertices. Such an element is skipped, not decoded, but a row holding a list has to be walked one at a time. So an element there may declare at most eight rows per vertex the file declares, the rows holding a list (and every ascii row) at most two per vertex together, and the bytes skipped count toward the 512 MiB; a header that declares more is refused before anything is walked. An element of empty lists ahead of one vertex is refused at once rather than walked for half a minute.
The limits are sized for one scan. Ten million points is several sweeps of a 128-beam lidar,
and keeps the decoded coordinates - three doubles a point at most, three floats for a scan that
stores them so - under a quarter of a gigabyte. That bounds the
coordinates, not a viewer sample: measured on one machine, a sample of a 10,000,000-point scan peaked at
about 429 MiB (performance.md). The
limits are checked against the header before anything is decoded, and an LZF stream may be no
larger than LZF can make from the data the header declares. Whatever else a hostile file
provokes while it is parsed is refused as CORRUPT_MEDIA against that one file: an ingest run
reports it and carries on, and nothing of it is stored.
read gives both answers from one decode, and is what ingest uses: the scan is parsed once, and
its blob is written only after it, together with its preview.
The thumbnail is a bird's-eye view, drawn from above along the source's declared frame's up axis with forward up the picture: each pixel is the tallest point in it, shaded from dark to light over the scan's height range, on black. It is a JPEG like every other preview, sized and pinned the same way, so the thumbnail route and the gallery serve it unchanged.
A point-cloud asset carries modality: "point_cloud" and its point_cloud metadata, and no
width, height, format or calibration. Its content is served as application/octet-stream,
the PCD or PLY as ingested. Whatever reads pixels refuses it with UNSUPPORTED_MEDIA - a point
suggestion, a pre-processing preview, MCP's get_asset_image with full - and a pre-label run
passes it over. A pixel-space label (bbox, polygon, polyline) on a scan is refused with
INVALID_ANNOTATION; a classification_tag and the 3D geometries are accepted.
sample(handle, budget=n) is the fourth method, and the only one that decodes intensity and
colour as well as x, y and z. It keeps every ceil(total / budget)-th of the scan's finite
points in file order, so one scan and one budget always give the same points, and returns a
PointSample (in visionset.kernel.domain): the total before thinning, the stride, and
the origin, and little-endian buffers of float32 positions relative to that origin, float32
intensity and 8-bit colour, the last two None when the scan has no such field. A non-finite
intensity reads as 0, and a position still beyond float32's range is held at its edge. Colour is a four-byte PCD rgb or rgba unpacked
from its 0x00RRGGBB, or PLY red, green and blue together - uchar as stored, ushort scaled down,
float read as 0 to 1; a scan with only some of the three channels has no colour. It refuses
exactly what probe refuses.
IngestService.points(project_id, asset_id, max_points=500_000) reads a stored scan through it,
and GET /projects/{project_id}/assets/{asset_id}/points?max_points=N serves
PointSample.encode():
| Bytes | Content |
|---|---|
| 0-15 | header, little-endian: the magic VSPC, then u32 version (1), u32 count, u32 flags (bit 0 intensity, bit 1 rgb, bit 2 origin) |
| next 24, if bit 2 | f64 origin x, y, z |
next 12 x count |
f32 x, y, z per point, relative to the origin |
next 4 x count, if bit 0 |
f32 intensity per point |
next 3 x count, if bit 1 |
u8 r, g, b per point |
max_points is 1,000 to 2,000,000, default 500,000; a value outside that range is 422
VALIDATION_ERROR (a ValueError through the service), not clamped. An image asset is 404
ASSET_NOT_FOUND: it has no points. The scan's full count and bounds are not in the buffer -
they are the asset's point_cloud metadata.
Positions are relative to an origin, so float32 keeps a georeferenced scan's precision. At a
million metres float32's spacing is six centimetres. A point is origin + position. Each axis whose
median finite point lies 8,192 or more from zero (POINT_ORIGIN_THRESHOLD) is offset by that
median, rounded to a whole unit; every other axis by zero. The median is read from an even stride
of at most 4,096 of every finite point (POINT_ORIGIN_SUBSAMPLE), not from the bounds, so a stray
return at zero cannot pull the origin off the scan, and it depends on the scan alone, never on the
budget. A scan near its frame's zero has a zero origin and no bit 2, so its buffer is laid out
as it was before the origin existed; a reader that does not know bit 2 refuses a buffer that has
it, rather than drawing it in the wrong place. Labels are not moved: a cuboid or polyline stays in
the scan's frame, and the viewer subtracts the origin, in doubles, only from what it hands the GPU.
A decoded sample is cached per workspace, and a scan is decoded once whatever the budget. The
first request for a scan decodes the whole scan into its stride-1 sample, which is kept in the open
workspace's point_samples cache under the asset's content_hash and MAX_POINT_CLOUD_POINTS;
every budget is thinned from it (thinned in visionset.kernel.domain) and kept under the hash
and that budget. Every point is encoded on its own and the origin depends on the scan alone, so a
thinned sample is byte for byte what sampling the scan at that budget answers. Content addressing
is what keeps an entry from going stale: other bytes have another hash, so an entry is only ever
served for the bytes it was decoded from. The cache holds at most 128 MiB of samples and drops the
least recently used first; a sample bigger than that is served and not kept, so a scan whose whole
sample passes the bound (about seven million points with both fields) is decoded again for a
budget not yet asked for. Concurrent requests for one uncached scan share one decode, whatever
their budgets, and at most two scans are decoded at once across the workspace; a refusal is raised
to each waiting request and not kept. At 19 bytes a point with both fields, one sample is about
9.5 MB at the default budget and 38 MB at the maximum. The response is held in memory as well:
PointSample.encode() joins the sections into one new buffer on every request, cached or not, so
each request in flight holds one more copy of its sample.
A decode holds one copy of the columns it reads. Binary point data is read in bounded chunks and each wanted field gathered into its own column, never the raw rows whole beside them; a coordinate keeps the width the file stored it in. A scan with no non-finite coordinate is not copied again, and one with some is filtered a column at a time.
On the recorded baseline, ingest decoded, hashed and
thumbnailed a 640x480 JPEG in about 13 ms, flat from 500 to 5,000 images (65 s for 5,000), and
stored about 1.1 times the source bytes. A 120,000-point binary PCD scan cost about 79 ms to
ingest (about 46 ms in a later re-run), and a cold points() sample of it at the default budget about 13 ms (0.3 ms once
cached). At the other end, a single scan at the 10,000,000-point cap
took about 2.8 s to ingest and 1.3 s for a cold default sample, and a viewer sample of it peaked at
about 429 MiB of resident memory, above the quarter of a gigabyte the cap's note describes for the
coordinates alone. The limits above are refusals; an over-limit header is refused in under a
millisecond before any point is read. Those timings are measurements on one machine, and
performance.md lists the sizes and shapes nobody has measured.
This page used to describe a second port here, VideoProcessor, backed by an adapter that shelled
out to ffmpeg and streamed extracted PNG frames back. That port is gone. A client can still demux
and decode a clip on the machine it sits on and post the JPEG frames it produced through the
session VideoImportService manages. A server-side ingest is the second door: the kernel's
VideoDecoder port, implemented only by an adapter that runs the system's FFmpeg 6.1 or newer as a
subprocess, found on PATH or through VISIONSET_FFMPEG and VISIONSET_FFPROBE, never bundled or
installed by VisionSet. It feeds the same session, and its decoder build is recorded as the
materializer; see Server-side video ingest and
the decision. See ingest.md for that session and sources.md for what a video
source records about the client that produced its frames.
The reasons a dedicated video port existed are still true of the code that replaced it - a decoder that seeks needs an addressable clip rather than a stream, and the sampling grid, the rotation handling and the scale rounding all had to be pinned somewhere for two independent readings of one clip to agree on a frame count. They are just true of a browser package now instead of a server-side adapter, one that ports this kernel's own grid arithmetic across the language boundary rather than re-deriving it.
Two things used to be listed here as not built yet, and neither is. Source came off the list
with registration, which records what a client's decoder read off a clip and the extraction
policy chosen for it, built on VideoMetadata exactly as anticipated - see
sources.md. The Asset fields came off it with ingest: what a probe
reports is stored as asset.format, and a video frame's ordinal and timestamp land on the asset
as frame_index/frame_timestamp beside the source it was cut from - now set at
VideoImportService.commit, once every frame a session expects has arrived, rather than at
extraction time.
The thumbnail write came off it too. thumbnail() still only hands back bytes - storing them is
not the port's job - but those bytes go into the blob store as each frame is staged, and the hash
lands on asset.thumbnail_hash. The cache-key-not-identity rule above is what that column is
built on, and IngestService.backfill_thumbnails is how an asset that predates it, or one whose
preview would not render, gets caught up. See ingest.md.
ImageProcessor is called from two places in this process now, IngestService and
VideoImportService, and both are named above - never from a route, a CLI command or an MCP
tool directly, so decoding one more kind of bytes has stayed a change to a service, not to the
port or to what calls it.