diff --git a/apps/detail-agent-pi/README.md b/apps/detail-agent-pi/README.md index f579f5cd..9bd568c8 100644 --- a/apps/detail-agent-pi/README.md +++ b/apps/detail-agent-pi/README.md @@ -91,7 +91,7 @@ Windows 本地包完成后会清理同一输出目录内较旧的本地运行包 } ``` -- `referenceMode` 可填 `composition-only`(只参考构图)或 `none`(不参考)。只参考构图时,策划可读对应模板原图并将构图关系写成提示词。验图可参考该文字。 +- `referenceMode` 可填 `template-base`(固定模板原图作底图,随后附本款实拍)、`composition-only`(只参考构图)或 `none`(不参考)。只参考构图时,策划可读对应模板原图并将构图关系写成提示词。验图可参考该文字。 - `mainImageAspects` 用图位登记的标准比例,例如 `["1:1", "3:4"]`。模板可选画幅见 `plan_production.availableMainImageAspects`。 - 主代理可用 `set_production_settings` 记录按企业 Skill 确定的选择。项目记录覆盖组件配置,并在本款各输出及续作中复用。缺少声明时,由主代理选择,主图计划在选择后列出相应图位。 - 生图回执 `attachmentSources` 按发送顺序列出来源及用途。 diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index 06ab4d1e..603404e7 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -5,6 +5,8 @@ import { mergeReviewCopy } from './copy-image-alignment.mjs'; import { validateWorkerArguments } from './worker-receipts.mjs'; import { screenAssessment, screenFindings, numberScreenCopy, numberScreenSlots, resolveReviewField, TEMPLATE_REVIEW_GUIDANCE } from './screen-review.mjs'; +const TEMPLATE_REVIEW = '模板底图候选须对照固定原图核对商品以外的画面,并按实拍核对颜色、结构、比例、部件和旧商品残留。裁出的特写须对照模板核对部位、角度与占比,按实拍核对细节。'; + const params = properties => Type.Object(properties,{additionalProperties:false}); const tool = (name, description, parameters, execute) => ({ name,label:description,description,parameters,execute:(_id,args)=>execute(args), @@ -67,7 +69,7 @@ export async function reviewProductionCandidate({ [key,Type.Optional(Type.Union([Type.Boolean(),Type.Null()],{description}))])); const {imageIssues,overlayFixes,copyFixes,summary}=screenAssessment.properties; const requirementsText='顶层填写候选 verdict(pass、revise 或 missing)和非空 reason。checks 可省略,按实际证据填写。整屏问题在顶层填写 imageIssues、overlayFixes 或 copyFixes。整屏通过时填 screenVerdict: pass,发现问题时可从问题列表推导 needs_fix。整屏模板风格填顶层 templateStyle;候选图的模板风格填在 checks 对象内的 templateStyle 字段。'; - const example='最小提交示例 '+JSON.stringify({verdict:'revise',reason:'实拍扶手为弧形,候选误画成直角。'}); + const example='最小提交示例 '+JSON.stringify({verdict:'revise',reason:'候选商品与实拍的部件形状不一致。'}); const assessment=params({ candidateId:Type.Optional(Type.String({description:'省略时使用本次受审候选。'})),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))), shownSubject:Type.Optional(Type.String({description:'画面实际突出呈现的部位、景别或场景。'})), @@ -188,7 +190,8 @@ export async function reviewProductionCandidate({ overlayLayers:screen.details.overlayLayers,templateFidelity:screen.details.templateFidelity, fieldRequirements:screen.details.fieldRequirements}}); const instructions=[ - '第一张是本次候选原图,用于对照实拍检查商品结构、颜色和材质。第二张是候选按采纳方式放入后的整屏画面。后续如有模板原屏会明确标注,再后面为同款实拍。可从本次生图提示词读取适用的构图依据。', + '第一张是本次候选原图,用于对照实拍检查商品结构、颜色和材质。第二张是候选按采纳方式放入后的整屏画面。后续图位原图、模板原屏和本款实拍按图注识别。可从本次生图提示词读取适用的构图依据。', + TEMPLATE_REVIEW, TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), '对照模板判断候选图的风格,填在 checks 对象内的 templateStyle 字段,缺少模板依据时填 null。', requirementsText, @@ -207,8 +210,10 @@ export async function reviewProductionCandidate({ '按 checks 逐项记录结论,比较同款实拍和模板参考。允许 null 的检查在不适用或缺乏证据时填 null,并在 reason 说明。检查 generationEvidence 中的实发模型、参数和像素。根据本款 product 资料和已发布的企业 Skill 判定禁止标识,查看主体和配饰上的铭牌、文字及 logo。未读到模板原图时记录依据缺失。暗中遮住标题,描述仍能看出的用途。任何实际问题要记录位置和依据。', '调用 review_candidate 提交结论。', ].join('\n'); - const images=[input.images.at(-1),screen.image,...(screen.templateImage?[screen.templateImage]:[]),...originalImages]; - const captions=['受审候选原图','候选放入后的整屏合成',...(screen.templateImage?['模板原屏']:[]),...originalImages.map((_image,index)=> + const slotTemplate=input.layoutSource==='pinnedTemplateOriginal' + ?input.images.slice(referenceCount,referenceCount+(input.layoutCount??0)):[]; + const images=[input.images.at(-1),screen.image,...slotTemplate,...(screen.templateImage?[screen.templateImage]:[]),...originalImages]; + const captions=['受审候选原图','候选放入后的整屏合成',...slotTemplate.map(()=>'固定模板图位原图'),...(screen.templateImage?['模板原屏']:[]),...originalImages.map((_image,index)=> '同款实拍 '+(originalReference??'P'+String(index+1).padStart(2,'0')))]; const scope=productRequestScope('review',candidateId); await runAgent(slot.id,instructions,prompt,[review],images,scope,captions,signal); diff --git a/apps/detail-agent-pi/src/copy-image-alignment.mjs b/apps/detail-agent-pi/src/copy-image-alignment.mjs index c4e70914..b2f1f340 100644 --- a/apps/detail-agent-pi/src/copy-image-alignment.mjs +++ b/apps/detail-agent-pi/src/copy-image-alignment.mjs @@ -1,4 +1,4 @@ -export const COPY_IMAGE_PROMPT_GUIDANCE='让画面清晰呈现关联文案的重点。用本款实拍保持商品一致。只参考构图时,将模板构图提炼为提示词中的文字。构图可用 transform_slot_image 调整,具体创作要求见适用企业 Skill。'; +export const COPY_IMAGE_PROMPT_GUIDANCE='整件商品图优先用模板原图作底图。说明要换掉的旧商品、所用实拍、位置朝向大小和透视,按实拍保留颜色、结构、比例和部件。保留模板画面,按需调整与商品接触的动作和道具,清除旧商品残留,避免生成文字。特写优先从本款中景裁出,可请求 2K。模板无商品或无法对位时可改用实拍、已有候选或用文字描述构图。'; export const OVERLAY_SCREEN_CRITERIA='核对叠层错位、压字或数值不符。overlayLayers 的 overlapsSlots 对应图位 fieldId,bounds 为像素边界,text 为当前文字,mapped 表示是否已映射。group 是直属图层组,overlayGroups 按组列出本屏的成员 ID。同组尺寸线、端点和数字应作为一套核对和处理。belowSlot 标出图位下方可能露出的图层,留意其中的旧字和底条。每项按 fieldId 指向图位,coverage 是屏内图层边界的覆盖比例,opacity 是图位内容不透明度,blendMode 是图位混合模式。'; export const COPY_IMAGE_SCREEN_GUIDANCE='对照商品资料、实时文案和适用企业 Skill 核对整屏实际画面。检查材质、颜色、款式、结构、尺寸与标注是否一致,以及文字溢出、裁切和可读性。'+OVERLAY_SCREEN_CRITERIA; diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index f64dc93e..09ec283d 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -168,7 +168,7 @@ export async function callProductionTool(host, name, args, signal) { if(input.adopted)return {...target,accepted:false,reason:'canvas_inactive'}; const plan=await host.canvas.detailHistory({projectPlan:true,targetOutput:target}); const {referenceMode}=productionSettings(host.store,plan.template.production); - const options={targetOutput:target,includeTemplateReference:!input.candidateId&&referenceMode==='composition-only', + const options={targetOutput:target,includeTemplateReference:!input.candidateId&&['template-base','composition-only'].includes(referenceMode), ...(input.candidateId&&!input.includeReferences?{includeProductReferences:false}:null)}; return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)}); } diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 883bf213..3b863e15 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -70,6 +70,7 @@ const preparationArgs={ reworkCandidateId:optional(text), references:optional(Type.Array(productReference,{minItems:1,uniqueItems:true})), referenceIndexes:optional(Type.Array(page,{minItems:1,uniqueItems:true,description:'本款原片的零起始编号,按实际发送顺序填写。'})), + useTemplateBase:optional(Type.Boolean({description:'使用本图位固定模板原稿像素作为第一张图,随后发送本款实拍。显式 false 可切换做法。'})), prefer2k:optional(Type.Boolean({description:'传 true 可请求 2K,例如用于后续局部裁切。'})), retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})), }; @@ -86,8 +87,8 @@ const outputScope={outputId:optional(text),variantId:optional(text)}; export const productionOperationTools = [ ['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。work 中的 waitingCanvas 列出仍在等切回的图位。',obj({outputId:text,variantId:text})], - ['set_production_settings','将按企业 Skill 确定的参考方式或主图画幅记录到当前项目。composition-only 表示只参考构图,none 表示不参考。',obj({ - referenceMode:optional(Type.Union([Type.Literal('composition-only'),Type.Literal('none')])), + ['set_production_settings','将按企业 Skill 确定的参考方式或主图画幅记录到当前项目。template-base 表示用原图换商品,composition-only 表示只参考构图,none 表示不参考。',obj({ + referenceMode:optional(Type.Union([Type.Literal('template-base'),Type.Literal('composition-only'),Type.Literal('none')])), mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1,uniqueItems:true})), })], ['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。参考方式或主图画幅未声明时,按企业 Skill 确定后用 set_production_settings 记录。生图上限及来源适用于所有图位。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})], @@ -102,7 +103,7 @@ export const productionOperationTools = [ ['write_copy_fields','按 revision 原位写入指定文字格。可传 expectedText 核对原文,每个 layer 只传一次。原生命令已写过时可用 recordOnly 登记。某一屏文案定下来就可以按 dispatchReady 派这一屏的图位,不必等整页文案;子代理在后台生图时继续写下一屏。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({ revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),expectedText:optional(Type.String()),sources:ids,pictures:ids,reason:optional(Type.String())}))), })], - ['read_slot_images','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({ + ['read_slot_images','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。模板底图候选会同时返回该图位原图。用 includeReferences=true 查看本款实拍。',obj({ ...outputScope,slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()), })], ['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,slotId:slotRef,...productImageArgs})], @@ -113,7 +114,7 @@ export const productionOperationTools = [ ...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], ['await_image_slots','等待任一在途制作、验图或生图请求返回,提供状态、编号和修改摘要。单次最多等待 3 分钟,超时后原工作继续。省略 slotIds 时也关注整屏复核,完整意见用 read_screen_review 按屏读取;图位详情用 review_image_slots。omitted 是因体积限制省略的条数。未知结果用 reconcile_image_slots 核查,waiting_canvas 表示等待可写画布。',obj({...outputScope,slotIds:optional(ids)})], - ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位;waiting_canvas 的图位在等待切回可写画布。指定 slotIds 查看详情;批量详情超出预算时返回摘要,用 nextOffset 作为 offset 翻页,再用单个 slotId 查看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),offset:optional(Type.Integer({minimum:0}))})], + ['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位;waiting_canvas 的图位在等待切回可写画布。指定 slotIds 查看详情,或在 slotIds 填写一个图位并指定 candidateId 查看实际候选像素;批量详情超出预算时返回摘要,用 nextOffset 作为 offset 翻页,再用单个 slotId 查看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),candidateId:optional(text),offset:optional(Type.Integer({minimum:0}))})], ['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。用候选号在当前目标图位做本地变换或复用。用 nextOffset 作为 offset 翻页,candidateId 展开单条。',obj({...outputScope,candidateId:optional(Type.String()),offset:optional(Type.Integer({minimum:0}))})], ['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。用 nextOffset 作为 offset 翻页,candidateId 展开单条,可用 projectId 指定来源项目。',obj({ slotIds:optional(Type.Array(Type.String())),candidateId:optional(Type.String()),projectId:optional(Type.String()),offset:optional(Type.Integer({minimum:0})), @@ -121,7 +122,7 @@ export const productionOperationTools = [ ['stage_archived_image','把已完成的候选加入当前目标图位待验,沿用其原素材任务。来源是本项目任一成品的同花色候选时省略 projectId,来源是另一同款项目时使用 read_archived_images 返回的 projectId。请按目标图位复核再决定是否采用。',obj({ ...outputScope,slotId:slotRef,projectId:optional(Type.String()),candidateId:text, })], - ['check_image_slots','请验图代理按企业 Skill 同看候选原图及候选放入后的整屏画面,检查商品还原和叠层对位,并对照当前图位关联文案核对图文一致性。可用 fit 指定预览放置方式。默认先返回受理结果,可用 review_image_slots 查看结论,用 adopt_production_image 采用你选定的候选。',obj({ + ['check_image_slots','请验图代理按企业 Skill 同看候选原图及候选放入后的整屏画面,模板底图候选也会附上固定图位原图。检查商品还原和叠层对位,并对照当前图位关联文案核对图文一致性。可用 fit 指定预览放置方式。默认先返回受理结果,可用 review_image_slots 查看结论,用 adopt_production_image 采用你选定的候选。',obj({ ...outputScope,wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean()),fit:optional(fit)})), })], ['adopt_production_image','采用你选择的候选,用 reason 记录采用理由,返回画布修订和模板叠层。单图位屏与验图画面一致时沿用复核结论。screensReadyForReview 列出图位已齐、尚未复核当前画面的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})], @@ -831,7 +832,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const transformImage=(slot,{sourceCandidateId,referenceIndex,reference,...transform},signal)=> serialize(()=>localCandidate(slot,'transform',{sourceCandidateId,referenceIndex:reference?referenceIndexOf(reference):referenceIndex,transform},signal,'transform')); const prepareImageRequest=async(slot,{prompt,retryOf,prefer2k, - references,referenceIndexes,reworkCandidateId,reworkChange},signal)=>{ + references,referenceIndexes,reworkCandidateId,reworkChange,useTemplateBase},signal)=>{ signal?.throwIfAborted(); await current(); const live=await liveSlot(slot); @@ -839,6 +840,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, if(status.drawLimitReached)return drawLimit(live,status); const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined, prefer2k,reworkOf:reworkCandidateId,reworkChange, + useTemplateBase:useTemplateBase??(productionSettings(store,plan.template?.production).referenceMode==='template-base'||undefined), referenceIndexes:references?.map(referenceIndexOf)??referenceIndexes}, undefined,imageScope).catch(async error=>{ if(error.message!=='同款原图编号无效')throw error; @@ -868,7 +870,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, return {candidateId:receipt.id??candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message, ...(receipt.candidates?{candidates:receipt.candidates}:null), ...(receipt.generationEvidence?{generationEvidence:receipt.generationEvidence}:null), - requestedSource:'generate',attachmentSources:receipt.attachmentSources??request.spec?.references?.map(({source,role})=>({source,role})),...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), + requestedSource:'generate',attachmentSources:receipt.attachmentSources??request.attachmentSources??request.spec?.references?.map(({source,role})=>({source,role})),...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), ...(!settledImagePhases.includes(phase)&&phase!=='draw_limit_reached'?{pendingOriginal:receipt.id??candidateId}:null), ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; }; @@ -919,7 +921,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, jobs.set(id,{row,run,requestId:id,startedAt:performance.now()}); if(workerNumber===undefined)notice('正在生图'); return {slotId:slot.id,phase:'accepted',candidateId:id,operationId:id, - ...(request.spec?.references?{attachmentSources:request.spec.references.map(({source,role})=>({source,role}))}:null)}; + ...(request.attachmentSources?{attachmentSources:request.attachmentSources}:request.spec?.references?{attachmentSources:request.spec.references.map(({source,role})=>({source,role}))}:null)}; }; const useProductImage=async(slot,{reference,...options},signal)=>{ if(reference)options.referenceIndex=referenceIndexOf(reference); @@ -1271,19 +1273,20 @@ export async function openProductionOperations(host,{target=host.productionGoal, const wantsCandidate=Boolean(args.candidateId?.trim()||args.adopted); const includeProduct=args.includeReferences||!wantsCandidate&&!seenProduct; const {referenceMode}=productionSettings(store,plan.template.production); - const includeLayout=referenceMode==='composition-only'&&!wantsCandidate&&(args.includeReferences||!seenLayouts.has(slot.id)); + const includeLayout=['template-base','composition-only'].includes(referenceMode)&&!wantsCandidate&&(args.includeReferences||!seenLayouts.has(slot.id)); const {images=[],referenceCount=0,layoutCount=0,textRegionPreview,bareCandidate, actionReviewDetail,groundContactDetail,sceneEdgeDetails,...details}=await readImages(slot.id,{ ...args,includeProductReferences:includeProduct,includeTemplateReference:includeLayout, }); const product=includeProduct?images.slice(0,referenceCount):[]; - const layout=includeLayout?images.slice(referenceCount,referenceCount+layoutCount):[]; + const layout=includeLayout||details.layoutSource==='pinnedTemplateOriginal' + ?images.slice(referenceCount,referenceCount+layoutCount):[]; if(product.length)seenProduct=true; if(layout.length)seenLayouts.add(slot.id); return imageResult({...details,referenceCount:product.length,layoutCount:layout.length, ...(product.length?{productReferences:productReferences(product.length)}:null), ...(seenProduct&&!includeProduct?{productReferencesEarlier:true}:null), - ...(seenLayouts.has(slot.id)&&!includeLayout?{layoutReferenceEarlier:true}:null), + ...(seenLayouts.has(slot.id)&&!layout.length?{layoutReferenceEarlier:true}:null), images:[...product,...layout,...images.slice(referenceCount+layoutCount)]}); }, use_product_image({slotId,...options},signal){ @@ -1342,7 +1345,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, (args,activeSignal)=>useProductImage(slot,args,activeSignal),true), workerTool('transform_slot_image','用本款实拍或本项目候选裁切、镜像、旋转、缩放或位移',transformImageArgs, (args,activeSignal)=>transformImage(slot,args,activeSignal)), - workerTool('prepare_image_request','准备并持久保存完整生图请求。',preparationArgs, + workerTool('prepare_image_request','准备并持久保存完整生图请求。'+imagePromptGuidance,preparationArgs, async(args,activeSignal)=>{ latestPrepared=undefined; const receipt=await prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal); @@ -1373,11 +1376,11 @@ export async function openProductionOperations(host,{target=host.productionGoal, return receipt; },result=>!result.limitReached), ]; - const readTool={name:'read_slot_images',label:'查看本图位参考',description:'读取本款实拍。只参考构图时也会返回模板原图,供提炼构图文字。', + const readTool={name:'read_slot_images',label:'查看本图位参考',description:'读取本款实拍。按制作配置返回模板参考。', parameters:obj({}),execute:async()=>{ delegateSignal.throwIfAborted(); const {referenceMode}=productionSettings(store,plan.template.production); - const result=await readImages(slot.id,{includeTemplateReference:referenceMode==='composition-only'}); + const result=await readImages(slot.id,{includeTemplateReference:['template-base','composition-only'].includes(referenceMode)}); return imageResult({...result,productReferences:productReferences(result.referenceCount)}); }}; const run=scheduleDelegate(delegateSignal,async()=>{ @@ -1410,7 +1413,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const live=await liveSlot(slot); const status=slotDrawStatus(live); const {referenceMode}=productionSettings(store,plan.template.production); - const instructions='只参考构图时,将适用的机位、取景、主体位置、比例和留白写入生图提示词。生图附件只使用本款实拍与获准素材。完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例,仅供参考。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+ + const instructions='按图位画面选择模板换商品或取用已有候选。完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例,仅供参考。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+ (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':''); const screenCopy=await liveSlotCopy(slot); delegateSignal.throwIfAborted(); @@ -1480,7 +1483,11 @@ export async function openProductionOperations(host,{target=host.productionGoal, clearTimeout(timer); } }, - async review_image_slots({slotIds,offset=0}){ + async review_image_slots({slotIds,candidateId,offset=0}){ + if(candidateId){ + if(slotIds?.length!==1)throw Error('查看候选像素时请在 slotIds 填写一个图位'); + return operations.read_slot_images({slotId:slotIds[0],candidateId,includeReferences:true}); + } const live=await liveSlots(); const {requested,matched,unmatched}=readSelection(slotIds); const checks=Map.groupBy([...reviewWork],job=>job.row.slotId); diff --git a/apps/detail-agent-pi/src/production-slots.mjs b/apps/detail-agent-pi/src/production-slots.mjs index b32fa7d9..5a1e44b0 100644 --- a/apps/detail-agent-pi/src/production-slots.mjs +++ b/apps/detail-agent-pi/src/production-slots.mjs @@ -25,7 +25,9 @@ export async function saveProductionSettings(store,choices) { } export function productionPicturePlan(outputId,slots,{referenceMode,mainImageAspects}) { - const reference={referenceMode:referenceMode??null,...(!referenceMode?{referenceNotice:'参考方式未声明'}:null)}; + const reference={referenceMode:referenceMode??null}; + if(referenceMode==='template-base')reference.referenceNotice='整件商品图可用固定模板原图换商品,局部细节可从中景裁切'; + if(!referenceMode)reference.referenceNotice='参考方式未声明'; if(outputId!=='main_images')return {...reference,plannedSlots:slots}; const availableMainImageAspects=[...new Set(slots.map(slot=>slot.aspectRatio).filter(Boolean))]; return {...reference,availableMainImageAspects,mainImageAspects:mainImageAspects??null, diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 71ef17d0..c286174f 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -9,10 +9,12 @@ maxGenerationAttempts: 4 从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read` 按路径查看已锁定的文件。 - `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。 -- transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景。 -- 按已发布规则撰写完整的 `prompt`,包括商品外观、构图、颜色、参考用途和返工要求。用 `referenceIndexes` 指定发送的原片及顺序,按需指定模板参考、画幅规格或实拍合成。实拍合成时,提示词描述在模板场景中擦除旧商品,本款实拍由客户端合成。 +- 中景、全景、整件商品图、主图与 SKU 优先以模板原图为底图。用 `useTemplateBase` 选择底图,通过 `referenceIndexes` 选本款实拍。 +- 提示词按图位说明换掉哪件旧商品、参照哪些实拍以及本款的位置、朝向、大小与透视。颜色、结构、比例和部件按实拍。保留模板背景、机位、光线、构图、色调、人物、道具与留白。商品结构有差异时可调整接触商品的动作和道具。清除旧商品残留,避免生成文字。 +- 特写或局部细节先看模板取景的部位、角度和占比。复用或生成本款中景,再用 `transform_slot_image` 裁成目标图框。可跨图位和成品使用同花色候选。查看裁后清晰度指标,必要时请求 2K 或用更近的中景重新裁切。 +- 模板无商品或形态无法对位时,可用 `use_product_image` 直接取实拍、用 `transform_slot_image` 复用候选,或将模板构图写入提示词。按本图位画面选择。 - 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。调用 `dispatch_image_request` 时填写该回执的 `requestId`,宿主从该编号绑定的请求读取版本和哈希。 -- 生图准备回执列出同批候选的各自请求号。确认首个 `requestId` 即派发本批。对照 `review_image_slots` 的 `comparison`、实际像素、画幅、五段提示词及哈希回执,选择采用的候选,再用 `adopt_production_image` 的 `reason` 记录选择理由。 +- 生图准备回执列出同批候选的各自请求号。确认首个 `requestId` 即派发本批。对照 `review_image_slots` 的 `comparison`、实际像素、画幅与请求回执,选择采用的候选,再用 `adopt_production_image` 的 `reason` 记录选择理由。 - 同批有未知原请求时,按原号核查到终态后才能补出。每次补出按剩余额度派发。全部候选未通过且本图位已达上限时,挑最合适的可用候选并写明采用理由。交付时会将该候选尚未解决的审稿问题记入已知问题。 - 模板制作配置示例 `{"schemaVersion":1,"candidatesPerSlot":2,"maxCandidatesPerSlot":4}`。默认每批 2 张,每个图位累计 4 张。已提交后失败或结果未知均计入额度。 - `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。 diff --git a/apps/detail-agent-pi/test/candidate-review.test.mjs b/apps/detail-agent-pi/test/candidate-review.test.mjs index e6988371..9b2be152 100644 --- a/apps/detail-agent-pi/test/candidate-review.test.mjs +++ b/apps/detail-agent-pi/test/candidate-review.test.mjs @@ -60,3 +60,19 @@ test('before any copy is written the review omits shown fields instead of reject assert.equal(result.verdict,'pass'); assert.deepEqual(result.observation.visualEvidence,[]); }); + +test('template-base review includes the fixed slot image alongside the candidate',async()=>{ + const slot={id:'slot',fieldId:'image',label:'商品图'}; + const pixels=data=>({type:'image',mimeType:'image/png',data}); + const [photo,base,candidate,composite]=['photo','base','candidate','composite'].map(pixels); + const canvas={detailImages:async()=>({candidateId:'candidate',referenceCount:1,layoutCount:1,layoutSource:'pinnedTemplateOriginal',images:[photo,base,candidate]})}; + const screen={image:composite,details:{page:0,screenFingerprint:'fixture',slots:[slot],screenCopy:[],overlayLayers:[]}}; + const runAgent=async(_slot,instructions,_prompt,[review],images,_scope,captions)=>{ + assert.deepEqual(images,[candidate,composite,base,photo]); + assert.equal(captions[2],'固定模板图位原图'); + assert.match(instructions,/旧商品残留/u); + review.execute('',review.prepareArguments({verdict:'pass',reason:'本款与实拍一致',screenVerdict:'pass'})); + }; + const result=await reviewProductionCandidate({canvas,runAgent,slot,screen,candidateId:'candidate',referenceMode:'template-base'}); + assert.equal(result.verdict,'pass'); +}); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 5846ee6c..dc4dfbc0 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -482,11 +482,11 @@ test('closeup preparation forwards only the requested reference and resolution o 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}]){ + {useTemplateReference:false,useSceneComposite:false,prefer2k:true},{useTemplateBase:true},{useTemplateBase:false}]){ 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:options.prefer2k,referenceIndexes:[0,2]}); + const {useTemplateReference,useSceneComposite,useTemplateBase,prefer2k,referenceIndexes}=forwarded.at(-1); + assert.deepEqual({useTemplateReference,useSceneComposite,useTemplateBase,prefer2k,referenceIndexes}, + {useTemplateReference:undefined,useSceneComposite:undefined,useTemplateBase:options.useTemplateBase,prefer2k:options.prefer2k,referenceIndexes:[0,2]}); } await actions.prepare_image_request({slotId:'P06',prompt:args.prompt,references:['P01','P03']}); assert.deepEqual(forwarded.at(-1).referenceIndexes,[0,2]); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 68bc1539..95429c44 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -434,20 +434,6 @@ fn product_crop_mode<'a>(state: &'a Value, output: &Value, field: &Value) -> R bool { - task["sceneComposite"].is_object() || task["references"].as_array().into_iter().flatten() - .any(|reference| reference["role"] == "template-layout") -} - -#[test] -fn template_images_from_legacy_preparations_cannot_be_dispatched() { - let mut task = json!({"references":[{"source":"photo","role":"product"},{"source":"scene","role":"scene"}]}); - assert!(!contains_template_generation_reference(&task)); - task["references"].as_array_mut().unwrap().push(json!({"role":"template-layout"})); - assert!(contains_template_generation_reference(&task)); - assert!(contains_template_generation_reference(&json!({"sceneComposite":{}}))); -} - fn specified_image_ratio(field: &Value) -> Option<(u64, u64)> { let description = field["outputSpec"].as_str().or_else(|| field["requirements"].as_str())?; let text = description.split_once("标准比例")?.1.trim_start_matches([' ', ':', ':']); @@ -2142,7 +2128,23 @@ impl Backend { let candidate_record = candidate_id.map(|id| read_candidate(&dir, id)).transpose()?; let candidate_prompt = candidate_record.as_ref().map(|record| record["prompt"].clone()); let is_production_review = state["productTemplates"].is_object() && candidate_record.is_some(); - let layout = if target["originalsOnly"] == true || target["includeTemplateReference"] == false { + let template_base = candidate_record.as_ref().is_some_and(|record| record["templateBase"] == true); + let cropped_candidate = state["template"]["enterprise"].is_object() && candidate_record.as_ref().is_some_and(|record| { + let crop = &record["canvasTransform"]["transform"]["crop"]; + crop.is_array() && *crop != json!([0,0,1000,1000]) + }); + let fixed_layout = target["originalsOnly"] != true && (template_base || cropped_candidate); + let layout = if fixed_layout && template_base { + let id = candidate_id.ok_or("候选编号缺失")?; + super::images::read_image_request(&dir, id) + .and_then(|task| super::images::verified_reference_at(&task["references"][0])) + .map(Some) + } else if fixed_layout { + let original = json!({"templateHash":state["template"]["contentHash"],"component":output["component"], + "documentId":output["id"],"variantId":variant_id,"fieldId":field["fieldId"]}); + let frame = slot_frame(field, mapped_slot(&state, slot, &variant_id)).ok_or("当前图位缺少实际图框")?; + self.template_edit_pixels(&dir, &original, frame).map(Some) + } else if target["originalsOnly"] == true || target["includeTemplateReference"] == false { Ok(None) } else if is_production_review { if candidate_record.as_ref().is_some_and(|record| record["sourceType"] != "product-reference") { @@ -2240,6 +2242,7 @@ impl Backend { let mapping = cached_prompt_mapping(&dir, &state["template"]); let aspect = specified_image_ratio(field).map(|(w,h)| format!("{w}:{h}")); Ok(json!({"images":images,"referenceCount":reference_count,"layoutCount":layout_count,"layoutIssue":layout_issue, + "layoutSource":(fixed_layout && layout_count>0).then_some("pinnedTemplateOriginal"), "relatedCopy":target["relatedCopy"],"adopted":adopted_canvas.is_some(), "outputId":target["outputId"],"variantId":variant_id, "textRegions":text_regions, @@ -2252,24 +2255,36 @@ impl Backend { "dimensions":variant(&state,&variant_id)?["dimensions"]}})) } - pub(super) fn read_pinned_template_image(&self, dir: &Path, target: &Value) -> R { + fn pinned_template_layer(&self, dir: &Path, target: &Value) -> R<(Document, photocraft_doc::LayerId, Value, Value)> { let state = load(dir)?; - let pack = &state["template"]; + let component = target["component"].as_str().ok_or("模板组件缺失")?; + let pack = state["productTemplates"].get(component).unwrap_or(&state["template"]); if !pack["enterprise"].is_object() || target["templateHash"] != pack["contentHash"] { return Err("当前项目的固定模板原图不可用".into()); } - let component = target["component"].as_str().ok_or("模板组件缺失")?; let variant_id = target["variantId"].as_str().ok_or("原稿图位花色缺失")?; variant(&state, variant_id)?; - let original = self.enterprise_template_canvas(pack, component, target["documentId"].as_str(), variant_id, |_| {})?; + let document = if component == "detail" { None } else { target["documentId"].as_str() }; + let original = self.enterprise_template_canvas(pack, component, document, variant_id, |_| {})?; let meta = mapping(&original).ok_or("固定原稿缺少图位映射")?; let field = page_fields(&meta).flat_map(|(_, fields)| fields) .find(|field| field["fieldId"] == target["fieldId"] && field["kind"] == "image") .ok_or("指定图位在固定原稿里缺少可读图层")?; let id = field["nativeLayerId"].as_u64().ok_or("指定图位在原稿中没有图层身份")?; - let image = photocraft_ui_egui::jiansun::template_layer_jpeg(&original, photocraft_doc::LayerId(id))?; + let field = field.clone(); + Ok((original, photocraft_doc::LayerId(id), field, pack["version"].clone())) + } + + pub(super) fn read_pinned_template_image(&self, dir: &Path, target: &Value) -> R { + let (original, id, field, version) = self.pinned_template_layer(dir, target)?; + let image = photocraft_ui_egui::jiansun::template_layer_jpeg(&original, id)?; Ok(json!({"source":"pinnedTemplateOriginal","fieldId":field["fieldId"],"label":field["label"], - "templateVersion":pack["version"],"images":[{"type":"image","data":image,"mimeType":"image/jpeg"}]})) + "templateVersion":version,"images":[{"type":"image","data":image,"mimeType":"image/jpeg"}]})) + } + + fn template_edit_pixels(&self, dir: &Path, target: &Value, frame: &Value) -> R> { + let (original, id, field, _) = self.pinned_template_layer(dir, target)?; + render_template_edit(original, id, &field["frame"], frame) } pub(super) fn repair_template_ending(&self, dir: &Path, doc: &mut Document, progress: impl FnMut(Value)) -> R> { @@ -3046,6 +3061,48 @@ impl Backend { } } +fn encode_template_rgba(width: u32, height: u32, rgba: Vec) -> R> { + use photocraft_codecs::{ChannelLayout, Format, Image, encode}; + let image = Image::from_u8(width, height, ChannelLayout::Rgba, rgba).map_err(|_| "模板图位像素无效")?; + encode(&image, Format::Png, &Default::default()).map_err(|_| "模板图位无法编码".into()) +} + +fn render_template_edit( + mut original: Document, id: photocraft_doc::LayerId, original_frame: &Value, frame: &Value, +) -> R> { + let mut layer = original.layer(id).ok_or("原稿图层不存在")?.clone(); + layer.clipped = false; + let x = original_frame["x"].as_f64().ok_or("原稿图框横坐标无效")?.round() as i32; + let y = original_frame["y"].as_f64().ok_or("原稿图框纵坐标无效")?.round() as i32; + let extent = |key| frame[key].as_f64().filter(|n| (1.0..=8192.0).contains(n)) + .map(|n| n.round() as i32).ok_or("图框尺寸无效"); + let (width, height) = (extent("width")?, extent("height")?); + let area = photocraft_geom::Rect::new(x, y, x + width, y + height); + original.layers = vec![layer]; + let pixels = photocraft_compose::render(&original, area).to_rgba8(); + encode_template_rgba(width as u32, height as u32, pixels.pixels) +} + +#[test] +fn jiansun_template_edit_crops_only_the_selected_layer() { + let original = crate::jiansun_document::import( + &json!({"name":"fixture","screens":[{"name":"test","width":12,"height":12,"background":"#ffffff","layers":[ + {"kind":"image","name":"base","source":"base","x":2,"y":2,"width":8,"height":8}, + {"kind":"image","name":"overlay","source":"overlay","x":2,"y":2,"width":8,"height":8} + ]}]}), + &std::collections::HashMap::from([ + ("base".to_owned(), encode_template_rgba(8,8,[180,30,20,255].repeat(64)).unwrap()), + ("overlay".to_owned(), encode_template_rgba(8,8,[20,30,180,255].repeat(64)).unwrap()), + ]), + ).unwrap(); + let id = original.walk().into_iter().find(|(_,_,layer)| layer.name=="base").unwrap().2.id; + let frame = json!({"x":3,"y":3,"width":4,"height":3}); + let base = render_template_edit(original, id, &frame, &frame).unwrap(); + let base = photocraft_codecs::decode(&base).unwrap().convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); + assert_eq!((base.width(), base.height()), (4,3)); + assert_eq!(base.data(), [180,30,20,255].repeat(12)); +} + fn subject_bounds( surface: &photocraft_raster::Surface, frame: photocraft_geom::Rect, ) -> Result<[i32; 4], &'static str> { @@ -3981,9 +4038,6 @@ impl Backend { && ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field| task["slotBinding"][*field] == scope[if *field=="workspaceId" {"id"}else{*field}])); if !belongs { return Err("生图请求不属于当前账户、项目、工作画布或图位".into()); } - if task["phase"] == "prepared" && contains_template_generation_reference(&task) { - return Err(BridgeFailure::new("image_request_failed", false, false, "已准备的请求包含模板图片,请重新准备生图请求")); - } super::images::freeze_image_request_locked(dir, &mut task, request)?; let Some(dispatch) = lock_candidate_dispatch(dir, &id)? else { return Ok(json!({"phase":"running","candidateId":id})); @@ -4046,9 +4100,7 @@ impl Backend { receipt["message"] = json!(message); } self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, true, message))?; - receipt["attachmentSources"] = json!(task["references"].as_array().into_iter().flatten() - .map(|reference| json!({"source":reference["source"],"role":reference["role"]})) - .collect::>()); + receipt["attachmentSources"] = super::images::attachment_sources(&task); Ok(receipt) }); if let (Some((_, presentation)), Err(error)) = (production, &result) { @@ -4520,9 +4572,24 @@ impl Backend { if selected.is_empty() { return Err("正式生图至少需要一张同款产品参考图".into()); } images = json!(selected); } + let use_template_base = input["useTemplateBase"] == true; + if use_template_base { + if !attachments.is_empty() { return Err("模板底图请求只接受本款实拍作为参考".into()); } + images.as_array_mut().ok_or("本款实拍无效")?.retain(|item| item["purpose"] == "product"); + if images.as_array().is_none_or(Vec::is_empty) { + return Err("模板底图请求至少需要一张本款实拍".into()); + } + } creation["brief"]["images"] = images.clone(); creation["generation"] = Value::Null; // Never inherit a different colour's legacy anchor. - let (references, layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?; + if use_template_base { + let target = json!({"templateHash":state["template"]["contentHash"],"component":output["component"], + "documentId":output["id"],"variantId":variant_id,"fieldId":field["fieldId"]}); + let base = self.template_edit_pixels(&dir, &target, &field["frame"])?; + let source = format!("pinned-template:{}", field["fieldId"].as_str().ok_or("图位字段缺失")?); + attachments.push((json!({"id":source,"purpose":"template-base"}), base)); + } + let (references, mut layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?; let settings = self.settings()?; let model = settings["imageModel"].as_str().filter(|model| !model.is_empty()).ok_or("请先选择生图模型")?; let candidate = if input["workflowOperationId"].is_null() || preparing { @@ -4554,6 +4621,11 @@ impl Backend { let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height})); let mut origins = creation["brief"]["images"].as_array().cloned().unwrap_or_default(); origins.extend(attachments.iter().map(|(asset,_)| json!({"source":asset["id"],"purpose":asset["purpose"].as_str().unwrap_or("approved-material")}))); + if use_template_base { + layers.rotate_right(1); + origins.rotate_right(1); + record["templateBase"] = json!(true); + } let image_input = json!({"doc":doc,"revision":input["baseRevision"],"model":model, "mode":if parent.is_some(){"refine"}else{"generate"},"text":instructions,"references":layers, "slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k,"referenceOrigins":origins, @@ -6705,9 +6777,17 @@ mod tests { let id = Uuid::new_v4().to_string(); let scoped = production_image_target(state.clone(), &scope).unwrap(); + let job = dir.join("image-jobs").join(&id); + fs::create_dir_all(&job).unwrap(); + let reference_path = job.join("reference.png"); + let reference_bytes = encode_template_rgba(1, 1, vec![120, 60, 30, 255]).unwrap(); + fs::write(&reference_path, &reference_bytes).unwrap(); + let reference_hash = format!("{:x}", Sha256::digest(&reference_bytes)); + let references = ["template-layout", "template-base", "product"].map(|role| + json!({"role":role,"path":reference_path,"sha256":reference_hash})); let mut task = json!({"id":id,"doc":doc,"localProjectId":backend.locations.get(&doc), "accountScope":backend.scope(),"origin":backend.origin,"outputScope":"detail","phase":"prepared", - "requestSpecRevision":1,"references":[],"prompt":"展示真实商品","candidateRecord":{"inputHash":"stale"}, + "requestSpecRevision":1,"references":references,"prompt":"展示真实商品","candidateRecord":{"inputHash":"stale"}, "slotBinding":{"slotId":slot,"fieldId":"S01-I01","outputId":"S01", "workspaceId":scope["id"],"templateHash":scope["templateHash"], "structureHash":scoped["structureHash"],"variantId":variant,"detailBatch":true}}); @@ -7561,6 +7641,21 @@ mod tests { with_details["groundContactDetail"] = json!(true); let review = backend.read_detail_review_images(doc, &with_details, Some(&canvas)).unwrap(); assert_eq!(review["groundContactDetail"]["mimeType"], "image/jpeg"); + let base = encode_template_rgba(16, 8, [220, 30, 20, 255].repeat(128)).unwrap(); + let base_path = job.join("reference-0.png"); + fs::write(&base_path, &base).unwrap(); + record["templateBase"] = json!(true); + write_json(&candidate_path(&project, &id).unwrap(), &record).unwrap(); + let mut task = read_json(&job.join("task.json")).unwrap(); + task["requestSpecHash"] = json!("fixture"); + task["references"] = json!([{"role":"template-base","path":base_path, + "sha256":format!("{:x}", Sha256::digest(&base))}]); + write_json(&job.join("task.json"), &task).unwrap(); + let review = backend.read_detail_review_images(doc, &with_details, None).unwrap(); + assert_eq!(review["layoutCount"], 1); + let review_base = STANDARD.decode(review["images"][0]["data"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&review_base).unwrap().dimensions(), (16, 8)); + assert_eq!(review["images"].as_array().unwrap().len(), 2); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 774d24f0..0ac5992e 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -87,23 +87,32 @@ fn image_spec(task: &Value) -> Value { "sceneComposite":task["sceneComposite"],"localProductSha256":task["localProductSha256"]}) } +pub(super) fn attachment_sources(task: &Value) -> Value { + json!(task["references"].as_array().into_iter().flatten().map(|reference| { + json!({"source":reference["source"],"role":reference["role"], + "position":reference["position"],"size":reference["size"]}) + }).collect::>()) +} + pub(super) fn image_request_receipt(task: &Value) -> Value { json!({"requestId":task["id"],"revision":task["requestSpecRevision"],"requestSpecHash":task["requestSpecHash"], "frozen":task["frozenAt"].is_number(),"phase":task["phase"],"slotId":task["slotBinding"]["slotId"], "outputId":task["outputScope"],"variantId":task["slotBinding"]["variantId"], "templateHash":task["slotBinding"]["templateHash"],"retryOf":task["candidateRecord"]["retryOf"], - "reworkOf":task["candidateRecord"]["reworkOf"],"reworkChange":task["candidateRecord"]["reworkChange"],"spec":image_spec(task)}) + "reworkOf":task["candidateRecord"]["reworkOf"],"reworkChange":task["candidateRecord"]["reworkChange"],"attachmentSources":attachment_sources(task),"spec":image_spec(task)}) +} + +pub(super) fn verified_reference_at(reference: &Value) -> R> { + let file = Path::new(reference["path"].as_str().ok_or("参考图记录无效")?); + let bytes = fs::read(file).map_err(|_| "本机参考图不可读取")?; + if bytes.len() > 10 * 1024 * 1024 || reference["sha256"] != format!("{:x}", Sha256::digest(&bytes)) { + return Err("参考图已变化,未提交".into()); + } + Ok(bytes) } fn verified_reference_bytes(task: &Value) -> R>> { - task["references"].as_array().ok_or("参考图记录无效")?.iter().map(|reference| { - let file = Path::new(reference["path"].as_str().ok_or("参考图记录无效")?); - let bytes = fs::read(file).map_err(|_| "本机参考图不可读取")?; - if bytes.len() > 10 * 1024 * 1024 || reference["sha256"] != format!("{:x}", Sha256::digest(&bytes)) { - return Err("参考图已变化,未提交".into()); - } - Ok(bytes) - }).collect() + task["references"].as_array().ok_or("参考图记录无效")?.iter().map(verified_reference_at).collect() } fn image_payload(task: &Value, files: &[Vec]) -> R { @@ -1035,7 +1044,8 @@ impl Backend { protocol::frame(&mut contract, u64::from(width), u64::from(height), false)?; } // The scene composite reuses its template base locally, so it stays lossless. - let (bytes, extension) = reference_upload(&raster, scene.is_none() && contract["jpegReferences"] == true)?; + let (bytes, extension) = reference_upload(&raster, scene.is_none() && contract["jpegReferences"] == true + && input["referenceOrigins"][i]["purpose"] != "template-base")?; total = total.saturating_add(bytes.len()); if bytes.len() > 10 * 1024 * 1024 || total > 24 * 1024 * 1024 { return Err("参考图总量过大,请减少图片".into()); @@ -1628,6 +1638,26 @@ mod tests { assert!(wire.contains("name=\"output_format\"\r\n\r\njpeg\r\n")); assert!(wire.contains("name=\"output_compression\"\r\n\r\n95\r\n")); } + #[test] + fn jiansun_template_base_preserves_request_order_and_source_receipt() { + let task = json!({"modelId":"fixture-image","prompt":"替换商品", + "protocol":{"field":"image[]","multipart":true,"parameters":{}}, + "references":[ + {"path":"reference-0.png","source":"pinned-template:image","role":"template-base","position":1,"size":[20,30]}, + {"path":"reference-1.jpg","source":"photo","role":"product","position":2,"size":[80,90]} + ]}); + let files = [b"base".to_vec(), b"photo".to_vec()]; + let payload = image_payload(&task, &files).unwrap(); + assert_eq!(payload["image[]"], json!([ + format!("data:image/png;base64,{}", STANDARD.encode(&files[0])), + format!("data:image/jpeg;base64,{}", STANDARD.encode(&files[1])) + ])); + assert_eq!(image_request_receipt(&task)["attachmentSources"], json!([ + {"source":"pinned-template:image","role":"template-base","position":1,"size":[20,30]}, + {"source":"photo","role":"product","position":2,"size":[80,90]} + ])); + } + struct CanvasPostFixture { dir: PathBuf, root: PathBuf,