File size: 4,320 Bytes
6daffc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# SPDX-License-Identifier: GPL-3.0-only
# Copyright 2026 Data Archetype
"""Where the loader node finds the release, and loading it.

The node folder is the Hugging Face repository checkout, so the default
source is the folder itself. A clone without its large files holds Git LFS
pointer files instead; the loader detects them and says how to download the
weights.
"""

from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

from ..dflow.loading import CONFIG_FILENAME, MODEL_FILENAME, RELEASE_FILENAME
from ..dflow.pipeline import REPOSITORY, TEXT_ENCODER_DIRNAME, DFlowComponents
from ..dflow.preview import LatentRgbPreview
from .types import DFlowModelHandle, DFlowWeightSource

if TYPE_CHECKING:
    import torch

NODE_FOLDER = Path(__file__).parents[1]
"""The custom-node folder (the repository root)."""

BUNDLED_FILES = (
    CONFIG_FILENAME,
    RELEASE_FILENAME,
    MODEL_FILENAME,
    f"{TEXT_ENCODER_DIRNAME}/config.json",
    f"{TEXT_ENCODER_DIRNAME}/model.safetensors",
    f"{TEXT_ENCODER_DIRNAME}/tokenizer.json",
)
"""Release files the bundled source needs, relative to the node folder."""

_LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/"
# Git LFS pointer files are about 130 bytes; real release files are larger.
_LFS_POINTER_MAX_BYTES = 1024


def is_lfs_pointer(path: Path) -> bool:
    """Whether ``path`` is a Git LFS pointer file instead of its content."""

    if path.stat().st_size > _LFS_POINTER_MAX_BYTES:
        return False
    with path.open("rb") as handle:
        return handle.read(len(_LFS_POINTER_PREFIX)) == _LFS_POINTER_PREFIX


def bundled_release_dir(folder: Path = NODE_FOLDER) -> Path:
    """Return the node folder after checking it holds the release files.

    Raises:
        FileNotFoundError: If a file is missing or is a Git LFS pointer; the
            message gives the download command.
    """

    missing = [name for name in BUNDLED_FILES if not (folder / name).is_file()]
    pointers = [
        name
        for name in BUNDLED_FILES
        if name not in missing and is_lfs_pointer(folder / name)
    ]
    if missing or pointers:
        problems = [f"missing {name}" for name in missing] + [
            f"{name} is a Git LFS pointer" for name in pointers
        ]
        raise FileNotFoundError(
            f"The dflow_2b weights are not in the node folder {folder} "
            f"({'; '.join(problems)}). Download them with:\n"
            f"  hf download {REPOSITORY} --local-dir {folder}\n"
            "or choose the hub source in DFlow Loader."
        )
    return folder


def release_location(
    source: DFlowWeightSource, *, local_dir: str, repository: str
) -> Path | str:
    """The release directory or Hub repository a source reads.

    Each source reads only its own field: BUNDLED neither, LOCAL_DIR
    ``local_dir``, HUB ``repository``.

    Raises:
        FileNotFoundError: For missing bundled files or local directory.
        ValueError: For an empty field the source needs.
    """

    match source:
        case DFlowWeightSource.BUNDLED:
            return bundled_release_dir()
        case DFlowWeightSource.LOCAL_DIR:
            if not local_dir.strip():
                raise ValueError("The local_dir source needs local_dir.")
            path = Path(local_dir.strip()).expanduser()
            if not path.is_dir():
                raise FileNotFoundError(f"No release directory at {path}.")
            return path
        case DFlowWeightSource.HUB:
            if not repository.strip():
                raise ValueError("The hub source needs a repository id.")
            return repository.strip()
        case _ as unreachable:
            raise ValueError(f"Unsupported weight source: {unreachable}")


def load_model(
    location: Path | str,
    *,
    device: torch.device,
    compile_model: bool,
    revision: str | None,
    cache_dir: Path | None,
) -> DFlowModelHandle:
    """Load the release and the preview projection onto ``device``."""

    components = DFlowComponents.from_pretrained(
        location,
        device=device,
        compile=compile_model,
        revision=revision,
        cache_dir=cache_dir,
    )
    return DFlowModelHandle(
        components=components, preview=LatentRgbPreview.bundled().to(device)
    )