Skip to content

SUPRA-Tex: 3D Generation with Super-Aligned Texture

fix: improve back-view generation and review validation

Fanpeng MENGe1c5c0280522
diff --git a/.gitignore b/.gitignore
index dbc1fa6..e7a469e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,21 @@ dist/
# Local models, datasets, runs, and credentials.
/ckpts/
+/ckpt/
+/checkpoints/
+/weights/
+/supra-tex-weights/
+/.cache/huggingface/
+
+# Keep model binaries out of Git even when saved outside the directories above.
+*.safetensors
+*.ckpt
+*.pt
+*.pth
+*.bin
+*.onnx
+*.gguf
+
/external-src/
/outputs/
/data/
diff --git a/README.md b/README.md
index db93581..8cf0c65 100644
--- a/README.md
+++ b/README.md
@@ -203,7 +203,9 @@ in five stages, each a separate command in
the opposite view, as a normal map and silhouette mask that share the same
rasterization.
3. **Back image.** An image generator paints a back view that follows the normal
- pack, and a visual review accepts or rejects it. Our implementation runs
+ pack, and a visual review labels it. `acceptable` and `needs_review` may
+ continue after all hard checks pass; `needs_regeneration` remains blocked.
+ Review labels and defects are retained in downstream records. Our implementation runs
GPT-6 Astra with its built-in image generation tool through the external Codex
CLI; this is the only stage outside this repository.
4. **Back materials.** The accepted image is cut to the rendered silhouette, and
diff --git a/README_zh-CN.md b/README_zh-CN.md
index 226dd67..1055550 100644
--- a/README_zh-CN.md
+++ b/README_zh-CN.md
@@ -165,7 +165,9 @@ python texturing.py --pipeline supra3d/supra-tex --output outputs/pitcher_plant_
1. **正面输入**:图像生成 3D 的前端生成网格、相机和参考视角的材质图,并记录所用的模型。
2. **背面法线图**:从大致相反方向选一个背面相机渲染网格,得到同一次光栅化的法线图和轮廓 mask。
-3. **背面图像**:图像生成模型参照法线图画出背面,再经过视觉审核决定是否采用。
+3. **背面图像**:图像生成模型参照法线图画出背面,再经过视觉审核。
+ `acceptable` 和 `needs_review` 在所有硬性校验通过后均可进入下一阶段;`needs_regeneration` 仍会阻断。
+ 原始审阅标签与缺陷描述会保留并传入后续记录,运行成功不代表视觉评级变为完全通过。
我们通过外部的 Codex CLI 调用 GPT-6 Astra 及其内置的图像生成工具来完成这一步,这也是唯一不在本仓库里的环节。
4. **背面材质**:按渲染出的轮廓裁切采用的背面图,再用同一个材质适配器预测 albedo 和金属度、粗糙度。
5. **补全与细化**:正反两面都转成表面观测,重叠处以正面为准,只需一次补全就能生成其余区域;
diff --git a/docs/dual_view.md b/docs/dual_view.md
index 81636b5..ba670bf 100644
--- a/docs/dual_view.md
+++ b/docs/dual_view.md
@@ -134,8 +134,11 @@ python -m supratex.backview.harness report --run-root work/back_generation
```
Inspect `work/back_generation/report/index.html`. A result needs successful
-worker execution and an accepted visual review for the selected image. An
-image file alone is insufficient. The default case ID is `input`; if using
+worker execution, all provenance and output checks, and a current `acceptable`
+or `needs_review` visual review for the selected image. `needs_review` permits
+the next stage without changing the review label or removing its defects.
+`needs_regeneration`, missing or stale reviews, and hard-check failures remain
+blocked. An image file alone is insufficient. The default case ID is `input`; if using
`--case`, keep it consistent across generation and material preparation.
### 4. Prepare back material maps
@@ -151,6 +154,14 @@ python -m supratex.backview validate \
This stage selects the material backend and model artifacts recorded for the
front. It preserves the generated image, applies the rendered silhouette,
and writes matching condition images, material maps, and validation metadata.
+The `back_view_review` metadata retains the original visual grade, review flag,
+defects, and review source/hash for follow-up iterations.
+Material preparation keeps its historical review snapshot. A new completion run
+revalidates the current review and records that snapshot without overwriting the
+preparation record. If the review changes during completion, final publication
+stops; a later review change makes a newly recorded completion snapshot stale.
+Legacy records without a snapshot use the current review and are identified as
+not having a recorded review snapshot.
### 5. Complete and validate the mesh
@@ -164,8 +175,10 @@ python -m supratex.backview validate --work-dir work/dual_view
Front observations win overlap. Back-only observations extend the visible
material set, and completion runs once. Texture reprojection then processes
the front and back views while preserving front-protected texels.
-`receipt.json` records the final result and its validation status. Failed
-checks leave intermediate files and stop final output publication.
+`receipt.json` records the final result and its validation status separately from
+the retained `back_view_review` snapshot. A successful result can still carry
+`needs_review`; execution success is not a clean visual rating. Failed checks
+leave intermediate files and stop final output publication.
## Resume an interrupted run
@@ -176,7 +189,8 @@ python -m supratex.backview.harness run \
--run-root work/back_generation --execute
```
-Add `--retry-review` to request a new attempt after a rejected visual review.
+Add `--retry-review` to request a new attempt for either `needs_review` or
+`needs_regeneration`, including eligible results retained for a later iteration.
Otherwise recovery can finish a missing review without requesting a new image.
After generation succeeds, run material preparation into a new output directory
and texturing into a fresh work directory. Full `infer.py` does not resume a
diff --git a/infer.py b/infer.py
index 0f5aa6e..f79281f 100644
--- a/infer.py
+++ b/infer.py
@@ -322,10 +322,19 @@ def run(args: argparse.Namespace) -> Path:
receipt.update(stage="completion", frontend=result)
record()
print(f"[2/2] Surface observations, PBR completion, GLB export -> {output}", flush=True)
- run_completion(input_dir=handoff, output=output, model_config=config, checkpoint=checkpoint,
- trellis_root=encoders, seed=args.seed, texture_size=args.texture_size,
- decimation_target=args.decimation_target, texture_format=args.texture_format, gutter=args.gutter,
- remove_floaters=args.remove_floaters, **optional)
+ try:
+ run_completion(input_dir=handoff, output=output, model_config=config, checkpoint=checkpoint,
+ trellis_root=encoders, seed=args.seed, texture_size=args.texture_size,
+ decimation_target=args.decimation_target, texture_format=args.texture_format, gutter=args.gutter,
+ remove_floaters=args.remove_floaters, **optional)
+ finally:
+ # Copy the snapshot actually consumed by completion, including failed
+ # runs, rather than the possibly older material-preparation review.
+ completion_record = work / "dual_view" / "receipt.json"
+ if args.dual_view and completion_record.is_file():
+ completion = json.loads(completion_record.read_text(encoding="utf-8"))
+ receipt["back_view_review"] = completion["back_view_review"]
+ receipt["review_changed_since_preparation"] = completion["review_changed_since_preparation"]
if not output.is_file() or output.stat().st_size == 0:
raise RuntimeError(f"completion did not emit a nonempty GLB: {output}")
except Exception as error:
diff --git a/supratex/backview/__main__.py b/supratex/backview/__main__.py
index 381cc30..2e9a024 100644
--- a/supratex/backview/__main__.py
+++ b/supratex/backview/__main__.py
@@ -60,7 +60,10 @@ def main(argv: list[str] | None = None) -> int:
parser.error("--back-view-dir validation requires --input-dir")
from supratex.inference.dual_view import load_back_case
loaded = load_back_case(args.input_dir, args.back_view_dir)
- result = {"valid": True, "camera_protocol": loaded["cameras"]["protocol"]}
+ result = {"valid": True, "camera_protocol": loaded["cameras"]["protocol"],
+ "back_view_review": loaded["back_view_review"],
+ "requires_review": loaded["back_view_review"]["requires_review"],
+ "review_changed_since_preparation": loaded["review_changed_since_preparation"]}
else:
from supratex.inference.dual_view import validate_result
result = validate_result(args.work_dir)
diff --git a/supratex/backview/harness/README.md b/supratex/backview/harness/README.md
index 7509e3b..62b1b10 100644
--- a/supratex/backview/harness/README.md
+++ b/supratex/backview/harness/README.md
@@ -41,8 +41,9 @@ preserve all attempts, actual tool returns, prompts, and visual reviews.
Terminal policy refusals and missing capabilities are recorded as failures.
Completed cases are reused on resume. A missing or stale review triggers
-review-only recovery without a new generation. Visually rejected results
-remain rejected; request a correction explicitly with `--retry-review`.
+review-only recovery without a new generation. `needs_review` may continue after
+all hard checks pass, while `needs_regeneration` remains blocked. Request a new
+attempt for either status explicitly with `--retry-review`.
A failed worker cannot pass merely because an older image exists.
## Artifacts and acceptance
@@ -61,15 +62,45 @@ and event logs, and worker completion records. Postprocessing adds:
The report at `report/index.html` is offline and in English. It hides stale
processed images and links complete JSON audit records. `validate_result`
-accepts a result only when all recorded inputs, prompts, attempts, outputs,
-worker completion, and the current `acceptable` visual review agree. A
-completed generation with `needs_review` or `needs_regeneration` remains
-unaccepted for inference. Logs establish provenance and detect stale or changed
-artifacts; local records are not cryptographic attestations of a remote service.
+allows inference only when all recorded inputs, prompts, attempts, outputs,
+worker completion, and the current visual review agree. Both `acceptable` and
+`needs_review` may continue after those checks pass; `needs_regeneration`, a
+missing or stale review, and any hard-check failure block inference.
+
+Eligibility does not change the visual grade. The original `visual_review.json`
+and its defects are preserved. Validation and downstream receipts retain a
+`back_view_review` snapshot with its status, `requires_review` flag, source path,
+SHA-256, and original review. Reports distinguish allowed acceptable cases,
+allowed needs_review cases, and blocked cases. `accepted` remains the per-case
+eligible count, while `needs_review` and `needs_review_cases` identify all cases
+carrying that visual label, including cases blocked by hard checks. A duplicate
+raw-image hash can still block the batch audit independently of per-case counts.
+Logs establish provenance and detect stale or changed artifacts; local records
+are not cryptographic attestations of a remote service.
+
+Defects are objects with `severity` (`minor` or `major`) and a concrete
+`description`. `acceptable` has no recorded defects; minor defects require
+`needs_review`, and any major defect requires `needs_regeneration`. Contradictory
+or malformed reviews are ineligible without silently changing their grade.
+
+The reviewer must inspect the actual `back_rgba.png`, `back_rgb.png`, `overlay.png`
+and `alignment.json`. After inspection, the review records
+`postprocessing_reviewed: true`, `reviewed_processed_file_sha256` (copied from
+`validation.json`'s `processed_file_sha256`) and `postprocessing_policy_sha256`.
+These hashes bind all four processed files and the loaded postprocessor source,
+in addition to `reviewed_raw_sha256`. Changed processed files or policy invalidate
+the current review even if the raw image is unchanged. Resume preserves already
+reviewed files instead of postprocessing them again. Legacy reviews without these
+bindings are preserved but require postprocessing and review-only recovery; they
+are never automatically rebound or upgraded, and recovery does not generate a new
+image. Existing input and prompt snapshots remain unchanged.
Postprocessing standardizes the canvas and, only when native alpha is
meaningful, estimates a uniform scale and translation. Scale is limited to
-0.65–1.35 and translation to 15% of each canvas dimension. It does not rotate,
+0.65–1.35 and translation to 15% of each canvas dimension. A proposed transform
+must improve native-resolution silhouette IoU without decreasing target coverage;
+otherwise the original framing is retained and the rejected parameters, metrics
+and reason are saved in `alignment.json`. It does not rotate,
flip, deform individual parts, inpaint texture, or adjust brightness. The
original target mask is then applied. Matching final alpha proves the mask
constraint, **not** internal surface correspondence. The latter remains a
diff --git a/supratex/backview/harness/__main__.py b/supratex/backview/harness/__main__.py
index caccc11..402698a 100644
--- a/supratex/backview/harness/__main__.py
+++ b/supratex/backview/harness/__main__.py
@@ -28,7 +28,8 @@ def main(argv=None) -> int:
sub.add_argument("--timeout", type=int, default=1800)
sub.add_argument("--codex", default="codex")
sub.add_argument("--case", action="append")
- sub.add_argument("--retry-review", action="store_true")
+ sub.add_argument("--retry-review", action="store_true",
+ help="Request a new attempt for needs_review or needs_regeneration results")
elif name == "prompt":
sub.add_argument("--refine", action="store_true")
elif name == "register":
diff --git a/supratex/backview/harness/core.py b/supratex/backview/harness/core.py
index 73258df..efc5152 100644
--- a/supratex/backview/harness/core.py
+++ b/supratex/backview/harness/core.py
@@ -18,6 +18,7 @@ MODEL = "gpt-6-astra"
EFFORT = "ultra"
GENERATION_TOOL = "image_gen.imagegen"
SCHEMA = "supratex.backview.harness.v1"
+INFERENCE_REVIEW_STATUSES = frozenset({"acceptable", "needs_review"})
INPUT_FILES = {
"front_rgb": "front_rgb.png",
"back_normal": "back_normal.png",
@@ -277,10 +278,35 @@ def generation_current(root: Path, task: dict) -> bool:
return False
-def current_review(root: Path, task: dict) -> dict | None:
+def current_review_snapshot(root: Path, task: dict) -> dict | None:
+ """Require a review of the current processed files and loaded policy."""
output = checked_path(root, task["output_dir"])
try:
- review = read_json(output / "visual_review.json")
+ source = output / "visual_review.json"
+ contents = source.read_bytes()
+ review = json.loads(contents)
+ if not isinstance(review, dict):
+ return None
+ defects = review.get("defects")
+ if not isinstance(defects, list) or any(
+ not isinstance(defect, dict) or defect.get("severity") not in ("minor", "major")
+ or not isinstance(defect.get("description"), str) or not defect["description"].strip()
+ for defect in defects):
+ return None
+ severities = {defect["severity"] for defect in defects}
+ if (("major" in severities and review.get("status") != "needs_regeneration")
+ or (defects and review.get("status") == "acceptable")):
+ return None
+ from .postprocess import REVIEWED_FILES, SCHEMA_VERSION, policy_sha256
+ policy = policy_sha256()
+ alignment = read_json(output / "alignment.json")
+ processed = {name: sha(output / name) for name in REVIEWED_FILES}
+ if (review.get("postprocessing_reviewed") is not True
+ or review.get("postprocessing_policy_sha256") != policy
+ or review.get("reviewed_processed_file_sha256") != processed
+ or alignment.get("schema_version") != SCHEMA_VERSION
+ or alignment.get("postprocessing_policy_sha256") != policy):
+ return None
required = ("rear_view", "geometry", "materials", "text_and_patterns", "lighting_and_brightness")
if (review.get("reviewed_raw_sha256") == sha(output / "raw.png")
and review.get("case_id") == task["case_id"]
@@ -288,17 +314,24 @@ def current_review(root: Path, task: dict) -> dict | None:
and all(review.get(k) for k in required)
and isinstance(review.get("defects"), list)
and review.get("interior_pixel_alignment_proven") is False):
- return review
- except (OSError, ValueError, KeyError):
+ return {"status": review["status"], "requires_review": review["status"] == "needs_review",
+ "source": str(source), "sha256": hashlib.sha256(contents).hexdigest(), "review": review}
+ except (OSError, ValueError, KeyError, TypeError):
pass
return None
+def current_review(root: Path, task: dict) -> dict | None:
+ snapshot = current_review_snapshot(root, task)
+ return snapshot["review"] if snapshot is not None else None
+
+
def validate_result(run_root: Path, case_id: str = "input") -> dict:
- """Accept only current, auditable, visually accepted 1024-square observations."""
+ """Gate inference on integrity and eligibility, without upgrading visual grades."""
root = Path(run_root).resolve()
result = {"case_id": case_id, "valid": False, "records_valid": False,
"status": "invalid", "errors": [], "warnings": [], "back_rgba": None,
+ "requires_review": False, "back_view_review": None,
"interior_pixel_alignment_proven": False}
errors = result["errors"]
try:
@@ -356,13 +389,16 @@ def validate_result(run_root: Path, case_id: str = "input") -> dict:
mask = np.asarray(image.convert("L"))
if alpha.shape != mask.shape or not np.array_equal(alpha, mask):
errors.append("Final alpha must equal the original renderer mask exactly")
- review = current_review(root, task)
- if review is None:
+ snapshot = current_review_snapshot(root, task)
+ if snapshot is None:
errors.append("Visual review is missing, incomplete, or stale")
else:
- result["status"] = review["status"]
- if review["status"] != "acceptable":
- result["warnings"].append("Visual review requires attention; the observation is not accepted for inference")
+ result.update(status=snapshot["status"], requires_review=snapshot["requires_review"],
+ back_view_review=snapshot)
+ if snapshot["requires_review"]:
+ result["warnings"].append("Visual review is needs_review; inference is allowed only if all integrity checks pass. Review label and defects are retained.")
+ elif snapshot["status"] == "needs_regeneration":
+ result["warnings"].append("Visual review requires regeneration; the observation is not accepted for inference")
status = read_json(output / "worker_status.json")
if status.get("run_success") is not True or status.get("exit_code") != 0:
errors.append("The required Astra worker did not complete successfully")
@@ -386,7 +422,7 @@ def validate_result(run_root: Path, case_id: str = "input") -> dict:
errors.append("Worker invocation is not bound to the current case inputs and prompt")
result["back_rgba"] = str(output / "back_rgba.png")
result["records_valid"] = not errors
- result["valid"] = not errors and result["status"] == "acceptable"
+ result["valid"] = not errors and result["status"] in INFERENCE_REVIEW_STATUSES
if result["records_valid"]:
result.update(worker_model=provenance["worker_model"],
worker_reasoning_effort=provenance["worker_reasoning_effort"],
@@ -399,4 +435,5 @@ def validate_result(run_root: Path, case_id: str = "input") -> dict:
input_sha256=task["input_sha256"])
except (OSError, ValueError, KeyError, TypeError, IndexError) as exc:
errors.append(f"{type(exc).__name__}: {exc}")
+ result.update(valid=False, records_valid=False)
return result
diff --git a/supratex/backview/harness/postprocess.py b/supratex/backview/harness/postprocess.py
index 1e13199..fe7fe83 100644
--- a/supratex/backview/harness/postprocess.py
+++ b/supratex/backview/harness/postprocess.py
@@ -18,7 +18,9 @@ from scipy.ndimage import binary_erosion, distance_transform_edt
RESAMPLE = Image.Resampling
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
+REVIEWED_FILES = ("back_rgba.png", "back_rgb.png", "overlay.png", "alignment.json")
+_LOADED_POLICY_SHA256 = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
def read_json(path: Path):
@@ -42,6 +44,13 @@ def sha256(path: Path) -> str:
return digest.hexdigest()
+def policy_sha256() -> str:
+ """Identify the loaded policy; a source edit requires a fresh interpreter."""
+ if sha256(Path(__file__)) != _LOADED_POLICY_SHA256:
+ raise ValueError("Postprocessing policy changed after import; restart before processing or reviewing")
+ return _LOADED_POLICY_SHA256
+
+
def mask_image(path: Path) -> Image.Image:
"""Use grayscale values, or meaningful alpha for an RGBA mask export."""
with Image.open(path) as opened:
@@ -275,6 +284,7 @@ def process(task: dict, run_root: Path) -> dict:
write_json(output / "validation.json", validation)
return validation
try:
+ policy = policy_sha256()
normal_path = resolve_path(task["back_normal"], run_root)
front_path = resolve_path(task["front_rgb"], run_root)
mask_path = resolve_path(task["back_mask"], run_root)
@@ -304,12 +314,16 @@ def process(task: dict, run_root: Path) -> dict:
if transform["applied"]:
proposed = affine(standardized, transform["scale"], transform["dx_px"], transform["dy_px"])
proposed_metrics = mask_metrics(np.asarray(proposed.getchannel("A")) >= 128, target)
- # Thumbnail optimisation must also improve the native-resolution silhouette.
- if proposed_metrics["iou"] > raw_metrics["iou"]:
+ # A better silhouette must not reduce supported target texture.
+ coverage_decreased = proposed_metrics["target_coverage"] < raw_metrics["target_coverage"]
+ if proposed_metrics["iou"] > raw_metrics["iou"] and not coverage_decreased:
registered, preclip_metrics = proposed, proposed_metrics
else:
transform["rejected_proposal"] = {k: transform[k] for k in ("scale", "dx_px", "dy_px")}
- transform.update(scale=1.0, dx_px=0.0, dy_px=0.0, applied=False, rejection_reason="no_native_resolution_iou_improvement")
+ transform["rejected_proposal_metrics"] = proposed_metrics
+ transform.update(scale=1.0, dx_px=0.0, dy_px=0.0, applied=False,
+ rejection_reason="target_coverage_decreased" if coverage_decreased
+ else "no_native_resolution_iou_improvement")
# Preserve straight RGB wherever the generator supplied any alpha.
# Baking source alpha into RGB here would apply coverage a second time
@@ -337,6 +351,7 @@ def process(task: dict, run_root: Path) -> dict:
alignment = {
"schema_version": SCHEMA_VERSION,
+ "postprocessing_policy_sha256": policy,
"case_id": case_id,
"raw_sha256": raw_digest,
"front_rgb_sha256": sha256(front_path),
@@ -372,6 +387,8 @@ def process(task: dict, run_root: Path) -> dict:
],
}
write_json(output / "alignment.json", alignment)
+ if policy_sha256() != policy:
+ raise ValueError("Postprocessing policy changed during processing")
validation.update(
status="needs_visual_review", message="Postprocessing complete; internal geometric alignment and text legibility remain unproven.",
dimensions_match_target=True,
@@ -381,6 +398,8 @@ def process(task: dict, run_root: Path) -> dict:
raw_sha256=alignment["raw_sha256"],
visual_review_present=(output / "visual_review.json").is_file(),
provenance_present=(output / "provenance.json").is_file(),
+ postprocessing_policy_sha256=policy,
+ processed_file_sha256={name: sha256(output / name) for name in REVIEWED_FILES},
)
except Exception as exc:
validation.update(status="error", message=f"{type(exc).__name__}: {exc}")
diff --git a/supratex/backview/harness/prompts/backview_universal.txt b/supratex/backview/harness/prompts/backview_universal.txt
index 0144f3d..150e690 100644
--- a/supratex/backview/harness/prompts/backview_universal.txt
+++ b/supratex/backview/harness/prompts/backview_universal.txt
@@ -11,10 +11,12 @@ GEOMETRY IS FIXED
Preserve the geometry guide's silhouette and all internal geometric boundaries at their exact image coordinates. Preserve thin parts, disconnected visible parts, cavities and background holes. Do not rotate, mirror, straighten, enlarge, recenter, crop or simplify the object. Do not adopt the front reference camera or copy its silhouette. Do not add, delete or relocate structural parts. Normal colors must be entirely replaced by material appearance; they are not paint, illumination or colored panels.
TEXTURE AND REAR-SIDE REASONING
-Continue materials consistently around the object, respecting surface orientation and physical seams. Creatively complete previously unseen rear surfaces as part of the SAME object's visual design. New rear-side text, patterns, graphics, labels and decorative details are explicitly allowed and desired wherever they make sense for the object. They need not already be visible in the front image. Make them coherent with the front reference's identity, palette, typography, graphic style, print scale, material character and degree of wear. Create a plausible rear design, not a mirrored copy of the entire front image. Preserve existing readable brand spelling when reusing it, and keep new lettering clear, intentional and coherent rather than pseudo-letter clutter. Keep print, linework, seams, grain and small surface detail crisp at native resolution with correct surface perspective and no oversharpened halos. New texture details may not add or change physical geometry, and do not add labels to objects where they would be inappropriate.
+Continue materials consistently around the object, respecting surface orientation and physical seams. Creatively complete previously unseen rear surfaces as part of the SAME object's visual design. When the front reference contains a product label, branding or readable packaging text, the rear MUST include a designed rear label or printed information panel with clearly readable, coherent text. A bare or blank rear surface does not satisfy this requirement. Continue the front identity through the rear label's palette, typography, graphic style, print scale, material character and degree of wear. Create plausible rear copy and supporting graphics; the unseen words and design need not already appear in the front image. Keep a recognizable brand spelling when reusing it. Use a compact, intentional hierarchy of readable text instead of pseudo-letter clutter or a mirrored copy of the entire front label.
+
+New rear-side text, patterns, graphics, labels and decorative details are welcome. Printed labels, lettering and flat graphic panels are surface appearance, not added structural geometry: render them directly on the fixed guided surfaces even when the normal image contains no label boundary. Preserve the guide's physical contours and components. For objects without product labels or lettering in the front reference, continue their materials and decorative design without requiring a packaging label. Keep print, linework, seams, grain and small surface detail crisp at native resolution with correct surface perspective and no oversharpened halos.
LIGHTING AND BRIGHTNESS CONSISTENCY
Match the FRONT RGB reference's illumination style, exposure, white balance, overall object brightness, contrast, ambient fill, shadow softness, and highlight strength. The rear view must look like the same object photographed in the same lighting setup with the same exposure settings. Do not make the rear globally darker merely because it is the back, and do not brighten, wash out, recolor, or dramatically relight it. Preserve the apparent lightness of corresponding materials. Let only surface orientation and geometry justify local shading differences; keep shadow detail as readable as in the front reference. Do not copy front-view shadow shapes or specular highlights onto geometrically different rear surfaces. Normal-map channel values encode direction, never exposure or light intensity.
RENDERING AND OUTPUT
-Match the reference's material character and level of stylization, with clear texture detail under the matched illumination described above. Do not add cast shadows outside the object. Produce a clean RGBA PNG with a genuinely transparent background, preserving the guide's negative spaces and contour. Request the same pixel dimensions as Image 1 (the current benchmark is 1024 by 1024). Return only the rear-view image: no panel layout, captions, borders, watermark, normal-map overlay or front-view inset.
+Match the reference's material character and level of stylization, with clear texture detail under the matched illumination described above. Do not add cast shadows outside the object. Produce a clean RGBA PNG with a genuinely transparent background, preserving the guide's negative spaces and contour. Request the same pixel dimensions as Image 1 (the current benchmark is 1024 by 1024). Return only the rear-view image, including the required on-object label and lettering. Do not add captions outside the object, comparison-panel layouts, framing borders, watermarks, normal-map overlays or front-view insets.
diff --git a/supratex/backview/harness/prompts/refinement_universal.txt b/supratex/backview/harness/prompts/refinement_universal.txt
index bd09134..af43053 100644
--- a/supratex/backview/harness/prompts/refinement_universal.txt
+++ b/supratex/backview/harness/prompts/refinement_universal.txt
@@ -2,6 +2,6 @@ UNIVERSAL CORRECTION PASS — GEOMETRY AND OBSERVED EXPOSURE
Treat this as a strict technical reconstruction, not an improved product photograph. Image 2's observed RGB lightness is the exposure target, including an intentionally dim or underexposed appearance. Do not auto-expose, brighten dark reference materials, whiten neutral materials, increase saturation, enhance highlights, or replace the reference illumination with a studio setup. A material that looks dark gray in Image 2 must retain that observed dark-gray lightness on comparable surfaces in the result, even if its underlying real-world material would be white under stronger light. Match the reference's actual displayed appearance, not an imagined well-lit version. Preserve reference shadow depth and subdued contrast without losing recoverable texture.
-Image 1 specifies the entire image-coordinate layout, not merely the outer outline. Keep its exact scale and position. Read the actual visible surfaces from the normal guide even when the target is an unusual rear-underneath view. Do not convert a visible base or underside into a top opening, cavity or conventional upright view. Preserve internal geometric traces at their given coordinates, but do not interpret a geometric trace as evidence of a paper sticker, label or different material.
+Image 1 specifies the entire image-coordinate layout, not merely the outer outline. Keep its exact scale and position. Read the actual visible surfaces from the normal guide even when the target is an unusual rear-underneath view. Do not convert a visible base or underside into a top opening, cavity or conventional upright view. Preserve internal geometric traces at their given coordinates. Use the front reference and the object's visual identity to design surface materials, labels and printing; normal-map traces describe geometry and do not restrict the presence of rear labels or text.
-For areas not visible in the front reference, invent a plausible rear design with appropriate text and graphics when useful. New rear-side labels, numeric tables, barcodes, lettering or patterns are allowed; keep their style, palette, scale, clarity and apparent lighting consistent with the front design. Newness is not a defect. Prioritize the correct geometry, matching material appearance and exposure, and readable coherent detail. Return one rear-view image in the original normal-image frame. Do not add explanatory text or comparison panels outside the object. These rules apply unchanged to every object category.
+When the front reference contains a product label, branding or readable packaging text, include a coherent rear label or printed information panel with clearly readable rear text. This is required, including when an earlier candidate omitted all labels and lettering. Design plausible rear copy and supporting graphics in the front reference's typography, palette, scale, print material and degree of wear. Keep recognizable brand spelling when reused. A plain bare rear or a graphic panel without readable text does not satisfy this requirement. Flat printing and labels belong on the existing guided surfaces without changing the object's physical geometry. For objects without front product labels or lettering, continue their material and decorative design without requiring packaging text. New rear details need not already be visible in the reference; newness is not a defect. Preserve the correct geometry, matching material appearance and exposure, and readable coherent detail. Return one rear-view image in the original normal-image frame. Do not add explanatory text or comparison panels outside the object. These rules apply unchanged to every object category.
diff --git a/supratex/backview/harness/prompts/worker_universal.txt b/supratex/backview/harness/prompts/worker_universal.txt
index c9409e4..dc9180d 100644
--- a/supratex/backview/harness/prompts/worker_universal.txt
+++ b/supratex/backview/harness/prompts/worker_universal.txt
@@ -8,9 +8,9 @@ For each assigned case:
1. Inspect the local back_normal and front_rgb with view_image in that order. Only those two images may be generation inputs. Do not inspect or provide ground-truth rear RGB, previous generated candidates, or other cases' images to the generator. Read back_mask and cameras only as metadata for postprocessing and review.
2. Use prompts/backview_universal.txt unchanged for a first generation. Save its exact bytes as results/<case_id>/prompt_attemptN.txt. Invoke built-in image_gen with the exact prompt, referenced_image_paths=[absolute back_normal, absolute front_rgb], and transparent_background=true. The Astra worker controls the image tool; its undisclosed synthesis model produces the pixels. Do not claim that the Astra text model emits the image directly.
3. Preserve the full actual tool return in results/<case_id>/tool_result_attemptN.json. Use an actual image path returned by the tool. If there is no usable returned image file, record the actual failure and stop the case. Register with: PYTHON_EXECUTABLE -m supratex.backview.harness register --run-root HARNESS_ROOT --case CASE_ID --raw RETURNED_IMAGE_PATH --tool-result SAVED_TOOL_RESULT --prompt-file SAVED_PROMPT --attempt N. Never fabricate a result, tool return, or review.
-4. Inspect the registered raw and the front reference. Write results/<case_id>/visual_review.json with case_id, reviewed_raw_sha256, status (acceptable, needs_review, or needs_regeneration), rear_view, geometry, materials, text_and_patterns, lighting_and_brightness, defects (list), and interior_pixel_alignment_proven=false. Give concrete observations for each field. Compare exposure, corresponding-material lightness, color cast, contrast, and shadow readability. New rear text, graphics, labels, and patterns are allowed; judge their coherence and legibility, not their prior visibility. Mark unresolved fine detail uncertain. A matching final mask is not evidence of internal geometric correspondence.
-5. For an incorrect camera, missing major components, substantial lighting/material mismatch, or visibly incoherent text, one fresh correction candidate is permitted using exactly backview_universal.txt + one newline + refinement_universal.txt. Use the original two inputs, never an earlier output. Save the complete combined prompt and use the next unused attempt number. The command PYTHON_EXECUTABLE -m supratex.backview.harness prompt --run-root HARNESS_ROOT --refine prints the combined prompt. The same base and correction apply to every object. Preserve both attempts and state which is selected and why. To select an earlier candidate again, register that original returned file and its matching saved prompt/tool return with its original attempt number. Keep the review bound to the selected raw hash. Persistent major failures must remain needs_regeneration. Do not invent case-specific prompts.
-6. Run PYTHON_EXECUTABLE -m supratex.backview.harness postprocess --run-root HARNESS_ROOT --case CASE_ID. Inspect back_rgba.png and overlay.png, then update the visual review for remaining defects. Permitted uniform framing corrections may resolve an initial translation/scale error; do not reject solely because native dimensions differed before standardization. Lack of mathematical proof alone is not a visual failure. Mark observed minor defects needs_review and major residual failures needs_regeneration.
+4. Inspect the registered raw and the front reference. Write results/<case_id>/visual_review.json with case_id, reviewed_raw_sha256, status (acceptable, needs_review, or needs_regeneration), rear_view, geometry, materials, text_and_patterns, lighting_and_brightness, defects (list), and interior_pixel_alignment_proven=false. Each defect has severity (minor or major) and a concrete description. Use acceptable when no defects are recorded, needs_review for minor defects or uncertain fine detail, and needs_regeneration for any major defect. Give concrete observations for each field. Compare exposure, corresponding-material lightness, color cast, contrast, and shadow readability. In text_and_patterns, explicitly describe the front's product labels/branding/lettering and whether a designed rear label or printed information panel with readable text is present in the generated image. When the front contains a product label, branding or readable packaging text, missing the required rear label or readable rear text is a major defect and MUST be needs_regeneration; "no generated text to assess" is not a passing review. New rear copy and graphics are expected: assess their coherence and legibility, not whether they were already visible in the front. A flat printed label does not violate fixed physical geometry. For objects without front product labels or lettering, packaging text is not required. Mark unresolved fine detail uncertain; distinguish uncertain small print from an entirely absent required label. A matching final mask is not evidence of internal geometric correspondence.
+5. For an incorrect camera, missing major components, substantial lighting/material mismatch, a missing required rear label or readable text, or visibly incoherent text, one fresh correction candidate is permitted using exactly backview_universal.txt + one newline + refinement_universal.txt. Use the original two inputs, never an earlier output. Save the complete combined prompt and use the next unused attempt number. The command PYTHON_EXECUTABLE -m supratex.backview.harness prompt --run-root HARNESS_ROOT --refine prints the combined prompt. The same base and correction apply to every object. Preserve both attempts and state which is selected and why. To select an earlier candidate again, register that original returned file and its matching saved prompt/tool return with its original attempt number. Keep the review bound to the selected raw hash. Persistent major failures, including an absent required rear label or readable text, must remain needs_regeneration. Do not invent case-specific prompts.
+6. Run PYTHON_EXECUTABLE -m supratex.backview.harness postprocess --run-root HARNESS_ROOT --case CASE_ID. Inspect back_rgba.png, back_rgb.png, overlay.png and alignment.json, then update the visual review for remaining defects. Confirm the required rear label and readable text remain present in these actual processed files; if absent, keep a major defect and needs_regeneration. Only after inspecting those exact files, set postprocessing_reviewed=true, copy validation.json's processed_file_sha256 dictionary unchanged into reviewed_processed_file_sha256, and copy its postprocessing_policy_sha256 into the review's postprocessing_policy_sha256. These bind the actual processed images, alignment record and policy, in addition to reviewed_raw_sha256. Never refresh hashes on an old review without inspecting the current files. Permitted uniform framing corrections may resolve an initial translation/scale error; do not reject solely because native dimensions differed before standardization. Lack of mathematical proof alone is not a visual failure. Mark observed minor defects needs_review and major residual failures needs_regeneration.
A transient connection failure that produced no usable image may be retried once with identical inputs and prompt and a new attempt number; preserve its failed tool return. Policy refusals are terminal: save status="terminal_policy_refusal" and the actual tool response, and do not retry or rephrase to evade them.
diff --git a/supratex/backview/harness/report.py b/supratex/backview/harness/report.py
index c9dde20..447a1b4 100644
--- a/supratex/backview/harness/report.py
+++ b/supratex/backview/harness/report.py
@@ -8,7 +8,21 @@ import os
from pathlib import Path
from urllib.parse import quote
-from .core import checked_path, load_tasks, read_json, sha, validate_result, write_json
+from .core import checked_path, load_tasks, sha, validate_result, write_json
+
+
+def _review_counts(records: list[dict]) -> dict:
+ """Separate per-case eligibility from the original visual review grades."""
+ visual = Counter(row["status"] for row in records)
+ return {
+ "accepted": sum(row["valid"] for row in records),
+ "accepted_acceptable": sum(row["valid"] and row["status"] == "acceptable" for row in records),
+ "accepted_needs_review": sum(row["valid"] and row["status"] == "needs_review" for row in records),
+ "blocked": sum(not row["valid"] for row in records),
+ "needs_review": visual["needs_review"],
+ "needs_review_cases": [row["case_id"] for row in records if row["status"] == "needs_review"],
+ "visual_status_counts": dict(sorted(visual.items())),
+ }
def audit_run(root: Path) -> dict:
@@ -23,7 +37,7 @@ def audit_run(root: Path) -> dict:
report = {"case_count": len(records), "records_valid": all(r["records_valid"] for r in records) and not duplicates,
"all_accepted": all(r["valid"] for r in records) and not duplicates,
"duplicate_raw_hashes": duplicates, "cases": records,
- "interior_pixel_alignment_proven": False}
+ "interior_pixel_alignment_proven": False, **_review_counts(records)}
write_json(root / "batch_validation.json", report)
return report
@@ -63,8 +77,14 @@ def build_report(root: Path) -> Path:
("provenance.json", "Generation provenance"), ("worker_status.json", "Astra worker completion"),
("failure.json", "Generation failure")))
details += record(checked_path(root, task["cameras"]), "Original camera metadata")
- accepted = "Accepted for inference" if status["valid"] else "Not accepted for inference"
- cards.append(f'<article data-case="{escape(case_id, quote=True)}"><h2>{escape(case_id)}</h2>'
+ if not status["valid"]:
+ accepted = "Blocked for inference"
+ elif status["status"] == "needs_review":
+ accepted = "Allowed for inference · Review required"
+ else:
+ accepted = "Allowed for inference · Visually acceptable"
+ cards.append(f'<article data-case="{escape(case_id, quote=True)}" '
+ f'data-status="{escape(status["status"], quote=True)}"><h2>{escape(case_id)}</h2>'
f'<p><strong>{accepted}</strong> · Visual status: {escape(status["status"])}</p>'
f'<div class="images">{images}</div><ul>{notes}</ul>{details}</article>')
html = """<!doctype html>
@@ -77,25 +97,41 @@ article{padding:22px;background:#19242f;border:1px solid #344554;border-radius:1
.images{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px}figure{margin:0;min-width:0}
figcaption{font-size:12px;margin:6px 0}img{width:100%;aspect-ratio:1;object-fit:contain;background:#e7e9ec}
details{margin-top:12px}summary{cursor:pointer}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#0c1219;padding:16px}
-.note{background:#22313f;padding:16px;border-left:3px solid #8ad6d0}input{padding:10px;width:280px;max-width:80%}
+.note{background:#22313f;padding:16px;border-left:3px solid #8ad6d0}input,select{padding:10px;max-width:80%}input{width:280px}
@media(max-width:850px){.images{grid-template-columns:repeat(2,minmax(0,1fr))}body{padding:16px}}
</style><main><h1>SupraTex back-view generation review</h1>
<p>Compare the original inputs, actual generation, permitted postprocessing, and recorded Astra review.</p>
<p class="note">GPT-6 Astra orchestrates the built-in image tool; the underlying synthesis model is undisclosed.
Final alpha is constrained to the renderer mask. This does not prove internal pixel correspondence.
-Stale or incomplete artifacts are excluded from final previews. Camera geometry is not inferred from placeholder metadata.</p>
+Stale or incomplete artifacts are excluded from final previews. Camera geometry is not inferred from placeholder metadata.
+Inference eligibility is separate from visual quality: needs_review may continue after all hard checks pass,
+while its review label and defects remain recorded for follow-up.</p>
"""
- html += (f'<p>Cases: {audit["case_count"]} · Accepted: {sum(row["valid"] for row in audit["cases"])}'
+ html += (f'<p>Cases: {audit["case_count"]} · Allowed for inference: {audit["accepted"]}'
+ f' (acceptable: {audit["accepted_acceptable"]}; needs_review: {audit["accepted_needs_review"]})'
+ f' · Blocked: {audit["blocked"]}</p>'
+ f'<p>Visual needs_review labels: {audit["needs_review"]} (including blocked cases)'
+ f' · Batch audit: {"passed" if audit["all_accepted"] else "blocked"}'
+ f' · Duplicate raw hashes: {len(audit["duplicate_raw_hashes"])}'
f' · Audit: <a href="../batch_validation.json">full JSON</a></p>'
- '<label>Filter by case ID <input id="filter" type="search"></label>' + "".join(cards))
+ '<label>Filter by case ID <input id="filter" type="search"></label> '
+ '<label>Visual status <select id="status-filter"><option value="">All</option>'
+ '<option value="acceptable">acceptable</option><option value="needs_review">needs_review</option>'
+ '<option value="needs_regeneration">needs_regeneration</option><option value="invalid">invalid</option>'
+ '</select></label>' + "".join(cards))
html += """</main><script>
-document.querySelector('#filter').addEventListener('input',function(){
- const query=this.value.toLowerCase();
- for(const item of document.querySelectorAll('article'))item.hidden=!item.dataset.case.toLowerCase().includes(query);
-});</script></html>
+function filterCases(){
+ const query=document.querySelector('#filter').value.toLowerCase();
+ const status=document.querySelector('#status-filter').value;
+ for(const item of document.querySelectorAll('article')){
+ item.hidden=!item.dataset.case.toLowerCase().includes(query)||(status!==''&&item.dataset.status!==status);
+ }
+}
+document.querySelector('#filter').addEventListener('input',filterCases);
+document.querySelector('#status-filter').addEventListener('change',filterCases);
+</script></html>
"""
destination = report_dir / "index.html"
destination.write_text(html, encoding="utf-8")
- write_json(report_dir / "summary.json", {"case_count": audit["case_count"],
- "accepted": sum(row["valid"] for row in audit["cases"]), "records_valid": audit["records_valid"]})
+ write_json(report_dir / "summary.json", {key: value for key, value in audit.items() if key != "cases"})
return destination
diff --git a/supratex/backview/harness/run_batch.py b/supratex/backview/harness/run_batch.py
index 2ceeb01..f99209e 100644
--- a/supratex/backview/harness/run_batch.py
+++ b/supratex/backview/harness/run_batch.py
@@ -25,8 +25,9 @@ def run_generation(run_root: Path, *, workers: int = 1, execute: bool = False,
case_ids: list[str] | None = None, retry_review: bool = False) -> dict:
"""Plan by default; execution requires Codex with Astra and built-in image_gen.
- A completed but visually rejected observation remains unaccepted. Corrections
- require retry_review=True; resume never silently spends another generation.
+ A completed needs_review observation may continue while retaining its label;
+ needs_regeneration remains blocked. Corrections to either require
+ retry_review=True; resume never silently spends another generation.
"""
root = Path(run_root).resolve()
if not 1 <= workers <= 3:
@@ -98,6 +99,14 @@ def run_generation(run_root: Path, *, workers: int = 1, execute: bool = False,
assignment = {"HARNESS_ROOT": str(root), "CASE_IDS": [task["case_id"]],
"PYTHON_EXECUTABLE": sys.executable, "START_ATTEMPT": next_attempt}
prompt = worker_prompt + "\nASSIGNMENT\n" + json.dumps(assignment, ensure_ascii=False) + "\n"
+ # Also applies to review recovery using older immutable prompt snapshots.
+ prompt += ("CURRENT REVIEW CONTRACT: after postprocessing, inspect back_rgba.png, back_rgb.png, "
+ "overlay.png and alignment.json. Only then set postprocessing_reviewed=true, copy "
+ "validation.json's processed_file_sha256 to reviewed_processed_file_sha256 and its "
+ "postprocessing_policy_sha256 unchanged into visual_review.json. Each defect must have "
+ "severity=minor|major and a concrete description; acceptable has no recorded defects, "
+ "minor defects require needs_review and any major defect requires needs_regeneration. "
+ "Never bind an existing review to changed outputs without inspecting them again.\n")
if review_only:
prompt += ("REVIEW-ONLY RECOVERY: do not call image_gen, do not register a new candidate, "
"and do not change the selected raw. Inspect the existing inputs and raw, run "
@@ -144,7 +153,9 @@ def run_generation(run_root: Path, *, workers: int = 1, execute: bool = False,
with ThreadPoolExecutor(max_workers=workers) as pool:
summary["statuses"] = list(pool.map(run, pending))
for task in tasks:
- process(task, root)
+ # Do not rewrite artifacts already inspected and bound by the worker.
+ if current_review(root, task) is None:
+ process(task, root)
summary["results"] = [validate_result(root, task["case_id"]) for task in tasks]
summary["success"] = (not blocked and all(s["run_success"] for s in summary["statuses"])
and all(r["valid"] for r in summary["results"]))
diff --git a/supratex/backview/workflow.py b/supratex/backview/workflow.py
index ac9efdf..5d99acf 100644
--- a/supratex/backview/workflow.py
+++ b/supratex/backview/workflow.py
@@ -77,7 +77,7 @@ def prepare_back_material(front_input_dir: Path, pack_dir: Path, run_root: Path,
front_receipt = validate_material_receipt(front_input_dir)
report = validate_result(run_root, case_id=case_id)
if report.get("valid") is not True:
- raise ValueError(f"generated back did not pass integrity and visual review: {report}")
+ raise ValueError(f"generated back did not pass integrity and inference eligibility checks: {report}")
for name in ("cameras.json", "back_mask.png", "back_normal.png", "front_rgb.png"):
if digest(run_root / "inputs" / case_id / name) != digest(pack_dir / name):
raise ValueError(f"harness input snapshot differs from this normal pack: {name}")
@@ -90,7 +90,8 @@ def prepare_back_material(front_input_dir: Path, pack_dir: Path, run_root: Path,
shutil.copytree(pack_dir, output_dir)
shutil.copyfile(generated, output_dir / "back_rgba.png")
record = {"status": "running", "stage": "prepare", "front_input": str(front_input_dir),
- "generation_run": str(run_root), "case_id": case_id}
+ "generation_run": str(run_root), "case_id": case_id,
+ "back_view_review": report["back_view_review"]}
write_json(output_dir / "back_material_run.json", record)
try:
prepare_condition(output_dir / "back_rgba.png", output_dir, case_id=case_id)
@@ -99,7 +100,8 @@ def prepare_back_material(front_input_dir: Path, pack_dir: Path, run_root: Path,
"generation_tool": report.get("generation_tool"),
"back_rgba_sha256": digest(output_dir / "back_rgba.png"),
"cameras_sha256": digest(output_dir / "cameras.json"),
- "run_root": str(run_root), "case_id": case_id, "validation": report}
+ "run_root": str(run_root), "case_id": case_id, "validation": report,
+ "back_view_review": report["back_view_review"]}
write_json(output_dir / "generation_receipt.json", generation)
camera = view_camera(cameras, "back")
camera = {key: value.tolist() if hasattr(value, "tolist") else value for key, value in camera.items()}
diff --git a/supratex/inference/dual_view.py b/supratex/inference/dual_view.py
index b176765..009a1c3 100644
--- a/supratex/inference/dual_view.py
+++ b/supratex/inference/dual_view.py
@@ -115,6 +115,11 @@ def load_back_case(input_dir: str | Path, back_view_dir: str | Path) -> dict[str
or current_generation.get("back_rgba_sha256") != generation["back_rgba_sha256"]
or current_generation.get("cameras_sha256") != generation["cameras_sha256"]):
raise ValueError("the original generation evidence is missing, changed, or no longer accepted")
+ # Keep the preparation receipt as history, but use the latest eligible review
+ # for this run. Legacy receipts have no snapshot to compare against.
+ review = current_generation["back_view_review"]
+ prepared_review = generation.get("back_view_review")
+ review_changed = prepared_review != review if prepared_review is not None else None
prepare = json.loads((back / "prepare.json").read_text(encoding="utf-8"))
if (prepare.get("status") != "complete" or prepare.get("source_sha256") != digest(back / "back_rgba.png")
or prepare.get("condition_rgba_sha256") != digest(back / "condition_rgba.png")
@@ -129,7 +134,8 @@ def load_back_case(input_dir: str | Path, back_view_dir: str | Path) -> dict[str
with Image.open(back / "mra.png") as image:
mra = image.copy()
return {"rgba": rgba, "albedo": albedo, "mra": mra, "mask": mask,
- "cameras": cameras, "root": back, "material": materials[1], "generation": generation}
+ "cameras": cameras, "root": back, "material": materials[1], "generation": generation,
+ "back_view_review": review, "review_changed_since_preparation": review_changed}
def trusted_mask(rgba: Image.Image) -> torch.Tensor:
@@ -246,7 +252,14 @@ def validate_result(work_dir: str | Path) -> dict[str, Any]:
if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value) or not threshold <= value <= 1:
raise ValueError(f"dual observation gate failed: {key}")
front, back = Path(receipt["front_input"]), Path(receipt["back_input"])
- load_back_case(front, back)
+ loaded = load_back_case(front, back)
+ review = loaded["back_view_review"]
+ snapshot_recorded = "back_view_review" in receipt or "back_view_review" in texture
+ if snapshot_recorded:
+ if receipt.get("back_view_review") != texture.get("back_view_review"):
+ raise ValueError("texture and final receipts disagree on back-view review")
+ if receipt.get("back_view_review") != review:
+ raise ValueError("back-view review changed after completion; the recorded snapshot is stale")
bindings = {"geometry_sha256": front / "geometry.pt", "cameras_sha256": back / "cameras.json",
"front_material_receipt_sha256": front / "material_receipt.json",
"back_material_receipt_sha256": back / "material_receipt.json"}
@@ -265,4 +278,6 @@ def validate_result(work_dir: str | Path) -> dict[str, Any]:
raise ValueError("the stitched mesh and published copy do not match their receipts")
return {"valid": True, "protocol": PROTOCOL, "camera_protocol": CAMERA_PROTOCOL,
"output": str(published), "receipt": str(work / "receipt.json"),
+ "back_view_review": review, "requires_review": review["requires_review"],
+ "review_snapshot_recorded": snapshot_recorded,
"candidate_19_phase_checked": True, "stitched_19_phase_checked": False}
diff --git a/supratex/inference/pipeline.py b/supratex/inference/pipeline.py
index d7d526b..379e6e2 100644
--- a/supratex/inference/pipeline.py
+++ b/supratex/inference/pipeline.py
@@ -632,6 +632,8 @@ def run_completion(*, input_dir: str | Path, output: str | Path, model_config: s
receipt = {"protocol": PROTOCOL, "camera_protocol": CAMERA_PROTOCOL, "view": "dual",
"status": "running", "stage": "texture", "front_input": str(front_root),
"back_input": str(back_root), "output": str(output),
+ "back_view_review": back["back_view_review"],
+ "review_changed_since_preparation": back["review_changed_since_preparation"],
"checkpoint": str(Path(checkpoint).expanduser().resolve()),
"model_config": str(Path(model_config).expanduser().resolve()),
"seed": seed, "sampler": "Euler", "steps": 25,
@@ -664,7 +666,9 @@ def run_completion(*, input_dir: str | Path, output: str | Path, model_config: s
final, validation, refine_error = None, None, error
# Model and reprojection work can be long-running. Revalidate the
# original inputs and generation evidence before publishing the mesh.
- load_back_case(front_root, back_root)
+ current_back = load_back_case(front_root, back_root)
+ if current_back["back_view_review"] != receipt["back_view_review"]:
+ raise RuntimeError("back-view review changed during dual-view completion; rerun with the current review")
bindings = {"geometry_sha256": front_root / "geometry.pt",
"cameras_sha256": back_root / "cameras.json",
"front_material_receipt_sha256": front_root / "material_receipt.json",