vibedgames 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
  2. package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
  3. package/assets/rebuild-object/LICENSE +201 -0
  4. package/assets/rebuild-object/NOTICE +7 -0
  5. package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
  6. package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
  7. package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
  8. package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
  9. package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
  10. package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
  11. package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
  12. package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
  13. package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
  14. package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
  15. package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
  16. package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
  17. package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
  18. package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
  19. package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
  20. package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
  21. package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
  22. package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
  23. package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
  24. package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
  25. package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
  26. package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
  27. package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
  28. package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
  29. package/assets/rebuild-object/forge/materials/__init__.py +17 -0
  30. package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
  31. package/assets/rebuild-object/forge/materials/reference.py +240 -0
  32. package/assets/rebuild-object/forge/next.py +116 -0
  33. package/assets/rebuild-object/forge/report.py +38 -0
  34. package/assets/rebuild-object/forge/requirements.txt +6 -0
  35. package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
  36. package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
  37. package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
  38. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
  39. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
  40. package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
  41. package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
  42. package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
  43. package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
  44. package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
  45. package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
  46. package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
  47. package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
  48. package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
  49. package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
  50. package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
  51. package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
  52. package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
  53. package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
  54. package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
  55. package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
  56. package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
  57. package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
  58. package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
  59. package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
  60. package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
  61. package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
  62. package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
  63. package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
  64. package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
  65. package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
  66. package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
  67. package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
  68. package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
  69. package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
  70. package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
  71. package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
  72. package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
  73. package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
  74. package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
  75. package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
  76. package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
  77. package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
  78. package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
  79. package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
  80. package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
  81. package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
  82. package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
  83. package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
  84. package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
  85. package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
  86. package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
  87. package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
  88. package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
  89. package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
  90. package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
  91. package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
  92. package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
  93. package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
  94. package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
  95. package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
  96. package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
  97. package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
  98. package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
  99. package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
  100. package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
  101. package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
  102. package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
  103. package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
  104. package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
  105. package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
  106. package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
  107. package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
  108. package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
  109. package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
  110. package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
  111. package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
  112. package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
  113. package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
  114. package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
  115. package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
  116. package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
  117. package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
  118. package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
  119. package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
  120. package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
  121. package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
  122. package/assets/rebuild-object/forge/state.py +98 -0
  123. package/assets/rebuild-object/steps.json +381 -0
  124. package/dist/{chunk-FXXVXDTW.js → chunk-24TITAFS.js} +1 -1
  125. package/dist/{chunk-OGX4DKIS.js → chunk-2C5PG2QO.js} +1 -1
  126. package/dist/{chunk-HYOXGNWS.js → chunk-2DEVOKI7.js} +1 -1
  127. package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
  128. package/dist/{chunk-S7HYWITX.js → chunk-2HXGMXGC.js} +1 -1
  129. package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
  130. package/dist/{chunk-VB4WLJR2.js → chunk-3IXRQTRF.js} +1 -1
  131. package/dist/{chunk-2KVQJKIZ.js → chunk-4ENHS32B.js} +23 -36
  132. package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
  133. package/dist/{chunk-4FJXCS3K.js → chunk-4ZGQKPK5.js} +1 -1
  134. package/dist/{chunk-SBXCK2I2.js → chunk-6CLUPFQA.js} +2 -2
  135. package/dist/{chunk-TXOE5UY5.js → chunk-7WTF2BA4.js} +1 -1
  136. package/dist/{chunk-R2WVORGD.js → chunk-AAXZNK4Z.js} +1 -1
  137. package/dist/{chunk-DOOQUFPG.js → chunk-ALLBT4FB.js} +1 -1
  138. package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
  139. package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
  140. package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
  141. package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
  142. package/dist/{chunk-SUSX3QIA.js → chunk-E72TFJZP.js} +1 -1
  143. package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
  144. package/dist/{chunk-U6DTE5IX.js → chunk-F7LYJSZE.js} +1 -1
  145. package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
  146. package/dist/{chunk-GLEW7VJQ.js → chunk-FPILHRLZ.js} +1 -1
  147. package/dist/{chunk-OPUCUUID.js → chunk-G63MXDX2.js} +4 -0
  148. package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
  149. package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
  150. package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
  151. package/dist/{chunk-RKS7SI5L.js → chunk-NO6KPV64.js} +1 -1
  152. package/dist/{chunk-KJK5CB6E.js → chunk-NXW3Z4Y4.js} +1 -1
  153. package/dist/{chunk-7RPLQWR2.js → chunk-OHOAZGO4.js} +1 -1
  154. package/dist/chunk-PYJNI5WD.js +83 -0
  155. package/dist/{chunk-NCX6LYNJ.js → chunk-Q4XAGTFX.js} +1 -1
  156. package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
  157. package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
  158. package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
  159. package/dist/{chunk-HX5Q63UA.js → chunk-T777EXAO.js} +1 -1
  160. package/dist/{chunk-UQ7VO6B3.js → chunk-TZZNRA3S.js} +1 -1
  161. package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
  162. package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
  163. package/dist/{chunk-ZHLPE6LI.js → chunk-UIKYK7KI.js} +1 -1
  164. package/dist/{chunk-KAGVI3CE.js → chunk-UJRSQO2B.js} +1 -1
  165. package/dist/{chunk-Q2QC6KAZ.js → chunk-V7LEYVXB.js} +29 -25
  166. package/dist/{chunk-DB7WVFS7.js → chunk-WRMQEXUC.js} +1 -1
  167. package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
  168. package/dist/{chunk-QLCVLCPM.js → chunk-X4QIOXNQ.js} +1 -1
  169. package/dist/{chunk-5YPLKGY3.js → chunk-Y6WHUK2O.js} +1 -1
  170. package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
  171. package/dist/index.js +20 -20
  172. package/package.json +32 -22
  173. package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
  174. package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
  175. package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env python3
2
+ """Intake-correctness cross-check (Plan 1.3 §4.6) — no semantic garbage-in.
3
+
4
+ Reference admission (§4.5) proves the image is a valid target; this proves the
5
+ intake actually UNDERSTOOD it. A vague prompt can make intake confidently
6
+ mis-classify (a knife specced as a "spoon"); if that wrong guess drives spec
7
+ authoring, everything downstream is wrong. So before spec authoring proceeds, the
8
+ intake's object-class/material guess is (a) exposed as `assumptionsExposed`, and
9
+ (b) cross-checked against an objectness verdict. A contradiction HALTS to
10
+ request-input rather than building a wrong spec.
11
+
12
+ Scaffold note (§4.6 + build order §8.5): the objectness verdict ideally comes from
13
+ OSIM (Phase 3, deterministic, zero-token) or, failing that, one cheap VLM objectness
14
+ call. This module owns the DECISION/control-flow now; the objectness source is
15
+ pluggable and wired in Phase 3. With no verdict available, it proceeds but records
16
+ that confirmation is deferred — never silently claims confirmation it didn't get.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ # A contradiction only halts when the objectness signal is confident enough to be trusted.
28
+ CONTRADICTION_CONFIDENCE_MIN = 0.6
29
+
30
+
31
+ def expose_assumptions(assessment: dict[str, Any]) -> dict[str, Any]:
32
+ """Extract the intake's confident guesses so a wrong default is visible, not buried."""
33
+ psa = assessment.get("preSpecAssessment", assessment)
34
+ obj = psa.get("objectClass", {}) if isinstance(psa.get("objectClass"), dict) else {}
35
+ return {
36
+ "primaryType": obj.get("primaryType"),
37
+ "primaryDomain": obj.get("primaryDomain"),
38
+ "materialFamilies": obj.get("materialFamilies", []),
39
+ }
40
+
41
+
42
+ def decide(
43
+ assessment: dict[str, Any],
44
+ objectness_verdict: dict[str, Any] | None,
45
+ ) -> dict[str, Any]:
46
+ """Decide whether spec authoring may proceed.
47
+
48
+ objectness_verdict (pluggable; from OSIM in Phase 3 or a VLM objectness call):
49
+ {"matchesDeclaredClass": bool, "confidence": float, "detectedClass": str}
50
+ or None when no objectness source is available yet.
51
+
52
+ Returns {action: 'proceed'|'halt', confirmed: bool, assumptionsExposed, reason}.
53
+ """
54
+ assumptions = expose_assumptions(assessment)
55
+
56
+ if objectness_verdict is None:
57
+ return {
58
+ "action": "proceed",
59
+ "confirmed": False,
60
+ "assumptionsExposed": assumptions,
61
+ "reason": (
62
+ "no objectness source available yet — confirmation DEFERRED to Phase 3 (OSIM). "
63
+ "Proceeding on exposed assumptions; they remain falsifiable at Divine-Eye review."
64
+ ),
65
+ }
66
+
67
+ matches = bool(objectness_verdict.get("matchesDeclaredClass"))
68
+ confidence = float(objectness_verdict.get("confidence", 0.0))
69
+ detected = objectness_verdict.get("detectedClass")
70
+
71
+ if not matches and confidence >= CONTRADICTION_CONFIDENCE_MIN:
72
+ return {
73
+ "action": "halt",
74
+ "confirmed": False,
75
+ "assumptionsExposed": assumptions,
76
+ "reason": (
77
+ f"intake declared object class {assumptions.get('primaryType')!r} but the objectness "
78
+ f"check detected {detected!r} (confidence {confidence:.2f} ≥ {CONTRADICTION_CONFIDENCE_MIN}). "
79
+ "Halting to request-input rather than building a wrong spec (§4.6)."
80
+ ),
81
+ }
82
+
83
+ return {
84
+ "action": "proceed",
85
+ "confirmed": matches,
86
+ "assumptionsExposed": assumptions,
87
+ "reason": (
88
+ f"objectness check {'confirms' if matches else 'does not contradict'} the declared class "
89
+ f"(confidence {confidence:.2f})."
90
+ ),
91
+ }
92
+
93
+
94
+ def main(argv: list[str]) -> int:
95
+ parser = argparse.ArgumentParser(description=__doc__)
96
+ parser.add_argument("assessment", type=Path, help="assessment/spec JSON with preSpecAssessment.objectClass")
97
+ parser.add_argument("--objectness", type=Path, help="optional objectness verdict JSON (matchesDeclaredClass/confidence/detectedClass)")
98
+ parser.add_argument("--json", action="store_true")
99
+ args = parser.parse_args(argv)
100
+
101
+ assessment = json.loads(args.assessment.read_text(encoding="utf-8"))
102
+ verdict = json.loads(args.objectness.read_text(encoding="utf-8")) if args.objectness else None
103
+ result = decide(assessment, verdict)
104
+
105
+ if args.json:
106
+ print(json.dumps(result, indent=2, ensure_ascii=False))
107
+ else:
108
+ print(f"action: {result['action'].upper()} confirmed={result['confirmed']}")
109
+ print(f" assumptions: {result['assumptionsExposed']}")
110
+ print(f" reason: {result['reason']}")
111
+ # Exit 1 on halt so a pipeline runner can gate on it; 0 on proceed.
112
+ return 1 if result["action"] == "halt" else 0
113
+
114
+
115
+ if __name__ == "__main__":
116
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env python3
2
+ """Reference-admission gate (Plan 1.3 §4.5.2) — no meaningless references.
3
+
4
+ Before an image/crop is admitted as ground truth for a component or the whole
5
+ object, it must pass deterministic checks so the Divine Eye never compares a
6
+ render against junk (empty mask, fragmented subject, too-small crop, a duplicate
7
+ angle that adds no information). A reference that fails is rejected WITH A REASON
8
+ at intake, before any tokens are spent — never silently used.
9
+
10
+ Pure Python stdlib (reuses extract_pbr_evidence's mask primitives + the shared
11
+ pHash). No PIL/numpy.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
23
+ from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
24
+
25
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
26
+ from image_hash import hamming, phash_from_image # noqa: E402
27
+
28
+
29
+ # Thresholds (calibratable in Plan 1.3 §5; conservative defaults here).
30
+ MIN_FOREGROUND_COVERAGE = 0.05
31
+ MAX_FOREGROUND_COVERAGE = 0.97
32
+ MIN_SHORT_SIDE_PX = 64
33
+ MIN_LARGEST_COMPONENT_FRACTION = 0.60 # largest blob must be ≥60% of all foreground
34
+ DUPLICATE_HAMMING_THRESHOLD = 6 # pHash distance ≤ this vs an admitted ref ⇒ duplicate
35
+ COHERENCE_GRID = 96 # downsample mask to this side for connected-component analysis
36
+
37
+
38
+ def largest_component_fraction(
39
+ mask: list[bool], width: int, height: int, grid: int = COHERENCE_GRID
40
+ ) -> float:
41
+ """Fraction of foreground occupied by its single largest 4-connected blob,
42
+ computed on a downsampled grid. ~1.0 = one coherent subject; low = scattered
43
+ fragments (a meaningless silhouette for IoU/DCD)."""
44
+ if width <= 0 or height <= 0 or not mask:
45
+ return 0.0
46
+ g = min(grid, max(1, width), max(1, height))
47
+ cell = [[False] * g for _ in range(g)]
48
+ for idx, on in enumerate(mask):
49
+ if not on:
50
+ continue
51
+ x = idx % width
52
+ y = idx // width
53
+ if y >= height:
54
+ break
55
+ cell[min(g - 1, y * g // height)][min(g - 1, x * g // width)] = True
56
+ total = sum(1 for row in cell for c in row if c)
57
+ if total == 0:
58
+ return 0.0
59
+ seen = [[False] * g for _ in range(g)]
60
+ best = 0
61
+ for sy in range(g):
62
+ for sx in range(g):
63
+ if not cell[sy][sx] or seen[sy][sx]:
64
+ continue
65
+ size = 0
66
+ stack = [(sy, sx)]
67
+ seen[sy][sx] = True
68
+ while stack:
69
+ cy, cx = stack.pop()
70
+ size += 1
71
+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
72
+ ny, nx = cy + dy, cx + dx
73
+ if 0 <= ny < g and 0 <= nx < g and cell[ny][nx] and not seen[ny][nx]:
74
+ seen[ny][nx] = True
75
+ stack.append((ny, nx))
76
+ best = max(best, size)
77
+ return best / total
78
+
79
+
80
+ def check_admission(
81
+ crop_path: Path,
82
+ viewpoint: str = "reference",
83
+ against_hashes: list[int] | None = None,
84
+ ) -> dict[str, Any]:
85
+ """Return an admission verdict dict with reasons + a provenance tag.
86
+
87
+ `against_hashes` are pHashes of already-admitted references; a near-duplicate
88
+ (Hamming ≤ threshold) is rejected as adding no information."""
89
+ reasons: list[str] = []
90
+ try:
91
+ width, height, pixels, _load_warnings = load_image(crop_path)
92
+ except Exception as exc: # noqa: BLE001
93
+ # A reference that cannot even be decoded is a clean rejection, not a crash —
94
+ # an undecodable image is the most meaningless "reference" of all.
95
+ return {
96
+ "admitted": False,
97
+ "reasons": [f"cannot decode image as a usable reference: {type(exc).__name__}: {exc}"],
98
+ "provenance": {
99
+ "viewpoint": viewpoint,
100
+ "sourcePath": str(crop_path.resolve()),
101
+ "width": 0,
102
+ "height": 0,
103
+ "foregroundCoverage": 0.0,
104
+ "largestComponentFraction": 0.0,
105
+ "pHash": None,
106
+ "duplicateOfHash": None,
107
+ },
108
+ }
109
+
110
+ short_side = min(width, height)
111
+ if short_side < MIN_SHORT_SIDE_PX:
112
+ reasons.append(
113
+ f"resolution floor: short side {short_side}px < {MIN_SHORT_SIDE_PX}px "
114
+ "(too few pixels to derive geometry/color reliably)"
115
+ )
116
+
117
+ mask, diag, _mask_warnings = build_foreground_mask(width, height, pixels)
118
+ coverage = float(diag.get("foregroundCoverage", 0.0))
119
+ if coverage < MIN_FOREGROUND_COVERAGE:
120
+ reasons.append(
121
+ f"foreground coverage {coverage:.3f} < {MIN_FOREGROUND_COVERAGE} "
122
+ "(empty/near-empty — meaningless silhouette)"
123
+ )
124
+ elif coverage > MAX_FOREGROUND_COVERAGE:
125
+ reasons.append(
126
+ f"foreground coverage {coverage:.3f} > {MAX_FOREGROUND_COVERAGE} "
127
+ "(no background to segment against — silhouette not isolable)"
128
+ )
129
+
130
+ coherence = largest_component_fraction(mask, width, height)
131
+ if coverage >= MIN_FOREGROUND_COVERAGE and coherence < MIN_LARGEST_COMPONENT_FRACTION:
132
+ reasons.append(
133
+ f"mask coherence: largest connected blob is {coherence:.2f} of foreground "
134
+ f"< {MIN_LARGEST_COMPONENT_FRACTION} (fragmented/scattered subject — ambiguous)"
135
+ )
136
+
137
+ ref_hash = phash_from_image(width, height, pixels)
138
+ duplicate_of: int | None = None
139
+ for other in against_hashes or []:
140
+ if hamming(ref_hash, other) <= DUPLICATE_HAMMING_THRESHOLD:
141
+ duplicate_of = other
142
+ reasons.append(
143
+ f"duplicate/near-duplicate: pHash within {DUPLICATE_HAMMING_THRESHOLD} of an "
144
+ "already-admitted reference (adds no information)"
145
+ )
146
+ break
147
+
148
+ admitted = not reasons
149
+ return {
150
+ "admitted": admitted,
151
+ "reasons": reasons,
152
+ "provenance": {
153
+ "viewpoint": viewpoint,
154
+ "sourcePath": str(crop_path.resolve()),
155
+ "width": width,
156
+ "height": height,
157
+ "foregroundCoverage": round(coverage, 4),
158
+ "largestComponentFraction": round(coherence, 4),
159
+ "pHash": ref_hash,
160
+ "duplicateOfHash": duplicate_of,
161
+ },
162
+ }
163
+
164
+
165
+ def main(argv: list[str]) -> int:
166
+ parser = argparse.ArgumentParser(description=__doc__)
167
+ parser.add_argument("image", type=Path)
168
+ parser.add_argument("--viewpoint", default="reference", help="viewpoint tag this ref is ground truth for")
169
+ parser.add_argument(
170
+ "--against",
171
+ default="",
172
+ help="comma-separated pHashes (ints) of already-admitted references, for duplicate detection",
173
+ )
174
+ parser.add_argument("--json", action="store_true", help="emit the verdict as JSON")
175
+ args = parser.parse_args(argv)
176
+
177
+ against: list[int] = []
178
+ for token in args.against.split(","):
179
+ token = token.strip()
180
+ if token:
181
+ try:
182
+ against.append(int(token))
183
+ except ValueError:
184
+ print(f"warning: ignoring non-integer --against token {token!r}", file=sys.stderr)
185
+
186
+ try:
187
+ verdict = check_admission(args.image.expanduser().resolve(), args.viewpoint, against)
188
+ except Exception as exc: # noqa: BLE001
189
+ print(f"error: {exc}", file=sys.stderr)
190
+ return 2
191
+
192
+ if args.json:
193
+ print(json.dumps(verdict, indent=2, ensure_ascii=False))
194
+ else:
195
+ status = "ADMITTED" if verdict["admitted"] else "REJECTED"
196
+ print(f"{status} ({verdict['provenance']['viewpoint']}) pHash={verdict['provenance']['pHash']}")
197
+ for reason in verdict["reasons"]:
198
+ print(f" - {reason}")
199
+ return 0 if verdict["admitted"] else 1
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+
8
+ def resolve_identity(
9
+ explicit: dict[str, Any] | None,
10
+ resolved: dict[str, Any] | None,
11
+ classification: dict[str, Any] | None,
12
+ ) -> dict[str, Any]:
13
+ if explicit:
14
+ return {"status": "resolved", "identity": dict(explicit), "provenance": "explicit-user-metadata"}
15
+ if resolved and resolved.get("status") == "ambiguous":
16
+ return {"status": "ambiguous", "candidates": list(resolved.get("candidates", []))}
17
+ if resolved and resolved.get("status") == "no-match":
18
+ return {"status": "no-match", "reason": resolved.get("reason", "metadata lookup found no match")}
19
+ if resolved and resolved.get("status") in {None, "resolved"}:
20
+ return {"status": "resolved", "identity": dict(resolved), "provenance": "resolved-metadata"}
21
+ if classification and classification.get("itemFamily"):
22
+ return {"status": "resolved", "identity": dict(classification), "provenance": "classification-record"}
23
+ return {"status": "request-input", "reason": "authoritative identity evidence is unavailable"}
24
+
25
+
26
+ def normalize_cs2_metadata(metadata: dict[str, Any]) -> dict[str, Any]:
27
+ float_value = metadata.get("float", metadata.get("floatValue"))
28
+ paint_seed = metadata.get("paintSeed", metadata.get("paint_seed"))
29
+ hidden_confidence = metadata.get("hiddenRegionConfidence")
30
+ if not isinstance(hidden_confidence, (int, float)):
31
+ hidden_confidence = 0.25
32
+ return {
33
+ "identity": {
34
+ "name": metadata.get("name", metadata.get("itemName")),
35
+ "paintIndex": metadata.get("paintIndex", metadata.get("paint_index")),
36
+ "rarity": metadata.get("rarity"),
37
+ "previewUrl": metadata.get("previewUrl", metadata.get("imageUrl")),
38
+ "floatRange": metadata.get("floatRange", {"min": metadata.get("minFloat"), "max": metadata.get("maxFloat")}),
39
+ },
40
+ "float": float_value,
41
+ "paintSeed": paint_seed,
42
+ "finishStyle": metadata.get("finishStyle"),
43
+ "approximations": {
44
+ "float": {"value": float_value, "approximated": float_value is None, "confidence": 0.0 if float_value is None else 1.0},
45
+ "paintSeed": {"value": paint_seed, "approximated": paint_seed is None, "confidence": 0.0 if paint_seed is None else 1.0},
46
+ "hiddenRegions": {"confidence": float(hidden_confidence), "approximated": True},
47
+ "finishStyle": {"value": metadata.get("finishStyle"), "approximated": metadata.get("finishStyle") is None},
48
+ },
49
+ }
50
+
51
+
52
+ def enrich_manifest_with_metadata(manifest: dict[str, Any], resolution: dict[str, Any]) -> dict[str, Any]:
53
+ result = dict(manifest)
54
+ result["metadataResolution"] = dict(resolution)
55
+ result.setdefault("warnings", [])
56
+ warnings = list(result["warnings"])
57
+ if resolution.get("status") in {"no-match", "ambiguous"}:
58
+ if "metadata-unavailable" not in warnings:
59
+ warnings.append("metadata-unavailable")
60
+ result["exactnessTier"] = result.get("exactnessTier", "image-only")
61
+ elif resolution.get("status") == "resolved":
62
+ result["metadata"] = normalize_cs2_metadata(resolution.get("identity", resolution))
63
+ if result.get("exactnessTier") == "image-only":
64
+ result["exactnessTier"] = "metadata-assisted"
65
+ result["warnings"] = warnings
66
+ return result
67
+
68
+
69
+ def classify_map_path(path: Path) -> dict[str, Any]:
70
+ name = path.name.lower()
71
+ if any(token in name for token in ("_orm", "_mrao", "_packed")):
72
+ return {"mapClass": "packed", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard", "packedChannels": {"roughness": "r", "metalness": "g", "ao": "b"}}
73
+ if any(token in name for token in ("_normal", "_nrm", "_bump")):
74
+ return {"mapClass": "normal", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
75
+ if any(token in name for token in ("_rough", "_roughness")):
76
+ return {"mapClass": "roughness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
77
+ if any(token in name for token in ("_metal", "_metalness")):
78
+ return {"mapClass": "metalness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
79
+ if any(token in name for token in ("_ao", "_occlusion")):
80
+ return {"mapClass": "ao", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
81
+ if any(token in name for token in ("_height", "_displacement")):
82
+ return {"mapClass": "height", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
83
+ if any(token in name for token in ("_mask", "_wear", "_pattern")):
84
+ return {"mapClass": "mask", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}
85
+ return {"mapClass": "albedo", "path": str(path), "colorSpace": "srgb", "uvOrientation": "standard"}
86
+
87
+
88
+ def adapt_texture_result(extraction: dict[str, Any], output_dir: Path) -> dict[str, Any]:
89
+ if extraction.get("status") != "ok":
90
+ return {"status": "fallback", "textureSource": "image-only", "reason": extraction.get("reason", "texture extraction unavailable")}
91
+ records: list[dict[str, Any]] = []
92
+ for path in sorted(output_dir.rglob("*")):
93
+ if path.is_file():
94
+ record = classify_map_path(path)
95
+ record.update({"source": "local-vpk", "ipBoundary": "local-user-install-not-redistributable"})
96
+ records.append(record)
97
+ return {"status": "ok", "textureSource": "local-vpk", "assets": records}
98
+
99
+
100
+ def map_assets_to_reference_pbr(records: list[dict[str, Any]]) -> dict[str, Any]:
101
+ channels: dict[str, dict[str, Any]] = {}
102
+ for record in records:
103
+ map_class = record.get("mapClass")
104
+ if map_class in {"albedo", "normal", "roughness", "metalness", "height", "ao", "mask"}:
105
+ channels.setdefault(str(map_class), dict(record))
106
+ elif map_class == "packed":
107
+ for channel, packed_channel in record.get("packedChannels", {}).items():
108
+ channels.setdefault(channel, {"path": record.get("path"), "source": record.get("source", "local-vpk"), "derived": True, "packedChannel": packed_channel, "colorSpace": "linear", "uvOrientation": record.get("uvOrientation", "standard")})
109
+ missing = [channel for channel in ("albedo", "normal", "roughness", "metalness") if channel not in channels]
110
+ if "ao" not in channels:
111
+ channels["ao"] = {"derived": True, "from": "normal-or-geometry", "confidence": 0.25}
112
+ return {"maps": channels, "missingRequired": missing, "complete": not missing}
113
+
114
+
115
+ def validate_route_requirements(manifest: dict[str, Any], *, allow_fallback: bool = False) -> dict[str, Any]:
116
+ result = dict(manifest)
117
+ route = result.get("route")
118
+ tier = result.get("exactnessTier")
119
+ if route == "reference-projection":
120
+ camera = result.get("camera", {})
121
+ projection = result.get("projection", {})
122
+ has_camera = camera.get("status") == "solved" or bool(camera.get("referenceCamera"))
123
+ has_delit = bool(result.get("deLitAlbedo") or projection.get("deLitSource"))
124
+ if not (has_camera and has_delit):
125
+ if allow_fallback:
126
+ result["route"] = "procedural-finish"
127
+ result["state"] = "fallback"
128
+ result.setdefault("warnings", []).append("projection-evidence-unavailable; procedural fallback selected")
129
+ else:
130
+ result["state"] = "request-input"
131
+ return result
132
+ if route == "authored-texture":
133
+ assets = result.get("assets", {}).get("records", []) if isinstance(result.get("assets"), dict) else []
134
+ channels = {item.get("mapClass") for item in assets if isinstance(item, dict)}
135
+ if not {"albedo", "normal"}.issubset(channels) or not ({"roughness", "packed"} & channels):
136
+ result["state"] = "request-input" if tier == "exact-texture" else "fallback"
137
+ if tier == "exact-texture" and route != "authored-texture":
138
+ result["state"] = "request-input"
139
+ return result