diff --git a/packages/commands/src/commands/vision/describe.ts b/packages/commands/src/commands/vision/describe.ts index dd261eabe..bee12c296 100644 --- a/packages/commands/src/commands/vision/describe.ts +++ b/packages/commands/src/commands/vision/describe.ts @@ -1,19 +1,71 @@ import { defineCommand, chatPath, + multimodalGenerationPath, type ChatRequest, type ChatResponse, type ChatMessageContent, + type NativeOcrRequest, + type NativeOcrResponse, + type OcrBuiltinTask, + type OcrResult, BailianError, ExitCode, isLocalFile, imageFileToDataUri, redactDataUri, + type LocalizedText, } from "bailian-cli-core"; import { existsSync, statSync } from "fs"; import { extname } from "path"; +type Localize = (text: LocalizedText) => string; + +const DEFAULT_VISION_MODEL = "qwen3-vl-plus"; + +/** + * Model used only when `--ocr-task` is set. It never becomes the default of a + * plain describe call, so image/video description behaviour stays untouched. + */ +const DEFAULT_OCR_MODEL = "qwen-vl-ocr"; + +/** Built-in tasks forwarded to `parameters.ocr_options.task`. */ +const OCR_TASKS: readonly OcrBuiltinTask[] = [ + "advanced_recognition", + "key_information_extraction", + "table_parsing", + "document_parsing", + "formula_recognition", + "text_recognition", + "multi_lan", +] as const; + +/** + * Model ids whose native multimodal-generation API accepts `ocr_options`. + * `qwen-vl-ocr-2024-10-28` predates the built-in tasks, and any id outside + * this set (including future snapshots) is refused locally instead of being + * guessed at. + */ +const OCR_SUPPORTED_MODELS: readonly string[] = [ + "qwen-vl-ocr", + "qwen-vl-ocr-2025-11-20", + "qwen3.5-ocr", +]; + +/** + * Since qwen3.5-ocr a built-in task and a user prompt coexist; earlier models + * use a fixed internal prompt per task, so an explicit prompt would be + * silently overridden by the service. + */ +const OCR_PROMPT_AWARE_MODELS: readonly string[] = ["qwen3.5-ocr"]; + +/** Documented ceiling for a Base64 data URI on Qwen-OCR image input. */ +const MAX_DATA_URI_BYTES = 10 * 1024 * 1024; + +/** Base64 inflates payloads by roughly a third; used as a read-only precheck. */ +const BASE64_INFLATE_RATIO = 4 / 3; + const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv", ".wmv"]); function isVideoInput(input: string): boolean { @@ -32,13 +84,207 @@ async function toImageUrl(image: string): Promise { return imageFileToDataUri(image); } +function isRemoteOrInline(image: string): boolean { + return ( + image.startsWith("http://") || + image.startsWith("https://") || + image.startsWith("data:") || + image.startsWith("oss://") + ); +} + +/** + * Read-only estimate of the encoded size, used only to *route* a local file: + * over budget goes straight to the upload path instead of encoding first. The + * authoritative decision still compares the real `Buffer.byteLength` of the + * produced data URI in {@link resolveOcrImage}. + */ +function exceedsDataUriBudget(imagePath: string): boolean { + try { + return statSync(imagePath).size * BASE64_INFLATE_RATIO > MAX_DATA_URI_BYTES; + } catch { + return false; + } +} + +/** + * The native multimodal-generation route is a plain DashScope capability. Both + * Token Plan shapes (token-plan endpoint and `sk-sp-` key) were verified unable + * to serve it, so the boundary is raised locally with an actionable hint rather + * than passing through an opaque server error. Checked before dry-run: a preview + * of a request that can never succeed would advertise the capability. + */ +function assertNativeOcrAvailable(isTokenPlan: boolean, localize: Localize): void { + if (!isTokenPlan) return; + throw new BailianError( + localize({ + "en-US": + "Built-in OCR tasks require the native DashScope multimodal-generation API, which a Token Plan connection (endpoint or API key) does not provide.", + "zh-CN": + "内置 OCR 任务需要 DashScope 原生多模态接口,Token Plan 连接(端点或 API Key)不提供该能力。", + }), + ExitCode.USAGE, + localize({ + "en-US": + "Run the image description without --ocr-task on this profile, or switch to a config profile with a standard DashScope API key.", + "zh-CN": "该配置下去掉 --ocr-task 走图像描述,或切换到含标准 DashScope API Key 的配置。", + }), + ); +} + +/** + * OCR input contract: an http(s) URL, an in-budget data URI, an already-resolved + * `oss://` URL, or a local path that exists. `isLocalFile` reports false for a + * missing path, so without this check a typo would be forwarded verbatim as if it + * were a URL. A missing file is argument validation here (exit USAGE), matching + * the established `--video` not-found branch in this command. + */ +function assertOcrImageSource(image: string | undefined, localize: Localize): string { + if (image === undefined) { + throw new BailianError( + localize({ + "en-US": "Built-in OCR tasks need an image passed to --image.", + "zh-CN": "内置 OCR 任务需要通过 --image 传入图片。", + }), + ExitCode.USAGE, + ); + } + // An inline payload must respect the same documented ceiling as an encoded + // local file, and it is checked here so dry-run catches it too: identical + // bytes passed as a path would take the upload fallback instead of failing + // server-side with an unexplainable error. Only the length is reported, so a + // data URI never leaks into diagnostics. + if (image.startsWith("data:") && Buffer.byteLength(image, "utf8") > MAX_DATA_URI_BYTES) { + throw new BailianError( + localize({ + "en-US": `The inline data URI is ${Buffer.byteLength(image, "utf8")} bytes, which exceeds the ${MAX_DATA_URI_BYTES}-byte limit for encoded image input.`, + "zh-CN": `内联 data URI 长 ${Buffer.byteLength(image, "utf8")} 字节,超过编码后图片输入的 ${MAX_DATA_URI_BYTES} 字节上限。`, + }), + ExitCode.USAGE, + localize({ + "en-US": + "Pass a local image path (large files are uploaded to temporary storage automatically) or an http(s) image URL.", + "zh-CN": "请改传本地图片路径(大图会自动上传临时存储)或 http(s) 图片 URL。", + }), + ); + } + if (isRemoteOrInline(image) || existsSync(image)) return image; + throw new BailianError( + localize({ "en-US": `Image file not found: ${image}`, "zh-CN": `图片文件不存在:${image}` }), + ExitCode.USAGE, + localize({ + "en-US": "Pass an existing local path, an http(s) image URL or a data URI.", + "zh-CN": "请传入存在的本地路径、http(s) 图片 URL 或 data URI。", + }), + ); +} + +/** Read-only dry-run stand-in for the image value; never encodes or uploads. */ +function ocrImagePreview(image: string): string { + if (image.startsWith("data:")) return redactDataUri(image); + if (isRemoteOrInline(image)) return image; + return ``; +} + +/** + * Resolve the image for the native request. Small local files become data URIs, + * which is the input form documented for Qwen-OCR; anything whose *encoded* size + * would exceed the data URI budget falls back to the shared temporary upload + * (`resolveImageInput`), the same route `bl omni translate` already uses against + * this endpoint. The client adds `X-DashScope-OssResourceResolve` automatically, + * so large local images keep working instead of regressing against plain + * describe, which uploads them today. + */ +async function resolveOcrImage( + uploadLocalFile: (path: string) => Promise, + image: string, +): Promise { + if (isRemoteOrInline(image)) return image; + if (exceedsDataUriBudget(image)) return uploadLocalFile(image); + const dataUri = imageFileToDataUri(image); + if (Buffer.byteLength(dataUri, "utf8") <= MAX_DATA_URI_BYTES) return dataUri; + return uploadLocalFile(image); +} + +function buildOcrRequest(input: { + model: string; + task: OcrBuiltinTask; + image: string; + minPixels?: number; + maxPixels?: number; + text?: string; +}): NativeOcrRequest { + const content: NativeOcrRequest["input"]["messages"][number]["content"] = [ + { + image: input.image, + ...(input.minPixels !== undefined ? { min_pixels: input.minPixels } : {}), + ...(input.maxPixels !== undefined ? { max_pixels: input.maxPixels } : {}), + }, + // Only models that combine a task with an instruction receive one; the + // earlier generations would silently override it with a fixed task prompt. + ...(input.text !== undefined ? [{ text: input.text }] : []), + ]; + return { + model: input.model, + input: { messages: [{ role: "user", content }] }, + parameters: { ocr_options: { task: input.task } }, + }; +} + +function assertPositiveIntegers( + value: number | undefined, + flag: string, +): LocalizedText | undefined { + if (value === undefined) return undefined; + if (!Number.isInteger(value) || value <= 0) { + return { + "en-US": `--${flag} must be a positive integer.`, + "zh-CN": `参数 --${flag} 必须为正整数。`, + }; + } + return undefined; +} + +/** + * The native OCR endpoint answers under `output.choices`, while the compatible + * chat path answers with a top-level `choices` array. Text mode merges the + * content parts and falls back to readable JSON for structured results, so an + * `ocr_result` object never renders as "[object Object]". + */ +/** + * Merged `content[].text` wins over `ocr_result` for the text rendering. That is + * deliberate and verified against the live service: for `key_information_extraction` + * and `advanced_recognition` the `text` part already mirrors the structured payload + * (a fenced JSON block carrying `kv_result` / `words_info`), so choosing `text` does + * not hide the extraction result. `ocr_result` is only serialized when no text part + * is present. JSON output always carries the full service envelope either way. + */ +function ocrTextPreview(response: NativeOcrResponse): string { + const parts = response.output?.choices?.[0]?.message?.content ?? []; + const texts = parts + .map((part) => part.text) + .filter((text): text is string => typeof text === "string" && text.length > 0); + if (texts.length > 0) return texts.join("\n"); + const structured = parts.filter((part) => part.ocr_result !== undefined); + if (structured.length === 1) return JSON.stringify(structured[0]!.ocr_result, null, 2); + if (structured.length > 1) { + return JSON.stringify( + structured.map((part) => part.ocr_result as OcrResult), + null, + 2, + ); + } + return ""; +} + export default defineCommand({ description: { "en-US": "Describe an image or video using Qwen-VL", "zh-CN": "使用 Qwen-VL 描述图片或视频", }, auth: "apiKey", - usageArgs: "--image [--video ] [--prompt ]", + usageArgs: + "--image [--video ] [--prompt ] [--ocr-task ] [--min-pixels ] [--max-pixels ]", flags: { image: { type: "string", @@ -65,8 +311,37 @@ export default defineCommand({ type: "string", valueHint: "", description: { - "en-US": "Vision model (default: qwen3-vl-plus)", - "zh-CN": "视觉模型(默认:qwen3-vl-plus)", + "en-US": + "Vision model (default: qwen3-vl-plus; with --ocr-task the default becomes qwen-vl-ocr and only qwen-vl-ocr, qwen-vl-ocr-2025-11-20 and qwen3.5-ocr are accepted)", + "zh-CN": + "视觉模型(默认 qwen3-vl-plus;带 --ocr-task 时默认改为 qwen-vl-ocr,且仅支持 qwen-vl-ocr、qwen-vl-ocr-2025-11-20、qwen3.5-ocr)", + }, + }, + ocrTask: { + type: "string", + // Help renders the choices union instead of this hint (registry.ts:32); + // the field itself is required by ValueFlag. + valueHint: "", + choices: OCR_TASKS, + description: { + "en-US": "Built-in OCR task (uses the native API)", + "zh-CN": "内置 OCR 任务(使用原生接口)", + }, + }, + minPixels: { + type: "number", + valueHint: "", + description: { + "en-US": "Minimum pixels for the image item (bounds depend on the model)", + "zh-CN": "图片项的最小像素(合法区间随型号变化)", + }, + }, + maxPixels: { + type: "number", + valueHint: "", + description: { + "en-US": "Maximum pixels for the image item (bounds depend on the model)", + "zh-CN": "图片项的最大像素(合法区间随型号变化)", }, }, }, @@ -85,19 +360,117 @@ export default defineCommand({ "en-US": '--image photo.png --prompt "Extract the text" --model qwen3-vl-plus', "zh-CN": '--image photo.png --prompt "提取文字" --model qwen3-vl-plus', }, + "--image receipt.png --ocr-task key_information_extraction", + { + "en-US": + '--image table.png --ocr-task table_parsing --model qwen3.5-ocr --min-pixels 3072 --max-pixels 8388608 --prompt "Convert the table to HTML"', + "zh-CN": + '--image table.png --ocr-task table_parsing --model qwen3.5-ocr --min-pixels 3072 --max-pixels 8388608 --prompt "把表格转成 HTML"', + }, ], - validate: (f) => - !f.image && !(f.video as string[] | undefined)?.length - ? "Provide --image or --video." - : undefined, + notes: [ + { + "en-US": + "--ocr-task switches to the native DashScope multimodal-generation API: the response nests choices under output.choices instead of a top-level choices array, so parse the two modes differently.", + "zh-CN": + "--ocr-task 会切换到 DashScope 原生多模态接口:响应的 choices 位于 output 下,不再是顶层 choices,两种模式需分别解析。", + }, + { + "en-US": + "Without --ocr-task, --dry-run prints an input summary rather than the wire body: min_pixels / max_pixels appear at the top of that summary, while the actual request attaches them to the image content item next to type and image_url. With --ocr-task the previewed body is the real request.", + "zh-CN": + "不带 --ocr-task 时,--dry-run 输出的是入参摘要而非真实请求体:摘要里 min_pixels / max_pixels 位于顶层,实际请求会把它们挂在图片 content 项上(与 type、image_url 同级)。带 --ocr-task 时预览的 body 就是真实请求。", + }, + { + "en-US": + "The qwen-vl-ocr default applies only when --ocr-task is set; without it the model, request path and output stay exactly as before.", + "zh-CN": "qwen-vl-ocr 默认仅在带 --ocr-task 时生效;不带时型号、请求路径与输出保持不变。", + }, + { + "en-US": + "Pixel bounds are model-specific (qwen3.5-ocr and qwen-vl-ocr-2025-11-20 start at 3072, qwen-vl-ocr at 3136, qwen3-vl-plus at 65536) and are not checked locally; the service reports out-of-range values.", + "zh-CN": + "像素区间与型号绑定(qwen3.5-ocr 与 qwen-vl-ocr-2025-11-20 下限 3072,qwen-vl-ocr 为 3136,qwen3-vl-plus 为 65536),本地不校验,越界由服务端返回原始错误。", + }, + { + "en-US": + "Built-in OCR tasks take a single image only, reject --video, and need a standard DashScope connection (not Token Plan). Output length is capped per model (qwen-vl-ocr up to 4096 tokens), so long tables or documents can be truncated; the CLI warns when the service reports length truncation.", + "zh-CN": + "内置 OCR 任务仅支持单张图片,不接受 --video,且需普通 DashScope 连接(不支持 Token Plan)。输出长度按型号封顶(qwen-vl-ocr 最大 4096 Token),长表格或文档可能被截断;服务端判定截断时 CLI 会告警。", + }, + { + "en-US": + "Not supported in this release: enable_rotate, custom extraction schema (ocr_options.task_config.result_schema), multi-turn OCR and PDF input.", + "zh-CN": + "本期不支持:旋转矫正、自定义抽取 schema(ocr_options.task_config.result_schema)、多轮 OCR 与 PDF 输入。", + }, + { + "en-US": + "OCR results often contain personal data (identity documents, invoices). Keep the JSON out of project logs and fixtures, and never run live tests against real credentials or identity documents.", + "zh-CN": + "OCR 结果常含个人信息(证件、票据)。请勿把结果写入项目日志与测试素材,live 测试不要使用真实证件。", + }, + ], + validate: (flags) => { + if (!flags.image && !(flags.video ?? []).length) { + return { + "en-US": "Provide --image or --video.", + "zh-CN": "请提供 --image 或 --video。", + }; + } + + // A video file passed to --image is reclassified as video input at run time, + // so pixel flags and OCR tasks would silently lose their image item. + const imageIsVideo = flags.image !== undefined && isVideoInput(flags.image); + const hasVideo = (flags.video ?? []).length > 0 || imageIsVideo; + + const minPixelsError = assertPositiveIntegers(flags.minPixels, "min-pixels"); + if (minPixelsError) return minPixelsError; + const maxPixelsError = assertPositiveIntegers(flags.maxPixels, "max-pixels"); + if (maxPixelsError) return maxPixelsError; + + const hasPixels = flags.minPixels !== undefined || flags.maxPixels !== undefined; + if (hasPixels && flags.minPixels !== undefined && flags.maxPixels !== undefined) { + if (flags.minPixels > flags.maxPixels) { + return { + "en-US": "--min-pixels must not exceed --max-pixels.", + "zh-CN": "--min-pixels 不能大于 --max-pixels。", + }; + } + } + if (hasPixels && (flags.image === undefined || imageIsVideo)) { + return { + "en-US": + "--min-pixels / --max-pixels belong to an image item. Provide --image with an image (video input does not accept them).", + "zh-CN": + "--min-pixels / --max-pixels 属于图片项。请为 --image 传入图片(视频输入不接受该参数)。", + }; + } + + if (flags.ocrTask !== undefined) { + if (hasVideo) { + return { + "en-US": + "Built-in OCR tasks accept image input only. Remove --video, or pass an image to --image.", + "zh-CN": "内置 OCR 任务仅接受图片输入。请去掉 --video,或给 --image 传入图片。", + }; + } + const model = flags.model || DEFAULT_OCR_MODEL; + if (!OCR_SUPPORTED_MODELS.includes(model)) { + return { + "en-US": `--ocr-task is supported by ${OCR_SUPPORTED_MODELS.join(", ")}. Got "${model}".`, + "zh-CN": `--ocr-task 仅支持 ${OCR_SUPPORTED_MODELS.join("、")},当前为 "${model}"。`, + }; + } + } + + return undefined; + }, async run(ctx) { const { settings, flags } = ctx; let image = flags.image; const videoInputs = flags.video ?? []; - const model = - flags.model || - (ctx.client.usesTokenPlanEndpoint() ? settings.defaultTextModel : undefined) || - "qwen3-vl-plus"; + const ocrTask = flags.ocrTask; // Auto-detect: if --image was given a video file, treat it as --video if (image && isVideoInput(image)) { @@ -105,21 +478,114 @@ export default defineCommand({ image = undefined; } + // OCR mode never borrows the Token Plan text-model fallback; its own default + // is the stable OCR model id and stays local to this mode. + const model = + ocrTask !== undefined + ? flags.model || DEFAULT_OCR_MODEL + : flags.model || + (ctx.client.usesTokenPlanEndpoint() ? settings.defaultTextModel : undefined) || + DEFAULT_VISION_MODEL; + const hasVideo = videoInputs.length > 0; const defaultPrompt = hasVideo ? "Describe the video." : "Describe the image."; const prompt = flags.prompt || defaultPrompt; const format = settings.output; + // Checked before dry-run so a Token Plan connection never previews a request + // that cannot succeed. + if (ocrTask !== undefined) { + assertNativeOcrAvailable(ctx.client.usesTokenPlanConnection(), ctx.localize); + } + + // An empty --prompt counts as unset, the same way the compatible path below + // treats it (`flags.prompt || defaultPrompt`). Otherwise a shell variable that + // expanded to "" would add a useless empty text item, or claim a prompt was + // dropped when there was nothing to drop. + const userPrompt = flags.prompt || undefined; + + // A built-in task carries its own prompt on the pre-qwen3.5 generations, so + // an explicit --prompt would be silently overridden. Drop it from the request + // and say so instead of pretending the combination works. + const promptAware = OCR_PROMPT_AWARE_MODELS.includes(model); + const ocrPrompt = ocrTask !== undefined && promptAware ? userPrompt : undefined; + if (ocrTask !== undefined && !promptAware && userPrompt !== undefined) { + ctx.output.warning({ + code: "OCR_TASK_PROMPT_IGNORED", + message: ctx.localize({ + "en-US": `Model "${model}" applies a fixed prompt for built-in OCR tasks, so --prompt is not sent. Use qwen3.5-ocr to combine a task with an instruction.`, + "zh-CN": `型号 "${model}" 的内置 OCR 任务使用固定 prompt,--prompt 不会被发送。需要任务与指令组合请改用 qwen3.5-ocr。`, + }), + }); + } + if (settings.dryRun) { + if (ocrTask === undefined) { + // Legacy summary shape: identical keys unless the new flags are given. + ctx.output.result({ + request: { + prompt, + image: image ? redactDataUri(image) : undefined, + video: videoInputs.length ? videoInputs.map(redactDataUri) : undefined, + model, + ...(flags.minPixels !== undefined ? { min_pixels: flags.minPixels } : {}), + ...(flags.maxPixels !== undefined ? { max_pixels: flags.maxPixels } : {}), + }, + }); + return; + } ctx.output.result({ - request: { - prompt, - image: image ? redactDataUri(image) : undefined, - video: videoInputs.length ? videoInputs.map(redactDataUri) : undefined, + endpoint: ctx.client.url(multimodalGenerationPath()), + request: buildOcrRequest({ model, - }, + task: ocrTask, + image: ocrImagePreview(assertOcrImageSource(image, ctx.localize)), + minPixels: flags.minPixels, + maxPixels: flags.maxPixels, + text: ocrPrompt, + }), + }); + return; + } + + if (ocrTask !== undefined) { + // Synchronous by design: no X-DashScope-Async header and no task polling, + // unlike the omni translate flow that shares this endpoint path. + const imageSource = assertOcrImageSource(image, ctx.localize); + const request = buildOcrRequest({ + model, + task: ocrTask, + image: await resolveOcrImage( + (path) => ctx.client.resolveImageInput(path, model), + imageSource, + ), + minPixels: flags.minPixels, + maxPixels: flags.maxPixels, + text: ocrPrompt, + }); + const response = await ctx.client.requestJson({ + path: multimodalGenerationPath(), + method: "POST", + body: request, }); + // qwen-vl-ocr caps output at 4096 tokens and that ceiling is not + // self-service, so a truncated table or document must never look complete. + if (response.output?.choices?.[0]?.finish_reason === "length") { + ctx.output.warning({ + code: "OCR_OUTPUT_TRUNCATED", + message: ctx.localize({ + "en-US": + "The OCR result was truncated by the model output limit. Try qwen3.5-ocr, or split the source into smaller images.", + "zh-CN": + "OCR 结果被模型输出上限截断。建议改用 qwen3.5-ocr,或将原图拆分为多张更小图片。", + }), + }); + } + ctx.output.result( + response, + format === "text" ? { text: ocrTextPreview(response) } : undefined, + ); return; } @@ -153,7 +619,14 @@ export default defineCommand({ } } - contentArray.push({ type: "image_url", image_url: { url: finalImageUrl } }); + // On the compatible chat path the pixel keys sit next to `type` and + // `image_url`, not inside `image_url` and not at request level. + contentArray.push({ + type: "image_url", + image_url: { url: finalImageUrl }, + ...(flags.minPixels !== undefined ? { min_pixels: flags.minPixels } : {}), + ...(flags.maxPixels !== undefined ? { max_pixels: flags.maxPixels } : {}), + }); } // ---- Text prompt ---- diff --git a/packages/commands/tests/e2e/vision-describe.e2e.test.ts b/packages/commands/tests/e2e/vision-describe.e2e.test.ts index 95d7bf983..df010162f 100644 --- a/packages/commands/tests/e2e/vision-describe.e2e.test.ts +++ b/packages/commands/tests/e2e/vision-describe.e2e.test.ts @@ -1,7 +1,12 @@ import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, test } from "vite-plus/test"; -import { makeE2eOutputDir, parseStdoutJson, runCommandE2e } from "./helpers.ts"; +import { + makeE2eOutputDir, + parseStdoutJson, + runCommandE2e, + runCommandInProcess, +} from "./helpers.ts"; import { VISION_ROUTES } from "./topic-routes.ts"; describe("e2e: vision describe", () => { @@ -42,4 +47,32 @@ describe("e2e: vision describe", () => { const data = parseStdoutJson<{ request?: { model?: string } }>(stdout); expect(data.request?.model).toBe("qwen3.8-max"); }); + + // Baseline for the OCR flag work: the legacy dry-run summary must stay + // key-for-key identical when none of the new flags are passed. This is the + // gate the OCR suite compares against, so it lives with the subprocess case + // that remains this topic's representative process-boundary test. + test("dry-run 摘要在不使用新参数时保持既有形状", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/image.png", + "--api-key", + "sk-e2e", + "--base-url", + "https://dashscope.aliyuncs.com", + "--dry-run", + "--output", + "json", + "--quiet", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson<{ request?: Record }>(stdout); + expect(data.request).toEqual({ + prompt: "Describe the image.", + image: "https://example.com/image.png", + model: "qwen3-vl-plus", + }); + }); }); diff --git a/packages/commands/tests/e2e/vision-ocr.e2e.test.ts b/packages/commands/tests/e2e/vision-ocr.e2e.test.ts new file mode 100644 index 000000000..a76e5e7c9 --- /dev/null +++ b/packages/commands/tests/e2e/vision-ocr.e2e.test.ts @@ -0,0 +1,803 @@ +import { writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { join } from "node:path"; +import { describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EMediaEnabled, + isDashScopeE2EReady, + makeE2eOutputDir, + parseStdoutJson, + runCommandE2e, + runCommandHelp, + runCommandInProcess, +} from "./helpers.ts"; +import { VISION_ROUTES } from "./topic-routes.ts"; + +const NATIVE_OCR_PATH = "/api/v1/services/aigc/multimodal-generation/generation"; +const CHAT_PATH = "/compatible-mode/v1/chat/completions"; + +interface CapturedRequest { + path: string; + method: string; + body: Record; + headers: Record; +} + +type Responder = (request: CapturedRequest) => { status: number; payload: unknown }; + +interface MockServer { + baseUrl: string; + requests: CapturedRequest[]; + close(): Promise; +} + +/** Local HTTP stand-in so the offline matrix never reaches the network. */ +async function startMockServer(respond: Responder): Promise { + const requests: CapturedRequest[] = []; + const server = createServer((incoming, outgoing) => { + const chunks: Buffer[] = []; + incoming.on("data", (chunk: Buffer) => chunks.push(chunk)); + incoming.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + const captured: CapturedRequest = { + path: incoming.url ?? "", + method: incoming.method ?? "GET", + body: raw ? (JSON.parse(raw) as Record) : {}, + headers: incoming.headers as Record, + }; + requests.push(captured); + const { status, payload } = respond(captured); + outgoing.writeHead(status, { "Content-Type": "application/json" }); + outgoing.end(JSON.stringify(payload)); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + return { + baseUrl: `http://127.0.0.1:${address.port}`, + requests, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +const nativeTextResponse = { + output: { + choices: [ + { + finish_reason: "stop", + message: { role: "assistant", content: [{ text: "发票抬头\n金额 100.00" }] }, + }, + ], + }, + usage: { input_tokens: 812, output_tokens: 12 }, + request_id: "req-ocr-text", +}; + +const nativeStructuredResponse = { + output: { + choices: [ + { + finish_reason: "stop", + message: { + role: "assistant", + content: [{ ocr_result: { kv_result: { 姓名: "示例", 证件号: "123456789" } } }], + }, + }, + ], + }, + request_id: "req-ocr-kv", +}; + +const truncatedResponse = { + output: { + choices: [ + { + finish_reason: "length", + message: { role: "assistant", content: [{ text: "
half" }] }, + }, + ], + }, + request_id: "req-ocr-truncated", +}; + +function imageContentItem(body: Record): Record { + const input = body.input as { messages: Array<{ content: Array> }> }; + return input.messages[0]!.content[0]!; +} + +/** Native envelope: choices live under output, unlike the chat envelope. */ +interface NativeEnvelope { + output?: { + choices?: NativeChoice[]; + }; + usage?: Record; + request_id?: string; + /** Must stay absent in OCR mode: this is not a chat completion. */ + choices?: unknown; +} + +interface NativeChoice { + message?: { content?: NativeContentPart[] }; +} + +interface NativeContentPart { + text?: string; + ocr_result?: { kv_result?: Record }; +} + +function promptTextItems(body: Record): Array> { + const input = body.input as { messages: Array<{ content: Array> }> }; + return input.messages[0]!.content.filter((item) => item.text !== undefined); +} + +describe("e2e: vision ocr task routing", () => { + test("help 暴露三个新参数与七个内置任务", async () => { + // runCommandHelp renders in-worker and returns the rendered page on stderr. + const { stderr: help } = await runCommandHelp(VISION_ROUTES, ["vision", "describe", "--help"]); + expect(help).toContain("--ocr-task"); + expect(help).toContain("--min-pixels"); + expect(help).toContain("--max-pixels"); + // choices replace the value hint in help output, so the union must be visible. + expect(help).toContain("advanced_recognition"); + expect(help).toContain("key_information_extraction"); + expect(help).toContain("multi_lan"); + expect(help).toContain("native API"); + }); + + test("未知任务由解析层拒绝(退出码 2)", async () => { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "invoice_parser", + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(exitCode, stderr).toBe(2); + expect(stderr).toContain("--ocr-task"); + }); + + test("像素参数要求正整数且 min<=max", async () => { + const invalid = [ + ["--min-pixels", "0"], + ["--min-pixels", "-5"], + ["--min-pixels", "1.5"], + ["--min-pixels", "8388608", "--max-pixels", "3072"], + ]; + for (const args of invalid) { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + ...args, + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(exitCode, `${args.join(" ")} → ${stderr}`).toBe(2); + } + }); + + test("只有视频输入时不接受像素参数", async () => { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--video", + "https://example.com/clip.mp4", + "--min-pixels", + "3072", + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(exitCode, stderr).toBe(2); + expect(stderr).toContain("--min-pixels"); + }); + + test("内置任务拒绝视频输入而不是静默忽略任务", async () => { + const viaVideo = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--video", + "https://example.com/clip.mp4", + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(viaVideo.exitCode, viaVideo.stderr).toBe(2); + expect(viaVideo.stderr).toContain("image"); + + // An image argument holding a video file is reclassified, which would drop + // the image item the task needs. + const imageIsVideo = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/clip.mp4", + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(imageIsVideo.exitCode, imageIsVideo.stderr).toBe(2); + }); + + test("型号允许表:表外型号在任何请求之前拒绝", async () => { + for (const model of ["qwen-vl-ocr-2024-10-28", "qwen3-vl-plus", "qwen-vl-ocr-latest"]) { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "table_parsing", + "--model", + model, + "--api-key", + "sk-e2e", + "--dry-run", + ]); + expect(exitCode, `${model} → ${stderr}`).toBe(2); + expect(stderr, model).toContain("--ocr-task"); + } + }); + + test("OCR dry-run 产出原生 body 且不触网、不读文件、不上传", async () => { + const server = await startMockServer(() => ({ status: 200, payload: {} })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/receipt.png", + "--ocr-task", + "key_information_extraction", + "--min-pixels", + "3136", + "--max-pixels", + "6422528", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(server.requests).toHaveLength(0); + const preview = parseStdoutJson<{ + endpoint?: string; + request?: Record; + }>(stdout); + expect(preview.endpoint).toBe(`${server.baseUrl}${NATIVE_OCR_PATH}`); + expect(preview.request?.model).toBe("qwen-vl-ocr"); + expect(preview.request?.parameters).toEqual({ + ocr_options: { task: "key_information_extraction" }, + }); + expect(imageContentItem(preview.request!)).toEqual({ + image: "https://example.com/receipt.png", + min_pixels: 3136, + max_pixels: 6422528, + }); + // Built-in tasks bring their own prompt; never inject the Describe default. + expect(promptTextItems(preview.request!)).toEqual([]); + } finally { + await server.close(); + } + }); + + test("本地图片在 dry-run 里只留来源标记,Data URI 不外泄", async () => { + const dir = makeE2eOutputDir("vision-ocr-dry-local"); + const imagePath = join(dir, "receipt.png"); + writeFileSync(imagePath, Buffer.from("89504e470d0a1a0a0000000d49484452", "hex")); + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + imagePath, + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(stdout).toContain(" { + const dir = makeE2eOutputDir("vision-ocr-small-local"); + const imagePath = join(dir, "receipt.png"); + writeFileSync(imagePath, Buffer.from("89504e470d0a1a0a0000000d49484452", "hex")); + const server = await startMockServer(() => ({ status: 200, payload: nativeTextResponse })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + imagePath, + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + // A single request proves the upload endpoint was never called. + expect(server.requests).toHaveLength(1); + const [request] = server.requests; + expect(request!.path).toBe(NATIVE_OCR_PATH); + expect(String(imageContentItem(request!.body).image)).toMatch(/^data:image\/png;base64,/); + expect(stdout).toContain("req-ocr-text"); + } finally { + await server.close(); + } + }); + + // The allowlist has three entries; the middle snapshot must pass too, not only + // the default and the prompt-aware model. + test("允许表内的快照型号正向通过", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/page.png", + "--ocr-task", + "table_parsing", + "--model", + "qwen-vl-ocr-2025-11-20", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const preview = parseStdoutJson<{ request?: Record }>(stdout); + expect(preview.request?.model).toBe("qwen-vl-ocr-2025-11-20"); + expect(preview.request?.parameters).toEqual({ ocr_options: { task: "table_parsing" } }); + }); + + test("不存在的图片路径报 USAGE,且不发送裸路径", async () => { + const server = await startMockServer(() => ({ status: 200, payload: nativeTextResponse })); + try { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + join(makeE2eOutputDir("vision-ocr-missing"), "absent.png"), + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(2); + expect(server.requests).toHaveLength(0); + } finally { + await server.close(); + } + }); + + test("固定 prompt 型号剥离 --prompt,qwen3.5-ocr 保留组合", async () => { + const stripped = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "table_parsing", + "--prompt", + "把表格转成 HTML", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(stripped.exitCode, stripped.stderr).toBe(0); + const strippedBody = parseStdoutJson<{ request?: Record }>(stripped.stdout); + expect(promptTextItems(strippedBody.request!)).toEqual([]); + expect(stripped.stderr).toContain("OCR_TASK_PROMPT_IGNORED"); + + const combined = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "table_parsing", + "--model", + "qwen3.5-ocr", + "--prompt", + "把表格转成 HTML", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(combined.exitCode, combined.stderr).toBe(0); + const combinedBody = parseStdoutJson<{ request?: Record }>(combined.stdout); + expect(combinedBody.request?.model).toBe("qwen3.5-ocr"); + expect(promptTextItems(combinedBody.request!)).toEqual([{ text: "把表格转成 HTML" }]); + expect(combined.stderr).not.toContain("OCR_TASK_PROMPT_IGNORED"); + }); + + // An empty --prompt means "unset" (a shell variable that expanded to ""), so it + // must not add an empty text item nor claim a prompt was dropped. + test("空 --prompt 等同未传", async () => { + const combined = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "table_parsing", + "--model", + "qwen3.5-ocr", + "--prompt", + "", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(combined.exitCode, combined.stderr).toBe(0); + const body = parseStdoutJson<{ request?: Record }>(combined.stdout); + expect(promptTextItems(body.request!)).toEqual([]); + + const fixed = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "text_recognition", + "--prompt", + "", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(fixed.exitCode, fixed.stderr).toBe(0); + expect(fixed.stderr).not.toContain("OCR_TASK_PROMPT_IGNORED"); + }); + + // Reachable in-process (and by any programmatic caller) even though the OS + // argument limit blocks such a long argv; the payload must not be echoed back. + test("超过编码上限的内联 data URI 本地拒绝且不回显载荷", async () => { + const oversized = `data:image/png;base64,${"A".repeat(11 * 1024 * 1024)}`; + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + oversized, + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(2); + expect(stderr).toContain("data URI"); + expect(stdout).not.toContain("AAAA"); + expect(stderr).not.toContain("AAAA"); + }); + + test("Token Plan 连接下 OCR 模式即使命令 dry-run 也拒绝", async () => { + const ocr = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "text_recognition", + "--api-key", + "sk-sp-e2e-placeholder", + "--dry-run", + "--output", + "json", + ]); + expect(ocr.exitCode, ocr.stderr).toBe(2); + // A preview of an impossible request would advertise the capability. + expect(ocr.stdout).toBe(""); + expect(ocr.stderr).toContain("Token Plan"); + + const plain = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--api-key", + "sk-sp-e2e-placeholder", + "--dry-run", + "--output", + "json", + ]); + expect(plain.exitCode, plain.stderr).toBe(0); + }); + + test("OCR 模式命中原生端点、同步、无 Async 头", async () => { + const server = await startMockServer(() => ({ status: 200, payload: nativeTextResponse })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/receipt.png", + "--ocr-task", + "text_recognition", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(server.requests).toHaveLength(1); + const [request] = server.requests; + expect(request!.path).toBe(NATIVE_OCR_PATH); + expect(request!.method).toBe("POST"); + expect(request!.headers["x-dashscope-async"]).toBeUndefined(); + expect(request!.body.parameters).toEqual({ ocr_options: { task: "text_recognition" } }); + // The service envelope is returned verbatim: callers must branch on mode. + const data = parseStdoutJson(stdout); + expect(data.request_id).toBe("req-ocr-text"); + expect(data.output?.choices?.[0]?.message?.content?.[0]?.text).toContain("金额 100.00"); + expect(data.choices).toBeUndefined(); + } finally { + await server.close(); + } + }); + + test("text 模式渲染 ocr_result 且不出现 [object Object]", async () => { + const server = await startMockServer(() => ({ + status: 200, + payload: nativeStructuredResponse, + })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/card.png", + "--ocr-task", + "key_information_extraction", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "text", + ]); + expect(exitCode, stderr).toBe(0); + expect(stdout).not.toContain("[object Object]"); + expect(stdout).toContain("kv_result"); + expect(stdout).toContain("证件号"); + } finally { + await server.close(); + } + }); + + test("输出被型号上限截断时告警", async () => { + const server = await startMockServer(() => ({ status: 200, payload: truncatedResponse })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/long-table.png", + "--ocr-task", + "table_parsing", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toContain("OCR_OUTPUT_TRUNCATED"); + const data = parseStdoutJson<{ request_id?: string }>(stdout); + expect(data.request_id).toBe("req-ocr-truncated"); + } finally { + await server.close(); + } + }); + + test("服务端错误原文透传,不被本地翻译", async () => { + const server = await startMockServer(() => ({ + status: 400, + payload: { code: "InvalidParameter", message: "min_pixels is out of range", request_id: "r" }, + })); + try { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/a.png", + "--ocr-task", + "text_recognition", + "--min-pixels", + "3072", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode).toBe(1); + expect(stderr).toContain("min_pixels is out of range"); + } finally { + await server.close(); + } + }); + + test("大图改走临时上传,不把超限 Data URI 内联", async () => { + const dir = makeE2eOutputDir("vision-ocr-large"); + const imagePath = join(dir, "scan.png"); + // Just over the encoded 10MB data-URI budget once Base64 inflates it. + writeFileSync(imagePath, Buffer.alloc(8 * 1024 * 1024 + 1024, 7)); + const server = await startMockServer((request) => + request.path.startsWith("/api/v1/uploads") + ? { status: 500, payload: { code: "MockUploadClosed", message: "upload closed in test" } } + : { status: 200, payload: nativeTextResponse }, + ); + try { + const { stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + imagePath, + "--ocr-task", + "document_parsing", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode).not.toBe(0); + // Chose the upload route instead of inlining a payload over the ceiling. + expect(server.requests.some((request) => request.path.startsWith("/api/v1/uploads"))).toBe( + true, + ); + expect(server.requests.some((request) => request.path === NATIVE_OCR_PATH)).toBe(false); + expect(stderr).toContain("upload"); + } finally { + await server.close(); + } + }); + + test("只给像素参数时仍走 Chat 兼容路径且像素挂在图片项上", async () => { + const server = await startMockServer(() => ({ + status: 200, + payload: { + id: "chat-1", + object: "chat.completion", + created: 1, + model: "qwen3-vl-plus", + choices: [ + { + index: 0, + message: { role: "assistant", content: "一张图" }, + finish_reason: "stop", + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }, + })); + try { + const { stdout, stderr, exitCode } = await runCommandInProcess(VISION_ROUTES, [ + "vision", + "describe", + "--image", + "https://example.com/photo.png", + "--min-pixels", + "65536", + "--max-pixels", + "2621440", + "--api-key", + "sk-e2e", + "--base-url", + server.baseUrl, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + expect(server.requests).toHaveLength(1); + const [request] = server.requests; + expect(request!.path).toBe(CHAT_PATH); + const messages = request!.body.messages as Array<{ content: Array> }>; + const imageItem = messages[0]!.content.find((item) => item.type === "image_url")!; + // Siblings of type/image_url, never nested inside image_url. + expect(imageItem.min_pixels).toBe(65536); + expect(imageItem.max_pixels).toBe(2621440); + expect(imageItem.image_url).toEqual({ url: "https://example.com/photo.png" }); + expect(request!.body.model).toBe("qwen3-vl-plus"); + // Legacy chat envelope keeps top-level choices for scripts. + expect(parseStdoutJson<{ choices?: unknown }>(stdout).choices).toBeDefined(); + } finally { + await server.close(); + } + }); +}); + +describe.skipIf(!isBailianE2EMediaEnabled() || !isDashScopeE2EReady())( + "e2e: vision ocr(DashScope 媒体)", + () => { + test("原生结构化 OCR 真实调用成功", async () => { + // Sample document image used by the official Qwen-OCR API reference. + const docImage = + "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg"; + const { stdout, stderr, exitCode } = await runCommandE2e(VISION_ROUTES, [ + "vision", + "describe", + "--image", + docImage, + "--ocr-task", + "text_recognition", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + expect(data.request_id).toBeTruthy(); + const text = data.output?.choices?.[0]?.message?.content?.[0]?.text ?? ""; + // Recognized content must exist, but exact wording is not a hard contract. + expect(text.trim().length).toBeGreaterThan(0); + }); + + test("信息抽取任务返回 ocr_result 结构", async () => { + const docImage = + "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg"; + const { stdout, stderr, exitCode } = await runCommandE2e(VISION_ROUTES, [ + "vision", + "describe", + "--image", + docImage, + "--ocr-task", + "key_information_extraction", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const data = parseStdoutJson(stdout); + const result = data.output?.choices?.[0]?.message?.content?.[0]?.ocr_result; + expect(result).toBeDefined(); + expect(typeof result?.kv_result).toBe("object"); + }); + }, +); diff --git a/packages/commands/tests/output/vision-ocr-output.test.ts b/packages/commands/tests/output/vision-ocr-output.test.ts new file mode 100644 index 000000000..1fc8084fe --- /dev/null +++ b/packages/commands/tests/output/vision-ocr-output.test.ts @@ -0,0 +1,240 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, expect, test } from "vite-plus/test"; +import { runCommandE2e, runCommandInProcess } from "../e2e/helpers.ts"; + +/** + * Output contract for the two response shapes `bl vision describe` can now + * return: the OpenAI-compatible chat envelope (top-level `choices`) and the + * native OCR envelope (`output.choices`). Scripts switch on the presence of + * `--ocr-task`, so both shapes are pinned here instead of only in E2E. + */ +const routes = { "vision describe": "visionDescribe" }; +const NATIVE_OCR_PATH = "/api/v1/services/aigc/multimodal-generation/generation"; +const CHAT_PATH = "/compatible-mode/v1/chat/completions"; + +const chatEnvelope = { + id: "chat-fixture", + object: "chat.completion", + model: "qwen3-vl-plus", + choices: [ + { index: 0, message: { role: "assistant", content: "一张图片" }, finish_reason: "stop" }, + ], + usage: { prompt_tokens: 2, completion_tokens: 3, total_tokens: 5 }, +}; + +const textEnvelope = { + output: { + choices: [ + { finish_reason: "stop", message: { role: "assistant", content: [{ text: "发票抬头" }] } }, + ], + }, + usage: { input_tokens: 10, output_tokens: 2 }, + request_id: "ocr-text-request", +}; + +const structuredEnvelope = { + output: { + choices: [ + { + finish_reason: "stop", + message: { + role: "assistant", + content: [{ ocr_result: { kv_result: { 金额: "100.00" } } }], + }, + }, + ], + }, + request_id: "ocr-kv-request", +}; + +const truncatedEnvelope = { + output: { + choices: [ + { + finish_reason: "length", + message: { role: "assistant", content: [{ text: "
half" }] }, + }, + ], + }, + request_id: "ocr-length-request", +}; + +interface CapturedRequest { + path: string; + method: string; + body: Record; +} + +let server: Server; +let origin = ""; +let directory = ""; +let requests: CapturedRequest[] = []; +let responseBody: unknown = textEnvelope; + +beforeEach(async () => { + directory = mkdtempSync(join(tmpdir(), "vision-ocr-output-")); + requests = []; + server = createServer((incoming, outgoing) => { + const chunks: Buffer[] = []; + incoming.on("data", (chunk: Buffer) => chunks.push(chunk)); + incoming.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + requests.push({ + path: incoming.url ?? "", + method: incoming.method ?? "GET", + body: raw ? (JSON.parse(raw) as Record) : {}, + }); + outgoing.writeHead(200, { "Content-Type": "application/json" }); + outgoing.end(JSON.stringify(responseBody)); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected loopback address"); + origin = `http://127.0.0.1:${address.port}`; +}); + +afterEach(async () => { + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + rmSync(directory, { recursive: true, force: true }); +}); + +function invoke( + flags: string[], + display: { format: "text" | "json"; quiet?: boolean }, + subprocess = false, +) { + const args = ["vision", "describe", ...flags, "--output", display.format]; + if (display.quiet) args.push("--quiet"); + // One subprocess case keeps the process-boundary stdout/stderr channel pinned + // without paying CLI startup for every display combination. + const run = subprocess ? runCommandE2e : runCommandInProcess; + return run( + routes, + args, + { + HOME: directory, + BAILIAN_CONFIG_DIR: directory, + DASHSCOPE_API_KEY: "sk-vision-ocr-placeholder", + DASHSCOPE_BASE_URL: origin, + DASHSCOPE_QUIET: "0", + DASHSCOPE_VERBOSE: "0", + BAILIAN_INSTALL_METHOD: "brew", + NODE_OPTIONS: "", + NODE_USE_ENV_PROXY: "0", + HTTP_PROXY: "", + http_proxy: "", + HTTPS_PROXY: "", + https_proxy: "", + ALL_PROXY: "", + all_proxy: "", + NO_PROXY: "", + no_proxy: "", + }, + {}, + ); +} + +const image = "https://example.com/invoice.png"; + +test("OCR mode returns the native envelope and posts one synchronous native request", async () => { + responseBody = textEnvelope; + const result = await invoke(["--image", image, "--ocr-task", "text_recognition"], { + format: "json", + quiet: true, + }); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stderr).toBe(""); + const data = JSON.parse(result.stdout) as Record; + // Contract: native mode nests choices under output and never emits the chat + // envelope's top-level choices, so parsers must branch on --ocr-task. + expect(data).toEqual(textEnvelope); + expect(data.choices).toBeUndefined(); + expect(requests).toHaveLength(1); + const [request] = requests; + expect(request!.path).toBe(NATIVE_OCR_PATH); + expect(request!.method).toBe("POST"); + expect(request!.body).toEqual({ + model: "qwen-vl-ocr", + input: { + messages: [ + { + role: "user", + content: [{ image }], + }, + ], + }, + parameters: { ocr_options: { task: "text_recognition" } }, + }); +}); + +test("OCR mode subprocess preserves the JSON result and diagnostics channel", async () => { + responseBody = truncatedEnvelope; + // Real subprocess: this is the case that pins the process-boundary split of + // result on stdout versus JSON diagnostics on stderr. + const result = await invoke( + ["--image", image, "--ocr-task", "table_parsing"], + { format: "json" }, + true, + ); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual(truncatedEnvelope); + // Warnings stay on stderr as one JSON object per line, never in the result. + const diagnostics = result.stderr.trim().split("\n").filter(Boolean); + expect(diagnostics.length).toBeGreaterThan(0); + for (const line of diagnostics) expect(() => JSON.parse(line)).not.toThrow(); + const warning = JSON.parse(diagnostics[0]!) as { + warning?: { code?: string; message?: string }; + }; + expect(warning.warning?.code).toBe("OCR_OUTPUT_TRUNCATED"); + // The result itself looks complete, so the message must name the remedy. + expect(warning.warning?.message).toContain("truncated"); +}); + +test("text mode merges content text", async () => { + responseBody = textEnvelope; + const result = await invoke(["--image", image, "--ocr-task", "text_recognition"], { + format: "text", + }); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout).toBe("发票抬头\n"); +}); + +test("text mode renders structured ocr_result readably instead of [object Object]", async () => { + responseBody = structuredEnvelope; + const result = await invoke(["--image", image, "--ocr-task", "key_information_extraction"], { + format: "text", + }); + expect(result.exitCode, result.stderr).toBe(0); + expect(result.stdout).not.toContain("[object Object]"); + expect(result.stdout).toContain("kv_result"); + expect(result.stdout).toContain("100.00"); +}); + +test("without --ocr-task the chat envelope and body shape are unchanged", async () => { + responseBody = chatEnvelope; + const result = await invoke(["--image", image, "--min-pixels", "65536"], { + format: "json", + quiet: true, + }); + expect(result.exitCode, result.stderr).toBe(0); + const data = JSON.parse(result.stdout) as { choices?: unknown; output?: unknown }; + expect(data.choices).toBeDefined(); + expect(data.output).toBeUndefined(); + expect(requests).toHaveLength(1); + const [request] = requests; + expect(request!.path).toBe(CHAT_PATH); + const messages = request!.body.messages as Array<{ content: Array> }>; + const imageItem = messages[0]!.content.find((item) => item.type === "image_url")!; + expect(imageItem).toEqual({ + type: "image_url", + image_url: { url: image }, + min_pixels: 65536, + }); +}); diff --git a/packages/core/src/telemetry/tracker.ts b/packages/core/src/telemetry/tracker.ts index f263a8b43..4527bdd68 100644 --- a/packages/core/src/telemetry/tracker.ts +++ b/packages/core/src/telemetry/tracker.ts @@ -64,6 +64,10 @@ const PARAM_ALLOWLIST = new Set([ "pitch", "rate", "volume", + // OCR selectors: enumerable task id plus numeric pixel thresholds. + "ocrTask", + "minPixels", + "maxPixels", // Console gateway API name (public service identifier, not PII) "api", // Mode / behavior flags diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 8edbd7bf5..8b898b7b5 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -7,7 +7,19 @@ export interface ChatMessage { export type ChatMessageContent = | { type: "text"; text: string } - | { type: "image_url"; image_url: { url: string } } + /** + * `min_pixels` / `max_pixels` are documented as siblings of `type` and + * `image_url` on the OpenAI-compatible chat API (not nested inside + * `image_url`, and not request-level). Bounds differ per model generation, + * so they stay optional and unvalidated here: the service rejects values + * outside the selected model's documented range. + */ + | { + type: "image_url"; + image_url: { url: string }; + min_pixels?: number; + max_pixels?: number; + } | { type: "input_audio"; input_audio: { data: string; format?: string } } | { type: "audio_url"; audio_url: { url: string } } | { type: "video"; video: string[] } @@ -208,6 +220,87 @@ export interface DashScopeImageSyncResponse { request_id: string; } +// ---- Native OCR (DashScope multimodal-generation) ---- + +/** + * Built-in OCR tasks accepted by `parameters.ocr_options.task` on the native + * multimodal-generation endpoint. The OpenAI-compatible chat completions API + * has no equivalent parameter and can only imitate a task through a prompt. + */ +export type OcrBuiltinTask = + | "advanced_recognition" + | "key_information_extraction" + | "table_parsing" + | "document_parsing" + | "formula_recognition" + | "text_recognition" + | "multi_lan"; + +/** Word-level geometry produced by `advanced_recognition`. */ +export interface OcrWordsInfo { + text?: string; + /** Corner coordinates: [x1, y1, x2, y2, x3, y3, x4, y4]. */ + location?: number[]; + /** Oriented box: [center_x, center_y, width, height, angle]. */ + rotate_rect?: number[]; +} + +/** + * Structured task payload. Only `key_information_extraction` and + * `advanced_recognition` return it; the other tasks answer with plain text, + * HTML or LaTeX inside `content[].text`. Unknown keys are preserved so a + * service-side field addition does not fail parsing. + */ +export interface OcrResult { + /** Extracted field name to value mapping. */ + kv_result?: Record; + /** Recognized words with their geometry. */ + words_info?: OcrWordsInfo[]; + [key: string]: unknown; +} + +export interface NativeOcrRequest { + model: string; + input: { + messages: Array<{ + role: "user"; + content: Array<{ + /** Image URL, `oss://` temporary URL or Base64 data URI. */ + image?: string; + /** User instruction; combined with a task only on qwen3.5-ocr. */ + text?: string; + /** Documented per model generation; forwarded without local bound checks. */ + min_pixels?: number; + max_pixels?: number; + }>; + }>; + }; + parameters: { + ocr_options: { task: OcrBuiltinTask }; + }; +} + +/** + * Synchronous native response envelope. It is intentionally *not* shaped like + * a chat completion: `choices` lives under `output`, which is why callers must + * branch on OCR mode when parsing. + */ +export interface NativeOcrResponse { + output: { + choices: Array<{ + finish_reason: string; + message: { + role: "assistant"; + content: Array<{ text?: string; ocr_result?: OcrResult }>; + }; + }>; + }; + usage?: Record; + request_id?: string; + code?: string; + message?: string; +} + // ---- Video (DashScope) ---- export interface DashScopeVideoRequest { diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index f223a6cd9..ac30407e6 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -70,6 +70,11 @@ export type { DashScopeVideoRequest, DashScopeVideoRetalkRequest, DashScopeVideoStyleTransformRequest, + NativeOcrRequest, + NativeOcrResponse, + OcrBuiltinTask, + OcrResult, + OcrWordsInfo, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 42b5d127b..1f8d99b02 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -164,6 +164,24 @@ More examples per command: see `reference/.md` (e.g. [`reference/text.md` 单次同步推理使用 `text chat --batch`,通过 message 或 messages-file 提供同一请求的对话上下文,不用于独立请求文件;命令等待该次响应,不创建任务 ID。Batch 不适用于 Token Plan;显式 Batch/自定义代理使用现有解析凭证,不推断 Key 类型。端点、请求超时及互斥参数见 `reference/text.md`。 +### 意图理解模型(tongyi-intent-detect-v3) + +走 `bl text chat`,没有独立的 intent 命令。它是 OpenAI 兼容 Chat 模型:候选意图与槽位**写在 system message 里**,响应是标签化伪 XML(tags / tool_call / content 三段)由调用方解析。模型卡明确**不支持 Function Calling**,所以不要把意图映射成 `tools` 数组。官方文档只给 SDK 示例,端点路径可由兼容模式推出;文档「支持的模型」写最大输出 1024、模型卡写 4096,二者矛盾,长度敏感场景先实测。地域仅见北京示例。 + +```bash +# 意图 + 槽位联合预测(响应含 tool_call 块与 content) +bl text chat --model tongyi-intent-detect-v3 \ + --system 'You are a helpful assistant. The tools you can use are as follows: [{"name":"alarm_set","description":"设置闹钟","parameters":{"time":{"type":"string","description":"时间,HH:mm"}}}]. Response in INTENT_MODE.' \ + --message "明天七点半叫我" --output json + +# 纯意图分类(答案就是列表里的一个 tag) +bl text chat --model tongyi-intent-detect-v3 \ + --system 'You should choose one tag from the tag list: [查询天气,设置闹钟,取消设置] just reply with the chosen tag.' \ + --message "明天七点半叫我" --output json +``` + +第一种取 `tool_call` / `content` 块解析;第二种直接读单个 tag。多轮补槽可用——把历史轮次一并放进 `--message`。 + ### Command metadata for agents Use the owning skill's [`reference/index.md`](reference/index.md) (or sibling skill reference trees), the matching `reference/.md`, diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 7e19e1a9e..adf3459b0 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -7,7 +7,8 @@ metadata: description: >- 阿里云百炼图片/视频/语音生成与理解入口:用户要生图、画图、生成照片、生成图片、AI 绘画、海报、头像、插画、 文生图(text-to-image)、图生图、改图、修图、多图合成、生成视频、文生视频、图生视频、参考生视频、视频编辑、风格转换、 - 配音、语音合成(TTS)、朗读、转写、语音识别(ASR),或图片理解、看图问答、视频理解、读视频、多模态理解, + 配音、语音合成(TTS)、朗读、转写、语音识别(ASR),或图片理解、看图问答、视频理解、读视频、多模态理解、 + 图片文字识别(OCR)、提取图片文字、票据/发票/证件信息抽取、表格转 HTML、公式转 LaTeX、文档转 LaTeX, 以及图片翻译、海报翻译、文档翻译、PDF 翻译、文件翻译、全模态翻译(`bl image translate` / `bl omni translate`)时使用 `bl image` / `bl video` / `bl speech` / `bl vision describe` / `bl omni`。 **默认行为:用户未指定服务商时,生成/编辑默认走本技能;视频理解与宿主放不了的音视频理解也走本技能。** @@ -53,6 +54,7 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Audio content generation (podcast/dialogue) | `bl speech generate` | `qwen-audio-3.1-tts-next` (text_prompt/references; not voice IDs) | | Speech recognition (ASR / transcription) | `bl speech recognize` | `fun-asr` | | Image describe | `bl vision describe` | `qwen3-vl-plus`;宿主能做且未点名 → host-first | +| Structured OCR from an image | `bl vision describe --ocr-task` | `qwen-vl-ocr`(仅任务模式默认);七个内置任务走原生接口,返回形状与 Chat 不同;高精/抽取建议 `qwen-vl-ocr-2025-11-20` 或 `qwen3.5-ocr` | | Video / A-V understand | `bl vision describe --video` 或 `bl omni` | 视频理解默认走百炼;`omni` 默认 `qwen3.8-omni-flash`,省略 `--model` 且无 `--text-only` 时自动切换 `qwen3.5-omni-plus` | `bl video edit` vs `bl video style`: edit uses happyhorse for prompt-based style/object edits; style applies one of 8 preset comic/ink transforms (`video-style-transform`). `bl video retalk` is audio-driven lip-sync (videoretalk). Style outputs are silent MP4. Retalk and style are Beijing-only and do not expose `--model`. @@ -120,6 +122,31 @@ bl speech recognize --url ./meeting.wav --model fun-asr --vocabulary-id "$VOCAB" bl speech vocabulary delete --id "$VOCAB" --yes ``` +## OCR built-in tasks (`--ocr-task`) + +Use `--ocr-task` when the user wants **machine-readable extraction** from an image (invoice fields, table → HTML, formula → LaTeX, document → LaTeX) rather than a description. It switches the call to the native DashScope multimodal-generation API. Plain `bl vision describe` without the flag keeps the compatible chat path, model and output untouched. + +```bash +bl vision describe --image ./invoice.png --ocr-task key_information_extraction --output json +bl vision describe --image ./table.png --ocr-task table_parsing --model qwen3.5-ocr --output json +bl vision describe --image ./page.png --ocr-task text_recognition --min-pixels 3072 --max-pixels 8388608 --output json +``` + +Tasks: `text_recognition`, `multi_lan`, `table_parsing`, `document_parsing`, `formula_recognition`, `advanced_recognition`, `key_information_extraction`. Only `--image` is accepted (single image, no `--video`), and it needs a standard DashScope API key — **Token Plan connections are refused up front**, use plain describe there. + +Rules that matter when parsing the output: + +- **Two JSON shapes.** With `--ocr-task` the result nests choices under `output` (`output.choices[0].message.content[]`); without it the result is a chat completion with top-level `choices[0].message.content`. Never hard-code `choices[0]` for both modes. +- **Two payload types.** `text_recognition` / `multi_lan` return plain text, `table_parsing` returns HTML, `formula_recognition` / `document_parsing` return LaTeX — all inside `content[].text`; do not `JSON.parse` them. `advanced_recognition` and `key_information_extraction` additionally return `content[].ocr_result` (`words_info[]` geometry / `kv_result` fields). +- **Model defaults.** `qwen-vl-ocr` is the default **only** in task mode and does not change other `vision describe` behaviour. Only `qwen-vl-ocr`, `qwen-vl-ocr-2025-11-20` and `qwen3.5-ocr` accept built-in tasks; `qwen-vl-ocr-2024-10-28` does not. `qwen3.5-ocr` is the one that combines a task with `--prompt` — on the other two a non-empty `--prompt` is dropped with an `OCR_TASK_PROMPT_IGNORED` warning, because those apply a fixed per-task prompt. An empty `--prompt ""` counts as unset and is neither sent nor warned about. +- **Pixel bounds are per model generation** (`qwen3.5-ocr` / `qwen-vl-ocr-2025-11-20` start at 3072, `qwen-vl-ocr` documents 3136, `qwen3-vl-plus` on the plain path starts at 65536). The CLI only checks positive integers and `min <= max`; out-of-range values come back as service errors — quote the server message, do not re-explain it. +- **Truncation.** Output length is capped per model (`qwen-vl-ocr` up to 4096 tokens, not self-service to raise). The CLI emits an `OCR_OUTPUT_TRUNCATED` warning when the service reports length truncation; retry with `qwen3.5-ocr` or split the image. +- **Local files** follow the shared rule: small images become data URIs, larger ones go through DashScope temporary storage (`oss://`, 48h) automatically. A `data:` URI supplied by the caller is checked against the same 10MB encoded ceiling and is rejected locally with exit 2, so hand the path to the CLI instead of pre-encoding it when the image is large. +- `key_information_extraction` without a custom schema extracts **all** visible fields; `ocr_options.task_config.result_schema`, `enable_rotate`, multi-turn OCR and PDF input are not exposed yet. Say so explicitly instead of inventing a flag. +- OCR output contains real personal data (names, ID numbers, amounts). Keep results out of project logs, committed fixtures and screenshots, and never run live tests against genuine identity documents. + +Intent detection (`tongyi-intent-detect-v3`) is a `bl text chat` capability, not a generation one; its system-message shapes and response parsing live in the `bailian-cli` skill under「意图理解模型」. Do not route intent requests through `bl vision describe`. + ## Output language - In-frame text and captions for generated images/videos follow the user's language unless the prompt specifies otherwise. diff --git a/skills/bailian-gen/reference/vision.md b/skills/bailian-gen/reference/vision.md index 9d4eedd76..1ce444692 100644 --- a/skills/bailian-gen/reference/vision.md +++ b/skills/bailian-gen/reference/vision.md @@ -15,23 +15,36 @@ Index: [index.md](index.md) ### `bl vision describe` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------- | -| **Name** | `vision describe` | -| **Description** | Describe an image or video using Qwen-VL | -| **Authentication** | API Key | -| **Usage** | `bl vision describe --image [--video ] [--prompt ]` | +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `vision describe` | +| **Description** | Describe an image or video using Qwen-VL | +| **Authentication** | API Key | +| **Usage** | `bl vision describe --image [--video ] [--prompt ] [--ocr-task ] [--min-pixels ] [--max-pixels ]` | #### Flags -| Flag | Type | Required | Description | -| ----------------------- | ------ | -------- | --------------------------------------------------- | -| `--image ` | string | no | Local image path or URL | -| `--video ` | array | no | Video file URL or local path (mp4/mov/avi/mkv/webm) | -| `--prompt ` | string | no | Question about the content (default: auto-detected) | -| `--model ` | string | no | Vision model (default: qwen3-vl-plus) | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--image ` | string | no | Local image path or URL | +| `--video ` | array | no | Video file URL or local path (mp4/mov/avi/mkv/webm) | +| `--prompt ` | string | no | Question about the content (default: auto-detected) | +| `--model ` | string | no | Vision model (default: qwen3-vl-plus; with --ocr-task the default becomes qwen-vl-ocr and only qwen-vl-ocr, qwen-vl-ocr-2025-11-20 and qwen3.5-ocr are accepted) | +| `--ocr-task ` | string | no | Built-in OCR task (uses the native API) | +| `--min-pixels ` | number | no | Minimum pixels for the image item (bounds depend on the model) | +| `--max-pixels ` | number | no | Maximum pixels for the image item (bounds depend on the model) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- --ocr-task switches to the native DashScope multimodal-generation API: the response nests choices under output.choices instead of a top-level choices array, so parse the two modes differently. +- Without --ocr-task, --dry-run prints an input summary rather than the wire body: min_pixels / max_pixels appear at the top of that summary, while the actual request attaches them to the image content item next to type and image_url. With --ocr-task the previewed body is the real request. +- The qwen-vl-ocr default applies only when --ocr-task is set; without it the model, request path and output stay exactly as before. +- Pixel bounds are model-specific (qwen3.5-ocr and qwen-vl-ocr-2025-11-20 start at 3072, qwen-vl-ocr at 3136, qwen3-vl-plus at 65536) and are not checked locally; the service reports out-of-range values. +- Built-in OCR tasks take a single image only, reject --video, and need a standard DashScope connection (not Token Plan). Output length is capped per model (qwen-vl-ocr up to 4096 tokens), so long tables or documents can be truncated; the CLI warns when the service reports length truncation. +- Not supported in this release: enable_rotate, custom extraction schema (ocr_options.task_config.result_schema), multi-turn OCR and PDF input. +- OCR results often contain personal data (identity documents, invoices). Keep the JSON out of project logs and fixtures, and never run live tests against real credentials or identity documents. #### Examples @@ -54,3 +67,11 @@ bl vision describe --video ./local-video.mp4 ```bash bl vision describe --image photo.png --prompt "Extract the text" --model qwen3-vl-plus ``` + +```bash +bl vision describe --image receipt.png --ocr-task key_information_extraction +``` + +```bash +bl vision describe --image table.png --ocr-task table_parsing --model qwen3.5-ocr --min-pixels 3072 --max-pixels 8388608 --prompt "Convert the table to HTML" +```