【StableDiffusion】2024.6.4 亲测成功,无魔法 Civitai 镜像,国内下载 Civitai 模型的方法

一、废话不说,直接开始

废话:请注意,这个插件不是万能的,有一些模型无法下载,大概能下载 70% 左右的模型

1.github下载插件

https://github.com/tzwm/sd-webui-model-downloader-cn/tree/main

这个步骤不用我多说了吧…
如果会用 git 的话,直接到 extension 目录下:

输入cmd,回车,打开cmd,

在这里插入图片描述

运行 git 命令

git clone --depth 1 https://github.com/tzwm/sd-webui-model-downloader-cn.git

在这里插入图片描述

2.下载之后的插件在这里

对比一下大小吧,别下载失败了

在这里插入图片描述

二、改源码

1.为什么改源码?

经过我的测试,这个源码一进行预览,就会报错,爆得满屏都是 error
我不确定这是否是源码本身的问题,有可能是我本地网络环境的问题

TIPS:到这个步骤的时候,你可以尝试一下,按照 github 上开发者的方法,能不能正常预览和下载 civitai 上面的模型
如果不行的话,就照我下面说的做吧

2.改!

2.1
进入 sd-webui-model-downloader-cn\scripts 目录

在这里插入图片描述
在这里插入图片描述

2.2
用 IDE 打开这个 model-downloader-cn.py 文件

在这里插入图片描述
2.3
把这整个文件直接全部删除,把我下面的代码黏贴进去 (别忘了把末尾的 CSDN 的文字水印去掉…)

import modules.scripts as scripts
from modules.paths_internal import models_path, data_path
from modules import script_callbacks, shared
from PIL import Image
import numpy as np
import gradio as gr
import requests
import os
import re
import subprocess
import threading


API_URL = "https://api.tzone03.xyz/"
ONLINE_DOCS_URL = API_URL + "docs/"
RESULT_PATH = "tmp/model-downloader-cn.log"
VERSION = "v1.1.4"


def check_aria2c():
    try:
        subprocess.run("aria2c", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except FileNotFoundError:
        return False

def process_image(url):
    response = requests.get(url, stream=True)
    image = Image.open(response.raw)
    return image

def get_model_path(model_type):
    co = shared.cmd_opts
    pj = os.path.join
    MODEL_TYPE_DIR = {
        "Checkpoint": ["ckpt_dir", pj(models_path, 'Stable-diffusion')],
        "LORA": ["lora_dir", pj(models_path, 'Lora')],
        "TextualInversion": ["embeddings_dir", pj(data_path, 'embeddings')],
        "Hypernetwork": ["hypernetwork_dir", pj(models_path, 'hypernetworks')],
        # "AestheticGradient": "",
        # "Controlnet": "", #controlnet-dir
        "LoCon": ["lyco_dir", pj(models_path, 'LyCORIS')],
        "VAE": ["vae_dir", pj(models_path, 'VAE')],
    }

    dir_list = MODEL_TYPE_DIR.get(model_type)
    if dir_list == None:
        return None

    if hasattr(co, dir_list[0]) and getattr(co, dir_list[0]):
        return getattr(co, dir_list[0])
    else:
        return dir_list[1]


def request_civitai_detail(url):
    pattern = r'https://civitai\.com/models/(.+)'
    m = re.match(pattern, url)
    if not m:
        return False, "不是一个有效的 civitai 模型页面链接,暂不支持"

    req_url = API_URL + "civitai/models/" + m.group(1)
    res = requests.get(req_url)

    if res.status_code >= 500:
        return False, "呃 服务好像挂了,理论上我应该在修了,可以进群看看进度……"
    if res.status_code >= 400:
        return False, "不是一个有效的 civitai 模型页面链接,暂不支持"

    if res.ok:
        return True, res.json()
    else:
        return False, res.text


def resp_to_components(resp):
    if resp is None:
        return [None, None, None, None, None, None, None, None, None, None]

    img = resp["version"]["image"]["url"]
    if img:
        img = process_image(img)

    trained_words = resp["version"].get("trainedWords", [])
    if not trained_words:
        trained_words = ["girl"]

    trained_words_str = ", ".join(trained_words)
    updated_at = resp["version"].get("updatedAt", "N/A")

    return [
        resp["name"],
        resp["type"],
        trained_words_str,
        resp["creator"]["username"],
        ", ".join(resp["tags"]),
        updated_at,
        resp["description"],
        img,
        resp["version"]["file"]["name"],
        resp["version"]["file"]["downloadUrl"],
    ]

def preview(url):
    ok, resp = request_civitai_detail(url)
    if not ok:
        return [resp] + resp_to_components(None) + [gr.update(interactive=False)]

    has_download_file = False
    more_guides = ""
    if resp["version"]["file"]["downloadUrl"]:
        has_download_file = True
        more_guides = f',点击下载按钮\n{resp["version"]["file"]["name"]}'

    return [f"预览成功{more_guides}"] + resp_to_components(resp) + \
           [gr.update(interactive=has_download_file)]



def download(model_type, filename, url, image_arr):
    if not (model_type and url and filename):
        return "下载信息缺失"

    target_path = get_model_path(model_type)
    if not target_path:
        return f"暂不支持这种类型:{model_type}"

    if isinstance(image_arr, np.ndarray) and image_arr.any() is not None:
        image_filename = filename.rsplit(".", 1)[0] + ".jpeg"
        target_file = os.path.join(target_path, image_filename)
        if not os.path.exists(target_file):
            image = Image.fromarray(image_arr)
            image.save(target_file)

    target_file = os.path.join(target_path, filename)
    if os.path.exists(target_file):
        return f"已经存在了,不重复下载:\n{target_file}"


    cmd = f'curl -o "{target_file}" "{url}" 2>&1'
    if check_aria2c():
        cmd = f'aria2c -c -x 16 -s 16 -k 1M -d "{target_path}" -o "{filename}" "{url}" 2>&1'

    result = subprocess.run(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        encoding="UTF-8"
    )
    status_output = ""
    if result.returncode == 0:
        status_output = f"下载成功,保存到:\n{target_file}\n{result.stdout}"
    else:
        status_output = f"下载失败了,错误信息:\n{result.stdout}"

    return status_output


def request_online_docs():
    banner = "## 加载失败,可以更新插件试试:\nhttps://github.com/tzwm/sd-webui-model-downloader-cn"
    footer = "## 交流互助群\n![](https://oss.talesofai.cn/public/qrcode_20230413-183818.png?cc0429)"

    try:
        res = requests.get(ONLINE_DOCS_URL + "banner.md")
        if res.ok:
            banner = res.text

        res = requests.get(ONLINE_DOCS_URL + "footer.md")
        if res.ok:
            footer = res.text
    except Exception as e:
        print("sd-webui-model-downloader-cn 文档请求失败")

    return banner, footer


def on_ui_tabs():
    banner, footer = request_online_docs()

    with gr.Blocks() as ui_component:
        gr.Markdown(banner)
        with gr.Row() as input_component:
            with gr.Column():
                inp_url = gr.Textbox(
                    label="Civitai 模型的页面地址,不是下载链接",
                    placeholder="类似 https://civitai.com/models/28687/pen-sketch-style"
                )
                with gr.Row():
                    preview_btn = gr.Button("预览")
                    download_btn = gr.Button("下载", interactive=False)
                with gr.Row():
                    result = gr.Textbox(
                        # value=result_update,
                        label="执行结果",
                        interactive=False,
                        # every=1,
                    )
            with gr.Column() as preview_component:
                with gr.Row():
                    with gr.Column() as model_info_component:
                        name = gr.Textbox(label="名称", interactive=False)
                        model_type = gr.Textbox(label="类型", interactive=False)
                        trained_words = gr.Textbox(label="触发词", interactive=False)
                        creator = gr.Textbox(label="作者", interactive=False)
                        tags = gr.Textbox(label="标签", interactive=False)
                        updated_at = gr.Textbox(label="最近更新时间", interactive=False)
                    with gr.Column() as model_image_component:
                        image = gr.Image(
                            show_label=False,
                            interactive=False,
                        )
                with gr.Accordion("介绍", open=False):
                    description = gr.HTML()
        with gr.Row(visible=False):
            filename = gr.Textbox(
                visible=False,
                label="model_filename",
                interactive=False,
            )
            download_url = gr.Textbox(
                visible=False,
                label="model_download_url",
                interactive=False,
            )
        with gr.Row():
            gr.Markdown(f"版本:{VERSION}\n\n作者:@tzwm\n{footer}")


        def preview_components():
            return [
                name,
                model_type,
                trained_words,
                creator,
                tags,
                updated_at,
                description,
                image,
            ]

        def file_info_components():
            return [
                filename,
                download_url,
            ]

        preview_btn.click(
            fn=preview,
            inputs=[inp_url],
            outputs=[result] + preview_components() + \
                file_info_components() + [download_btn]
        )
        download_btn.click(
            fn=download,
            inputs=[model_type] + file_info_components() + [image],
            outputs=[result]
        )

    return [(ui_component, "模型下载", "model_downloader_cn_tab")]

script_callbacks.on_ui_tabs(on_ui_tabs)

2.4
保存,退出,重启 StableDiffusion 的 WEB UI

三、试试?

1.试试就试试

1.1
随便找一个 civitai 上面的模型,按照 github 原作者的说明进行操作(也就是复制 url)

在这里插入图片描述
1.2
黏贴,预览,成功的话点击“下载”
请注意,点击下载之后不会有任何反应,如何判断模型是否已经开始下载了呢?
打开 任务管理器,看看网络是不是开始快速占用了!

在这里插入图片描述

开始下载啦

在这里插入图片描述

四、没啦,祝你今天开心.

  • 13
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MicroLindb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值