ai-chatbot/lib/canvas/text-edit-ocr.ts

83 lines
2.7 KiB
TypeScript

import "server-only";
import sharp from "sharp";
import { getQwenVisionProviderApiKey } from "@/lib/ai/qwen3-vl";
import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
import { textEditRegionSchema } from "./text-edit-region";
const OCR_MODEL = "qwen3.5-ocr";
const OCR_ENDPOINT =
"https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
export const TEXT_EDIT_MAX_PIXELS = 40_000_000;
export async function detectCanvasTextRegions(imageUrl: string) {
const [source, apiKey] = await Promise.all([
fetchImageBufferFromUrl(imageUrl),
getQwenVisionProviderApiKey(),
]);
const { data, info } = await sharp(source, { limitInputPixels: TEXT_EDIT_MAX_PIXELS })
.autoOrient()
.resize({ width: 2560, height: 2560, fit: "inside", withoutEnlargement: true })
.flatten({ background: "#fff" })
.jpeg({ quality: 93, chromaSubsampling: "4:4:4" })
.toBuffer({ resolveWithObject: true });
const response = await fetch(OCR_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: OCR_MODEL,
input: {
messages: [{
role: "user",
content: [{
image: `data:image/jpeg;base64,${data.toString("base64")}`,
enable_rotate: false,
min_pixels: Math.min(3072, info.width * info.height),
max_pixels: 8_388_608,
}],
}],
},
parameters: { ocr_options: { task: "advanced_recognition" } },
}),
signal: AbortSignal.timeout(35_000),
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`定位文字服务返回 HTTP ${response.status}`);
}
const result = await response.json();
const words: unknown = result.output?.choices?.[0]?.message?.content?.find(
(part: { ocr_result?: unknown }) => part.ocr_result,
)?.ocr_result?.words_info;
if (!Array.isArray(words)) {
throw new Error("定位文字服务未返回有效的区域列表");
}
const items = words.flatMap((word, index) => {
if (typeof word?.text !== "string" || !word.text.trim()) return [];
if (!Array.isArray(word.location)) return [];
const bounds = textEditRegionSchema.safeParse(
word.location.map((value: unknown, coordinate: number) =>
typeof value === "number"
? value / (coordinate % 2 ? info.height : info.width)
: NaN,
),
);
return bounds.success
? [{ id: String(index + 1), text: word.text.trim(), region: bounds.data }]
: [];
}).slice(0, 50);
if (words.length > 0 && items.length === 0) {
throw new Error("已识别文字,但未获得可用于编辑的位置");
}
return { items, model: OCR_MODEL };
}