diff --git a/app/api/canvas/local-edit/route.ts b/app/api/canvas/local-edit/route.ts index 33cbf15e6..e51ac90d5 100644 --- a/app/api/canvas/local-edit/route.ts +++ b/app/api/canvas/local-edit/route.ts @@ -17,6 +17,7 @@ import { import { modelLacksReferenceImageInputSupport, } from "@/lib/ai/reference-image-capability"; +import { isFalGptImage2EditModelId } from "@/lib/ai/providers/fal-image"; import { getImageToolCreditCost } from "@/lib/points/config"; import { prepareFeaturePointsCharge } from "@/lib/points/feature-charge"; import { uploadFile } from "@/lib/storage/service"; @@ -100,6 +101,11 @@ const MAX_REFERENCE_IMAGES_PER_REGION = 3; const MAX_SCALE_ADJUST_CROP_REFERENCES = 4; const SCALE_ADJUST_CROP_PADDING_RATIO = 0.18; const SCALE_ADJUST_CROP_MAX_EDGE = 1536; +const SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN = 0.045; +const SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN = 0.18; +const SCALE_ADJUST_LAYOUT_GUIDE_WASH_COLOR = "#f5f7fb"; +const SCALE_ADJUST_STRUCTURE_LOCK_MIN_MASK_RATIO = 0.006; +const SCALE_ADJUST_STRUCTURE_LOCK_COMPONENT_MIN_RATIO = 0.00018; const MIN_REGION_EDGE_PX = 24; const SCALE_ADJUST_OPERATION = "scale-adjust"; type LocalEditOperation = "local-edit" | typeof SCALE_ADJUST_OPERATION; @@ -110,6 +116,18 @@ type ScaleAdjustCropReference = { regionIndex: number; url: string; }; +type ScaleAdjustPatchReference = { + sourceCropUrl: string; + structureLockedDraft?: boolean; + targetDraftUrl: string; + workspaceRect: NormalizedLocalEditRegion["rect"]; + workspacePixelRect: { + left: number; + top: number; + width: number; + height: number; + }; +}; type AiModelWithProviderForSelection = Awaited< ReturnType >[number]; @@ -277,6 +295,19 @@ function getScaleAdjustModelFamily( ); } +function isScaleAdjustMaskCapableModel( + entry: AiModelWithProviderForSelection | null | undefined +) { + if (!entry || getScaleAdjustModelFamily(entry) !== "gpt-image-2") { + return false; + } + if (entry.provider.type === "openai-image") return true; + if (entry.provider.type === "fal-image") { + return isFalGptImage2EditModelId(entry.model.modelId || ""); + } + return false; +} + function isScaleAdjustCoordinateGuideModel( entry: AiModelWithProviderForSelection | null | undefined ) { @@ -355,6 +386,7 @@ function compareScaleAdjustProviderCandidates( function resolveScaleAdjustPreferredModelId(params: { configuredModelId: string; + honorRequestedModelBeforeGpt?: boolean; requestedModelId: string; models: AiModelWithProviderForSelection[]; }) { @@ -366,6 +398,37 @@ function resolveScaleAdjustPreferredModelId(params: { params.models, params.configuredModelId ); + if ( + params.honorRequestedModelBeforeGpt && + requestedModel && + isScaleAdjustUsableImageEditModel(requestedModel) + ) { + return requestedModel.model.id || params.requestedModelId; + } + + const gptImage2Candidates = params.models + .filter((entry) => isScaleAdjustUsableImageEditModel(entry)) + .filter((entry) => getScaleAdjustModelFamily(entry) === "gpt-image-2") + .sort((left, right) => + compareScaleAdjustProviderCandidates( + left, + right, + params.requestedModelId || params.configuredModelId + ) + ); + if (gptImage2Candidates[0]) { + return gptImage2Candidates[0].model.id; + } + + if ( + isScaleAdjustUsableImageEditModel(requestedModel) && + requestedModel && + getScaleAdjustModelFamily(requestedModel) !== "nano-banana-2" && + requestedModel.provider.type !== "alibaba-image" + ) { + return requestedModel.model.id || params.requestedModelId; + } + const autoDetailModel = params.models.find(isScaleAdjustDedicatedDetailModel); const preferredModel = (isScaleAdjustDedicatedDetailModel(requestedModel) ? requestedModel : null) || @@ -563,6 +626,20 @@ function getScaleAdjustTargetRect( return region.rect; } +function hasScaleAdjustEnlargeTarget( + regions: NormalizedLocalEditRegion[], + scalePercent?: ScaleAdjustPercent | null +) { + return regions.some((region) => { + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const widthFactor = + region.rect.width > 0 ? targetRect.width / region.rect.width : 1; + const heightFactor = + region.rect.height > 0 ? targetRect.height / region.rect.height : 1; + return widthFactor > 1.08 || heightFactor > 1.08; + }); +} + function expandRectWithMargins( rect: NormalizedLocalEditRegion["rect"], marginX: number, @@ -692,6 +769,39 @@ function buildScaleAdjustCompositeRegions( }); } +function getScaleAdjustPatchWorkspaceRect( + regions: NormalizedLocalEditRegion[], + scalePercent?: ScaleAdjustPercent | null +) { + const workspaceRects = regions.map((region) => { + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const baseWorkspace = getScaleAdjustWorkspaceRect( + region.rect, + targetRect, + scalePercent + ); + const marginX = Math.min( + SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN, + Math.max( + SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN, + baseWorkspace.width * 0.22, + region.rect.width * 0.18 + ) + ); + const marginY = Math.min( + SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN, + Math.max( + SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN, + baseWorkspace.height * 0.22, + region.rect.height * 0.18 + ) + ); + return expandRectWithMargins(baseWorkspace, marginX, marginY); + }); + + return workspaceRects.reduce((combined, rect) => getRectUnion(combined, rect)); +} + function expandPixelRectForCrop(params: { height: number; pixelRect: NormalizedLocalEditRegion["pixelRect"]; @@ -731,11 +841,17 @@ async function createScaleAdjustCropReferences(params: { const regionsForCrop = params.regions.slice(0, MAX_SCALE_ADJUST_CROP_REFERENCES); for (const region of regionsForCrop) { - const cropBox = expandPixelRectForCrop({ - height: params.sourceHeight, - pixelRect: region.pixelRect, - width: params.sourceWidth, + const focusBox = getScaleAdjustFocusedSourceBox({ + region, + sourceBox: region.pixelRect, }); + const cropBox = getScaleAdjustFocusDirection(region) + ? focusBox + : expandPixelRectForCrop({ + height: params.sourceHeight, + pixelRect: region.pixelRect, + width: params.sourceWidth, + }); const cropBuffer = await sharp(params.sourceBuffer, { failOn: "none" }) .extract(cropBox) .resize({ @@ -761,6 +877,1122 @@ async function createScaleAdjustCropReferences(params: { return references; } +function getScaleAdjustVisualGuidePlacement(params: { + height: number; + region: NormalizedLocalEditRegion; + scalePercent?: ScaleAdjustPercent | null; + width: number; +}) { + const { height, region, scalePercent, width } = params; + const source = region.pixelRect; + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const target = region.targetPixelRect || rectToPixels(targetRect, width, height); + const sourceLeft = clamp(source.left, 0, Math.max(0, width - 1)); + const sourceTop = clamp(source.top, 0, Math.max(0, height - 1)); + const sourceRight = clamp( + source.left + source.width, + sourceLeft + 1, + width + ); + const sourceBottom = clamp( + source.top + source.height, + sourceTop + 1, + height + ); + const sourceFootprintBox = { + left: Math.round(sourceLeft), + top: Math.round(sourceTop), + width: Math.max(1, Math.round(sourceRight - sourceLeft)), + height: Math.max(1, Math.round(sourceBottom - sourceTop)), + }; + const sourceBox = getScaleAdjustFocusedSourceBox({ + region, + sourceBox: sourceFootprintBox, + }); + const sourceWidth = sourceBox.width; + const sourceHeight = sourceBox.height; + const widthScale = target.width / Math.max(1, sourceWidth); + const heightScale = target.height / Math.max(1, sourceHeight); + const uniformScale = Math.max( + 0.05, + Math.min( + Number.isFinite(widthScale) && widthScale > 0 ? widthScale : 1, + Number.isFinite(heightScale) && heightScale > 0 ? heightScale : 1 + ) + ); + const placedWidth = clamp( + Math.round(sourceWidth * uniformScale), + 1, + Math.max(1, width) + ); + const placedHeight = clamp( + Math.round(sourceHeight * uniformScale), + 1, + Math.max(1, height) + ); + const targetCenterX = target.left + target.width / 2; + const targetCenterY = target.top + target.height / 2; + const placedLeft = clamp( + Math.round(targetCenterX - placedWidth / 2), + 0, + Math.max(0, width - placedWidth) + ); + const placedTop = clamp( + Math.round(targetCenterY - placedHeight / 2), + 0, + Math.max(0, height - placedHeight) + ); + + return { + placedHeight: Math.max(1, Math.round(placedHeight)), + placedLeft: Math.max(0, Math.round(placedLeft)), + placedTop: Math.max(0, Math.round(placedTop)), + placedWidth: Math.max(1, Math.round(placedWidth)), + sourceBox: { + left: sourceBox.left, + top: sourceBox.top, + width: sourceWidth, + height: sourceHeight, + }, + sourceFootprintBox, + targetBox: target, + uniformScale, + }; +} + +function getScaleAdjustFocusDirection(region: NormalizedLocalEditRegion) { + const text = normalizeScaleAdjustModelText(region.prompt); + const compact = text.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, ""); + if (text.includes("left") || compact.includes("左")) return "left"; + if (text.includes("right") || compact.includes("右")) return "right"; + if (text.includes("top") || compact.includes("上")) return "top"; + if (text.includes("bottom") || compact.includes("下")) return "bottom"; + return ""; +} + +function getScaleAdjustFocusedSourceBox(params: { + region: NormalizedLocalEditRegion; + sourceBox: { left: number; top: number; width: number; height: number }; +}) { + const { region, sourceBox } = params; + const direction = getScaleAdjustFocusDirection(region); + if (!direction) return sourceBox; + + const minWidth = Math.max(1, Math.round(sourceBox.width * 0.42)); + const minHeight = Math.max(1, Math.round(sourceBox.height * 0.42)); + let left = sourceBox.left; + let top = sourceBox.top; + let width = sourceBox.width; + let height = sourceBox.height; + + if (direction === "left") { + width = Math.max(minWidth, Math.round(sourceBox.width * 0.68)); + } else if (direction === "right") { + const nextWidth = Math.max(minWidth, Math.round(sourceBox.width * 0.68)); + left = sourceBox.left + sourceBox.width - nextWidth; + width = nextWidth; + } else if (direction === "top") { + height = Math.max(minHeight, Math.round(sourceBox.height * 0.72)); + } else if (direction === "bottom") { + const nextHeight = Math.max(minHeight, Math.round(sourceBox.height * 0.72)); + top = sourceBox.top + sourceBox.height - nextHeight; + height = nextHeight; + } + + return { + left, + top, + width, + height, + }; +} + +function buildScaleAdjustPatchMaskSvg(params: { height: number; width: number }) { + const { height, width } = params; + const blur = Math.max(2, Math.min(14, Math.round(Math.min(width, height) * 0.035))); + const inset = Math.min( + Math.floor(Math.min(width, height) / 8), + Math.max(1, Math.round(blur * 0.7)) + ); + const rectWidth = Math.max(1, width - inset * 2); + const rectHeight = Math.max(1, height - inset * 2); + + return Buffer.from( + ` + + + + + + + ` + ); +} + +function buildScaleAdjustSourceFootprintWashSvg(params: { + boxes: Array<{ left: number; top: number; width: number; height: number }>; + height: number; + width: number; +}) { + const { boxes, height, width } = params; + const blur = Math.max(4, Math.min(22, Math.round(Math.min(width, height) * 0.016))); + const rects = boxes + .map((box) => { + const left = Math.max(0, box.left - blur); + const top = Math.max(0, box.top - blur); + const right = Math.min(width, box.left + box.width + blur); + const bottom = Math.min(height, box.top + box.height + blur); + return ``; + }) + .join(""); + + return Buffer.from( + ` + + + + + + ${rects} + ` + ); +} + +function buildScaleAdjustTargetFootprintShadowSvg(params: { + height: number; + placements: Array>; + width: number; +}) { + const { height, placements, width } = params; + const minSide = Math.max(1, Math.min(width, height)); + const blur = Math.max(4, Math.min(18, Math.round(minSide * 0.014))); + const rects = placements + .map((placement) => { + const pad = Math.max(2, Math.round(blur * 0.45)); + const left = clamp( + placement.placedLeft - pad, + 0, + Math.max(0, width - 1) + ); + const top = clamp( + placement.placedTop - pad, + 0, + Math.max(0, height - 1) + ); + const right = clamp( + placement.placedLeft + placement.placedWidth + pad, + left + 1, + width + ); + const bottom = clamp( + placement.placedTop + placement.placedHeight + pad, + top + 1, + height + ); + const radius = Math.max(4, Math.round(blur * 1.2)); + return ``; + }) + .join(""); + + return Buffer.from( + ` + + + + + + ${rects} + ` + ); +} + +function getScaleAdjustRawPixelIndex(width: number, x: number, y: number) { + return (y * width + x) * 3; +} + +function getScaleAdjustPixelLuma(r: number, g: number, b: number) { + return r * 0.299 + g * 0.587 + b * 0.114; +} + +function getScaleAdjustPixelStats(r: number, g: number, b: number) { + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + return { + luma: getScaleAdjustPixelLuma(r, g, b), + saturation: max > 0 ? (max - min) / max : 0, + }; +} + +function isScaleAdjustLikelySkinPixel(r: number, g: number, b: number) { + return ( + r > 132 && + g > 82 && + b > 58 && + r > g * 1.06 && + g > b * 1.03 && + r - b < 135 + ); +} + +function isScaleAdjustLikelyWhiteFabricPixel( + r: number, + g: number, + b: number, + luma: number, + saturation: number +) { + return ( + luma > 158 && + saturation < 0.3 && + Math.abs(r - g) < 34 && + Math.abs(g - b) < 44 + ); +} + +function estimateScaleAdjustBoxBackground(params: { + box: { left: number; top: number; width: number; height: number }; + raw: Buffer; + width: number; +}) { + const { box, raw, width } = params; + const samples: Array<{ b: number; g: number; luma: number; r: number }> = []; + const borderX = Math.max(2, Math.round(box.width * 0.08)); + const borderY = Math.max(2, Math.round(box.height * 0.08)); + + for (let localY = 0; localY < box.height; localY += 1) { + const y = box.top + localY; + const isBorderY = localY < borderY || localY >= box.height - borderY; + for (let localX = 0; localX < box.width; localX += 1) { + const isBorderX = localX < borderX || localX >= box.width - borderX; + if (!isBorderX && !isBorderY) continue; + const x = box.left + localX; + const rawIndex = getScaleAdjustRawPixelIndex(width, x, y); + const r = raw[rawIndex] || 0; + const g = raw[rawIndex + 1] || 0; + const b = raw[rawIndex + 2] || 0; + const { luma, saturation } = getScaleAdjustPixelStats(r, g, b); + if (isScaleAdjustLikelySkinPixel(r, g, b)) continue; + if (saturation > 0.42 && luma < 185) continue; + samples.push({ b, g, luma, r }); + } + } + + if (samples.length === 0) { + return { b: 245, g: 247, luma: 246, r: 245 }; + } + + samples.sort((left, right) => right.luma - left.luma); + const kept = samples.slice(0, Math.max(12, Math.ceil(samples.length * 0.38))); + const totals = kept.reduce( + (acc, sample) => { + acc.r += sample.r; + acc.g += sample.g; + acc.b += sample.b; + acc.luma += sample.luma; + return acc; + }, + { b: 0, g: 0, luma: 0, r: 0 } + ); + + return { + b: totals.b / kept.length, + g: totals.g / kept.length, + luma: totals.luma / kept.length, + r: totals.r / kept.length, + }; +} + +function dilateScaleAdjustStructureMask(params: { + height: number; + mask: Uint8Array; + radius: number; + width: number; +}) { + const { height, mask, radius, width } = params; + if (radius <= 0) return mask; + const output = new Uint8Array(mask.length); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + if (mask[y * width + x] === 0) continue; + const left = Math.max(0, x - radius); + const right = Math.min(width - 1, x + radius); + const top = Math.max(0, y - radius); + const bottom = Math.min(height - 1, y + radius); + for (let yy = top; yy <= bottom; yy += 1) { + for (let xx = left; xx <= right; xx += 1) { + output[yy * width + xx] = 255; + } + } + } + } + return output; +} + +function buildScaleAdjustStructureInitialMask(params: { + box: { left: number; top: number; width: number; height: number }; + raw: Buffer; + width: number; +}) { + const { box, raw, width } = params; + const background = estimateScaleAdjustBoxBackground(params); + const mask = new Uint8Array(box.width * box.height); + + for (let localY = 0; localY < box.height; localY += 1) { + const y = box.top + localY; + for (let localX = 0; localX < box.width; localX += 1) { + if (localX >= box.width * 0.9) continue; + const x = box.left + localX; + const rawIndex = getScaleAdjustRawPixelIndex(width, x, y); + const r = raw[rawIndex] || 0; + const g = raw[rawIndex + 1] || 0; + const b = raw[rawIndex + 2] || 0; + const { luma, saturation } = getScaleAdjustPixelStats(r, g, b); + if (isScaleAdjustLikelySkinPixel(r, g, b)) continue; + if (isScaleAdjustLikelyWhiteFabricPixel(r, g, b, luma, saturation)) { + continue; + } + + const colorDistance = Math.sqrt( + (r - background.r) ** 2 + + (g - background.g) ** 2 + + (b - background.b) ** 2 + ); + const darkStructure = luma < Math.min(136, background.luma - 38); + const saturatedStructure = + saturation > 0.16 && luma < 218 && colorDistance > 38; + const woodOrCaneStructure = + r > 46 && + g > 26 && + b < 132 && + r >= g * 0.9 && + g >= b * 1.02 && + saturation > 0.18 && + luma < 218; + + if (darkStructure || saturatedStructure || woodOrCaneStructure) { + mask[localY * box.width + localX] = 255; + } + } + } + + return dilateScaleAdjustStructureMask({ + height: box.height, + mask, + radius: Math.max(1, Math.round(Math.min(box.width, box.height) * 0.004)), + width: box.width, + }); +} + +function filterScaleAdjustStructureComponents(params: { + box: { width: number; height: number }; + mask: Uint8Array; +}) { + const { box, mask } = params; + const width = box.width; + const height = box.height; + const visited = new Uint8Array(mask.length); + const output = new Uint8Array(mask.length); + const queueX: number[] = []; + const queueY: number[] = []; + const minComponentArea = Math.max( + 10, + Math.round(width * height * SCALE_ADJUST_STRUCTURE_LOCK_COMPONENT_MIN_RATIO) + ); + + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const startIndex = y * width + x; + if (mask[startIndex] === 0 || visited[startIndex]) continue; + + queueX.length = 0; + queueY.length = 0; + queueX.push(x); + queueY.push(y); + visited[startIndex] = 1; + let head = 0; + let area = 0; + let minX = x; + let minY = y; + let maxX = x; + let maxY = y; + + while (head < queueX.length) { + const cx = queueX[head] || 0; + const cy = queueY[head] || 0; + head += 1; + area += 1; + minX = Math.min(minX, cx); + minY = Math.min(minY, cy); + maxX = Math.max(maxX, cx); + maxY = Math.max(maxY, cy); + + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) { + if (dx === 0 && dy === 0) continue; + const nx = cx + dx; + const ny = cy + dy; + if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue; + const nextIndex = ny * width + nx; + if (mask[nextIndex] === 0 || visited[nextIndex]) continue; + visited[nextIndex] = 1; + queueX.push(nx); + queueY.push(ny); + } + } + } + + const componentWidth = maxX - minX + 1; + const componentHeight = maxY - minY + 1; + const componentBoxArea = Math.max(1, componentWidth * componentHeight); + const componentDensity = area / componentBoxArea; + const centerXRatio = (minX + componentWidth / 2) / width; + const touchesRight = maxX >= width * 0.88; + const edgeSliver = touchesRight && componentWidth < width * 0.18; + const elongated = + componentHeight > componentWidth * 2.4 || + componentWidth > componentHeight * 2.4; + const likelyStructure = + area >= minComponentArea || + (elongated && area >= Math.max(8, minComponentArea * 0.4)); + const centeredEnough = centerXRatio >= 0.04 && centerXRatio <= 0.88; + const fillSurfaceComponent = + componentWidth >= width * 0.14 && + componentHeight >= height * 0.045 && + componentWidth <= width * 0.82 && + componentHeight <= height * 0.42 && + componentDensity >= 0.035 && + componentDensity <= 0.72; + + if (likelyStructure && centeredEnough && !edgeSliver) { + if (fillSurfaceComponent) { + for (let fillY = minY; fillY <= maxY; fillY += 1) { + for (let fillX = minX; fillX <= maxX; fillX += 1) { + output[fillY * width + fillX] = 255; + } + } + } else { + for (let index = 0; index < queueX.length; index += 1) { + output[(queueY[index] || 0) * width + (queueX[index] || 0)] = 255; + } + } + } + } + } + + return dilateScaleAdjustStructureMask({ + height, + mask: output, + radius: Math.max(1, Math.round(Math.min(width, height) * 0.006)), + width, + }); +} + +function solidifyScaleAdjustStructureMask(params: { + box: { width: number; height: number }; + mask: Uint8Array; +}) { + const { box, mask } = params; + const width = box.width; + const height = box.height; + const bridgeGap = Math.max(2, Math.round(Math.min(width, height) * 0.006)); + const output = dilateScaleAdjustStructureMask({ + height, + mask, + radius: Math.max(1, Math.round(Math.min(width, height) * 0.004)), + width, + }); + + for (let y = 0; y < height; y += 1) { + let x = 0; + while (x < width) { + while (x < width && output[y * width + x] !== 0) x += 1; + const gapStart = x; + while (x < width && output[y * width + x] === 0) x += 1; + const gapEnd = x - 1; + const gapLength = gapEnd - gapStart + 1; + if ( + gapLength > 0 && + gapLength <= bridgeGap && + gapStart > 0 && + gapEnd < width - 1 && + output[y * width + gapStart - 1] !== 0 && + output[y * width + gapEnd + 1] !== 0 + ) { + for (let fillX = gapStart; fillX <= gapEnd; fillX += 1) { + output[y * width + fillX] = 255; + } + } + } + } + + for (let x = 0; x < width; x += 1) { + let y = 0; + while (y < height) { + while (y < height && output[y * width + x] !== 0) y += 1; + const gapStart = y; + while (y < height && output[y * width + x] === 0) y += 1; + const gapEnd = y - 1; + const gapLength = gapEnd - gapStart + 1; + if ( + gapLength > 0 && + gapLength <= bridgeGap && + gapStart > 0 && + gapEnd < height - 1 && + output[(gapStart - 1) * width + x] !== 0 && + output[(gapEnd + 1) * width + x] !== 0 + ) { + for (let fillY = gapStart; fillY <= gapEnd; fillY += 1) { + output[fillY * width + x] = 255; + } + } + } + } + + const panelRowThreshold = Math.max(8, Math.round(width * 0.055)); + const panelMinHeight = Math.max(12, Math.round(height * 0.035)); + const panelMaxGap = Math.max(1, Math.round(height * 0.006)); + let panelStart = -1; + let panelGap = 0; + const getRowMarkedCount = (rowY: number) => { + let count = 0; + for (let rowX = 0; rowX < width; rowX += 1) { + if (output[rowY * width + rowX] !== 0) count += 1; + } + return count; + }; + const fillPanelBand = (startY: number, endY: number) => { + const bandHeight = endY - startY + 1; + if (bandHeight < panelMinHeight) return; + let minX = width; + let maxX = -1; + let marked = 0; + for (let bandY = startY; bandY <= endY; bandY += 1) { + for (let bandX = 0; bandX < width; bandX += 1) { + if (output[bandY * width + bandX] === 0) continue; + minX = Math.min(minX, bandX); + maxX = Math.max(maxX, bandX); + marked += 1; + } + } + if (maxX < minX) return; + const span = maxX - minX + 1; + const density = marked / Math.max(1, span * bandHeight); + if ( + span < width * 0.16 || + span > width * 0.86 || + density < 0.025 || + density > 0.78 + ) { + return; + } + for (let fillY = startY; fillY <= endY; fillY += 1) { + for (let fillX = minX; fillX <= maxX; fillX += 1) { + output[fillY * width + fillX] = 255; + } + } + }; + + for (let y = 0; y < height; y += 1) { + const hasPanelRow = getRowMarkedCount(y) >= panelRowThreshold; + if (hasPanelRow) { + if (panelStart < 0) panelStart = y; + panelGap = 0; + continue; + } + if (panelStart < 0) continue; + panelGap += 1; + if (panelGap <= panelMaxGap) continue; + fillPanelBand(panelStart, y - panelGap); + panelStart = -1; + panelGap = 0; + } + if (panelStart >= 0) { + fillPanelBand(panelStart, height - 1 - panelGap); + } + + return dilateScaleAdjustStructureMask({ + height, + mask: output, + radius: Math.max(1, Math.round(Math.min(width, height) * 0.004)), + width, + }); +} + +function getScaleAdjustMaskBoundingBox(params: { + height: number; + mask: Uint8Array; + width: number; +}) { + const { height, mask, width } = params; + let left = width; + let top = height; + let right = -1; + let bottom = -1; + let count = 0; + + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + if (mask[y * width + x] === 0) continue; + left = Math.min(left, x); + top = Math.min(top, y); + right = Math.max(right, x); + bottom = Math.max(bottom, y); + count += 1; + } + } + + if (right < left || bottom < top) return null; + return { + count, + left, + top, + width: right - left + 1, + height: bottom - top + 1, + }; +} + +function extractScaleAdjustMaskBuffer(params: { + box: { left: number; top: number; width: number; height: number }; + mask: Uint8Array; + maskWidth: number; +}) { + const { box, mask, maskWidth } = params; + const output = Buffer.alloc(box.width * box.height); + for (let y = 0; y < box.height; y += 1) { + const sourceStart = (box.top + y) * maskWidth + box.left; + const targetStart = y * box.width; + for (let x = 0; x < box.width; x += 1) { + output[targetStart + x] = mask[sourceStart + x] || 0; + } + } + return output; +} + +async function buildScaleAdjustMaskWashPatch(params: { + background: { b: number; g: number; r: number }; + box: { width: number; height: number }; + maskBuffer: Buffer; +}) { + const { background, box, maskBuffer } = params; + const alpha = await sharp(maskBuffer, { + raw: { channels: 1, height: box.height, width: box.width }, + }) + .blur(Math.max(1.2, Math.min(box.width, box.height) * 0.018)) + .raw() + .toBuffer(); + const rgba = Buffer.alloc(box.width * box.height * 4); + for (let index = 0; index < box.width * box.height; index += 1) { + const offset = index * 4; + rgba[offset] = Math.round(background.r); + rgba[offset + 1] = Math.round(background.g); + rgba[offset + 2] = Math.round(background.b); + rgba[offset + 3] = Math.round((alpha[index] || 0) * 0.9); + } + return sharp(rgba, { + raw: { channels: 4, height: box.height, width: box.width }, + }) + .png({ compressionLevel: 6 }) + .toBuffer(); +} + +async function buildScaleAdjustStructureLockedComposite(params: { + placement: ReturnType; + raw: Buffer; + sourceBuffer: Buffer; + sourceWidth: number; +}) { + const { placement, raw, sourceBuffer, sourceWidth } = params; + const initialMask = buildScaleAdjustStructureInitialMask({ + box: placement.sourceBox, + raw, + width: sourceWidth, + }); + const mask = filterScaleAdjustStructureComponents({ + box: placement.sourceBox, + mask: initialMask, + }); + const structureBbox = getScaleAdjustMaskBoundingBox({ + height: placement.sourceBox.height, + mask, + width: placement.sourceBox.width, + }); + if (!structureBbox) return null; + const maskRatio = structureBbox.count / Math.max(1, placement.sourceBox.width * placement.sourceBox.height); + if (maskRatio < SCALE_ADJUST_STRUCTURE_LOCK_MIN_MASK_RATIO) return null; + const subjectMask = solidifyScaleAdjustStructureMask({ + box: placement.sourceBox, + mask, + }); + const bbox = getScaleAdjustMaskBoundingBox({ + height: placement.sourceBox.height, + mask: subjectMask, + width: placement.sourceBox.width, + }); + if (!bbox) return null; + + const sourceSubjectBox = { + left: placement.sourceBox.left + bbox.left, + top: placement.sourceBox.top + bbox.top, + width: bbox.width, + height: bbox.height, + }; + const sourceSubjectMask = extractScaleAdjustMaskBuffer({ + box: bbox, + mask: subjectMask, + maskWidth: placement.sourceBox.width, + }); + const background = estimateScaleAdjustBoxBackground({ + box: placement.sourceBox, + raw, + width: sourceWidth, + }); + const sourceWashMask = dilateScaleAdjustStructureMask({ + height: placement.sourceBox.height, + mask: subjectMask, + radius: Math.max( + 2, + Math.round(Math.min(placement.sourceBox.width, placement.sourceBox.height) * 0.012) + ), + width: placement.sourceBox.width, + }); + const sourceWashPatch = await buildScaleAdjustMaskWashPatch({ + background, + box: placement.sourceBox, + maskBuffer: Buffer.from(sourceWashMask), + }); + const subjectCrop = await sharp(sourceBuffer, { failOn: "none" }) + .extract(sourceSubjectBox) + .removeAlpha() + .png({ compressionLevel: 6 }) + .toBuffer(); + const subjectAlpha = await sharp(sourceSubjectMask, { + raw: { channels: 1, height: bbox.height, width: bbox.width }, + }) + .blur(Math.max(0.7, Math.min(bbox.width, bbox.height) * 0.006)) + .png({ compressionLevel: 6 }) + .toBuffer(); + const widthFactor = + placement.targetBox.width / Math.max(1, placement.sourceFootprintBox.width); + const heightFactor = + placement.targetBox.height / Math.max(1, placement.sourceFootprintBox.height); + const structureScale = Math.max( + 0.05, + Math.min( + 3.5, + Math.sqrt( + Math.max(0.0025, widthFactor) * Math.max(0.0025, heightFactor) + ) + ) + ); + const placedWidth = Math.max(1, Math.round(bbox.width * structureScale)); + const placedHeight = Math.max(1, Math.round(bbox.height * structureScale)); + const sourceCenterX = sourceSubjectBox.left + sourceSubjectBox.width / 2; + const sourceCenterY = sourceSubjectBox.top + sourceSubjectBox.height / 2; + const targetCenterX = + placement.targetBox.left + + ((sourceCenterX - placement.sourceFootprintBox.left) / + Math.max(1, placement.sourceFootprintBox.width)) * + placement.targetBox.width; + const targetCenterY = + placement.targetBox.top + + ((sourceCenterY - placement.sourceFootprintBox.top) / + Math.max(1, placement.sourceFootprintBox.height)) * + placement.targetBox.height; + const structureOverlay = await sharp(subjectCrop, { failOn: "none" }) + .joinChannel(subjectAlpha) + .resize(placedWidth, placedHeight, { + fit: "fill", + kernel: sharp.kernel.lanczos3, + }) + .png({ compressionLevel: 6 }) + .toBuffer(); + + return { + overlay: { + input: structureOverlay, + left: Math.round(targetCenterX - placedWidth / 2), + top: Math.round(targetCenterY - placedHeight / 2), + }, + wash: { + input: sourceWashPatch, + left: placement.sourceBox.left, + top: placement.sourceBox.top, + }, + }; +} + +function getScaleAdjustEditMaskBoxes(params: { + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; + sourceHeight: number; + sourceWidth: number; +}) { + const { regions, scalePercent, sourceHeight, sourceWidth } = params; + return regions.map((region) => { + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const workspaceRect = getScaleAdjustWorkspaceRect( + region.rect, + targetRect, + scalePercent + ); + return rectToPixels(workspaceRect, sourceWidth, sourceHeight); + }); +} + +async function buildScaleAdjustEditMaskBuffer(params: { + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; + sourceHeight: number; + sourceWidth: number; +}) { + const { regions, scalePercent, sourceHeight, sourceWidth } = params; + const boxes = getScaleAdjustEditMaskBoxes({ + regions, + scalePercent, + sourceHeight, + sourceWidth, + }); + const minSide = Math.max(1, Math.min(sourceWidth, sourceHeight)); + const blur = Math.max(5, Math.min(28, Math.round(minSide * 0.018))); + const pad = Math.max(2, Math.round(blur * 0.55)); + const rects = boxes + .map((box) => { + const left = clamp(box.left - pad, 0, Math.max(0, sourceWidth - 1)); + const top = clamp(box.top - pad, 0, Math.max(0, sourceHeight - 1)); + const right = clamp( + box.left + box.width + pad, + left + 1, + sourceWidth + ); + const bottom = clamp( + box.top + box.height + pad, + top + 1, + sourceHeight + ); + return ``; + }) + .join(""); + const editMaskSvg = Buffer.from( + ` + + + + + + + ${rects} + ` + ); + const editAlpha = await sharp(editMaskSvg, { failOn: "none" }) + .resize(sourceWidth, sourceHeight, { fit: "fill" }) + .greyscale() + .raw() + .toBuffer(); + const rgba = Buffer.alloc(sourceWidth * sourceHeight * 4); + for (let index = 0; index < sourceWidth * sourceHeight; index += 1) { + const offset = index * 4; + const editable = editAlpha[index] || 0; + rgba[offset] = 0; + rgba[offset + 1] = 0; + rgba[offset + 2] = 0; + rgba[offset + 3] = clamp(255 - editable, 0, 255); + } + return sharp(rgba, { + raw: { channels: 4, height: sourceHeight, width: sourceWidth }, + }) + .png({ compressionLevel: 9 }) + .toBuffer(); +} + +async function buildScaleAdjustVisualLayoutGuideBuffer(params: { + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; + sourceBuffer: Buffer; + sourceHeight: number; + sourceWidth: number; + structureLockedDraft?: boolean; +}) { + const { + regions, + scalePercent, + sourceBuffer, + sourceHeight, + sourceWidth, + structureLockedDraft = false, + } = params; + const sourceRaw = structureLockedDraft + ? await sharp(sourceBuffer, { failOn: "none" }) + .removeAlpha() + .toColorspace("srgb") + .raw() + .toBuffer() + : null; + const sourceFootprintBoxes: Array<{ + left: number; + top: number; + width: number; + height: number; + }> = []; + const placements: Array> = + []; + const composites: Array<{ input: Buffer; left: number; top: number }> = []; + const subjectWashComposites: Array<{ + input: Buffer; + left: number; + top: number; + }> = []; + + for (const region of regions) { + const placement = getScaleAdjustVisualGuidePlacement({ + height: sourceHeight, + region, + scalePercent, + width: sourceWidth, + }); + placements.push(placement); + const targetWidthFactor = + placement.targetBox.width / Math.max(1, placement.sourceFootprintBox.width); + const targetHeightFactor = + placement.targetBox.height / Math.max(1, placement.sourceFootprintBox.height); + const shouldUseStructureLock = + structureLockedDraft && + sourceRaw && + (targetWidthFactor > 1.08 || targetHeightFactor > 1.08); + const structureLockedComposite = shouldUseStructureLock + ? await buildScaleAdjustStructureLockedComposite({ + placement, + raw: sourceRaw, + sourceBuffer, + sourceWidth, + }) + : null; + + if (structureLockedComposite) { + subjectWashComposites.push(structureLockedComposite.wash); + composites.push(structureLockedComposite.overlay); + continue; + } + + sourceFootprintBoxes.push(placement.sourceFootprintBox); + + const resizedCropBuffer = await sharp(sourceBuffer, { failOn: "none" }) + .extract(placement.sourceBox) + .resize(placement.placedWidth, placement.placedHeight, { + fit: "fill", + }) + .png({ compressionLevel: 6 }) + .toBuffer(); + const cropBuffer = await sharp(resizedCropBuffer, { failOn: "none" }) + .ensureAlpha() + .composite([ + { + input: buildScaleAdjustPatchMaskSvg({ + height: placement.placedHeight, + width: placement.placedWidth, + }), + blend: "dest-in", + }, + ]) + .png({ compressionLevel: 6 }) + .toBuffer(); + composites.push({ + input: cropBuffer, + left: placement.placedLeft, + top: placement.placedTop, + }); + } + + const washComposite = sourceFootprintBoxes.length + ? [ + { + input: buildScaleAdjustSourceFootprintWashSvg({ + boxes: sourceFootprintBoxes, + height: sourceHeight, + width: sourceWidth, + }), + left: 0, + top: 0, + }, + ] + : []; + const targetShadowComposite = placements.length + ? structureLockedDraft + ? [] + : [ + { + input: buildScaleAdjustTargetFootprintShadowSvg({ + height: sourceHeight, + placements, + width: sourceWidth, + }), + left: 0, + top: 0, + }, + ] + : []; + + return sharp(sourceBuffer, { failOn: "none" }) + .composite([ + ...washComposite, + ...subjectWashComposites, + ...targetShadowComposite, + ...composites, + ]) + .png({ compressionLevel: 6 }) + .toBuffer(); +} + +async function createScaleAdjustPatchReference(params: { + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; + sourceBuffer: Buffer; + sourceHeight: number; + sourceWidth: number; +}): Promise { + const { regions, scalePercent, sourceBuffer, sourceHeight, sourceWidth } = + params; + const workspaceRect = getScaleAdjustPatchWorkspaceRect(regions, scalePercent); + const workspacePixelRect = rectToPixels(workspaceRect, sourceWidth, sourceHeight); + const structureLockedDraft = hasScaleAdjustEnlargeTarget(regions, scalePercent); + const targetDraftBuffer = await buildScaleAdjustVisualLayoutGuideBuffer({ + regions, + scalePercent, + sourceBuffer, + sourceHeight, + sourceWidth, + structureLockedDraft, + }); + const [sourceCropBuffer, targetDraftCropBuffer] = await Promise.all([ + sharp(sourceBuffer, { failOn: "none" }) + .extract(workspacePixelRect) + .png({ compressionLevel: 6 }) + .toBuffer(), + sharp(targetDraftBuffer, { failOn: "none" }) + .extract(workspacePixelRect) + .png({ compressionLevel: 6 }) + .toBuffer(), + ]); + const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + const [sourceCropUpload, targetDraftUpload] = await Promise.all([ + uploadFile( + `canvas-scale-adjust-workspace-source-${suffix}.png`, + toArrayBuffer(sourceCropBuffer) + ), + uploadFile( + `canvas-scale-adjust-workspace-target-draft-${suffix}.png`, + toArrayBuffer(targetDraftCropBuffer) + ), + ]); + + return { + sourceCropUrl: sourceCropUpload.url, + structureLockedDraft, + targetDraftUrl: targetDraftUpload.url, + workspacePixelRect, + workspaceRect, + }; +} + function wrapText(text: string, maxChars: number, maxLines = 3) { const compact = text.replace(/\s+/g, " ").trim(); if (!compact) return []; @@ -939,7 +2171,7 @@ function buildScaleAdjustAnnotationSvg(params: { const actionLabel = isShrink ? "SHRINK" : isEnlarge ? "ENLARGE" : "MOVE"; const scaleLabel = `${actionLabel} ${widthFactor.toFixed(2)}W ${heightFactor.toFixed(2)}H`; const instructionLabel = isShrink - ? "OLD OUTSIDE = BACKGROUND" + ? "OLD OUTSIDE -> BG" : isEnlarge ? "TARGET = FINAL FOOTPRINT" : "FINAL SUBJECT CENTER"; @@ -981,6 +2213,192 @@ function buildScaleAdjustAnnotationSvg(params: { `); } +function buildScaleAdjustZoomedCoordinateSvg(params: { + width: number; + height: number; + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; +}) { + const { width, height, regions, scalePercent } = params; + const minSide = Math.max(1, Math.min(width, height)); + const strokeWidth = Math.max(3, Math.round(minSide * 0.006)); + const fontSize = Math.max(22, Math.round(minSide * 0.026)); + const smallFontSize = Math.max(18, Math.round(fontSize * 0.72)); + const panelMarginX = Math.round(width * 0.1); + const panelMarginY = Math.round(height * 0.12); + const panelLeft = panelMarginX; + const panelTop = panelMarginY; + const panelWidth = Math.max(1, width - panelMarginX * 2); + const panelHeight = Math.max(1, height - panelMarginY * 2); + const sourceColor = "#9ca3af"; + const targetColor = "#111827"; + const helperColor = "#4b5563"; + const padX = Math.round(fontSize * 0.42); + const labelHeight = Math.round(fontSize * 1.35); + const label = (text: string, x: number, y: number, color: string) => { + const labelWidth = Math.min( + Math.round(text.length * fontSize * 0.58 + padX * 2), + Math.max(160, width - 16) + ); + const left = clamp(x, 8, Math.max(8, width - labelWidth - 8)); + const top = clamp(y, 8, Math.max(8, height - labelHeight - 8)); + return ` + + ${escapeXml(text)} + `; + }; + + const regionSvg = regions + .map((region) => { + const source = region.pixelRect; + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const target = + region.targetPixelRect || rectToPixels(targetRect, width, height); + const sourceRight = source.left + source.width; + const sourceBottom = source.top + source.height; + const targetRight = target.left + target.width; + const targetBottom = target.top + target.height; + const unionLeft = Math.min(source.left, target.left); + const unionTop = Math.min(source.top, target.top); + const unionRight = Math.max(sourceRight, targetRight); + const unionBottom = Math.max(sourceBottom, targetBottom); + const marginX = Math.max(12, Math.round((unionRight - unionLeft) * 0.35)); + const marginY = Math.max(12, Math.round((unionBottom - unionTop) * 0.35)); + const viewLeft = unionLeft - marginX; + const viewTop = unionTop - marginY; + const viewWidth = Math.max(1, unionRight - unionLeft + marginX * 2); + const viewHeight = Math.max(1, unionBottom - unionTop + marginY * 2); + const scale = Math.min( + panelWidth / viewWidth, + panelHeight / viewHeight + ); + const drawnWidth = viewWidth * scale; + const drawnHeight = viewHeight * scale; + const originX = panelLeft + (panelWidth - drawnWidth) / 2 - viewLeft * scale; + const originY = panelTop + (panelHeight - drawnHeight) / 2 - viewTop * scale; + const project = (box: { left: number; top: number; width: number; height: number }) => ({ + left: Math.round(originX + box.left * scale), + top: Math.round(originY + box.top * scale), + width: Math.max(1, Math.round(box.width * scale)), + height: Math.max(1, Math.round(box.height * scale)), + }); + const sourceBox = project(source); + const targetBox = project(target); + const sourceCenterX = sourceBox.left + sourceBox.width / 2; + const sourceCenterY = sourceBox.top + sourceBox.height / 2; + const targetCenterX = targetBox.left + targetBox.width / 2; + const targetCenterY = targetBox.top + targetBox.height / 2; + const widthFactor = source.width > 0 ? target.width / source.width : 1; + const heightFactor = source.height > 0 ? target.height / source.height : 1; + const actionLabel = + widthFactor < 0.92 || heightFactor < 0.92 + ? "SHRINK" + : widthFactor > 1.08 || heightFactor > 1.08 + ? "ENLARGE" + : "MOVE"; + const scaleLabel = `${actionLabel} ${widthFactor.toFixed(2)}W ${heightFactor.toFixed(2)}H`; + const radius = Math.max(10, Math.round(strokeWidth * 2.2)); + const centerMoved = + Math.hypot(targetCenterX - sourceCenterX, targetCenterY - sourceCenterY) > + Math.max(10, minSide * 0.018); + + return ` + + + + + ${ + centerMoved + ? `` + : "" + } + ${label(`OLD ${region.index}`, sourceBox.left, sourceBox.top - labelHeight - strokeWidth, sourceColor)} + ${label(`TARGET ${region.index}`, targetBox.left, targetBox.top + strokeWidth, targetColor)} + ${label(scaleLabel, targetBox.left, targetBox.top + targetBox.height + strokeWidth * 2, helperColor)} + ${label("OLD OUTSIDE -> BG", sourceBox.left, sourceBox.top + sourceBox.height + strokeWidth * 4 + labelHeight, helperColor)} + `; + }) + .join(""); + + return Buffer.from(` + + + + + + + + + LOCAL SCALE MAP - USE PROMPT PIXELS FOR ABSOLUTE POSITION + ${regionSvg} + + `); +} + +function buildScaleAdjustMarkedPhotoGuideSvg(params: { + width: number; + height: number; + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; +}) { + const { width, height, regions, scalePercent } = params; + const minSide = Math.max(1, Math.min(width, height)); + const strokeWidth = Math.max(3, Math.round(minSide * 0.005)); + const currentColor = "#00b8d4"; + const finalColor = "#2563eb"; + + const regionSvg = regions + .map((region) => { + const source = region.pixelRect; + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const target = + region.targetPixelRect || rectToPixels(targetRect, width, height); + const radius = Math.max(8, Math.round(strokeWidth * 2)); + return ` + + + + + `; + }) + .join(""); + + return Buffer.from(` + + + ${regionSvg} + + `); +} + +async function buildScaleAdjustMarkedPhotoGuideBuffer(params: { + sourceBuffer: Buffer; + width: number; + height: number; + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; +}) { + const { sourceBuffer, width, height, regions, scalePercent } = params; + return sharp(sourceBuffer, { failOn: "none" }) + .rotate() + .resize(width, height, { fit: "cover", position: "center" }) + .modulate({ brightness: 1.04, saturation: 0.45 }) + .composite([ + { + input: buildScaleAdjustMarkedPhotoGuideSvg({ + height, + regions, + scalePercent, + width, + }), + left: 0, + top: 0, + }, + ]) + .png({ compressionLevel: 6 }) + .toBuffer(); +} + function buildLocalEditPrompt(regions: NormalizedLocalEditRegion[]) { const regionLines = regions .map((region) => { @@ -1067,7 +2485,7 @@ function buildScaleAdjustPrompt( cropIndex >= 0 ? `;输入图片${cropIndex + 3}是该区域的干净局部裁切参考图,只用于识别目标主体的身份、轮廓与原始比例` : ""; - return `区域 ${region.index}${cropNote}:请在输入图片1中找到源框范围内最主要、可独立调整的商品/物体主体。${sourcePixelLine};${targetPixelLine};${scaleLine}${targetPositionNote}源框只是“寻找主体”的范围,不是最终边界,也不是要缩放或贴回的矩形补丁。目标框只是主体调整后的视觉占位参考,不要求主体填满矩形,更不能改变主体自身宽高比、透视或形体。请像真实图片编辑一样先保留锁定的原始画布,再只把这个主体整体等比变大/变小/移动到目标视觉占位;主体缩放后露出或遮挡的极小背景区域需要自然重建。严禁把输入图片1整张图、输入图片2坐标图、任意裁切图、源框矩形区域或目标框矩形区域当成图片块整体缩放、平移、复制、裁切或贴回。如果源框中只覆盖到主体的一部分,请根据局部裁切参考和可见结构推断该主体的完整可见轮廓,只调整主体,不调整矩形框内背景。`; + return `区域 ${region.index}${cropNote}:请在输入图片1中找到源框范围内最主要、可独立调整的商品/物体主体。${sourcePixelLine};${targetPixelLine};${scaleLine}${targetPositionNote}源框只是“寻找主体”的范围,不是最终边界,也不是要缩放或贴回的矩形补丁。目标框只是主体调整后的视觉占位参考,不要求主体填满矩形,更不能改变主体自身宽高比、透视或形体。请像真实图片编辑一样先保留锁定的原始画布,再只把这个主体整体等比变大/变小/移动到目标视觉占位;主体缩放后露出或遮挡的极小背景区域需要自然重建。严禁把输入图片1整张图、输入图片2目标布局参考图、任意裁切图、源框矩形区域或目标框矩形区域当成图片块整体缩放、平移、复制、裁切或贴回。如果源框中只覆盖到主体的一部分,请根据局部裁切参考和可见结构推断该主体的完整可见轮廓,只调整主体,不调整矩形框内背景。`; }) .join("\n"); const cropLines = cropReferences @@ -1081,25 +2499,25 @@ function buildScaleAdjustPrompt( "这是一项局部主体比例 inpaint/edit 任务,不是整图缩放、整图裁切或重新构图任务。", sourceSizeLine, "输入图片1是原始干净图,也是最终输出必须继承的唯一画面基底。除目标主体尺寸变化与必要背景补全外,输入图片1中的文字、Logo、装饰、排版、背景、光线、构图边界和所有未选区域必须保持不变。", - "输入图片2是一张与输入图片1尺寸完全相同的灰度坐标指令图,不是照片,也不是输出底图。它只用细线源框和目标框说明坐标关系;不得学习、复刻或输出其中的线框、灰底或 UI 标记。", + "输入图片2是一张与输入图片1尺寸和画幅完全相同的完整画面编辑意图图,不是输出底图。它保留原图完整画幅作为稳定参考,并把源框旧主体占位强淡化为“这里的原尺寸主体需要被目标尺寸替换并自然修复背景”的指令;同时把同一目标主体粗略缩放后放在用户希望的最终位置和大小。请只读取目标主体的最终视觉占位、中心位置和原画幅关系;输入图片2里被淡化的旧主体不能表示最终还要保留原尺寸主体。不得学习、复刻或输出淡化痕迹、阴影占位、矩形裁切边缘、拼接痕迹或参考图粗糙画质。", cropLines ? `输入图片3及之后是框选区域的干净局部裁切参考图,作用是帮助你确认“要缩放的是哪个主体”。这些裁切图不是输出底图,不得被整体放大、贴回或覆盖到原图上。\n${cropLines}` : "", - "输入图片2中的源框表示输入图片1里目标主体当前大致位置;它只用于定位主体,不限制调整后的空间。目标框表示用户希望主体调整后的视觉占位和中心位置。最终画面不得出现这些线框或灰底;主体也不需要填满目标矩形,必须保持主体自身原始宽高比和透视形体。", + "输入图片2中的完整画面编辑意图是强约束:淡化的 OLD 占位表示旧尺寸主体要被移除/修复,清晰的 TARGET 占位表示最终主体大小和中心位置;整张图不应缩放、裁切或平移。最终输出必须回到输入图片1的真实照片环境中完成自然编辑,不得直接粘贴 input2 的矩形图块;主体不需要填满目标矩形,必须保持主体自身原始宽高比和透视形体。", "如果系统或模型只能读取一张参考图,必须优先以输入图片1为输出基底,不得清理、改写或删除输入图片1中框选区域外的任何文字和图形。", "系统已根据用户框选区域计算出下方每个区域的原图坐标;框选区域只是定位目标主体的搜索范围,不是最终画面的裁切块、贴片、蒙版边界,也不是放大后的空间上限,更不是要整体缩放的矩形图层。", "最终结果必须保持原始干净图的画幅比例、构图边界、镜头透视、光线、色温、材质质感和清晰度;严禁整张图整体缩放、裁切、平移、重新排版或重新生成。", "Highest priority rule: do NOT zoom, crop, resize, reframe, pan, or regenerate the full canvas. Treat image 1 as a locked background plate; edit only the selected subject and the smallest necessary background around its old and new footprint.", "请不要生成任何彩色框、矩形边框、箭头、连线、角点、编号圆点、提示词气泡、标注文字、UI 控件或半透明色块。", - "请同时使用下方每个区域的源框/目标框像素坐标和输入图片2的坐标图来理解目标占位。坐标只用于指导主体位置和大小,不是要求把某个矩形图块缩放后贴回。", + "请同时使用下方每个区域的源框/目标框像素坐标和输入图片2的目标布局参考来理解目标占位。坐标和参考图只用于指导主体位置和大小,不是要求把某个矩形图块缩放后贴回。", "", - "任务:先在输入图片1中识别源框范围内最主要、可独立调整的主体物体,再只对这个“主体物体”做局部比例调整。调整后的主体大小和位置必须接近目标框表示的视觉占位;如果输出看起来和原图一样,就是失败。", + "任务:先在输入图片1中识别源框范围内最主要、可独立调整的主体物体,再只对这个“主体物体”做局部比例调整。调整后的主体大小和位置必须接近目标框表示的视觉占位;不接受看起来和原图几乎相同的输出。", regionLines, "", "关键要求:", "1. 只调整目标主体物体本身的整体视觉比例,不得保留原尺寸;主体轮廓宽度和高度必须同步等比变化,宽高比必须与原主体一致,不能为了贴合目标框而拉宽、压窄、拉高或压扁。", "2. 严禁把整个矩形框选区域、输入图片1整张图或任意裁切图当成图片块整体缩放、平移、复制、裁切或贴回;最终画面不得出现矩形拼接边缘、色差硬边、补丁感、裁切线或局部贴片痕迹。", - "2.1 严禁把输入图片1整张图整体放大、缩小、裁切或重新构图;如果画面中的标题、Logo、页面文字、边框、窗框、背景家具或非目标主体发生整体位移/缩放/消失,必须视为失败并重新生成。请把这些元素当作像素锚点,它们的位置和比例不能跟着目标主体变化。", + "2.1 严禁把输入图片1整张图整体放大、缩小、裁切或重新构图;画面中的标题、Logo、页面文字、边框、窗框、背景家具或非目标主体必须作为像素锚点保持原位置和原比例,不能跟着目标主体变化。", "3. 如果输入图片2中的目标框明显小于源框,目标主体应自然变小,主体缩小后露出的背景、桌面、墙面、阴影、纹理和透视必须被重新生成并无缝补全,选区内应出现明显新增留白或背景。", "4. 如果输入图片2中的目标框明显大于源框,目标主体应自然变大;允许主体自然超出用户手画的原始源框,使用周围真实背景完成边缘、阴影和遮挡衔接。宽度和高度都要同步变大,不能出现“高度变高但宽度变窄”的非等比变形;主体边缘与遮挡关系要合理,不能产生突兀裁切。", "5. 如果目标框中心与源框中心不同,允许主体同步移动到目标框中心附近;如果主体靠近画布边界导致目标空间不足,请用能完整放入画面的最大统一倍率整体调整,绝不能为了塞进画面而只压缩宽度或只拉伸高度。", @@ -1117,7 +2535,12 @@ function buildScaleAdjustCoordinatePrompt( regions: NormalizedLocalEditRegion[], scalePercent: ScaleAdjustPercent | null | undefined, sourceSize: { width: number; height: number }, - cropReferences: ScaleAdjustCropReference[] = [] + cropReferences: ScaleAdjustCropReference[] = [], + options: { + falSafe?: boolean; + markedPhotoGuide?: boolean; + visualLayoutGuide?: boolean; + } = {} ) { const regionLines = regions .map((region) => { @@ -1136,6 +2559,10 @@ function buildScaleAdjustCoordinatePrompt( const sourceBottom = region.pixelRect.top + region.pixelRect.height; const targetRight = targetPixelRect.left + targetPixelRect.width; const targetBottom = targetPixelRect.top + targetPixelRect.height; + const regionUserInstruction = region.prompt.trim(); + const userInstructionLine = regionUserInstruction + ? ` User instruction for this region: ${regionUserInstruction}.` + : ""; const isShrink = widthFactor < 0.92 || heightFactor < 0.92; const isEnlarge = widthFactor > 1.08 || heightFactor > 1.08; const scaleDirection = @@ -1152,9 +2579,26 @@ function buildScaleAdjustCoordinatePrompt( const cropNote = cropIndex >= 0 - ? ` Input image ${cropIndex + 3} is a clean crop reference for this same furniture identity and silhouette; use it only to recognize the subject, never paste it, and do not preserve its old size.` + ? options.falSafe + ? ` Input image ${cropIndex + 3} is an extra identity and silhouette reference.` + : ` Input image ${cropIndex + 3} is a clean crop reference for this same furniture identity and silhouette; use it only to recognize the subject, never paste it, and do not preserve its old size.` : ""; - return `Region ${region.index}: OLD search box in input 1 left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; TARGET final visual footprint left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; target scale is ${widthFactor.toFixed(2)}x width and ${heightFactor.toFixed(2)}x height. Main action: ${scaleDirection}. The final furniture silhouette must clearly leave the OLD footprint edges and align much closer to TARGET than OLD; returning an almost unchanged furniture footprint is invalid. ${footprintRule}${cropNote}`; + if (options.falSafe) { + const actionPhrase = + isShrink + ? "resize the furniture proportionally smaller and place it inside the final footprint" + : isEnlarge + ? "resize the same furniture proportionally larger toward the final footprint" + : "place the same furniture subject on the final footprint"; + const blendPhrase = + isShrink + ? "Blend the newly visible floor, rug, wall, window area, shadow, and background around it naturally." + : isEnlarge + ? "Blend edges, contact shadows, and occlusion with the surrounding room naturally." + : "Keep the surrounding room stable."; + return `Region ${region.index}: current furniture box in source photo left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; requested final footprint left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; scale factor width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. Edit direction: ${actionPhrase}. ${blendPhrase}${cropNote}`; + } + return `Region ${region.index}: OLD search box in input 1 left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; TARGET final visual footprint left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; target scale is ${widthFactor.toFixed(2)}x width and ${heightFactor.toFixed(2)}x height. Main action: ${scaleDirection}.${userInstructionLine} The final furniture silhouette must clearly leave the OLD footprint edges and align much closer to TARGET than OLD; returning an almost unchanged furniture footprint is not acceptable. ${footprintRule}${cropNote}`; }) .join("\n"); const cropLines = cropReferences @@ -1164,30 +2608,53 @@ function buildScaleAdjustCoordinatePrompt( ) .join("\n"); + if (options.falSafe) { + return [ + "Interior furniture photo edit.", + `Return one realistic photo with the same camera frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, + "Input image 1 is the source photo. Input image 2 is a marked copy of the source photo for location guidance only and should not appear in the final photo.", + "In the guide, the cyan dashed box marks the existing furniture area and the blue solid box marks the requested final footprint.", + "Resize only the furniture subject indicated by each current box. Keep the camera, room layout, walls, windows, floor, rug, sofa, lamp, text, and background stable.", + "Preserve the furniture identity, material, perspective, objects on top, and natural aspect ratio.", + "For a smaller final footprint, show the furniture smaller and blend newly visible floor, rug, wall, window area, shadow, and background around it naturally. For a larger final footprint, scale the same furniture proportionally with natural edges and contact shadows.", + "Return a clean photo without guide marks, boxes, arrows, overlays, patch edges, color mismatch, or full-frame zoom.", + cropLines ? `${cropLines}` : "", + "", + "Region instructions:", + regionLines, + ].join("\n"); + } + + const coordinateGuideLine = options.visualLayoutGuide + ? "输入图片2是一张完整画面的粗略目标布局草稿,不是输出底图。它把 OLD 源框旧主体占位洗淡,表示旧尺寸主体必须从原尺寸位置移除并自然修复背景;同时把目标主体粗略缩放/移动到 TARGET 最终占位附近,这个缩小后的位置和尺寸是最终结果必须匹配的几何目标。请把 input 2 当成最终构图/比例的强约束:如果 input 2 中目标主体比 input 1 小,最终输出也必须明显变小,不能保留 input 1 的原尺寸主体。不要复制 input 2 的淡化痕迹、粗糙拼接、局部透明边、矩形补丁、亮度变化或参考图画质;最终必须以 input 1 的真实照片为唯一画面基底重新完成无缝图片编辑。" + : options.markedPhotoGuide + ? "输入图片2是一张原图浅化后的完整画面位置参考图,不是输出底图。青色虚线框表示当前主体搜索框(对应下方 OLD),蓝色实线框表示目标最终占位(对应下方 TARGET)。请用输入图片2理解主体在真实室内画面中的位置关系,但最终图不能出现任何框线、色块、标注或参考图的浅化效果。" + : "Input image 2 is a zoomed neutral coordinate instruction map, not a photo and not output content. It enlarges the OLD and TARGET boxes so their relative scale is easy to read; use the numeric pixel coordinates below for the exact absolute position in input image 1. The OLD box/label locates the current furniture; the TARGET box/label gives the required final footprint, center, and scale factor. If the map says OLD OUTSIDE -> BG, rebuild the old full-size furniture area outside TARGET as natural background in the final photo. Read the boxes, labels, arrows, and scale text only as instructions; never output any map graphics."; + return [ "Local furniture scale edit. Use input image 1 as the clean original photo and the locked camera frame.", - "One-shot cost constraint: solve this in the first generation. Do not rely on later retries or alternate candidates; an unchanged result wastes the request and is invalid.", - "中文硬约束:只调整 OLD 框中的主要家具主体。TARGET 框是最终占位;如果是缩小,OLD 框里超出 TARGET 的旧家具必须消失并补成自然背景;如果是放大,同一件家具必须明显变大。禁止整图缩放、整图裁切、整图重绘。", - "一次成功硬约束:不要保守返回原尺寸。目标家具的可见轮廓必须明显从 OLD 原始占位变到 TARGET 占位;如果最终看起来和原图一样,就是失败。", + "One-shot cost constraint: produce the requested edit in this generation without relying on later retries or alternate candidates; an unchanged result is not acceptable.", + "中文硬约束:只调整 OLD 框中的主要家具主体。TARGET 框是最终占位;如果是缩小,OLD 框里超出 TARGET 的旧家具占位必须改为自然背景;如果是放大,同一件家具必须明显变大。禁止整图缩放、整图裁切、整图重绘。", + "一次成功硬约束:不要保守返回原尺寸。目标家具的可见轮廓必须明显从 OLD 原始占位变到 TARGET 占位;不接受看起来和原图几乎相同的结果。", `Return one seamless realistic photo with the same frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, - "Input image 2 is a separate neutral coordinate instruction map, not a photo and not output content. The light gray OLD rectangle/label locates the current furniture in input image 1; the dark TARGET rectangle/label gives the required final size and center. The map may include arrows, scale-factor text, OLD OUTSIDE = BACKGROUND, and TARGET = FINAL FOOTPRINT labels: read them as instructions only, never as visual content.", + coordinateGuideLine, cropLines ? `${cropLines}` : "", "", "Task:", - "Find the main movable furniture subject inside each OLD box in input image 1. Resize and, if needed, move that subject only so its final visible footprint matches the TARGET box.", + "Find the main movable furniture subject inside each OLD box in input image 1. Resize and, if needed, move that subject only so its final visible footprint matches the TARGET box shown in input image 2 and the numeric TARGET coordinates below.", "Do a real subject-scale edit, not a full image zoom. The camera, room layout, windows, wall decor, text, floor, rug, and all non-target furniture must remain stable.", "If an OLD box contains more than one object, choose the dominant furniture/product inside that box, usually the largest or most central movable item. Keep adjacent lamps, plants, side tables, pillows, wall decor, windows, text, and background objects at their original size unless they are clearly part of the same furniture subject.", "Keep the furniture identity, material, perspective, objects on top, and natural aspect ratio from input image 1. Do not create a second copy or extra parts. Do not preserve the original furniture size just because the scene looks realistic; the user explicitly wants a visible scale change.", "For beds, sofas, tables, chairs, cabinets, benches, and other large furniture, still perform the scale edit on that furniture. Do not treat large furniture as locked architecture.", - "If the target is smaller, the furniture must visibly become smaller and be mostly contained by the TARGET footprint. The OLD area outside the TARGET footprint must no longer contain the full-size furniture; naturally heal newly exposed floor, rug, wall, bedding, shadows, and background. If the target is larger, enlarge the same furniture naturally without stretching it.", - "缩小时请优先让目标家具明显缩小,而不是为了保守而保持原样。原尺寸保留、只轻微变形、或只改变整张图构图都算失败。", - "Never keep the selected furniture at its original footprint. If the edited furniture still fills the OLD rectangle instead of the TARGET rectangle, the result is invalid.", + "If the target is smaller, the furniture must visibly become smaller and be mostly contained by the TARGET footprint. Rebuild the OLD area outside the TARGET footprint as newly exposed floor, rug, wall, bedding, shadows, and background. If the target is larger, enlarge the same furniture naturally without stretching it.", + "缩小时请优先让目标家具明显缩小,而不是为了保守而保持原样。不接受原尺寸保留、只轻微变形、或只改变整张图构图。", + "Do not keep the selected furniture at its original footprint. The edited furniture should fit the TARGET rectangle much better than the OLD rectangle.", "", "Region requirements:", regionLines, "", - "Success check: compare the final furniture footprint with the OLD and TARGET boxes from input image 2. The selected furniture size must clearly change from the original and align much closer to TARGET than OLD, while the rest of the photo stays stable.", - "Do not paste rectangular image areas. Do not output coordinate-map lines, labels, boxes, seams, hard patch edges, haze, color mismatch, full-canvas zoom, crop, pan, or redesign.", + "Success check: compare the final furniture footprint with input image 1 and the neutral coordinate map in input image 2. The selected furniture size must clearly change from the original and align much closer to TARGET than OLD, while the rest of the photo stays stable.", + "Do not paste rectangular image areas. Do not output coordinate-map lines, labels, boxes, arrows, scale text, muted wash, overlays, seams, hard patch edges, haze, color mismatch, full-canvas zoom, crop, pan, or redesign.", "Return only the clean edited photo.", ].join("\n"); } @@ -1195,17 +2662,207 @@ function buildScaleAdjustCoordinatePrompt( function buildScaleAdjustCoordinateSystemPrompt() { return [ "You are an image editing model for local furniture scale adjustment.", - "Input image 1 is the only final photo base. Input image 2 is a coordinate instruction map, not a photo layer.", + "Input image 1 is the only final photo base. Input image 2 is a zoomed neutral coordinate instruction map, not a photo layer.", "Follow both English and Chinese instructions. The Chinese lines are hard constraints for avoiding unchanged furniture and full-canvas zoom.", "Generate a clean realistic final photo by editing the target furniture itself and naturally rebuilding only the tiny surrounding background that becomes visible.", - "Prefer a clear visible size change over a conservative unchanged result; unchanged furniture is a failed edit.", - "When shrinking, remove the old full-size furniture footprint outside the target footprint and heal it as natural background. Large furniture is editable and must not remain locked at original size.", + "Prefer a clear visible size change over a conservative unchanged result; unchanged furniture is not acceptable.", + "When shrinking, rebuild the old full-size furniture footprint outside the target footprint as natural background. Large furniture is editable and must not remain locked at original size.", "Do not paste, composite, clone, crop, resize, or copy rectangular image patches from any input.", - "Never output guide artifacts from the coordinate reference: no lines, labels, blocks, seams, rectangular borders, arrows, masks, UI marks, or annotations.", + "Never output guide artifacts from the edit map: no faded wash, placeholder shadow, overlay patch, rough crop rectangle, lines, labels, blocks, seams, rectangular borders, arrows, masks, UI marks, or annotations.", "Keep the camera frame, lighting, wall, floor, rug, windows, background furniture, text, logos, and all non-target regions stable.", ].join("\n"); } +function buildScaleAdjustTextOnlyPrompt( + regions: NormalizedLocalEditRegion[], + scalePercent: ScaleAdjustPercent | null | undefined, + cropReferences: ScaleAdjustCropReference[] = [], + sourceSize: { width: number; height: number } +) { + const cropLines = cropReferences + .map( + (reference, index) => + `Input image ${index + 2}: clean crop reference for Region ${reference.regionIndex}; use it only to identify the furniture subject and its natural aspect ratio, never paste the crop into the output.` + ) + .join("\n"); + const regionLines = regions + .map((region) => { + const cropIndex = cropReferences.findIndex( + (reference) => reference.regionIndex === region.index + ); + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const targetPixelRect = + region.targetPixelRect || + rectToPixels(targetRect, sourceSize.width, sourceSize.height); + const widthFactor = + region.rect.width > 0 ? targetRect.width / region.rect.width : 1; + const heightFactor = + region.rect.height > 0 ? targetRect.height / region.rect.height : 1; + const sourceRight = region.pixelRect.left + region.pixelRect.width; + const sourceBottom = region.pixelRect.top + region.pixelRect.height; + const targetRight = targetPixelRect.left + targetPixelRect.width; + const targetBottom = targetPixelRect.top + targetPixelRect.height; + const cropNote = + cropIndex >= 0 + ? ` Input image ${cropIndex + 2} is the clean crop reference for this furniture identity and silhouette.` + : ""; + return `Region ${region.index}: hidden coordinate set A current area x0=${region.pixelRect.left}, y0=${region.pixelRect.top}, x1=${sourceRight}, y1=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; hidden coordinate set B final size/location x0=${targetPixelRect.left}, y0=${targetPixelRect.top}, x1=${targetRight}, y1=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; final visual scale width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. User request: ${region.prompt || "make the same furniture match set B"}.${cropNote}`; + }) + .join("\n"); + + return [ + "Local furniture scale edit. Input image 1 is the locked source photo and the only final canvas base.", + `Return one clean realistic photo with exactly the same camera frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, + cropLines ? cropLines : "", + "The final photo must contain only natural scene content. Never add artificial graphic overlays, visible coordinate aids, labels, lines, UI elements, or text.", + "Only edit the main movable furniture subject inside each current pixel area. Keep all other furniture, sofa, lamps, wall, windows, rug, floor, decor, lighting, and camera frame stable.", + "Use the numeric pixel sets below as hidden instructions only; they are not visual content and must not be drawn.", + "When set B is smaller than set A, make the same furniture visibly smaller and naturally rebuild the newly visible floor, rug, wall, shadow, or background around it. Do not leave the old full-size furniture silhouette.", + "Keep the furniture identity, materials, perspective, objects on top, contact shadows, and natural aspect ratio. Do not stretch, squash, duplicate, or paste a rectangular crop.", + "中文硬约束:输入图1是锁定底图,只能调整 A 像素范围里的主要家具主体,让它变成 B 像素范围对应的大小和位置。A/B 坐标只是隐藏指令,最终照片里绝对不能画出任何线条、框、文字、标注或 UI 元素。", + "", + "Region instructions:", + regionLines, + "", + "Success check before returning: the selected furniture must be clearly closer to set B than to set A, while the rest of the photo remains visually unchanged and clean.", + ].filter(Boolean).join("\n"); +} + +function toPatchRelativePixelBox( + box: { left: number; top: number; width: number; height: number }, + workspace: ScaleAdjustPatchReference["workspacePixelRect"] +) { + const left = clamp(box.left - workspace.left, 0, Math.max(0, workspace.width - 1)); + const top = clamp(box.top - workspace.top, 0, Math.max(0, workspace.height - 1)); + const right = clamp( + box.left + box.width - workspace.left, + left + 1, + workspace.width + ); + const bottom = clamp( + box.top + box.height - workspace.top, + top + 1, + workspace.height + ); + + return { + left, + top, + width: Math.max(1, right - left), + height: Math.max(1, bottom - top), + }; +} + +function buildScaleAdjustPatchPrompt( + regions: NormalizedLocalEditRegion[], + scalePercent: ScaleAdjustPercent | null | undefined, + patchReference: ScaleAdjustPatchReference, + sourceSize: { width: number; height: number }, + cropReferences: ScaleAdjustCropReference[] = [], + options: { includeSourceReference?: boolean; targetDraftPrimary?: boolean } = {} +) { + const targetDraftPrimary = options.targetDraftPrimary === true; + const includeSourceReference = options.includeSourceReference !== false; + const structureLockedDraft = patchReference.structureLockedDraft === true; + const sourceInputIndex = targetDraftPrimary && includeSourceReference ? 2 : 1; + const draftInputIndex = targetDraftPrimary ? 1 : 2; + const cropReferenceStartIndex = + targetDraftPrimary && !includeSourceReference ? 2 : 3; + const firstInputRole = targetDraftPrimary + ? structureLockedDraft + ? includeSourceReference + ? "Input image 1 is a rough product-structure-locked target crop. The selected furniture/product was moved and scaled using source-photo pixels, so its final size, position, rods, panels, weave, wheels, material, and perspective are the hard target. Repair rough background holes, edge halos, blur, occlusion, contact shadows, and surface artifacts without redesigning the product. Input image 2 is only the clean background/person reference, never the size reference." + : "Input image 1 is a rough product-structure-locked target crop and the only visual reference. The selected furniture/product was moved and scaled using source-photo pixels, so its final size, position, rods, panels, weave, wheels, material, and perspective are the hard target. Repair rough background holes, edge halos, blur, occlusion, contact shadows, and surface artifacts without redesigning the product." + : includeSourceReference + ? "Input image 1 is the rough edited target-layout crop. It is the hard layout target: the selected furniture size and center in the final output must match this draft, but the rough wash, ghosted old footprint, placeholder shadow, blur, and patch artifacts must be cleaned." + : "Input image 1 is the rough edited target-layout crop and the only visual reference. It is the hard layout target: the selected furniture size and center in the final output must match this draft. Clean away the rough wash, ghosted old footprint, placeholder shadow, blur, and patch artifacts." + : "Input image 1 is the exact crop from the original photo and is the locked crop base."; + const secondInputRole = targetDraftPrimary + ? includeSourceReference + ? "Input image 2 is the original clean crop. Use it for stable crop framing, background texture, lighting, perspective, furniture identity, and non-target human/person preservation. Do not restore the selected furniture to its old size from this image." + : "" + : "Input image 2 is a rough target-layout draft of the same crop. It is the hard layout target for the selected furniture size and position. Use it to understand the final footprint and newly visible background area, then remove any rough seams, washed areas, placeholder shadows, blur, or patch artifacts from that draft."; + const cropLines = cropReferences + .map( + (reference, index) => + `Input image ${index + cropReferenceStartIndex}: clean identity crop for Region ${reference.regionIndex}; use it only to recognize the target furniture shape and materials, not its old size.` + ) + .join("\n"); + const regionLines = regions + .map((region) => { + const cropIndex = cropReferences.findIndex( + (reference) => reference.regionIndex === region.index + ); + const targetRect = getScaleAdjustTargetRect(region, scalePercent); + const targetPixelRect = + region.targetPixelRect || + rectToPixels(targetRect, sourceSize.width, sourceSize.height); + const sourceInPatch = toPatchRelativePixelBox( + region.pixelRect, + patchReference.workspacePixelRect + ); + const targetInPatch = toPatchRelativePixelBox( + targetPixelRect, + patchReference.workspacePixelRect + ); + const widthFactor = + region.rect.width > 0 ? targetRect.width / region.rect.width : 1; + const heightFactor = + region.rect.height > 0 ? targetRect.height / region.rect.height : 1; + const action = + widthFactor < 0.92 || heightFactor < 0.92 + ? "make the same furniture visibly smaller" + : widthFactor > 1.08 || heightFactor > 1.08 + ? "make the same furniture visibly larger" + : "move the same furniture to the final footprint"; + const cropNote = + cropIndex >= 0 + ? ` Input image ${cropIndex + cropReferenceStartIndex} is the clean identity reference for this exact furniture.` + : ""; + return `Region ${region.index}: current search area inside input image ${sourceInputIndex} crop is x=${sourceInPatch.left}, y=${sourceInPatch.top}, w=${sourceInPatch.width}, h=${sourceInPatch.height}; final visual footprint inside input image ${draftInputIndex} / output crop is x=${targetInPatch.left}, y=${targetInPatch.top}, w=${targetInPatch.width}, h=${targetInPatch.height}; requested scale width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. User request: ${region.prompt || action}. Main action: ${action}. The final object must be much closer to the final footprint than to the current search area.${cropNote}`; + }) + .join("\n"); + const chineseHardConstraint = (() => { + if (!targetDraftPrimary) { + return "中文硬约束:只输出输入图1同一裁切范围的干净局部照片;输入图2是目标大小/位置草稿,必须按它的目标尺寸和目标位置输出,不是要保留旧尺寸。目标家具必须相对原图产生明显比例变化,非目标背景和裁切边缘要稳定自然。"; + } + if (structureLockedDraft) { + return includeSourceReference + ? "中文硬约束:输入图1已经用原图产品像素把目标家具/产品放到目标尺寸和目标位置,产品结构、杆件、面板、编织纹理、轮子、材质和透视都要按输入图1保留。输入图2只能作为干净背景、人物、光影参考,绝对不能把产品恢复成输入图2里的旧尺寸。不能重新设计或替换产品,但要清理产品表面的草稿黑斑、破洞、脏点、灰块和藤编断裂,让藤编面板连续干净、轮子只出现在底部。" + : "中文硬约束:输入图1已经用原图产品像素把目标家具/产品放到目标尺寸和目标位置,产品结构、杆件、面板、编织纹理、轮子、材质和透视都要按输入图1保留。不能重新设计或替换产品,但要清理产品表面的草稿黑斑、破洞、脏点、灰块和藤编断裂,让藤编面板连续干净、轮子只出现在底部。"; + } + return includeSourceReference + ? "中文硬约束:输入图1是目标大小/位置草稿,必须按它的目标尺寸和目标位置输出;输入图2只是原始质感、人物和背景参考,绝对不要把家具恢复成输入图2里的旧尺寸。只输出同一裁切范围的干净局部照片,去掉草稿中的泛白、残影和拼接感。" + : "中文硬约束:输入图1是唯一视觉参考和目标大小/位置草稿,必须按它的目标尺寸和目标位置输出。不要找回旧尺寸家具。只输出同一裁切范围的干净局部照片,去掉草稿中的泛白、残影和拼接感。"; + })(); + + return [ + "Local furniture scale edit inside a cropped workspace.", + `Return exactly one clean realistic crop with the same framing and aspect as input image 1. The crop represents full-photo pixels left=${patchReference.workspacePixelRect.left}, top=${patchReference.workspacePixelRect.top}, width=${patchReference.workspacePixelRect.width}, height=${patchReference.workspacePixelRect.height}.`, + firstInputRole, + secondInputRole, + cropLines, + "Only edit the selected movable furniture subject. Keep the crop borders, wall, window frame, floor, rug, sofa, lamps, decor, lighting, camera perspective, and all non-target furniture stable.", + "If people, faces, arms, hands, bodies, hair, or worn clothing appear in the crop, they are not furniture. Preserve the human scale, identity, pose, face, hand shape, and clothing position as much as possible; do not enlarge, shrink, duplicate, or redraw the person as part of the furniture scale edit.", + "When the final footprint is smaller, the selected furniture must clearly shrink; erase the old larger furniture footprint outside the final footprint and replace it with natural background/floor/rug/wall/shadow that matches the original crop.", + structureLockedDraft + ? "When the final footprint is larger, the target draft already places the same furniture/product at the required larger size. Do not redesign the product geometry; keep the locked rods, panels, weave, wheels, material, and perspective while cleaning background gaps, boundary blending, rough surface artifacts, natural occlusion, and contact shadows." + : "When the final footprint is larger, enlarge the selected furniture itself to match the target draft while keeping nearby people and hands natural. If a hand touches or holds an item on the furniture, keep the hand anatomically plausible and use the original crop as the person-preservation reference.", + "Keep the same furniture identity, material, perspective, object details, contact shadows, and natural aspect ratio. Do not stretch, squash, duplicate, or replace it with a different item.", + "Hard failure condition: if the selected furniture remains near its original old size, the answer is wrong. The output must visibly change the furniture footprint to match the target draft footprint.", + structureLockedDraft + ? "Remove every rough draft artifact from input image 1: gray fill patches, beige wash, flat painted areas, jagged mask holes, broken woven-panel cells, black speckled stains, dark blotches on cane panels, rectangular crop edges, and ghost fragments. Woven panels must look like continuous clean cane weave; wheels belong only under the bottom frame, not as black stains inside the woven panel. Rods, wheels, and hooks must remain the same product structure, with natural material texture." + : "", + "Do not output boxes, lines, labels, coordinate marks, UI marks, text, arrows, overlays, rough layout artifacts, rectangular patch edges, or a full-room image.", + chineseHardConstraint, + "", + "Region instructions:", + regionLines, + "", + "Success check before returning: the selected furniture footprint must be clearly closer to the final footprint than the current search area, and the crop must look like one natural photograph.", + ].filter(Boolean).join("\n"); +} + export async function POST(request: NextRequest) { try { const session = await auth(); @@ -1344,6 +3001,10 @@ export async function POST(request: NextRequest) { const detailFixedModel = isScaleAdjustOperation ? resolveScaleAdjustPreferredModelId({ configuredModelId: configuredDetailModel, + honorRequestedModelBeforeGpt: hasScaleAdjustEnlargeTarget( + regions, + scalePercent + ), requestedModelId: requestedModel || "", models: scaleAdjustModelCandidates, }) @@ -1369,44 +3030,152 @@ export async function POST(request: NextRequest) { const scaleAdjustModelFamily = getScaleAdjustModelFamily( resolvedScaleAdjustModelEntry ); - const annotatedBuffer = await sharp(sourceBuffer, { failOn: "none" }) - .composite([ - { - input: isScaleAdjustOperation - ? buildScaleAdjustAnnotationSvg({ + const useProviderTextOnlyCoordinatePrompt = + isScaleAdjustOperation && + resolvedScaleAdjustModelEntry?.provider?.type === "alibaba-image"; + const useScaleAdjustCoordinatePrompt = useScaleAdjustCoordinateGuide; + const useFalScaleAdjustCoordinatePrompt = + useScaleAdjustCoordinatePrompt && + resolvedScaleAdjustModelEntry?.provider?.type === "fal-image"; + const useScaleAdjustVisualLayoutGuide = + useScaleAdjustCoordinatePrompt && + !useFalScaleAdjustCoordinatePrompt && + !useProviderTextOnlyCoordinatePrompt; + const useScaleAdjustMarkedPhotoGuide = + useScaleAdjustCoordinatePrompt && !useScaleAdjustVisualLayoutGuide; + const useScaleAdjustStructureLockedPatchWorkflow = + isScaleAdjustOperation && hasScaleAdjustEnlargeTarget(regions, scalePercent); + const useScaleAdjustEditMask = + isScaleAdjustOperation && + !useScaleAdjustStructureLockedPatchWorkflow && + isScaleAdjustMaskCapableModel(resolvedScaleAdjustModelEntry); + const useScaleAdjustPatchWorkflow = + isScaleAdjustOperation && + (useScaleAdjustStructureLockedPatchWorkflow || !useScaleAdjustEditMask); + const sendScaleAdjustAnnotatedReferenceToModel = + isScaleAdjustOperation && + !useScaleAdjustPatchWorkflow && + !useProviderTextOnlyCoordinatePrompt; + const annotatedBuffer = isScaleAdjustOperation + ? useScaleAdjustCoordinatePrompt + ? useScaleAdjustVisualLayoutGuide + ? await buildScaleAdjustVisualLayoutGuideBuffer({ + regions, + scalePercent, + sourceBuffer, + sourceHeight, + sourceWidth, + }) + : useScaleAdjustMarkedPhotoGuide + ? await buildScaleAdjustMarkedPhotoGuideBuffer({ + height: sourceHeight, + regions, + scalePercent, + sourceBuffer, + width: sourceWidth, + }) + : await sharp( + buildScaleAdjustZoomedCoordinateSvg({ height: sourceHeight, regions, scalePercent, width: sourceWidth, - }) - : buildAnnotationSvg({ + }), + { failOn: "none" } + ) + .png({ compressionLevel: 6 }) + .toBuffer() + : await buildScaleAdjustVisualLayoutGuideBuffer({ + regions, + scalePercent, + sourceBuffer, + sourceHeight, + sourceWidth, + }) + : await sharp(sourceBuffer, { failOn: "none" }) + .composite([ + { + input: buildAnnotationSvg({ height: sourceHeight, hidePromptText: false, regions, width: sourceWidth, }), - left: 0, - top: 0, - }, - ]) - .png({ compressionLevel: 6 }) - .toBuffer(); - const annotatedFilename = `${isScaleAdjustOperation ? "canvas-scale-adjust-guide" : "canvas-local-edit"}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`; + left: 0, + top: 0, + }, + ]) + .png({ compressionLevel: 6 }) + .toBuffer(); + const annotatedFilename = `${isScaleAdjustOperation ? "canvas-scale-adjust-layout-guide" : "canvas-local-edit"}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`; const annotatedUpload = await uploadFile( annotatedFilename, toArrayBuffer(annotatedBuffer) ); - const scaleAdjustCropReferences = - isScaleAdjustOperation - ? await createScaleAdjustCropReferences({ + const scaleAdjustEditMaskUpload = useScaleAdjustEditMask + ? await uploadFile( + `canvas-scale-adjust-edit-mask-${Date.now()}-${Math.random() + .toString(36) + .slice(2, 8)}.png`, + toArrayBuffer( + await buildScaleAdjustEditMaskBuffer({ + regions, + scalePercent, + sourceHeight, + sourceWidth, + }) + ) + ) + : null; + const scaleAdjustPatchReference = useScaleAdjustPatchWorkflow + ? await createScaleAdjustPatchReference({ regions, + scalePercent, sourceBuffer, sourceHeight, sourceWidth, }) - : []; + : null; + const shouldCreateScaleAdjustCropReferences = + isScaleAdjustOperation && + (!scaleAdjustPatchReference && + (useScaleAdjustVisualLayoutGuide || + !useScaleAdjustCoordinatePrompt || + useProviderTextOnlyCoordinatePrompt || + (useScaleAdjustMarkedPhotoGuide && !useFalScaleAdjustCoordinatePrompt))); + const scaleAdjustCropReferences: ScaleAdjustCropReference[] = + shouldCreateScaleAdjustCropReferences + ? await createScaleAdjustCropReferences({ + regions, + sourceBuffer, + sourceHeight, + sourceWidth, + }) + : []; + const useScaleAdjustPatchTargetDraftPrimary = Boolean(scaleAdjustPatchReference); + const includeScaleAdjustPatchSourceReference = + scaleAdjustPatchReference?.structureLockedDraft === true; const prompt = isScaleAdjustOperation - ? useScaleAdjustCoordinateGuide + ? scaleAdjustPatchReference + ? buildScaleAdjustPatchPrompt( + regions, + scalePercent, + scaleAdjustPatchReference, + { width: sourceWidth, height: sourceHeight }, + scaleAdjustCropReferences, + { + includeSourceReference: includeScaleAdjustPatchSourceReference, + targetDraftPrimary: useScaleAdjustPatchTargetDraftPrimary, + } + ) + : useProviderTextOnlyCoordinatePrompt + ? buildScaleAdjustTextOnlyPrompt( + regions, + scalePercent, + scaleAdjustCropReferences, + { width: sourceWidth, height: sourceHeight } + ) + : useScaleAdjustCoordinatePrompt ? buildScaleAdjustCoordinatePrompt( regions, scalePercent, @@ -1414,7 +3183,12 @@ export async function POST(request: NextRequest) { width: sourceWidth, height: sourceHeight, }, - scaleAdjustCropReferences + scaleAdjustCropReferences, + { + falSafe: useFalScaleAdjustCoordinatePrompt, + markedPhotoGuide: useScaleAdjustMarkedPhotoGuide, + visualLayoutGuide: useScaleAdjustVisualLayoutGuide, + } ) : buildScaleAdjustPrompt( regions, @@ -1423,8 +3197,13 @@ export async function POST(request: NextRequest) { { width: sourceWidth, height: sourceHeight } ) : buildLocalEditPrompt(regions); - const scaleAdjustCoordinateNegativePrompt = - "visible annotation, guide overlay, translucent overlay, text label, arrows, boxes, rectangle border, UI marks, pasted patch, seam, hard rectangular edge, color mismatch, different-resolution area, whole image zoom, whole image crop, whole image pan, whole image redesign, unchanged target furniture, stretched furniture, squashed furniture, duplicate furniture, second copy, extra legs, extra rails, side panels, shelves, cabinets, lattice panels"; + const scaleAdjustCoordinateNegativePrompt = useFalScaleAdjustCoordinatePrompt + ? "guide marks, labels, boxes, arrows, overlays, patch edges, color mismatch, full-frame zoom, duplicate furniture, stretched furniture, distorted furniture" + : "visible annotation, guide overlay, translucent overlay, target placement overlay, faded wash, placeholder shadow, text label, arrows, boxes, rectangle border, UI marks, pasted patch, rough layout patch, hard crop edge, seam, hard rectangular edge, color mismatch, different-resolution area, whole image zoom, whole image crop, whole image pan, whole image redesign, unchanged target furniture, old-size target furniture, stretched furniture, squashed furniture, duplicate furniture, second copy, extra legs, extra rails, side panels, shelves, cabinets, lattice panels"; + const scaleAdjustTextOnlyNegativePrompt = + "artificial graphic overlay, visible coordinate aid, visible line, visible label, UI element, annotation text, full image redesign, full-frame zoom, crop, pan, pasted crop, hard patch edge, color mismatch, changed sofa, changed lamp, changed wall, changed rug, duplicate furniture, stretched furniture, distorted furniture"; + const scaleAdjustPatchNegativePrompt = + "full room image, changed crop border, artificial graphic overlay, visible coordinate aid, visible line, visible label, UI element, annotation text, guide mark, pasted crop, hard patch edge, color mismatch, gray draft patch, beige wash patch, flat painted area, broken woven panel, jagged mask hole, black speckled stain, dark blotch on cane panel, dirty woven panel, wheel inside woven panel, duplicate furniture, unchanged target furniture, changed locked product, redrawn product interior, different furniture, stretched furniture, distorted furniture"; const manualRegionReferenceImageUrls = regions.flatMap((region) => region.referenceImages.map((reference) => reference.url) ); @@ -1432,9 +3211,27 @@ export async function POST(request: NextRequest) { (reference) => reference.url ); const referenceImages = isScaleAdjustOperation - ? [ + ? scaleAdjustPatchReference + ? useScaleAdjustPatchTargetDraftPrimary + ? [ + scaleAdjustPatchReference.targetDraftUrl, + ...(includeScaleAdjustPatchSourceReference + ? [scaleAdjustPatchReference.sourceCropUrl] + : []), + ...scaleAdjustCropReferenceImageUrls, + ...manualRegionReferenceImageUrls, + ] + : [ + scaleAdjustPatchReference.sourceCropUrl, + scaleAdjustPatchReference.targetDraftUrl, + ...scaleAdjustCropReferenceImageUrls, + ...manualRegionReferenceImageUrls, + ] + : [ sourceImageUrl, - annotatedUpload.url, + ...(sendScaleAdjustAnnotatedReferenceToModel + ? [annotatedUpload.url] + : []), ...scaleAdjustCropReferenceImageUrls, ...manualRegionReferenceImageUrls, ] @@ -1442,18 +3239,19 @@ export async function POST(request: NextRequest) { const scaleAdjustCompositeRegions = isScaleAdjustOperation ? buildScaleAdjustCompositeRegions(regions, scalePercent) : []; + const scaleAdjustProtectedRegions = + isScaleAdjustOperation && scaleAdjustPatchReference + ? [...scaleAdjustCompositeRegions, scaleAdjustPatchReference.workspaceRect] + : scaleAdjustCompositeRegions; const scaleAdjustVerificationConfig = isScaleAdjustOperation ? { - allowOutsideChangedWhenChangedInside: useScaleAdjustCoordinateGuide - ? true - : undefined, - protectedRegions: scaleAdjustCompositeRegions, - rejectFailedCandidates: - useScaleAdjustCoordinateGuide && Boolean(scaleAdjustModelFamily) - ? true - : undefined, + allowOutsideChangedWhenChangedInside: false, + allowDeterministicFallback: false, + protectedRegions: scaleAdjustProtectedRegions, + rejectFailedCandidates: true, sourceImageUrl, regions: regions.map((region) => region.rect), + regionPrompts: regions.map((region) => region.prompt), ...(typeof scalePercent === "number" ? { scalePercent: scalePercent as ScaleAdjustPercent } : {}), @@ -1471,18 +3269,55 @@ export async function POST(request: NextRequest) { : {}), } : undefined; + const requestedImageSize = + typeof body.imageSize === "string" && body.imageSize.trim() + ? body.imageSize.trim() + : "2K"; + const resolvedRequestImageSize = + scaleAdjustPatchReference?.structureLockedDraft === true + ? requestedImageSize + : scaleAdjustPatchReference + ? "1K" + : requestedImageSize; const imageRequest: CanvasGenerateImageRequest = { - aspectRatio: resolvedAspectRatio, + allowFailover: isScaleAdjustOperation ? false : undefined, + aspectRatio: scaleAdjustPatchReference + ? inferClosestAspectRatio( + scaleAdjustPatchReference.workspacePixelRect.width, + scaleAdjustPatchReference.workspacePixelRect.height + ) + : resolvedAspectRatio, billingFeature: "repaint", debugLabel: operation === SCALE_ADJUST_OPERATION ? "canvas-scale-adjust" : "canvas-local-edit", debugMeta: { annotatedReferenceUrl: annotatedUpload.url, - annotatedReferenceSentToModel: isScaleAdjustOperation, + annotatedReferenceSentToModel: sendScaleAdjustAnnotatedReferenceToModel, annotatedReferenceType: isScaleAdjustOperation - ? "scale-adjust-neutral-coordinate-guide-map" + ? useProviderTextOnlyCoordinatePrompt + ? "scale-adjust-text-coordinate-only-debug-map" + : useScaleAdjustCoordinatePrompt + ? useScaleAdjustVisualLayoutGuide + ? "scale-adjust-visual-layout-guide" + : useScaleAdjustMarkedPhotoGuide + ? "scale-adjust-marked-photo-guide" + : "scale-adjust-neutral-coordinate-map" + : "scale-adjust-full-frame-semantic-edit-map" : "source-overlay", - cleanSourceReferenceIndex: 1, + scaleAdjustEditMaskApplied: Boolean(scaleAdjustEditMaskUpload), + scaleAdjustEditMaskUrl: scaleAdjustEditMaskUpload?.url || null, + scaleAdjustEditMaskProviderType: + useScaleAdjustEditMask + ? resolvedScaleAdjustModelEntry?.provider?.type || null + : null, + cleanSourceReferenceIndex: + scaleAdjustPatchReference && + useScaleAdjustPatchTargetDraftPrimary && + !includeScaleAdjustPatchSourceReference + ? null + : scaleAdjustPatchReference && useScaleAdjustPatchTargetDraftPrimary + ? 2 + : 1, configuredDetailModelId: configuredDetailModel || null, detailFixedModelApplied: Boolean(detailFixedModel), detailFixedModelId: detailFixedModel || null, @@ -1490,26 +3325,59 @@ export async function POST(request: NextRequest) { operation, requestedModel: requestedModel || null, resolvedAspectRatio, + scaleAdjustPatchWorkflowApplied: Boolean(scaleAdjustPatchReference), + scaleAdjustPatchStructureLockedDraftApplied: + scaleAdjustPatchReference?.structureLockedDraft === true, + scaleAdjustPatchReferenceOrder: + scaleAdjustPatchReference && useScaleAdjustPatchTargetDraftPrimary + ? includeScaleAdjustPatchSourceReference + ? "target-draft-source-identity" + : "target-draft-identity" + : scaleAdjustPatchReference + ? "source-target-draft-identity" + : null, + scaleAdjustPatchSourceCropUrl: + scaleAdjustPatchReference?.sourceCropUrl || null, + scaleAdjustPatchTargetDraftUrl: + scaleAdjustPatchReference?.targetDraftUrl || null, + scaleAdjustPatchWorkspacePixelRect: + scaleAdjustPatchReference?.workspacePixelRect || null, + scaleAdjustPatchWorkspaceRect: + scaleAdjustPatchReference?.workspaceRect || null, resolvedModel: resolvedModel || null, resolvedScaleAdjustProviderType: resolvedScaleAdjustModelEntry?.provider?.type || null, scaleAdjustModelFamily: scaleAdjustModelFamily || null, scaleAdjustCoordinateGuideApplied: useScaleAdjustCoordinateGuide, + scaleAdjustCoordinatePromptApplied: + useScaleAdjustCoordinatePrompt || useProviderTextOnlyCoordinatePrompt, + scaleAdjustTextOnlyCoordinatePromptApplied: + useProviderTextOnlyCoordinatePrompt, + scaleAdjustNeutralCoordinateMapApplied: + isScaleAdjustOperation && + useScaleAdjustCoordinatePrompt && + !useScaleAdjustMarkedPhotoGuide && + !useScaleAdjustVisualLayoutGuide, + scaleAdjustMarkedPhotoGuideApplied: useScaleAdjustMarkedPhotoGuide, + scaleAdjustFalMarkedPhotoGuideApplied: useFalScaleAdjustCoordinatePrompt, + scaleAdjustVisualLayoutGuideApplied: + isScaleAdjustOperation && + !useProviderTextOnlyCoordinatePrompt && + (!useScaleAdjustCoordinatePrompt || useScaleAdjustVisualLayoutGuide), falScaleAdjustCoordinateGuideApplied: useScaleAdjustCoordinateGuide && resolvedScaleAdjustModelEntry?.provider?.type === "fal-image", + falScaleAdjustSafePromptApplied: useFalScaleAdjustCoordinatePrompt, scaleAdjustProviderFallbackPolicy: isScaleAdjustOperation - ? scaleAdjustModelFamily - ? "same-name-service-error-only-fal-last" - : "default-model-failover" + ? "disabled-one-shot-single-model" : undefined, scaleAdjustQualityFailoverPolicy: isScaleAdjustOperation - ? "disabled-return-first-ai-candidate" + ? "disabled-reject-unchanged-ai-candidate" : undefined, scaleAdjustPreferSameNameProviderFailover: - isScaleAdjustOperation && Boolean(scaleAdjustModelFamily), + false, scaleAdjustStrictSameFamilyFailover: - isScaleAdjustOperation && Boolean(scaleAdjustModelFamily), + false, manualRegionReferenceImageCount: manualRegionReferenceImageUrls.length, regionReferenceImageCount: referenceImages.length, @@ -1522,12 +3390,23 @@ export async function POST(request: NextRequest) { scaleAdjustTargetRegionCount: regions.filter((region) => region.targetRect) .length, scaleAdjustPromptStrategy: isScaleAdjustOperation - ? useScaleAdjustCoordinateGuide - ? "same-name-locked-source-neutral-coordinate-map-v31-one-shot" - : "locked-plate-neutral-coordinate-guide-map-pixel-anchors-v8" + ? scaleAdjustPatchReference + ? scaleAdjustPatchReference.structureLockedDraft + ? "ai-patch-workspace-structure-locked-draft-v85-one-shot" + : "ai-patch-workspace-draft-v70-one-shot" + : useFalScaleAdjustCoordinatePrompt + ? "fal-safe-marked-photo-box-guide-no-old-crop-v44-one-shot" + : useScaleAdjustVisualLayoutGuide + ? "same-name-focused-layout-crop-guide-v54-one-shot" + : useProviderTextOnlyCoordinatePrompt + ? "provider-text-coordinate-crop-v61-one-shot" + : useScaleAdjustMarkedPhotoGuide + ? "same-name-marked-photo-box-guide-no-old-crop-v45-one-shot" + : "locked-plate-semantic-target-map-no-old-crop-v15" : undefined, - scaleAdjustPostCompositeApplied: false, - scaleAdjustUsesFullFrameOutput: isScaleAdjustOperation, + scaleAdjustPostCompositeApplied: Boolean(scaleAdjustPatchReference), + scaleAdjustUsesFullFrameOutput: + isScaleAdjustOperation && !scaleAdjustPatchReference, sourceHeight, sourceNodeId: body.sourceNodeId || null, sourceWidth, @@ -1535,25 +3414,38 @@ export async function POST(request: NextRequest) { displayPrompt, falSafetyTolerance: useScaleAdjustCoordinateGuide ? "6" : undefined, falSystemPrompt: - useScaleAdjustCoordinateGuide + useScaleAdjustCoordinatePrompt ? buildScaleAdjustCoordinateSystemPrompt() : undefined, falThinkingLevel: useScaleAdjustCoordinateGuide ? "high" : undefined, imageCount: 1, - imageSize: - typeof body.imageSize === "string" && body.imageSize.trim() - ? body.imageSize.trim() - : "2K", + imageSize: resolvedRequestImageSize, model: resolvedModel || undefined, negativePrompt: isScaleAdjustOperation - ? useScaleAdjustCoordinateGuide + ? scaleAdjustPatchReference + ? scaleAdjustPatchNegativePrompt + : useProviderTextOnlyCoordinatePrompt + ? scaleAdjustTextOnlyNegativePrompt + : useScaleAdjustCoordinatePrompt ? scaleAdjustCoordinateNegativePrompt - : "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、箭头、连线、角点、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、蓝色色块、色条、灰底坐标图、选区边框、白边、画幅压扁、画面拉伸、整张图缩放、全图放大、全图裁切、全图平移、整体重绘、删除文字、清理文字、改写文字、文字模糊、Logo消失、主体拉伸、主体压扁、主体变窄、主体变高但变窄、横向挤压、纵向拉伸、透视变形、矩形贴片、硬边、拼接线、补丁感、局部裁切、色差边缘、背景断裂、背景错位、窗框错位、文字错位、地毯纹理错位、非主体背景重绘、主体未缩放、整块框选区域缩放" + : "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、箭头、连线、角点、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、蓝色色块、色条、灰底坐标图、目标占位叠图、淡化痕迹、选区边框、白边、画幅压扁、画面拉伸、整张图缩放、全图放大、全图裁切、全图平移、文字位置变化、文字内容变化、文字模糊、Logo位置变化、主体拉伸、主体压扁、主体变窄、主体变高但变窄、横向挤压、纵向拉伸、透视变形、矩形贴片、硬边、拼接线、补丁感、局部裁切、色差边缘、背景断裂、背景错位、窗框错位、文字错位、地毯纹理错位、非主体背景重绘、主体未缩放、整块框选区域缩放" : "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、选区边框、白边、画幅压扁、画面拉伸、主体截断、动物截断、缺头、缺尾巴、缺四肢、贴边裁切、矩形贴片、硬边、拼接线、补丁感、色差边缘、背景错位、地面纹理断裂、椅脚错位", prompt, promptExtend: false, + providerImageParams: scaleAdjustEditMaskUpload + ? { maskImageUrl: scaleAdjustEditMaskUpload.url } + : undefined, referenceImages, + scaleAdjustPatchComposite: scaleAdjustPatchReference + ? { + featherMaxPx: 42, + featherMinPx: 10, + featherRatio: 0.018, + sourceImageUrl, + workspaceRegion: scaleAdjustPatchReference.workspaceRect, + } + : undefined, scaleAdjustVerification: scaleAdjustVerificationConfig, localEditComposite: isScaleAdjustOperation ? undefined