Mike0021 commited on
Commit
605a39e
·
verified ·
1 Parent(s): 0b0db20

PBR option: pbr=true / POST /api/jobs/{id}/pbr (per-view albedo/roughness/metallic from the projtex-pbr ZeroGPU Space, baked into a metallicRoughness GLB)

Browse files
Files changed (7) hide show
  1. app/jobs.py +64 -1
  2. app/llms.txt +10 -1
  3. app/server.py +27 -3
  4. projtex/mesh.py +19 -6
  5. projtex/pbr.py +117 -0
  6. projtex/project.py +96 -0
  7. tests/smoke.py +8 -1
app/jobs.py CHANGED
@@ -774,6 +774,8 @@ class JobManager:
774
  bake = p.bake()
775
  job.result["bake"] = {"resolution": bake["resolution"], "views_used": bake["views_used"],
776
  "layer_texels": bake["layer_texels"]}
 
 
777
  job.progress = {"step": "rendering previews"}
778
  p.render(turntable=8, size=640, compare_source=bool(p.data["mesh"].get("textured_materials")))
779
  from projtex.report import views_sheet
@@ -966,6 +968,65 @@ class JobManager:
966
  self._submit(job, "undo_retouch", op)
967
  return job
968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
969
  def bake(self, job_id: str, resolution: int, single_mesh: bool | None = None) -> Job:
970
  job = self.get(job_id)
971
  self._object_only(job)
@@ -1099,7 +1160,9 @@ def job_files(job: Job) -> dict:
1099
  for key, rel in (("textured_glb", "bake/textured.glb"), ("albedo", "bake/albedo.png"),
1100
  ("coverage_map", "bake/coverage.png"), ("contact_sheet", "renders/contact_sheet.png"),
1101
  ("comparison", "renders/comparison.png"), ("views_sheet", "renders/views_sheet.png"),
1102
- ("problems_map", "inspect/problems.png")):
 
 
1103
  if (r / rel).exists():
1104
  out[key] = rel
1105
  if (r / "renders").exists():
 
774
  bake = p.bake()
775
  job.result["bake"] = {"resolution": bake["resolution"], "views_used": bake["views_used"],
776
  "layer_texels": bake["layer_texels"]}
777
+ if job.params.get("pbr"):
778
+ self._pbr(job, p)
779
  job.progress = {"step": "rendering previews"}
780
  p.render(turntable=8, size=640, compare_source=bool(p.data["mesh"].get("textured_materials")))
781
  from projtex.report import views_sheet
 
968
  self._submit(job, "undo_retouch", op)
969
  return job
970
 
971
+ def _decomposer(self, job: Job):
972
+ """The PBR decomposer for this job (the caller's quota), giving the CPU slot back while it runs."""
973
+ from projtex.pbr import MockDecomposer, SpaceDecomposer
974
+
975
+ if job.params.get("backend") == "mock":
976
+ return MockDecomposer()
977
+ inner, sem = SpaceDecomposer(**{k: v for k, v in self._ident_kw(job).items() if k != "anonymous"}), self.cpu
978
+
979
+ class Yielding:
980
+ name = inner.name
981
+
982
+ def decompose(self, image):
983
+ sem.release()
984
+ try:
985
+ return inner.decompose(image)
986
+ finally:
987
+ sem.acquire()
988
+
989
+ return Yielding()
990
+
991
+ def _pbr(self, job: Job, p) -> None:
992
+ """PBR maps for every view, then the PBR bake. A failure leaves the colour result as it is."""
993
+ def prog(k, n, name):
994
+ job.progress = {"step": "PBR maps", "done": k, "total": n, "last": name}
995
+
996
+ job.progress = {"step": "PBR maps"}
997
+ try:
998
+ out = p.pbr_views(self._decomposer(job), progress=prog)
999
+ job.progress = {"step": "baking PBR maps"}
1000
+ info = p.bake_pbr()
1001
+ job.result["pbr"] = {"views": len(out["views"]), "decomposed_now": len(out["decomposed"]),
1002
+ "metallic_fraction": info["metallic_fraction"],
1003
+ "roughness_mean": info["roughness_mean"]}
1004
+ job.event(f"PBR: {len(out['views'])} views split into albedo, roughness and metallic")
1005
+ except Exception as exc: # noqa: BLE001 - the colour texture is done: report and keep it
1006
+ log.exception("PBR failed for %s", job.id)
1007
+ job.result["pbr"] = {"error": str(exc)[:300]}
1008
+ job.result.setdefault("warnings", []).append(
1009
+ f"PBR maps failed ({str(exc)[:160]}); the colour texture is unaffected. Retry with POST "
1010
+ f"/api/jobs/{job.id}/pbr")
1011
+
1012
+ def pbr(self, job_id: str, identity: Identity) -> Job:
1013
+ """Add PBR materials to a finished texture job (views already decomposed are reused)."""
1014
+ job = self.get(job_id)
1015
+ self._object_only(job)
1016
+ self._refresh_identity(job, identity)
1017
+
1018
+ def op(j: Job):
1019
+ p = self._open(j)
1020
+ try:
1021
+ j.params["pbr"] = True
1022
+ self._pbr(j, p)
1023
+ j.progress = {"step": "done"}
1024
+ finally:
1025
+ self._close(p)
1026
+
1027
+ self._submit(job, "pbr", op)
1028
+ return job
1029
+
1030
  def bake(self, job_id: str, resolution: int, single_mesh: bool | None = None) -> Job:
1031
  job = self.get(job_id)
1032
  self._object_only(job)
 
1160
  for key, rel in (("textured_glb", "bake/textured.glb"), ("albedo", "bake/albedo.png"),
1161
  ("coverage_map", "bake/coverage.png"), ("contact_sheet", "renders/contact_sheet.png"),
1162
  ("comparison", "renders/comparison.png"), ("views_sheet", "renders/views_sheet.png"),
1163
+ ("problems_map", "inspect/problems.png"), ("textured_pbr_glb", "bake/textured_pbr.glb"),
1164
+ ("albedo_pbr", "bake/albedo_pbr.png"), ("roughness", "bake/roughness.png"),
1165
+ ("metallic", "bake/metallic.png"), ("metallic_roughness", "bake/metallic_roughness.png")):
1166
  if (r / rel).exists():
1167
  out[key] = rel
1168
  if (r / "renders").exists():
app/llms.txt CHANGED
@@ -58,7 +58,8 @@ default backend qwen-turbo, about 30 s with qwen-space).
58
  - textured_glb has the same objects (node names and transforms) and materials (names, metallic, roughness, alpha,
59
  emission, and glTF material extensions such as glass transmission/IOR, emissive strength or clearcoat) as the
60
  file you sent, in the same orientation; every material's base colour now uses one shared baked texture atlas.
61
- Normal/roughness/metallic maps are not produced. Import it in place of your model:
 
62
  Blender: bpy.ops.import_scene.gltf(filepath="textured.glb") (objects keep their names; the image is packed in
63
  the GLB). three.js: GLTFLoader; the texture is sRGB and already flagged as such; `getObjectByName` works with
64
  your original names.
@@ -66,6 +67,14 @@ default backend qwen-turbo, about 30 s with qwen-space).
66
  fits your original model directly: plug it into your own material's base colour. If they were regenerated
67
  (they overlapped or were missing, e.g. three.js BoxGeometry/CylinderGeometry, Blender primitives after joining),
68
  use the GLB, whose UVs are new. Force a choice with "uv": "keep" | "regen".
 
 
 
 
 
 
 
 
69
  - Game-ready single asset: "single_mesh": true returns one object with one material (metallic/roughness are the
70
  area-weighted means of yours); POST /api/jobs/{id}/bake {"single_mesh": true} switches an existing job.
71
  - Prepare meshes like this: one GLB with all parts (several objects and materials are fine), modifiers applied,
 
58
  - textured_glb has the same objects (node names and transforms) and materials (names, metallic, roughness, alpha,
59
  emission, and glTF material extensions such as glass transmission/IOR, emissive strength or clearcoat) as the
60
  file you sent, in the same orientation; every material's base colour now uses one shared baked texture atlas.
61
+ Roughness/metallic maps come with "pbr": true (below); normal maps are not produced. Import it in place of your
62
+ model:
63
  Blender: bpy.ops.import_scene.gltf(filepath="textured.glb") (objects keep their names; the image is packed in
64
  the GLB). three.js: GLTFLoader; the texture is sRGB and already flagged as such; `getObjectByName` works with
65
  your original names.
 
67
  fits your original model directly: plug it into your own material's base colour. If they were regenerated
68
  (they overlapped or were missing, e.g. three.js BoxGeometry/CylinderGeometry, Blender primitives after joining),
69
  use the GLB, whose UVs are new. Force a choice with "uv": "keep" | "regen".
70
+ - PBR materials: "pbr": true (or POST /api/jobs/{id}/pbr on a finished job) splits every generated view into
71
+ albedo, roughness and metallic maps (a LoRA for Qwen-Image-Edit-2511 trained on renders of MatSynth materials,
72
+ 4 steps on a ZeroGPU Space with your quota, ~5 s per view) and bakes them like the colour: files.textured_pbr_glb
73
+ has a de-lit base colour and a glTF metallicRoughness texture (G roughness, B metallic) on every material, so the
74
+ model reacts to your scene's light (varnished wood and porcelain catch highlights, brass and chrome reflect);
75
+ files.albedo_pbr, roughness, metallic, metallic_roughness are the maps for your own material. Material names and
76
+ part_prompts settle metal or not where they say it ("Brass", "walnut veneer", "gloss paint"): glossy paint can
77
+ otherwise come out metallic. pbr.metallic_fraction and pbr.roughness_mean in the status summarise the result.
78
  - Game-ready single asset: "single_mesh": true returns one object with one material (metallic/roughness are the
79
  area-weighted means of yours); POST /api/jobs/{id}/bake {"single_mesh": true} switches an existing job.
80
  - Prepare meshes like this: one GLB with all parts (several objects and materials are fine), modifiers applied,
app/server.py CHANGED
@@ -224,6 +224,8 @@ def status_payload(job, base: str, events: int = 12) -> dict:
224
  pending = None
225
  if job.result.get("model"):
226
  out["model"] = job.result["model"]
 
 
227
  if job.result.get("warnings"):
228
  out["warnings"] = job.result["warnings"]
229
  if job.state == "waiting_for_images":
@@ -460,6 +462,11 @@ class TextureRequest(BaseModel):
460
  lighting: Literal["flat", "soft", "natural"] | None = Field(None, description="Lighting asked of the model "
461
  "(flat = albedo-like, default).")
462
  texture_size: int | None = Field(None, description="Baked texture size: 1024, 2048 (default) or 4096.")
 
 
 
 
 
463
  view_size: int | None = Field(None, description="Generated image size per view (512-1024, default 1024).")
464
  up: Literal["auto", "y", "z", "-z", "x"] | None = Field(None, description="Up axis of the asset if not +Y "
465
  "(GLB is always +Y). The result keeps "
@@ -613,6 +620,11 @@ class RetouchRequest(BaseModel):
613
  hf_token: str | None = None
614
 
615
 
 
 
 
 
 
616
  class BakeRequest(BaseModel):
617
  resolution: Literal[1024, 2048, 4096] = 2048
618
  single_mesh: bool | None = Field(None, description="true: one object, one material; false: your objects and "
@@ -662,7 +674,8 @@ def texture_mesh(prompt: str = "", upload_id: str = "", mesh_url: str = "", mesh
662
  mode: str = "", backend: str = "qwen-turbo", subject: str = "", preset: str = "",
663
  focus_prompt: str = "", texture_size: int = 0, uv: str = "", up: str = "",
664
  part_prompts: dict[str, str] | None = None, single_mesh: bool = False, inside: str = "",
665
- metal: str = "", pattern_swatches: str = "", hf_token: str = "", ctx: Context | None = None) -> dict:
 
666
  """Start texturing a mesh; returns a job id immediately (the job takes ~15 s per view with qwen-turbo).
667
  Mesh: upload_id (from REST POST /api/uploads with the file as raw body), mesh_url (public .glb/.obj/.ply/.stl/
668
  .zip), mesh_base64 (the file itself, up to 20 MB) or sample ('avocado' | 'lantern' | 'head'). prompt: materials
@@ -673,12 +686,13 @@ def texture_mesh(prompt: str = "", upload_id: str = "", mesh_url: str = "", mesh
673
  names only the parts it shows (recommended for multi-part models). The result GLB keeps your objects and
674
  materials (single_mesh: one object, one material instead). inside: plain (default: the inside of a mug or vase
675
  gets its material's main colour) | paint. metal: keep (default: painted reflections) | flat (chrome-like
676
- materials get an even base colour, for renderers with environment lighting). Then poll get_job."""
 
677
  params = {k: v for k, v in dict(prompt=prompt, upload_id=upload_id, sample=sample, mesh_url=mesh_url, mode=mode,
678
  backend=backend, subject=subject, preset=preset, focus_prompt=focus_prompt,
679
  texture_size=texture_size, uv=uv, up=up, part_prompts=part_prompts,
680
  single_mesh=single_mesh, inside=inside, metal=metal,
681
- pattern_swatches=pattern_swatches).items() if v}
682
 
683
  def run():
684
  return status_payload(MANAGER.create(params, _mcp_ident(ctx, hf_token or None),
@@ -1153,6 +1167,16 @@ def api_bake(job_id: str, req: BakeRequest, request: Request) -> dict:
1153
  raise http_error(exc)
1154
 
1155
 
 
 
 
 
 
 
 
 
 
 
1156
  @app.post("/api/jobs/{job_id}/pick", tags=["quality loop"],
1157
  summary="3D point / normal / UV under image pixels (to aim a retouch)")
1158
  def api_pick(job_id: str, req: PickRequest) -> dict:
 
224
  pending = None
225
  if job.result.get("model"):
226
  out["model"] = job.result["model"]
227
+ if job.result.get("pbr"):
228
+ out["pbr"] = job.result["pbr"]
229
  if job.result.get("warnings"):
230
  out["warnings"] = job.result["warnings"]
231
  if job.state == "waiting_for_images":
 
462
  lighting: Literal["flat", "soft", "natural"] | None = Field(None, description="Lighting asked of the model "
463
  "(flat = albedo-like, default).")
464
  texture_size: int | None = Field(None, description="Baked texture size: 1024, 2048 (default) or 4096.")
465
+ pbr: bool | None = Field(None, description="Also make PBR materials: every view is split into albedo, roughness "
466
+ "and metallic maps (a LoRA for Qwen-Image-Edit-2511 trained on "
467
+ "MatSynth renders, on ZeroGPU with your quota), baked like the colour: "
468
+ "files.textured_pbr_glb (base colour + metallicRoughness texture), "
469
+ "albedo_pbr, roughness, metallic, metallic_roughness")
470
  view_size: int | None = Field(None, description="Generated image size per view (512-1024, default 1024).")
471
  up: Literal["auto", "y", "z", "-z", "x"] | None = Field(None, description="Up axis of the asset if not +Y "
472
  "(GLB is always +Y). The result keeps "
 
620
  hf_token: str | None = None
621
 
622
 
623
+ class PbrRequest(BaseModel):
624
+ hf_token: str | None = Field(None, description="Your Hugging Face token, for your own ZeroGPU quota (or send it "
625
+ "as the X-HF-Token header)")
626
+
627
+
628
  class BakeRequest(BaseModel):
629
  resolution: Literal[1024, 2048, 4096] = 2048
630
  single_mesh: bool | None = Field(None, description="true: one object, one material; false: your objects and "
 
674
  mode: str = "", backend: str = "qwen-turbo", subject: str = "", preset: str = "",
675
  focus_prompt: str = "", texture_size: int = 0, uv: str = "", up: str = "",
676
  part_prompts: dict[str, str] | None = None, single_mesh: bool = False, inside: str = "",
677
+ metal: str = "", pattern_swatches: str = "", pbr: bool = False, hf_token: str = "",
678
+ ctx: Context | None = None) -> dict:
679
  """Start texturing a mesh; returns a job id immediately (the job takes ~15 s per view with qwen-turbo).
680
  Mesh: upload_id (from REST POST /api/uploads with the file as raw body), mesh_url (public .glb/.obj/.ply/.stl/
681
  .zip), mesh_base64 (the file itself, up to 20 MB) or sample ('avocado' | 'lantern' | 'head'). prompt: materials
 
686
  names only the parts it shows (recommended for multi-part models). The result GLB keeps your objects and
687
  materials (single_mesh: one object, one material instead). inside: plain (default: the inside of a mug or vase
688
  gets its material's main colour) | paint. metal: keep (default: painted reflections) | flat (chrome-like
689
+ materials get an even base colour, for renderers with environment lighting). pbr: true also bakes PBR maps
690
+ (albedo, roughness, metallic; files.textured_pbr_glb). Then poll get_job."""
691
  params = {k: v for k, v in dict(prompt=prompt, upload_id=upload_id, sample=sample, mesh_url=mesh_url, mode=mode,
692
  backend=backend, subject=subject, preset=preset, focus_prompt=focus_prompt,
693
  texture_size=texture_size, uv=uv, up=up, part_prompts=part_prompts,
694
  single_mesh=single_mesh, inside=inside, metal=metal,
695
+ pattern_swatches=pattern_swatches, pbr=pbr).items() if v}
696
 
697
  def run():
698
  return status_payload(MANAGER.create(params, _mcp_ident(ctx, hf_token or None),
 
1167
  raise http_error(exc)
1168
 
1169
 
1170
+ @app.post("/api/jobs/{job_id}/pbr", status_code=202, tags=["jobs"],
1171
+ summary="Add PBR materials (albedo, roughness, metallic) to a finished texture job")
1172
+ def api_pbr(job_id: str, request: Request, req: PbrRequest | None = None) -> dict:
1173
+ try:
1174
+ ident = identity_from(_hdr(request), req.hf_token if req else None)
1175
+ return status_payload(MANAGER.pbr(job_id, ident), base_url(request))
1176
+ except JobError as exc:
1177
+ raise http_error(exc)
1178
+
1179
+
1180
  @app.post("/api/jobs/{job_id}/pick", tags=["quality loop"],
1181
  summary="3D point / normal / UV under image pixels (to aim a retouch)")
1182
  def api_pick(job_id: str, req: PickRequest) -> dict:
projtex/mesh.py CHANGED
@@ -527,12 +527,14 @@ def single_mesh(mesh: TexMesh, name: str = "baked") -> TexMesh:
527
 
528
 
529
  def export_glb(mesh: TexMesh, texture: Image.Image, path: str | Path, unlit: bool = False,
530
- up_axis: str = "y", single: bool = False, image_format: str = "PNG") -> Path:
 
531
  """Write a GLB that mirrors the source scene: one node per source object (same name and world transform,
532
  vertices back in object space), one primitive per source material (same name, metallic/roughness/alpha
533
  kept), every material using the one baked baseColor texture. ``up_axis`` undoes ``orient_up``.
534
  ``single``: one node, one mesh, one material instead (see ``single_mesh``). ``image_format``: PNG or JPEG
535
- (several times smaller for photographic textures such as terrain colour maps)."""
 
536
  import io
537
 
538
  import pygltflib as G
@@ -596,6 +598,16 @@ def export_glb(mesh: TexMesh, texture: Image.Image, path: str | Path, unlit: boo
596
  blob.append(0)
597
  views.append(G.BufferView(buffer=0, byteOffset=len(blob), byteLength=len(png.getvalue())))
598
  blob.extend(png.getvalue())
 
 
 
 
 
 
 
 
 
 
599
  materials, ext_used = [], set()
600
  for m, _ in sorted(used_mats.items(), key=lambda kv: kv[1]):
601
  info = mesh.materials[m] if m < len(mesh.materials) else {}
@@ -604,7 +616,9 @@ def export_glb(mesh: TexMesh, texture: Image.Image, path: str | Path, unlit: boo
604
  pbrMetallicRoughness=G.PbrMetallicRoughness(
605
  baseColorTexture=G.TextureInfo(index=0),
606
  baseColorFactor=[1.0, 1.0, 1.0, float(info.get("opacity", 1.0))],
607
- metallicFactor=float(info.get("metallic", 0.0)), roughnessFactor=float(info.get("roughness", 1.0))),
 
 
608
  doubleSided=bool(info.get("double_sided", True)),
609
  extras={"projtex": "baseColor baked by projtex"})
610
  if info.get("alpha_mode") in ("BLEND", "MASK"):
@@ -625,10 +639,9 @@ def export_glb(mesh: TexMesh, texture: Image.Image, path: str | Path, unlit: boo
625
  scene=0, scenes=[G.Scene(nodes=list(range(len(nodes))))], nodes=nodes, meshes=meshes,
626
  materials=materials, accessors=accessors, bufferViews=views,
627
  buffers=[G.Buffer(byteLength=len(blob))],
628
- images=[G.Image(bufferView=len(views) - 1, mimeType="image/jpeg" if jpeg else "image/png",
629
- name="baked_albedo")],
630
  samplers=[G.Sampler(magFilter=G.LINEAR, minFilter=G.LINEAR_MIPMAP_LINEAR)],
631
- textures=[G.Texture(source=0, sampler=0)],
632
  extensionsUsed=sorted(ext_used),
633
  )
634
  gltf.set_binary_blob(bytes(blob))
 
527
 
528
 
529
  def export_glb(mesh: TexMesh, texture: Image.Image, path: str | Path, unlit: bool = False,
530
+ up_axis: str = "y", single: bool = False, image_format: str = "PNG",
531
+ metallic_roughness: Image.Image | None = None) -> Path:
532
  """Write a GLB that mirrors the source scene: one node per source object (same name and world transform,
533
  vertices back in object space), one primitive per source material (same name, metallic/roughness/alpha
534
  kept), every material using the one baked baseColor texture. ``up_axis`` undoes ``orient_up``.
535
  ``single``: one node, one mesh, one material instead (see ``single_mesh``). ``image_format``: PNG or JPEG
536
+ (several times smaller for photographic textures such as terrain colour maps). ``metallic_roughness``: a
537
+ glTF metallicRoughness texture (G = roughness, B = metallic) used by every material, whose factors become 1."""
538
  import io
539
 
540
  import pygltflib as G
 
598
  blob.append(0)
599
  views.append(G.BufferView(buffer=0, byteOffset=len(blob), byteLength=len(png.getvalue())))
600
  blob.extend(png.getvalue())
601
+ images = [G.Image(bufferView=len(views) - 1, mimeType="image/jpeg" if jpeg else "image/png",
602
+ name="baked_albedo")]
603
+ if metallic_roughness is not None:
604
+ mr = io.BytesIO()
605
+ metallic_roughness.convert("RGB").save(mr, format="PNG")
606
+ while len(blob) % 4:
607
+ blob.append(0)
608
+ views.append(G.BufferView(buffer=0, byteOffset=len(blob), byteLength=len(mr.getvalue())))
609
+ blob.extend(mr.getvalue())
610
+ images.append(G.Image(bufferView=len(views) - 1, mimeType="image/png", name="baked_metallic_roughness"))
611
  materials, ext_used = [], set()
612
  for m, _ in sorted(used_mats.items(), key=lambda kv: kv[1]):
613
  info = mesh.materials[m] if m < len(mesh.materials) else {}
 
616
  pbrMetallicRoughness=G.PbrMetallicRoughness(
617
  baseColorTexture=G.TextureInfo(index=0),
618
  baseColorFactor=[1.0, 1.0, 1.0, float(info.get("opacity", 1.0))],
619
+ metallicFactor=1.0 if metallic_roughness is not None else float(info.get("metallic", 0.0)),
620
+ roughnessFactor=1.0 if metallic_roughness is not None else float(info.get("roughness", 1.0)),
621
+ metallicRoughnessTexture=G.TextureInfo(index=1) if metallic_roughness is not None else None),
622
  doubleSided=bool(info.get("double_sided", True)),
623
  extras={"projtex": "baseColor baked by projtex"})
624
  if info.get("alpha_mode") in ("BLEND", "MASK"):
 
639
  scene=0, scenes=[G.Scene(nodes=list(range(len(nodes))))], nodes=nodes, meshes=meshes,
640
  materials=materials, accessors=accessors, bufferViews=views,
641
  buffers=[G.Buffer(byteLength=len(blob))],
642
+ images=images,
 
643
  samplers=[G.Sampler(magFilter=G.LINEAR, minFilter=G.LINEAR_MIPMAP_LINEAR)],
644
+ textures=[G.Texture(source=i, sampler=0) for i in range(len(images))],
645
  extensionsUsed=sorted(ext_used),
646
  )
647
  gltf.set_binary_blob(bytes(blob))
projtex/pbr.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PBR materials for projection-textured meshes: each generated view is split into albedo, roughness and metallic
2
+ maps by an image decomposer, the maps are projected and blended exactly like the colour (same cameras, masks and
3
+ per-view weights), and the bake gets a de-lit base colour plus a glTF metallicRoughness texture.
4
+
5
+ Decomposers (docs/PBR.md): ``lora`` is Qwen-Image-Edit-2511 with a LoRA trained on synthetic renders of MatSynth
6
+ materials (one instruction per map), served by a ZeroGPU Space; ``mock`` returns the view itself, roughness 0.5 and
7
+ no metal (tests, dry runs)."""
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import os
12
+ import tempfile
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import cv2
17
+ import numpy as np
18
+ from PIL import Image
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ MAPS = ("albedo", "roughness", "metallic")
23
+ PBR_SPACE = os.environ.get("PROJTEX_PBR_SPACE", "Mike0021/projtex-pbr")
24
+
25
+
26
+ class Decomposer:
27
+ name = "base"
28
+
29
+ def decompose(self, image: Image.Image) -> dict[str, Image.Image]:
30
+ """``image``: a lit view (RGB). Returns albedo (sRGB, RGB), roughness and metallic (L, plain 0-1 values)."""
31
+ raise NotImplementedError
32
+
33
+
34
+ class MockDecomposer(Decomposer):
35
+ name = "mock"
36
+
37
+ def decompose(self, image):
38
+ w, h = image.size
39
+ return {"albedo": image.convert("RGB"), "roughness": Image.new("L", (w, h), 128),
40
+ "metallic": Image.new("L", (w, h), 0)}
41
+
42
+
43
+ class SpaceDecomposer(Decomposer):
44
+ """The PBR LoRA behind a Gradio Space: one call returns the three maps of a view."""
45
+
46
+ name = "lora"
47
+
48
+ def __init__(self, space: str = PBR_SPACE, token: str | None = None, headers: dict | None = None,
49
+ retries: int = 3, steps: int = 4):
50
+ self.space, self.token, self.headers, self.retries, self.steps = space, token, headers, retries, steps
51
+ self._client = None
52
+
53
+ def _c(self):
54
+ if self._client is None:
55
+ from gradio_client import Client
56
+
57
+ self._client = Client(self.space, token=self.token, headers=self.headers, verbose=False)
58
+ return self._client
59
+
60
+ def decompose(self, image):
61
+ from gradio_client import handle_file
62
+
63
+ err = None
64
+ with tempfile.TemporaryDirectory(prefix="projtex_pbr_") as td:
65
+ p = Path(td) / "view.png"
66
+ image.convert("RGB").save(p)
67
+ for attempt in range(self.retries):
68
+ try:
69
+ t = time.time()
70
+ a, r, m = self._c().predict(handle_file(str(p)), self.steps, api_name="/decompose")
71
+ log.info("pbr %s in %.1fs", self.space, time.time() - t)
72
+ size = image.size
73
+ return {"albedo": Image.open(a).convert("RGB").resize(size, Image.BICUBIC),
74
+ "roughness": Image.open(r).convert("L").resize(size, Image.BICUBIC),
75
+ "metallic": Image.open(m).convert("L").resize(size, Image.BICUBIC)}
76
+ except Exception as exc: # noqa: BLE001 - a Space can fail in many ways; retry, then report
77
+ err = exc
78
+ self._client = None
79
+ time.sleep(5 + 10 * attempt)
80
+ raise RuntimeError(f"PBR decomposition failed on {self.space}: {err}")
81
+
82
+
83
+ def get_decomposer(name: str = "lora", **kw) -> Decomposer:
84
+ return MockDecomposer() if name == "mock" else SpaceDecomposer(**kw)
85
+
86
+
87
+ def keep_view_hue(view: np.ndarray, albedo: np.ndarray, chroma: float = 0.25) -> np.ndarray:
88
+ """The decomposer's albedo with the view's own hues: its brightness (the shading removed) times the view's
89
+ colour, each channel within ``chroma`` of it. Guards against the decomposer recolouring a part."""
90
+ lum = np.array([0.2126, 0.7152, 0.0722], np.float32)
91
+ lv, la = view @ lum, albedo @ lum
92
+ ratio = np.clip(la / np.maximum(lv, 1e-3), 0.2, 5.0)[..., None]
93
+ out = view * ratio
94
+ return np.clip(out + np.clip(albedo - out, -chroma * np.maximum(out, 0.05), chroma * np.maximum(out, 0.05)),
95
+ 0, 1)
96
+
97
+
98
+ _METAL = (r"\b(?:metal|metals|metallic|steel|stainless|chrome|chromed|chromium|brass|bronze|copper|gold|silver|"
99
+ r"aluminium|aluminum|iron|wrought|tin|pewter|zinc|nickel|titanium|gunmetal)\b")
100
+ _NONMETAL = (r"\b(?:wood|wooden|walnut|oak|pine|maple|mahogany|veneer|paint|painted|lacquer|lacquered|plastic|"
101
+ r"bakelite|resin|ceramic|porcelain|glaze|glazed|clay|terracotta|stone|marble|granite|concrete|brick|"
102
+ r"glass|rubber|leather|fabric|cloth|cotton|wool|felt|paper|cardboard|velvet|silk|vinyl|enamel|"
103
+ r"plaster|bone|skin|fur|hair|wax|foam|cork|carbon)\b")
104
+
105
+
106
+ def metal_prior(text: str) -> float | None:
107
+ """1.0 for a material described only with metal words (brass knobs, chrome trim), 0.0 for one described only
108
+ with non-metal words (walnut veneer, gloss paint, bakelite), None when mixed or unknown (painted steel)."""
109
+ import re
110
+
111
+ t = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", re.sub(r"[_-]+", " ", text or "")) # WalnutVeneer -> Walnut Veneer
112
+ m, n = bool(re.search(_METAL, t, re.I)), bool(re.search(_NONMETAL, t, re.I))
113
+ if m and not n:
114
+ return 1.0
115
+ if n and not m:
116
+ return 0.0
117
+ return None
projtex/project.py CHANGED
@@ -1878,6 +1878,102 @@ class Project:
1878
  self.save()
1879
  return info
1880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1881
  def export(self, path: str | Path | None = None, fmt: str = "glb", resolution: int | None = None,
1882
  unlit: bool = False) -> dict:
1883
  tex = _np_to_img(self.texture(resolution))
 
1878
  self.save()
1879
  return info
1880
 
1881
+ # ======================================================================= PBR
1882
+ def pbr_views(self, decomposer, views: list[str] | None = None, force: bool = False, progress=None) -> dict:
1883
+ """Split each usable view into albedo / roughness / metallic maps (views/<name>/pbr_<map>.png), once per
1884
+ view image."""
1885
+ from .pbr import MAPS
1886
+
1887
+ done = []
1888
+ todo = [v for v in self.views if self._usable(v) and (not views or v.name in views)]
1889
+ for k, v in enumerate(todo):
1890
+ src = self.root / v.image
1891
+ outs = [self.root / "views" / v.name / f"pbr_{m}.png" for m in MAPS]
1892
+ if not force and all(o.exists() and o.stat().st_mtime >= src.stat().st_mtime for o in outs):
1893
+ continue
1894
+ maps = decomposer.decompose(Image.open(src).convert("RGB"))
1895
+ for m, o in zip(MAPS, outs):
1896
+ o.parent.mkdir(parents=True, exist_ok=True)
1897
+ maps[m].save(o)
1898
+ done.append(v.name)
1899
+ if progress:
1900
+ progress(k + 1, len(todo), v.name)
1901
+ return {"decomposed": done, "views": [v.name for v in todo]}
1902
+
1903
+ def fuse_map(self, name: str, res: int) -> tuple[np.ndarray, np.ndarray]:
1904
+ """One PBR map in texel space: each view's pbr_<name>.png projected with the colour's cameras, masks and
1905
+ per-view weights, gaps filled. Returns (map, covered)."""
1906
+ acc = Accumulator(res, self.fusion().sharpness)
1907
+ for i, v in enumerate(self.views):
1908
+ f = self.root / "views" / v.name / f"pbr_{name}.png"
1909
+ if not self._usable(v) or not f.exists():
1910
+ continue
1911
+ src = _img_to_np(self.root / v.image)
1912
+ img = _img_to_np(f)
1913
+ if img.shape[:2] != src.shape[:2]:
1914
+ img = cv2.resize(img, src.shape[1::-1], interpolation=cv2.INTER_LINEAR)
1915
+ cam = v.camera.resized(src.shape[1], src.shape[0])
1916
+ depth = self.gl.render_view(self.mesh, cam, mode="clay")["depth"]
1917
+ mask = self._valid_mask(v, src, depth)
1918
+ acc.add(project_view(self.gl, self.mesh, cam, img, res, self.fusion(), depth=depth, priority=v.priority,
1919
+ mask=mask), i)
1920
+ covered = acc.den > 0
1921
+ return self.filled({"color": acc.color(), "covered": covered}), covered
1922
+
1923
+ def _metal_priors(self, metal: np.ndarray, res: int) -> dict:
1924
+ """What the materials' names and part prompts say, applied in place: parts described only as metal become
1925
+ metallic, parts described only as something else (wood, paint, bakelite...) not. The decomposer reads glossy
1926
+ paint as metal; the words settle it where they can. Returns {material: prior}."""
1927
+ from .pbr import metal_prior
1928
+
1929
+ parts = self.settings.get("part_prompts") if isinstance(self.settings.get("part_prompts"), dict) else {}
1930
+ tm = self._texel_materials(res)
1931
+ out = {}
1932
+ for i, m in enumerate(self.mesh.materials):
1933
+ name = m.get("name") or ""
1934
+ prior = metal_prior(f"{name} {parts.get(name, '')}")
1935
+ if prior is None:
1936
+ continue
1937
+ metal[tm == i] = prior
1938
+ out[name] = prior
1939
+ return out
1940
+
1941
+ def bake_pbr(self, resolution: int | None = None, out_dir: str = "bake", keep_hue: bool = True) -> dict:
1942
+ """The PBR bake: a de-lit base colour (the decomposed albedo, with the views' hues when ``keep_hue``),
1943
+ roughness, metallic and their glTF metallicRoughness texture (G roughness, B metallic), and textured_pbr.glb.
1944
+ Run pbr_views first."""
1945
+ from .pbr import keep_view_hue
1946
+
1947
+ res = int(resolution or self.settings["texture_size"])
1948
+ od = self.root / out_dir
1949
+ od.mkdir(parents=True, exist_ok=True)
1950
+ colour = self.filled(self.fuse(res))
1951
+ albedo, cov = self.fuse_map("albedo", res)
1952
+ if not cov.any():
1953
+ raise RuntimeError("no decomposed views: run pbr_views first")
1954
+ if keep_hue:
1955
+ albedo = keep_view_hue(colour, albedo)
1956
+ rough = self.fuse_map("roughness", res)[0].mean(-1)
1957
+ metal = self.fuse_map("metallic", res)[0].mean(-1)
1958
+ priors = self._metal_priors(metal, res)
1959
+ mr = np.stack([np.ones_like(rough), rough, metal], -1)
1960
+ paths = {"albedo_pbr": str(_save(albedo, od / "albedo_pbr.png")),
1961
+ "roughness": str(_save(np.repeat(rough[..., None], 3, -1), od / "roughness.png")),
1962
+ "metallic": str(_save(np.repeat(metal[..., None], 3, -1), od / "metallic.png")),
1963
+ "metallic_roughness": str(_save(mr, od / "metallic_roughness.png"))}
1964
+ paths["glb_pbr"] = str(export_glb(self.mesh, _np_to_img(albedo), od / "textured_pbr.glb",
1965
+ up_axis=self.data["mesh"].get("up_axis", "y"),
1966
+ single=bool(self.settings.get("export_single_mesh")),
1967
+ metallic_roughness=_np_to_img(mr)))
1968
+ info = {"resolution": res, "paths": paths, "covered": round(float(cov.mean()), 4),
1969
+ "metallic_fraction": round(float((metal[cov] > 0.5).mean()), 4) if cov.any() else 0.0,
1970
+ "roughness_mean": round(float(rough[cov].mean()), 3) if cov.any() else None,
1971
+ "metal_priors": priors}
1972
+ (od / "pbr.json").write_text(json.dumps(info, indent=2))
1973
+ self._log("bake_pbr", {"resolution": res})
1974
+ self.save()
1975
+ return info
1976
+
1977
  def export(self, path: str | Path | None = None, fmt: str = "glb", resolution: int | None = None,
1978
  unlit: bool = False) -> dict:
1979
  tex = _np_to_img(self.texture(resolution))
tests/smoke.py CHANGED
@@ -98,6 +98,13 @@ def rest_checks(base: str, H: dict) -> str:
98
  check(d["state"] == "done", "nested-camera retouch done")
99
  n_layers = len(d.get("retouch_layers") or [])
100
  check(n_layers > 0, "retouch layers listed in the status")
 
 
 
 
 
 
 
101
  r = requests.post(f"{base}/api/jobs/{jid}/retouch", headers=H, timeout=200,
102
  json={"render_camera": "orbit00", "mask": {"rect": [0.4, 0.4, 0.6, 0.6]}, "dry_run": True})
103
  ok = r.status_code == 200 and r.json().get("dry_run") and r.json().get("mask_pixels", 0) > 0
@@ -223,7 +230,7 @@ def terrain_checks(base: str, H: dict) -> None:
223
  buf = io.BytesIO()
224
  Image.fromarray(((h - h.min()) / np.ptp(h) * 65535).astype(np.uint16)).save(buf, format="PNG")
225
  body = {"heightmap": {"base64": base64.b64encode(buf.getvalue()).decode(), "size_m": 600, "height_m": 80},
226
- "prompt": "a green valley", "backend": "mock", "macro_size": 2048, "layers": [
227
  {"name": "grass", "prompt": "short grass"},
228
  {"name": "rock", "prompt": "grey rock", "where": {"slope": [10, None]}},
229
  {"name": "road", "prompt": "packed gravel", "paths": [{"points": [[-300, 0], [300, 50]], "width": 8}]}]}
 
98
  check(d["state"] == "done", "nested-camera retouch done")
99
  n_layers = len(d.get("retouch_layers") or [])
100
  check(n_layers > 0, "retouch layers listed in the status")
101
+ r = requests.post(f"{base}/api/jobs/{jid}/pbr", headers=H, timeout=60)
102
+ check(r.status_code == 202, f"pbr -> {r.status_code}")
103
+ d = wait(base, jid, H)
104
+ f = d.get("files") or {}
105
+ check(d["state"] == "done" and (d.get("pbr") or {}).get("views", 0) > 0 and
106
+ {"textured_pbr_glb", "roughness", "metallic", "metallic_roughness"} <= set(f),
107
+ f"PBR maps baked (mock decomposer): {d.get('pbr')}")
108
  r = requests.post(f"{base}/api/jobs/{jid}/retouch", headers=H, timeout=200,
109
  json={"render_camera": "orbit00", "mask": {"rect": [0.4, 0.4, 0.6, 0.6]}, "dry_run": True})
110
  ok = r.status_code == 200 and r.json().get("dry_run") and r.json().get("mask_pixels", 0) > 0
 
230
  buf = io.BytesIO()
231
  Image.fromarray(((h - h.min()) / np.ptp(h) * 65535).astype(np.uint16)).save(buf, format="PNG")
232
  body = {"heightmap": {"base64": base64.b64encode(buf.getvalue()).decode(), "size_m": 600, "height_m": 80},
233
+ "prompt": "a green valley", "backend": "mock", "macro_size": 2048, "water_level": 10.0, "layers": [
234
  {"name": "grass", "prompt": "short grass"},
235
  {"name": "rock", "prompt": "grey rock", "where": {"slope": [10, None]}},
236
  {"name": "road", "prompt": "packed gravel", "paths": [{"points": [[-300, 0], [300, 50]], "width": 8}]}]}