{
  pkgs,
  lib,
  config,
  comfyui,
  comfy_dir ? "/run/user/1000/comfyui/",
  spandrel,
  plugins ? config.comfyui.plugins,
  ...
}: let
  inherit (pkgs) python3;
  python = python3.withPackages (
    ps:
      with ps; [
        torch
        torchsde
        torchvision
        torchaudio
        einops
        transformers
        tokenizers
        sentencepiece
        safetensors
        aiohttp
        pyyaml
        pillow
        scipy
        tqdm
        psutil
        kornia
        soundfile

        spandrel
      ] ++ plugins
  );
in
  pkgs.stdenvNoCC.mkDerivation {
    name = "comfyui";
    pname = "comfyui";
    version = "dev-${builtins.toString comfyui.lastModified}";
    src = comfyui;
    nativeBuildInputs = let
      inherit (pkgs) makeWrapper;
    in [
      makeWrapper
    ];
    propagatedBuildInputs = let
      inherit (pkgs.cudaPackages) cudatoolkit;
    in [
      python
      cudatoolkit
    ];

    patches = [./folder_paths.patch];

    installPhase = let
      launcher =
        pkgs.writeShellScript "launch.sh"
        ''
          mkdir -p $COMFY_DIR/custom_nodes
          mkdir -p $COMFY_DIR/models/{checkpoints,configs,loras,vae,clip,unet,diffusion_models,clip_vision,style_models,embeddings,diffusers,vae_approx,controlnet,gligen,upscale_models,hypernetworks,photomaker,classifiers}
          ${python}/bin/python3 $COMFY/comfyui/main.py --output-directory $(mktemp)
        '';
    in ''
      mkdir -p $out/comfyui
      cp -r * $out/comfyui
      mkdir -p $out/bin
      makeWrapper ${launcher} $out/bin/comfyui --prefix PATH : ${lib.makeBinPath [python]} \
        --set PYTHONPATH ${lib.makeLibraryPath [python]} --set COMFY $out --set COMFY_DIR ${comfy_dir}
    '';
    meta.mainProgram = "comfyui";
  }
