保留原图像素和画幅的局部文字编辑
This commit is contained in:
parent
e264fd3e30
commit
fafff4f7e8
@ -8,12 +8,14 @@ import { db } from "@/lib/db";
|
||||
import { aiModel } from "@/lib/db/schema";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import sharp from "sharp";
|
||||
import { detectCanvasTextRegions } from "@/lib/canvas/text-edit-ocr";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 120;
|
||||
|
||||
const requestSchema = z.object({
|
||||
imageUrl: z.string().min(1, "图片地址不能为空"),
|
||||
mode: z.literal("local").optional(),
|
||||
});
|
||||
|
||||
const OCR_IMAGE_FETCH_TIMEOUT_MS = 15000;
|
||||
@ -184,6 +186,11 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ success: false, error: "仅支持 URL 图片,不允许 base64 传输" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (parsed.data.mode === "local") {
|
||||
const data = await detectCanvasTextRegions(imageUrl);
|
||||
return NextResponse.json({ success: true, data });
|
||||
}
|
||||
|
||||
const detected = await detectTextWithVip98k(imageUrl);
|
||||
if (detected !== null) {
|
||||
return NextResponse.json({ success: true, data: { items: detected, model: "ocr" } });
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
@ -22,6 +23,11 @@ import { createKrea } from "@/lib/ai/providers/krea";
|
||||
import { createVolcanoVision } from "@/lib/ai/providers/volcano-vision";
|
||||
import { isImageGenerationModelDescriptor } from "@/lib/ai/model-classification";
|
||||
import { normalizeOptionalHexColor } from "@/lib/canvas/text-edit-colors";
|
||||
import { editCanvasTextLocally, LocalTextEditError } from "@/lib/canvas/text-edit-local";
|
||||
import { TEXT_EDIT_MAX_PIXELS } from "@/lib/canvas/text-edit-ocr";
|
||||
import { textEditRegionSchema } from "@/lib/canvas/text-edit-region";
|
||||
import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
|
||||
import { trackRuntimeWork } from "@/lib/observability/active-work";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
|
||||
@ -39,11 +45,13 @@ const textItemSchema = z.object({
|
||||
editedText: z.string().optional(),
|
||||
textColor: z.string().optional(),
|
||||
action: z.enum(["replace", "delete"]).optional(),
|
||||
region: textEditRegionSchema.optional(),
|
||||
});
|
||||
|
||||
const requestSchema = z.object({
|
||||
imageUrl: z.string().min(1, "图片地址不能为空"),
|
||||
items: z.array(textItemSchema).min(1, "至少需要一条文字修改"),
|
||||
mode: z.literal("local").optional(),
|
||||
});
|
||||
|
||||
const SUPPORTED_TEXT_EDIT_PROVIDER_TYPES = new Set([
|
||||
@ -614,6 +622,38 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ success: false, error: "未检测到有效的文字改动或删除" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (parsed.data.mode === "local") {
|
||||
const regionsById = new Map(parsed.data.items.map((item) => [item.id, item.region]));
|
||||
const edits = [
|
||||
...replacements,
|
||||
...deletions.map((item) => ({ ...item, editedText: "", textColor: undefined })),
|
||||
].map((item) => {
|
||||
const region = regionsById.get(item.id);
|
||||
if (!region) throw new LocalTextEditError("文字缺少位置,请重新识别后再应用");
|
||||
if (item.editedText.length > 400) throw new LocalTextEditError("每条替换文字最多 400 个字符");
|
||||
return { ...item, region };
|
||||
});
|
||||
if (edits.length > 50) throw new LocalTextEditError("每次最多编辑 50 条文字");
|
||||
return await trackRuntimeWork(async () => {
|
||||
const source = await fetchImageBufferFromUrl(imageUrl);
|
||||
const result = await editCanvasTextLocally(source, edits, TEXT_EDIT_MAX_PIXELS);
|
||||
const uploaded = await uploadFile(
|
||||
`canvas-text-edit-${randomUUID()}.png`,
|
||||
bufferToArrayBuffer(result),
|
||||
{ preferQiniuForm: true },
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
originalUrl: uploaded.url,
|
||||
thumbnailUrl: uploaded.url,
|
||||
model: "local-text-edit",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const models = await getEnabledAiModelsWithProvider();
|
||||
const candidates = getTextEditModelCandidates(models);
|
||||
|
||||
@ -645,6 +685,9 @@ export async function POST(request: Request) {
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof LocalTextEditError) {
|
||||
return NextResponse.json({ success: false, error: error.message }, { status: 422 });
|
||||
}
|
||||
logger.error("request_failed", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
|
||||
@ -659,6 +659,7 @@ const normalizeTextEditItems = (
|
||||
editedText: (item.editedText || item.originalText || "").trim(),
|
||||
textColor: normalizeOptionalHexColor(item.textColor),
|
||||
confidence: item.confidence,
|
||||
region: item.region,
|
||||
} as ImageTextEditItem;
|
||||
})
|
||||
.filter((item): item is ImageTextEditItem => !!item);
|
||||
@ -1733,7 +1734,7 @@ export function ImageNode({
|
||||
const [isDetectingText, setIsDetectingText] = useState(false);
|
||||
const [isApplyingTextEdit, setIsApplyingTextEdit] = useState(false);
|
||||
const [deletedTextItems, setDeletedTextItems] = useState<
|
||||
Array<{ id: string; originalText: string }>
|
||||
Array<Pick<ImageTextEditItem, "id" | "originalText" | "region">>
|
||||
>([]);
|
||||
const [isEditingTitle, setIsEditingTitle] = useState(false);
|
||||
const [draftTitle, setDraftTitle] = useState("");
|
||||
@ -5937,7 +5938,7 @@ export function ImageNode({
|
||||
|
||||
if (!forceRefresh && data.textEditSource === data.src) {
|
||||
const cached = normalizeTextEditItems(data.textEditItems);
|
||||
if (cached.length > 0) {
|
||||
if (cached.length > 0 && cached.every((item) => item.region)) {
|
||||
setTextEditItems(cached);
|
||||
setDeletedTextItems([]);
|
||||
setTextEditError(null);
|
||||
@ -5949,7 +5950,7 @@ export function ImageNode({
|
||||
setTextEditError(null);
|
||||
|
||||
try {
|
||||
const result = await imageGenerationService.detectCanvasText(data.src);
|
||||
const result = await imageGenerationService.detectCanvasText(data.src, "local");
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || "文字识别失败");
|
||||
@ -5965,6 +5966,7 @@ export function ImageNode({
|
||||
editedText: text,
|
||||
textColor: undefined,
|
||||
confidence: item.confidence,
|
||||
region: item.region,
|
||||
} as ImageTextEditItem;
|
||||
})
|
||||
.filter((item): item is ImageTextEditItem => !!item);
|
||||
@ -6008,7 +6010,7 @@ export function ImageNode({
|
||||
setTextEditError(null);
|
||||
|
||||
const cached = normalizeTextEditItems(data.textEditItems);
|
||||
if (cached.length > 0 && data.textEditSource === data.src) {
|
||||
if (cached.length > 0 && data.textEditSource === data.src && cached.every((item) => item.region)) {
|
||||
setTextEditItems(cached);
|
||||
setDeletedTextItems([]);
|
||||
return;
|
||||
@ -6091,7 +6093,7 @@ export function ImageNode({
|
||||
if (target?.originalText) {
|
||||
setDeletedTextItems((deletedPrev) => {
|
||||
if (deletedPrev.some((item) => item.id === id)) return deletedPrev;
|
||||
return [...deletedPrev, { id, originalText: target.originalText }];
|
||||
return [...deletedPrev, { id, originalText: target.originalText, region: target.region }];
|
||||
});
|
||||
}
|
||||
return prev.filter((item) => item.id !== id);
|
||||
@ -6135,6 +6137,7 @@ export function ImageNode({
|
||||
originalText: item.originalText.trim(),
|
||||
editedText,
|
||||
textColor: normalizeOptionalHexColor(item.textColor),
|
||||
region: item.region,
|
||||
action,
|
||||
};
|
||||
})
|
||||
@ -6153,6 +6156,7 @@ export function ImageNode({
|
||||
id: item.id,
|
||||
originalText: item.originalText.trim(),
|
||||
action: "delete" as const,
|
||||
region: item.region,
|
||||
}))
|
||||
.filter((item) => item.originalText.length > 0);
|
||||
|
||||
@ -6193,6 +6197,7 @@ export function ImageNode({
|
||||
const result = await imageGenerationService.editCanvasText({
|
||||
imageUrl: data.src,
|
||||
items: requestItems,
|
||||
mode: "local",
|
||||
});
|
||||
|
||||
if (!result.success || !result.data?.originalUrl) {
|
||||
@ -11793,7 +11798,7 @@ export function ImageNode({
|
||||
|
||||
<div className="max-h-[360px] space-y-3 overflow-y-auto px-4 py-3">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
识别图片文字后可逐条修改或删除,应用后会在保持画面风格的前提下完成文字更新。
|
||||
识别图片文字后可逐条修改或删除。仅处理所选文字区域,保留原图尺寸。
|
||||
</p>
|
||||
|
||||
{isDetectingText && (
|
||||
@ -11860,7 +11865,7 @@ export function ImageNode({
|
||||
{deletedTextItems.length > 0 && (
|
||||
<div className="rounded-md border border-orange-300 border-dashed bg-orange-50 px-3 py-2 text-orange-700 text-xs dark:border-orange-900 dark:bg-orange-950/40 dark:text-orange-200">
|
||||
已标记删除 {deletedTextItems.length}{" "}
|
||||
条文字,应用时会明确告诉生图模型移除这些文字并修复背景。
|
||||
条文字,应用后会去除旧字并修补局部背景。
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -27,7 +27,7 @@ function parseAssistantText(payload: any): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
async function getQwenVisionProviderApiKey() {
|
||||
export async function getQwenVisionProviderApiKey() {
|
||||
const providers = await getEnabledAiProviders();
|
||||
const hasApiKey = (item: (typeof providers)[number]) =>
|
||||
typeof item.apiKey === "string" && Boolean(item.apiKey.trim());
|
||||
|
||||
338
lib/canvas/text-edit-local.ts
Normal file
338
lib/canvas/text-edit-local.ts
Normal file
@ -0,0 +1,338 @@
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import type { TextEditRegion } from "./text-edit-region";
|
||||
|
||||
type Point = { x: number; y: number };
|
||||
type Pixel = [number, number, number, number];
|
||||
type Raster = {
|
||||
data: Buffer;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
type TextLine = {
|
||||
center: Point;
|
||||
width: number;
|
||||
height: number;
|
||||
angle: number;
|
||||
};
|
||||
type Edit = {
|
||||
originalText: string;
|
||||
editedText: string;
|
||||
textColor?: string;
|
||||
region: TextEditRegion;
|
||||
};
|
||||
|
||||
export class LocalTextEditError extends Error {}
|
||||
|
||||
const FONT_FILE = path.resolve("public/fonts/smart-edit/source-han.otf");
|
||||
const FONT_FAMILY = "Source Han Sans SC";
|
||||
|
||||
export async function editCanvasTextLocally(
|
||||
source: Buffer,
|
||||
edits: Edit[],
|
||||
maxPixels: number,
|
||||
): Promise<Buffer> {
|
||||
const { data, info } = await sharp(source, { limitInputPixels: maxPixels })
|
||||
.autoOrient()
|
||||
.toColourspace("srgb")
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
const original = { data, width: info.width, height: info.height };
|
||||
const output = { ...original, data: Buffer.from(original.data) };
|
||||
|
||||
const lines = edits.map((edit) => ({ ...edit, line: toTextLine(edit.region, original) }));
|
||||
const editArea = lines.reduce((area, { line }) => area + line.width * line.height, 0);
|
||||
if (editArea > 2_000_000) {
|
||||
throw new LocalTextEditError("所选文字区域较大,请分次编辑");
|
||||
}
|
||||
|
||||
const redraw = lines.map((edit) => {
|
||||
const recolor = edit.editedText === edit.originalText ? edit.textColor : undefined;
|
||||
const inkColor = updateTextInk(original, output, edit.line, edit.originalText, recolor);
|
||||
return { ...edit, color: edit.textColor || inkColor, recolor };
|
||||
});
|
||||
for (const edit of redraw) {
|
||||
if (edit.editedText && !edit.recolor) {
|
||||
await drawText(output, edit.line, edit.editedText, edit.color);
|
||||
}
|
||||
}
|
||||
|
||||
return sharp(output.data, {
|
||||
raw: { width: output.width, height: output.height, channels: 4 },
|
||||
}).png().toBuffer();
|
||||
}
|
||||
|
||||
function toTextLine(region: TextEditRegion, image: Raster): TextLine {
|
||||
const points = [0, 2, 4, 6].map((index) => ({
|
||||
x: region[index] * image.width,
|
||||
y: region[index + 1] * image.height,
|
||||
}));
|
||||
const [topLeft, topRight, bottomRight, bottomLeft] = points;
|
||||
const dx = (topRight.x - topLeft.x + bottomRight.x - bottomLeft.x) / 2;
|
||||
const dy = (topRight.y - topLeft.y + bottomRight.y - bottomLeft.y) / 2;
|
||||
const width = Math.hypot(dx, dy);
|
||||
const height = (
|
||||
Math.hypot(bottomLeft.x - topLeft.x, bottomLeft.y - topLeft.y) +
|
||||
Math.hypot(bottomRight.x - topRight.x, bottomRight.y - topRight.y)
|
||||
) / 2;
|
||||
if (width < 2 || height < 2 || width * height > image.width * image.height / 3) {
|
||||
throw new LocalTextEditError("文字位置不够准确,请重新识别后再试");
|
||||
}
|
||||
return {
|
||||
center: {
|
||||
x: points.reduce((sum, point) => sum + point.x, 0) / 4,
|
||||
y: points.reduce((sum, point) => sum + point.y, 0) / 4,
|
||||
},
|
||||
width,
|
||||
height,
|
||||
angle: Math.atan2(dy, dx),
|
||||
};
|
||||
}
|
||||
|
||||
function getPixel(image: Raster, x: number, y: number): Pixel {
|
||||
const offset = (y * image.width + x) * 4;
|
||||
return [
|
||||
image.data[offset], image.data[offset + 1],
|
||||
image.data[offset + 2], image.data[offset + 3],
|
||||
];
|
||||
}
|
||||
|
||||
function absolutePoint(line: TextLine, u: number, v: number): Point {
|
||||
const cos = Math.cos(line.angle);
|
||||
const sin = Math.sin(line.angle);
|
||||
return {
|
||||
x: line.center.x + u * cos - v * sin,
|
||||
y: line.center.y + u * sin + v * cos,
|
||||
};
|
||||
}
|
||||
|
||||
function sampleEdge(image: Raster, line: TextLine, u: number, v: number, step: number) {
|
||||
const samples: Pixel[] = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const point = absolutePoint(line, u, v + i * step);
|
||||
const x = Math.floor(point.x);
|
||||
const y = Math.floor(point.y);
|
||||
if (x < 0 || x >= image.width || y < 0 || y >= image.height) continue;
|
||||
samples.push(getPixel(image, x, y));
|
||||
}
|
||||
if (samples.length === 0) return;
|
||||
return medianPixel(samples);
|
||||
}
|
||||
|
||||
function medianPixel(samples: Pixel[]): Pixel {
|
||||
return [0, 1, 2, 3].map((channel) =>
|
||||
samples.map((sample) => sample[channel]).sort((a, b) => a - b)[samples.length >> 1],
|
||||
) as Pixel;
|
||||
}
|
||||
|
||||
function mixPixels(a: Pixel, b: Pixel, t: number): Pixel {
|
||||
return [0, 1, 2, 3].map((channel) =>
|
||||
a[channel] + (b[channel] - a[channel]) * t
|
||||
) as Pixel;
|
||||
}
|
||||
|
||||
function pixelDifference(a: Pixel, b: Pixel): Pixel {
|
||||
return [0, 1, 2, 3].map((channel) => a[channel] - b[channel]) as Pixel;
|
||||
}
|
||||
|
||||
function magnitude(pixel: Pixel) {
|
||||
return Math.hypot(...pixel);
|
||||
}
|
||||
|
||||
function colorHex(pixel: Pixel) {
|
||||
return `#${pixel.slice(0, 3).map((value) => value.toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
|
||||
function updateTextInk(original: Raster, output: Raster, line: TextLine, text: string, recolor?: string) {
|
||||
const padding = Math.max(2, Math.min(6, Math.round(Math.min(line.width, line.height) * 0.08)));
|
||||
const halfWidth = line.width / 2 + padding;
|
||||
const halfHeight = line.height / 2 + padding;
|
||||
const corners = [
|
||||
absolutePoint(line, -halfWidth, -halfHeight),
|
||||
absolutePoint(line, halfWidth, -halfHeight),
|
||||
absolutePoint(line, halfWidth, halfHeight),
|
||||
absolutePoint(line, -halfWidth, halfHeight),
|
||||
];
|
||||
const left = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.x))));
|
||||
const top = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.y))));
|
||||
const right = Math.min(original.width, Math.ceil(Math.max(...corners.map((point) => point.x))));
|
||||
const bottom = Math.min(original.height, Math.ceil(Math.max(...corners.map((point) => point.y))));
|
||||
const cos = Math.cos(line.angle);
|
||||
const sin = Math.sin(line.angle);
|
||||
// In a narrow line, samples from either side preserve detail that crosses the text band.
|
||||
const transpose = line.height > line.width * 1.7;
|
||||
const extent = transpose ? halfWidth : halfHeight;
|
||||
const referenceLine = transpose ? { ...line, angle: line.angle - Math.PI / 2 } : line;
|
||||
const samples = new Map<number, [Pixel, Pixel]>();
|
||||
|
||||
function backgroundAt(u: number, v: number) {
|
||||
const alongLine = transpose ? -v : u;
|
||||
const lane = Math.floor(alongLine);
|
||||
let pair = samples.get(lane);
|
||||
if (!pair) {
|
||||
const before = sampleEdge(original, referenceLine, alongLine, -extent - 1, -1);
|
||||
const after = sampleEdge(original, referenceLine, alongLine, extent + 1, 1);
|
||||
const existing = before ?? after;
|
||||
if (!existing) return;
|
||||
pair = [before ?? existing, after ?? existing];
|
||||
samples.set(lane, pair);
|
||||
}
|
||||
const across = transpose ? u : v;
|
||||
return mixPixels(pair[0], pair[1], (across / extent + 1) / 2);
|
||||
}
|
||||
|
||||
const sampleInk: Array<{ pixel: Pixel; delta: Pixel; contrast: number }> = [];
|
||||
const width = right - left;
|
||||
const height = bottom - top;
|
||||
const sampleStep = Math.max(1, Math.round(Math.sqrt(width * height / 6000)));
|
||||
for (let y = top; y < bottom; y += sampleStep) {
|
||||
for (let x = left; x < right; x += sampleStep) {
|
||||
const dx = x + 0.5 - line.center.x;
|
||||
const dy = y + 0.5 - line.center.y;
|
||||
const u = dx * cos + dy * sin;
|
||||
const v = -dx * sin + dy * cos;
|
||||
if (Math.abs(u) > line.width / 2 || Math.abs(v) > line.height / 2) continue;
|
||||
const background = backgroundAt(u, v);
|
||||
if (!background) continue;
|
||||
const pixel = getPixel(original, x, y);
|
||||
const delta = pixelDifference(pixel, background);
|
||||
sampleInk.push({ pixel, delta, contrast: magnitude(delta) });
|
||||
}
|
||||
}
|
||||
sampleInk.sort((a, b) => b.contrast - a.contrast);
|
||||
const strongest = sampleInk.slice(0, Math.max(3, Math.floor(sampleInk.length * 0.08)));
|
||||
const ink = strongest.length > 0
|
||||
? medianPixel(strongest.map((sample) => sample.pixel))
|
||||
: undefined;
|
||||
const direction = strongest.length > 0
|
||||
? medianPixel(strongest.map((sample) => sample.delta))
|
||||
: undefined;
|
||||
const contrast = direction ? magnitude(direction) : 0;
|
||||
if (!ink || !direction || contrast < 15) {
|
||||
throw new LocalTextEditError(`无法准确去除「${text.slice(0, 24)}」,请重新识别`);
|
||||
}
|
||||
|
||||
const threshold = Math.max(8, Math.min(16, contrast * 0.08));
|
||||
const mask = new Uint8Array(width * height);
|
||||
const colorRgb = recolor?.slice(1).match(/../g)?.map((channel) => Number.parseInt(channel, 16));
|
||||
let foundInk = false;
|
||||
for (let y = top; y < bottom; y++) {
|
||||
for (let x = left; x < right; x++) {
|
||||
const dx = x + 0.5 - line.center.x;
|
||||
const dy = y + 0.5 - line.center.y;
|
||||
const u = dx * cos + dy * sin;
|
||||
const v = -dx * sin + dy * cos;
|
||||
if (Math.abs(u) > halfWidth || Math.abs(v) > halfHeight) continue;
|
||||
const background = backgroundAt(u, v);
|
||||
if (!background) continue;
|
||||
const delta = pixelDifference(getPixel(original, x, y), background);
|
||||
const alongInk = delta.reduce((dot, value, channel) => dot + value * direction[channel], 0) / contrast;
|
||||
if (alongInk <= threshold || alongInk < magnitude(delta) * 0.75) continue;
|
||||
foundInk = true;
|
||||
mask[(y - top) * width + x - left] = 1;
|
||||
if (colorRgb) {
|
||||
const coverage = Math.min(1, alongInk / contrast);
|
||||
const offset = (y * output.width + x) * 4;
|
||||
for (let channel = 0; channel < 3; channel++) {
|
||||
output.data[offset + channel] = Math.round(
|
||||
background[channel] + (colorRgb[channel] - background[channel]) * coverage,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!foundInk) {
|
||||
throw new LocalTextEditError(`无法准确定位「${text.slice(0, 24)}」,请重新识别`);
|
||||
}
|
||||
if (colorRgb) return colorHex(ink);
|
||||
|
||||
// Include antialiasing and compression around each stroke without filling the text box.
|
||||
const halo = Math.min(3, Math.max(2, Math.round(padding / 2)));
|
||||
for (let y = top; y < bottom; y++) {
|
||||
for (let x = left; x < right; x++) {
|
||||
const dx = x + 0.5 - line.center.x;
|
||||
const dy = y + 0.5 - line.center.y;
|
||||
const u = dx * cos + dy * sin;
|
||||
const v = -dx * sin + dy * cos;
|
||||
if (Math.abs(u) > halfWidth || Math.abs(v) > halfHeight) continue;
|
||||
if (!hasNearbyInk(mask, width, height, x - left, y - top, halo)) continue;
|
||||
const background = backgroundAt(u, v);
|
||||
if (!background) continue;
|
||||
|
||||
const offset = (y * output.width + x) * 4;
|
||||
for (let channel = 0; channel < 4; channel++) {
|
||||
output.data[offset + channel] = Math.round(background[channel]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return colorHex(ink);
|
||||
}
|
||||
|
||||
function hasNearbyInk(mask: Uint8Array, width: number, height: number, x: number, y: number, halo: number) {
|
||||
for (let row = Math.max(0, y - halo); row <= Math.min(height - 1, y + halo); row++) {
|
||||
for (let col = Math.max(0, x - halo); col <= Math.min(width - 1, x + halo); col++) {
|
||||
if (mask[row * width + col]) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function escapeText(text: string) {
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
async function drawText(output: Raster, line: TextLine, text: string, color: string) {
|
||||
const vertical = line.height > line.width * 1.7 && /\p{Script=Han}/u.test(text);
|
||||
const width = Math.max(1, Math.floor(line.width));
|
||||
const height = Math.max(1, Math.floor(line.height));
|
||||
const glyphSize = vertical ? width : height;
|
||||
const pointSize = Math.max(1, Math.floor(glyphSize * 0.82));
|
||||
const contents = vertical ? Array.from(text).join("\n") : text.replace(/\s+/g, " ");
|
||||
const layer = await sharp({
|
||||
text: {
|
||||
text: `<span foreground="${color}">${escapeText(contents)}</span>`,
|
||||
font: `${FONT_FAMILY} ${pointSize}`,
|
||||
fontfile: FONT_FILE,
|
||||
rgba: true,
|
||||
},
|
||||
}).resize({ width, height, fit: "inside", withoutEnlargement: true })
|
||||
.raw().toBuffer({ resolveWithObject: true });
|
||||
|
||||
const originX = vertical ? -layer.info.width / 2 : -line.width / 2;
|
||||
const originY = vertical ? -line.height / 2 : -layer.info.height / 2;
|
||||
const corners = [
|
||||
absolutePoint(line, originX, originY),
|
||||
absolutePoint(line, originX + layer.info.width, originY),
|
||||
absolutePoint(line, originX + layer.info.width, originY + layer.info.height),
|
||||
absolutePoint(line, originX, originY + layer.info.height),
|
||||
];
|
||||
const left = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.x))));
|
||||
const top = Math.max(0, Math.floor(Math.min(...corners.map((point) => point.y))));
|
||||
const right = Math.min(output.width, Math.ceil(Math.max(...corners.map((point) => point.x))));
|
||||
const bottom = Math.min(output.height, Math.ceil(Math.max(...corners.map((point) => point.y))));
|
||||
const cos = Math.cos(line.angle);
|
||||
const sin = Math.sin(line.angle);
|
||||
|
||||
for (let y = top; y < bottom; y++) {
|
||||
for (let x = left; x < right; x++) {
|
||||
const dx = x + 0.5 - line.center.x;
|
||||
const dy = y + 0.5 - line.center.y;
|
||||
const u = Math.floor(dx * cos + dy * sin - originX);
|
||||
const v = Math.floor(-dx * sin + dy * cos - originY);
|
||||
if (u < 0 || u >= layer.info.width || v < 0 || v >= layer.info.height) continue;
|
||||
const src = (v * layer.info.width + u) * 4;
|
||||
const dst = (y * output.width + x) * 4;
|
||||
const alpha = layer.data[src + 3] / 255;
|
||||
if (alpha === 0) continue;
|
||||
const remaining = output.data[dst + 3] / 255 * (1 - alpha);
|
||||
const combined = alpha + remaining;
|
||||
for (let channel = 0; channel < 3; channel++) {
|
||||
output.data[dst + channel] = Math.round(
|
||||
(layer.data[src + channel] * alpha + output.data[dst + channel] * remaining) / combined,
|
||||
);
|
||||
}
|
||||
output.data[dst + 3] = Math.round(combined * 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
82
lib/canvas/text-edit-ocr.ts
Normal file
82
lib/canvas/text-edit-ocr.ts
Normal file
@ -0,0 +1,82 @@
|
||||
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 };
|
||||
}
|
||||
12
lib/canvas/text-edit-region.ts
Normal file
12
lib/canvas/text-edit-region.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const coordinate = z.number().min(0).max(1);
|
||||
|
||||
export const textEditRegionSchema = z.tuple([
|
||||
coordinate, coordinate,
|
||||
coordinate, coordinate,
|
||||
coordinate, coordinate,
|
||||
coordinate, coordinate,
|
||||
]);
|
||||
|
||||
export type TextEditRegion = z.infer<typeof textEditRegionSchema>;
|
||||
@ -61,6 +61,7 @@ const nextConfig: NextConfig = {
|
||||
// 外部包配置(Next.js 16+)
|
||||
serverExternalPackages: ["sharp"],
|
||||
outputFileTracingIncludes: {
|
||||
"/api/canvas/text-edit": ["./public/fonts/smart-edit/source-han.otf"],
|
||||
"/api/canvas/generation-tasks": ["./services/smart-edit/analyze.py", "./services/smart-edit/separate.py", "./services/smart-edit/font.py"],
|
||||
"/api/canvas/smart-edit/fonts/[id]": ["./services/smart-edit/font.py"],
|
||||
"/api/canvas/smart-edit/capabilities": ["./services/smart-edit/analyze.py", "./services/smart-edit/separate.py", "./services/smart-edit/font.py"],
|
||||
|
||||
@ -7,6 +7,7 @@ import type {
|
||||
CanvasNode,
|
||||
CanvasWorkspaceType,
|
||||
} from '@/types/canvas';
|
||||
import type { TextEditRegion } from '@/lib/canvas/text-edit-region';
|
||||
import type { VideoGenerationMode, VideoRatio, VideoResolution } from '@/types/ai';
|
||||
import { fetchUploadWithRetry } from '@/lib/client/upload-with-retry';
|
||||
import { requestLongTaskResult } from '@/lib/client/long-task';
|
||||
@ -121,6 +122,7 @@ export interface CanvasTextDetectItem {
|
||||
id: string;
|
||||
text: string;
|
||||
confidence?: number;
|
||||
region?: TextEditRegion;
|
||||
}
|
||||
|
||||
export interface CanvasTextEditPayloadItem {
|
||||
@ -129,6 +131,7 @@ export interface CanvasTextEditPayloadItem {
|
||||
editedText?: string;
|
||||
textColor?: string;
|
||||
action?: 'replace' | 'delete';
|
||||
region?: TextEditRegion;
|
||||
}
|
||||
|
||||
export interface CanvasTextSuggestionItem {
|
||||
@ -1073,12 +1076,12 @@ export const imageGenerationService = {
|
||||
},
|
||||
|
||||
// 识别图片中的文字(OCR)
|
||||
async detectCanvasText(imageUrl: string): Promise<ApiResponse<{ items: CanvasTextDetectItem[]; model?: string }>> {
|
||||
async detectCanvasText(imageUrl: string, mode?: 'local'): Promise<ApiResponse<{ items: CanvasTextDetectItem[]; model?: string }>> {
|
||||
try {
|
||||
const response = await fetch('/api/canvas/text-detect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ imageUrl }),
|
||||
body: JSON.stringify({ imageUrl, mode }),
|
||||
});
|
||||
const data = await response.json();
|
||||
return data;
|
||||
@ -1122,6 +1125,7 @@ export const imageGenerationService = {
|
||||
async editCanvasText(params: {
|
||||
imageUrl: string;
|
||||
items: CanvasTextEditPayloadItem[];
|
||||
mode?: 'local';
|
||||
}): Promise<ApiResponse<{ thumbnailUrl: string; originalUrl: string; model?: string }>> {
|
||||
try {
|
||||
const response = await fetch('/api/canvas/text-edit', {
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import type { TextEditRegion } from "@/lib/canvas/text-edit-region";
|
||||
import type { AgentWorkflowPersistedState } from "@/types/agent";
|
||||
import type { UiScreenDocument } from "@/lib/ui-screen/schema";
|
||||
import type { StyleProPersistedState } from "@/lib/style-pro/config";
|
||||
@ -54,6 +55,7 @@ export interface ImageTextEditItem {
|
||||
editedText: string;
|
||||
textColor?: string;
|
||||
confidence?: number;
|
||||
region?: TextEditRegion;
|
||||
}
|
||||
|
||||
// 图片节点数据
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user