From 7c89221b85fb8a67db0066c93fd8afff88fca9fe Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Mon, 30 Nov 2026 10:13:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E9=BD=90=E5=B0=8F=E5=A3=B9=E5=9B=BE?= =?UTF-8?q?=E4=BD=8D=E7=94=A8=E5=9B=BE=E6=9D=A5=E6=BA=90=E4=B8=8E=E7=94=BB?= =?UTF-8?q?=E9=9D=A2=E7=9B=B8=E4=BC=BC=E5=BA=A6=E5=9B=9E=E6=89=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/production-operations.mjs | 34 +- apps/detail-agent-pi/src/screen-review.mjs | 5 +- .../src/skills/product-image-sources/SKILL.md | 1 + .../test/screen-review.test.mjs | 26 +- .../src/jiansun_canvas_workspace.rs | 2 + .../apps/photocraft/src/jiansun_pi_runtime.rs | 2 + .../photocraft/src/jiansun_screen_preview.rs | 13 +- .../src/jiansun_slot_image_facts.rs | 361 ++++++++++++++++++ .../src/jiansun_template_fidelity.rs | 20 +- 9 files changed, 437 insertions(+), 27 deletions(-) create mode 100644 apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 46878ff9..22d653f7 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -127,7 +127,7 @@ export const productionOperationTools = [ ['adopt_production_image','采用选定的候选,返回画布修订和模板叠层。可用 reason 记录采用理由。单图位屏与已有验图画面一致时附复核结论。screensReadyForReview 列出图位已齐、待复核的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})], ['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})], ['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原请求已收口。网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或 180 秒恢复预算用完后原查询仍是 unresolved 或 404 request_not_found,都会进入此终态。404 request_not_found 收口时按未发起处理。expired 可以为同图位另备新请求;按未发起处理的请求不计入该图位的生图次数,其他已派发请求仍计入。',obj({...outputScope,slotIds:optional(ids)})], - ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry、annotationLayout 和 textClipping。textLayers 逐层返回样式差异、当前和模板的字形附近对比度 P10/P50(WCAG 公式)及底色亮度标准差,缺少样本时对应值为空。annotationLayout.dimensionGroups 按模板图层编号列出标签和线,subjectBoundsOffsets 为端点减去主体框左、上、右、下边界的坐标差。textClipping 列出越出当前屏的文字图层和墨迹边界矩形 [x,y,w,h]。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({ + ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry、annotationLayout 和 textClipping。slotImageFacts 逐图位列出已采用图片的 source(来源类别、候选或请求号、上游图位或实拍文件)、当前与模板图框的近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空),以及 nearest 中最多三个其它图位的成品、花色、屏号、sameOutput 和 64 位 dHash 汉明距离 distance(0–64,越小越相似)。textLayers 逐层返回样式差异、当前和模板的字形附近对比度 P10/P50(WCAG 公式)及底色亮度标准差,缺少样本时对应值为空。annotationLayout.dimensionGroups 按模板图层编号列出标签和线,subjectBoundsOffsets 为端点减去主体框左、上、右、下边界的坐标差。textClipping 列出越出当前屏的文字图层和墨迹边界矩形 [x,y,w,h]。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({ page:optional(page),pages:optional(Type.Array(page)), region:optional(Type.Tuple([Type.Integer(),Type.Integer(),Type.Integer({minimum:1}),Type.Integer({minimum:1})])), zoom:optional(Type.Number({minimum:1,maximum:4})), @@ -657,7 +657,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, })).progressSummary; let displayEpoch=0, progressVersion=0, progressSnapshot; const markProgressDirty=()=>{progressVersion++;}; - function saveOutputScreenReview({page,screenFingerprint,issues},signal,inputSignature,receipt){ + function saveOutputScreenReview({page,screenFingerprint,issues,slotImageFacts},signal,inputSignature,receipt){ return serialize(async()=>{ signal?.throwIfAborted(); const copyInputs=productionInputs(await current(),variantId); @@ -665,7 +665,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const snapshot=await copySnapshot({screenFingerprintPage:page}); if(!screenFingerprint||snapshot.screenFingerprint!==screenFingerprint)throw Error('本屏已变化,请读取当前画面'); signal?.throwIfAborted(); - await saveScreenCheck({page,screenFingerprint,issues,copyInputs,receipt}); + await saveScreenCheck({page,screenFingerprint,issues,copyInputs,receipt,slotImageFacts}); notice('整屏复核已记录'); }); } @@ -1820,24 +1820,18 @@ export async function openProductionOperations(host,{target=host.productionGoal, job.run=scheduleDelegate(activeSignal,async permit=>{ job.receipt={page,state:'checking'}; notice('正在按屏复核'); - const saved=new Map(journal.screenReviews??[]).get(page-1); - if(saved?.receipt && saved.screenFingerprint){ - const live=await current(); - const inputs=productionInputs(live,variantId); - if(saved.copyInputs===inputs){ - const snapshot=await onCanvas(activeSignal,()=>copySnapshot({screenFingerprintPage:page-1}),permit); - activeSignal.throwIfAborted(); - const requirements=fieldRequirements(live).filter(row=>row.page===snapshot.pages?.[page-1]); - if(snapshot.screenFingerprint===saved.screenFingerprint && - isDeepStrictEqual(requirements,saved.receipt.fieldRequirements??[])){ - job.receipt={...saved.receipt,revision:snapshot.revision,reused:true}; - return; - } - } - } const screen=await onCanvas(activeSignal,()=>operations.read_output_screen({page:page-1,includeTemplateImage:true},activeSignal),permit); + const {revision,screenFingerprint,screenChanged,fieldRequirements:requirements=[],slotImageFacts}=screen.details; const previous=new Map(journal.screenReviews??[]).get(page-1); - if(previous?.candidateReview && (!screen.details.templateFidelity || previous.candidateReview.templateEvidence) && !screen.details.screenChanged && + if(previous?.receipt && previous.screenFingerprint && !screenChanged && + previous.screenFingerprint===screenFingerprint && + isDeepStrictEqual(requirements,previous.receipt.fieldRequirements??[]) && + isDeepStrictEqual(slotImageFacts??[],previous.slotImageFacts??[]) && + previous.copyInputs===productionInputs(await current(),variantId)){ + job.receipt={...previous.receipt,revision,reused:true}; + return; + } + if(previous?.candidateReview && !slotImageFacts?.length && (!screen.details.templateFidelity || previous.candidateReview.templateEvidence) && !screen.details.screenChanged && previous.screenFingerprint===screen.details.screenFingerprint && previous.copyInputs===productionInputs(await current(),variantId)){ job.receipt={...previous.candidateReview,revision:screen.details.revision,...(screen.details.fieldRequirements?{fieldRequirements:screen.details.fieldRequirements}:null),reused:true}; @@ -1850,7 +1844,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, const {inputSignature}=await references(); const confirmed=screen.details.fieldRequirements?{...receipt,fieldRequirements:screen.details.fieldRequirements}:receipt; await onCanvas(activeSignal,()=>saveOutputScreenReview({ - page:page-1,screenFingerprint:receipt.screenFingerprint, + page:page-1,screenFingerprint:receipt.screenFingerprint,slotImageFacts, issues:[...receipt.imageIssues,...receipt.overlayFixes,...receipt.copyFixes], },activeSignal,inputSignature,confirmed),permit); job.receipt=confirmed; diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs index 51fd82ff..3e0096c8 100644 --- a/apps/detail-agent-pi/src/screen-review.mjs +++ b/apps/detail-agent-pi/src/screen-review.mjs @@ -141,7 +141,7 @@ export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity, } export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) { - const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,annotationLayout,fieldRequirements,templateFidelity,textClipping,textLayers,screenCopy=[]} = screen.details; + const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,annotationLayout,fieldRequirements,templateFidelity,textClipping,textLayers,slotImageFacts,screenCopy=[]} = screen.details; const images = screen.content.filter(item => item.type === 'image'); if (!screenFingerprint || ![1,2].includes(images.length)) throw Error('未读取到当前屏的实际画面和内容指纹'); if (screenChanged) throw Error('读取画面后本屏已变化,请复查当前屏'); @@ -177,12 +177,13 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,原生标注也可引用 annotationLayout 或 textClipping 中的编号,正文问题填写 screenCopy 中的 field。', '每项问题只引用一个编号,从本屏对应清单原样复制。一个问题涉及多个字段时逐项填写。找不到对应图位、叠层或文案字段时,省略编号并用 location 描述画面位置。', OVERLAY_SCREEN_FIELDS, + 'slotImageFacts 逐图位列出已采用图片的 source(来源类别、候选或请求号、上游图位或实拍文件)、当前与模板图框的近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空),以及 nearest 中最多三个其它图位的成品、花色、屏号、sameOutput 和 64 位 dHash 汉明距离 distance(0–64,越小越相似)。', 'textLayers 按原生图层号列出文字与模板原图层不同的样式(styleDifferences),以及字形附近的对比度和底色明暗波动(readability 为当前画面,templateReadability 为模板原屏同一图层)。', TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), SCREEN_REVIEW_REQUIREMENTS, ].join('\n'); const prompt = JSON.stringify({page,revision,product,slots:numberScreenSlots(slots),slotGeometry,annotationLayout, - screenCopy:numberScreenCopy(screenCopy),fieldRequirements,overlayLayers,overlayGroups,templateFidelity,textClipping,textLayers,productReferenceCount:photos.length}); + screenCopy:numberScreenCopy(screenCopy),fieldRequirements,overlayLayers,overlayGroups,templateFidelity,textClipping,textLayers,slotImageFacts,productReferenceCount:photos.length}); const captions = ['当前整屏成片', ...(images.length===2?['模板原屏']:[]), ...photos.map((_,index) => `本款实拍 ${index + 1}`)]; await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal); signal?.throwIfAborted(); 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 76e5cc6c..06cbc9ea 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 @@ -21,6 +21,7 @@ maxGenerationAttempts: 4 ## 画布回执 - `read_output_screen` 返回合成画面与图层差异。`page` 从 0 开始,`region` 为画布像素坐标 `[x,y,w,h]`,`zoom` 为 1–4 倍。网格刻度使用原画布坐标。`includeTemplateImage` 返回原屏,`templateLayerId` 返回指定图层的完整原值与现值。 +- `slotImageFacts` 描述本屏已采用图位。`source.kind` 分为 `generation`、`transform`、`reused`、`product-reference` 和 `unrecorded`。`candidateId`、`requestId` 分别是采用候选号和对应生图请求号。`sourceCandidateId`、`sourceProjectId`、`sourceSlotId`、`sourceOutputId` 标识上游候选、工程、图位和模板输出。`photoSource`、`photoName` 是实拍文件引用和名称。`nearest` 列出最多三个相近的其它采用图位,包含成品、花色、从零计数的页码和 `sameOutput`。`distance` 是 64 位 dHash 的汉明距离,越小越相似。`nearWhiteFlatRatio` 和 `templateNearWhiteFlatRatio` 是当前和模板图框合成取样中近白且局部平坦的像素比例,范围 0–1。取样像素的 RGB 各通道至少为 235,且与上下左右相邻像素的各通道差不超过 8。`templateRatioSource: "original-screen-preview"` 表示从已存模板原屏预览取样。缺样本时比例为空。 - `canvasFacts` 描述图层与画布关系。`outsideCanvas` 为 true 表示完全在画布外,`emptyBounds` 为 true 表示边界为空。`layerVisible` 是图层自身的可见性,`ancestorsVisible` 是祖先图层的可见性。 - `overlayLayers` 中的 `group` 是直属组,`overlayGroups` 列出各组的本屏成员 ID。`knots` 是形状锚点数,`subjectHit` 表示标注框与估测主体框是否相交。`belowSlot` 按 `fieldId` 列出上方图位,`coverage` 是图位覆盖屏内图层边界的比例,`opacity` 和 `blendMode` 是图位内容的不透明度和混合模式。 - `annotationLayout.dimensionGroups` 按模板的 dimensionGuides 列出标签、线及源图层编号。各线的 subjectBoundsOffsets 按图位列出端点相对主体包围盒左、上、右、下边界的有符号像素差。 diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs index ac007f9b..0bf4921f 100644 --- a/apps/detail-agent-pi/test/screen-review.test.mjs +++ b/apps/detail-agent-pi/test/screen-review.test.mjs @@ -93,7 +93,7 @@ async function fixture(t) { const pages=Array.from({length:18},(_,i)=>`P${i+1}`); const fields=pages.map((page,i)=>({page,layer:100+i,field:`title-${i+1}`,currentText:'橡胶木桌面'})); const slots=pages.map((documentId,i)=>({documentId,id:`slot-${i+1}`,fieldId:`pic-${i+1}`,selectedCandidateId:'candidate'})); - const state={revision:7,overlay:true,reads:[],referenceReads:0,colorName:'深木色', + const state={revision:7,overlay:true,reads:[],referenceReads:0,colorName:'深木色',slotImageFacts:undefined, fingerprints:pages.map(page=>`screen-${page}`)}; const summaryFor=(reviews=[])=>({ screensWithOpenIssues:reviews.filter(row=>row.issues?.length&&row.screenFingerprint===state.fingerprints[row.page-1]), @@ -126,6 +126,7 @@ async function fixture(t) { if(page>=pages.length)throw Error('此屏不属于当前工作画布'); return {page,revision:state.revision,screenFingerprint:state.fingerprints[page],images:[pixels],fields:[slots[page].fieldId], textClipping:[{nativeLayerId:600+page,clippedInkBounds:[[100,20,7,14]]}], + slotImageFacts:state.slotImageFacts, textLayers:[{nativeLayerId:700+page,styleDifferences:{fillColor:{template:'#ffffff',current:'#333333'}}, readability:{contrastP10:1.4,contrastP50:2.1},templateReadability:{contrastP10:3.2,contrastP50:4.6}}], annotationLayout:{lines:[{nativeLayerId:501+page,endpoints:[[10,20],[10,80]]}]}, @@ -220,7 +221,7 @@ test('同屏同商品资料复用整屏助手的完整回执,屏指纹或资 state.revision++; assert.deepEqual(await check(),{...first,revision:state.revision,reused:true}); assert.equal(reviews,1); - assert.deepEqual(state.reads,[0]); + assert.deepEqual(state.reads,[0,0]); assert.equal(state.referenceReads,1); state.fingerprints[0]='changed'; assert.equal((await check()).screenFingerprint,'changed'); @@ -231,6 +232,23 @@ test('同屏同商品资料复用整屏助手的完整回执,屏指纹或资 await actions.close(); }); +test('其它成品采用图变化时,整屏复核使用最新相似度', async t=>{ + const {host,actions,state}=await fixture(t); + const distances=[]; + host.runDetailAgent=async(_id,_system,input,[tool])=>{ + distances.push(JSON.parse(input).slotImageFacts[0].nearest[0].distance); + await tool.execute('',pass); + }; + const check=async()=> (await actions.check_output_screens({pages:[1]}))[0]; + state.slotImageFacts=[{slotId:'slot-1',nearest:[{slotId:'main-1',sameOutput:false,distance:22}]}]; + assert.equal((await check()).verdict,'pass'); + assert.equal((await check()).reused,true); + state.slotImageFacts=[{slotId:'slot-1',nearest:[{slotId:'main-1',sameOutput:false,distance:4}]}]; + assert.equal((await check()).reused,undefined); + assert.deepEqual(distances,[22,4]); + await actions.close(); +}); + test('多图位屏齐备后在采纳与验图回执提示,当前画面复核后清除提示', async t=>{ const {host,actions,state,slots}=await fixture(t); slots[1].documentId='P1'; @@ -283,8 +301,10 @@ test('非当前成品的候选等待验图时直接读取其已保存画布', {t test('screen reviews keep images in the worker and persist findings and passes',async t=>{ const {host,state,journal}=await fixture(t); + state.slotImageFacts=[{slotId:'slot', source:{kind:'generation',requestId:'request'},nearest:[],nearWhiteFlatRatio:0.2,templateNearWhiteFlatRatio:0.1}]; host.runDetailAgent=async(_id,system,input,[tool],images,scope)=>{ - const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout,textClipping,textLayers}=JSON.parse(input); + const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout,textClipping,textLayers,slotImageFacts}=JSON.parse(input); + assert.deepEqual(slotImageFacts,state.slotImageFacts); assert.deepEqual(textClipping,[{nativeLayerId:599+page,clippedInkBounds:[[100,20,7,14]]}]); assert.deepEqual(textLayers.map(row=>[row.nativeLayerId,row.styleDifferences.fillColor.current]),[[699+page,'#333333']]); assert.deepEqual(annotationLayout.lines,[{nativeLayerId:500+page,endpoints:[[10,20],[10,80]]}]); 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 98178802..081e0817 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3039,6 +3039,8 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: #[path = "jiansun_screen_preview.rs"] mod screen_preview; +#[path = "jiansun_slot_image_facts.rs"] +mod slot_image_facts; #[path = "jiansun_text_readability.rs"] mod text_readability; pub(super) use screen_preview::ScreenReader; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index a5b339b9..587e156a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -855,6 +855,8 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender, ctx: } else { let mut receipt = reader.read(&document, &v)?; if v["templateComparison"] == true { + let dir = backend.project_dir(document.id.0)?; + reader.read_slot_image_facts(&dir, &document, &mut receipt); backend.attach_template_fidelity(&document, &mut receipt, v["includeTemplateImage"] == true, v["templateLayerId"].as_u64())?; } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs index 3fcc4b4e..2fa38d08 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_screen_preview.rs @@ -19,7 +19,10 @@ const SCREEN_CACHE_CAPACITY: usize = 4; /// Reuse recent screen images during a Pi run, keyed by the immutable canvas snapshot. #[derive(Default)] -pub(in crate::jiansun_backend) struct ScreenReader(Mutex>); +pub(in crate::jiansun_backend) struct ScreenReader( + Mutex>, + super::slot_image_facts::SlotImageReader, +); impl ScreenReader { pub(in crate::jiansun_backend) fn read(&self, native: &Arc, input: &Value) -> R { @@ -45,6 +48,14 @@ impl ScreenReader { Ok(receipt) } + pub(in crate::jiansun_backend) fn read_slot_image_facts( + &self, dir: &std::path::Path, native: &Arc, receipt: &mut Value, + ) { + if receipt["images"].is_array() { + self.1.read(dir, native, receipt); + } + } + fn jpeg(&self, native: &Arc, area: Rect) -> R>> { let document = Arc::downgrade(native); let text_gamma = photocraft_compose::psblend::text_gamma().to_bits(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs new file mode 100644 index 00000000..ad052eee --- /dev/null +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs @@ -0,0 +1,361 @@ +use super::*; +use image::{GrayImage, RgbImage, imageops}; +use photocraft_doc::{Layer, LayerContent, LayerId, SmartSource}; +use photocraft_geom::Rect; +use photocraft_ui_egui::jiansun::production_facts::{layer_frame, path_visible}; +use std::{ + collections::HashMap, + sync::{Mutex, Weak}, + time::SystemTime, +}; + +const SAMPLE_WIDTH: u32 = 72; +const SAMPLE_HEIGHT: u32 = 64; + +fn measure(pixels: &RgbImage) -> (u64, f64) { + let gray = image::DynamicImage::ImageRgb8(pixels.clone()).into_luma8(); + let small: GrayImage = imageops::resize(&gray, 9, 8, imageops::FilterType::Triangle); + let mut hash = 0; + for y in 0..8 { + for x in 0..8 { + hash = (hash << 1) | u64::from(small[(x, y)][0] > small[(x + 1, y)][0]); + } + } + let mut white = 0; + let (w, h) = pixels.dimensions(); + for y in 1..h - 1 { + for x in 1..w - 1 { + let center = pixels[(x, y)].0; + if center.iter().all(|&c| c >= 235) + && [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] + .into_iter() + .all(|pos| pixels[pos].0.into_iter().zip(center).all(|(a, b)| a.abs_diff(b) <= 8)) + { + white += 1; + } + } + } + (hash, (1000.0 * f64::from(white) / f64::from((w - 2) * (h - 2))).round() / 1000.0) +} + +fn mapped_frame(field: &Value) -> Option { + let frame = &field["frame"]; + let coord = |key: &str| frame[key].as_f64().map(|n| n.round() as i32); + let width = u32::try_from(coord("width")?).ok()?; + let height = u32::try_from(coord("height")?).ok()?; + Some(Rect::from_xywh(coord("x")?, coord("y")?, width, height)) +} + +fn slot_layer<'a>(doc: &'a Document, field: &Value) -> Option<&'a Layer> { + let path = doc.path_of(LayerId(field["nativeLayerId"].as_u64()?))?; + if !path_visible(doc, &path) { + return None; + } + doc.layer_at(&path) +} + +fn slot_pixels(doc: &Document, area: Rect, field: &Value, layer: &Layer) -> Option { + let frame = mapped_frame(field).unwrap_or_else(|| layer_frame(doc, layer)).intersect(&area); + if frame.is_empty() { + return None; + } + // Use the same compositing path as the screen preview, preserving mask, + // placement and native retouch within the actual frame. + let rendered = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, frame, SAMPLE_WIDTH.min(frame.width()), SAMPLE_HEIGHT.min(frame.height())); + let rgb = + rendered.px.into_iter().flat_map(|[r, g, b, alpha]| [r, g, b].map(|c| ((c * alpha + 1.0 - alpha).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = RgbImage::from_raw(rendered.rect.width(), rendered.rect.height(), rgb)?; + if image.dimensions() == (SAMPLE_WIDTH, SAMPLE_HEIGHT) { + return Some(image); + } + Some(imageops::resize(&image, SAMPLE_WIDTH, SAMPLE_HEIGHT, imageops::FilterType::Triangle)) +} + +pub(super) fn template_ratios(doc: &Document, page: &Value, area: Rect) -> Value { + let ratios: serde_json::Map = fields(page) + .filter_map(|field| { + let id = field["slotId"].as_str()?; + let pixels = slot_pixels(doc, area, field, slot_layer(doc, field)?)?; + Some((id.to_owned(), json!(measure(&pixels).1))) + }) + .collect(); + Value::Object(ratios) +} + +pub(super) fn preview_ratios(bytes: &[u8], page: &Value, area: Rect) -> Option { + let decoded = photocraft_codecs::decode(bytes).ok()?.convert(photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8); + let (width, height) = decoded.dimensions(); + let image = RgbImage::from_raw(width, height, decoded.data().to_vec())?; + let ratios: serde_json::Map = fields(page) + .filter_map(|field| { + let id = field["slotId"].as_str()?; + let rect = mapped_frame(field)?.intersect(&area); + if rect.is_empty() { + return None; + } + let x = |n| ((n - area.x0) as f64 * f64::from(image.width()) / f64::from(area.width())).round() as u32; + let y = |n| ((n - area.y0) as f64 * f64::from(image.height()) / f64::from(area.height())).round() as u32; + let (left, top, right, bottom) = (x(rect.x0), y(rect.y0), x(rect.x1), y(rect.y1)); + if right <= left || bottom <= top { + return None; + } + let crop = imageops::crop_imm(&image, left, top, right - left, bottom - top).to_image(); + let pixels = imageops::resize(&crop, SAMPLE_WIDTH, SAMPLE_HEIGHT, imageops::FilterType::Triangle); + Some((id.to_owned(), json!(measure(&pixels).1))) + }) + .collect(); + Some(Value::Object(ratios)) +} + +fn fields(page: &Value) -> impl Iterator { + page["mapping"]["fields"].as_array().into_iter().flatten().filter(|field| field["kind"] == "image") +} + +fn lineage(record: &Value, parent: &Value) -> Value { + let transform = &record["canvasTransform"]; + let reused = &record["reusedFrom"]; + let photo = record["sourceType"] == "product-reference"; + let kind = if transform.is_object() || record["binding"]["referenceCrop"].is_array() { + "transform" + } else if reused.is_object() { + "reused" + } else if photo { + "product-reference" + } else if record["requestId"].is_string() { + "generation" + } else { + "unrecorded" + }; + let mut source = json!({"kind":kind,"candidateId":record["id"]}); + for (key, value) in [ + ("requestId", record.get("requestId").filter(|id| id.is_string()).unwrap_or(&record["sourceRequestId"])), + ("sourceCandidateId", transform.get("sourceCandidateId").filter(|id| id.is_string()).unwrap_or(&reused["candidateId"])), + ("sourceProjectId", &reused["projectId"]), + ("sourceSlotId", &parent["binding"]["slotId"]), + ("sourceOutputId", &parent["binding"]["outputId"]), + ("photoSource", if photo { &record["references"][0]["source"] } else { &Value::Null }), + ("photoName", if photo { &record["references"][0]["name"] } else { &Value::Null }), + ] { + if !value.is_null() { + source[key] = value.clone(); + } + } + source +} + +fn slot_source(dir: &Path, layer: &Layer, candidate: &str, slot: &Value) -> Value { + let record = read_candidate(dir, candidate).ok().filter(|record| { + if !candidate_available(record) || record["binding"]["slotId"] != *slot { + return false; + } + let LayerContent::Smart(smart) = &layer.content else { return false }; + let SmartSource::Embedded { file_name, bytes } = &smart.source else { return false }; + file_name == "candidate.png" && matches_placed_candidate(dir, &record["artifact"], bytes) + }); + let Some(record) = record else { return json!({"kind":"unrecorded"}) }; + let origin = &record["reusedFrom"]; + let parent = origin["candidateId"] + .as_str() + .and_then(|id| { + if record["canvasTransform"].is_object() { + return read_candidate(dir, id).ok(); + } + let project = uuid(&origin["projectId"], "项目").ok()?; + read_candidate(&dir.parent()?.join(project), id).ok() + }) + .unwrap_or_default(); + lineage(&record, &parent) +} + +struct Slot { + hash: u64, + near_white: f64, + identity: Value, + candidate: String, + layer_id: LayerId, +} + +fn canvas_slots(doc: &Document, meta: &Value) -> Vec { + let Some(variant) = meta["variantId"].as_str() else { return Vec::new() }; + let mut slots = Vec::new(); + for (index, page) in meta["outputs"].as_array().into_iter().flatten().enumerate() { + let Ok(area) = screen_area(doc.bounds(), page) else { continue }; + for field in fields(page) { + let Some(slot) = field["slotId"].as_str() else { continue }; + let marker = format!("jiansun.adopted.{variant}.{slot}"); + let Some((_, candidate)) = doc.metadata.text.iter().find(|(key, _)| key == &marker) else { continue }; + let Some(layer) = slot_layer(doc, field) else { continue }; + let Some(pixels) = slot_pixels(doc, area, field, layer) else { continue }; + let (hash, near_white) = measure(&pixels); + let identity = json!({"slotId":slot,"fieldId":field["fieldId"],"outputId":meta["component"], + "variantId":variant,"documentId":meta["documentId"],"page":index}); + slots.push(Slot { hash, near_white, identity, candidate: candidate.clone(), layer_id: layer.id }); + } + } + slots +} + +#[derive(Default)] +struct ProjectSamples { + active: Weak, + slots: Vec, + saved: HashMap)>, +} + +// Cache small measurements, without keeping the other output canvases in memory. +#[derive(Default)] +pub(super) struct SlotImageReader(Mutex); + +impl SlotImageReader { + pub(super) fn read(&self, dir: &Path, doc: &Arc, receipt: &mut Value) { + let Some(meta) = mapping(doc) else { return }; + let Some(page) = receipt["page"].as_u64() else { return }; + let Ok(mut samples) = self.0.lock() else { return }; + let key = mapping_key(meta["variantId"].as_str().unwrap_or_default(), meta["component"].as_str().unwrap_or_default(), meta["documentId"].as_str()); + let active = Arc::downgrade(doc); + if !active.ptr_eq(&samples.active) { + samples.slots = canvas_slots(doc, &meta); + samples.active = active; + } + if !samples.slots.iter().any(|slot| slot.identity["page"] == page) { + receipt["slotImageFacts"] = json!([]); + return; + } + let state = load_detail_workspace(dir).ok(); + let files: HashMap<_, _> = state + .as_ref() + .and_then(|state| state["mappings"].as_object()) + .into_iter() + .flatten() + .filter(|(other, _)| *other != &key) + .map(|(key, _)| dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"))) + .filter_map(|file| Some((file.clone(), fs::metadata(&file).ok()?.modified().ok()?))) + .collect(); + samples.saved.retain(|file, (stamp, _)| files.get(file) == Some(stamp)); + for (file, stamp) in files { + if samples.saved.contains_key(&file) { + continue; + } + let Ok(other) = super::super::load_draft(dir, &file) else { continue }; + let Some(other_meta) = mapping(&other).filter(|other| other["workspaceId"] == meta["workspaceId"]) else { continue }; + samples.saved.insert(file, (stamp, canvas_slots(&other, &other_meta))); + } + let others = samples.saved.values().flat_map(|(_, slots)| slots); + receipt["slotImageFacts"] = json!( + samples + .slots + .iter() + .filter(|slot| slot.identity["page"] == page) + .map(|slot| { + let source = doc + .layer(slot.layer_id) + .map_or_else(|| json!({"kind":"unrecorded"}), |layer| slot_source(dir, layer, &slot.candidate, &slot.identity["slotId"])); + json!({"slotId":slot.identity["slotId"],"source":source,"nearWhiteFlatRatio":slot.near_white, + "templateNearWhiteFlatRatio":null,"nearest":nearest(slot, &samples.slots, others.clone())}) + }) + .collect::>() + ); + } +} + +fn nearest<'a>(slot: &Slot, current: &'a [Slot], others: impl Iterator) -> Vec { + let mut ranked: Vec<_> = current + .iter() + .filter(|other| other.identity["slotId"] != slot.identity["slotId"]) + .map(|other| (false, other)) + .chain(others.map(|other| (true, other))) + .map(|(cross, other)| ((slot.hash ^ other.hash).count_ones(), cross, other)) + .collect(); + ranked.sort_by(|(da, ca, a), (db, cb, b)| (da, ca, a.identity["slotId"].as_str()).cmp(&(db, cb, b.identity["slotId"].as_str()))); + let mut selected: Vec<_> = ranked.iter().take(3).copied().collect(); + if let Some((_, first, _)) = selected.first() + && selected.iter().all(|(_, cross, _)| cross == first) + && let Some(alternate) = ranked.iter().find(|(_, cross, _)| cross != first) + { + if selected.len() == 3 { + selected.pop(); + } + selected.push(*alternate); + } + selected + .into_iter() + .map(|(distance, cross, other)| { + let mut identity = other.identity.clone(); + identity["distance"] = json!(distance); + identity["sameOutput"] = json!(!cross); + identity + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn jiansun_slot_distance_and_near_white_background() { + let scene = |reverse| { + RgbImage::from_fn(72, 64, |x, y| { + let light = if reverse { 71 - x } else { x } * 2 + y; + image::Rgb([light as u8, 80, 60]) + }) + }; + let original = scene(false); + let mut similar = original.clone(); + similar[(30, 30)][0] += 8; + let (hash, room) = measure(&original); + assert!((hash ^ measure(&similar).0).count_ones() <= 2); + assert!((hash ^ measure(&scene(true)).0).count_ones() >= 48); + assert_eq!(room, 0.0); + let white = RgbImage::from_pixel(72, 64, image::Rgb([250, 250, 250])); + assert_eq!(measure(&white).1, 1.0); + } + + #[test] + fn jiansun_slot_nearest_covers_both_outputs_with_three_rows() { + let slot = |id, hash| Slot { hash, near_white: 0.0, identity: json!({"slotId":id}), candidate: String::new(), layer_id: LayerId(1) }; + let current = [slot("S05", 0), slot("S04", 1), slot("S06", 3), slot("S07", 7)]; + let other = [slot("M02", 15), slot("M03", 255)]; + let rows = nearest(¤t[0], ¤t, other.iter()); + assert_eq!( + rows, + [ + json!({"slotId":"S04","distance":1,"sameOutput":true}), + json!({"slotId":"S06","distance":2,"sameOutput":true}), + json!({"slotId":"M02","distance":4,"sameOutput":false}), + ] + ); + } + + #[test] + fn jiansun_slot_pixels_use_the_visible_frame_after_placement() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + use photocraft_doc::Size; + use photocraft_raster::Surface; + let mut doc = Document::new("test", Size::new(180, 100), ColorMode::Rgb, SampleType::U8); + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.fill_rect(Rect::from_xywh(0, 0, 90, 100), &[1.0, 1.0, 1.0, 1.0]); + surface.fill_rect(Rect::from_xywh(90, 0, 90, 100), &[0.3, 0.2, 0.1, 1.0]); + doc.layers.push(Layer::new("photo", LayerContent::Raster(surface))); + let layer = &doc.layers[0]; + let field = |x| json!({"nativeLayerId":layer.id.0,"frame":{"x":x,"y":0,"width":90,"height":100}}); + assert_eq!(measure(&slot_pixels(&doc, doc.bounds(), &field(0), layer).unwrap()).1, 1.0); + assert_eq!(measure(&slot_pixels(&doc, doc.bounds(), &field(90), layer).unwrap()).1, 0.0); + } + + #[test] + fn jiansun_slot_lineage_distinguishes_four_sources() { + let parent = json!({"binding":{"slotId":"S04","outputId":"details"}}); + assert_eq!(lineage(&json!({"id":"gen","requestId":"req"}), &Value::Null), json!({"kind":"generation","candidateId":"gen","requestId":"req"})); + let crop = lineage(&json!({"id":"crop","canvasTransform":{"sourceCandidateId":"gen"},"sourceRequestId":"req"}), &parent); + assert_eq!(crop["kind"], "transform"); + assert_eq!(crop["sourceSlotId"], "S04"); + assert_eq!(crop["sourceCandidateId"], "gen"); + let reuse = lineage(&json!({"id":"reuse","reusedFrom":{"projectId":"project","candidateId":"gen"}}), &parent); + assert_eq!(reuse["kind"], "reused"); + assert_eq!(reuse["sourceSlotId"], "S04"); + let photo = json!({"id":"photo","sourceType":"product-reference","references":[{"source":"local:photo"}]}); + assert_eq!(lineage(&photo, &Value::Null)["photoSource"], "local:photo"); + assert_eq!(lineage(&photo, &Value::Null)["kind"], "product-reference"); + } +} diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_fidelity.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_fidelity.rs index 0721c5a2..9fdcc5e9 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_fidelity.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_fidelity.rs @@ -50,7 +50,8 @@ pub(super) fn capture(dir: &Path, doc: &Document, meta: &Value) -> R<()> { }).collect(); let image = screen_preview::render_at_limit(doc, area, 1024.0)?; let baseline_path = path(dir, meta, index); - write_json(&baseline_path, &json!({"templateHash":meta["templateHash"],"layers":rows}))?; + write_json(&baseline_path, &json!({"templateHash":meta["templateHash"],"layers":rows, + "slotNearWhiteFlatRatios":super::slot_image_facts::template_ratios(doc, page, area)}))?; photocraft_format::atomic_write(&baseline_path.with_extension("jpg"), &image) .map_err(|error| error.to_string())?; } @@ -111,6 +112,23 @@ pub(super) fn attach(dir: &Path, doc: &Document, receipt: &mut Value, include_im receipt["templateFidelity"] = compare(doc, &baseline, &meta); attach_text_comparison(doc, receipt, &baseline["layers"]); let original_path = baseline_path.with_extension("jpg"); + let mut ratios = baseline["slotNearWhiteFlatRatios"].clone(); + let from_preview = ratios.is_null() && receipt["slotImageFacts"].as_array().is_some_and(|rows| !rows.is_empty()); + if from_preview && let Some(mapped_page) = meta["outputs"].get(page as usize) + && let Ok(area) = screen_area(doc.bounds(), mapped_page) + && let Ok(bytes) = fs::read(&original_path) + { + ratios = super::slot_image_facts::preview_ratios(&bytes, mapped_page, area).unwrap_or_default(); + } + for row in receipt["slotImageFacts"].as_array_mut().into_iter().flatten() { + if let Some(id) = row["slotId"].as_str() { + let ratio = &ratios[id]; + row["templateNearWhiteFlatRatio"] = ratio.clone(); + if from_preview && ratio.is_number() { + row["templateRatioSource"] = json!("original-screen-preview"); + } + } + } if original_path.is_file() { receipt["templateFidelity"]["originalImage"] = json!(true); }