| 
 | 1 | +# Copyright 2025 The HuggingFace Team. All rights reserved.  | 
 | 2 | +#  | 
 | 3 | +# Licensed under the Apache License, Version 2.0 (the "License");  | 
 | 4 | +# you may not use this file except in compliance with the License.  | 
 | 5 | +# You may obtain a copy of the License at  | 
 | 6 | +#  | 
 | 7 | +#     http://www.apache.org/licenses/LICENSE-2.0  | 
 | 8 | +#  | 
 | 9 | +# Unless required by applicable law or agreed to in writing, software  | 
 | 10 | +# distributed under the License is distributed on an "AS IS" BASIS,  | 
 | 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  | 
 | 12 | +# See the License for the specific language governing permissions and  | 
 | 13 | +# limitations under the License.  | 
 | 14 | + | 
 | 15 | +"""  | 
 | 16 | +Usage example:  | 
 | 17 | +    TODO  | 
 | 18 | +"""  | 
 | 19 | + | 
 | 20 | +import ast  | 
 | 21 | +from argparse import ArgumentParser, Namespace  | 
 | 22 | +from pathlib import Path  | 
 | 23 | +import importlib.util  | 
 | 24 | +import os  | 
 | 25 | +from ..utils import logging  | 
 | 26 | +from . import BaseDiffusersCLICommand  | 
 | 27 | + | 
 | 28 | + | 
 | 29 | +EXPECTED_PARENT_CLASSES = ["PipelineBlock"]  | 
 | 30 | +CONFIG = "config.json"  | 
 | 31 | + | 
 | 32 | +def conversion_command_factory(args: Namespace):  | 
 | 33 | +    return CustomBlocksCommand(args.block_module_name, args.block_class_name)  | 
 | 34 | + | 
 | 35 | + | 
 | 36 | +class CustomBlocksCommand(BaseDiffusersCLICommand):  | 
 | 37 | +    @staticmethod  | 
 | 38 | +    def register_subcommand(parser: ArgumentParser):  | 
 | 39 | +        conversion_parser = parser.add_parser("custom_blocks")  | 
 | 40 | +        conversion_parser.add_argument(  | 
 | 41 | +            "--block_module_name",  | 
 | 42 | +            type=str,  | 
 | 43 | +            default="block.py",  | 
 | 44 | +            help="Module filename in which the custom block will be implemented.",  | 
 | 45 | +        )  | 
 | 46 | +        conversion_parser.add_argument(  | 
 | 47 | +            "--block_class_name", type=str, default=None, help="Name of the custom block. If provided None, we will try to infer it."  | 
 | 48 | +        )  | 
 | 49 | +        conversion_parser.set_defaults(func=conversion_command_factory)  | 
 | 50 | + | 
 | 51 | +    def __init__(self, block_module_name: str = "block.py", block_class_name: str = None):  | 
 | 52 | +        self.logger = logging.get_logger("diffusers-cli/custom_blocks")  | 
 | 53 | +        self.block_module_name = Path(block_module_name)  | 
 | 54 | +        self.block_class_name = block_class_name  | 
 | 55 | + | 
 | 56 | +    def run(self):  | 
 | 57 | +        # determine the block to be saved.  | 
 | 58 | +        out = self._get_class_names(self.block_module_name)  | 
 | 59 | +        classes_found = list({cls for cls, _ in out})  | 
 | 60 | +          | 
 | 61 | +        if self.block_class_name is not None:  | 
 | 62 | +            child_class, parent_class = self._choose_block(out, self.block_class_name)  | 
 | 63 | +            if child_class is None and parent_class is None:  | 
 | 64 | +                raise ValueError(  | 
 | 65 | +                    "`block_class_name` could not be retrieved. Available classes from "  | 
 | 66 | +                    f"{self.block_module_name}:\n{classes_found}"  | 
 | 67 | +                )  | 
 | 68 | +        else:  | 
 | 69 | +            self.logger.info(  | 
 | 70 | +                f"Found classes: {classes_found} will be using {classes_found[0]}. "  | 
 | 71 | +                "If this needs to be changed, re-run the command specifying `block_class_name`."  | 
 | 72 | +            )  | 
 | 73 | +            child_class, parent_class =  out[0][0], out[0][1]  | 
 | 74 | + | 
 | 75 | +        # dynamically get the custom block and initialize it to call `save_pretrained` in the current directory.  | 
 | 76 | +        # the user is responsible for running it, so I guess that is safe?  | 
 | 77 | +        module_name = f"__dynamic__{self.block_module_name.stem}"  | 
 | 78 | +        spec = importlib.util.spec_from_file_location(module_name, str(self.block_module_name))  | 
 | 79 | +        module = importlib.util.module_from_spec(spec)  | 
 | 80 | +        spec.loader.exec_module(module)  | 
 | 81 | +        getattr(module, child_class)().save_pretrained(os.getcwd())  | 
 | 82 | + | 
 | 83 | +        # or, we could create it manually.  | 
 | 84 | +        # automap = self._create_automap(parent_class=parent_class, child_class=child_class)  | 
 | 85 | +        # with open(CONFIG, "w") as f:  | 
 | 86 | +        #     json.dump(automap, f)  | 
 | 87 | +        with open("requirements.txt", "w") as f:  | 
 | 88 | +            f.write("")  | 
 | 89 | + | 
 | 90 | +    def _choose_block(self, candidates, chosen=None):  | 
 | 91 | +        for cls, base in candidates:  | 
 | 92 | +            if cls == chosen:  | 
 | 93 | +                return cls, base  | 
 | 94 | +        return None, None  | 
 | 95 | + | 
 | 96 | +    def _get_class_names(self, file_path):  | 
 | 97 | +        source = file_path.read_text(encoding="utf-8")  | 
 | 98 | +        try:  | 
 | 99 | +            tree = ast.parse(source, filename=file_path)  | 
 | 100 | +        except SyntaxError as e:  | 
 | 101 | +            raise ValueError(f"Could not parse {file_path!r}: {e}") from e  | 
 | 102 | + | 
 | 103 | +        results: list[tuple[str, str]] = []  | 
 | 104 | +        for node in tree.body:  | 
 | 105 | +            if not isinstance(node, ast.ClassDef):  | 
 | 106 | +                continue  | 
 | 107 | + | 
 | 108 | +            # extract all base names for this class  | 
 | 109 | +            base_names = [  | 
 | 110 | +                bname for b in node.bases  | 
 | 111 | +                if (bname := self._get_base_name(b)) is not None  | 
 | 112 | +            ]  | 
 | 113 | + | 
 | 114 | +            # for each allowed base that appears in the class's bases, emit a tuple  | 
 | 115 | +            for allowed in EXPECTED_PARENT_CLASSES:  | 
 | 116 | +                if allowed in base_names:  | 
 | 117 | +                    results.append((node.name, allowed))  | 
 | 118 | + | 
 | 119 | +        return results  | 
 | 120 | + | 
 | 121 | +    def _get_base_name(self, node: ast.expr):  | 
 | 122 | +        if isinstance(node, ast.Name):  | 
 | 123 | +            return node.id  | 
 | 124 | +        elif isinstance(node, ast.Attribute):  | 
 | 125 | +            val = self._get_base_name(node.value)  | 
 | 126 | +            return f"{val}.{node.attr}" if val else node.attr  | 
 | 127 | +        return None  | 
 | 128 | +      | 
 | 129 | +    def _create_automap(self, parent_class, child_class):  | 
 | 130 | +        module = str(self.block_module_name).replace(".py", "").rsplit(".", 1)[-1]  | 
 | 131 | +        auto_map = {f"{parent_class}": f"{module}.{child_class}"}  | 
 | 132 | +        return {"auto_map": auto_map}  | 
 | 133 | +      | 
0 commit comments