From 60c160632dbcfe2f681acca8accfa75fd25924f8 Mon Sep 17 00:00:00 2001 From: Sven Rogge Date: Wed, 4 Nov 2026 00:28:05 +0100 Subject: [PATCH 1/2] feat: add versioned image classification and embedded previews --- README.md | 55 ++++++- bun.lock | 148 +++++++++++++++++- fixtures/embedded-preview.ts | 27 ++++ package.json | 19 +-- packages/client/src/classify-image.spec.ts | 88 +++++++++++ packages/client/src/classify-image.ts | 70 +++++++++ packages/client/src/client.spec.ts | 37 +++-- packages/client/src/client.ts | 55 ++++--- packages/client/src/index.ts | 1 + packages/client/src/read-json-response.ts | 18 +++ packages/common/src/classification.spec.ts | 32 ++++ packages/common/src/classification.ts | 54 +++++++ packages/common/src/index.ts | 13 +- packages/core/package.json | 1 + packages/core/src/images/classify-image.ts | 82 ++++++++++ .../images/extract-embedded-preview.spec.ts | 64 ++++++++ .../src/images/extract-embedded-preview.ts | 53 +++++++ packages/core/src/images/image-processor.ts | 83 ++++++++-- packages/core/src/index.ts | 3 +- packages/server/package.json | 2 +- .../src/images/classify-image-handler.spec.ts | 40 +++++ .../src/images/classify-image-handler.ts | 34 ++++ .../src/images/process-image-handler.ts | 17 +- packages/server/src/server.ts | 18 ++- packages/typebox/src/index.ts | 7 +- 25 files changed, 927 insertions(+), 94 deletions(-) create mode 100644 fixtures/embedded-preview.ts create mode 100644 packages/client/src/classify-image.spec.ts create mode 100644 packages/client/src/classify-image.ts create mode 100644 packages/client/src/read-json-response.ts create mode 100644 packages/common/src/classification.spec.ts create mode 100644 packages/common/src/classification.ts create mode 100644 packages/core/src/images/classify-image.ts create mode 100644 packages/core/src/images/extract-embedded-preview.spec.ts create mode 100644 packages/core/src/images/extract-embedded-preview.ts create mode 100644 packages/server/src/images/classify-image-handler.spec.ts create mode 100644 packages/server/src/images/classify-image-handler.ts diff --git a/README.md b/README.md index 9e0555d..c60c3e0 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,51 @@ import { serveOpts } from "@m4k/server"; Bun.serve(serveOpts); ``` +### Image classification and embedded previews + +The optional classification API runs a pinned CPU CLIP model on the M4K host. `GET /info` +advertises `clip-image-labels` version `1` and `embedded-preview/1`. Existing conversion behaviour +is unchanged unless the new options/endpoints are selected. These changes require deploying this +server version, not just upgrading a client. + +```ts +import { classifyImage } from "@m4k/client"; + +const result = await classifyImage("http://localhost:3000", Bun.file("preview.jpg"), { + classifierId: "clip-image-labels", + classifierVersion: "1", + labels: ["landscape", "receipt", "family photo"], +}); +``` + +`POST /images/classify` uploads the selected representation with JSON `X-Options`. It returns +classifier/version, the uploaded bytes' SHA-256 and every candidate's score. Labels are a complete +ordered candidate set (2–32 distinct labels, 1–80 characters each). Scores are softmax rankings +within that set, not independent probabilities; changing the candidates changes their meaning. +The fixed model is `Xenova/clip-vit-base-patch32` revision +`6b7c523703ae26e39be4b03774966f8571c7f523` (MIT), Transformers.js 3.8.1, CPU/q8, +with prompt `This is a photo of {}`. Changing this profile requires a new classifier version. +Only static JPEG/PNG/WebP previews up to 8 MiB / 1,048,576 pixels are accepted. +One inference runs per process; busy requests receive 429. Cancellation discards results without +freeing the slot before native inference finishes. There is no model, original or cloud fallback. + +The model is downloaded on first use and remains in memory. `M4K_MODEL_CACHE` selects the persistent +model-cache directory (default `${M4K_TMP_DIR:-/tmp/m4k}/models`); ensure the service user can write it. +Mount that directory to retain weights across container replacements. Model downloads do not +upload input media. The quantized model cache is approximately 149 MiB in the tested configuration; +this is not a runtime memory limit. CPU ONNX binaries are packaged by the dependency; optional CUDA +postinstall/downloads are not required. The server bundle keeps Transformers.js external so native +runtime assets resolve from installed dependencies. + +For RAW classification preparation, `processImage(..., { embeddedPreview: true, format: "jpeg" })` +uses only a TIFF IFD1 JPEG thumbnail, never full RAW development. Input is limited to 128 MiB, +each of IFD0/IFD1 to 256 entries, and the JPEG to 8 MiB / 1,048,576 pixels. Both TIFF byte orders +are supported; missing/malformed thumbnails fail without developing or passing through the source. +Source orientation is applied by normal conversion; metadata preservation options are forbidden +in this mode. Callers must require `embedded-preview/1` before uploading to avoid older servers +silently ignoring the option. No broad camera-format or physical-device compatibility is claimed; +extractor tests use synthetic TIFF/DNG containers. + ### 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. @@ -45,11 +90,11 @@ Example, using the client on Bun: ```ts import { ProcessedFile, processVideo } from "@m4k/client"; -for await (const value of processVideo( - "http://localhost:3000", - Bun.file("fixtures/video.mp4"), - { format: "mp4", videoCodec: "libx265", output: "output/video.mp4" } -)) { +for await (const value of processVideo("http://localhost:3000", Bun.file("fixtures/video.mp4"), { + format: "mp4", + videoCodec: "libx265", + output: "output/video.mp4", +})) { if (value instanceof ProcessedFile) { // handle the processed file } else { diff --git a/bun.lock b/bun.lock index 24263c5..9e301eb 100644 --- a/bun.lock +++ b/bun.lock @@ -5,6 +5,7 @@ "": { "name": "m4k-workspaces", "dependencies": { + "@huggingface/transformers": "3.8.1", "sharp": "^0.35.5", }, "devDependencies": { @@ -36,6 +37,7 @@ "name": "m4k", "version": "0.3.5", "dependencies": { + "@huggingface/transformers": "3.8.1", "@m4k/common": "workspace:^", }, "devDependencies": { @@ -95,6 +97,10 @@ "@ffmpeg-installer/win32-x64": ["@ffmpeg-installer/win32-x64@4.1.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg=="], + "@huggingface/jinja": ["@huggingface/jinja@0.5.11", "", {}, "sha512-YzEzwM5oQf4r0vs7ifWQ+yuVR1YkAHrjERQ+a8WRsStHHp4NRBg+NesjiFc+X2AFUpRvvrIeHDS1xFy9jY/IjQ=="], + + "@huggingface/transformers": ["@huggingface/transformers@3.8.1", "", { "dependencies": { "@huggingface/jinja": "^0.5.3", "onnxruntime-node": "1.21.0", "onnxruntime-web": "1.22.0-dev.20250409-89f8206ba4", "sharp": "^0.34.1" } }, "sha512-tsTk4zVjImqdqjS8/AOZg2yNLd1z9S5v+7oUPpXaasDRwEDhB+xnglK1k5cad26lL5/ZIaeREgWWy0bs9y9pPA=="], + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="], @@ -139,7 +145,7 @@ "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="], - "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], + "@img/sharp-wasm32": ["@img/sharp-wasm32@0.34.5", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="], "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="], @@ -149,6 +155,8 @@ "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.5", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="], + "@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], + "@m4k/client": ["@m4k/client@workspace:packages/client"], "@m4k/common": ["@m4k/common@workspace:packages/common"], @@ -157,6 +165,24 @@ "@m4k/typebox": ["@m4k/typebox@workspace:packages/typebox"], + "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="], + + "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], + + "@protobufjs/codegen": ["@protobufjs/codegen@2.0.5", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="], + + "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.1", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="], + + "@protobufjs/fetch": ["@protobufjs/fetch@1.1.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="], + + "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="], + + "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="], + + "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="], + + "@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="], + "@sinclair/typebox": ["@sinclair/typebox@0.34.52", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="], "@sv2dev/multipart-stream": ["@sv2dev/multipart-stream@0.2.3", "", { "peerDependencies": { "typescript": "^5.0.0 || ^6.0.0" } }, "sha512-Sy1znBqcrpy2zgH3KzlSjLlaOXPienb/p/MKCEs1yC4MbMsZgDeh2BAsNBumpUaeJzV4T7PPxbh3pvq5gaeC0Q=="], @@ -203,24 +229,144 @@ "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], + "boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="], + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + "chownr": ["chownr@3.0.0", "", {}, "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g=="], + + "define-data-property": ["define-data-property@1.1.4", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="], + + "define-properties": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="], + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + "detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="], + + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + + "flatbuffers": ["flatbuffers@25.9.23", "", {}, "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ=="], + + "global-agent": ["global-agent@3.0.0", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="], + + "globalthis": ["globalthis@1.0.4", "", { "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" } }, "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "guid-typescript": ["guid-typescript@1.0.9", "", {}, "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ=="], + + "has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="], + "husky": ["husky@9.1.7", "", { "bin": { "husky": "bin.js" } }, "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA=="], + "json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="], + + "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "m4k": ["m4k@workspace:packages/core"], + "matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="], + + "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], + + "minizlib": ["minizlib@3.1.0", "", { "dependencies": { "minipass": "^7.1.2" } }, "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw=="], + + "object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="], + + "onnxruntime-common": ["onnxruntime-common@1.21.0", "", {}, "sha512-Q632iLLrtCAVOTO65dh2+mNbQir/QNTVBG3h/QdZBpns7mZ0RYbLRBgGABPbpU9351AgYy7SJf1WaeVwMrBFPQ=="], + + "onnxruntime-node": ["onnxruntime-node@1.21.0", "", { "dependencies": { "global-agent": "^3.0.0", "onnxruntime-common": "1.21.0", "tar": "^7.0.1" }, "os": [ "linux", "win32", "darwin", ], "hasInstallScript": true }, "sha512-NeaCX6WW2L8cRCSqy3bInlo5ojjQqu2fD3D+9W5qb5irwxhEyWKXeH2vZ8W9r6VxaMPUan+4/7NDwZMtouZxEw=="], + + "onnxruntime-web": ["onnxruntime-web@1.22.0-dev.20250409-89f8206ba4", "", { "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", "onnxruntime-common": "1.22.0-dev.20250409-89f8206ba4", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, "sha512-0uS76OPgH0hWCPrFKlL8kYVV7ckM7t/36HfbgoFw6Nd0CZVVbQC4PkrR8mBX8LtNUFZO25IQBqV2Hx2ho3FlbQ=="], + + "platform": ["platform@1.3.6", "", {}, "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="], + + "protobufjs": ["protobufjs@7.6.6", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" }, "hasInstallScript": true }, "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg=="], + + "roarr": ["roarr@2.15.4", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="], + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="], + + "serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="], + "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], + "sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], + + "tar": ["tar@7.5.22", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA=="], + "tasque": ["tasque@0.1.2", "", { "peerDependencies": { "typescript": "^5.0.0" } }, "sha512-84SpyCE9C+/ZNtCKlUgZMpfSrSnBigvPDdt+pZAIIIpulAIJYb6/Twonv2yg83o/1uq8MODhJ43o0WjyY6NvwA=="], "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="], + "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "yallist": ["yallist@5.0.0", "", {}, "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw=="], + + "@huggingface/transformers/sharp": ["sharp@0.34.5", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" }, "hasInstallScript": true }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="], + + "@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], + + "@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], + + "onnxruntime-web/onnxruntime-common": ["onnxruntime-common@1.22.0-dev.20250409-89f8206ba4", "", {}, "sha512-vDJMkfCfb0b1A836rgHj+ORuZf4B4+cc2bASQtpeoJLueuFc5DuYwjIZUBrSvx/fO5IrLjLz+oTrB3pcGlhovQ=="], + + "@huggingface/transformers/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="], + + "@huggingface/transformers/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.2.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.2.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.2.4", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.2.4", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.2.4", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.2.4", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.2.4", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="], + + "@huggingface/transformers/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.2.4", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.2.4" }, "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.2.4" }, "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.2.4" }, "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg=="], + + "@huggingface/transformers/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="], + + "@huggingface/transformers/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="], + + "@huggingface/transformers/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="], + + "@huggingface/transformers/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.34.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="], + + "@huggingface/transformers/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.34.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="], + + "@huggingface/transformers/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.5", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="], } } diff --git a/fixtures/embedded-preview.ts b/fixtures/embedded-preview.ts new file mode 100644 index 0000000..5d217f9 --- /dev/null +++ b/fixtures/embedded-preview.ts @@ -0,0 +1,27 @@ +/** Synthetic little-endian TIFF/DNG metadata with an IFD1 JPEG, not a camera RAW decoder fixture. */ +export function embeddedPreviewFixture(jpeg: Uint8Array, orientation = 6): Buffer { + const offset = 8 + 2 + 2 * 12 + 4; + const dataOffset = offset + 2 + 5 * 12 + 4; + const bytes = Buffer.alloc(dataOffset + jpeg.length); + bytes.write("II"); + bytes.writeUInt16LE(42, 2); + bytes.writeUInt32LE(8, 4); + bytes.writeUInt16LE(2, 8); + const entry = (at: number, tag: number, type: number, count: number, value: number) => { + bytes.writeUInt16LE(tag, at); + bytes.writeUInt16LE(type, at + 2); + bytes.writeUInt32LE(count, at + 4); + bytes.writeUInt32LE(value, at + 8); + }; + entry(10, 0x112, 3, 1, orientation); + entry(22, 0xc612, 1, 4, 0x00000401); + bytes.writeUInt32LE(offset, 34); + bytes.writeUInt16LE(5, offset); + entry(offset + 2, 0x100, 4, 1, 32); + entry(offset + 14, 0x101, 4, 1, 16); + entry(offset + 26, 0x103, 3, 1, 6); + entry(offset + 38, 0x201, 4, 1, dataOffset); + entry(offset + 50, 0x202, 4, 1, jpeg.length); + bytes.set(jpeg, dataOffset); + return bytes; +} diff --git a/package.json b/package.json index b1278ae..f1bd2ba 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,15 @@ { "name": "m4k-workspaces", + "version": "0.0.0", "private": true, "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sv2dev/m4k.git" + }, + "workspaces": [ + "packages/*" + ], "scripts": { "dev": "bun --filter @m4k/server dev", "test": "bun --filter '*' test", @@ -11,18 +19,11 @@ "typecheck": "bun --filter '*' typecheck" }, "dependencies": { + "@huggingface/transformers": "3.8.1", "sharp": "^0.35.5" }, "devDependencies": { "husky": "^9.1.7", "typescript": "^7.0.2" - }, - "workspaces": [ - "packages/*" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/sv2dev/m4k.git" - }, - "version": "0.0.0" + } } diff --git a/packages/client/src/classify-image.spec.ts b/packages/client/src/classify-image.spec.ts new file mode 100644 index 0000000..2e9008f --- /dev/null +++ b/packages/client/src/classify-image.spec.ts @@ -0,0 +1,88 @@ +import { describe, expect, test } from "bun:test"; +import { imageClassifier } from "@m4k/common"; +import { classifyImage } from "./classify-image.js"; + +const options = { + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + labels: ["landscape", "receipt"], +}; + +describe("classifyImage client", () => { + test("does not upload a preview to an unsupported server", async () => { + let uploads = 0; + const server = Bun.serve({ + port: 0, + fetch(request) { + if (request.method === "POST") uploads++; + return Response.json({ service: "m4k", classifiers: [] }); + }, + }); + + const error = await classifyImage(server.url.origin, new Blob(["preview"]), options) + .then( + () => null, + (error: unknown) => error, + ) + .finally(() => server.stop(true)); + + expect(error).toBeInstanceOf(RangeError); + expect(uploads).toBe(0); + }); + + test("preserves Unicode candidates through HTTP headers", async () => { + const labels = ["風景", "家族📷"]; + const sha256 = new Bun.CryptoHasher("sha256").update("preview").digest("hex"); + let received: unknown; + const server = Bun.serve({ + port: 0, + fetch(request) { + if (request.method === "GET") + return Response.json({ service: "m4k", classifiers: [imageClassifier] }); + received = JSON.parse(request.headers.get("X-Options")!); + return Response.json({ + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256, + labels: labels.map((label, i) => ({ label, score: i === 0 ? 0.9 : 0.1 })), + }); + }, + }); + + const result = await classifyImage(server.url.origin, new Blob(["preview"]), { + ...options, + labels, + }).finally(() => server.stop(true)); + + expect(received).toMatchObject({ labels }); + expect(result.labels.map((entry) => entry.label)).toEqual(labels); + }); + + test("rejects labels returned for different uploaded bytes", async () => { + const server = Bun.serve({ + port: 0, + fetch(request) { + return request.method === "GET" + ? Response.json({ service: "m4k", classifiers: [imageClassifier] }) + : Response.json({ + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256: "0".repeat(64), + labels: [ + { label: "landscape", score: 0.9 }, + { label: "receipt", score: 0.1 }, + ], + }); + }, + }); + + const error = await classifyImage(server.url.origin, new Blob(["preview"]), options) + .then( + () => null, + (error: unknown) => error, + ) + .finally(() => server.stop(true)); + + expect(error).toMatchObject({ message: "Classification response belongs to different bytes" }); + }); +}); diff --git a/packages/client/src/classify-image.ts b/packages/client/src/classify-image.ts new file mode 100644 index 0000000..7b6832a --- /dev/null +++ b/packages/client/src/classify-image.ts @@ -0,0 +1,70 @@ +import { + imageClassifier, + encodeOptions, + validateClassificationOptions, + type ClassificationOptions, + type ClassificationResult, +} from "@m4k/common"; + +import { readJsonResponse } from "./read-json-response.js"; + +/** No local fallback: uploads only after the server advertises the pinned classifier. */ +export async function classifyImage( + host: string, + input: Blob, + options: ClassificationOptions, + { signal }: { signal?: AbortSignal } = {}, +): Promise { + if (!validateClassificationOptions(options)) + throw new RangeError("Unsupported classifier configuration"); + if (input.size > imageClassifier.maxBytes) + throw new RangeError("Classification preview exceeds byte limit"); + const init = signal ? { signal } : {}; + const infoResponse = await fetch(`${host}/info`, { ...init, redirect: "error" }); + if (!infoResponse.ok) throw new Error(`M4K capability check failed (${infoResponse.status})`); + const info = (await readJsonResponse(infoResponse)) as { + service?: string; + classifiers?: { id: string; version: string; revision: string }[]; + }; + if ( + info.service !== "m4k" || + !Array.isArray(info.classifiers) || + !info.classifiers.some( + (c) => + c.id === imageClassifier.id && + c.version === imageClassifier.version && + c.revision === imageClassifier.revision, + ) + ) + throw new RangeError("M4K does not advertise the requested classifier"); + const response = await fetch(`${host}/images/classify`, { + ...init, + method: "POST", + body: input, + redirect: "error", + headers: { "Content-Type": "application/octet-stream", "X-Options": encodeOptions(options) }, + }); + 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, + ) + ) + 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) + throw new Error("Classification response belongs to different bytes"); + return result; +} diff --git a/packages/client/src/client.spec.ts b/packages/client/src/client.spec.ts index 76ae061..55418fe 100644 --- a/packages/client/src/client.spec.ts +++ b/packages/client/src/client.spec.ts @@ -1,11 +1,21 @@ import { ProcessedFile } from "@m4k/common"; import serveOpts from "@m4k/server"; -import { describe, expect, it, spyOn } from "bun:test"; +import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test"; import { processAudio, processImage, processVideo } from "./client"; -spyOn(global, "fetch").mockImplementation((async (x: RequestInfo) => - serveOpts.fetch.call(serveOpts as any, new Request(x), null as any)) as any); -spyOn(console, "warn").mockImplementation(() => {}); +let restoreMocks = () => {}; +beforeEach(() => { + const fetchSpy = spyOn(global, "fetch").mockImplementation((async ( + x: RequestInfo, + init?: RequestInit, + ) => serveOpts.fetch.call(serveOpts as any, new Request(x, init), null as any)) as any); + const warnSpy = spyOn(console, "warn").mockImplementation(() => {}); + restoreMocks = () => { + fetchSpy.mockRestore(); + warnSpy.mockRestore(); + }; +}); +afterEach(() => restoreMocks()); describe("processAudio()", () => { it("should query the server to process an audio file", async () => { @@ -25,9 +35,7 @@ describe("processAudio()", () => { } } - expect(files).toEqual([ - { name: "audio.mp3", type: "audio/mpeg", size: 52288 }, - ]); + expect(files).toEqual([{ name: "audio.mp3", type: "audio/mpeg", size: 52288 }]); }); }); @@ -75,21 +83,16 @@ describe("processVideo()", () => { } } - expect(files).toEqual([ - { name: "video.mp4", type: "video/mp4", size: expect.any(Number) }, - ]); + expect(files).toEqual([{ name: "video.mp4", type: "video/mp4", size: expect.any(Number) }]); }); it("should immediately throw an error if the signal is already aborted", async () => { const video = Bun.file("../../fixtures/video.mp4"); try { await Array.fromAsync( - processVideo( - "http://localhost:3000", - video, - [{ format: "mp4", name: "video.mp4" }], - { signal: AbortSignal.abort() } - ) + processVideo("http://localhost:3000", video, [{ format: "mp4", name: "video.mp4" }], { + signal: AbortSignal.abort(), + }), ); throw new Error("should not get here"); } catch (e) { @@ -105,7 +108,7 @@ describe("processVideo()", () => { "http://localhost:3000", video, [{ ext: "mp4", name: "video.mp4", videoCodec: "copy" }], - { signal: AbortSignal.timeout(0) } + { signal: AbortSignal.timeout(0) }, )) { } throw new Error("should not get here"); diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 215375d..1b36794 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -1,6 +1,7 @@ import { ProcessedFile, isImageNoOp, + encodeOptions, type ProcessingError, type Progress, type QueuePosition, @@ -8,6 +9,7 @@ import { type RemoteImageOptions, type RemoteVideoOptions, } from "@m4k/common"; +import { readJsonResponse } from "./read-json-response.js"; import { iterableToStream, streamParts } from "@sv2dev/multipart-stream"; /** @@ -22,7 +24,7 @@ export async function* processAudio( host: string, input: AsyncIterable | Blob, opts: RemoteAudioOptions | RemoteAudioOptions[], - { signal }: { signal?: AbortSignal } = {} + { signal }: { signal?: AbortSignal } = {}, ) { yield* runFetch(`${host}/audio/process`, input, opts, { signal }); } @@ -39,10 +41,27 @@ export async function* processImage( host: string, input: AsyncIterable | Blob, opts: RemoteImageOptions | RemoteImageOptions[], - { signal }: { signal?: AbortSignal } = {} + { signal }: { signal?: AbortSignal } = {}, ) { + const optsArr = Array.isArray(opts) ? opts : [opts]; + if (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"); + const info = (await readJsonResponse(response)) as { + service?: string; + imageProfiles?: string[]; + }; + if ( + info.service !== "m4k" || + !Array.isArray(info.imageProfiles) || + !info.imageProfiles.includes("embedded-preview/1") + ) + throw new RangeError("M4K does not support embedded preview extraction"); + } if (input instanceof Blob && input.type) { - const optsArr = Array.isArray(opts) ? opts : [opts]; const inputExt = input.type.replace(/^image\//, "").toLowerCase(); if (optsArr.every((o) => isImageNoOp(o, inputExt))) { yield { progress: 0 } as Progress; @@ -51,7 +70,7 @@ export async function* processImage( yield new ProcessedFile( optsArr[i].name ?? `file${i + 1}.${ext}`, `image/${ext}`, - input.stream() as unknown as AsyncIterable + input.stream() as unknown as AsyncIterable, ) as ProcessedFile & { stream: AsyncIterable }; yield { progress: Math.round(((i + 1) / optsArr.length) * 100) } as Progress; } @@ -61,7 +80,6 @@ export async function* processImage( yield* runFetch(`${host}/images/process`, input, opts, { signal }); } - /** * Process a video. * @param host - The host of the server. @@ -74,7 +92,7 @@ export async function* processVideo( host: string, input: AsyncIterable | Blob, opts: RemoteVideoOptions | RemoteVideoOptions[], - { signal }: { signal?: AbortSignal } = {} + { signal }: { signal?: AbortSignal } = {}, ) { yield* runFetch(`${host}/videos/process`, input, opts, { signal }); } @@ -83,39 +101,34 @@ async function* runFetch( url: string, input: AsyncIterable | Blob, opts: any, - { signal }: { signal?: AbortSignal } = {} + { signal }: { signal?: AbortSignal } = {}, ) { signal?.throwIfAborted(); + const preview = (Array.isArray(opts) ? opts : [opts]).some( + (option) => option.embeddedPreview === true, + ); const res = await fetch( new Request(url, { + redirect: preview ? "error" : "follow", method: "POST", body: inputToStream(input), - headers: { "X-Options": JSON.stringify(opts) }, + headers: { "X-Options": encodeOptions(opts) }, signal, - }) + }), ); if (!res.ok) { - throw new Error( - `Failed to optimize: [${res.statusText}] ${await res.text()}` - ); + throw new Error(`Failed to optimize: [${res.statusText}] ${await res.text()}`); } for await (const part of streamParts(res)) { if (part.type === "application/json") { - const msg = (await part.json()) as - | Progress - | QueuePosition - | ProcessingError; + const msg = (await part.json()) as Progress | QueuePosition | ProcessingError; if ("error" in msg) { signal?.throwIfAborted(); throw new Error(msg.error); } yield msg; } else if (part.type !== "text/plain") { - yield new ProcessedFile( - part.filename!, - part.type!, - part - ) as ProcessedFile & { + yield new ProcessedFile(part.filename!, part.type!, part) as ProcessedFile & { stream: AsyncIterable; }; } diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 8093122..7cfa7dc 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,2 +1,3 @@ +export { classifyImage } from "./classify-image.js"; export { ProcessedFile } from "@m4k/common"; export { processAudio, processImage, processVideo } from "./client.js"; diff --git a/packages/client/src/read-json-response.ts b/packages/client/src/read-json-response.ts new file mode 100644 index 0000000..c1c83ce --- /dev/null +++ b/packages/client/src/read-json-response.ts @@ -0,0 +1,18 @@ +/** Capabilities and classifier annotations are bounded JSON, not media streams. */ +export async function readJsonResponse(response: Response): Promise { + if (!response.body) throw new Error("Empty M4K JSON response"); + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.byteLength; + if (size > 65536) throw new Error("M4K JSON response exceeds 64 KiB"); + chunks.push(chunk); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)) as unknown; +} diff --git a/packages/common/src/classification.spec.ts b/packages/common/src/classification.spec.ts new file mode 100644 index 0000000..2f40e78 --- /dev/null +++ b/packages/common/src/classification.spec.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from "bun:test"; +import { validateClassificationOptions } from "./classification.js"; + +const config = { + classifierId: "clip-image-labels", + classifierVersion: "1", + labels: ["landscape", "receipt"], +}; + +describe("validateClassificationOptions", () => { + test("accepts a bounded, versioned candidate set", () => { + const input = config; + + const valid = validateClassificationOptions(input); + + expect(valid).toBe(true); + }); + + test("rejects unsupported versions and duplicate, empty or excessive candidates", () => { + const inputs = [ + { ...config, classifierVersion: "latest" }, + { ...config, labels: ["x", "x"] }, + { ...config, labels: ["", "x"] }, + { ...config, labels: ["x"] }, + { ...config, labels: Array.from({ length: 33 }, (_, i) => String(i)) }, + ]; + + const results = inputs.map(validateClassificationOptions); + + expect(results).toEqual([false, false, false, false, false]); + }); +}); diff --git a/packages/common/src/classification.ts b/packages/common/src/classification.ts new file mode 100644 index 0000000..efe60c0 --- /dev/null +++ b/packages/common/src/classification.ts @@ -0,0 +1,54 @@ +/** Closed, immutable classifier profile. Changing weights, runtime, prompt or preprocessing needs a new version. */ +export const imageClassifier = { + id: "clip-image-labels", + version: "1", + model: "Xenova/clip-vit-base-patch32", + revision: "6b7c523703ae26e39be4b03774966f8571c7f523", + template: "This is a photo of {}", + maxBytes: 8 * 1024 * 1024, + maxPixels: 1024 * 1024, + maxLabels: 32, +} as const; + +export type ClassificationOptions = { + classifierId: string; + classifierVersion: string; + labels: readonly string[]; +}; +export type ClassificationResult = { + classifierId: string; + classifierVersion: string; + /** SHA-256 of the exact uploaded representation, not of the decoded image. */ + sha256: string; + /** Softmax across the complete candidate set, not calibrated independent probabilities. */ + labels: { label: string; score: number }[]; +}; + +/** ASCII-safe JSON for HTTP byte-string headers, preserving arbitrary Unicode label text. */ +export function encodeOptions(value: unknown): string { + return JSON.stringify(value).replace( + /[^\u0020-\u007e]/g, + (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`, + ); +} + +export function validateClassificationOptions(value: unknown): value is ClassificationOptions { + if (!value || typeof value !== "object") return false; + const o = value as ClassificationOptions; + return ( + o.classifierId === imageClassifier.id && + o.classifierVersion === imageClassifier.version && + Array.isArray(o.labels) && + o.labels.length >= 2 && + o.labels.length <= imageClassifier.maxLabels && + new Set(o.labels).size === o.labels.length && + o.labels.every( + (label: unknown) => + typeof label === "string" && + label.length > 0 && + label.length <= 80 && + label === label.trim() && + !/[\u0000-\u001f\u007f{}]/.test(label), + ) + ); +} diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts index 1832641..39293bf 100644 --- a/packages/common/src/index.ts +++ b/packages/common/src/index.ts @@ -1,3 +1,11 @@ +export { + imageClassifier, + encodeOptions, + validateClassificationOptions, + type ClassificationOptions, + type ClassificationResult, +} from "./classification.js"; + export type Progress = { progress: number; }; @@ -26,6 +34,8 @@ type ImageFormat = | "jp2"; export type ImageOptions = { + /** Extract a bounded embedded JPEG preview from a TIFF-based camera file; never demosaic RAW. */ + embeddedPreview?: boolean; /** The rotation of the image. If not provided, the image will be auto-rotated, according to the EXIF data. To disable auto-rotation, set to `0`. */ rotate?: number; /** Resizing options. */ @@ -151,7 +161,7 @@ export class ProcessedFile { constructor( readonly name: string, readonly type: string, - readonly stream?: AsyncIterable + readonly stream?: AsyncIterable, ) {} } @@ -161,6 +171,7 @@ export function isImageNoOp(opt: ImageOptions, inputExt: string): boolean { const outFmt = opt.format ?? opt.ext ?? "avif"; if (outFmt !== inputExt) return false; return ( + !opt.embeddedPreview && !opt.resize && !opt.crop && opt.rotate == null && diff --git a/packages/core/package.json b/packages/core/package.json index 9d2014b..ed87d69 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -33,6 +33,7 @@ "test": "bun test" }, "dependencies": { + "@huggingface/transformers": "3.8.1", "@m4k/common": "workspace:^" }, "devDependencies": { diff --git a/packages/core/src/images/classify-image.ts b/packages/core/src/images/classify-image.ts new file mode 100644 index 0000000..b8fe8c7 --- /dev/null +++ b/packages/core/src/images/classify-image.ts @@ -0,0 +1,82 @@ +import { createHash } from "node:crypto"; +import sharp from "sharp"; +import { + imageClassifier, + validateClassificationOptions, + type ClassificationOptions, + type ClassificationResult, +} from "@m4k/common"; + +let classifier: Promise>> | undefined; +let busy = false; +async function loadClassifier() { + const { env, pipeline } = await import("@huggingface/transformers"); + env.cacheDir = process.env.M4K_MODEL_CACHE ?? `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/models`; + return pipeline("zero-shot-image-classification", imageClassifier.model, { + revision: imageClassifier.revision, + dtype: "q8", + device: "cpu", + }); +} + +async function decodePreview(input: Uint8Array) { + try { + const image = sharp(input, { limitInputPixels: imageClassifier.maxPixels, animated: false }); + const metadata = await image.metadata(); + if (!["jpeg", "png", "webp"].includes(metadata.format ?? "") || (metadata.pages ?? 1) !== 1) + throw new RangeError("Classification requires a single JPEG, PNG or WebP preview"); + return await image + .rotate() + .removeAlpha() + .toColourspace("srgb") + .raw() + .toBuffer({ resolveWithObject: true }); + } catch (error) { + throw error instanceof RangeError ? error : new RangeError("Invalid classification preview"); + } +} + +/** Bounded preview-only inference. No arbitrary models, remote image URLs or file outputs. */ +export async function classifyImage( + input: Uint8Array, + options: ClassificationOptions, + { signal }: { signal?: AbortSignal } = {}, +): Promise { + if (!validateClassificationOptions(options)) + throw new RangeError("Unsupported classifier configuration"); + if (input.byteLength > imageClassifier.maxBytes) + throw new RangeError("Classification preview exceeds byte limit"); + signal?.throwIfAborted(); + if (busy) throw new Error("Classifier is busy"); + busy = true; + try { + const bytes = Uint8Array.from(input); + const candidates = [...options.labels]; + const { data, info } = await decodePreview(bytes); + signal?.throwIfAborted(); + const { RawImage } = await import("@huggingface/transformers"); + classifier ??= loadClassifier().catch((error) => { + classifier = undefined; + throw error; + }); + const run = await classifier; + signal?.throwIfAborted(); + const labels = await run( + new RawImage(new Uint8ClampedArray(data), info.width, info.height, 3), + candidates, + { + hypothesis_template: imageClassifier.template, + }, + ); + // Native inference cannot be preempted; retain the slot until it stops and discard cancelled results. + signal?.throwIfAborted(); + return { + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256: createHash("sha256").update(bytes).digest("hex"), + labels: labels as ClassificationResult["labels"], + }; + } finally { + busy = false; + } +} diff --git a/packages/core/src/images/extract-embedded-preview.spec.ts b/packages/core/src/images/extract-embedded-preview.spec.ts new file mode 100644 index 0000000..d8ddd2e --- /dev/null +++ b/packages/core/src/images/extract-embedded-preview.spec.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from "bun:test"; +import sharp from "sharp"; +import { ProcessedFile } from "@m4k/common"; +import { embeddedPreviewFixture } from "../../../../fixtures/embedded-preview.js"; +import { extractEmbeddedPreview } from "./extract-embedded-preview.js"; +import { processImage } from "./image-processor.js"; + +const jpeg = () => + sharp({ create: { width: 32, height: 16, channels: 3, background: "red" } }) + .jpeg() + .toBuffer(); + +describe("extractEmbeddedPreview", () => { + test("extracts an independent JPEG with the source orientation", async () => { + const input = embeddedPreviewFixture(await jpeg()); + const before = Buffer.from(input); + + const preview = await extractEmbeddedPreview(input); + const metadata = await sharp(preview).metadata(); + + expect(metadata.format).toBe("jpeg"); + expect(metadata.orientation).toBe(6); + expect(input.equals(before)).toBe(true); + }); + + test("transforms the embedded preview with orientation applied and metadata removed", async () => { + const input = embeddedPreviewFixture(await jpeg()); + let output: Buffer | undefined; + + for await (const value of processImage( + (async function* () { + yield input; + })(), + { embeddedPreview: true, format: "jpeg", resize: { width: 8, height: 8 } }, + )!) { + if (value instanceof ProcessedFile) { + const chunks: Uint8Array[] = []; + for await (const chunk of value.stream!) chunks.push(chunk); + output = Buffer.concat(chunks); + } + } + const metadata = await sharp(output!).metadata(); + + expect(metadata.width).toBe(4); + expect(metadata.height).toBe(8); + expect(metadata.orientation).toBeUndefined(); + }); + + test("fails visibly when no embedded JPEG exists instead of developing or passing through the source", async () => { + const input = embeddedPreviewFixture(new Uint8Array()); + + const result = extractEmbeddedPreview(input); + + expect(result).rejects.toThrow("No supported embedded JPEG preview"); + }); + + test("rejects a regular image selected as a RAW preview input", async () => { + const input = await jpeg(); + + const result = extractEmbeddedPreview(input); + + expect(result).rejects.toThrow("TIFF-based"); + }); +}); diff --git a/packages/core/src/images/extract-embedded-preview.ts b/packages/core/src/images/extract-embedded-preview.ts new file mode 100644 index 0000000..80e7ca9 --- /dev/null +++ b/packages/core/src/images/extract-embedded-preview.ts @@ -0,0 +1,53 @@ +import sharp from "sharp"; + +/** Bounded TIFF IFD0 -> IFD1 JPEG thumbnail extraction; no arbitrary TIFF traversal or RAW development. */ +export async function extractEmbeddedPreview(input: Buffer): Promise { + if (input.byteLength > 128 * 1024 * 1024) + throw new RangeError("RAW preview input exceeds 128 MiB"); + const little = input.subarray(0, 4).equals(Buffer.from([73, 73, 42, 0])); + if (input.length < 8 || (!little && !input.subarray(0, 4).equals(Buffer.from([77, 77, 0, 42])))) + throw new RangeError("Embedded preview requires a TIFF-based camera file"); + const view = new DataView(input.buffer, input.byteOffset, input.byteLength); + const ifd = (offset: number) => { + if (offset < 8 || offset > input.length - 2) + throw new RangeError("Invalid embedded preview directory"); + const count = view.getUint16(offset, little); + if (count > 256 || offset + 2 + count * 12 + 4 > input.length) + throw new RangeError("Invalid embedded preview directory"); + const tags = new Map(); + for (let i = 0; i < count; i++) { + const at = offset + 2 + i * 12; + const type = view.getUint16(at + 2, little); + if (view.getUint32(at + 4, little) !== 1 || (type !== 3 && type !== 4)) continue; + tags.set( + view.getUint16(at, little), + type === 3 ? view.getUint16(at + 8, little) : view.getUint32(at + 8, little), + ); + } + return { tags, next: view.getUint32(offset + 2 + count * 12, little) }; + }; + const firstOffset = view.getUint32(4, little); + const first = ifd(firstOffset); + if (!first.next || first.next === firstOffset) + throw new RangeError("No supported embedded JPEG preview"); + const { tags } = ifd(first.next); + const offset = tags.get(0x201) ?? 0; + const length = tags.get(0x202) ?? 0; + if ( + (tags.has(0x103) && tags.get(0x103) !== 6) || + offset < 8 || + length < 2 || + length > 8 * 1024 * 1024 || + offset > input.length - length + ) + throw new RangeError("No supported embedded JPEG preview"); + const jpeg = input.subarray(offset, offset + length); + if (jpeg[0] !== 0xff || jpeg[1] !== 0xd8) + throw new RangeError("No supported embedded JPEG preview"); + const orientation = first.tags.get(0x112) ?? 1; + // Attach only orientation to the private intermediate; the normal transform applies it. + return sharp(jpeg, { limitInputPixels: 1024 * 1024 }) + .withMetadata({ orientation: orientation >= 1 && orientation <= 8 ? orientation : 1 }) + .jpeg() + .toBuffer(); +} diff --git a/packages/core/src/images/image-processor.ts b/packages/core/src/images/image-processor.ts index 895231f..c613f23 100644 --- a/packages/core/src/images/image-processor.ts +++ b/packages/core/src/images/image-processor.ts @@ -7,6 +7,8 @@ import { createQueue } from "tasque"; import { ffmpeg, createTmp, randomId } from "../util/ffmpeg-processor.js"; import { exhaustAsyncIterableToWritable } from "../util/streams.js"; +import { extractEmbeddedPreview } from "./extract-embedded-preview.js"; + export { ffmpeg }; export type Format = Required["format"]; @@ -24,11 +26,21 @@ const imageTmpDir = `${process.env.M4K_TMP_DIR ?? "/tmp/m4k"}/image`; export function processImage( input: string | AsyncIterable | Blob, opts: ImageOptions | ImageOptions[], - { signal }: { signal?: AbortSignal } = {} + { signal }: { signal?: AbortSignal } = {}, ) { const iterable = imageQueue.iterate(async function* () { const optsArr = Array.isArray(opts) ? opts : [opts]; - const resolvedInput = await resolveInput(input); + const preview = optsArr.some((o) => o.embeddedPreview); + if ( + preview && + optsArr.some((o) => !o.embeddedPreview || o.keepMetadata || o.keepExif || o.keepIcc) + ) + throw new RangeError( + "Embedded previews require metadata stripping and cannot mix input modes", + ); + const resolvedInput = preview + ? await extractEmbeddedPreview(await boundedInput(input)) + : await resolveInput(input); const inputExt = detectExt(resolvedInput); if (inputExt != null && optsArr.every((o) => isImageNoOp(o, inputExt))) { @@ -75,7 +87,7 @@ export const imageQueue = createQueue({ async function runSharp( input: string | Buffer | Blob, - opts: ImageOptions[] + opts: ImageOptions[], ): Promise { const sharpInstance = sharp(); void exhaustAsyncIterableToWritable(toSharpInput(input), sharpInstance); @@ -94,7 +106,7 @@ async function runSharp( resize, rotate, }, - idx + idx, ) => { let s = sharpInstance.clone(); s = s.rotate(rotate); @@ -117,8 +129,8 @@ async function runSharp( s = s.toFormat(ext, { quality }); const buf = await s.toBuffer(); return new ProcessedFile(`file${idx + 1}.${ext}`, `image/${ext}`, toAsyncIterable(buf)); - } - ) + }, + ), ); } @@ -130,14 +142,24 @@ async function ffmpegDecodeToPng(input: string | Buffer | Blob): Promise const inputPath = typeof input === "string" ? input - : await createTmp(imageTmpDir, id, input instanceof Buffer ? toAsyncIterable(input) : (input as Blob)); + : await createTmp( + imageTmpDir, + id, + input instanceof Buffer ? toAsyncIterable(input) : (input as Blob), + ); try { await new Promise((resolve, reject) => { - const child = spawn(ffmpeg, ["-y", "-i", inputPath, "-update", "1", "-frames:v", "1", outPath], { - stdio: ["pipe", "pipe", "pipe"], - }); + const child = spawn( + ffmpeg, + ["-y", "-i", inputPath, "-update", "1", "-frames:v", "1", outPath], + { + stdio: ["pipe", "pipe", "pipe"], + }, + ); let errStr = ""; - child.stderr!.on("data", (chunk: Buffer) => { errStr += chunk.toString(); }); + child.stderr!.on("data", (chunk: Buffer) => { + errStr += chunk.toString(); + }); child.on("close", (code) => { if (code !== 0) reject(new Error(`ffmpeg exited with code ${code}: ${errStr}`)); else resolve(); @@ -150,8 +172,25 @@ async function ffmpegDecodeToPng(input: string | Buffer | Blob): Promise } } +async function boundedInput(input: string | AsyncIterable | Blob): Promise { + const iterable = + typeof input === "string" + ? createReadStream(input) + : "stream" in input + ? input.stream() + : input; + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of iterable) { + size += chunk.length; + if (size > 128 * 1024 * 1024) throw new RangeError("RAW preview input exceeds 128 MiB"); + chunks.push(chunk); + } + return Buffer.concat(chunks); +} + async function resolveInput( - input: string | AsyncIterable | Blob + input: string | AsyncIterable | Blob, ): Promise { if (typeof input === "string" || "stream" in input) return input as string | Blob; const chunks: Uint8Array[] = []; @@ -190,17 +229,27 @@ function detectExt(input: string | Buffer | Blob): string | null { } if (input instanceof Buffer && input.byteLength >= 12) { if (input[0] === 0xff && input[1] === 0xd8) return "jpeg"; - if (input[0] === 0x89 && input[1] === 0x50 && input[2] === 0x4e && input[3] === 0x47) return "png"; + if (input[0] === 0x89 && input[1] === 0x50 && input[2] === 0x4e && input[3] === 0x47) + return "png"; if (input[0] === 0x47 && input[1] === 0x49 && input[2] === 0x46) return "gif"; - if (input[0] === 0x52 && input[1] === 0x49 && input[2] === 0x46 && input[3] === 0x46 && - input[8] === 0x57 && input[9] === 0x45 && input[10] === 0x42 && input[11] === 0x50) return "webp"; + if ( + input[0] === 0x52 && + input[1] === 0x49 && + input[2] === 0x46 && + input[3] === 0x46 && + input[8] === 0x57 && + input[9] === 0x45 && + input[10] === 0x42 && + input[11] === 0x50 + ) + return "webp"; // AVIF/HEIF: ftyp box at offset 4, brand at offset 8 if (input[4] === 0x66 && input[5] === 0x74 && input[6] === 0x79 && input[7] === 0x70) { const brand = input.slice(8, 12).toString("ascii"); if (brand.startsWith("avif") || brand.startsWith("avis")) return "avif"; - if (brand.startsWith("heic") || brand.startsWith("heix") || brand.startsWith("mif1")) return "heif"; + if (brand.startsWith("heic") || brand.startsWith("heix") || brand.startsWith("mif1")) + return "heif"; } } return null; } - diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 40f8798..b70fce1 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,9 +5,10 @@ export { type ProcessingError, type Progress, type QueuePosition, - type VideoOptions + type VideoOptions, } from "@m4k/common"; export { audioQueue, processAudio } from "./audio/audio-processor.js"; +export { classifyImage } from "./images/classify-image.js"; export { imageQueue, processImage } from "./images/image-processor.js"; export { getExtension } from "./util/ffmpeg-processor.js"; export { mimeTypes } from "./util/mime.js"; diff --git a/packages/server/package.json b/packages/server/package.json index 0e4d89b..1ee5216 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -28,7 +28,7 @@ "dev": "bun --watch src/index.ts", "prepublishOnly": "bun run build", "build": "tsc -b", - "build:docker": "bun build ./src/index.ts --outfile dist/server/app.js --target bun --external sharp", + "build:docker": "bun build ./src/index.ts --outfile dist/server/app.js --target bun --external sharp --external @huggingface/transformers", "typecheck": "tsc --noEmit", "test": "bun test" }, diff --git a/packages/server/src/images/classify-image-handler.spec.ts b/packages/server/src/images/classify-image-handler.spec.ts new file mode 100644 index 0000000..c513b28 --- /dev/null +++ b/packages/server/src/images/classify-image-handler.spec.ts @@ -0,0 +1,40 @@ +import { describe, expect, test } from "bun:test"; +import { classifyImageHandler } from "./classify-image-handler.js"; + +const config = { + classifierId: "clip-image-labels", + classifierVersion: "1", + labels: ["landscape", "receipt"], +}; +const request = (options: unknown, body: Uint8Array = new Uint8Array([1])) => + new Request("http://m4k/images/classify", { + method: "POST", + headers: { "X-Options": JSON.stringify(options) }, + body, + }); + +describe("classifyImageHandler", () => { + test("refuses an unsupported classifier before inference", async () => { + const input = request({ ...config, classifierId: "arbitrary-model" }); + + const response = await classifyImageHandler(input); + + expect(response.status).toBe(422); + }); + + test("bounds streamed previews even without a content length", async () => { + const input = request(config, new Uint8Array(8 * 1024 * 1024 + 1)); + + const response = await classifyImageHandler(input); + + expect(response.status).toBe(413); + }); + + test("never falls back to classifying an invalid image", async () => { + const input = request(config); + + const response = await classifyImageHandler(input); + + expect(response.status).toBe(422); + }); +}); diff --git a/packages/server/src/images/classify-image-handler.ts b/packages/server/src/images/classify-image-handler.ts new file mode 100644 index 0000000..1d97e34 --- /dev/null +++ b/packages/server/src/images/classify-image-handler.ts @@ -0,0 +1,34 @@ +import { imageClassifier, validateClassificationOptions } from "@m4k/common"; +import { classifyImage } from "m4k"; + +/** Admission validates options before reading bytes; body is bounded even without Content-Length. */ +export async function classifyImageHandler(request: Request): Promise { + let options: unknown; + try { + options = JSON.parse(request.headers.get("X-Options") ?? "null"); + } catch { + return new Response("Invalid classification options", { status: 400 }); + } + if (!validateClassificationOptions(options)) + return new Response("Unsupported classifier configuration", { status: 422 }); + if (!request.body) return new Response("No preview provided", { status: 400 }); + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of request.body) { + size += chunk.byteLength; + if (size > imageClassifier.maxBytes) + return new Response("Preview exceeds byte limit", { status: 413 }); + chunks.push(chunk); + } + try { + return Response.json( + await classifyImage(Buffer.concat(chunks), options, { signal: request.signal }), + ); + } catch (error) { + if (request.signal.aborted) return new Response("Cancelled", { status: 499 }); + if (error instanceof RangeError) return new Response(error.message, { status: 422 }); + if (error instanceof Error && error.message === "Classifier is busy") + return new Response(error.message, { status: 429 }); + return new Response("Classification failed", { status: 503 }); + } +} diff --git a/packages/server/src/images/process-image-handler.ts b/packages/server/src/images/process-image-handler.ts index f150316..f8cfbda 100644 --- a/packages/server/src/images/process-image-handler.ts +++ b/packages/server/src/images/process-image-handler.ts @@ -49,11 +49,12 @@ export async function processImageHandler(request: Request) { yield value; } } - })() + })(), ); } const querySchema = T.Object({ + embeddedPreview: T.Optional(T.Boolean()), rotate: T.Optional(numberQueryParamSchema), width: T.Optional(numberQueryParamSchema), height: T.Optional(numberQueryParamSchema), @@ -75,16 +76,10 @@ const querySchema = T.Object({ const compiledQuerySchema = TypeCompiler.Compile(querySchema); function queryToOptions(params: unknown): RemoteImageOptions { - const { - width, - height, - fit, - cropLeft, - cropTop, - cropWidth, - cropHeight, - ...query - } = parse(compiledQuerySchema, params); + const { width, height, fit, cropLeft, cropTop, cropWidth, cropHeight, ...query } = parse( + compiledQuerySchema, + params, + ); return { ...query, ...((width || height) && { diff --git a/packages/server/src/server.ts b/packages/server/src/server.ts index 42db8f1..bb3ab30 100644 --- a/packages/server/src/server.ts +++ b/packages/server/src/server.ts @@ -1,5 +1,7 @@ import type { ServeOptions, Server } from "bun"; import { version } from "../package.json"; +import { imageClassifier } from "@m4k/common"; +import { classifyImageHandler } from "./images/classify-image-handler.js"; import { processAudioHandler } from "./audio/process-audio-handler.js"; import { processImageHandler } from "./images/process-image-handler.js"; import { processVideoHandler } from "./videos/process-video-handler.js"; @@ -25,21 +27,23 @@ export const serveOpts: ServeOptions = { const routes = { GET: { - "/info": () => Response.json({ version, service: "m4k" }), + "/info": () => + Response.json({ + version, + service: "m4k", + classifiers: [imageClassifier], + imageProfiles: ["embedded-preview/1"], + }), }, POST: { "/audio/process": processAudioHandler, "/images/process": processImageHandler, + "/images/classify": classifyImageHandler, "/videos/process": processVideoHandler, }, } as Partial< Record< string, - Partial< - Record< - string, - (req: Request, server: Server) => Promise | Response - > - > + Partial) => Promise | Response>> > >; diff --git a/packages/typebox/src/index.ts b/packages/typebox/src/index.ts index 33a8cda..d93337a 100644 --- a/packages/typebox/src/index.ts +++ b/packages/typebox/src/index.ts @@ -30,6 +30,7 @@ const imageFormat = T.Union([ T.Literal("jp2"), ]); export const imageOptionsSchema = T.Object({ + embeddedPreview: T.Optional(T.Boolean()), rotate: T.Optional(T.Number()), resize: T.Optional( T.Object({ @@ -42,9 +43,9 @@ export const imageOptionsSchema = T.Object({ T.Literal("fill"), T.Literal("inside"), T.Literal("outside"), - ]) + ]), ), - }) + }), ), ext: T.Optional(imageFormat), format: T.Optional(imageFormat), @@ -59,7 +60,7 @@ export const imageOptionsSchema = T.Object({ top: T.Optional(T.Number()), width: T.Number(), height: T.Number(), - }) + }), ), args: T.Optional(T.Array(T.String())), name: T.Optional(T.String()), From e6a0dece8c30a75b8489b9f2c3925d626186cb0a Mon Sep 17 00:00:00 2001 From: Sven Rogge Date: Wed, 4 Nov 2026 07:43:34 +0100 Subject: [PATCH 2/2] fix: address classification lifecycle and API review feedback --- README.md | 6 +- fixtures/classification-lifecycle.ts | 137 ++++++++++++++++++ fixtures/run-classification-scenario.ts | 27 ++++ packages/client/src/classify-image.spec.ts | 50 +++++++ packages/client/src/classify-image.ts | 3 +- packages/common/src/classification.spec.ts | 18 +++ .../core/src/images/classify-image.spec.ts | 41 ++++++ packages/core/src/images/classify-image.ts | 4 +- packages/core/src/util/wait-for-load.ts | 23 +++ .../src/images/classify-image-handler.spec.ts | 19 +++ .../src/images/process-image-handler.spec.ts | 83 ++++++++--- .../src/images/process-image-handler.ts | 4 +- packages/server/src/util/typebox.ts | 14 +- 13 files changed, 399 insertions(+), 30 deletions(-) create mode 100644 fixtures/classification-lifecycle.ts create mode 100644 fixtures/run-classification-scenario.ts create mode 100644 packages/core/src/images/classify-image.spec.ts create mode 100644 packages/core/src/util/wait-for-load.ts diff --git a/README.md b/README.md index c60c3e0..89cd909 100644 --- a/README.md +++ b/README.md @@ -61,8 +61,10 @@ The fixed model is `Xenova/clip-vit-base-patch32` revision `6b7c523703ae26e39be4b03774966f8571c7f523` (MIT), Transformers.js 3.8.1, CPU/q8, with prompt `This is a photo of {}`. Changing this profile requires a new classifier version. Only static JPEG/PNG/WebP previews up to 8 MiB / 1,048,576 pixels are accepted. -One inference runs per process; busy requests receive 429. Cancellation discards results without -freeing the slot before native inference finishes. There is no model, original or cloud fallback. +One inference runs per process; busy requests receive 429. Cancellation while waiting for model +loading releases the request slot immediately; the shared load continues and is reused by the next +request. Once native inference starts, cancellation discards results without freeing its slot before +inference finishes. There is no model, original or cloud fallback. The model is downloaded on first use and remains in memory. `M4K_MODEL_CACHE` selects the persistent model-cache directory (default `${M4K_TMP_DIR:-/tmp/m4k}/models`); ensure the service user can write it. diff --git a/fixtures/classification-lifecycle.ts b/fixtures/classification-lifecycle.ts new file mode 100644 index 0000000..60e3c27 --- /dev/null +++ b/fixtures/classification-lifecycle.ts @@ -0,0 +1,137 @@ +// Child-process fixture: mock only the model boundary, keeping real Sharp decoding and handlers. +import { mock } from "bun:test"; +import sharp from "sharp"; + +const scenario = Bun.argv[2]; +const loadStarted = Promise.withResolvers(); +const pendingLoad = Promise.withResolvers(); +const inferenceStarted = Promise.withResolvers(); +const pendingInference = Promise.withResolvers(); +let loads = 0; +let inferences = 0; +let pixels: object | undefined; + +async function infer(_image: unknown, labels: string[]) { + inferences++; + if (scenario === "inference-abort" && inferences === 1) { + inferenceStarted.resolve(); + await pendingInference.promise; + } + return labels.map((label) => ({ label, score: 1 / labels.length })); +} + +mock.module("@huggingface/transformers", () => ({ + env: {}, + pipeline: async () => { + loads++; + if (scenario.startsWith("load-") && loads === 1) { + loadStarted.resolve(); + return pendingLoad.promise; + } + return infer; + }, + RawImage: class { + constructor(data: Uint8ClampedArray, width: number, height: number, channels: number) { + pixels = { width, height, channels, bytes: data.length }; + } + }, +})); + +const bytes = await sharp({ create: { width: 32, height: 16, channels: 3, background: "red" } }) + .jpeg() + .toBuffer(); +const options = { + classifierId: "clip-image-labels", + classifierVersion: "1", + labels: ["landscape", "receipt"], +}; +const expectedSha256 = new Bun.CryptoHasher("sha256").update(bytes).digest("hex"); + +if (scenario === "handler-success") { + const { classifyImageHandler } = + await import("../packages/server/src/images/classify-image-handler.ts"); + const response = await classifyImageHandler( + new Request("http://m4k/images/classify", { + method: "POST", + body: bytes, + headers: { "X-Options": JSON.stringify(options) }, + }), + ); + console.log( + JSON.stringify({ + status: response.status, + body: await response.json(), + expectedSha256, + pixels, + loads, + inferences, + }), + ); +} else { + const { classifyImage } = await import("../packages/core/src/images/classify-image.ts"); + const ctrl = new AbortController(); + let settled = false; + const first = classifyImage(bytes, options, { signal: ctrl.signal }).then( + () => { + settled = true; + return "completed"; + }, + (error: Error) => { + settled = true; + return error.name; + }, + ); + if (scenario.startsWith("load-")) { + await loadStarted.promise; + ctrl.abort(); + const aborted = await first; + if (scenario === "load-abort") { + const retry = classifyImage(bytes, options); + const competing = await classifyImage(bytes, options).then( + () => "unexpected", + (error: Error) => error.message, + ); + pendingLoad.resolve(infer); + console.log( + JSON.stringify({ + aborted, + competing, + retry: await retry, + loads, + inferences, + expectedSha256, + pixels, + }), + ); + } else { + pendingLoad.reject(new Error("background load failed")); + const retry = await classifyImage(bytes, options); + console.log(JSON.stringify({ aborted, retry, loads, inferences, expectedSha256, pixels })); + } + } else if (scenario === "inference-abort") { + await inferenceStarted.promise; + ctrl.abort(); + const competing = await classifyImage(bytes, options).then( + () => "unexpected", + (error: Error) => error.message, + ); + const settledBeforeInferenceEnded = settled; + pendingInference.resolve(); + const aborted = await first; + const retry = await classifyImage(bytes, options); + console.log( + JSON.stringify({ + aborted, + competing, + settledBeforeInferenceEnded, + retry, + loads, + inferences, + expectedSha256, + pixels, + }), + ); + } else { + throw new Error(`Unknown scenario: ${scenario}`); + } +} diff --git a/fixtures/run-classification-scenario.ts b/fixtures/run-classification-scenario.ts new file mode 100644 index 0000000..6158afb --- /dev/null +++ b/fixtures/run-classification-scenario.ts @@ -0,0 +1,27 @@ +/** Isolate model mocks from the other package suites and from real-container smoke tests. */ +export async function runClassificationScenario(scenario: string) { + const child = Bun.spawn( + [ + process.execPath, + new URL("./classification-lifecycle.ts", import.meta.url).pathname, + scenario, + ], + { + stdout: "pipe", + stderr: "pipe", + }, + ); + const timeout = setTimeout(() => child.kill(), 4_000); + try { + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (code !== 0) throw new Error(`Classification fixture failed (${code}): ${stderr}`); + return JSON.parse(stdout); + } finally { + clearTimeout(timeout); + if (child.exitCode === null) child.kill(); + } +} diff --git a/packages/client/src/classify-image.spec.ts b/packages/client/src/classify-image.spec.ts index 2e9008f..7f4e6ea 100644 --- a/packages/client/src/classify-image.spec.ts +++ b/packages/client/src/classify-image.spec.ts @@ -58,6 +58,56 @@ describe("classifyImage client", () => { expect(result.labels.map((entry) => entry.label)).toEqual(labels); }); + test("rejects candidate scores that do not sum to one", async () => { + const sha256 = new Bun.CryptoHasher("sha256").update("preview").digest("hex"); + const server = Bun.serve({ + port: 0, + fetch(request) { + return request.method === "GET" + ? Response.json({ service: "m4k", classifiers: [imageClassifier] }) + : Response.json({ + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256, + labels: options.labels.map((label) => ({ label, score: 0.9 })), + }); + }, + }); + + const error = await classifyImage(server.url.origin, new Blob(["preview"]), options) + .then( + () => null, + (error: unknown) => error, + ) + .finally(() => server.stop(true)); + + expect(error).toMatchObject({ message: "Invalid classification response" }); + }); + + test("accepts normalization differences within floating-point tolerance", async () => { + const sha256 = new Bun.CryptoHasher("sha256").update("preview").digest("hex"); + const server = Bun.serve({ + port: 0, + fetch(request) { + return request.method === "GET" + ? Response.json({ service: "m4k", classifiers: [imageClassifier] }) + : Response.json({ + classifierId: imageClassifier.id, + classifierVersion: imageClassifier.version, + sha256, + labels: options.labels.map((label) => ({ label, score: 0.50000003 })), + }); + }, + }); + + const result = await classifyImage(server.url.origin, new Blob(["preview"]), options).finally( + () => server.stop(true), + ); + + expect(result.labels).toHaveLength(2); + expect(result.sha256).toBe(sha256); + }); + test("rejects labels returned for different uploaded bytes", async () => { const server = Bun.serve({ port: 0, diff --git a/packages/client/src/classify-image.ts b/packages/client/src/classify-image.ts index 7b6832a..3663117 100644 --- a/packages/client/src/classify-image.ts +++ b/packages/client/src/classify-image.ts @@ -59,7 +59,8 @@ export async function classifyImage( !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"); const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", await input.arrayBuffer())); diff --git a/packages/common/src/classification.spec.ts b/packages/common/src/classification.spec.ts index 2f40e78..a19f335 100644 --- a/packages/common/src/classification.spec.ts +++ b/packages/common/src/classification.spec.ts @@ -16,6 +16,24 @@ describe("validateClassificationOptions", () => { expect(valid).toBe(true); }); + test("accepts the eighty-character label boundary", () => { + const input = { ...config, labels: ["x".repeat(80), "receipt"] }; + + const valid = validateClassificationOptions(input); + + expect(valid).toBe(true); + }); + + test("rejects whitespace, braces, controls and overlong labels", () => { + const invalid = [" leading", "trailing ", "{label}", "line\nbreak", "x".repeat(81)]; + + const valid = invalid.map((label) => + validateClassificationOptions({ ...config, labels: [label, "receipt"] }), + ); + + expect(valid).toEqual([false, false, false, false, false]); + }); + test("rejects unsupported versions and duplicate, empty or excessive candidates", () => { const inputs = [ { ...config, classifierVersion: "latest" }, diff --git a/packages/core/src/images/classify-image.spec.ts b/packages/core/src/images/classify-image.spec.ts new file mode 100644 index 0000000..50eb2d1 --- /dev/null +++ b/packages/core/src/images/classify-image.spec.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import { runClassificationScenario } from "../../../../fixtures/run-classification-scenario.js"; + +describe("classifyImage lifecycle", () => { + test("releases an aborted model-load waiter and reuses the single pending load", async () => { + const scenario = "load-abort"; + + const result = await runClassificationScenario(scenario); + + expect(result.aborted).toBe("AbortError"); + expect(result.competing).toBe("Classifier is busy"); + expect(result.loads).toBe(1); + expect(result.inferences).toBe(1); + expect(result.retry.sha256).toBe(result.expectedSha256); + expect(result.pixels).toEqual({ width: 32, height: 16, channels: 3, bytes: 1536 }); + }); + + test("handles a background load rejection after abort and permits a fresh load", async () => { + const scenario = "load-failure"; + + const result = await runClassificationScenario(scenario); + + expect(result.aborted).toBe("AbortError"); + expect(result.loads).toBe(2); + expect(result.inferences).toBe(1); + expect(result.retry.sha256).toBe(result.expectedSha256); + }); + + test("keeps the slot during non-preemptible inference and discards the cancelled result", async () => { + const scenario = "inference-abort"; + + const result = await runClassificationScenario(scenario); + + expect(result.settledBeforeInferenceEnded).toBe(false); + expect(result.competing).toBe("Classifier is busy"); + expect(result.aborted).toBe("AbortError"); + expect(result.loads).toBe(1); + expect(result.inferences).toBe(2); + expect(result.retry.sha256).toBe(result.expectedSha256); + }); +}); diff --git a/packages/core/src/images/classify-image.ts b/packages/core/src/images/classify-image.ts index b8fe8c7..c0d6dde 100644 --- a/packages/core/src/images/classify-image.ts +++ b/packages/core/src/images/classify-image.ts @@ -7,6 +7,8 @@ import { type ClassificationResult, } from "@m4k/common"; +import { waitForLoad } from "../util/wait-for-load.js"; + let classifier: Promise>> | undefined; let busy = false; async function loadClassifier() { @@ -59,7 +61,7 @@ export async function classifyImage( classifier = undefined; throw error; }); - const run = await classifier; + const run = await waitForLoad(classifier, signal); signal?.throwIfAborted(); const labels = await run( new RawImage(new Uint8ClampedArray(data), info.width, info.height, 3), diff --git a/packages/core/src/util/wait-for-load.ts b/packages/core/src/util/wait-for-load.ts new file mode 100644 index 0000000..49a5230 --- /dev/null +++ b/packages/core/src/util/wait-for-load.ts @@ -0,0 +1,23 @@ +/** Stop waiting on cancellation without cancelling or duplicating a shared model load. */ +export function waitForLoad(load: Promise, signal?: AbortSignal): Promise { + if (!signal) return load; + return new Promise((resolve, reject) => { + const onAbort = () => { + signal.removeEventListener("abort", onAbort); + reject(signal.reason); + }; + signal.addEventListener("abort", onAbort, { once: true }); + // Always observe settlement, even after cancellation, so a failed background load is handled. + load.then( + (value) => { + signal.removeEventListener("abort", onAbort); + resolve(value); + }, + (error) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + if (signal.aborted) onAbort(); + }); +} diff --git a/packages/server/src/images/classify-image-handler.spec.ts b/packages/server/src/images/classify-image-handler.spec.ts index c513b28..0147588 100644 --- a/packages/server/src/images/classify-image-handler.spec.ts +++ b/packages/server/src/images/classify-image-handler.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test"; +import { runClassificationScenario } from "../../../../fixtures/run-classification-scenario.js"; import { classifyImageHandler } from "./classify-image-handler.js"; const config = { @@ -14,6 +15,24 @@ const request = (options: unknown, body: Uint8Array = new Uint8Array([1])) => }); describe("classifyImageHandler", () => { + test("returns verified annotations after real JPEG decoding with only the model stubbed", async () => { + const scenario = "handler-success"; + + const result = await runClassificationScenario(scenario); + + expect(result.status).toBe(200); + expect(result.body).toEqual({ + classifierId: "clip-image-labels", + classifierVersion: "1", + sha256: result.expectedSha256, + labels: [ + { label: "landscape", score: 0.5 }, + { label: "receipt", score: 0.5 }, + ], + }); + expect(result.pixels).toEqual({ width: 32, height: 16, channels: 3, bytes: 1536 }); + }); + test("refuses an unsupported classifier before inference", async () => { const input = request({ ...config, classifierId: "arbitrary-model" }); diff --git a/packages/server/src/images/process-image-handler.spec.ts b/packages/server/src/images/process-image-handler.spec.ts index f898d50..cb23ed8 100644 --- a/packages/server/src/images/process-image-handler.spec.ts +++ b/packages/server/src/images/process-image-handler.spec.ts @@ -1,17 +1,66 @@ -import type { - ProcessingError, - Progress, - QueuePosition, - RemoteImageOptions, -} from "@m4k/common"; +import type { ProcessingError, Progress, QueuePosition, RemoteImageOptions } from "@m4k/common"; import { streamParts } from "@sv2dev/multipart-stream"; import { describe, expect, it } from "bun:test"; +import sharp from "sharp"; +import { embeddedPreviewFixture } from "../../../../fixtures/embedded-preview.js"; import { processImageHandler } from "./process-image-handler"; const fixture = Bun.file("../../fixtures/image.jpeg"); const avifFixture = Bun.file("../../fixtures/image.avif"); describe("/process", () => { + it("decodes embeddedPreview=true from the URL query", async () => { + const jpeg = await sharp({ create: { width: 32, height: 16, channels: 3, background: "red" } }) + .jpeg() + .toBuffer(); + const input = embeddedPreviewFixture(jpeg); + + const response = await processImageHandler( + new Request("http://m4k/images/process?embeddedPreview=true&format=jpeg", { + method: "POST", + body: input, + }), + ); + const collected = await collectResponse(response); + + expect(response.status).toBe(200); + expect(collected).toContainEqual( + expect.objectContaining({ filename: "file1.jpeg", type: "image/jpeg" }), + ); + expect(collected.some((part) => "error" in part)).toBe(false); + }); + + it("decodes embeddedPreview=false without enabling RAW extraction", async () => { + const input = fixture; + + const response = await processImageHandler( + new Request("http://m4k/images/process?embeddedPreview=false&format=jpeg", { + method: "POST", + body: input, + }), + ); + const collected = await collectResponse(response); + + expect(response.status).toBe(200); + expect(collected).toContainEqual( + expect.objectContaining({ filename: "file1.jpeg", type: "image/jpeg" }), + ); + expect(collected.some((part) => "error" in part)).toBe(false); + }); + + it("rejects an invalid embeddedPreview query value", async () => { + const input = fixture; + + const response = await processImageHandler( + new Request("http://m4k/images/process?embeddedPreview=maybe&format=jpeg", { + method: "POST", + body: input, + }), + ); + + expect(response.status).toBe(400); + }); + it("should process a single image", async () => { const opts: RemoteImageOptions = { resize: { width: 100, height: 1000 }, @@ -22,7 +71,7 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); expect(response.status).toBe(200); @@ -46,14 +95,14 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); const r2 = processImageHandler( new Request(`http://localhost:3000/images/process`, { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); const collected1 = await collectResponse(await r1); @@ -82,7 +131,7 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); expect(res.status).toBe(400); @@ -94,7 +143,7 @@ describe("/process", () => { new Request(`http://localhost:3000/images/process`, { method: "POST", body: fixture, - }) + }), ); expect(res.status).toBe(400); @@ -107,7 +156,7 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": "{" }, - }) + }), ); expect(res.status).toBe(400); @@ -132,7 +181,7 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); const collected = await collectResponse(response); @@ -157,7 +206,7 @@ describe("/process", () => { method: "POST", body: avifFixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); expect(response.status).toBe(200); @@ -182,7 +231,7 @@ describe("/process", () => { method: "POST", body: fixture, headers: { "X-Options": JSON.stringify(opts) }, - }) + }), ); expect(response.status).toBe(200); @@ -209,9 +258,7 @@ async function collectResponse(response: Response) { )[] = []; for await (const part of streamParts(response)) { if (part.type === "application/json") { - collected.push( - (await part.json()) as QueuePosition | Progress | ProcessingError - ); + collected.push((await part.json()) as QueuePosition | Progress | ProcessingError); } else if (part.type === "text/plain") { continue; // keepalive } else { diff --git a/packages/server/src/images/process-image-handler.ts b/packages/server/src/images/process-image-handler.ts index f8cfbda..a0063a3 100644 --- a/packages/server/src/images/process-image-handler.ts +++ b/packages/server/src/images/process-image-handler.ts @@ -6,7 +6,7 @@ import { ProcessedFile, processImage } from "m4k"; import { rm } from "node:fs/promises"; import { parseOpts } from "../util/request-parsing.js"; import { error, queueAndStream } from "../util/response.js"; -import { numberQueryParamSchema, parse } from "../util/typebox.js"; +import { booleanQueryParamSchema, numberQueryParamSchema, parse } from "../util/typebox.js"; const compiledOptionsSchema = TypeCompiler.Compile(imageOptionsSchema); @@ -54,7 +54,7 @@ export async function processImageHandler(request: Request) { } const querySchema = T.Object({ - embeddedPreview: T.Optional(T.Boolean()), + embeddedPreview: T.Optional(booleanQueryParamSchema), rotate: T.Optional(numberQueryParamSchema), width: T.Optional(numberQueryParamSchema), height: T.Optional(numberQueryParamSchema), diff --git a/packages/server/src/util/typebox.ts b/packages/server/src/util/typebox.ts index 4d02ba3..9418e97 100644 --- a/packages/server/src/util/typebox.ts +++ b/packages/server/src/util/typebox.ts @@ -1,19 +1,21 @@ import { Type as T, type TSchema } from "@sinclair/typebox"; import type { TypeCheck } from "@sinclair/typebox/compiler"; -export const numberQueryParamSchema = T.Transform( - T.Union([T.String(), T.Number()]) -) +export const numberQueryParamSchema = T.Transform(T.Union([T.String(), T.Number()])) .Decode(Number) .Encode(JSON.stringify); +export const booleanQueryParamSchema = T.Transform( + T.Union([T.Literal("true"), T.Literal("false"), T.Boolean()]), +) + .Decode((value) => value === true || value === "true") + .Encode((value) => (value ? "true" : "false")); + export function parse(schema: TypeCheck, value: unknown) { const valid = schema.Check(value); if (!valid) { const error = schema.Errors(value).First()!; - throw new RangeError( - `${error.path ? `[${error.path}] ` : ""}${error.message}` - ); + throw new RangeError(`${error.path ? `[${error.path}] ` : ""}${error.message}`); } return schema.Decode(value); }