Download data_process/_blender/process_scene_textured.py from Kairos-HomeWorld/HomeWorld-Data: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/datasets/Kairos-HomeWorld/HomeWorld-Data/resolve/main/data_process/_blender/process_scene_textured.py
- Command line
-
hf download hf://datasets/Kairos-HomeWorld/HomeWorld-Data/data_process/_blender/process_scene_textured.py
-
curl -L -o process_scene_textured.py https://huggingface.co/datasets/Kairos-HomeWorld/HomeWorld-Data/resolve/main/data_process/_blender/process_scene_textured.py
12.5 kB
| """Process one original scene: replace a random texture pair, then configure lighting.""" | |
| import argparse | |
| import hashlib | |
| import re | |
| import runpy | |
| import shutil | |
| import sys | |
| import tempfile | |
| from array import array | |
| from pathlib import Path | |
| import bpy | |
| WALL_BASENAME = "white_wall.png" | |
| FLOOR_BASENAME = "wood_floor.jpeg" | |
| TEXTURE_LIBRARY = runpy.run_path(str(Path(__file__).resolve().parents[1] / "texture_library.py")) | |
| OBJECT_PATTERNS = { | |
| WALL_BASENAME: re.compile(r"Wall_\d+(?:\.\d+)?"), | |
| FLOOR_BASENAME: re.compile(r"Floor(?:\.\d+)?"), | |
| } | |
| OUTPUT_NAMES = {"flat.blend", "preview_top.png"} | |
| def lighting_functions(): | |
| return runpy.run_path(str(Path(__file__).with_name("apply_lighting.py"))) | |
| def image_digest(image): | |
| values = array("f", [0.0]) * len(image.pixels) | |
| if not values: | |
| raise RuntimeError(f"Image has no pixels: {image.name}") | |
| image.pixels.foreach_get(values) | |
| return hashlib.sha256(values.tobytes()).hexdigest() | |
| def packed_digest(image): | |
| return tuple( | |
| hashlib.sha256(item.packed_file.data).hexdigest() | |
| for item in image.packed_files | |
| ) | |
| def texture_targets(): | |
| """Identify images via architectural objects, never by global name matching.""" | |
| targets = {} | |
| allowed_nodes = set() | |
| material_names = set() | |
| object_names = set() | |
| counts = dict.fromkeys(OBJECT_PATTERNS, 0) | |
| for obj in bpy.context.scene.objects: | |
| basename = next( | |
| (name for name, pattern in OBJECT_PATTERNS.items() | |
| if pattern.fullmatch(obj.name)), None | |
| ) | |
| if basename is None: | |
| continue | |
| if obj.type != "MESH" or not obj.data.polygons: | |
| raise RuntimeError(f"Invalid architectural mesh: {obj.name}") | |
| counts[basename] += 1 | |
| object_names.add(obj.name) | |
| for index in {face.material_index for face in obj.data.polygons}: | |
| if index >= len(obj.material_slots): | |
| raise RuntimeError(f"Missing material slot: {obj.name}") | |
| material = obj.material_slots[index].material | |
| if not material or not material.use_nodes: | |
| raise RuntimeError(f"Missing node material: {obj.name}") | |
| matches = [ | |
| node for node in material.node_tree.nodes | |
| if node.type == "TEX_IMAGE" and node.image | |
| and Path(node.image.filepath).name == basename | |
| and any( | |
| link.to_node.type == "BSDF_PRINCIPLED" | |
| and link.to_socket.name == "Base Color" | |
| for link in node.outputs["Color"].links | |
| ) | |
| ] | |
| if len(matches) != 1: | |
| raise RuntimeError(f"Expected one base-color texture in {material.name}") | |
| node = matches[0] | |
| image = node.image | |
| if (image.source != "FILE" or image.library | |
| or not re.fullmatch(re.escape(basename) + r"(?:\.\d+)?", image.name)): | |
| raise RuntimeError(f"Unsupported architectural image: {image.name}") | |
| if image.name in targets and targets[image.name] != basename: | |
| raise RuntimeError(f"Image shared by wall and floor: {image.name}") | |
| targets[image.name] = basename | |
| allowed_nodes.add((material.name, node.name)) | |
| material_names.add(material.name) | |
| if not all(counts.values()): | |
| raise RuntimeError(f"Both walls and floors are required: {counts}") | |
| # Refuse ambiguous sharing rather than recoloring furniture or ceilings. | |
| for obj in bpy.data.objects: | |
| if obj.name not in object_names and any( | |
| slot.material and slot.material.name in material_names | |
| for slot in obj.material_slots): | |
| raise RuntimeError(f"Architectural material shared with {obj.name}") | |
| for owner in (*bpy.data.materials, *bpy.data.worlds, *bpy.data.node_groups): | |
| tree = owner if isinstance(owner, bpy.types.NodeTree) else owner.node_tree | |
| if not tree: | |
| continue | |
| for node in tree.nodes: | |
| image = getattr(node, "image", None) | |
| if image and image.name in targets: | |
| if (owner.name, node.name) not in allowed_nodes: | |
| raise RuntimeError(f"Architectural image shared with {owner.name}") | |
| return targets, counts | |
| def replace_image_data(image, candidate_path): | |
| name = image.name | |
| colorspace = image.colorspace_settings.name | |
| alpha_mode = image.alpha_mode | |
| if image.packed_files: | |
| image.unpack(method="REMOVE") | |
| image.filepath = str(candidate_path) | |
| image.reload() | |
| image.colorspace_settings.name = colorspace | |
| image.alpha_mode = alpha_mode | |
| image.pack() | |
| if image.name != name or not image.packed_files: | |
| raise RuntimeError(f"Image identity or packing changed: {name}") | |
| def choose_set(textures_root, requested="random", seed=None, scene_key=""): | |
| return TEXTURE_LIBRARY["choose_set"](textures_root, requested, seed, scene_key) | |
| def validate_output(source, target, replace_existing): | |
| if target.name != "flat.blend": | |
| raise RuntimeError("The output filename must be flat.blend") | |
| if target == source or target.parent == source.parent: | |
| raise RuntimeError("Refusing to overwrite the source") | |
| if target.parent.exists(): | |
| if not replace_existing: | |
| raise RuntimeError("Refusing to overwrite existing outputs; use --replace-existing") | |
| entries = list(target.parent.iterdir()) | |
| if ({path.name for path in entries} - OUTPUT_NAMES | |
| or any(not path.is_file() or path.is_symlink() for path in entries)): | |
| raise RuntimeError("Existing output contains unexpected entries; refusing replacement") | |
| def replace_textures(textures_root, set_name, targets): | |
| expected = {} | |
| for basename in OBJECT_PATTERNS: | |
| path = textures_root / set_name / basename | |
| candidate = bpy.data.images.load(str(path), check_existing=False) | |
| try: | |
| if not all(candidate.size) or candidate.colorspace_settings.name != "sRGB": | |
| raise RuntimeError(f"Invalid sRGB texture: {path}") | |
| if basename == WALL_BASENAME: | |
| pixels = array("f", [0.0]) * len(candidate.pixels) | |
| candidate.pixels.foreach_get(pixels) | |
| if any(max(pixels[channel::4]) - min(pixels[channel::4]) > 1e-6 | |
| for channel in range(3)): | |
| raise RuntimeError(f"Wall texture must be solid color: {path}") | |
| expected[basename] = { | |
| "size": tuple(candidate.size), | |
| "pixels": image_digest(candidate), | |
| "packed": (hashlib.sha256(path.read_bytes()).hexdigest(),), | |
| } | |
| finally: | |
| bpy.data.images.remove(candidate) | |
| for name, basename in targets.items(): | |
| image = bpy.data.images[name] | |
| if image.colorspace_settings.name != "sRGB": | |
| raise RuntimeError(f"Unexpected color space for {name}") | |
| replace_image_data(image, textures_root / set_name / basename) | |
| check_image(image, expected[basename]) | |
| return expected | |
| def check_image(image, expected): | |
| if (tuple(image.size) != expected["size"] | |
| or image_digest(image) != expected["pixels"] | |
| or packed_digest(image) != expected["packed"] | |
| or image.colorspace_settings.name != "sRGB"): | |
| raise RuntimeError(f"Texture content verification failed: {image.name}") | |
| def verify_output(target, targets, counts, expected, untouched, names, set_name): | |
| bpy.ops.wm.open_mainfile(filepath=str(target)) | |
| actual_targets, actual_counts = texture_targets() | |
| if actual_targets != targets or actual_counts != counts: | |
| raise RuntimeError("Architectural image names or assignments changed") | |
| if set(bpy.data.images.keys()) != names: | |
| raise RuntimeError("Image datablocks added or removed") | |
| for name, basename in targets.items(): | |
| check_image(bpy.data.images[name], expected[basename]) | |
| for name, fingerprint in untouched.items(): | |
| if packed_digest(bpy.data.images[name]) != fingerprint: | |
| raise RuntimeError(f"Unrelated packed image changed: {name}") | |
| lighting_functions()["verify_lighting"](bpy.context.scene) | |
| if bpy.context.scene.get("random_texture_set") != set_name: | |
| raise RuntimeError("Texture selection metadata was not saved") | |
| if any(obj.name.startswith("TopPreviewCamera") for obj in bpy.data.objects): | |
| raise RuntimeError("Preview-only camera leaked into saved scene") | |
| print( | |
| f"PIPELINE_VERIFIED texture_set={set_name} " | |
| f"wall_objects={counts[WALL_BASENAME]} floor_objects={counts[FLOOR_BASENAME]} " | |
| f"replaced_images={len(targets)} unchanged_images={len(untouched)}", | |
| flush=True, | |
| ) | |
| def process(output, textures_root, requested_set="random", seed=None, | |
| preview_size=768, preview_samples=32, replace_existing=False): | |
| if not bpy.data.filepath: | |
| raise RuntimeError("Open a source blend before processing") | |
| source = Path(bpy.data.filepath).resolve() | |
| target = Path(output).absolute() | |
| if target.is_symlink() or target.parent.is_symlink(): | |
| raise RuntimeError("Output must not be a symlink") | |
| target = target.resolve() | |
| validate_output(source, target, replace_existing) | |
| if preview_size <= 0 or preview_samples <= 0: | |
| raise RuntimeError("Preview size and samples must be positive") | |
| if bpy.data.objects.get("FixedSun"): | |
| raise RuntimeError("Source already has FixedSun; use the original data scene") | |
| before = source.stat() | |
| source_stat = (before.st_size, before.st_mtime_ns) | |
| textures_root = Path(textures_root).resolve() | |
| set_name = choose_set(textures_root, requested_set, seed, source.parent.name) | |
| targets, counts = texture_targets() | |
| names = set(bpy.data.images.keys()) | |
| untouched = { | |
| image.name: packed_digest(image) | |
| for image in bpy.data.images if image.name not in targets | |
| } | |
| print(f"PIPELINE_START source={source} texture_set={set_name}", flush=True) | |
| expected = replace_textures(textures_root, set_name, targets) | |
| bpy.context.scene["random_texture_set"] = set_name | |
| bpy.context.scene["texture_pipeline"] = "random textures then environment and sun lighting" | |
| print(f"TEXTURES_PACKED count={len(targets)} names_preserved=True", flush=True) | |
| # A sibling staging directory keeps relative paths valid after publication. | |
| target.parent.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory( | |
| prefix=f".{target.parent.name}_processing_", dir=target.parent.parent) as temporary: | |
| staged = Path(temporary) / "flat.blend" | |
| lighting_functions()["process"](staged, size=preview_size, samples=preview_samples) | |
| verify_output(staged, targets, counts, expected, untouched, names, set_name) | |
| after = source.stat() | |
| if (after.st_size, after.st_mtime_ns) != source_stat: | |
| raise RuntimeError("Source file changed during processing") | |
| if {path.name for path in staged.parent.iterdir()} != OUTPUT_NAMES: | |
| raise RuntimeError("Expected exactly blend and preview_top outputs") | |
| validate_output(source, target, replace_existing) | |
| if target.parent.exists(): | |
| shutil.rmtree(target.parent) | |
| staged.parent.rename(target.parent) | |
| print( | |
| f"PIPELINE_DONE output={target} preview={target.parent / 'preview_top.png'} " | |
| f"texture_set={set_name} source_unchanged=True", | |
| flush=True, | |
| ) | |
| return set_name | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--output", required=True, help="Path ending in flat.blend") | |
| parser.add_argument("--textures", required=True, type=Path) | |
| parser.add_argument("--set", default="random", help="Texture directory name, or random") | |
| parser.add_argument("--seed", type=int, default=None) | |
| parser.add_argument("--size", type=int, default=768) | |
| parser.add_argument("--samples", type=int, default=32) | |
| parser.add_argument("--replace-existing", action="store_true") | |
| argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] | |
| args = parser.parse_args(argv) | |
| process( | |
| args.output, args.textures, requested_set=args.set, seed=args.seed, | |
| preview_size=args.size, preview_samples=args.samples, | |
| replace_existing=args.replace_existing, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |