import copy from pathlib import Path from diffusers.modular_pipelines import ModularPipeline, SequentialPipelineBlocks from diffusers.modular_pipelines.modular_pipeline_utils import InsertableDict, OutputParam from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module from huggingface_hub import file_exists from huggingface_hub.errors import HFValidationError from transformers import AutoTokenizer from .before_denoise import KimodoLatentsStep, KimodoTimestepsStep from .decoders import KimodoDecodeStep, KimodoPostprocessStep from .denoise import KimodoDenoiseStep from .encoders import KimodoTextEncodeStep KimodoDenoiseBlocksDict = InsertableDict( [ ("prepare_latents", KimodoLatentsStep()), ("set_timesteps", KimodoTimestepsStep()), ("denoise_loop", KimodoDenoiseStep()), ] ) class KimodoCoreDenoiseStep(SequentialPipelineBlocks): model_name = "kimodo" block_classes = KimodoDenoiseBlocksDict.values() block_names = KimodoDenoiseBlocksDict.keys() @property def description(self): return "Prepare seeded noise and a timestep schedule, then denoise reusable text conditioning." KimodoBlocksDict = InsertableDict( [ ("text_encoder", KimodoTextEncodeStep()), ("denoise", KimodoCoreDenoiseStep()), ("decode", KimodoDecodeStep()), ("postprocess", KimodoPostprocessStep()), ] ) def _component_source(entry, name, repo, revision): """Return (module, class, repo, subfolder, revision) for one `modular_model_index.json` entry. The model repository's own index names a module file (or `transformers`); its components load from `repo`, so a local copy stays local even though the index records Hub ids. An index written by `pipe.save_pretrained()` stores dotted module paths into the dynamic-module cache (or null with a `type_hint`) and the location of each component. """ module, cls = entry[0], entry[1] spec = entry[2] if len(entry) > 2 and entry[2] else {} if module is not None and "." not in module: return module, cls, repo, spec.get("subfolder") or name, revision if module is None: module, cls = spec["type_hint"] return ( module.rsplit(".", 1)[-1], cls, spec.get("pretrained_model_name_or_path") or repo, spec.get("subfolder") or name, spec.get("revision") or revision, ) def _has_file(repo, filename, revision): if Path(str(repo)).is_dir(): return (Path(str(repo)) / filename).is_file() try: return file_exists(str(repo), filename, revision=revision) except (HFValidationError, OSError): return False def _code_repo(module, candidates): """First (repo, revision) holding `.py`; a saved pipeline's directory holds weights but not code.""" for repo, revision in candidates: if _has_file(repo, f"{module}.py", revision): return repo, revision raise OSError( f"Could not find {module}.py in {[str(repo) for repo, _ in candidates]}. A pipeline saved with " "`save_pretrained` keeps only weights; copy the model repository's .py files into it." ) def _leaves(block): if not block.sub_blocks: yield block for child in block.sub_blocks.values(): yield from _leaves(child) class KimodoBlocks(SequentialPipelineBlocks): model_name = "kimodo" block_classes = KimodoBlocksDict.values() block_names = KimodoBlocksDict.keys() def __init__(self, components_repo=None, components_revision=None, trust_components_code=False): super().__init__() self.components_repo = components_repo self.components_revision = components_revision if components_repo is None: return if not trust_components_code: raise ValueError("Set trust_components_code=True to load code from the model repository") index = ModularPipeline.load_config(components_repo, revision=components_revision) names = [s.name for s in super().expected_components if s.default_creation_method == "from_pretrained"] sources = {name: _component_source(index[name], name, components_repo, components_revision) for name in names} candidates = [(components_repo, components_revision)] + [(r, v) for _, _, r, _, v in sources.values()] candidates = list(dict.fromkeys(candidates)) overrides = {} for name, (module, cls, repo, subfolder, revision) in sources.items(): if module == "transformers": type_hint = AutoTokenizer else: code_repo, code_revision = _code_repo(module, candidates) type_hint = get_class_from_dynamic_module( code_repo, module_file=f"{module}.py", class_name=cls, revision=code_revision, trust_remote_code=True, ) overrides[name] = dict( type_hint=type_hint, pretrained_model_name_or_path=str(repo), subfolder=subfolder, revision=revision ) # The block instances are shared module-level objects; give this pipeline its own copies to carry the specs. self.sub_blocks = copy.deepcopy(self.sub_blocks) for leaf in _leaves(self): leaf.component_overrides = overrides @property def description(self): return "Kimodo text-to-motion with an explicit frame count and seed." @property def outputs(self): return [OutputParam("motion", type_hint=dict, description="Batched SOMA77 motion tensors in meters, Y-up.")] # Public helpers also make transitive block dependencies available to the Hub code loader. from .guidance import KimodoGuidance # noqa: E402, F401 from .operations import Cancelled, ResolvableBlock # noqa: E402, F401 from .prompt_utils import tokenize_prompt # noqa: E402, F401 from .sanitize import sanitize_text # noqa: E402, F401