@aivax/cli 0.0.0-stage → 1.1.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/LICENSE +21 -0
- package/README.md +213 -2
- package/package.json +41 -5
- package/src/args.js +84 -0
- package/src/cli.js +124 -0
- package/src/commands/account.js +132 -0
- package/src/commands/analytics.js +30 -0
- package/src/commands/api.js +37 -0
- package/src/commands/auth.js +142 -0
- package/src/commands/batch.js +191 -0
- package/src/commands/chat-clients.js +157 -0
- package/src/commands/conversations.js +92 -0
- package/src/commands/crud.js +68 -0
- package/src/commands/docs.js +91 -0
- package/src/commands/gateways.js +85 -0
- package/src/commands/generate.js +197 -0
- package/src/commands/logs.js +41 -0
- package/src/commands/models.js +38 -0
- package/src/commands/ocr.js +370 -0
- package/src/commands/rag.js +452 -0
- package/src/commands/shell.js +46 -0
- package/src/commands/skills.js +48 -0
- package/src/commands/tests.js +429 -0
- package/src/commands/web.js +68 -0
- package/src/errors.js +19 -0
- package/src/http.js +175 -0
- package/src/input.js +120 -0
- package/src/pdf.js +209 -0
- package/src/profiles.js +67 -0
- package/src/prompt.js +67 -0
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, extname } from "node:path";
|
|
4
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
5
|
+
import { crc32 as checksum } from "node:zlib";
|
|
6
|
+
import { ApiError, UsageError } from "../errors.js";
|
|
7
|
+
import { fetchData, print, request } from "../http.js";
|
|
8
|
+
import { openFile, readJson } from "../input.js";
|
|
9
|
+
import { fetchSources, schemaOption } from "./web.js";
|
|
10
|
+
|
|
11
|
+
const MIME_TYPES = {
|
|
12
|
+
".pdf": "application/pdf",
|
|
13
|
+
".png": "image/png",
|
|
14
|
+
".jpg": "image/jpeg",
|
|
15
|
+
".jpeg": "image/jpeg",
|
|
16
|
+
".webp": "image/webp",
|
|
17
|
+
".tif": "image/tiff",
|
|
18
|
+
".tiff": "image/tiff",
|
|
19
|
+
".bmp": "image/bmp",
|
|
20
|
+
".doc": "application/msword",
|
|
21
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
22
|
+
".odt": "application/vnd.oasis.opendocument.text",
|
|
23
|
+
".rtf": "application/rtf",
|
|
24
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
25
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
26
|
+
".odp": "application/vnd.oasis.opendocument.presentation",
|
|
27
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
28
|
+
".ods": "application/vnd.oasis.opendocument.spreadsheet",
|
|
29
|
+
".csv": "text/csv",
|
|
30
|
+
".epub": "application/epub+zip",
|
|
31
|
+
".txt": "text/plain",
|
|
32
|
+
".md": "text/markdown",
|
|
33
|
+
".html": "text/html",
|
|
34
|
+
".htm": "text/html"
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const MB = 1024 * 1024;
|
|
38
|
+
const MAX_ATTEMPTS = 5;
|
|
39
|
+
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504, 520, 522, 524]);
|
|
40
|
+
const FATAL_STATUS = new Set([401, 402, 403]);
|
|
41
|
+
const EMPTY_CONTENT_ERROR = /no text could be extracted/i;
|
|
42
|
+
|
|
43
|
+
const log = message => process.stderr.write(`${message}\n`);
|
|
44
|
+
|
|
45
|
+
const formatDuration = ms => {
|
|
46
|
+
const seconds = Math.round(ms / 1000);
|
|
47
|
+
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, "0")}s`;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const formatSize = bytes => `${(bytes / MB).toFixed(2)} MB`;
|
|
51
|
+
|
|
52
|
+
const crc32 = data => checksum(data).toString(16).padStart(8, "0");
|
|
53
|
+
|
|
54
|
+
const isFatal = error => error instanceof UsageError || (error instanceof ApiError && FATAL_STATUS.has(error.status));
|
|
55
|
+
|
|
56
|
+
async function post(ctx, path, body) {
|
|
57
|
+
for (let attempt = 1; ; attempt++) {
|
|
58
|
+
try {
|
|
59
|
+
const response = await request(ctx, "POST", path, { body, agentOutput: false });
|
|
60
|
+
const { data } = await response.json();
|
|
61
|
+
const credits = Number.parseFloat(response.headers.get("consumed-credits") ?? "");
|
|
62
|
+
|
|
63
|
+
return { data, cost: Number.isFinite(credits) ? credits : null };
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
const retryable = error instanceof ApiError ? RETRYABLE_STATUS.has(error.status) : !isFatal(error);
|
|
67
|
+
|
|
68
|
+
if (!retryable || attempt >= MAX_ATTEMPTS) {
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
await sleep(Math.max(2000 * 2 ** (attempt - 1), error.retryAfter ?? 0));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const parse = {
|
|
78
|
+
description: "Extract text from images, scanned PDFs and documents. Prints the extracted text.",
|
|
79
|
+
options: {
|
|
80
|
+
file: { alias: "f", value: "<file|url>", list: true, description: "Image, PDF, office document or URL. Repeatable. Also accepted as positional arguments." },
|
|
81
|
+
schema: schemaOption,
|
|
82
|
+
json: { description: "Print the full API result, including processing units." }
|
|
83
|
+
},
|
|
84
|
+
args: "[file...]",
|
|
85
|
+
async run(ctx) {
|
|
86
|
+
const sources = [...(ctx.options.file ?? []), ...ctx.args];
|
|
87
|
+
|
|
88
|
+
if (!sources.length) {
|
|
89
|
+
throw new UsageError("Provide at least one file with -f <file>.");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const { results } = await fetchData(ctx, "POST", "/api/v1/web/fetch", {
|
|
93
|
+
body: {
|
|
94
|
+
contents: await fetchSources(sources),
|
|
95
|
+
responseSchema: ctx.options.schema && await readJson(ctx.options.schema, "--schema")
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
if (ctx.options.json) {
|
|
100
|
+
print(results);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let failed = false;
|
|
105
|
+
|
|
106
|
+
for (const result of results) {
|
|
107
|
+
const source = sources[result.index];
|
|
108
|
+
|
|
109
|
+
if (result.error) {
|
|
110
|
+
failed = true;
|
|
111
|
+
process.stderr.write(`error: ${source}: ${result.error}\n`);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (sources.length > 1) {
|
|
116
|
+
print(`==> ${source} <==`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
print(result.extractedObject ?? result.extractedText ?? "");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (failed) {
|
|
123
|
+
process.exitCode = 1;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
async function splitDocument(input, mime, source) {
|
|
129
|
+
if (mime !== "application/pdf") {
|
|
130
|
+
return [{ page: null, bytes: input, error: null }];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const { compressImages, openPdf, splitPages } = await import("../pdf.js");
|
|
134
|
+
let doc;
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
doc = await openPdf(input);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
throw new UsageError(`Cannot open PDF: ${error.message}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
log(`Compressing ${source} (${formatSize(input.length)}, ${doc.getPageCount()} pages)...`);
|
|
144
|
+
const compressed = await compressImages(doc);
|
|
145
|
+
log(`Recompressed ${compressed.images} images (${formatSize(compressed.saved)} saved).`);
|
|
146
|
+
|
|
147
|
+
let lastReport = 0;
|
|
148
|
+
return await splitPages(doc, (done, total) => {
|
|
149
|
+
if (done === total || Date.now() - lastReport > 2000) {
|
|
150
|
+
lastReport = Date.now();
|
|
151
|
+
log(`Splitting pages ${done}/${total}...`);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const document = {
|
|
157
|
+
aliases: ["doc"],
|
|
158
|
+
description: "Transcribe a whole document page by page into Markdown or RAG-ready JSONL.",
|
|
159
|
+
options: {
|
|
160
|
+
file: { alias: "f", value: "<file>", description: "Document to transcribe. Also accepted as positional argument." },
|
|
161
|
+
format: { value: "<format>", description: "markdown (default) or jsonl. JSONL lines are segmented and ready for \"aivax rag import\"." },
|
|
162
|
+
output: { alias: "o", value: "<file>", description: "Output file. Defaults to stdout." },
|
|
163
|
+
chunkSize: { value: "<MB>", number: true, description: "Maximum request size in MB. Defaults to 5." },
|
|
164
|
+
concurrency: { value: "<n>", number: true, description: "Requests processed in parallel. Defaults to 4." }
|
|
165
|
+
},
|
|
166
|
+
args: "[file]",
|
|
167
|
+
async run(ctx) {
|
|
168
|
+
const { options } = ctx;
|
|
169
|
+
const inputPath = options.file ?? ctx.args[0];
|
|
170
|
+
const format = options.format === "md" ? "markdown" : options.format ?? "markdown";
|
|
171
|
+
const chunkBytes = (options.chunkSize ?? 5) * MB;
|
|
172
|
+
const concurrency = options.concurrency ?? 4;
|
|
173
|
+
|
|
174
|
+
if (!inputPath || ctx.args.length > (options.file ? 0 : 1)) {
|
|
175
|
+
throw new UsageError("Provide exactly one document with -f <file> or as positional argument.");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (format !== "markdown" && format !== "jsonl") {
|
|
179
|
+
throw new UsageError(`Invalid --format "${options.format}". Use markdown or jsonl.`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (!(chunkBytes > 0)) {
|
|
183
|
+
throw new UsageError("--chunk-size must be a positive number.");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
187
|
+
throw new UsageError("--concurrency must be a positive integer.");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const mime = MIME_TYPES[extname(inputPath).toLowerCase()];
|
|
191
|
+
if (!mime) {
|
|
192
|
+
throw new UsageError(`Unsupported file type "${extname(inputPath)}". Supported: ${Object.keys(MIME_TYPES).join(" ")}`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const input = await (await openFile(inputPath)).bytes();
|
|
196
|
+
const source = basename(inputPath);
|
|
197
|
+
const startedAt = Date.now();
|
|
198
|
+
const extractedAt = new Date(startedAt).toISOString();
|
|
199
|
+
|
|
200
|
+
const units = (await splitDocument(input, mime, source))
|
|
201
|
+
.map(({ page, bytes, error }) => ({ page, bytes, text: "", segments: [], error }));
|
|
202
|
+
|
|
203
|
+
const totalPages = mime === "application/pdf" ? units.length : null;
|
|
204
|
+
const chunks = [];
|
|
205
|
+
let currentSize = 0;
|
|
206
|
+
|
|
207
|
+
for (const unit of units.filter(item => item.bytes)) {
|
|
208
|
+
if (!chunks.length || currentSize + unit.bytes.length > chunkBytes) {
|
|
209
|
+
chunks.push([]);
|
|
210
|
+
currentSize = 0;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
chunks.at(-1).push(unit);
|
|
214
|
+
currentSize += unit.bytes.length;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
log(`Split into ${chunks.length} chunks of up to ${chunkBytes / MB} MB. Processing ${Math.min(concurrency, chunks.length)} at a time...`);
|
|
218
|
+
|
|
219
|
+
const totals = { units: units.filter(unit => !unit.bytes).length, processingUnits: 0, tokens: 0, segments: 0, cost: 0, empty: 0 };
|
|
220
|
+
let finishedChunks = 0;
|
|
221
|
+
let nextChunk = 0;
|
|
222
|
+
|
|
223
|
+
async function processChunk(chunk) {
|
|
224
|
+
const contents = chunk.map(unit => `data:${mime};base64,${Buffer.from(unit.bytes).toString("base64")}`);
|
|
225
|
+
const fetched = await post(ctx, "/api/v1/web/fetch", { contents, returnErrors: true });
|
|
226
|
+
totals.cost += fetched.cost ?? 0;
|
|
227
|
+
|
|
228
|
+
for (const result of fetched.data.results) {
|
|
229
|
+
const unit = chunk[result.index];
|
|
230
|
+
totals.processingUnits += result.processingUnits ?? 0;
|
|
231
|
+
|
|
232
|
+
if (result.error && EMPTY_CONTENT_ERROR.test(result.error)) {
|
|
233
|
+
totals.empty++;
|
|
234
|
+
}
|
|
235
|
+
else if (result.error || result.extractedText == null) {
|
|
236
|
+
unit.error = `OCR failed: ${result.error ?? "no result"}`;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
unit.text = result.extractedText.trim();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
for (const [index, unit] of chunk.entries()) {
|
|
244
|
+
if (!unit.error && !fetched.data.results.some(result => result.index === index)) {
|
|
245
|
+
unit.error = "OCR failed: missing result";
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const toSegment = chunk.filter(unit => !unit.error && unit.text);
|
|
250
|
+
|
|
251
|
+
if (format !== "jsonl" || !toSegment.length) {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
const { data, cost } = await post(ctx, "/api/v1/generations/segment", { documents: toSegment.map(unit => unit.text), sanitize: false });
|
|
257
|
+
totals.cost += cost ?? data.usage.cost;
|
|
258
|
+
totals.tokens += data.usage.processing_units;
|
|
259
|
+
|
|
260
|
+
for (const result of data.result) {
|
|
261
|
+
const unit = toSegment[result.index];
|
|
262
|
+
|
|
263
|
+
if (result.error) {
|
|
264
|
+
unit.error = `Segmentation failed: ${result.error}`;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
unit.segments = result.segments.filter(segment => segment.trim());
|
|
269
|
+
totals.segments += unit.segments.length;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
if (isFatal(error)) throw error;
|
|
274
|
+
toSegment.forEach(unit => unit.error = `Segmentation failed: ${error.message}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function worker() {
|
|
279
|
+
while (nextChunk < chunks.length) {
|
|
280
|
+
const number = nextChunk++;
|
|
281
|
+
const chunk = chunks[number];
|
|
282
|
+
const chunkStartedAt = Date.now();
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
await processChunk(chunk);
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
if (isFatal(error)) throw error;
|
|
289
|
+
chunk.forEach(unit => unit.error ??= `Request failed: ${error.message}`);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
chunk.forEach(unit => unit.bytes = null);
|
|
293
|
+
finishedChunks++;
|
|
294
|
+
totals.units += chunk.length;
|
|
295
|
+
|
|
296
|
+
const failed = chunk.filter(unit => unit.error).length;
|
|
297
|
+
const elapsed = Date.now() - startedAt;
|
|
298
|
+
const unitsTotal = totalPages ?? 1;
|
|
299
|
+
const range = totalPages ? `pages ${chunk[0].page}-${chunk.at(-1).page}` : source;
|
|
300
|
+
const eta = finishedChunks < chunks.length ? `, ETA ${formatDuration(elapsed / finishedChunks * (chunks.length - finishedChunks))}` : "";
|
|
301
|
+
const consumption = `${totals.processingUnits} OCR PUs${format === "jsonl" ? `, ${totals.tokens} segment tokens, ${totals.segments} segments` : ""}, $${totals.cost.toFixed(6)}`;
|
|
302
|
+
|
|
303
|
+
log(`[chunk ${number + 1}/${chunks.length}] ${range} ${failed ? `${failed} failed` : "ok"} in ${formatDuration(Date.now() - chunkStartedAt)}`
|
|
304
|
+
+ ` | ${totals.units}/${unitsTotal} ${totalPages ? "pages" : "files"} (${Math.round(totals.units / unitsTotal * 100)}%)`
|
|
305
|
+
+ ` | ${consumption}${eta}`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, chunks.length) }, worker));
|
|
310
|
+
|
|
311
|
+
const pageLabel = unit => totalPages ? `page ${unit.page}/${totalPages}` : source;
|
|
312
|
+
let output;
|
|
313
|
+
|
|
314
|
+
if (format === "markdown") {
|
|
315
|
+
output = units
|
|
316
|
+
.map(unit => {
|
|
317
|
+
if (!totalPages) return unit.error ? `<!-- ${unit.error} -->` : unit.text;
|
|
318
|
+
const marker = `<!-- ${pageLabel(unit)}${unit.error ? `: ${unit.error}` : ""} -->`;
|
|
319
|
+
return unit.text ? `${marker}\n\n${unit.text}` : marker;
|
|
320
|
+
})
|
|
321
|
+
.join("\n\n") + "\n";
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
const fileMeta = {
|
|
325
|
+
file_name: source,
|
|
326
|
+
file_hash_sha1: createHash("sha1").update(input).digest("hex"),
|
|
327
|
+
file_hash_crc32: crc32(input)
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
output = units
|
|
331
|
+
.flatMap(unit => unit.segments.map((text, index) => {
|
|
332
|
+
const pageSuffix = unit.page ? `:pg${unit.page}` : "";
|
|
333
|
+
const pageMeta = unit.page ? { page: unit.page, pages: totalPages, page_chunk: index + 1 } : {};
|
|
334
|
+
|
|
335
|
+
return `${JSON.stringify({
|
|
336
|
+
docid: `doc_${source}${pageSuffix}${unit.page ? "" : ":"}chk${crc32(text)}`,
|
|
337
|
+
__ref: `rf_${source}${pageSuffix}`,
|
|
338
|
+
text,
|
|
339
|
+
__meta: { ...fileMeta, ...pageMeta, extracted_at: extractedAt }
|
|
340
|
+
})}\n`;
|
|
341
|
+
}))
|
|
342
|
+
.join("");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (options.output) {
|
|
346
|
+
await writeFile(options.output, output);
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
process.stdout.write(output);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const failures = units.filter(unit => unit.error);
|
|
353
|
+
const errorsPath = `${options.output ?? inputPath}.errors.txt`;
|
|
354
|
+
|
|
355
|
+
if (failures.length) {
|
|
356
|
+
await writeFile(errorsPath, failures.map(unit => `${pageLabel(unit)}: ${unit.error}`).join("\n") + "\n");
|
|
357
|
+
process.exitCode = 1;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
log(`Done in ${formatDuration(Date.now() - startedAt)}: ${units.length - failures.length}/${units.length} ${totalPages ? "pages" : "files"} transcribed`
|
|
361
|
+
+ `${totals.empty ? `, ${totals.empty} without text` : ""}${failures.length ? `, ${failures.length} failed (see ${errorsPath})` : ""}.`
|
|
362
|
+
+ ` Consumption: ${totals.processingUnits} OCR PUs${format === "jsonl" ? `, ${totals.tokens} segment tokens` : ""}, $${totals.cost.toFixed(6)}.`
|
|
363
|
+
+ `${options.output ? ` Output: ${options.output}` : ""}`);
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
export default {
|
|
368
|
+
description: "OCR commands.",
|
|
369
|
+
commands: { parse, document }
|
|
370
|
+
};
|