feat(xiaoyi): trace delivered image fields to their source archives
This commit is contained in:
parent
1842111361
commit
33652b5747
@ -2416,9 +2416,45 @@ fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_ed
|
||||
}).collect()
|
||||
}
|
||||
|
||||
fn missing_export_images(dir: &Path, doc: &Document, state: &Value, meta: &Value, component: &str, variant: &str) -> Vec<String> {
|
||||
fn candidate_export_source(dir: &Path, record: &Value) -> Value {
|
||||
let candidate_id = record["id"].as_str().unwrap_or_default();
|
||||
let archive = format!("image-jobs/{candidate_id}");
|
||||
let task_record = format!("{archive}/task.json");
|
||||
let task = read_json(&dir.join(&task_record)).ok()
|
||||
.filter(|task| task["id"] == record["id"] && task["slotBinding"] == record["binding"]);
|
||||
let mut source = json!({
|
||||
"candidateId":candidate_id,"materialTaskId":material_task_id(record),
|
||||
"candidateRecord":format!("{archive}/{CANDIDATE}"),"candidateArtifact":record["artifact"],"kind":"unrecorded",
|
||||
});
|
||||
if task.is_some() {
|
||||
source["taskRecord"] = json!(task_record);
|
||||
}
|
||||
if record["sourceType"] == "archived-candidate" {
|
||||
source["kind"] = json!("reused");
|
||||
source["reusedFrom"] = record["reusedFrom"].clone();
|
||||
source["requestId"] = record["sourceRequestId"].clone();
|
||||
} else if record["sourceType"] == "product-reference" {
|
||||
source["kind"] = json!("product-reference");
|
||||
if let Some(crop) = record["binding"].get("referenceCrop") {
|
||||
source["referenceCrop"] = crop.clone();
|
||||
}
|
||||
} else if let Some(task) = task {
|
||||
source["kind"] = json!(if task["sceneComposite"].is_object() { "scene-composite" } else { "generation" });
|
||||
source["requestId"] = task["requestId"].clone();
|
||||
if dir.join(&archive).join("response.json").is_file() {
|
||||
source["responseRecord"] = json!(format!("{archive}/response.json"));
|
||||
}
|
||||
if task["sceneComposite"].is_object() && dir.join(&archive).join("scene-product.png").is_file() {
|
||||
source["compositeProduct"] = json!(format!("{archive}/scene-product.png"));
|
||||
}
|
||||
}
|
||||
source
|
||||
}
|
||||
|
||||
fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value, component: &str, variant: &str) -> (Vec<String>, Vec<Value>) {
|
||||
use photocraft_doc::{LayerContent, LayerId, SmartSource};
|
||||
let mut missing = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
let template = &state["template"];
|
||||
let current_input = input_hash(dir, state, variant).ok();
|
||||
for page in template["outputs"].as_array().into_iter().flatten().filter(|page| page["component"] == component) {
|
||||
@ -2435,16 +2471,32 @@ fn missing_export_images(dir: &Path, doc: &Document, state: &Value, meta: &Value
|
||||
&& record["binding"]["variantId"] == variant
|
||||
&& record["inputHash"].as_str().is_none_or(|input|
|
||||
!input.starts_with(VARIANT_INPUT_HASH) || current_input.as_deref() == Some(input)));
|
||||
let matches = layer_path.zip(record).is_some_and(|(path, record)| {
|
||||
(1..=path.len()).all(|len| doc.layer_at(&path[..len]).is_some_and(|layer| layer.visible && layer.opacity > 0.0))
|
||||
&& doc.layer_at(&path).is_some_and(|layer| matches!(&layer.content, LayerContent::Smart(smart)
|
||||
if matches!(&smart.source, SmartSource::Embedded {file_name, bytes}
|
||||
if file_name == "candidate.png" && matches_placed_candidate(dir, &record["artifact"], bytes))))
|
||||
let found = layer_path.zip(record).and_then(|(path, record)| {
|
||||
if !(1..=path.len()).all(|len| doc.layer_at(&path[..len]).is_some_and(|layer| layer.visible && layer.opacity > 0.0)) {
|
||||
return None;
|
||||
}
|
||||
let layer = doc.layer_at(&path)?;
|
||||
let LayerContent::Smart(smart) = &layer.content else { return None; };
|
||||
let SmartSource::Embedded { file_name, bytes } = &smart.source else { return None; };
|
||||
if file_name != "candidate.png" || !matches_placed_candidate(dir, &record["artifact"], bytes) {
|
||||
return None;
|
||||
}
|
||||
let mut source = candidate_export_source(dir, &record);
|
||||
source["pageId"] = page["id"].clone();
|
||||
source["fieldId"] = json!(id);
|
||||
source["slotId"] = json!(slot);
|
||||
source["nativeLayerId"] = json!(layer.id.0);
|
||||
source["embeddedSize"] = json!(creation::png_size(bytes).ok());
|
||||
Some(source)
|
||||
});
|
||||
if !matches { missing.push(id.to_owned()); }
|
||||
if let Some(source) = found {
|
||||
sources.push(source);
|
||||
} else {
|
||||
missing.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
missing
|
||||
(missing, sources)
|
||||
}
|
||||
|
||||
fn unverified_export_copy(
|
||||
@ -2641,6 +2693,7 @@ fn publish_product_generation(
|
||||
|| reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text {
|
||||
return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into());
|
||||
}
|
||||
let exported_mapping = mapping(&reopened);
|
||||
let save_region = |name: &str, role: &str, (top, width, height): (u64, u64, u64), bytes: Vec<u8>| -> R<Value> {
|
||||
let file = generation.path().join(name);
|
||||
photocraft_format::atomic_write(&file, &bytes).map_err(|error| format!("{name} 写入失败:{error}"))?;
|
||||
@ -2650,8 +2703,16 @@ fn publish_product_generation(
|
||||
{
|
||||
return Err(format!("{name} 内容或尺寸与导出结果不一致"));
|
||||
}
|
||||
Ok(json!({"path":file,"format":"jpg","role":role,"generationId":id,"top":top,"width":width,"height":height,
|
||||
"sizeBytes":saved.len(),"sha256":format!("{:x}",Sha256::digest(&saved))}))
|
||||
let mut artifact = json!({"path":file,"format":"jpg","role":role,"generationId":id,"top":top,"width":width,"height":height,
|
||||
"sizeBytes":saved.len(),"sha256":format!("{:x}",Sha256::digest(&saved))});
|
||||
if role != "detail"
|
||||
&& let Some(page) = exported_mapping.as_ref().and_then(|meta| meta["outputs"].as_array())
|
||||
.and_then(|pages| pages.iter().find(|page| page["top"] == top && page["width"] == width && page["height"] == height))
|
||||
&& let Some(page_id) = page["documentId"].as_str()
|
||||
{
|
||||
artifact["pageId"] = json!(page_id);
|
||||
}
|
||||
Ok(artifact)
|
||||
};
|
||||
let (files, split) = if let [region @ (0, width, height)] = regions && !screens.is_empty() {
|
||||
if screens.iter().any(|&(top, w, h)| w > *width || top.checked_add(h).is_none_or(|end| end > *height)) {
|
||||
@ -2745,7 +2806,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
} else {
|
||||
result["warnings"] = json!([production_profile::UNPUBLISHED_FIXED_TEXT]);
|
||||
}
|
||||
let missing = missing_export_images(dir, native, state, &meta, component, &variant_id);
|
||||
let (missing, image_sources) = export_image_sources(dir, native, state, &meta, component, &variant_id);
|
||||
if !missing.is_empty() {
|
||||
result["missingImages"] = json!(missing);
|
||||
return Ok(result);
|
||||
@ -2781,6 +2842,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
result["briefRevision"] = creation["revision"].clone();
|
||||
result["stageInputHash"] = json!(stage_input_hash(state, &creation, &variant_id, component)?);
|
||||
result["templateHash"] = state["template"]["contentHash"].clone();
|
||||
result["imageSources"] = json!(image_sources);
|
||||
let blank_reasons: serde_json::Map<String, Value> = journal["copyEvidence"].as_object().into_iter().flatten()
|
||||
.filter(|(_, row)| row["text"].as_str().is_some_and(|text| text.trim().is_empty()))
|
||||
.filter_map(|(id, row)| {
|
||||
@ -4255,6 +4317,137 @@ mod tests {
|
||||
.iter().any(|stage| stage["outputId"] == "detail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires copies of real completed ordinary and scene archives"]
|
||||
fn actual_archive_routes_are_traceable_from_native_delivery_files() {
|
||||
let evidence = PathBuf::from(std::env::var_os("JIANSUN_TRACE_TEST_ROOT").unwrap());
|
||||
for (kind, env) in [("generation", "JIANSUN_TRACE_ORDINARY_JOB"), ("scene-composite", "JIANSUN_TRACE_SCENE_JOB")] {
|
||||
let original_job = PathBuf::from(std::env::var_os(env).unwrap());
|
||||
let original_project = original_job.parent().unwrap().parent().unwrap();
|
||||
let original_id = original_job.file_name().unwrap().to_str().unwrap();
|
||||
let original = read_candidate(original_project, original_id).unwrap();
|
||||
let real_source = candidate_export_source(original_project, &original);
|
||||
assert_eq!(real_source["kind"], kind);
|
||||
let real_task = read_json(&original_project.join(real_source["taskRecord"].as_str().unwrap())).unwrap();
|
||||
assert!(real_task["requestId"].is_string());
|
||||
assert!(real_task["prompt"].as_str().is_some_and(|prompt| !prompt.is_empty()));
|
||||
assert!(real_task["references"].as_array().is_some_and(|refs| !refs.is_empty()));
|
||||
assert!(original_project.join(real_source["responseRecord"].as_str().unwrap()).is_file());
|
||||
if kind == "scene-composite" {
|
||||
assert!(real_task["sceneComposite"]["placements"].is_array());
|
||||
assert!(original_project.join(real_source["compositeProduct"].as_str().unwrap()).is_file());
|
||||
}
|
||||
let original_project_id = original_project.file_name().unwrap().to_str().unwrap();
|
||||
let root = evidence.join(kind);
|
||||
let copied_job = root.join(original_project_id).join("image-jobs").join(original_id);
|
||||
fs::create_dir_all(&copied_job).unwrap();
|
||||
for row in fs::read_dir(&original_job).unwrap() {
|
||||
let row = row.unwrap();
|
||||
if row.file_type().unwrap().is_file() {
|
||||
fs::copy(row.path(), copied_job.join(row.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
let dir = root.join("placement-fixture");
|
||||
let fixture = fixture();
|
||||
let mut state = load(&fixture.dir).unwrap();
|
||||
write_json(&dir.join("context.json"), &json!({"doc":1,"revision":3})).unwrap();
|
||||
state["productTemplates"] = json!({"detail":state["template"]});
|
||||
persist(&dir, state, 0).unwrap();
|
||||
let state = load(&dir).unwrap();
|
||||
let variant = state["activeVariantId"].as_str().unwrap();
|
||||
let mut placed = candidate(&dir, "complete");
|
||||
let candidate_id = placed["id"].as_str().unwrap().to_owned();
|
||||
let slot = placed["binding"]["slotId"].as_str().unwrap().to_owned();
|
||||
let new_job = dir.join("image-jobs").join(&candidate_id);
|
||||
fs::create_dir_all(&new_job).unwrap();
|
||||
let verified = template_slots::artifact(original_project, original_id, &real_task).unwrap();
|
||||
assert_eq!(original["artifact"], verified);
|
||||
let bytes = fs::read(copied_job.join("generated.png")).unwrap();
|
||||
fs::write(new_job.join("generated.png"), &bytes).unwrap();
|
||||
let reused_from = json!({"projectId":original_project_id,"candidateId":original_id});
|
||||
let staged_task = json!({"id":candidate_id,"phase":"complete","slotBinding":placed["binding"],
|
||||
"requestId":null,"sha256":verified["sha256"],"reusedFrom":reused_from,"sourceType":"archived-candidate"});
|
||||
placed["sourceType"] = json!("archived-candidate");
|
||||
placed["materialTaskId"] = json!(original_id);
|
||||
placed["sourceRequestId"] = real_task["requestId"].clone();
|
||||
placed["reusedFrom"] = reused_from.clone();
|
||||
placed["artifact"] = template_slots::artifact(&dir, &candidate_id, &staged_task).unwrap();
|
||||
write_json(&new_job.join("task.json"), &staged_task).unwrap();
|
||||
reserve(&dir, state.clone(), &placed).unwrap();
|
||||
|
||||
let mut document = slot_canvas::skeleton(&state["template"], "detail", None, variant).unwrap();
|
||||
let mut meta = mapping(&document).unwrap();
|
||||
meta["workspaceId"] = state["id"].clone();
|
||||
document.metadata.text.retain(|(name, _)| name != MAPPING);
|
||||
document.metadata.text.push((MAPPING.into(), meta.to_string()));
|
||||
let layer = mapped_fields(&meta).find(|field| field["slotId"] == slot).unwrap()["nativeLayerId"].as_u64().unwrap();
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(document, None);
|
||||
photocraft_engine::smart_cmds::replace_instance_bytes_fit(&mut session, photocraft_doc::LayerId(layer),
|
||||
"candidate.png", placement_pixels(bytes).unwrap().0, true).unwrap();
|
||||
let mut document = session.active().unwrap().doc.as_ref().clone();
|
||||
document.metadata.text.push((format!("jiansun.adopted.{variant}.{slot}"), candidate_id));
|
||||
let input = json!({"workspaceId":state["id"],"outputId":"detail","variantId":variant,"baseRevision":3,"complete":true});
|
||||
let receipt = export_product_stage_snapshot(&dir, 1, &state, &input, "test-account", Some(&document)).unwrap();
|
||||
assert_eq!(receipt["files"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(receipt["screenFiles"].as_array().unwrap().len(), 1);
|
||||
let source = &receipt["imageSources"][0];
|
||||
assert_eq!(source["kind"], "reused");
|
||||
assert_eq!(source["reusedFrom"], reused_from);
|
||||
assert_eq!(source["requestId"], real_task["requestId"]);
|
||||
assert_eq!(source["pageId"], receipt["screenFiles"][0]["pageId"]);
|
||||
let archive_from_receipt = root.join(source["reusedFrom"]["projectId"].as_str().unwrap())
|
||||
.join("image-jobs").join(source["reusedFrom"]["candidateId"].as_str().unwrap());
|
||||
assert_eq!(fs::read(archive_from_receipt.join("task.json")).unwrap(), fs::read(original_job.join("task.json")).unwrap());
|
||||
let reopened = photocraft_format::load_path(Path::new(receipt["editable"].as_str().unwrap())).unwrap();
|
||||
assert_eq!(reopened.metadata.text, document.metadata.text);
|
||||
for output in [&receipt["files"][0], &receipt["screenFiles"][0]] {
|
||||
assert!(artifact_matches(output, true));
|
||||
}
|
||||
write_json(&root.join("proof.json"), &json!({"originalKind":kind,"requestId":source["requestId"],
|
||||
"receipt":receipt_path(&dir, variant, "detail"),"files":receipt["files"],"screenFiles":receipt["screenFiles"],
|
||||
"editable":receipt["editable"],"field":source["fieldId"],"originalCandidate":original_id,
|
||||
"taskBytesMatch":true,"gatewayCalls":0})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the isolated copies of an actually completed SKU output and project"]
|
||||
fn completed_native_sku_exports_with_its_actual_image_lineage() {
|
||||
let dir = PathBuf::from(std::env::var_os("JIANSUN_TRACE_SKU_PROJECT").unwrap());
|
||||
let editable = PathBuf::from(std::env::var_os("JIANSUN_TRACE_SKU_EDITABLE").unwrap());
|
||||
let scope = std::env::var("JIANSUN_TRACE_SKU_ACCOUNT").unwrap();
|
||||
let document = photocraft_format::load_path(&editable).unwrap();
|
||||
let meta = mapping(&document).unwrap();
|
||||
let state = activate_edited_output(&dir, &document).unwrap();
|
||||
let variant = meta["variantId"].as_str().unwrap();
|
||||
let previous = read_json(&dir.parent().unwrap().join("original-sku-receipt.json")).unwrap();
|
||||
let revision = previous["sourceDocument"]["revision"].as_u64().unwrap();
|
||||
let input = json!({"workspaceId":state["id"],"outputId":"sku_images","variantId":variant,
|
||||
"baseRevision":revision,"complete":true});
|
||||
let receipt = export_product_stage_snapshot(&dir, 1, &state, &input, &scope, Some(&document)).unwrap();
|
||||
let outputs = receipt["files"].as_array().unwrap();
|
||||
assert!(!outputs.is_empty(), "{receipt:?}");
|
||||
assert!(outputs.iter().all(|file| artifact_matches(file, true)));
|
||||
assert!(artifact_matches(&receipt["sourceDocument"], true));
|
||||
let sources = receipt["imageSources"].as_array().unwrap();
|
||||
assert!(!sources.is_empty());
|
||||
for source in sources {
|
||||
assert!(source["fieldId"].is_string());
|
||||
assert!(source["pageId"].is_string());
|
||||
let candidate = read_json(&dir.join(source["candidateRecord"].as_str().unwrap())).unwrap();
|
||||
let task = read_json(&dir.join(source["taskRecord"].as_str().unwrap())).unwrap();
|
||||
assert_eq!(task["id"], candidate["id"]);
|
||||
assert_eq!(source["candidateId"], candidate["id"]);
|
||||
assert_eq!(source["kind"], "product-reference");
|
||||
assert!(candidate["references"][0]["source"].is_string());
|
||||
}
|
||||
assert_eq!(read_json(&receipt_path(&dir, variant, "sku_images")).unwrap()["imageSources"], receipt["imageSources"]);
|
||||
write_json(&dir.parent().unwrap().join("sku-proof.json"), &json!({"outputCount":outputs.len(),
|
||||
"imageFieldCount":sources.len(),"editable":receipt["editable"],"files":outputs,
|
||||
"receipt":receipt_path(&dir, variant, "sku_images"),"gatewayCalls":0})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_stage_cannot_export_a_template_with_an_unfilled_image_slot() {
|
||||
let fixture = fixture();
|
||||
@ -4345,7 +4538,15 @@ mod tests {
|
||||
assert!(artifact_matches(&ready["sourceDocument"], true));
|
||||
assert!(artifact_matches(&snapshot["sourceDocument"], true));
|
||||
let reopened = photocraft_format::load_path(Path::new(snapshot["editable"].as_str().unwrap())).unwrap();
|
||||
assert_eq!(missing_export_images(&fixture.dir, &reopened, &state, &meta, "detail", variant), Vec::<String>::new());
|
||||
let (missing, source_links) = export_image_sources(&fixture.dir, &reopened, &state, &meta, "detail", variant);
|
||||
assert!(missing.is_empty());
|
||||
assert_eq!(snapshot["imageSources"], json!(source_links));
|
||||
assert_eq!(snapshot["imageSources"][0]["fieldId"], "S01-I01");
|
||||
assert_eq!(snapshot["imageSources"][0]["pageId"], "S01");
|
||||
assert_eq!(snapshot["screenFiles"][0]["pageId"], "S01");
|
||||
assert_eq!(snapshot["imageSources"][0]["materialTaskId"], candidate["id"]);
|
||||
assert_eq!(snapshot["imageSources"][0]["embeddedSize"], json!([8,4]));
|
||||
assert_eq!(read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap()["imageSources"], snapshot["imageSources"]);
|
||||
|
||||
let receipt = receipt_path(&fixture.dir, variant, "detail");
|
||||
let mut broken = json!({"outputId":"detail"});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user