Spaces:
Running on Zero

File size: 6,110 Bytes
1acef1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf55f26
 
fadece3
bf55f26
 
 
 
 
 
fadece3
 
 
 
bf55f26
 
 
 
 
 
 
 
fadece3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
import copy
import math
import re
import secrets


NO_LORA = "关闭 LoRA"
SAMPLERS = ["er_sde", "euler", "euler_ancestral", "dpmpp_2m", "dpmpp_2m_sde", "heun"]
SCHEDULERS = ["sgm_uniform", "normal", "simple", "karras", "exponential", "beta"]
NEGATIVE_MODES = ["沿用工作流", "自定义"]


def defaults(graph, adapters):
    sample = graph["8"]["inputs"]
    latent = graph["7"]["inputs"]
    lora = graph["15"]["inputs"]
    slg = graph["12"]["inputs"]
    return {
        "lora": next(label for label, file in adapters.items() if file == lora["lora_name"]),
        "strength": lora["strength_model"],
        "width": latent["width"], "height": latent["height"],
        "seed": str(sample["noise_seed"]), "steps": sample["steps"], "cfg": sample["cfg"],
        "sampler": sample["sampler_name"], "scheduler": sample["scheduler"],
        "shift": graph["3"]["inputs"]["shift"], "rescale": graph["16"]["inputs"]["multiplier"],
        "single_layers": slg["single_layers"], "double_layers": slg["double_layers"],
        "slg_start": slg["start_percent"], "slg_end": slg["end_percent"],
        "negative_mode": NEGATIVE_MODES[0], "negative_text": "",
    }


def normalize(values, adapters):
    result = dict(values)
    for key, choices in (("lora", [NO_LORA, *adapters]), ("sampler", SAMPLERS),
                         ("scheduler", SCHEDULERS), ("negative_mode", NEGATIVE_MODES)):
        if result[key] not in choices:
            raise ValueError(f"{key} 选项无效")
    for key, low, high in (
        ("width", 256, 2048), ("height", 256, 2048), ("steps", 1, 60),
        ("cfg", 0, 30), ("strength", -2, 2), ("shift", 0.1, 20),
        ("rescale", 0, 1), ("slg_start", 0, 1), ("slg_end", 0, 1),
    ):
        value = result[key]
        if not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high:
            raise ValueError(f"{key} 范围为 {low} 至 {high}")
        if key in ("width", "height", "steps"):
            if int(value) != value or (key != "steps" and int(value) % 16):
                raise ValueError("宽高须为 16 的倍数,步数须为整数")
            result[key] = int(value)
    seed = str(result["seed"]).strip()
    if seed == "-1":
        seed = str(secrets.randbits(64))
    if not re.fullmatch(r"[0-9]{1,20}", seed) or int(seed) >= 2**64:
        raise ValueError("Seed 须为无符号 64 位整数,或填 -1 随机生成")
    result["seed"] = str(int(seed))
    for key in ("single_layers", "double_layers"):
        layers = result[key].strip()
        if layers and not re.fullmatch(r"[0-9]+(?:\s*,\s*[0-9]+)*", layers):
            raise ValueError("跳层编号请用逗号隔开,或留空")
        result[key] = layers
    if result["slg_start"] > result["slg_end"]:
        raise ValueError("跳层开始比例须小于或等于结束比例")
    return result


def apply_settings(template, prompt, values, adapters):
    graph = copy.deepcopy(template)
    sample = graph["8"]["inputs"]
    graph[sample["positive"][0]]["inputs"]["text"] = prompt
    if values["negative_mode"] == "自定义":
        graph[sample["negative"][0]]["inputs"]["text"] = values["negative_text"]
    graph["7"]["inputs"].update(width=values["width"], height=values["height"])
    sample.update(noise_seed=int(values["seed"]), steps=values["steps"], cfg=values["cfg"],
                  sampler_name=values["sampler"], scheduler=values["scheduler"])
    if values["lora"] == NO_LORA:
        graph["3"]["inputs"]["model"] = graph.pop("15")["inputs"]["model"]
    else:
        graph["15"]["inputs"].update(lora_name=adapters[values["lora"]], strength_model=values["strength"])
    graph["3"]["inputs"]["shift"] = values["shift"]
    graph["16"]["inputs"]["multiplier"] = values["rescale"]
    graph["12"]["inputs"].update(single_layers=values["single_layers"], double_layers=values["double_layers"],
                                 start_percent=values["slg_start"], end_percent=values["slg_end"])
    return graph


def add_reference_image(graph, filename):
    size = graph["7"]["inputs"]
    graph["17"] = {"class_type": "LoadImage", "inputs": {"image": filename}}
    graph["18"] = {"class_type": "ImageScale", "inputs": {
        "image": ["17", 0], "upscale_method": "lanczos", "crop": "center",
        "width": size["width"], "height": size["height"],
    }}


def apply_reference(graph, values, filename):
    add_reference_image(graph, filename)
    graph["7"] = {"class_type": "VAEEncode", "inputs": {"pixels": ["18", 0], "vae": ["9", 0]}}
    sample = graph["8"]["inputs"]
    sample["seed"] = sample.pop("noise_seed")
    for field in ("add_noise", "start_at_step", "end_at_step", "return_with_leftover_noise"):
        sample.pop(field)
    sample["denoise"] = values["denoise"]
    graph["8"]["class_type"] = "KSampler"
    return graph


def apply_composition(graph, values, filename, control_adapter, geometry_model):
    add_reference_image(graph, filename)
    sampling_model = graph["3"]["inputs"]
    graph["23"] = {"class_type": "LoraLoaderModelOnly", "inputs": {
        "model": sampling_model["model"], "lora_name": control_adapter, "strength_model": 1,
    }}
    sampling_model["model"] = ["23", 0]

    sample = graph["8"]["inputs"]
    graph["19"] = {"class_type": "MOSSImageControl", "inputs": {
        "positive": sample["positive"], "negative": sample["negative"], "vae": ["9", 0],
        "depth_map": ["22", 0], "strength": values["control_strength"],
        "start_percent": 0, "end_percent": values["control_end"],
    }}
    sample.update(positive=["19", 0], negative=["19", 1])
    graph["20"] = {"class_type": "LoadMoGeModel", "inputs": {"model_name": geometry_model}}
    graph["21"] = {"class_type": "MoGeInference", "inputs": {
        "moge_model": ["20", 0], "image": ["18", 0], "resolution_level": 9, "fov_x_degrees": 0,
        "batch_size": 1, "force_projection": True, "apply_mask": True, "refine_steps": 3,
    }}
    graph["22"] = {"class_type": "MoGeRender", "inputs": {
        "moge_geometry": ["21", 0], "output": values["control_type"],
    }}
    return graph