Stable Diffusion 插件开发基础讲解

近来Stable diffusion扩散网络大热,跟上时代,简单的文生图,图生图,其实可以满足绝大多数设计师的应用,但是有什么是赛博画手无法做到的呢?

那就是他们使用到的stable diffusion的插件开发,他们并不清楚stable diffusino的代码结构,如果遇到一些代码层面的报错问题,他们将无法简单解决。

我们想要开发出我想要的stable diffusion插件。那么我们首先要去学习一些gradio的基础知识。

Gradio接口文档

1.想要了解stable diffusion的插件的形式,插件基本都是放在extension文件夹里面。

启动器提供通过git下载对应的内容。

其实就是通过直接copy github里面的代码来实现插件的。

2.以一个简单ffmpeg嵌入倒放视频的功能为例吧

启动的时候需要安装一些库,需要准备install.py文件会自动运行代码

复制代码
import launch
if not launch.is_installed("ffmpeg-python"):
    launch.run_pip("install ffmpeg-python", "requirements for TemporalKit extension")

if not launch.is_installed("moviepy"):
    launch.run_pip("install moviepy", "requirements for TemporalKit extension")
    
if not launch.is_installed("imageio_ffmpeg"):
    launch.run_pip("install imageio_ffmpeg", "requirements for TemporalKit extension")

requirement.txt最好也准备一些你需要的库

复制代码
ffmpeg-python
moviepy

3.一个启动简单的启动代码,看不懂的可以看注释,这个例子简单包含按钮,滑动条,视频展示等容器。如果需要查看更多的容器,需要去看gradio api

复制代码
import gradio as gr
from modules import scripts, script_callbacks
import os
import ffmpeg

# base_dir = scripts.basedir()

#ffmpeg倒放命令
def convert_video(input_file: str, output_directory: str, speed: int, reverse: bool):
  #ffmpeg -i G:\1\c6cfb2d13929eb4967417e0bd81c314c.mp4 -vf reverse -y reverse.mp4
  fileName = os.path.basename(input_file)
  outputFile = os.path.join(output_directory, fileName)
  ffm = ffmpeg.input(input_file)
  if speed != 1 :
    ffm = ffm.filter('setpts', f'PTS/{speed}')

  if reverse :
    ffm = ffm.filter("reverse")

  ffm.output(outputFile).run()
  return outputFile

def on_ui_tabs():
  with gr.Blocks(analytics_enabled=False) as ffmpeg_kit_ui:
    with gr.Row():
      with gr.Column(variant="panel"):
        with gr.Column():
          video_file = gr.Textbox(
            label="Video File",
            placeholder="Wrire your video file address",
            value="",
            interactive=True,
          )
          org_video = gr.Video(
            interactive=True, mirror_webcam=False
          )
          def fn_upload_org_video(video):
            return video
          org_video.upload(fn_upload_org_video, org_video, video_file)
          gr.HTML(value="<p style='margin-bottom: 1.2em'>\
            If you have trouble entering the video path manually, you can also use drag and drop.For large videos, please enter the path manually. \
          </p>")
        with gr.Column():
          output_directory = gr.Textbox(
            label="Video Output Directory",
            placeholder="Directory containing your output files",
            value="",
            interactive=True,
          )
        with gr.Column():
          with gr.Row():
            speed_slider = gr.Slider(
              label="Video Speed",
              minimum=0, maximum=8,
              step=0.1,
              value=1
            )
          with gr.Row():
            reverse_checkbox = gr.Checkbox(
              label="Video need reverse",
              value=False
            )
      with gr.Column(variant="panel"):
        with gr.Row():
          convert_video_btn = gr.Button(
            "Convert Video", label="Convert Video", variant="primary"
          )
        with gr.Row():
          dst_video = gr.Video(
            interactive=True, mirror_webcam=False
          )
        #生成按钮
        convert_video_btn.click(
          convert_video,
          inputs=[
            video_file,
            output_directory,
            speed_slider,
            reverse_checkbox
          ],
          outputs=dst_video
        )
        gr.HTML(value="<p>Converts video in a folder</p>")
  #ui布局 扩展模块名 
  return (ffmpeg_kit_ui, "FFmpeg Kit", "ffmpeg_kit_ui"),

#启动的时候,script_callback加载到扩展模块当中
script_callbacks.on_ui_tabs(on_ui_tabs)
print("FFmpeg kit init")

这里只是一个ffmpeg的功能嵌入,并没有包含原来一些文生图,图生图的功能。

4.下一个介绍如何嵌入功能到文生图或者图生图的脚本功能

def title(self):设置脚本的标题,例如设想为"prompt matrix"

def show(self, is_img2img):决定脚本标签是否可以显示,比如如果脚本只想展示在img2img标签中,那便需要在show方法中做判断

def ui(self, is_img2img):ui界面的相关代码,例如"把可变部分放在提示词文本的开头""为每张图片使用不同随机种子"这些选项的实现。

def run(self, p, angle, hflip, vflip, overwrite):额外的处理流程,例如在这里改变prompt,然后传给下一步。这里p是图片处理器,里面的参数是可以读取ui里面的返回的[]对象

复制代码
#加载到文生图或者图生图的应用过程当中
class FFmpegKitScript(scripts.Script):
  def __init__(self) -> None:
    super().__init__()
  # 功能块名
  def title(self):
    return "FFmpeg Kit"
  #是否默认显示
  def show(self, is_img2img):
      return scripts.AlwaysVisible
  
  #ui显示
  def ui(self, is_img2img):
    video_file = gr.Textbox(
      label="Video File",
      placeholder="Wrire your video file address",
      value="",
      interactive=True,
    )
    output_directory = gr.Textbox(
      label="Video Output Directory",
      placeholder="Directory containing your output files",
      value="",
      interactive=True,
    )

    generateBtn = gr.Button("Generate", label="Generate", variant="primary")

    generateBtn.click(
      convert_video,
      inputs=[
        video_file,
        output_directory
      ],
      outputs=[]
    )

    return [
      video_file,
      output_directory,
      generateBtn,
    ]
  #运行的时候嵌入运行
  def run(self, video_file, output_directory, generateBtn):
    return

4.添加到设定页面里面
这里需要调用script_callbacks.on_ui_settings方法
shared.opts.add_optioin是添加公共的设置,Shared.OptionsInfo里面是对应的布局,对应都是return对象。
实在不知道怎么写的同学可以参照infinite_zoom这个插件。

vbnet复制代码def on_ui_settings():
    section = ("infinite-zoom", "Infinite Zoom")

    shared.opts.add_option(
        "infzoom_outpath",
        shared.OptionInfo(
            "outputs",
            "Path where to store your infinite video. Default is Outputs",
            gr.Textbox,
            {"interactive": True},
            section=section,    
        ),
    )

    shared.opts.add_option(
        "infzoom_outSUBpath",
        shared.OptionInfo(
            "infinite-zooms",
            "Which subfolder name to be created in the outpath. Default is 'infinite-zooms'",
            gr.Textbox,
            {"interactive": True},
            section=section,
        ),
    )

script_callbacks.on_ui_settings方法

shared.opts.add_optioin是添加公共的设置,Shared.OptionsInfo里面(on_ui_settings)

需要拿出设置里面的数据,可以拿shared.opts.data.get的方法来实现

复制代码
output_path = shared.opts.data.get("infzoom_outpath", "outputs")

这里简单介绍了,stable diffusion的插件功能的方法,一些深入的定制需要会在接下来的文章中介绍一些深入应用。

相关推荐
CoovallyAIHub29 分钟前
港大&字节重磅发布DanceGRPO:突破视觉生成RLHF瓶颈,多项任务性能提升超180%!
深度学习·算法·计算机视觉
CoovallyAIHub1 小时前
英伟达ViPE重磅发布!解决3D感知难题,SLAM+深度学习完美融合(附带数据集下载地址)
深度学习·算法·计算机视觉
xiaohouzi1122332 天前
OpenCV的cv2.VideoCapture如何加GStreamer后端
人工智能·opencv·计算机视觉
小关会打代码2 天前
计算机视觉案例分享之答题卡识别
人工智能·计算机视觉
天天进步20152 天前
用Python打造专业级老照片修复工具:让时光倒流的数字魔法
人工智能·计算机视觉
荼蘼2 天前
答题卡识别改分项目
人工智能·opencv·计算机视觉
IT古董2 天前
【第五章:计算机视觉-项目实战之图像分类实战】1.经典卷积神经网络模型Backbone与图像-(4)经典卷积神经网络ResNet的架构讲解
人工智能·计算机视觉·cnn
张子夜 iiii2 天前
4步OpenCV-----扫秒身份证号
人工智能·python·opencv·计算机视觉
paid槮2 天前
机器视觉之图像处理篇
图像处理·opencv·计算机视觉
九章云极AladdinEdu2 天前
超参数自动化调优指南:Optuna vs. Ray Tune 对比评测
运维·人工智能·深度学习·ai·自动化·gpu算力