@abhishek944/pi-classifier 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/LICENSE +201 -0
- package/README.md +425 -2
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +56 -0
- package/dist/choices.d.ts +8 -0
- package/dist/choices.js +131 -0
- package/dist/classification-tree.d.ts +4 -0
- package/dist/classification-tree.js +143 -0
- package/dist/classify.d.ts +10 -0
- package/dist/classify.js +120 -0
- package/dist/config.d.ts +82 -0
- package/dist/config.js +338 -0
- package/dist/cost.d.ts +8 -0
- package/dist/cost.js +202 -0
- package/dist/extension.d.ts +249 -0
- package/dist/extension.js +380 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.js +85 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +184 -0
- package/dist/providers.d.ts +2 -0
- package/dist/providers.js +624 -0
- package/dist/settings-write.d.ts +10 -0
- package/dist/settings-write.js +110 -0
- package/dist/tree.d.ts +4 -0
- package/dist/tree.js +136 -0
- package/dist/types.d.ts +228 -0
- package/dist/types.js +18 -0
- package/dist/validation.d.ts +3 -0
- package/dist/validation.js +94 -0
- package/package.json +72 -4
- package/src/auth.ts +74 -0
- package/src/choices.ts +173 -0
- package/src/classification-tree.ts +181 -0
- package/src/classify.ts +167 -0
- package/src/config.ts +442 -0
- package/src/cost.ts +250 -0
- package/src/extension.ts +511 -0
- package/src/http.ts +108 -0
- package/src/index.ts +25 -0
- package/src/inputs.ts +239 -0
- package/src/providers.ts +905 -0
- package/src/settings-write.ts +145 -0
- package/src/tree.ts +157 -0
- package/src/types.ts +248 -0
- package/src/validation.ts +138 -0
package/src/inputs.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { lstat, open, realpath } from "node:fs/promises";
|
|
4
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import sharp from "sharp";
|
|
7
|
+
import {
|
|
8
|
+
ClassifierError,
|
|
9
|
+
type ClassifyParams,
|
|
10
|
+
type PreparedImage,
|
|
11
|
+
type PreparedInput,
|
|
12
|
+
type ResolvedModel,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
import { hasBox } from "./validation.js";
|
|
15
|
+
|
|
16
|
+
export async function prepareInput(
|
|
17
|
+
params: ClassifyParams,
|
|
18
|
+
route: ResolvedModel,
|
|
19
|
+
cwd: string,
|
|
20
|
+
signal?: AbortSignal,
|
|
21
|
+
): Promise<PreparedInput> {
|
|
22
|
+
if (params.images?.length && !route.images)
|
|
23
|
+
throw new ClassifierError(
|
|
24
|
+
"capability",
|
|
25
|
+
"The selected model does not support images, or experimental Jev images are disabled.",
|
|
26
|
+
);
|
|
27
|
+
if (hasBox(params.questions) && (!route.box || !params.images?.length))
|
|
28
|
+
throw new ClassifierError(
|
|
29
|
+
"capability",
|
|
30
|
+
"box requires an enabled Jev 1.14 model, experimentalImages/experimentalBox and an image.",
|
|
31
|
+
);
|
|
32
|
+
const images: PreparedImage[] = [];
|
|
33
|
+
const clef = route.api === "cloudflare-system-one" && route.images;
|
|
34
|
+
const perImageLimit = (clef ? 4 : 5) * 1024 * 1024;
|
|
35
|
+
const totalLimit = (clef ? 8 : 10) * 1024 * 1024;
|
|
36
|
+
if (clef && (params.images?.length ?? 0) > 4)
|
|
37
|
+
throw new ClassifierError("input", "Clef accepts at most four images.");
|
|
38
|
+
let totalBytes = 0;
|
|
39
|
+
for (const path of params.images ?? []) {
|
|
40
|
+
if (signal?.aborted)
|
|
41
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
42
|
+
try {
|
|
43
|
+
if (/^[a-z]+:/i.test(path)) throw new Error();
|
|
44
|
+
const root = await realpath(cwd);
|
|
45
|
+
const target = resolve(root, path);
|
|
46
|
+
const inside = relative(root, target);
|
|
47
|
+
if (
|
|
48
|
+
!inside ||
|
|
49
|
+
inside === ".." ||
|
|
50
|
+
inside.startsWith(".." + sep) ||
|
|
51
|
+
isAbsolute(inside)
|
|
52
|
+
)
|
|
53
|
+
throw new Error();
|
|
54
|
+
// Reject symlink components, not just the final image.
|
|
55
|
+
let current = root;
|
|
56
|
+
for (const part of inside.split(sep)) {
|
|
57
|
+
current = resolve(current, part);
|
|
58
|
+
const entry = await lstat(current);
|
|
59
|
+
if (
|
|
60
|
+
entry.isSymbolicLink() ||
|
|
61
|
+
(current === target && !entry.isFile()) ||
|
|
62
|
+
(current !== target && !entry.isDirectory())
|
|
63
|
+
)
|
|
64
|
+
throw new Error();
|
|
65
|
+
}
|
|
66
|
+
const canonical = await realpath(target);
|
|
67
|
+
if (canonical !== target) throw new Error();
|
|
68
|
+
const file = await open(
|
|
69
|
+
target,
|
|
70
|
+
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
|
71
|
+
);
|
|
72
|
+
let bytes: Buffer;
|
|
73
|
+
try {
|
|
74
|
+
// Validate the actual opened object: checking the path before open is raceable.
|
|
75
|
+
await verifyOpenedPath(file.fd, root, signal);
|
|
76
|
+
const stat = await file.stat();
|
|
77
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > perImageLimit)
|
|
78
|
+
throw new Error();
|
|
79
|
+
// Read a bounded number of bytes even if another process grows the file.
|
|
80
|
+
const buffer = Buffer.alloc(perImageLimit + 1);
|
|
81
|
+
let offset = 0;
|
|
82
|
+
while (offset < buffer.length) {
|
|
83
|
+
if (signal?.aborted)
|
|
84
|
+
throw new ClassifierError(
|
|
85
|
+
"aborted",
|
|
86
|
+
"Classification was cancelled.",
|
|
87
|
+
);
|
|
88
|
+
const read = await file.read(
|
|
89
|
+
buffer,
|
|
90
|
+
offset,
|
|
91
|
+
buffer.length - offset,
|
|
92
|
+
null,
|
|
93
|
+
);
|
|
94
|
+
if (!read.bytesRead) break;
|
|
95
|
+
offset += read.bytesRead;
|
|
96
|
+
}
|
|
97
|
+
if (offset > perImageLimit) throw new Error();
|
|
98
|
+
bytes = buffer.subarray(0, offset);
|
|
99
|
+
} finally {
|
|
100
|
+
await file.close();
|
|
101
|
+
}
|
|
102
|
+
totalBytes += bytes.length;
|
|
103
|
+
if (totalBytes > totalLimit) throw new Error();
|
|
104
|
+
const meta = await sharp(bytes, {
|
|
105
|
+
limitInputPixels: 16_777_216,
|
|
106
|
+
}).metadata();
|
|
107
|
+
if (
|
|
108
|
+
!meta.width ||
|
|
109
|
+
!meta.height ||
|
|
110
|
+
!["png", "jpeg", "webp"].includes(meta.format ?? "") ||
|
|
111
|
+
(meta.pages ?? 1) > 1
|
|
112
|
+
)
|
|
113
|
+
throw new Error();
|
|
114
|
+
if (route.api === "system-one") {
|
|
115
|
+
if (meta.format === "webp")
|
|
116
|
+
throw new ClassifierError(
|
|
117
|
+
"input",
|
|
118
|
+
"Jev image assets accept PNG and JPEG only.",
|
|
119
|
+
);
|
|
120
|
+
const pixels = meta.width * meta.height;
|
|
121
|
+
if (
|
|
122
|
+
meta.width < 256 ||
|
|
123
|
+
meta.width > 1568 ||
|
|
124
|
+
meta.height < 256 ||
|
|
125
|
+
meta.height > 1568 ||
|
|
126
|
+
pixels < 78_400 ||
|
|
127
|
+
pixels > 2_458_624
|
|
128
|
+
) {
|
|
129
|
+
throw new ClassifierError(
|
|
130
|
+
"input",
|
|
131
|
+
"Resize or pad Jev images before sending: each side must be 256–1568 pixels and total area 78400–2458624 pixels. Images are not silently resized.",
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (
|
|
136
|
+
route.api === "perplexity-decisions" &&
|
|
137
|
+
Math.ceil(meta.width / 32) * Math.ceil(meta.height / 32) > 2048
|
|
138
|
+
)
|
|
139
|
+
throw new ClassifierError(
|
|
140
|
+
"input",
|
|
141
|
+
"Resize Perplexity images to at most 2048 tiles of 32×32 pixels before classifying.",
|
|
142
|
+
);
|
|
143
|
+
await decodeImage(bytes, signal);
|
|
144
|
+
images.push({
|
|
145
|
+
data: bytes.toString("base64"),
|
|
146
|
+
mimeType:
|
|
147
|
+
meta.format === "jpeg"
|
|
148
|
+
? "image/jpeg"
|
|
149
|
+
: meta.format === "png"
|
|
150
|
+
? "image/png"
|
|
151
|
+
: "image/webp",
|
|
152
|
+
width: meta.width,
|
|
153
|
+
height: meta.height,
|
|
154
|
+
});
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (signal?.aborted)
|
|
157
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
158
|
+
if (error instanceof ClassifierError) throw error;
|
|
159
|
+
throw new ClassifierError(
|
|
160
|
+
"input",
|
|
161
|
+
"Images must be non-animated PNG/JPEG/WebP regular files inside cwd, without symlinks, and fit the documented byte and pixel limits (Clef: 4 MiB each/8 MiB total; others: 5 MiB each/10 MiB total; 16 megapixels each).",
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { state: params.state, questions: params.questions, images };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function decodeImage(bytes: Buffer, signal?: AbortSignal): Promise<void> {
|
|
169
|
+
if (signal?.aborted)
|
|
170
|
+
throw new ClassifierError("aborted", "Classification was cancelled.");
|
|
171
|
+
// A real output pipeline decodes every pixel and honors libvips' native timeout.
|
|
172
|
+
const decoder = sharp(bytes, {
|
|
173
|
+
limitInputPixels: 16_777_216,
|
|
174
|
+
failOn: "warning",
|
|
175
|
+
})
|
|
176
|
+
.timeout({ seconds: 10 })
|
|
177
|
+
.raw();
|
|
178
|
+
let cancel = () => {};
|
|
179
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
180
|
+
try {
|
|
181
|
+
await new Promise<void>((resolve, reject) => {
|
|
182
|
+
cancel = () => {
|
|
183
|
+
decoder.destroy();
|
|
184
|
+
reject(new ClassifierError("aborted", "Classification was cancelled."));
|
|
185
|
+
};
|
|
186
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
187
|
+
timer = setTimeout(() => {
|
|
188
|
+
decoder.destroy();
|
|
189
|
+
reject(new ClassifierError("input", "Image decoding timed out."));
|
|
190
|
+
}, 10_000);
|
|
191
|
+
// Attach both handlers even after cancellation so the native callback cannot reject unhandled.
|
|
192
|
+
decoder.toBuffer().then(() => resolve(), reject);
|
|
193
|
+
});
|
|
194
|
+
} finally {
|
|
195
|
+
if (timer) clearTimeout(timer);
|
|
196
|
+
signal?.removeEventListener("abort", cancel);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const execFileAsync = promisify(execFile);
|
|
201
|
+
|
|
202
|
+
/** Verify containment of the opened descriptor, not a raceable pre-open path. */
|
|
203
|
+
export async function verifyOpenedPath(
|
|
204
|
+
fd: number,
|
|
205
|
+
root: string,
|
|
206
|
+
signal?: AbortSignal,
|
|
207
|
+
): Promise<void> {
|
|
208
|
+
let openedPath: string;
|
|
209
|
+
if (process.platform === "linux") {
|
|
210
|
+
openedPath = await realpath("/proc/self/fd/" + fd);
|
|
211
|
+
} else if (process.platform === "darwin") {
|
|
212
|
+
// Node does not expose F_GETPATH; the OS lsof utility queries it for this exact fd.
|
|
213
|
+
const { stdout } = await execFileAsync(
|
|
214
|
+
"/usr/sbin/lsof",
|
|
215
|
+
["-a", "-p", String(process.pid), "-d", String(fd), "-Fn"],
|
|
216
|
+
{
|
|
217
|
+
timeout: 3000,
|
|
218
|
+
maxBuffer: 8192,
|
|
219
|
+
...(signal ? { signal } : {}),
|
|
220
|
+
},
|
|
221
|
+
);
|
|
222
|
+
const paths = stdout.split("\n").filter((line) => line.startsWith("n"));
|
|
223
|
+
if (paths.length !== 1) throw new Error();
|
|
224
|
+
openedPath = paths[0]!.slice(1);
|
|
225
|
+
} else {
|
|
226
|
+
throw new ClassifierError(
|
|
227
|
+
"capability",
|
|
228
|
+
"Safe local file loading currently supports macOS and Linux only. Inline text/JSON classification remains available.",
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
const inside = relative(root, openedPath);
|
|
232
|
+
if (
|
|
233
|
+
!inside ||
|
|
234
|
+
inside === ".." ||
|
|
235
|
+
inside.startsWith(".." + sep) ||
|
|
236
|
+
isAbsolute(inside)
|
|
237
|
+
)
|
|
238
|
+
throw new Error();
|
|
239
|
+
}
|