批量指令编辑支持自定义输出宽高
This commit is contained in:
parent
06593978a5
commit
bf9f06d907
@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { createCanvasImageTask, enqueueCanvasImageTask } from "@/lib/canvas/image-task-queue";
|
||||
import { getSystemSetting } from "@/lib/db/queries";
|
||||
import { batchInstructionSizeSchema } from "@/lib/canvas/batch-instruction-size";
|
||||
import type { CanvasGenerateImageRequest } from "@/lib/canvas/generate-image";
|
||||
|
||||
const imageUrl = z.string().trim().max(8192).refine(value => {
|
||||
@ -19,17 +20,21 @@ const submission = z.object({
|
||||
taskId: z.string().uuid(),
|
||||
image: imageUrl,
|
||||
reference: imageUrl.optional(),
|
||||
instruction: z.string().trim().min(1).max(3000),
|
||||
instruction: z.string().trim().max(3000),
|
||||
square: z.boolean(),
|
||||
outputSize: batchInstructionSizeSchema.optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
const parsed = submission.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) return NextResponse.json({ error: "请提供原图和 1 至 3000 字的编辑指令" }, { status: 400 });
|
||||
if (!parsed.success) return NextResponse.json({ error: "请检查原图、输出尺寸和编辑指令" }, { status: 400 });
|
||||
|
||||
const { taskId, image, reference, instruction, square } = parsed.data;
|
||||
const { taskId, image, reference, instruction, square, outputSize } = parsed.data;
|
||||
if (!instruction && (!outputSize || reference)) {
|
||||
return NextResponse.json({ error: "请填写统一编辑指令。若只调整尺寸,请选择自定义宽高并移除共用参考图" }, { status: 400 });
|
||||
}
|
||||
if (reference === image) return NextResponse.json({ error: "共用参考图和待编辑原图相同" }, { status: 400 });
|
||||
|
||||
try {
|
||||
@ -40,12 +45,12 @@ export async function POST(request: Request) {
|
||||
|
||||
const referenceImages = reference ? [image, reference] : [image];
|
||||
const imageRequest: CanvasGenerateImageRequest = {
|
||||
prompt: [
|
||||
prompt: instruction ? [
|
||||
"编辑第一张图。保留第一张图的完整构图、原始宽高比和所有未要求修改的内容。",
|
||||
reference && "第二张图只提供指令指定的人脸、商品或其他特征。以第一张图为底图,保持第一张图中其余人物、姿势、衣着、商品、背景和光线,除非指令明确要求更改。",
|
||||
"保持原图整幅画面的四边,避免裁切或拉伸。只输出一张编辑后的图片。",
|
||||
"编辑指令:" + instruction,
|
||||
].filter(Boolean).join("\n"),
|
||||
].filter(Boolean).join("\n") : "",
|
||||
displayPrompt: instruction,
|
||||
aspectRatio: "auto",
|
||||
imageCount: 1,
|
||||
@ -53,7 +58,8 @@ export async function POST(request: Request) {
|
||||
requiredReferenceImageCount: referenceImages.length,
|
||||
agentImageMode: "auto",
|
||||
promptExtend: false,
|
||||
padBatchInstructionToSquare: square || undefined,
|
||||
padBatchInstructionToSquare: square && !outputSize || undefined,
|
||||
batchInstructionOutputSize: outputSize,
|
||||
batchInstructionWithReference: Boolean(reference) || undefined,
|
||||
debugLabel: "batch-instruction-edit",
|
||||
};
|
||||
|
||||
@ -35,6 +35,7 @@ import {
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { runBatchInstructionEdit, BatchInstructionEditError } from "@/lib/client/batch-instruction-edit";
|
||||
import { batchInstructionSizeSchema } from "@/lib/canvas/batch-instruction-size";
|
||||
import { downloadCanvasSelectionZip } from "@/lib/client/canvas-zip-download";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
@ -174,10 +175,15 @@ type SceneFusionPersistedState = {
|
||||
instructionItems: ProcessItem[];
|
||||
instructionText: string;
|
||||
instructionReference: string | null;
|
||||
instructionSquare: boolean;
|
||||
instructionSquare?: boolean;
|
||||
instructionOutputMode?: InstructionOutputMode;
|
||||
instructionWidth?: string;
|
||||
instructionHeight?: string;
|
||||
selectedResultIds: string[];
|
||||
};
|
||||
|
||||
type InstructionOutputMode = "original" | "square" | "custom";
|
||||
|
||||
type ReferenceSearchResponse = {
|
||||
success?: boolean;
|
||||
error?: {
|
||||
@ -535,7 +541,20 @@ export function SceneFusionView({
|
||||
const [instructionItems, setInstructionItems] = useState<ProcessItem[]>([]);
|
||||
const [instructionText, setInstructionText] = useState("");
|
||||
const [instructionReference, setInstructionReference] = useState<string | null>(null);
|
||||
const [instructionSquare, setInstructionSquare] = useState(false);
|
||||
const [instructionOutputMode, setInstructionOutputMode] = useState<InstructionOutputMode>("original");
|
||||
const [instructionWidth, setInstructionWidth] = useState("");
|
||||
const [instructionHeight, setInstructionHeight] = useState("");
|
||||
const customSizeSelected = instructionOutputMode === "custom";
|
||||
const parsedInstructionSize = batchInstructionSizeSchema.safeParse({
|
||||
width: Number(instructionWidth),
|
||||
height: Number(instructionHeight),
|
||||
});
|
||||
const instructionSize = customSizeSelected && parsedInstructionSize.success ? parsedInstructionSize.data : undefined;
|
||||
const resizeOnly = customSizeSelected && !instructionText.trim() && !instructionReference;
|
||||
const instructionReady = customSizeSelected
|
||||
? Boolean(instructionSize && (instructionText.trim() || resizeOnly))
|
||||
: Boolean(instructionText.trim());
|
||||
const invalidInstructionSize = customSizeSelected && Boolean(instructionWidth && instructionHeight) && !instructionSize;
|
||||
const [isInstructionUploading, setIsInstructionUploading] = useState(false);
|
||||
const [zipStage, setZipStage] = useState("");
|
||||
const [isZipping, setIsZipping] = useState(false);
|
||||
@ -582,14 +601,14 @@ export function SceneFusionView({
|
||||
if (mode === "random-bg") return Boolean(productImage) && randomCount > 0;
|
||||
if (isInstructionMode) {
|
||||
return config?.enabled !== false && !isInstructionUploading && instructionItems.length > 0 &&
|
||||
Boolean(instructionText.trim() || instructionItems.every(item => item.instructionSubmitted));
|
||||
(instructionReady || instructionItems.every(item => item.instructionSubmitted));
|
||||
}
|
||||
return batchItems.length > 0;
|
||||
}, [
|
||||
batchItems.length,
|
||||
config?.enabled,
|
||||
instructionItems,
|
||||
instructionText,
|
||||
instructionReady,
|
||||
isInstructionMode,
|
||||
isInstructionUploading,
|
||||
mode,
|
||||
@ -792,7 +811,13 @@ export function SceneFusionView({
|
||||
}
|
||||
if (typeof parsed.instructionText === "string") setInstructionText(parsed.instructionText);
|
||||
setInstructionReference(toPersistableImageValue(parsed.instructionReference) || null);
|
||||
setInstructionSquare(parsed.instructionSquare === true);
|
||||
setInstructionOutputMode(
|
||||
parsed.instructionOutputMode === "custom" || parsed.instructionOutputMode === "square" || parsed.instructionOutputMode === "original"
|
||||
? parsed.instructionOutputMode
|
||||
: parsed.instructionSquare === true ? "square" : "original"
|
||||
);
|
||||
if (typeof parsed.instructionWidth === "string") setInstructionWidth(parsed.instructionWidth);
|
||||
if (typeof parsed.instructionHeight === "string") setInstructionHeight(parsed.instructionHeight);
|
||||
if (Array.isArray(parsed.selectedResultIds)) {
|
||||
setSelectedResultIds(parsed.selectedResultIds.map((value) => String(value || "").trim()).filter(Boolean));
|
||||
}
|
||||
@ -886,7 +911,9 @@ export function SceneFusionView({
|
||||
instructionItems,
|
||||
instructionText,
|
||||
instructionReference,
|
||||
instructionSquare,
|
||||
instructionOutputMode,
|
||||
instructionWidth,
|
||||
instructionHeight,
|
||||
selectedResultIds,
|
||||
};
|
||||
|
||||
@ -909,7 +936,9 @@ export function SceneFusionView({
|
||||
instructionItems,
|
||||
instructionText,
|
||||
instructionReference,
|
||||
instructionSquare,
|
||||
instructionOutputMode,
|
||||
instructionWidth,
|
||||
instructionHeight,
|
||||
imageSize,
|
||||
mode,
|
||||
multiProductItems,
|
||||
@ -1820,8 +1849,8 @@ export function SceneFusionView({
|
||||
|
||||
const processBatchImageItem = async (item: ProcessItem) => {
|
||||
if (isInstructionMode) {
|
||||
if (!item.instructionSubmitted && !instructionText.trim()) {
|
||||
throw new Error("请填写统一编辑指令");
|
||||
if (!item.instructionSubmitted && !instructionReady) {
|
||||
throw new Error(customSizeSelected && !instructionSize ? "请填写有效的输出宽高" : "请填写统一编辑指令");
|
||||
}
|
||||
const taskId = item.instructionTaskId || crypto.randomUUID();
|
||||
const updateTask = (patch: Partial<ProcessItem>) => setInstructionItems(items =>
|
||||
@ -1834,7 +1863,8 @@ export function SceneFusionView({
|
||||
image: new URL(item.image, window.location.origin).href,
|
||||
reference: instructionReference ? new URL(instructionReference, window.location.origin).href : undefined,
|
||||
instruction: instructionText.trim(),
|
||||
square: instructionSquare,
|
||||
square: instructionOutputMode === "square",
|
||||
outputSize: instructionSize,
|
||||
submitted: item.instructionSubmitted,
|
||||
}, () => updateTask({ instructionSubmitted: true }));
|
||||
updateTask({ instructionTaskId: undefined, instructionSubmitted: undefined });
|
||||
@ -3048,7 +3078,9 @@ export function SceneFusionView({
|
||||
{isInstructionMode && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="batch-edit-instruction">统一编辑指令</Label>
|
||||
<Label htmlFor="batch-edit-instruction">
|
||||
{customSizeSelected && !instructionReference ? "统一编辑指令(可选)" : "统一编辑指令"}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="batch-edit-instruction"
|
||||
disabled={isProcessing}
|
||||
@ -3086,13 +3118,67 @@ export function SceneFusionView({
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="batch-edit-ratio">输出比例</Label>
|
||||
<Select disabled={isProcessing} onValueChange={(value) => setInstructionSquare(value === "square")} value={instructionSquare ? "square" : "original"}>
|
||||
<Select
|
||||
disabled={isProcessing}
|
||||
onValueChange={(value: InstructionOutputMode) => setInstructionOutputMode(value)}
|
||||
value={instructionOutputMode}
|
||||
>
|
||||
<SelectTrigger id="batch-edit-ratio" className="h-10"><SelectValue /></SelectTrigger>
|
||||
<SelectContent className="z-[30000] bg-background">
|
||||
<SelectItem value="original">原图比例</SelectItem>
|
||||
<SelectItem value="square">1:1 · 保留完整画面并补边</SelectItem>
|
||||
<SelectItem value="custom">自定义宽高</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{customSizeSelected && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="batch-edit-width">宽(像素)</Label>
|
||||
<Input
|
||||
aria-describedby="batch-edit-size-hint"
|
||||
aria-invalid={invalidInstructionSize}
|
||||
disabled={isProcessing}
|
||||
id="batch-edit-width"
|
||||
inputMode="numeric"
|
||||
max={8192}
|
||||
min={1}
|
||||
onChange={(event) => setInstructionWidth(event.target.value)}
|
||||
placeholder="800"
|
||||
step={1}
|
||||
type="number"
|
||||
value={instructionWidth}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="batch-edit-height">高(像素)</Label>
|
||||
<Input
|
||||
aria-describedby="batch-edit-size-hint"
|
||||
aria-invalid={invalidInstructionSize}
|
||||
disabled={isProcessing}
|
||||
id="batch-edit-height"
|
||||
inputMode="numeric"
|
||||
max={8192}
|
||||
min={1}
|
||||
onChange={(event) => setInstructionHeight(event.target.value)}
|
||||
placeholder="1000"
|
||||
step={1}
|
||||
type="number"
|
||||
value={instructionHeight}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
className={invalidInstructionSize ? "text-xs text-destructive" : "text-muted-foreground text-xs"}
|
||||
id="batch-edit-size-hint"
|
||||
role={invalidInstructionSize ? "alert" : undefined}
|
||||
>
|
||||
{invalidInstructionSize
|
||||
? "宽高须为 1 至 8192 的整数,且总像素不超过 2400 万。"
|
||||
: "等比缩放并补边,保留完整画面。编辑指令留空时只调整尺寸。"}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@ -3114,10 +3200,9 @@ export function SceneFusionView({
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
{getModeActionLabel(
|
||||
mode,
|
||||
mode === "random-bg" ? randomCount : resultItems.length
|
||||
)}
|
||||
{isInstructionMode && resizeOnly
|
||||
? `开始调整尺寸(${resultItems.length} 张)`
|
||||
: getModeActionLabel(mode, mode === "random-bg" ? randomCount : resultItems.length)}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
@ -3345,7 +3430,7 @@ export function SceneFusionView({
|
||||
{item.error || "处理失败"}
|
||||
</p>
|
||||
{isInstructionMode && (
|
||||
<Button className="mt-2" disabled={isProcessing || isInstructionUploading || (!item.instructionSubmitted && !instructionText.trim())}
|
||||
<Button className="mt-2" disabled={isProcessing || isInstructionUploading || (!item.instructionSubmitted && !instructionReady)}
|
||||
onClick={(event) => { event.stopPropagation(); void retrySingleItem(item); }} size="sm" variant="secondary">
|
||||
{item.instructionTaskId ? "查询原任务" : "重试这张"}
|
||||
</Button>
|
||||
@ -3409,7 +3494,7 @@ export function SceneFusionView({
|
||||
event.stopPropagation();
|
||||
retrySingleItem(item);
|
||||
}}
|
||||
disabled={isProcessing || (isInstructionMode && (isInstructionUploading || !instructionText.trim()))}
|
||||
disabled={isProcessing || (isInstructionMode && (isInstructionUploading || (!item.instructionSubmitted && !instructionReady)))}
|
||||
size="icon"
|
||||
variant="secondary"
|
||||
>
|
||||
|
||||
@ -3,34 +3,42 @@ import "server-only";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import sharp from "sharp";
|
||||
import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
import { buildS3PublicUrl, resolveS3UploadTarget, uploadFile } from "@/lib/storage/service";
|
||||
import type { BatchInstructionSize } from "./batch-instruction-size";
|
||||
|
||||
async function sampleBackground(source: sharp.Sharp) {
|
||||
const { data, info } = await source.clone().toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
const { width, height } = info;
|
||||
const corners = [0, (width - 1) * info.channels, (height - 1) * width * info.channels, (width * height - 1) * info.channels];
|
||||
const sample = (channel: number) =>
|
||||
Math.round(corners.reduce((sum, offset) => sum + data[offset + channel], 0) / corners.length);
|
||||
return { r: sample(0), g: sample(1), b: sample(2), alpha: sample(3) / 255 };
|
||||
}
|
||||
|
||||
export async function padImageToSquare(bytes: Buffer) {
|
||||
const source = sharp(bytes).autoOrient();
|
||||
const metadata = await source.metadata();
|
||||
const { width, height } = metadata.autoOrient;
|
||||
const { width, height } = (await source.metadata()).autoOrient;
|
||||
if (!width || !height) throw new Error("无法读取生成图尺寸");
|
||||
if (width === height) return null;
|
||||
|
||||
const size = Math.max(width, height);
|
||||
const left = Math.floor((size - width) / 2);
|
||||
const top = Math.floor((size - height) / 2);
|
||||
const { data, info } = await source.clone().ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
const corners = [0, (width - 1) * info.channels, (height - 1) * width * info.channels, (width * height - 1) * info.channels];
|
||||
const sample = (channel: number) =>
|
||||
Math.round(corners.reduce((sum, offset) => sum + data[offset + channel], 0) / corners.length);
|
||||
const background = { r: sample(0), g: sample(1), b: sample(2), alpha: sample(3) / 255 };
|
||||
const background = await sampleBackground(source);
|
||||
return source.extend({ left, right: size - width - left, top, bottom: size - height - top, background })
|
||||
.keepIccProfile()
|
||||
.png()
|
||||
.toBuffer();
|
||||
}
|
||||
|
||||
export async function squareBatchInstructionOutput(image: { originalUrl: string; thumbnailUrl: string }) {
|
||||
const bytes = await fetchImageBufferFromUrl(image.originalUrl);
|
||||
const padded = await padImageToSquare(bytes);
|
||||
if (!padded) return image;
|
||||
const thumbnail = await sharp(padded).resize(512, 512, { withoutEnlargement: true }).png().toBuffer();
|
||||
export async function fitBatchInstructionImage(bytes: Buffer, size: BatchInstructionSize) {
|
||||
const source = sharp(bytes, { limitInputPixels: 40_000_000 }).autoOrient();
|
||||
const background = await sampleBackground(source);
|
||||
return source.resize({ ...size, fit: "contain", background }).keepIccProfile().png().toBuffer();
|
||||
}
|
||||
|
||||
async function saveBatchInstructionImage(image: Buffer) {
|
||||
const thumbnail = await sharp(image).resize(512, 512, { fit: "inside", withoutEnlargement: true }).png().toBuffer();
|
||||
const id = randomUUID();
|
||||
const upload = (name: string, file: Buffer) => uploadFile(
|
||||
name,
|
||||
@ -38,8 +46,32 @@ export async function squareBatchInstructionOutput(image: { originalUrl: string;
|
||||
{ preferQiniuForm: true },
|
||||
);
|
||||
const [original, preview] = await Promise.all([
|
||||
upload(`batch-instruction-${id}.png`, padded),
|
||||
upload(`batch-instruction-${id}.png`, image),
|
||||
upload(`batch-instruction-${id}-thumb.png`, thumbnail),
|
||||
]);
|
||||
return { ...image, originalUrl: original.url, thumbnailUrl: preview.url };
|
||||
return { originalUrl: original.url, thumbnailUrl: preview.url };
|
||||
}
|
||||
|
||||
export async function formatBatchInstructionOutput<T extends { originalUrl: string; thumbnailUrl: string }>(
|
||||
generated: T,
|
||||
size?: BatchInstructionSize,
|
||||
) {
|
||||
const bytes = await fetchImageBufferFromUrl(generated.originalUrl);
|
||||
const output = size ? await fitBatchInstructionImage(bytes, size) : await padImageToSquare(bytes);
|
||||
return output ? { ...generated, ...await saveBatchInstructionImage(output) } : generated;
|
||||
}
|
||||
|
||||
export async function resizeBatchInstructionInput(source: string, size: BatchInstructionSize) {
|
||||
const target = await resolveS3UploadTarget();
|
||||
if (!target) throw new Error("图片存储暂不可用");
|
||||
const base = new URL(buildS3PublicUrl(target.config, ""));
|
||||
const image = new URL(source);
|
||||
if (image.origin !== base.origin || !image.pathname.startsWith(base.pathname) || image.pathname === base.pathname) {
|
||||
throw new Error("请重新上传待调整尺寸的图片");
|
||||
}
|
||||
|
||||
const response = await fetch(image, { redirect: "error", signal: AbortSignal.timeout(20_000) });
|
||||
if (!response.ok) throw new Error("无法读取待调整尺寸的图片");
|
||||
const output = await fitBatchInstructionImage(Buffer.from(await response.arrayBuffer()), size);
|
||||
return await saveBatchInstructionImage(output);
|
||||
}
|
||||
|
||||
9
lib/canvas/batch-instruction-size.ts
Normal file
9
lib/canvas/batch-instruction-size.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const dimension = z.number().int().min(1).max(8192);
|
||||
|
||||
export const batchInstructionSizeSchema = z
|
||||
.object({ width: dimension, height: dimension })
|
||||
.refine(({ width, height }) => width * height <= 24_000_000);
|
||||
|
||||
export type BatchInstructionSize = z.infer<typeof batchInstructionSizeSchema>;
|
||||
@ -188,6 +188,7 @@ export interface CanvasGenerateImageRequest {
|
||||
billingFeature?: "multi-view" | "repaint";
|
||||
requiredReferenceImageCount?: number;
|
||||
padBatchInstructionToSquare?: boolean;
|
||||
batchInstructionOutputSize?: import("./batch-instruction-size").BatchInstructionSize;
|
||||
batchInstructionWithReference?: boolean;
|
||||
batchInstructionFaceEdit?: boolean;
|
||||
ownerKey?: string;
|
||||
|
||||
@ -403,6 +403,18 @@ async function runSingleTask(entry: PendingTaskEntry) {
|
||||
: (async () => {
|
||||
const imageRequest = request as CanvasGenerateImageRequest;
|
||||
const ownerKey = String(task.userId || entry.userId);
|
||||
const outputSize = imageRequest.batchInstructionOutputSize;
|
||||
if (outputSize && !imageRequest.prompt) {
|
||||
const source = imageRequest.referenceImages?.[0];
|
||||
if (!source) throw new Error("缺少待调整尺寸的原图");
|
||||
const { resizeBatchInstructionInput } = await import("./batch-instruction-output");
|
||||
return {
|
||||
images: [await resizeBatchInstructionInput(source, outputSize)],
|
||||
model: "resize-1.0",
|
||||
modelRef: "resize-1.0",
|
||||
prompt: "批量调整图片尺寸",
|
||||
};
|
||||
}
|
||||
const prepared = imageRequest.batchInstructionWithReference
|
||||
? await (await import("./batch-instruction-reference")).prepareBatchInstructionWithReference(imageRequest)
|
||||
: imageRequest;
|
||||
@ -410,15 +422,15 @@ async function runSingleTask(entry: PendingTaskEntry) {
|
||||
...prepared,
|
||||
ownerKey,
|
||||
});
|
||||
if (imageRequest.padBatchInstructionToSquare) {
|
||||
const { squareBatchInstructionOutput } = await import("./batch-instruction-output");
|
||||
if (outputSize || imageRequest.padBatchInstructionToSquare) {
|
||||
const { formatBatchInstructionOutput } = await import("./batch-instruction-output");
|
||||
try {
|
||||
return {
|
||||
...initialResult,
|
||||
images: await Promise.all(initialResult.images.map(squareBatchInstructionOutput)),
|
||||
images: await Promise.all(initialResult.images.map(image => formatBatchInstructionOutput(image, outputSize))),
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn("[BatchInstruction] Square output failed", { taskId: task.id, error });
|
||||
console.warn("[BatchInstruction] Sized output failed", { taskId: task.id, error });
|
||||
throw new Error("图片已生成,但补边结果尚未确认。请核对原任务,避免重复生成。");
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import type { ParsedImage } from "@/lib/canvas/generate-image";
|
||||
import type { BatchInstructionSize } from "@/lib/canvas/batch-instruction-size";
|
||||
|
||||
const statusEndpoint = "/api/canvas/generate/image";
|
||||
type InstructionTask = {
|
||||
@ -20,6 +21,7 @@ export async function runBatchInstructionEdit(input: {
|
||||
reference?: string;
|
||||
instruction: string;
|
||||
square: boolean;
|
||||
outputSize?: BatchInstructionSize;
|
||||
submitted?: boolean;
|
||||
}, onSubmitted: () => void) {
|
||||
const taskPath = `${statusEndpoint}?taskId=${encodeURIComponent(input.taskId)}`;
|
||||
|
||||
@ -107,3 +107,75 @@ test("a product replacement that preserves the face still uses local product edi
|
||||
const cropped = await sharp(prepared.referenceImageBuffers.get(reference)).metadata();
|
||||
expect([cropped.width, cropped.height]).toEqual([150, 180]);
|
||||
});
|
||||
|
||||
test("custom width and height keep the whole image and pad both orientations", async () => {
|
||||
const { fitBatchInstructionImage } = serverLoader({
|
||||
"@/lib/ai/rmbg/service": {},
|
||||
"@/lib/storage/service": {},
|
||||
})("lib/canvas/batch-instruction-output.ts");
|
||||
|
||||
for (const [width, height] of [[400, 200], [200, 400]]) {
|
||||
const subject = await sharp({
|
||||
create: { width: 100, height: 100, channels: 3, background: "#f00000" },
|
||||
}).png().toBuffer();
|
||||
const source = await sharp({
|
||||
create: { width, height, channels: 3, background: "#132639" },
|
||||
}).composite([{ input: subject, left: (width - 100) / 2, top: (height - 100) / 2 }]).png().toBuffer();
|
||||
const result = await fitBatchInstructionImage(source, { width: 800, height: 1000 });
|
||||
const { data, info } = await sharp(result).removeAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
expect([info.width, info.height]).toEqual([800, 1000]);
|
||||
const red = { minX: 800, maxX: 0, minY: 1000, maxY: 0 };
|
||||
for (let y = 0; y < info.height; y++) {
|
||||
for (let x = 0; x < info.width; x++) {
|
||||
const index = (y * info.width + x) * info.channels;
|
||||
if (data[index] <= 180 || data[index + 1] >= 70) continue;
|
||||
red.minX = Math.min(red.minX, x);
|
||||
red.maxX = Math.max(red.maxX, x);
|
||||
red.minY = Math.min(red.minY, y);
|
||||
red.maxY = Math.max(red.maxY, y);
|
||||
}
|
||||
}
|
||||
const subjectSize = width > height ? 200 : 250;
|
||||
expect(Math.abs(red.maxX - red.minX + 1 - subjectSize)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(red.maxY - red.minY + 1 - subjectSize)).toBeLessThanOrEqual(1);
|
||||
expect(Array.from(data.subarray(0, 3))).toEqual([19, 38, 57]);
|
||||
}
|
||||
});
|
||||
|
||||
test("custom dimensions allow a resize-only task and reject invalid inputs", async () => {
|
||||
const queued: Array<Record<string, unknown>> = [];
|
||||
const { POST } = serverLoader({
|
||||
"@/app/(auth)/auth": { auth: async () => ({ user: { id: "test-owner" } }) },
|
||||
"@/lib/db/queries": { getSystemSetting: async () => null },
|
||||
"@/lib/canvas/image-task-queue": {
|
||||
createCanvasImageTask: async (params: { request: Record<string, unknown>; taskId: string }) => {
|
||||
queued.push(params.request);
|
||||
return { id: params.taskId, status: "pending" };
|
||||
},
|
||||
enqueueCanvasImageTask: async () => {},
|
||||
},
|
||||
})("app/api/canvas/batch-instruction/route.ts");
|
||||
|
||||
const request = {
|
||||
taskId: randomUUID(),
|
||||
image: "https://media.example/source.png",
|
||||
instruction: "",
|
||||
square: false,
|
||||
outputSize: { width: 800, height: 1000 },
|
||||
};
|
||||
const submit = (options: Record<string, unknown> = {}) => POST(new Request("https://app.example/api/canvas/batch-instruction", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ...request, ...options }),
|
||||
}));
|
||||
|
||||
expect((await submit()).status).toBe(202);
|
||||
expect(queued[0]).toMatchObject({
|
||||
prompt: "",
|
||||
referenceImages: [request.image],
|
||||
batchInstructionOutputSize: { width: 800, height: 1000 },
|
||||
});
|
||||
expect((await submit({ outputSize: { width: 8192, height: 8192 } })).status).toBe(400);
|
||||
expect((await submit({ outputSize: { width: 0, height: 1000 } })).status).toBe(400);
|
||||
expect((await submit({ reference: "https://media.example/reference.png" })).status).toBe(400);
|
||||
expect(queued).toHaveLength(1);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user