Spaces:
Running on Zero
Running on Zero
Download app.py from leben/moss-next4: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/leben/moss-next4/resolve/main/app.py
- Command line
-
hf download hf://spaces/leben/moss-next4/app.py
-
curl -L -o app.py https://huggingface.co/spaces/leben/moss-next4/resolve/main/app.py
13.5 kB
| import asyncio | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import tempfile | |
| import uuid | |
| import zipfile | |
| from contextlib import contextmanager | |
| from copy import deepcopy | |
| from pathlib import Path | |
| import spaces | |
| import gradio as gr | |
| from composition import (CONTROL_ADAPTER, CONTROL_DEFAULTS, CONTROL_TYPES, GEOMETRY_MODEL, GEOMETRY_REV, | |
| control_settings) | |
| from huggingface_hub import hf_hub_download | |
| from png_metadata import save_replay_metadata | |
| from reference_image import DEFAULT_DENOISE, decode_reference, normalize_denoise, reference_info | |
| from settings import (NEGATIVE_MODES, NO_LORA, SAMPLERS, SCHEDULERS, apply_composition, apply_reference, | |
| apply_settings, defaults, normalize) | |
| ROOT = Path(__file__).resolve().parent | |
| COMFY_REV = "086099f5d8886163ef77dc354f8382cb7431582a" | |
| MODEL_REV = "2929efe3cdd506c0a430bcfca70a9a8d805cc095" | |
| MODEL_REPO = "Comfy-Org/MOSS-Image" | |
| GRAPH = json.loads(os.environ["MOSS_WORKFLOW"]) | |
| RUNTIME = Path(tempfile.mkdtemp(prefix="moss-next4-")) | |
| COMFY = RUNTIME / f"ComfyUI-{COMFY_REV}" | |
| with zipfile.ZipFile(ROOT / "comfy-source.zip") as archive: | |
| archive.extractall(RUNTIME) | |
| sys.path.insert(0, str(COMFY)) | |
| import folder_paths | |
| from comfy.cli_args import args | |
| # SaveImage would embed the private graph. Add the public replay fields before serving the PNG. | |
| args.disable_metadata = True | |
| args.disable_dynamic_vram = True | |
| args.disable_comfy_compiler = True | |
| OUTPUT = RUNTIME / "output" | |
| INPUT = RUNTIME / "input" | |
| OUTPUT.mkdir() | |
| INPUT.mkdir() | |
| folder_paths.set_output_directory(str(OUTPUT)) | |
| folder_paths.set_input_directory(str(INPUT)) | |
| def link_model(category, name, repo=MODEL_REPO, revision=MODEL_REV): | |
| directory = COMFY / "models" / category | |
| target = directory / name | |
| if target.is_file(): | |
| return | |
| weight = Path(hf_hub_download(repo, f"{category}/{name}", revision=revision)) | |
| if not weight.is_file(): | |
| raise FileNotFoundError(name) | |
| directory.mkdir(parents=True, exist_ok=True) | |
| target.symlink_to(weight) | |
| print(f"Ready: {category}", flush=True) | |
| BASE_LOADER = GRAPH["1"]["inputs"] | |
| ENCODER = GRAPH["4"]["inputs"]["clip_name"] | |
| VAE = GRAPH["9"]["inputs"]["vae_name"] | |
| for category, name in ( | |
| ("diffusion_models", BASE_LOADER["unet_name"]), | |
| ("text_encoders", ENCODER), | |
| ("vae", VAE), | |
| ): | |
| link_model(category, name) | |
| catalog = json.loads((ROOT / "loras.json").read_text()) | |
| adapters = {} | |
| mounts = set() | |
| lora_directory = COMFY / "models" / "loras" | |
| lora_directory.mkdir(parents=True, exist_ok=True) | |
| for label, entry in catalog.items(): | |
| name = Path(entry["file"]).name | |
| if label == NO_LORA or name in adapters.values() or not name.endswith(".safetensors"): | |
| raise ValueError("Invalid LoRA catalog entry") | |
| if "repo" in entry: | |
| weight = Path(hf_hub_download(entry["repo"], entry["file"], revision=entry["revision"])) | |
| else: | |
| folder = Path(entry["directory"]) | |
| mounts.add(str(folder)) | |
| weight = folder / entry["file"] | |
| if weight.is_file(): | |
| (lora_directory / name).symlink_to(weight) | |
| adapters[label] = name | |
| else: | |
| print(f"LoRA unavailable: {label}", flush=True) | |
| DEFAULT = defaults(GRAPH, adapters) | |
| class GradioExecutionServer: | |
| client_id = None | |
| last_node_id = None | |
| sockets_metadata = {} | |
| def send_sync(self, event, data, sid=None): | |
| # Gradio owns the request lifecycle. Comfy events may contain user inputs. | |
| pass | |
| async def load_graph_nodes(graph): | |
| import nodes | |
| await nodes.init_public_apis() | |
| modules = ["nodes_flux", "nodes_model_advanced", "nodes_slg"] | |
| node_types = {node["class_type"] for node in graph.values()} | |
| if "MOSSImageControl" in node_types: | |
| modules.extend(("nodes_moss_image", "nodes_moge")) | |
| for module in modules: | |
| path = COMFY / "comfy_extras" / f"{module}.py" | |
| await nodes.load_custom_node(str(path), module_parent="comfy_extras") | |
| missing = node_types - nodes.NODE_CLASS_MAPPINGS.keys() | |
| if missing: | |
| raise RuntimeError(f"Missing ComfyUI nodes: {sorted(missing)}") | |
| def gpu_seconds(prompt, values): | |
| work = values["width"] * values["height"] * values["steps"] / (1232 * 1632 * 30) | |
| if values["sampler"] == "heun": | |
| work *= 2 | |
| return min(120, math.ceil(44 + 71 * work)) | |
| def run_workflow(prompt, values): | |
| graph = apply_settings(GRAPH, prompt, values, adapters) | |
| return execute_workflow(graph, prompt, values) | |
| def image_gpu_seconds(prompt, values, filename): | |
| return min(120, gpu_seconds(prompt, values) + 8) | |
| def run_image_workflow(prompt, values, filename): | |
| graph = apply_reference(apply_settings(GRAPH, prompt, values, adapters), values, filename) | |
| return execute_workflow(graph, prompt, values) | |
| def composition_gpu_seconds(prompt, values, filename): | |
| return min(120, gpu_seconds(prompt, values) + 24) | |
| def run_composition_workflow(prompt, values, filename): | |
| graph = apply_settings(GRAPH, prompt, values, adapters) | |
| apply_composition(graph, values, filename, CONTROL_ADAPTER, GEOMETRY_MODEL) | |
| return execute_workflow(graph, prompt, values) | |
| def execute_workflow(graph, prompt, values): | |
| import execution | |
| asyncio.run(load_graph_nodes(graph)) | |
| replay_graph = deepcopy(graph) | |
| if "17" in replay_graph and replay_graph["17"]["class_type"] == "LoadImage": | |
| replay_graph["17"]["inputs"]["image"] = Path(replay_graph["17"]["inputs"]["image"]).name | |
| job = uuid.uuid4().hex | |
| executor = execution.PromptExecutor( | |
| GradioExecutionServer(), | |
| cache_type=execution.CacheType.CLASSIC, | |
| cache_args={"ram": 0, "ram_inactive": 0}, | |
| ) | |
| executor.execute(graph, job, execute_outputs=["11"]) | |
| if not executor.success: | |
| for event, details in executor.status_messages: | |
| if event == "execution_error": | |
| raise RuntimeError(f"Node {details['node_id']} ({details['node_type']}): {details['exception_type']}") | |
| raise RuntimeError("ComfyUI execution interrupted") | |
| image = executor.history_result["outputs"]["11"]["images"][0] | |
| path = OUTPUT / image["subfolder"] / image["filename"] | |
| save_replay_metadata(path, replay_graph, prompt, values) | |
| return str(path) | |
| def generate_with_settings(prompt, lora, strength, width, height, seed, steps, cfg, | |
| sampler, scheduler, shift, rescale, single_layers, double_layers, | |
| slg_start, slg_end, negative_mode, negative_text): | |
| values = locals().copy() | |
| if not values.pop("prompt").strip(): | |
| raise gr.Error("请输入正向提示词") | |
| try: | |
| values = normalize(values, adapters) | |
| except ValueError as error: | |
| raise gr.Error(str(error)) from None | |
| return run_workflow(prompt, values), values["seed"] | |
| def generate_from_image(prompt, lora, strength, width, height, seed, steps, cfg, | |
| sampler, scheduler, shift, rescale, single_layers, double_layers, | |
| slg_start, slg_end, negative_mode, negative_text, denoise, reference_image): | |
| values = locals().copy() | |
| if not values.pop("prompt").strip(): | |
| raise gr.Error("请输入正向提示词") | |
| values.pop("reference_image") | |
| try: | |
| values["denoise"] = normalize_denoise(denoise) | |
| values = normalize(values, adapters) | |
| except ValueError as error: | |
| raise gr.Error(str(error)) from None | |
| with reference_input(reference_image, values, "i2i") as filename: | |
| image = run_image_workflow(prompt, values, filename) | |
| return image, values["seed"] | |
| def reference_input(reference_image, values, mode): | |
| try: | |
| data = decode_reference(reference_image) | |
| digest, extension, _ = reference_info(data) | |
| except ValueError as error: | |
| raise gr.Error(str(error)) from None | |
| values.update(mode=mode, reference_sha256=digest, reference_format=extension) | |
| with tempfile.TemporaryDirectory(dir=INPUT) as directory: | |
| path = Path(directory) / f"{digest}.{extension}" | |
| path.write_bytes(data) | |
| yield path.relative_to(INPUT).as_posix() | |
| def generate_from_composition(prompt, lora, strength, width, height, seed, steps, cfg, | |
| sampler, scheduler, shift, rescale, single_layers, double_layers, | |
| slg_start, slg_end, negative_mode, negative_text, | |
| control_type, control_strength, control_end, reference_image): | |
| values = locals().copy() | |
| if not values.pop("prompt").strip(): | |
| raise gr.Error("请输入正向提示词") | |
| values.pop("reference_image") | |
| try: | |
| values.update(control_settings(values)) | |
| values = normalize(values, adapters) | |
| except ValueError as error: | |
| raise gr.Error(str(error)) from None | |
| with reference_input(reference_image, values, "composition") as filename: | |
| try: | |
| link_model("loras", CONTROL_ADAPTER) | |
| link_model("geometry_estimation", GEOMETRY_MODEL, "Comfy-Org/MoGe", GEOMETRY_REV) | |
| except (OSError, ValueError) as error: | |
| print(f"Composition model setup failed: {type(error).__name__}", flush=True) | |
| raise gr.Error("Space 暂时无法加载构图参考模型,请稍后再试。") from None | |
| image = run_composition_workflow(prompt, values, filename) | |
| return image, values["seed"] | |
| def generate(prompt): | |
| image, _ = generate_with_settings(prompt, **DEFAULT) | |
| return image | |
| with gr.Blocks(title="MOSS Image · ComfyUI") as demo: | |
| gr.Markdown("# MOSS Image") | |
| with gr.Row(): | |
| with gr.Column(): | |
| prompt = gr.Textbox(label="正向提示词", lines=5) | |
| with gr.Row(): | |
| lora = gr.Dropdown([*adapters, NO_LORA], value=DEFAULT["lora"], label="LoRA") | |
| strength = gr.Slider(-2, 2, value=DEFAULT["strength"], step=0.05, label="LoRA 强度") | |
| with gr.Row(): | |
| width = gr.Slider(256, 2048, value=DEFAULT["width"], step=16, label="宽度") | |
| height = gr.Slider(256, 2048, value=DEFAULT["height"], step=16, label="高度") | |
| seed = gr.Textbox(label="Seed", value=DEFAULT["seed"], info="填 -1 随机生成") | |
| with gr.Row(): | |
| steps = gr.Slider(1, 60, value=DEFAULT["steps"], step=1, label="采样步数") | |
| cfg = gr.Slider(0, 30, value=DEFAULT["cfg"], step=0.1, label="CFG") | |
| with gr.Accordion("采样、跳层与负向提示词", open=False): | |
| with gr.Row(): | |
| sampler = gr.Dropdown(SAMPLERS, value=DEFAULT["sampler"], label="采样器") | |
| scheduler = gr.Dropdown(SCHEDULERS, value=DEFAULT["scheduler"], label="调度器") | |
| with gr.Row(): | |
| shift = gr.Slider(0.1, 20, value=DEFAULT["shift"], step=0.1, label="Shift") | |
| rescale = gr.Slider(0, 1, value=DEFAULT["rescale"], step=0.01, label="Rescale CFG") | |
| with gr.Row(): | |
| single = gr.Textbox(value=DEFAULT["single_layers"], label="Single layers") | |
| double = gr.Textbox(value=DEFAULT["double_layers"], label="Double layers") | |
| with gr.Row(): | |
| start = gr.Slider(0, 1, value=DEFAULT["slg_start"], step=0.01, label="跳层开始比例") | |
| end = gr.Slider(0, 1, value=DEFAULT["slg_end"], step=0.01, label="跳层结束比例") | |
| neg_mode = gr.Radio(NEGATIVE_MODES, value=DEFAULT["negative_mode"], label="负向提示词来源") | |
| neg_text = gr.Textbox(label="自定义负向提示词", value="", info="选择「自定义」时生效,留空即使用空负向") | |
| submit = gr.Button("生成图片", variant="primary") | |
| with gr.Column(): | |
| image = gr.Image(label="生成结果", format="png") | |
| used_seed = gr.Textbox(label="本次 Seed", interactive=False) | |
| settings_inputs = [prompt, lora, strength, width, height, seed, steps, cfg, sampler, scheduler, | |
| shift, rescale, single, double, start, end, neg_mode, neg_text] | |
| submit.click(generate_with_settings, settings_inputs, [image, used_seed], | |
| api_name="generate_with_settings", concurrency_id="generation") | |
| gr.Button(visible=False).click(generate, prompt, image, api_name="generate", concurrency_id="generation") | |
| denoise = gr.Slider(0.01, 1, value=DEFAULT_DENOISE, step=0.01, visible=False) | |
| reference_image = gr.Textbox(visible=False) | |
| gr.Button(visible=False).click(generate_from_image, [*settings_inputs, denoise, reference_image], | |
| [image, used_seed], api_name="generate_from_image", concurrency_id="generation") | |
| control_type = gr.Dropdown(list(CONTROL_TYPES), value=CONTROL_DEFAULTS["control_type"], visible=False) | |
| control_strength = gr.Slider(0.05, 2, value=CONTROL_DEFAULTS["control_strength"], step=0.05, visible=False) | |
| control_end = gr.Slider(0.05, 1, value=CONTROL_DEFAULTS["control_end"], step=0.05, visible=False) | |
| gr.Button(visible=False).click( | |
| generate_from_composition, | |
| [*settings_inputs, control_type, control_strength, control_end, reference_image], | |
| [image, used_seed], api_name="generate_from_composition", concurrency_id="generation", | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue(default_concurrency_limit=1).launch(blocked_paths=[*mounts, str(COMFY), str(INPUT)]) | |