Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,44 @@ in this mode. Callers must require `embedded-preview/1` before uploading to avoi
silently ignoring the option. No broad camera-format or physical-device compatibility is claimed;
extractor tests use synthetic TIFF/DNG containers.

#### Classifying while converting

`POST /images/process` accepts an optional `classify` property on each image option. As soon as
that entry's output has been produced, the server classifies exactly those output bytes and streams
the result as an `application/json` part, so a RAW file is uploaded once and the converted preview
never travels back and forth. Add `discard: true` to receive only the classification.

```ts
import { processImage, ProcessedFile } from "@m4k/client";

for await (const event of processImage("http://localhost:3000", Bun.file("IMG_0001.DNG"), [
{
embeddedPreview: true,
format: "jpeg",
resize: { width: 512, height: 512 },
classify: { classifierId: "clip-image-labels", classifierVersion: "1", labels: ["landscape", "receipt"] },
discard: true,
},
{ embeddedPreview: true, format: "jpeg", resize: { width: 2048, height: 2048 }, name: "web.jpg" },
])) {
if (event instanceof ProcessedFile) await Array.fromAsync(event.stream);
else if ("classification" in event) console.log(event.classification.index, event.classification.labels);
}
```

The part is `{"classification": {"index": 0, "classifierId", "classifierVersion", "sha256", "labels"}}`;
`index` is the position of the producing entry in the options array, `sha256` is the hash of the
classified output. Every classified entry needs an explicit `jpeg`, `png` or `webp` format within
the classifier limits (8 MiB / 1,048,576 pixels), which is why a resize is usually appropriate.
Several entries share one upload; each classified entry separately decodes its converted output.
Inline inference admits at most eight waiting callers; excess requests fail rather than retaining
unbounded preview buffers. Unlike the standalone
endpoint, a classification queues for the single inference slot instead of failing with 429, because
the conversion has already been done. There is no fallback: a failing classification ends the stream
with an error. Servers advertise `inline-classification/1` in `imageProfiles`; the client requires it
(and the pinned classifier) before uploading and fails if the server omits a requested classification.
`classify` is only available as JSON options (`X-Options` or `options`), not as a flat query parameter.

### Using the client

The client is available as a standalone package [@m4k/client](./packages/client). You can use it to connect to the m4k server.
Expand Down
108 changes: 106 additions & 2 deletions fixtures/classification-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,30 @@ const loadStarted = Promise.withResolvers<void>();
const pendingLoad = Promise.withResolvers<typeof infer>();
const inferenceStarted = Promise.withResolvers<void>();
const pendingInference = Promise.withResolvers<void>();
const waiterEntered = Promise.withResolvers<void>();
if (["process-wait", "queue-snapshot"].includes(scenario)) {
const { acquireInferenceSlot, releaseInferenceSlot } =
await import("../packages/core/src/images/inference-slot.ts");
let admissions = 0;
mock.module("../packages/core/src/images/inference-slot.ts", () => ({
acquireInferenceSlot: (wait: boolean, signal?: AbortSignal) => {
const admitted = acquireInferenceSlot(wait, signal);
if (++admissions === 2) waiterEntered.resolve();
return admitted;
},
releaseInferenceSlot,
}));
}
let loads = 0;
let inferences = 0;
let pixels: object | undefined;

async function infer(_image: unknown, labels: string[]) {
inferences++;
if (scenario === "inference-abort" && inferences === 1) {
if (
["inference-abort", "process-wait", "queue-snapshot"].includes(scenario) &&
inferences === 1
) {
inferenceStarted.resolve();
await pendingInference.promise;
}
Expand Down Expand Up @@ -47,7 +64,94 @@ const options = {
};
const expectedSha256 = new Bun.CryptoHasher("sha256").update(bytes).digest("hex");

if (scenario === "handler-success") {
/** Drains `processImage` (or the server handler's parts) into plain, comparable events. */
async function collect(events: AsyncIterable<unknown>) {
const out: unknown[] = [];
for await (const event of events) {
if (typeof event === "object" && event !== null && "stream" in event && "name" in event) {
const chunks: Uint8Array[] = [];
for await (const chunk of event.stream as AsyncIterable<Uint8Array>) chunks.push(chunk);
const data = Buffer.concat(chunks);
out.push({
file: event.name as string,
sha256: new Bun.CryptoHasher("sha256").update(data).digest("hex"),
});
} else out.push(event);
}
return out;
}

if (scenario === "process-inline" || scenario === "process-discard") {
const { processImage } = await import("../packages/core/src/images/image-processor.ts");
const events = await collect(
processImage(new Blob([bytes], { type: "image/jpeg" }), [
{
format: "jpeg",
resize: { width: 16 },
classify: options,
...(scenario === "process-discard" ? { discard: true } : {}),
},
{ format: "webp" },
])!,
);
console.log(JSON.stringify({ events, loads, inferences, pixels, expectedSha256 }));
} else if (scenario === "handler-process") {
const { processImageHandler } =
await import("../packages/server/src/images/process-image-handler.ts");
const response = await processImageHandler(
new Request("http://m4k/images/process", {
method: "POST",
body: bytes,
headers: {
"X-Options": JSON.stringify([
{ format: "jpeg", resize: { width: 16 }, classify: options, discard: true },
{ format: "webp", name: "keep.webp" },
]),
},
}),
);
console.log(JSON.stringify({ status: response.status, body: await response.text(), inferences }));
} else if (scenario === "process-wait") {
const { processImage } = await import("../packages/core/src/images/image-processor.ts");
const run = () =>
collect(
processImage(new Blob([bytes], { type: "image/jpeg" }), {
format: "jpeg",
classify: options,
})!,
).then(
(events) => ({ events }),
(error: Error) => ({ error: error.message }),
);
const first = run();
await inferenceStarted.promise;
const second = run();
// The real slot has synchronously admitted the second request behind active inference.
await waiterEntered.promise;
const inferencesWhileWaiting = inferences;
pendingInference.resolve();
console.log(
JSON.stringify({
first: await first,
second: await second,
inferencesWhileWaiting,
inferences,
}),
);
} else if (scenario === "queue-snapshot") {
const { classifyImage } = await import("../packages/core/src/images/classify-image.ts");
const first = classifyImage(bytes, options);
await inferenceStarted.promise;
const input = Uint8Array.from(bytes);
const requested = { ...options, labels: [...options.labels] };
const second = classifyImage(input, requested, { wait: true });
await waiterEntered.promise;
input.fill(0);
requested.labels.splice(0, requested.labels.length, "changed");
pendingInference.resolve();
await first;
console.log(JSON.stringify({ result: await second, expectedSha256, inferences }));
} else if (scenario === "handler-success") {
const { classifyImageHandler } =
await import("../packages/server/src/images/classify-image-handler.ts");
const response = await classifyImageHandler(
Expand Down
10 changes: 10 additions & 0 deletions packages/client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ All notable changes to `@m4k/client` are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- `processImage` accepts `classify`/`discard`, requires the `inline-classification/1` profile, validates every classification part and fails when one is missing.

### Fixed

- Reject redirected classification uploads and bound streamed JSON control parts to 64 KiB before parsing.

## [0.2.12]

### Added
Expand Down
19 changes: 2 additions & 17 deletions packages/client/src/classify-image.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
imageClassifier,
encodeOptions,
isValidClassificationResult,
validateClassificationOptions,
type ClassificationOptions,
type ClassificationResult,
Expand Down Expand Up @@ -46,23 +47,7 @@ export async function classifyImage(
});
if (!response.ok) throw new Error(`M4K classification failed (${response.status})`);
const result = (await readJsonResponse(response)) as ClassificationResult;
if (
result.classifierId !== options.classifierId ||
result.classifierVersion !== options.classifierVersion ||
!/^[a-f0-9]{64}$/.test(result.sha256) ||
!Array.isArray(result.labels) ||
result.labels.length !== options.labels.length ||
new Set(result.labels.map((entry) => entry.label)).size !== options.labels.length ||
result.labels.some(
(entry) =>
!options.labels.includes(entry.label) ||
!Number.isFinite(entry.score) ||
entry.score < 0 ||
entry.score > 1,
) ||
Math.abs(result.labels.reduce((sum, entry) => sum + entry.score, 0) - 1) > 1e-3
)
throw new Error("Invalid classification response");
if (!isValidClassificationResult(result, options)) throw new Error("Invalid classification response");
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", await input.arrayBuffer()));
const sha256 = [...hash].map((byte) => byte.toString(16).padStart(2, "0")).join("");
if (result.sha256 !== sha256)
Expand Down
62 changes: 51 additions & 11 deletions packages/client/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import {
ProcessedFile,
imageClassifier,
inlineClassificationProfile,
invalidInlineClassification,
isImageNoOp,
isValidClassificationResult,
encodeOptions,
type InlineClassification,
type ProcessingError,
type Progress,
type QueuePosition,
type RemoteAudioOptions,
type RemoteImageOptions,
type RemoteVideoOptions,
} from "@m4k/common";
import { readJsonResponse } from "./read-json-response.js";
import { readJsonParts, readJsonResponse } from "./read-json-response.js";
import { iterableToStream, streamParts } from "@sv2dev/multipart-stream";

/**
Expand All @@ -31,6 +36,10 @@ export async function* processAudio(

/**
* Process an image.
*
* An entry with `classify` is classified on the server right after its output was produced, so
* the converted file never travels back for classification. Its `InlineClassification` is yielded
* after the file (or instead of it, with `discard`). The stream fails if the server omits one.
* @param host - The host of the server.
* @param input - The input image. Can be a stream or a blob.
* @param opts - The options for the image processing.
Expand All @@ -44,22 +53,37 @@ export async function* processImage(
{ signal }: { signal?: AbortSignal } = {},
) {
const optsArr = Array.isArray(opts) ? opts : [opts];
if (optsArr.some((option) => option.embeddedPreview)) {
const invalid = invalidInlineClassification(optsArr);
if (invalid) throw new RangeError(invalid);
const classifying = optsArr.some((option) => option.classify);
if (classifying || optsArr.some((option) => option.embeddedPreview)) {
const response = await fetch(`${host}/info`, {
...(signal ? { signal } : {}),
redirect: "error",
});
if (!response.ok) throw new Error("M4K preview capability check failed");
if (!response.ok) throw new Error("M4K capability check failed");
const info = (await readJsonResponse(response)) as {
service?: string;
imageProfiles?: string[];
classifiers?: { id: string; version: string; revision: string }[];
};
const profiles =
info.service === "m4k" && Array.isArray(info.imageProfiles) ? info.imageProfiles : [];
const preview = optsArr.some((option) => option.embeddedPreview);
if (preview && !profiles.includes("embedded-preview/1"))
throw new RangeError("M4K does not support embedded preview extraction");
if (
info.service !== "m4k" ||
!Array.isArray(info.imageProfiles) ||
!info.imageProfiles.includes("embedded-preview/1")
classifying &&
(!profiles.includes(inlineClassificationProfile) ||
!Array.isArray(info.classifiers) ||
!info.classifiers.some(
(c) =>
c.id === imageClassifier.id &&
c.version === imageClassifier.version &&
c.revision === imageClassifier.revision,
))
Comment thread
sv2dev marked this conversation as resolved.
Resolved
)
throw new RangeError("M4K does not support embedded preview extraction");
throw new RangeError("M4K does not support classification while processing images");
}
if (input instanceof Blob && input.type) {
const inputExt = input.type.replace(/^image\//, "").toLowerCase();
Expand Down Expand Up @@ -97,19 +121,20 @@ export async function* processVideo(
yield* runFetch(`${host}/videos/process`, input, opts, { signal });
}

/** Stream conversion results, rejecting redirects for pinned profiles and bounding JSON parts. */
async function* runFetch(
url: string,
input: AsyncIterable<Uint8Array> | Blob,
opts: any,
{ signal }: { signal?: AbortSignal } = {},
) {
signal?.throwIfAborted();
const preview = (Array.isArray(opts) ? opts : [opts]).some(
(option) => option.embeddedPreview === true,
const pinned = (Array.isArray(opts) ? opts : [opts]).some(
(option) => option.embeddedPreview === true || !!option.classify,
);
const res = await fetch(
new Request(url, {
redirect: preview ? "error" : "follow",
redirect: pinned ? "error" : "follow",
method: "POST",
body: inputToStream(input),
headers: { "X-Options": encodeOptions(opts) },
Expand All @@ -119,20 +144,35 @@ async function* runFetch(
if (!res.ok) {
throw new Error(`Failed to optimize: [${res.statusText}] ${await res.text()}`);
}
const requested = (Array.isArray(opts) ? opts : [opts]) as RemoteImageOptions[];
const awaiting = new Set(requested.flatMap((o, i) => ("classify" in o && o.classify ? [i] : [])));
// Audio and video entries have no `classify`; this only guards image requests.
for await (const part of streamParts(res)) {
if (part.type === "application/json") {
const msg = (await part.json()) as Progress | QueuePosition | ProcessingError;
const msg = (await readJsonParts(part)) as
| Progress
| QueuePosition
| ProcessingError
| InlineClassification;
if ("error" in msg) {
signal?.throwIfAborted();
throw new Error(msg.error);
}
if ("classification" in msg) {
const { index } = msg.classification;
const asked = requested[index]?.classify;
const expected = awaiting.delete(index) && asked !== undefined;
if (!expected || !isValidClassificationResult(msg.classification, asked))
throw new Error("Invalid classification response");
}
yield msg;
} else if (part.type !== "text/plain") {
yield new ProcessedFile(part.filename!, part.type!, part) as ProcessedFile & {
stream: AsyncIterable<Uint8Array>;
};
}
}
if (awaiting.size > 0) throw new Error("M4K did not return every requested classification");
}

function inputToStream(input: AsyncIterable<Uint8Array> | Blob) {
Expand Down
Loading
Loading