Merge commit '1ee72c20' into feat/xiaoyi-integration-core
# Conflicts: # apps/detail-agent-pi/src/agent.mjs # apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
This commit is contained in:
commit
629b278fe7
@ -1,108 +1,108 @@
|
||||
// UI activity is an allowlisted description of SDK events, never tool arguments,
|
||||
// tool results, provider errors or arbitrary model-generated text.
|
||||
const labels = Object.freeze({
|
||||
ask_user: '等待用户回复',
|
||||
context_read: '读取项目规则', memory_set: '记录事实', memory_search: '检索历史',
|
||||
tool_develop: '编写并测试工具', tool_run: '运行工具', canvas_read: '读取画布', canvas_template_image: '读取模板原图',
|
||||
canvas_edit: '更新图层', canvas_preview: '预览修改', copywriting_options: '生成卖点选项',copywriting_fields:'准备逐格文案', workflow_read: '读取创作进度', workflow_navigate: '切换创作视图',
|
||||
workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作',
|
||||
native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具',
|
||||
canvas_candidate_image: '核对图位和候选', bash: '运行项目终端',
|
||||
open_production_output: '打开制作画布',
|
||||
plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
|
||||
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
|
||||
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍',
|
||||
prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片',
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
defer_production_output: '保留当前草稿', check_image_slots: '发起验图', finish_production: '提交成品导出',
|
||||
save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据',
|
||||
plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案',
|
||||
});
|
||||
const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
|
||||
const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
|
||||
const operationCategories = Object.freeze({
|
||||
'pi-state':'ui_ack', 'pi-production-open':'canvas_read', 'pi-canvas-read':'canvas_read',
|
||||
'pi-product-screen':'canvas_read', 'pi-detail-copy-fields':'canvas_read',
|
||||
'pi-template-image':'canvas_read', 'pi-detail-images':'canvas_read', 'pi-workflow-read':'canvas_read',
|
||||
'pi-preview':'canvas_read', 'pi-native-catalog':'canvas_read',
|
||||
'pi-image-request':'remote_image', 'pi-detail-copy-apply':'canvas_write', 'pi-edit':'canvas_write',
|
||||
'pi-write-request':'canvas_write', 'pi-workflow-execute':'canvas_write', 'pi-native-call':'canvas_write',
|
||||
canvas_read:'canvas_read', canvas_preview:'canvas_read', read_output_screen:'canvas_read', read_copy_fields:'canvas_read',
|
||||
prepare_image_request:'remote_image', dispatch_image_request:'remote_image',
|
||||
reconcile_image_slots:'remote_image', adopt_production_image:'canvas_write',
|
||||
write_copy_fields:'canvas_write', canvas_edit:'canvas_write', finish_production:'export',
|
||||
production_image_retired:'remote_image', whole_detail_review:'inference',
|
||||
});
|
||||
export const executionCategory = action => operationCategories[action] ?? 'ui_ack';
|
||||
|
||||
const inferencePhases = Object.freeze({
|
||||
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
|
||||
provider_started:['dispatch','running'], provider_finished:['receipt','completed'],
|
||||
provider_error:['receipt','failed'], response_audit:['inspect','completed'],
|
||||
usage:['usage','completed'], pi_retry:['retry','pending'],
|
||||
});
|
||||
|
||||
export function executionEvent(event, scope, health, at = Date.now()) {
|
||||
const inference = inferencePhases[event.type];
|
||||
const category = event.category ?? (inference ? 'inference' : executionCategory(event.toolName ?? event.type));
|
||||
const phase = event.phase ?? inference?.[0] ?? event.type;
|
||||
const status = event.status ?? (event.consumption === 'discarded_after_cancel' ? 'cancelled' :
|
||||
event.type === 'provider_finished' && event.phase ? event.phase :
|
||||
inference?.[1] ?? (event.isError ? 'failed' : 'completed'));
|
||||
// Keep legacy phase values on provider receipts and an independent lifecycle stage.
|
||||
return {at,...event,category,phase,status,stage:event.stage ?? inference?.[0] ?? phase,
|
||||
projectId:event.projectId ?? scope.projectId ?? null,runId:event.runId ?? scope.runId ?? null,
|
||||
operationId:event.operationId ?? event.id ?? event.toolCallId ?? scope.runId ?? null,
|
||||
attempt:event.attempt ?? 1,outputId:event.outputId ?? scope.outputId ?? null,
|
||||
variantId:event.variantId ?? scope.variantId ?? null,revision:event.revision ?? scope.revision ?? null,
|
||||
documentKey:event.documentKey ?? scope.documentKey ?? null,
|
||||
agentHeartbeat:health.agentHeartbeat ?? null,uiHeartbeat:health.uiHeartbeat ?? null,
|
||||
jobProgress:event.jobProgress ?? null,recentDurableCommit:health.recentDurableCommit ?? null};
|
||||
}
|
||||
|
||||
// Read this once from pi-begin, whose requestScope is frozen by the native host.
|
||||
// IDs outside the expected format are omitted instead of copied as free text.
|
||||
export function activityScope(identity, canvas, begun) {
|
||||
const request = begun?.context?.requestScope;
|
||||
const subject = request?.subject;
|
||||
// Production canvas state omits the full context. Its active begin receipt
|
||||
// still confirms the document carried by this native connection.
|
||||
const documentId = begun?.context?.id ?? (
|
||||
begun?.conversationActive === true && begun.run === canvas?.run ? canvas?.documentId : undefined
|
||||
);
|
||||
const values = {
|
||||
accountScope: safeId(identity?.scope), project: safeId(identity?.project),
|
||||
documentId: safeNumber(documentId), run: safeId(canvas?.run),
|
||||
outputId: safeId(request?.outputId), variantId: safeId(request?.variantId),
|
||||
slotId: safeId(subject?.slotId), candidateId: safeId(subject?.candidateId),
|
||||
revision: safeNumber(begun?.revision),
|
||||
};
|
||||
return Object.freeze(Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)));
|
||||
}
|
||||
|
||||
function details(event) {
|
||||
const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other';
|
||||
const stopped = event.isError && ['write_revoked','revision_conflict','cancelled']
|
||||
.includes(event.result?.details?.failure?.category);
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
const label = labels[toolName] || '工具';
|
||||
const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`;
|
||||
return { toolName, status, summary };
|
||||
}
|
||||
|
||||
export function activitySummary(event) { return details(event).summary; }
|
||||
|
||||
export function toolActivity(event, scope, timestampMs = Date.now()) {
|
||||
if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null;
|
||||
const toolCallId = safeId(event.toolCallId);
|
||||
if (!toolCallId || safeNumber(timestampMs) === undefined) return null;
|
||||
const durationMs = safeNumber(event.durationMs);
|
||||
const activity = details(event);
|
||||
return { version: 1, type: 'tool', toolCallId, ...activity, phase:activity.status,
|
||||
category:executionCategory(activity.toolName),timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope };
|
||||
}
|
||||
// UI activity is an allowlisted description of SDK events, never tool arguments,
|
||||
// tool results, provider errors or arbitrary model-generated text.
|
||||
const labels = Object.freeze({
|
||||
ask_user: '等待用户回复',
|
||||
context_read: '读取项目规则', memory_set: '记录事实', memory_search: '检索历史',
|
||||
tool_develop: '编写并测试工具', tool_run: '运行工具', canvas_read: '读取画布', canvas_template_image: '读取模板原图',
|
||||
canvas_edit: '更新图层', canvas_preview: '预览修改', copywriting_options: '生成卖点选项',copywriting_fields:'准备逐格文案', workflow_read: '读取创作进度', workflow_navigate: '切换创作视图',
|
||||
workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作',
|
||||
native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具',
|
||||
canvas_candidate_image: '核对图位和候选', bash: '运行项目终端',
|
||||
open_production_output: '打开制作画布',
|
||||
plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
|
||||
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
|
||||
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍', transform_slot_image: '调整候选图片',
|
||||
prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片',
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
defer_production_output: '保留当前草稿', check_image_slots: '发起验图', finish_production: '提交成品导出',
|
||||
save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据',
|
||||
plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案',
|
||||
});
|
||||
const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
|
||||
const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
|
||||
const operationCategories = Object.freeze({
|
||||
'pi-state':'ui_ack', 'pi-production-open':'canvas_read', 'pi-canvas-read':'canvas_read',
|
||||
'pi-product-screen':'canvas_read', 'pi-detail-copy-fields':'canvas_read',
|
||||
'pi-template-image':'canvas_read', 'pi-detail-images':'canvas_read', 'pi-workflow-read':'canvas_read',
|
||||
'pi-preview':'canvas_read', 'pi-native-catalog':'canvas_read',
|
||||
'pi-image-request':'remote_image', 'pi-detail-copy-apply':'canvas_write', 'pi-edit':'canvas_write',
|
||||
'pi-write-request':'canvas_write', 'pi-workflow-execute':'canvas_write', 'pi-native-call':'canvas_write',
|
||||
canvas_read:'canvas_read', canvas_preview:'canvas_read', read_output_screen:'canvas_read', read_copy_fields:'canvas_read',
|
||||
prepare_image_request:'remote_image', dispatch_image_request:'remote_image',
|
||||
reconcile_image_slots:'remote_image', adopt_production_image:'canvas_write',
|
||||
write_copy_fields:'canvas_write', canvas_edit:'canvas_write', finish_production:'export',
|
||||
production_image_retired:'remote_image', whole_detail_review:'inference',
|
||||
});
|
||||
export const executionCategory = action => operationCategories[action] ?? 'ui_ack';
|
||||
|
||||
const inferencePhases = Object.freeze({
|
||||
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
|
||||
provider_started:['dispatch','running'], provider_finished:['receipt','completed'],
|
||||
provider_error:['receipt','failed'], response_audit:['inspect','completed'],
|
||||
usage:['usage','completed'], pi_retry:['retry','pending'],
|
||||
});
|
||||
|
||||
export function executionEvent(event, scope, health, at = Date.now()) {
|
||||
const inference = inferencePhases[event.type];
|
||||
const category = event.category ?? (inference ? 'inference' : executionCategory(event.toolName ?? event.type));
|
||||
const phase = event.phase ?? inference?.[0] ?? event.type;
|
||||
const status = event.status ?? (event.consumption === 'discarded_after_cancel' ? 'cancelled' :
|
||||
event.type === 'provider_finished' && event.phase ? event.phase :
|
||||
inference?.[1] ?? (event.isError ? 'failed' : 'completed'));
|
||||
// Keep legacy phase values on provider receipts and an independent lifecycle stage.
|
||||
return {at,...event,category,phase,status,stage:event.stage ?? inference?.[0] ?? phase,
|
||||
projectId:event.projectId ?? scope.projectId ?? null,runId:event.runId ?? scope.runId ?? null,
|
||||
operationId:event.operationId ?? event.id ?? event.toolCallId ?? scope.runId ?? null,
|
||||
attempt:event.attempt ?? 1,outputId:event.outputId ?? scope.outputId ?? null,
|
||||
variantId:event.variantId ?? scope.variantId ?? null,revision:event.revision ?? scope.revision ?? null,
|
||||
documentKey:event.documentKey ?? scope.documentKey ?? null,
|
||||
agentHeartbeat:health.agentHeartbeat ?? null,uiHeartbeat:health.uiHeartbeat ?? null,
|
||||
jobProgress:event.jobProgress ?? null,recentDurableCommit:health.recentDurableCommit ?? null};
|
||||
}
|
||||
|
||||
// Read this once from pi-begin, whose requestScope is frozen by the native host.
|
||||
// IDs outside the expected format are omitted instead of copied as free text.
|
||||
export function activityScope(identity, canvas, begun) {
|
||||
const request = begun?.context?.requestScope;
|
||||
const subject = request?.subject;
|
||||
// Production canvas state omits the full context. Its active begin receipt
|
||||
// still confirms the document carried by this native connection.
|
||||
const documentId = begun?.context?.id ?? (
|
||||
begun?.conversationActive === true && begun.run === canvas?.run ? canvas?.documentId : undefined
|
||||
);
|
||||
const values = {
|
||||
accountScope: safeId(identity?.scope), project: safeId(identity?.project),
|
||||
documentId: safeNumber(documentId), run: safeId(canvas?.run),
|
||||
outputId: safeId(request?.outputId), variantId: safeId(request?.variantId),
|
||||
slotId: safeId(subject?.slotId), candidateId: safeId(subject?.candidateId),
|
||||
revision: safeNumber(begun?.revision),
|
||||
};
|
||||
return Object.freeze(Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)));
|
||||
}
|
||||
|
||||
function details(event) {
|
||||
const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other';
|
||||
const stopped = event.isError && ['write_revoked','revision_conflict','cancelled']
|
||||
.includes(event.result?.details?.failure?.category);
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
const label = labels[toolName] || '工具';
|
||||
const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`;
|
||||
return { toolName, status, summary };
|
||||
}
|
||||
|
||||
export function activitySummary(event) { return details(event).summary; }
|
||||
|
||||
export function toolActivity(event, scope, timestampMs = Date.now()) {
|
||||
if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null;
|
||||
const toolCallId = safeId(event.toolCallId);
|
||||
if (!toolCallId || safeNumber(timestampMs) === undefined) return null;
|
||||
const durationMs = safeNumber(event.durationMs);
|
||||
const activity = details(event);
|
||||
return { version: 1, type: 'tool', toolCallId, ...activity, phase:activity.status,
|
||||
category:executionCategory(activity.toolName),timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope };
|
||||
}
|
||||
|
||||
@ -63,6 +63,7 @@ references是用户提交时冻结的本轮引用;component为pixelMask或vect
|
||||
const PRODUCTION_SYSTEM = `你是小壹的制作 Agent。先读本项目适用的企业 Skill,并按它及模板在 PhotoCraft 制作和复核。由你决定要做什么、顺序、并行和返工。
|
||||
用 plan_production 读取本轮输出和工作画布。尚未绑定时,单独调用 open_production_output 打开所选画布,收到已保存的绑定回执后再查询 native_catalog 或调用画布工具。打开失败时按回执处理,可重新打开或选择另一待制作输出。用户查看的页面和制作画布独立。
|
||||
企业 Skill 中的命令行编修可在当前画布用等价的 PhotoCraft 原生命令完成。用已有产品资料写买家看得懂的文案,检查实际画面的图文对应、品牌元素和旧商品信息。
|
||||
transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
|
||||
复核后提交当前修订。PhotoCraft 按实际导出回执交接下一项。有子代理在运行就等待回执,原请求结果未确认时按原编号核查。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
|
||||
|
||||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||||
@ -75,7 +76,7 @@ const inactiveDocument = error => error?.category === 'scope_changed';
|
||||
const sequentialTools = new Set([
|
||||
'memory_set', 'canvas_edit', 'canvas_preview', 'copywriting_options', 'copywriting_fields',
|
||||
'workflow_navigate', 'workflow_execute', 'workflow_propose',
|
||||
'open_production_output', 'write_copy_fields', 'use_product_image', 'prepare_image_request',
|
||||
'open_production_output', 'write_copy_fields', 'use_product_image', 'transform_slot_image', 'prepare_image_request',
|
||||
'dispatch_image_request', 'delegate_image_slots', 'stage_archived_image', 'check_image_slots',
|
||||
'adopt_production_image', 'retire_production_image', 'reconcile_image_slots', 'record_screen_check',
|
||||
'defer_production_output', 'finish_production',
|
||||
|
||||
@ -11,6 +11,18 @@ export const copySignature = copy=>copy.map(({field,text,claims})=>[field,...(cl
|
||||
.sort(([left],[right])=>left.localeCompare(right));
|
||||
|
||||
const reviewChecks=['structure','color','templateStyle','composition','evidence'];
|
||||
const actions=['adopt','canvas_adjust','regenerate'];
|
||||
const coordinate=Type.Integer({minimum:0,maximum:1000});
|
||||
export const canvasTransformArgs={
|
||||
crop:Type.Optional(Type.Tuple([coordinate,coordinate,coordinate,coordinate],{
|
||||
description:'原图坐标 [左,上,右,下],从 0 到 1000。'})),
|
||||
flipX:Type.Optional(Type.Boolean()),flipY:Type.Optional(Type.Boolean()),
|
||||
rotateDeg:Type.Optional(Type.Number({description:'正值为顺时针角度。'})),
|
||||
scale:Type.Optional(Type.Number({exclusiveMinimum:0,description:'相对 fit 的缩放倍数,默认 1。'})),
|
||||
offsetX:Type.Optional(Type.Number({description:'向右移动的目标图框像素数。'})),
|
||||
offsetY:Type.Optional(Type.Number({description:'向下移动的目标图框像素数。'})),
|
||||
fit:Type.Optional(Type.Union([Type.Literal('cover'),Type.Literal('contain')])),
|
||||
};
|
||||
|
||||
export function readAutoAdoptionPolicy(policy) {
|
||||
if(policy==null)return null;
|
||||
@ -47,11 +59,12 @@ export function decideCandidateSet(policy, requests, reviews) {
|
||||
export async function reviewProductionCandidate({
|
||||
canvas,host,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
|
||||
reviewKnowledge,useFramedOriginal=true,refusal,onRequestFailure,requireOriginal=false,
|
||||
allowCanvasAdjustment=true,
|
||||
}) {
|
||||
const input=await canvas.detailImages(slot.id,candidateId,{
|
||||
...(adopted?{adopted:true}:null),
|
||||
...(rule?.actionReviewRegion?{actionReviewDetail:true}:null),
|
||||
...(requireOriginal?{includeCandidateOriginal:true}:null),
|
||||
...(requireOriginal||allowCanvasAdjustment&&!adopted?{includeCandidateOriginal:true}:null),
|
||||
});
|
||||
if(input.candidateId!==candidateId||!input.referenceCount||
|
||||
input.images?.length!==input.referenceCount+(input.layoutCount??0)+1||
|
||||
@ -86,7 +99,12 @@ export async function reviewProductionCandidate({
|
||||
const issue = {location:Type.String(),problem:Type.String(),suggestion:Type.String()};
|
||||
const assessment=params({
|
||||
candidateId:Type.String(),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))),
|
||||
...(allowCanvasAdjustment?{
|
||||
recommendedAction:Type.Optional(Type.Union(actions.map(value=>Type.Literal(value)))),
|
||||
canvasTransform:Type.Optional(params(canvasTransformArgs)),
|
||||
}:null),
|
||||
checks:params({structure:Type.Boolean(),color:Type.Boolean(),
|
||||
...(allowCanvasAdjustment?{material:Type.Optional(Type.Boolean())}:null),
|
||||
templateStyle:Type.Optional(Type.Boolean({description:'按本项目发布的规则判断模板风格'})),
|
||||
composition:Type.Boolean(),evidence:Type.Boolean()}),
|
||||
mustRedo:Type.Optional(Type.Array(params({...issue,
|
||||
@ -104,13 +122,14 @@ export async function reviewProductionCandidate({
|
||||
const review=tool('review_candidate','提交对候选图的独立结论、理由和画面依据。',assessment,value=>{
|
||||
if(value.candidateId!==candidateId)throw Error('验图候选编号不一致');
|
||||
if(!['pass','revise','missing'].includes(value.verdict))throw new InvalidToolReply('请明确填写候选的验图结论');
|
||||
receipt={candidateId,verdict:value.verdict,checks:value.checks,reason:value.reason,observation:{
|
||||
receipt={candidateId,verdict:value.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform,
|
||||
checks:value.checks,reason:value.reason,observation:{
|
||||
source,reviewedCopy:copySignature(copy),visualEvidence:value.shownFields??[],pixelFindings,
|
||||
mustRedo:value.mustRedo??[],canvasFixes:value.canvasFixes??[],
|
||||
generationFixes:value.generationFixes??value.mustRedo?.map(issue=>issue.suggestion),structureGuides:value.structureGuides,
|
||||
...(adopted?{adoptedCanvas:true}:null),...(originalReference?{originalReference}:null),
|
||||
}};
|
||||
const details={verdict:receipt.verdict};
|
||||
const details={verdict:receipt.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform};
|
||||
return {content:[{type:'text',text:JSON.stringify(details)}],details,terminate:true};
|
||||
});
|
||||
const requirements=rule?.focus??input.prompt??input.requirements;
|
||||
@ -128,6 +147,7 @@ export async function reviewProductionCandidate({
|
||||
'附件是供视觉查看的预览。原件的尺寸和透明通道见 candidateFile,实际图框见 frame。pixelFindings 是像素检查记录。',
|
||||
'requirements 是当前 fieldId 的画面要求。templateContext 提供整屏目标与通用适配规则。整屏要实现的多图对应关系由各图位分别完成,交给整屏复核。',
|
||||
'按发布规则分别记录 mustRedo 和 canvasFixes,填写问题位置、说明及建议。用 shownFields 记录画面可见依据。',
|
||||
...(allowCanvasAdjustment?['商品主体准确且问题仅涉及构图、裁切、朝向或偏移时,可在 canvasFixes 提出建议,并选填 recommendedAction 或 canvasTransform。裁切坐标以未裁切原图为准。主代理根据画面决定后续操作。']:[]),
|
||||
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
|
||||
...(reviewKnowledge.files.length?[knowledgeReadInstruction]:[]),
|
||||
'调用 review_candidate 提交结论。',
|
||||
|
||||
@ -578,7 +578,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
|
||||
const {referenceCount:observed,...result}=await reviewProductionCandidate({
|
||||
canvas,host,runAgent,slot,candidateId,signal,copy,rule,source,adopted,
|
||||
fit:fitFor(slot,source),artDirection:sceneDirection(rule),reviewKnowledge,
|
||||
useFramedOriginal:verifiedProduction,refusal:journal.items[slot.id]?.reviewRequestRejection,
|
||||
useFramedOriginal:verifiedProduction,allowCanvasAdjustment:false,refusal:journal.items[slot.id]?.reviewRequestRejection,
|
||||
onRequestFailure:reviewRequestRejection=>save(slot,{reviewRequestRejection}),
|
||||
});
|
||||
referenceCount=observed;
|
||||
|
||||
@ -7,7 +7,7 @@ import { PresentationBatch } from './stream-presentation.mjs';
|
||||
import { loadSlots } from './production-slots.mjs';
|
||||
import { productionKnowledge, knowledgeReadInstruction } from './production-knowledge.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { copySignature, decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from './candidate-review.mjs';
|
||||
import { canvasTransformArgs, copySignature, decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from './candidate-review.mjs';
|
||||
import { executeWorkflow, LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } from './workflow-execute.mjs';
|
||||
|
||||
const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
@ -23,6 +23,11 @@ const nextOutput=optional(obj({outputId:text,variantId:text}));
|
||||
const productImageArgs={
|
||||
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
|
||||
};
|
||||
const transformImageArgs={
|
||||
sourceCandidateId:optional(Type.String({description:'本项目当前花色的已完成候选号,可来自其他图位。'})),
|
||||
referenceIndex:optional(Type.Integer({minimum:0,maximum:7,description:'本款实拍的零起始编号,与候选号二选一。'})),
|
||||
...canvasTransformArgs,
|
||||
};
|
||||
const settledImagePhases=['complete','failed','retired','expired'];
|
||||
const expiryFields=receipt=>receipt?.resultExpiry?
|
||||
{requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
|
||||
@ -41,9 +46,9 @@ const preparationArgs={
|
||||
reworkCandidateId:optional(text),
|
||||
referenceIndexes:optional(Type.Array(page,{minItems:1,uniqueItems:true,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
|
||||
geometryReferenceIndex:optional(page),
|
||||
useTemplateReference:optional(Type.Boolean({description:'传 true,将模板参考追加到原片之后。'})),
|
||||
useTemplateReference:optional(Type.Boolean({description:'传 true 将模板参考追加到实拍之后,担心影响商品结构时可传 false。'})),
|
||||
useSceneComposite:optional(Type.Boolean({description:'模板声明实拍合成时,可只提交模板场景以擦除旧商品。prompt 应完整描述擦除;本款实拍在本地合成。'})),
|
||||
prefer2k:optional(Type.Boolean()),
|
||||
prefer2k:optional(Type.Boolean({description:'传 true 可请求 2K,例如用于后续局部裁切。'})),
|
||||
retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})),
|
||||
};
|
||||
const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:optional(text)};
|
||||
@ -62,7 +67,8 @@ export const productionOperationTools = [
|
||||
slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
|
||||
})],
|
||||
['use_product_image','用本款原片或裁切区域创建候选,返回后可继续处理其他图位。',obj({slotId:slotRef,...productImageArgs})],
|
||||
['prepare_image_request','保存完整生图请求。回执含可审阅的正式文本、实际参考顺序和模型参数,以及 requestId、revision 和 requestSpecHash。',obj({slotId:slotRef,...preparationArgs})],
|
||||
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移同图位或跨图位候选及本款实拍,返回新候选和像素清晰度指标。',obj({slotId:slotRef,...transformImageArgs})],
|
||||
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。',obj({slotId:slotRef,...preparationArgs})],
|
||||
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj(dispatchArgs)],
|
||||
['delegate_image_slots','把图位和可执行要求交给 Pi 子代理并行制作。每个图位单独返回已接收或无法定位的结果。',obj({
|
||||
jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
@ -113,7 +119,8 @@ function slotAttempts(slot, record) {
|
||||
const latest=record?.review;
|
||||
if((latest?.decision??latest?.verdict)==='revise'&&!reviews.some(row=>row.candidateId===latest.candidateId)){
|
||||
reviews.push({candidateId:latest.candidateId,reason:latest.reason,mustRedo:latest.observation?.mustRedo,
|
||||
generationFixes:latest.observation?.generationFixes});
|
||||
generationFixes:latest.observation?.generationFixes,recommendedAction:latest.recommendedAction,
|
||||
canvasTransform:latest.canvasTransform});
|
||||
}
|
||||
const attempts=record?.attempts??[];
|
||||
const attemptCount=new Set([
|
||||
@ -469,6 +476,22 @@ export async function openProductionOperations(host) {
|
||||
return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId,
|
||||
pendingOriginal:candidateId??original?.operationId};
|
||||
};
|
||||
const transformImage=async(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
await current();
|
||||
const receipt=await canvas.imageRequest('transform',{slotId:slot.id,sourceCandidateId,referenceIndex,transform});
|
||||
if(receipt?.status!=='complete'||!receipt.id)throw Error('原生画布未返回已保存的变换候选');
|
||||
const result={...receipt,candidateId:receipt.id,phase:'complete'};
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption&&!Object.keys(item.pendingGenerations??{}).length){
|
||||
Object.assign(item,{state:'candidate',candidateId:receipt.id,source:'transform'});
|
||||
}
|
||||
},{evidence:[slot.id,receipt.id,'candidate',receipt]});
|
||||
candidates.set(receipt.id,{slotId:slot.id,status:'complete'});
|
||||
notice('画布调整已有候选');
|
||||
return result;
|
||||
};
|
||||
const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,
|
||||
referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange,candidateSetId},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
@ -626,8 +649,8 @@ export async function openProductionOperations(host) {
|
||||
notice('正在核验候选图片');
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas,host,runAgent:host.runDetailAgent,
|
||||
slot,candidateId,signal,copy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews,requireOriginal:Boolean(candidateSet)});
|
||||
const {verdict,checks,reason,observation}=review;
|
||||
const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,
|
||||
const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review;
|
||||
const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform,
|
||||
evidenceVersion:1,creationRevision:plan.revisions?.creation};
|
||||
await update(journal=>{
|
||||
const record=journal.items[slot.id]??={};
|
||||
@ -636,7 +659,7 @@ export async function openProductionOperations(host) {
|
||||
record.approvals=(record.approvals??[]).filter(old=>old.candidateId!==candidateId);
|
||||
if(verdict==='pass')record.approvals.push(row);
|
||||
const history=record.reviewHistory??=[];
|
||||
history.push({candidateId,verdict,reason,mustRedo:observation.mustRedo,generationFixes:observation.generationFixes});
|
||||
history.push({candidateId,verdict,reason,recommendedAction,canvasTransform,mustRedo:observation.mustRedo,generationFixes:observation.generationFixes});
|
||||
},{evidence:[slot.id,candidateId,'review',row]});
|
||||
candidates.set(candidateId,{slotId:slot.id,status:verdict==='pass'?'passed':'rejected',reason});
|
||||
const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf;
|
||||
@ -750,6 +773,9 @@ export async function openProductionOperations(host) {
|
||||
const slot=matches(slotId);
|
||||
return launchImage(slot,slot.id,()=>useProductImage(slot,options,signal));
|
||||
},
|
||||
transform_slot_image({slotId,...options},signal){
|
||||
return serialize(()=>transformImage(matches(slotId),options,signal));
|
||||
},
|
||||
prepare_image_request({slotId,...args},signal){
|
||||
return prepareImageRequest(matches(slotId),args,signal);
|
||||
},
|
||||
@ -775,9 +801,9 @@ export async function openProductionOperations(host) {
|
||||
const activeSignal=signals.length?AbortSignal.any(signals):undefined;
|
||||
const result=await execute(args,activeSignal);
|
||||
const done=typeof terminate==='function'?terminate(result):terminate;
|
||||
if(terminate){
|
||||
if(terminate||name==='transform_slot_image'){
|
||||
produced=true;
|
||||
if(name==='use_product_image')generation.set(workerId,{slotId:slot.id,...result});
|
||||
if(name==='use_product_image'||name==='transform_slot_image')generation.set(workerId,{slotId:slot.id,...result});
|
||||
}
|
||||
return {...imageResult(result),...(done?{terminate:true}:null)};
|
||||
},
|
||||
@ -785,6 +811,8 @@ export async function openProductionOperations(host) {
|
||||
const makeTools=()=>[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>useProductImage(slot,args,activeSignal),true),
|
||||
workerTool('transform_slot_image','用本款实拍或本项目候选裁切、镜像、旋转、缩放或位移',transformImageArgs,
|
||||
(args,activeSignal)=>serialize(()=>transformImage(slot,args,activeSignal))),
|
||||
workerTool('prepare_image_request','准备并持久保存完整生图请求',preparationArgs,
|
||||
(args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)),
|
||||
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
|
||||
@ -816,6 +844,7 @@ export async function openProductionOperations(host) {
|
||||
if(old.candidateId===candidateId&&old.images?.at(-1)?.type==='image')rejectedImage=old.images.at(-1);
|
||||
const attempt=prior?.attempts?.find(entry=>entry.candidateId===candidateId);
|
||||
rework={candidateId,attempt:attemptCount+1,reason:feedback?.reason,
|
||||
recommendedAction:feedback?.recommendedAction,canvasTransform:feedback?.canvasTransform,
|
||||
suggestions:feedback?.mustRedo,generationFixes:feedback?.generationFixes,
|
||||
previousPrompt:old.candidateId===candidateId?old.candidatePrompt??undefined:undefined,
|
||||
previousInstruction:attempt?.prompt,
|
||||
@ -825,7 +854,7 @@ export async function openProductionOperations(host) {
|
||||
};
|
||||
}
|
||||
}
|
||||
const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、审阅准备回执并确认派发。'+
|
||||
const instructions='完成主代理委托的图位。可用 transform_slot_image 调整本款实拍或同图位、跨图位候选,并查看像素指标。仅需调整构图时可复用现有图片。特写可裁切已有或用 prefer2k 请求的 2K 中景,也可按需关闭模板参考。完成调整后可直接结束,也可继续调整或准备生图请求。'+
|
||||
(autoAdoptionPolicy?'\n按自动采用政策准备全部同批候选。后续准备传首张的 candidateSet.id 和同一份完整请求,备齐后分别审阅并派发。':'')+
|
||||
(rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+
|
||||
knowledgeReadInstruction;
|
||||
|
||||
@ -8,8 +8,10 @@ description: Use product image sources and Image Request tools in PhotoCraft.
|
||||
从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。
|
||||
|
||||
- `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。
|
||||
- transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
|
||||
- 按已发布规则撰写完整的 `prompt`,包括商品外观、构图、颜色、参考用途和返工要求。用 `referenceIndexes` 指定发送的原片及顺序,按需指定模板参考、画幅规格或实拍合成。实拍合成时,提示词描述在模板场景中擦除旧商品,本款实拍由客户端合成。
|
||||
- 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。调用 `dispatch_image_request` 时填写该回执的 `requestId`,宿主从该编号绑定的请求读取版本和哈希。
|
||||
- `plan_production` 返回 `autoAdoptionPolicy` 时,按 `candidateCount` 准备同批样本。第二张起传入首张的 `candidateSet.id` 和相同的正式请求。备齐后分别确认派发,完成后将整批编号交给 `check_image_slots`。验完会自动采用合格图,全部退回时可在图位回执查看待返工记录。
|
||||
- `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。
|
||||
- 验图可提供画布调整建议,按当前画面决定是否调整、重新生成或采用。
|
||||
- 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。
|
||||
|
||||
@ -828,7 +828,7 @@ test('production publishes direct native commands and no duplicate conversation
|
||||
for(const name of ['plan_production','native_catalog','read_production_knowledge','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){
|
||||
assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
|
||||
}
|
||||
for(const name of ['native_call','prepare_image_request','dispatch_image_request','finish_production']){
|
||||
for(const name of ['native_call','prepare_image_request','dispatch_image_request','transform_slot_image','finish_production']){
|
||||
assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
|
||||
}
|
||||
assert.equal((await x.host.prompt('完成制作')).production.complete,true);
|
||||
|
||||
@ -36,6 +36,118 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
function approve({requestId,revision,requestSpecHash}) {
|
||||
return {requestId,expectedRevision:revision,expectedHash:requestSpecHash};
|
||||
}
|
||||
|
||||
test('canvas advice leaves review, transformation and generation under agent control',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-canvas-adjust-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
const image={type:'image',mimeType:'image/png',data:'fixture'};
|
||||
const reviewed=[],transforms=[],placements=[];
|
||||
const metrics={cropSourcePixels:[120,100],targetFrame:[750,500],resolutionRatio:0.16,resolutionSufficient:false};
|
||||
const options={crop:[150,100,850,900],flipX:true,rotateDeg:-2,offsetY:4};
|
||||
const canvas={
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'detail',productVariantId:'oak',
|
||||
template:{contentHash:'studio'},totalSlots:1,slots:[{id:'slot',fieldId:'P05'}]}),
|
||||
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
|
||||
detailImages:async(_slot,candidateId,args)=>{
|
||||
assert.equal(args.includeCandidateOriginal,true);
|
||||
return {candidateId,referenceCount:1,images:[image,image]};
|
||||
},
|
||||
async imageRequest(action,args){
|
||||
assert.equal(action,'transform');
|
||||
transforms.push(args);
|
||||
return {status:'complete',id:'fixed',sourceCandidateId:'original',materialTaskId:'original-task',
|
||||
sourceRequestId:'source-request',...metrics};
|
||||
},
|
||||
read:async()=>({revision:3}),requestWrite:async revision=>({allowed:true,revision}),
|
||||
async workflowExecute({intent,operationId,candidateId}){
|
||||
assert.equal(intent,'adopt_candidate');
|
||||
placements.push(candidateId);
|
||||
return {phase:'submitted',operationId,candidateId};
|
||||
},
|
||||
async workflowPoll(operationId){return {operationId,candidateId:placements.at(-1),phase:'complete'};},
|
||||
};
|
||||
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'},
|
||||
async runDetailAgent(_slot,_system,prompt,tools){
|
||||
const {candidateId}=JSON.parse(prompt);
|
||||
if(!candidateId){
|
||||
const transform=tools.find(tool=>tool.name==='transform_slot_image');
|
||||
const receipt=await transform.execute('crop',{sourceCandidateId:'original',...options});
|
||||
assert.equal(receipt.terminate,undefined);
|
||||
assert.deepEqual(Object.fromEntries(Object.keys(metrics).map(key=>[key,receipt.details[key]])),metrics);
|
||||
assert.equal(receipt.details.sourceRequestId,'source-request');
|
||||
return;
|
||||
}
|
||||
reviewed.push(candidateId);
|
||||
const advice=candidateId==='original';
|
||||
await tools[0].execute('review',{candidateId,verdict:'revise',
|
||||
...(advice?{recommendedAction:'canvas_adjust',canvasTransform:options}:{}),
|
||||
checks:{structure:true,color:true,composition:false,evidence:true},
|
||||
reason:'商品正确,画面轻微歪斜且朝向反了'});
|
||||
},
|
||||
};
|
||||
const actions=await openProductionOperations(host);
|
||||
const [result]=await actions.check_image_slots({wait:true,candidates:[{slotId:'P05',candidateId:'original'}]});
|
||||
assert.deepEqual(reviewed,['original']);
|
||||
assert.deepEqual(transforms,[]);
|
||||
assert.deepEqual(placements,[]);
|
||||
assert.equal(result.recommendedAction,'canvas_adjust');
|
||||
assert.deepEqual(result.canvasTransform,options);
|
||||
const [withoutAdvice]=await actions.check_image_slots({wait:true,candidates:[{slotId:'P05',candidateId:'other'}]});
|
||||
assert.equal(withoutAdvice.verdict,'revise');
|
||||
assert.equal(withoutAdvice.recommendedAction,undefined);
|
||||
|
||||
const fixed=await actions.transform_slot_image({slotId:'P05',sourceCandidateId:'original',...options});
|
||||
assert.deepEqual(transforms,[{slotId:'slot',sourceCandidateId:'original',referenceIndex:undefined,transform:options}]);
|
||||
assert.deepEqual(fixed,{phase:'complete',status:'complete',id:'fixed',candidateId:'fixed',sourceCandidateId:'original',
|
||||
materialTaskId:'original-task',sourceRequestId:'source-request',...metrics});
|
||||
|
||||
await actions.delegate_image_slots({jobs:[{slotId:'P05',goal:'调整构图'}]});
|
||||
const {generation}=await actions.await_image_slots({slotIds:['P05']});
|
||||
assert.ok(generation.some(row=>row.candidateId==='fixed'&&row.resolutionSufficient===false));
|
||||
|
||||
let dispatched=false;
|
||||
imageBridge(host,async(_args,requestId)=>{
|
||||
dispatched=true;
|
||||
return {requestId,status:'complete',phase:'complete',id:requestId,candidateId:requestId};
|
||||
});
|
||||
await actions.check_image_slots({wait:true,candidates:[{slotId:'P05',candidateId:'original'}]});
|
||||
const request=await actions.prepare_image_request({slotId:'P05',prompt:'尝试重生成'});
|
||||
await actions.dispatch_image_request(approve(request));
|
||||
await actions.await_image_slots({slotIds:['P05']});
|
||||
assert.equal(dispatched,true);
|
||||
assert.deepEqual(reviewed,['original','other','original']);
|
||||
assert.equal(transforms.length,2);
|
||||
assert.deepEqual(placements,[]);
|
||||
await actions.close();
|
||||
});
|
||||
|
||||
test('closeup preparation forwards only the requested reference and resolution options',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-closeup-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'detail',productVariantId:'oak',
|
||||
template:{contentHash:'studio'},totalSlots:1,slots:[{id:'slot',fieldId:'P06',productionRule:{focus:'卷边接缝特写'}}]}),
|
||||
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
|
||||
async imageRequest(action,args){
|
||||
assert.equal(action,'prepare');
|
||||
forwarded.push(args);
|
||||
return {requestId:randomUUID(),revision:1,requestSpecHash:'mock',outputId:'detail',variantId:'oak',slotId:'slot',
|
||||
spec:{prompt:args.instructions}};
|
||||
},
|
||||
}};
|
||||
const forwarded=[];
|
||||
const actions=await openProductionOperations(host);
|
||||
const args={slotId:'P06',prompt:'侧光下看缝线间距',referenceIndexes:[0,2]};
|
||||
for(const options of [{},{useTemplateReference:true,useSceneComposite:true,prefer2k:false},
|
||||
{useTemplateReference:false,useSceneComposite:false,prefer2k:true}]){
|
||||
await actions.prepare_image_request({...args,...options});
|
||||
const {useTemplateReference,useSceneComposite,prefer2k,referenceIndexes}=forwarded.at(-1);
|
||||
assert.deepEqual({useTemplateReference,useSceneComposite,prefer2k,referenceIndexes},
|
||||
{useTemplateReference:undefined,useSceneComposite:undefined,prefer2k:undefined,referenceIndexes:[0,2],...options});
|
||||
}
|
||||
await actions.close();
|
||||
});
|
||||
async function generateAndWait(actions, {source,...request}) {
|
||||
let receipt;
|
||||
try {
|
||||
|
||||
@ -4,6 +4,9 @@ use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present,
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
use super::transfer;
|
||||
|
||||
#[path = "jiansun_image_transform.rs"]
|
||||
mod jiansun_image_transform;
|
||||
|
||||
const FILE: &str = "canvas-workspace.json";
|
||||
const CANDIDATE: &str = "canvas-candidate.json";
|
||||
const MAPPING: &str = "jiansun.slot-mapping.v1";
|
||||
@ -881,7 +884,12 @@ fn reserve(dir: &Path, mut state: Value, record: &Value) -> R<()> {
|
||||
candidates.push(record["id"].clone());
|
||||
// A crash between these writes is default-deny: records() detects orphans.
|
||||
write_json(&file, &record)?;
|
||||
persist_locked(dir, &mut state, expected)?;
|
||||
if let Err(error) = persist_locked(dir, &mut state, expected) {
|
||||
if record["canvasTransform"].is_object() {
|
||||
let _ = fs::remove_file(&file);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -1073,6 +1081,12 @@ fn candidate_receipt(record: &Value) -> Value {
|
||||
receipt["reusedFrom"] = record["reusedFrom"].clone();
|
||||
receipt["sourceRequestId"] = record["sourceRequestId"].clone();
|
||||
}
|
||||
if let Some(transform) = record["canvasTransform"].as_object() {
|
||||
receipt["canvasTransform"] = record["canvasTransform"].clone();
|
||||
for (key, value) in transform {
|
||||
receipt[key] = value.clone();
|
||||
}
|
||||
}
|
||||
receipt
|
||||
}
|
||||
// Every alias has its own renderable pixels. Keep a canonical source archive
|
||||
@ -3255,14 +3269,15 @@ impl Backend {
|
||||
let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?;
|
||||
let request = &binding["request"];
|
||||
transfer::no_credentials(request)?;
|
||||
if phase == "prepare" {
|
||||
if matches!(phase, "prepare" | "transform") {
|
||||
let mut input = request.clone();
|
||||
input["doc"] = json!(doc);
|
||||
input["baseRevision"] = binding["revision"].clone();
|
||||
input["variantId"] = binding["scope"]["variantId"].clone();
|
||||
input["detailBatch"] = json!(true);
|
||||
input["detailWorkspace"] = binding["scope"].clone();
|
||||
return self.canvas_workspace_action("slot-prepare-image", &input, events, ctx).map_err(BridgeFailure::from);
|
||||
let action = if phase == "transform" { "slot-transform-image" } else { "slot-prepare-image" };
|
||||
return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from);
|
||||
}
|
||||
if phase != "dispatch" { return Err("生图请求动作无效".into()); }
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx, cancellation)?;
|
||||
@ -3451,7 +3466,7 @@ impl Backend {
|
||||
next["structureHash"] = json!(hash(&json!([next["template"]["contentHash"], next["width"]]).to_string()));
|
||||
persist(&dir, next, expected)?;
|
||||
}
|
||||
let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep");
|
||||
let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep" | "slot-transform-image");
|
||||
let mut state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? };
|
||||
if batch && input["detailWorkspace"] != json!({"id":state["id"],"templateHash":state["template"]["contentHash"],
|
||||
"structureHash":state["structureHash"],"outputId":state["activeOutput"],"variantId":state["activeVariantId"]})
|
||||
@ -3642,6 +3657,18 @@ impl Backend {
|
||||
}
|
||||
events.send(Event::SlotCanvas(Box::new(native), result)).map_err(|_| "工作台已关闭,模板骨架记录保留")?;
|
||||
if let Some(receipt) = view_receipt { return Ok(receipt); }
|
||||
} else if method == "slot-transform-image" {
|
||||
let record = jiansun_image_transform::stage_candidate(&dir, state, input)?;
|
||||
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) {
|
||||
reference["purpose"] = json!("template-candidate");
|
||||
let _ = events.send(Event::Preview(reference, preview));
|
||||
}
|
||||
let receipt = candidate_receipt(&record);
|
||||
if let Ok(snapshot) = self.canvas_workspace_result(doc, &dir) {
|
||||
let _ = events.send(Event::Json("slot-append".into(), Ok(operation_receipt(snapshot, Some(receipt.clone()), None))));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return Ok(receipt);
|
||||
} else if matches!(method, "slot-prepare-image" | "slot-append") {
|
||||
let variant_id = uuid(&input["variantId"], "花色")?;
|
||||
let id = input["slotId"].as_str().ok_or("请选择图片目标")?.to_owned();
|
||||
@ -3817,7 +3844,7 @@ impl Backend {
|
||||
let candidate = uuid(input.get("candidateId").filter(|value| !value.is_null()).unwrap_or(&input["taskId"]), "原候选")?;
|
||||
let record = read_candidate(&dir, &candidate)?;
|
||||
checked_binding(&dir, &record["binding"], true)?;
|
||||
if record["sourceType"] == "product-reference" {
|
||||
if record["sourceType"] == "product-reference" || record["canvasTransform"].is_object() {
|
||||
return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None));
|
||||
}
|
||||
let Some(_dispatch) = lock_candidate_dispatch(&dir, &candidate)? else {
|
||||
@ -5016,6 +5043,75 @@ mod tests {
|
||||
json!({"version":2,"id":id,"sequence":state["candidates"].as_array().unwrap().len()+1,"binding":{"schemaVersion":2,"canvasFirst":true,"workspaceId":state["id"],"templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"slotId":slot,"variantId":variant,"fieldId":"S01-I01","outputId":"S01","taskId":id,"candidateId":id},"phase":phase,"modelId":"image-model","inputHash":input_hash(dir,&state,variant).unwrap(),"requestId":null,"prompt":"本地fixture不调用模型","instructions":"测试提示"})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_stages_cross_slot_pixels_and_keeps_generated_and_product_lineage() {
|
||||
let project = fixture();
|
||||
let mut backend = Backend::new(project.dir.join("profile")).unwrap();
|
||||
let doc = 1;
|
||||
backend.bind_new(doc);
|
||||
let owned = backend.project_dir(doc).unwrap();
|
||||
let dir = &owned;
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
for file in ["context.json", "creation.json", FILE] {
|
||||
fs::copy(project.dir.join(file), dir.join(file)).unwrap();
|
||||
}
|
||||
let mut state = load(dir).unwrap();
|
||||
let slots = state["template"]["outputs"][0]["slots"].as_array_mut().unwrap();
|
||||
let mut target = slots[0].clone();
|
||||
target["fieldId"] = json!("S01-I02");
|
||||
slots.push(target);
|
||||
state["template"]["contentHash"] = json!(template_slots::pack_hash(&state["template"]).unwrap());
|
||||
let image = photocraft_codecs::Image::from_u8(1800, 800, photocraft_codecs::ChannelLayout::Rgb, vec![110;1800*800*3]).unwrap();
|
||||
let pixels = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
|
||||
let digest = format!("{:x}", Sha256::digest(&pixels));
|
||||
let images = json!([{"name":"实拍","source":format!("local:{digest}"),"purpose":"product"}]);
|
||||
fs::create_dir_all(dir.join("creation-assets")).unwrap();
|
||||
fs::write(dir.join("creation-assets").join(format!("{digest}.png")), &pixels).unwrap();
|
||||
let mut creation = creation::load(dir).unwrap();
|
||||
creation["brief"]["images"] = images.clone();
|
||||
write_json(&dir.join("creation.json"), &creation).unwrap();
|
||||
state["brief"] = creation::load(dir).unwrap()["brief"].clone();
|
||||
let state = persist(dir, state, 1).unwrap();
|
||||
let variant = state["activeVariantId"].as_str().unwrap().to_owned();
|
||||
let slot = slot_id(&state["template"]["contentHash"], &variant, "S01-I02");
|
||||
let scope = json!({"id":state["id"],"templateHash":state["template"]["contentHash"],
|
||||
"structureHash":state["structureHash"],"outputId":"detail","variantId":variant});
|
||||
let mut source = candidate(dir, "complete");
|
||||
source["requestId"] = json!("upstream-task");
|
||||
let source_id = source["id"].as_str().unwrap().to_owned();
|
||||
let source_job = dir.join("image-jobs").join(&source_id);
|
||||
let task = json!({"id":source_id,"phase":"complete","sha256":digest,"slotBinding":source["binding"]});
|
||||
write_json(&source_job.join("task.json"), &task).unwrap();
|
||||
fs::write(source_job.join("generated.png"), &pixels).unwrap();
|
||||
source["artifact"] = template_slots::artifact(dir, &source_id, &task).unwrap();
|
||||
reserve(dir, state, &source).unwrap();
|
||||
|
||||
let mut action = json!({"action":"transform","scope":scope,"revision":1,
|
||||
"request":{"slotId":slot,"sourceCandidateId":source_id,"transform":{"crop":[250,200,750,800]}}});
|
||||
let (events, _receiver) = mpsc::channel();
|
||||
let ctx = egui::Context::default();
|
||||
let derived = backend.production_image_request(doc, &action, &events, &ctx).unwrap();
|
||||
let id = derived["id"].as_str().unwrap();
|
||||
let durable = read_candidate(dir, id).unwrap();
|
||||
assert_ne!(durable["id"], source["id"]);
|
||||
assert_eq!(durable["binding"]["slotId"], slot);
|
||||
assert_eq!(durable["canvasTransform"]["sourceCandidateId"], source["id"]);
|
||||
assert_eq!(material_task_id(&durable), &source["id"]);
|
||||
assert_eq!(durable["sourceRequestId"], "upstream-task");
|
||||
assert_eq!(candidate_receipt(&durable)["cropSourcePixels"], json!([900,480]));
|
||||
assert_eq!(candidate_receipt(&durable)["resolutionSufficient"], true);
|
||||
assert_eq!(photocraft_codecs::decode(&candidate_pixels(dir, &durable["artifact"]).unwrap()).unwrap().dimensions(), (750,300));
|
||||
|
||||
action["request"]["sourceCandidateId"] = Value::Null;
|
||||
action["request"]["referenceIndex"] = json!(0);
|
||||
let photo = backend.production_image_request(doc, &action, &events, &ctx).unwrap();
|
||||
let photo = read_candidate(dir, photo["id"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(photo["references"], images);
|
||||
assert_eq!(photo["sourceType"], "product-reference");
|
||||
assert_eq!(candidate_receipt(&photo)["referenceIndex"], 0);
|
||||
assert!(photo["requestId"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_candidates_excludes_requests_without_completed_images() {
|
||||
let project = fixture();
|
||||
|
||||
@ -0,0 +1,331 @@
|
||||
//! Pixel edits for a single candidate. Coordinates are relative to the source
|
||||
//! before editing, and offsets are pixels in the destination frame.
|
||||
use super::{
|
||||
Digest, Path, R, Sha256, Uuid, Value, candidate_available, candidate_pixels, candidate_uses_current_inputs, crop_product_image, definition,
|
||||
generation_references, hash, input_hash, json, local_product_photo, mapped_slot, material_task_id, new_binding, now, output_uses_variant,
|
||||
product_slot_binding, read_candidate, reserve, slot_frame, template_slots, uuid, write_json,
|
||||
};
|
||||
use image::{Rgba, Rgba32FImage, imageops};
|
||||
use photocraft_codecs::{ChannelLayout, Image, SampleType};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R<Value> {
|
||||
let slot = input["slotId"].as_str().ok_or("缺少目标图位")?;
|
||||
let variant = uuid(&input["variantId"], "花色")?;
|
||||
let (output, field) = definition(&state, slot, &variant)?;
|
||||
if !output_uses_variant(&state["brief"], output["component"].as_str().unwrap_or("detail"), &variant) {
|
||||
return Err("当前花色未选入此输出".into());
|
||||
}
|
||||
let frame = slot_frame(field, mapped_slot(&state, slot, &variant)).ok_or("找不到实际图框")?;
|
||||
let extent = |key| frame[key].as_f64().filter(|n| (1.0..=8192.0).contains(n)).map(|n| n.round() as u32).ok_or("图框尺寸无效");
|
||||
let target = [extent("width")?, extent("height")?];
|
||||
let transform: Transform = serde_json::from_value(input["transform"].clone()).map_err(|_| "画布变换参数无效")?;
|
||||
let (bytes, source, reference_index, references, density) = match (input["sourceCandidateId"].as_str(), input["referenceIndex"].as_u64()) {
|
||||
(Some(candidate), None) if input["referenceIndex"].is_null() => {
|
||||
let id = uuid(&json!(candidate), "来源候选")?;
|
||||
if !state["candidates"].as_array().is_some_and(|rows| rows.contains(&json!(id))) {
|
||||
return Err("来源候选不属于本项目".into());
|
||||
}
|
||||
let record = read_candidate(dir, &id)?;
|
||||
let original_binding = &record["binding"];
|
||||
if !candidate_available(&record) || original_binding["variantId"] != variant {
|
||||
return Err("来源候选未完成或不属于当前商品花色".into());
|
||||
}
|
||||
let mut source_state = std::borrow::Cow::Borrowed(&state);
|
||||
if original_binding["templateHash"] != state["template"]["contentHash"] {
|
||||
let structure = hash(&json!([original_binding["templateHash"], state["width"]]).to_string());
|
||||
if !product_slot_binding(&state, original_binding) || original_binding["structureHash"] != structure {
|
||||
return Err("来源候选所用模板或画布宽度已变化".into());
|
||||
}
|
||||
let saved = source_state.to_mut();
|
||||
saved["template"]["contentHash"] = original_binding["templateHash"].clone();
|
||||
saved["structureHash"] = json!(structure);
|
||||
}
|
||||
if !candidate_uses_current_inputs(dir, &source_state, &record, &variant)? {
|
||||
return Err("来源候选的商品资料已变化".into());
|
||||
}
|
||||
let density = record["canvasTransform"]["resolutionRatio"].as_f64().unwrap_or(1.0).min(1.0);
|
||||
let bytes = candidate_pixels(dir, &record["artifact"])?;
|
||||
let index = record["canvasTransform"]["referenceIndex"].clone();
|
||||
let references = record["references"].clone();
|
||||
(bytes, Some(record), index, references, density)
|
||||
}
|
||||
(None, Some(index)) if index < 8 && input["sourceCandidateId"].is_null() => {
|
||||
let products = generation_references(dir, &state, &variant)?;
|
||||
let photo =
|
||||
products.as_array().into_iter().flatten().filter(|image| image["purpose"] == "product").nth(index as usize).ok_or("当前花色没有该同款原图")?;
|
||||
(local_product_photo(dir, photo)?, None, json!(index), json!([photo]), 1.0)
|
||||
}
|
||||
_ => return Err("须指定一个候选号或本款原片编号".into()),
|
||||
};
|
||||
let decoded = photocraft_codecs::decode_with(
|
||||
&bytes,
|
||||
&photocraft_codecs::DecodeOptions {
|
||||
limits: photocraft_codecs::Limits { max_width: 8192, max_height: 8192, max_pixels: 24_000_000, max_alloc: 192 * 1024 * 1024 },
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|_| "来源图片无法解码")?;
|
||||
let (edited, quality) = transform.render(&decoded, target, density)?;
|
||||
let edited = photocraft_codecs::encode(&edited, photocraft_codecs::Format::Png, &Default::default()).map_err(|_| "画布变换结果无法编码")?;
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let prompt = source.as_ref().and_then(|record| record["prompt"].as_str()).unwrap_or("本款实拍");
|
||||
let mut binding = new_binding(&state, output, field, slot, &variant, &id, prompt);
|
||||
if input["detailBatch"] == true {
|
||||
binding["detailBatch"] = json!(true);
|
||||
}
|
||||
let product_source = source.as_ref().is_none_or(|record| record["sourceType"] == "product-reference");
|
||||
let source_type = if product_source { "product-reference" } else { "archived-candidate" };
|
||||
let mut edit = json!({
|
||||
"sourceCandidateId":source.as_ref().map(|record| &record["id"]),
|
||||
"referenceIndex":reference_index,
|
||||
"transform":transform,
|
||||
});
|
||||
let metrics = serde_json::to_value(quality).map_err(|error| error.to_string())?;
|
||||
if let Some(fields) = metrics.as_object() {
|
||||
for (key, value) in fields {
|
||||
edit[key] = value.clone();
|
||||
}
|
||||
}
|
||||
let original_task = source.as_ref().map(material_task_id);
|
||||
let original_request = source.as_ref().and_then(|record| record["sourceRequestId"].as_str().or_else(|| record["requestId"].as_str()));
|
||||
let ancestry = source.as_ref().map(|record| json!({"projectId":state["id"],"candidateId":record["id"]}));
|
||||
let journal = json!({"version":1,"id":id,"phase":"complete","slotBinding":binding,
|
||||
"requestId":null,"sourceType":source_type,"canvasTransform":edit,
|
||||
"materialTaskId":original_task,"sourceRequestId":original_request,
|
||||
"sha256":format!("{:x}", Sha256::digest(&edited))});
|
||||
let job = dir.join("image-jobs").join(&id);
|
||||
let product_hash = input_hash(dir, &state, &variant)?;
|
||||
write_json(&job.join("task.json"), &journal)?;
|
||||
photocraft_format::atomic_write(&job.join("generated.png"), &edited).map_err(|_| "画布变换结果无法保存")?;
|
||||
let artifact = template_slots::artifact(dir, &id, &journal)?;
|
||||
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete","sourceType":source_type,
|
||||
"modelId":null,"inputHash":product_hash,"prompt":prompt,"instructions":"画布像素变换",
|
||||
"references":references,"requestId":null,"artifact":artifact,"createdAt":now(),
|
||||
"parentCandidateId":edit["sourceCandidateId"],"canvasTransform":edit,
|
||||
"materialTaskId":original_task,"sourceRequestId":original_request,"reusedFrom":ancestry});
|
||||
reserve(dir, state, &record)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub(super) struct Transform {
|
||||
pub crop: [u32; 4],
|
||||
flip_x: bool,
|
||||
flip_y: bool,
|
||||
rotate_deg: f64,
|
||||
scale: f64,
|
||||
offset_x: f64,
|
||||
offset_y: f64,
|
||||
fit: Fit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Fit {
|
||||
Cover,
|
||||
Contain,
|
||||
}
|
||||
|
||||
impl Default for Transform {
|
||||
fn default() -> Self {
|
||||
Self { crop: [0, 0, 1000, 1000], flip_x: false, flip_y: false, rotate_deg: 0.0, scale: 1.0, offset_x: 0.0, offset_y: 0.0, fit: Fit::Cover }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct Resolution {
|
||||
crop_source_pixels: [u32; 2],
|
||||
target_frame: [u32; 2],
|
||||
pub resolution_ratio: f64,
|
||||
resolution_sufficient: bool,
|
||||
}
|
||||
|
||||
impl Transform {
|
||||
pub(super) fn render(&self, source: &Image, [width, height]: [u32; 2], source_density: f64) -> Result<(Image, Resolution), String> {
|
||||
let [left, top, right, bottom] = self.crop;
|
||||
if left >= right || top >= bottom || right > 1000 || bottom > 1000 {
|
||||
return Err("裁切区域须为 0 到 1000 的有效矩形".into());
|
||||
}
|
||||
if !self.rotate_deg.is_finite() || !self.scale.is_finite() || self.scale <= 0.0 || !self.offset_x.is_finite() || !self.offset_y.is_finite() {
|
||||
return Err("画布变换参数无效".into());
|
||||
}
|
||||
if width == 0 || height == 0 || u64::from(width) * u64::from(height) > photocraft_io::SMART_PREVIEW_MAX_PIXELS {
|
||||
return Err("目标图框尺寸超出候选图片处理范围".into());
|
||||
}
|
||||
let bound = |edge: u32, size: u32| u64::from(edge) * u64::from(size);
|
||||
let x = (bound(left, source.width()) / 1000) as u32;
|
||||
let y = (bound(top, source.height()) / 1000) as u32;
|
||||
let cw = (bound(right, source.width()).div_ceil(1000) as u32) - x;
|
||||
let ch = (bound(bottom, source.height()).div_ceil(1000) as u32) - y;
|
||||
let (sin, cos) = match self.rotate_deg.rem_euclid(360.0) {
|
||||
0.0 => (0.0, 1.0),
|
||||
90.0 => (1.0, 0.0),
|
||||
180.0 => (0.0, -1.0),
|
||||
270.0 => (-1.0, 0.0),
|
||||
angle => angle.to_radians().sin_cos(),
|
||||
};
|
||||
let (w, h) = (f64::from(cw), f64::from(ch));
|
||||
let (tw, th) = (f64::from(width), f64::from(height));
|
||||
// Cover uses the inverse-rotated target extents so a small correction
|
||||
// does not open transparent corners at the default zoom.
|
||||
let (s, c) = (sin.abs(), cos.abs());
|
||||
let fit_scale = match self.fit {
|
||||
Fit::Cover => ((tw * c + th * s) / w).max((tw * s + th * c) / h),
|
||||
Fit::Contain => (tw / (w * c + h * s)).min(th / (w * s + h * c)),
|
||||
};
|
||||
let zoom = fit_scale * self.scale;
|
||||
if !zoom.is_finite() || zoom <= 0.0 || !zoom.recip().is_finite() {
|
||||
return Err("缩放超出有效范围".into());
|
||||
}
|
||||
let resolution_ratio = (source_density / zoom).min(f64::MAX);
|
||||
let quality =
|
||||
Resolution { crop_source_pixels: [cw, ch], target_frame: [width, height], resolution_ratio, resolution_sufficient: resolution_ratio >= 1.0 - 1e-9 };
|
||||
let samples = if x == 0 && y == 0 && (cw, ch) == source.dimensions() {
|
||||
source.to_rgba_f32()
|
||||
} else {
|
||||
crop_product_image(source, [x, y, x + cw, y + ch])?.to_rgba_f32()
|
||||
};
|
||||
let mut crop = Rgba32FImage::from_raw(cw, ch, samples).ok_or("裁切区域像素不完整")?;
|
||||
if self.flip_x {
|
||||
imageops::flip_horizontal_in_place(&mut crop);
|
||||
}
|
||||
if self.flip_y {
|
||||
imageops::flip_vertical_in_place(&mut crop);
|
||||
}
|
||||
|
||||
// Prefilter minification. Fractional translations and angle corrections
|
||||
// use bicubic sampling. Grid-aligned pixels take the exact copy path.
|
||||
let alpha_weighted = zoom < 1.0;
|
||||
if alpha_weighted {
|
||||
for pixel in crop.pixels_mut() {
|
||||
let alpha = pixel.0[3];
|
||||
for value in &mut pixel.0[..3] {
|
||||
*value *= alpha;
|
||||
}
|
||||
}
|
||||
crop = imageops::resize(&crop, (w * zoom).round().max(1.0) as u32, (h * zoom).round().max(1.0) as u32, imageops::FilterType::Lanczos3);
|
||||
}
|
||||
let (rw, rh) = (f64::from(crop.width()), f64::from(crop.height()));
|
||||
let mut result = Rgba32FImage::from_fn(width, height, |col, row| {
|
||||
let dx = f64::from(col) + 0.5 - tw / 2.0 - self.offset_x;
|
||||
let dy = f64::from(row) + 0.5 - th / 2.0 - self.offset_y;
|
||||
let sx = (dx * cos + dy * sin) / zoom * (rw / w) + rw / 2.0 - 0.5;
|
||||
let sy = (-dx * sin + dy * cos) / zoom * (rh / h) + rh / 2.0 - 0.5;
|
||||
sample(&crop, sx, sy, alpha_weighted)
|
||||
});
|
||||
if alpha_weighted {
|
||||
for pixel in result.pixels_mut() {
|
||||
unpremultiply(&mut pixel.0);
|
||||
}
|
||||
}
|
||||
let depth = if source.sample_type() == SampleType::U8 { SampleType::U8 } else { SampleType::U16 };
|
||||
let mut edited = Image::from_normalized(width, height, ChannelLayout::Rgba, depth, result.as_raw()).map_err(|error| error.to_string())?;
|
||||
if matches!(source.layout(), ChannelLayout::Rgb | ChannelLayout::Rgba) {
|
||||
edited.icc.clone_from(&source.icc);
|
||||
edited.cicp = source.cicp;
|
||||
}
|
||||
Ok((edited, quality))
|
||||
}
|
||||
}
|
||||
|
||||
fn cubic(distance: f64) -> f32 {
|
||||
let x = distance.abs();
|
||||
(if x < 1.0 {
|
||||
(1.5 * x - 2.5) * x * x + 1.0
|
||||
} else if x < 2.0 {
|
||||
((-0.5 * x + 2.5) * x - 4.0) * x + 2.0
|
||||
} else {
|
||||
0.0
|
||||
}) as f32
|
||||
}
|
||||
|
||||
fn unpremultiply(pixel: &mut [f32; 4]) {
|
||||
let alpha = pixel[3];
|
||||
if alpha > 0.0 {
|
||||
for value in &mut pixel[..3] {
|
||||
*value = (*value / alpha).clamp(0.0, 1.0);
|
||||
}
|
||||
} else {
|
||||
*pixel = [0.0; 4];
|
||||
}
|
||||
}
|
||||
|
||||
fn sample(image: &Rgba32FImage, x: f64, y: f64, alpha_weighted: bool) -> Rgba<f32> {
|
||||
if !(x >= -0.5 && x < f64::from(image.width()) - 0.5 && y >= -0.5 && y < f64::from(image.height()) - 0.5) {
|
||||
return Rgba([0.0; 4]);
|
||||
}
|
||||
if (x - x.round()).abs() < 1e-9 && (y - y.round()).abs() < 1e-9 {
|
||||
return *image.get_pixel(x.round() as u32, y.round() as u32);
|
||||
}
|
||||
let mut output = [0.0; 4];
|
||||
for iy in y.floor() as i64 - 1..=y.floor() as i64 + 2 {
|
||||
for ix in x.floor() as i64 - 1..=x.floor() as i64 + 2 {
|
||||
let pixel = &image.get_pixel(ix.clamp(0, i64::from(image.width()) - 1) as u32, iy.clamp(0, i64::from(image.height()) - 1) as u32).0;
|
||||
let weight = cubic(x - ix as f64) * cubic(y - iy as f64);
|
||||
let rgb_weight = if alpha_weighted { weight } else { weight * pixel[3] };
|
||||
for channel in 0..3 {
|
||||
output[channel] += pixel[channel] * rgb_weight;
|
||||
}
|
||||
output[3] += pixel[3] * weight;
|
||||
}
|
||||
}
|
||||
if !alpha_weighted {
|
||||
unpremultiply(&mut output);
|
||||
}
|
||||
Rgba(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn crop_flips_and_quarter_turns_copy_exact_pixels() {
|
||||
let source = Image::from_u8(3, 2, ChannelLayout::Gray, vec![10, 20, 30, 40, 50, 60]).unwrap();
|
||||
for (params, frame, expected) in [
|
||||
(json!({"crop":[334,0,1000,1000]}), [2, 2], vec![20, 30, 50, 60]),
|
||||
(json!({"flipX":true}), [3, 2], vec![30, 20, 10, 60, 50, 40]),
|
||||
(json!({"flipY":true}), [3, 2], vec![40, 50, 60, 10, 20, 30]),
|
||||
(json!({"rotateDeg":90}), [2, 3], vec![40, 10, 50, 20, 60, 30]),
|
||||
(json!({"rotateDeg":180}), [3, 2], vec![60, 50, 40, 30, 20, 10]),
|
||||
(json!({"rotateDeg":270}), [2, 3], vec![30, 60, 20, 50, 10, 40]),
|
||||
(json!({"offsetX":1,"offsetY":1}), [3, 2], vec![0, 0, 0, 0, 10, 20]),
|
||||
(json!({"fit":"contain"}), [5, 2], vec![0, 10, 20, 30, 0, 0, 40, 50, 60, 0]),
|
||||
] {
|
||||
let transform: Transform = serde_json::from_value(params).unwrap();
|
||||
let (result, quality) = transform.render(&source, frame, 1.0).unwrap();
|
||||
assert_eq!(result.data().chunks_exact(4).map(|pixel| pixel[0]).collect::<Vec<_>>(), expected);
|
||||
assert!(quality.resolution_sufficient);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaling_interpolates_and_a_small_rotation_preserves_cover() {
|
||||
let source = Image::from_u16(5, 5, ChannelLayout::Gray, &(0..25).map(|index| index * 2000).collect::<Vec<_>>()).unwrap();
|
||||
let transform: Transform = serde_json::from_value(json!({"scale":2,"rotateDeg":4})).unwrap();
|
||||
let (result, quality) = transform.render(&source, [5, 5], 1.0).unwrap();
|
||||
let rgba = result.to_rgba16();
|
||||
assert_eq!(result.sample_type(), SampleType::U16);
|
||||
assert_eq!(rgba[12 * 4], 24000);
|
||||
assert!(rgba.chunks_exact(4).all(|pixel| pixel[3] == u16::MAX));
|
||||
assert!(rgba[0] > 0 && rgba[0] < 24000);
|
||||
assert!(!quality.resolution_sufficient);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closeup_resolution_uses_real_crop_pixels_and_zoom() {
|
||||
let transform: Transform = serde_json::from_value(json!({"crop":[250,250,750,750]})).unwrap();
|
||||
for (side, sufficient) in [(2048, true), (640, false)] {
|
||||
let source = Image::from_u8(side, side, ChannelLayout::Rgb, vec![120; side as usize * side as usize * 3]).unwrap();
|
||||
let (result, quality) = transform.render(&source, [750, 750], 1.0).unwrap();
|
||||
assert_eq!(result.dimensions(), (750, 750));
|
||||
assert_eq!(quality.crop_source_pixels, [side / 2, side / 2]);
|
||||
assert_eq!(quality.resolution_sufficient, sufficient);
|
||||
assert!((quality.resolution_ratio - f64::from(side) / 1500.0).abs() < 1e-9);
|
||||
assert_eq!(&result.data()[..4], &[120, 120, 120, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -62,7 +62,7 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result<Value, String> {
|
||||
"open_production_output" => "打开制作画布",
|
||||
"plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则",
|
||||
"read_copy_fields" => "读取画布文字格", "read_slot_images" => "查看图位图片",
|
||||
"use_product_image" => "取用商品实拍", "prepare_image_request" => "准备生图请求",
|
||||
"use_product_image" => "取用商品实拍", "transform_slot_image" => "调整候选图片", "prepare_image_request" => "准备生图请求",
|
||||
"dispatch_image_request" => "生成候选图片", "delegate_image_slots" => "分派图片图位",
|
||||
"await_image_slots" => "等待子代理回执", "review_image_slots" => "查看图位结果",
|
||||
"adopt_production_image" => "回填候选图片", "retire_production_image" => "清理已退回的候选图",
|
||||
@ -536,7 +536,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer}))
|
||||
}
|
||||
"pi-image-request" => {
|
||||
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"))
|
||||
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"))
|
||||
.ok_or("生图请求动作无效")?;
|
||||
if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app)
|
||||
|| w.pi_request_scope["outputId"] != w.template_workflow["outputId"]
|
||||
@ -550,6 +550,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let allowed: &[&str] = match action {
|
||||
"prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange",
|
||||
"referenceIndexes","useTemplateReference","useSceneComposite"],
|
||||
"transform" => &["slotId","sourceCandidateId","referenceIndex","transform"],
|
||||
_ => &["requestId","expectedRevision","expectedHash","slotId"],
|
||||
};
|
||||
if request.as_object().is_none_or(|fields| fields.keys().any(|key| !allowed.contains(&key.as_str()))) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user