code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
#!/bin/bash
# SD WebUI Forge 启动参数配置
# 启动参数将保存在 <Start Path>/term-sd/config/sd-webui-forge-launch.conf
sd_webui_forge_launch_args_setting() {
local arg
local dialog_arg
local launch_args
local i
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--checklist "请选择 Stable-Diffusion-WebUI-Forge 启动参数, 确认之后将覆盖原有启动参数配置" \
$(get_dialog_size_menu) \
"1" "(update-all-extensions) 启动时更新所有扩展" OFF \
"2" "(skip-python-version-check) 跳过检查 Python 版本" OFF \
"3" "(skip-torch-cuda-test) 跳过 CUDA 可用性检查" OFF \
"4" "(reinstall-xformers) 启动时重新安装 xFormers" OFF \
"5" "(reinstall-torch) 启动时重新安装 PyTorch" OFF \
"6" "(update-check) 启动时检查更新" OFF \
"7" "(test-server) 配置测试服务器" OFF \
"8" "(log-startup) 显示详细启动日志" OFF \
"9" "(skip-prepare-environment) 跳过所有环境准备工作" OFF \
"10" "(skip-install) 跳过软件包的安装" OFF \
"11" "(dump-sysinfo) 将系统信息文件保存到磁盘并退出" OFF \
"12" "(do-not-download-clip) 跳过下载 CLIP 模型" OFF \
"13" "(no-half) 关闭 UNet 半精度优化" OFF \
"14" "(no-half-vae) 关闭 VAE 模型半精度优化" OFF \
"15" "(no-progressbar-hiding) 不隐藏 Gradio UI 中进度条" OFF \
"16" "(allow-code) 允许从 WebUI 执行自定义脚本" OFF \
"17" "(medvram) 启用显存优化 (显存 < 6g 时推荐使用)" OFF \
"18" "(medvram-sdxl) 仅在 SDXL 模型启用显存优化 (显存 < 8g 时推荐使用)" OFF \
"19" "(lowvram) 启用显存优化 (显存 < 4g 时推荐使用)" OFF \
"20" "(lowram) 将模型加载到显存中而不是内存中" OFF \
"21" "(precision full) 使用模型全精度" OFF \
"22" "(upcast-sampling) 使用向上采样法提高精度" OFF \
"23" "(share) 通过 Gradio 共享" OFF \
"24" "(enable-insecure-extension-access) 允许在开放远程访问时安装插件" OFF \
"25" "(xformers) 尝试使用 xFormers 优化" OFF \
"26" "(force-enable-xformers) 强制使用 xFormers 优化" OFF \
"27" "(xformers-flash-attention) 使用 xFormers-Flash优化 (仅支持 SD2.x 以上)" OFF \
"28" "(opt-split-attention) 使用 Split 优化" OFF \
"29" "(opt-sub-quad-attention) 使用 Sub-Quad 优化" OFF \
"30" "(opt-split-attention-invokeai) 使用 Sub-Quad-InvokeAI 优化" OFF \
"31" "(opt-split-attention-v1) 使用 Sub-Quad-V1 优化" OFF \
"32" "(opt-sdp-attention) 使用 Sdp 优化 (仅限 PyTorch2.0 以上)" OFF \
"33" "(opt-sdp-no-mem-attention) 使用无高效内存使用的 Sdp 优化" OFF \
"34" "(disable-opt-split-attention) 禁用 Split 优化" OFF \
"35" "(disable-nan-check) 禁用潜空间 NAN 检查" OFF \
"36" "(use-cpu) 使用 CPU 进行生图" OFF \
"37" "(disable-model-loading-ram-optimization) 禁用减少内存使用的优化" OFF \
"38" "(listen) 开放远程连接" OFF \
"39" "(hide-ui-dir-config) 隐藏 WebUI 目录配置" OFF \
"40" "(freeze-settings) 冻结 WebUI 设置" OFF \
"41" "(gradio-debug) 以 Debug 模式启用 Gradio" OFF \
"42" "(opt-channelslast) 使用 ChannelsLast 内存格式优化" OFF \
"43" "(autolaunch) 启动 WebUI 完成后自动启动浏览器" OFF \
"44" "(theme dark) 使用黑暗主题" OFF \
"45" "(use-textbox-seed) 使用文本框在 WebUI 中生成的种子" OFF \
"46" "(disable-console-progressbars) 禁用控制台进度条显示" OFF \
"47" "(enable-console-prompts) 启用在生图时输出提示词到控制台" OFF \
"48" "(disable-safe-unpickle) 禁用检查模型是否包含恶意代码" OFF \
"49" "(api) 启用 API" OFF \
"50" "(api-log) 启用输出所有 API 请求的日志记录" OFF \
"51" "(nowebui) 不加载 WebUI 界面" OFF \
"52" "(ui-debug-mode) 不加载模型启动 WebUI (UI Debug)" OFF \
"53" "(administrator) 启用管理员权限" OFF \
"54" "(disable-tls-verify) 禁用 TLS 证书验证" OFF \
"55" "(no-gradio-queue) 禁用 Gradio 队列" OFF \
"56" "(skip-version-check) 禁用 PyTorch, xFormers 版本检查" OFF \
"57" "(no-hashing) 禁用模型 Hash 检查" OFF \
"58" "(no-download-sd-model) 禁用自动下载模型, 即使模型路径无模型" OFF \
"59" "(add-stop-route) 添加 /_stop 路由以停止服务器" OFF \
"60" "(api-server-stop) 通过 API 启用服务器停止 / 重启 / 终止功能" OFF \
"61" "(disable-all-extensions) 禁用所有扩展运行" OFF \
"62" "(disable-extra-extensions) 禁用非内置的扩展运行" OFF \
"63" "(use-ipex) 使用 Intel XPU 作为生图后端" OFF \
"64" "(skip-load-model-at-start) 启动 WebUI 时不加载模型, 加速启动" OFF \
"65" "(in-browser) 启动 WebUI 完成后自动启动浏览器" OFF \
"66" "(disable-in-browser) 禁用在启动 WebUI 完成后自动启动浏览器" OFF \
"67" "(async-cuda-allocation) 启用 CUDA 流顺序内存分配器" OFF \
"68" "(disable-async-cuda-allocation) 禁用 CUDA 流顺序内存分配器" OFF \
"69" "(disable-attention-upcast) 禁用向上注意力优化" OFF \
"70" "(all-in-fp32) 强制使用 FP32" OFF \
"71" "(all-in-fp16) 强制使用 FP16" OFF \
"72" "(unet-in-bf16) 使用 BF16 精度运行 UNet" OFF \
"73" "(unet-in-fp16) 使用 FP16 精度运行 UNet" OFF \
"74" "(unet-in-fp8-e4m3fn) 使用 FP8(e4m3fn) 精度运行 UNet" OFF \
"75" "(unet-in-fp8-e5m2) 使用 FP8(e5m2) 精度运行 UNet" OFF \
"76" "(vae-in-fp16) 使用 FP16 精度运行 VAE" OFF \
"77" "(vae-in-fp32) 使用 FP32 精度运行 VAE" OFF \
"78" "(vae-in-bf16) 使用 BF16 精度运行 VAE" OFF \
"79" "(vae-in-cpu) 将 VAE 移至 CPU" OFF \
"80" "(clip-in-fp8-e4m3fn) 使用 FP8(e4m3fn) 精度运行 CLIP" OFF \
"81" "(clip-in-fp8-e5m2) 使用 FP8(e5m2) 精度运行 CLIP" OFF \
"82" "(clip-in-fp16) 使用 FP16 精度运行 CLIP" OFF \
"83" "(clip-in-fp32) 使用 FP32 精度运行 CLIP" OFF \
"84" "(disable-ipex-hijack) 禁用 IEPX 修复" OFF \
"85" "(preview-option none) 不使用图片预览" OFF \
"86" "(preview-option fast) 使用快速图片预览" OFF \
"87" "(preview-option taesd) 使用 TAESD 图片预览" OFF \
"88" "(attention-split) 使用 Split 优化" OFF \
"89" "(attention-quad) 使用 Quad 优化" OFF \
"90" "(attention-pytorch) 使用 PyTorch 方案优化" OFF \
"91" "(disable-xformers) 禁用 xFormers 优化" OFF \
"92" "(always-gpu) 将所有模型, 文本编码器储存在 GPU 中" OFF \
"93" "(always-high-vram) 不使用显存优化" OFF \
"94" "(always-normal-vram) 使用默认显存优化" OFF \
"95" "(always-low-vram) 使用显存优化 (将会降低生图速度)" OFF \
"96" "(always-no-vram) 使用显存优化 (将会大量降低生图速度)" OFF \
"97" "(always-cpu) 使用 CPU 进行生图" OFF \
"98" "(always-offload-from-vram) 生图完成后将模型从显存中卸载" OFF \
"99" "(pytorch-deterministic) 将 PyTorch 配置为使用确定性算法" OFF \
"100" "(disable-server-log) 禁用服务端日志输出" OFF \
"101" "(debug-mode) 启用 Debug 模式" OFF \
"102" "(is-windows-embedded-python) 启用 Windows 独占功能" OFF \
"103" "(disable-server-info) 禁用服务端信息输出" OFF \
"104" "(multi-user) 启用多用户模式" OFF \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
for i in ${dialog_arg}; do
case "${i}" in
1)
arg="--update-all-extensions"
;;
2)
arg="--skip-python-version-check"
;;
3)
arg="--skip-torch-cuda-test"
;;
4)
arg="--reinstall-xformers"
;;
5)
arg="--reinstall-torch"
;;
6)
arg="--update-check"
;;
7)
arg="--test-server"
;;
8)
arg="--log-startup"
;;
9)
arg="--skip-prepare-environment"
;;
10)
arg="--skip-install"
;;
11)
arg="--dump-sysinfo"
;;
12)
arg="--do-not-download-clip"
;;
13)
arg="--no-half"
;;
14)
arg="--no-half-vae"
;;
15)
arg="--no-progressbar-hiding"
;;
16)
arg="--allow-code"
;;
17)
arg="--medvram"
;;
18)
arg="--medvram-sdxl"
;;
19)
arg="--lowvram"
;;
20)
arg="--lowram"
;;
21)
arg="--precision full"
;;
22)
arg="--upcast-sampling"
;;
23)
arg="--share"
;;
24)
arg="--enable-insecure-extension-access"
;;
25)
arg="--xformers"
;;
26)
arg="--force-enable-xformers"
;;
27)
arg="--xformers-flash-attention"
;;
28)
arg="--opt-split-attention"
;;
29)
arg="--opt-sub-quad-attention"
;;
30)
arg="--opt-split-attention-invokeai"
;;
31)
arg="--opt-split-attention-v1"
;;
32)
arg="--opt-sdp-attention"
;;
33)
arg="--opt-sdp-no-mem-attention"
;;
34)
arg="--disable-opt-split-attention"
;;
35)
arg="--disable-nan-check"
;;
36)
arg="--use-cpu all"
;;
37)
arg="--disable-model-loading-ram-optimization"
;;
38)
arg="--listen"
;;
39)
arg="--hide-ui-dir-config"
;;
40)
arg="--freeze-settings"
;;
41)
arg="--gradio-debug"
;;
42)
arg="--opt-channelslast"
;;
43)
arg="--autolaunch"
;;
44)
arg="--theme dark"
;;
45)
arg="--use-textbox-seed"
;;
46)
arg="--disable-console-progressbars"
;;
47)
arg="--enable-console-prompts"
;;
48)
arg="--disable-safe-unpickle"
;;
49)
arg="--api"
;;
50)
arg="--api-log"
;;
51)
arg="--nowebui"
;;
52)
arg="--ui-debug-mode"
;;
53)
arg="--administrator"
;;
54)
arg="--disable-tls-verify"
;;
55)
arg="--no-gradio-queue"
;;
56)
arg="--skip-version-check"
;;
57)
arg="--no-hashing"
;;
58)
arg="--no-download-sd-model"
;;
59)
arg="--add-stop-route"
;;
60)
arg="--api-server-stop"
;;
61)
arg="--disable-all-extensions"
;;
62)
arg="--disable-extra-extensions"
;;
63)
arg="--use-ipex"
;;
64)
arg="--skip-load-model-at-start"
;;
65)
arg="--in-browser"
;;
66)
arg="--disable-in-browser"
;;
67)
arg="--async-cuda-allocation"
;;
68)
arg="--disable-async-cuda-allocation"
;;
69)
arg="--disable-attention-upcast"
;;
70)
arg="--all-in-fp32"
;;
71)
arg="--all-in-fp16"
;;
72)
arg="--unet-in-bf16"
;;
73)
arg="--unet-in-fp16"
;;
74)
arg="--unet-in-fp8-e4m3fn"
;;
75)
arg="--unet-in-fp8-e5m2"
;;
76)
arg="--vae-in-fp16"
;;
77)
arg="--vae-in-fp32"
;;
78)
arg="--vae-in-bf16"
;;
79)
arg="--vae-in-cpu"
;;
80)
arg="--clip-in-fp8-e4m3fn"
;;
81)
arg="--clip-in-fp8-e5m2"
;;
82)
arg="--clip-in-fp16"
;;
83)
arg="--clip-in-fp32"
;;
84)
arg="--disable-ipex-hijack"
;;
85)
arg="--preview-option none"
;;
86)
arg="--preview-option fast"
;;
87)
arg="--preview-option taesd"
;;
88)
arg="--attention-split"
;;
89)
arg="--attention-quad"
;;
90)
arg="--attention-pytorch"
;;
91)
arg="--disable-xformers"
;;
92)
arg="--always-gpu"
;;
93)
arg="--always-high-vram"
;;
94)
arg="--always-normal-vram"
;;
95)
arg="--always-low-vram"
;;
96)
arg="--always-no-vram"
;;
97)
arg="--always-cpu"
;;
98)
arg="--always-offload-from-vram"
;;
99)
arg="--pytorch-deterministic"
;;
100)
arg="--disable-server-log"
;;
101)
arg="--debug-mode"
;;
102)
arg="--is-windows-embedded-python"
;;
103)
arg="--disable-server-info"
;;
104)
arg="--multi-user"
;;
esac
launch_args="${arg} ${launch_args}"
done
# 生成启动脚本
term_sd_echo "设置 Stable-Diffusion-WebUI-Forge 启动参数: ${launch_args}"
echo "launch.py ${launch_args}" > "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf
else
term_sd_echo "取消设置 Stable-Diffusion-WebUI-Forge 启动参数"
fi
}
# SD WebUI Forge 启动界面
sd_webui_forge_launch() {
local dialog_arg
local launch_args
add_sd_webui_forge_normal_launch_args
while true; do
launch_args=$(cat "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf)
if is_use_venv; then
launch_args="python ${launch_args}"
else
launch_args="${TERM_SD_PYTHON_PATH} ${launch_args}"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择启动 Stable-Diffusion-WebUI-Forge / 修改 Stable-Diffusion-WebUI-Forge 启动参数\n当前启动参数: ${launch_args}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启动" \
"2" "> 配置预设启动参数" \
"3" "> 修改自定义启动参数" \
"4" "> 重置启动参数" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_launch
;;
2)
sd_webui_forge_launch_args_setting
;;
3)
sd_webui_forge_launch_args_revise
;;
4)
restore_sd_webui_forge_launch_args
;;
*)
break
;;
esac
done
}
# SD WebUI Forge 启动参数修改
sd_webui_forge_launch_args_revise() {
local dialog_arg
local launch_args
launch_args=$(cat "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf | awk '{sub("launch.py ","")}1')
dialog_arg=$(dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 自定义启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 Stable-Diffusion-WebUI-Forge 启动参数" \
$(get_dialog_size) \
"${launch_args}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
term_sd_echo "设置 Stable-Diffusion-WebUI-Forge 启动参数: ${dialog_arg}"
echo "launch.py ${dialog_arg}" > "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf
else
term_sd_echo "取消修改 Stable-Diffusion-WebUI-Forge 启动参数"
fi
}
# 添加默认启动参数配置
add_sd_webui_forge_normal_launch_args() {
if [[ ! -f "${START_PATH}/term-sd/config/sd-webui-forge-launch.conf" ]]; then # 找不到启动配置时默认生成一个
echo "launch.py --theme dark --autolaunch --xformers --api" > "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf
fi
}
# 重置启动参数
restore_sd_webui_forge_launch_args() {
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 重置启动参数选项选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 Stable-Diffusion-WebUI-Forge 启动参数" \
$(get_dialog_size)); then
term_sd_echo "重置 Stable-Diffusion-WebUI-Forge 启动参数"
rm -f "${START_PATH}"/term-sd/config/sd-webui-forge-launch.conf
add_sd_webui_forge_normal_launch_args
else
term_sd_echo "取消重置 Stable-Diffusion-WebUI-Forge 启动参数操作"
fi
}
|
2301_81996401/term-sd
|
modules/sd_webui_forge_launch.sh
|
Shell
|
agpl-3.0
| 21,177
|
#!/bin/bash
# SD WebUI 管理
sd_webui_manager() {
local dialog_arg
local sd_webui_branch
local sd_webui_branch_point
cd "${START_PATH}" # 回到最初路径
exit_venv # 确保进行下一步操作前已退出其他虚拟环境
if [[ -d "${SD_WEBUI_ROOT_PATH}" ]] && ! term_sd_is_dir_empty "${SD_WEBUI_ROOT_PATH}" ;then # 找到stable-diffusion-webui目录
while true; do
cd "${SD_WEBUI_ROOT_PATH}"
case $(git remote get-url origin | awk -F '/' '{print $NF}') in # 分支判断
stable-diffusion-webui|stable-diffusion-webui.git)
sd_webui_branch="AUTOMATIC1111 webui $(git_branch_display)"
sd_webui_branch_point="sd_webui"
;;
automatic|automatic.git)
sd_webui_branch="vladmandic webui $(git_branch_display)"
sd_webui_branch_point="sd_next"
;;
stable-diffusion-webui-directml|stable-diffusion-webui-directml.git|stable-diffusion-webui-amdgpu|stable-diffusion-webui-amdgpu.git)
sd_webui_branch="lshqqytiger webui $(git_branch_display)"
sd_webui_branch_point="sd_webui_amdgpu"
;;
stable-diffusion-webui-forge|stable-diffusion-webui-forge.git)
sd_webui_branch="lllyasviel webui $(git_branch_display)"
sd_webui_branch_point="sd_webui_forge"
;;
stable-diffusion-webui-reForge|stable-diffusion-webui-reForge.git)
sd_webui_branch="Panchovix webui $(git_branch_display)"
sd_webui_branch_point="sd_webui_reforge"
;;
sd-webui-forge-classic|sd-webui-forge-classic.git)
sd_webui_branch="Haoming02 webui $(git_branch_display)"
sd_webui_branch_point="sd_webui_forge_classic"
;;
*)
sd_webui_branch="null (Git文件损坏)"
sd_webui_branch_point="sd_webui"
esac
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 管理选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择 Stable-Diffusion-WebUI 管理选项的功能\n当前更新源: $(git_remote_display)\n当前分支: ${sd_webui_branch}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启动" \
"2" "> 更新" \
"3" "> 修复更新" \
"4" "> 管理插件" \
"5" "> 切换版本" \
"6" "> 更新源替换" \
"7" "> 分支切换" \
"8" "> 更新依赖" \
"9" "> Python 软件包安装 / 重装 / 卸载" \
"10" "> 依赖库版本管理" \
"11" "> 重新安装 PyTorch" \
"12" "> 修复虚拟环境" \
"13" "> 重新构建虚拟环境" \
"14" "> 重新安装后端组件" \
"15" "> 重新安装" \
"16" "> 卸载" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
sd_webui_launch
;;
2)
if is_git_repo; then
term_sd_echo "更新 Stable-Diffusion-WebUI 中"
git_pull_repository
if [[ "$?" == 0 ]]; then
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新结果" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 更新成功" \
$(get_dialog_size)
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新结果" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 更新失败" \
$(get_dialog_size)
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新结果" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 非 Git 安装, 无法更新" \
$(get_dialog_size)
fi
;;
3)
if is_git_repo; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新修复选项" \
--yes-label "是" --no-label "否" \
--yesno "是否修复 Stable-Diffusion-Webui 更新 ?" \
$(get_dialog_size)); then
git_fix_pointer_offset
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新修复选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 修复更新完成" \
$(get_dialog_size)
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新修复选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 非 Git 安装, 无法修复更新" \
$(get_dialog_size)
fi
;;
4)
sd_webui_extension_manager
;;
5)
if is_git_repo; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 版本切换选项" \
--yes-label "是" --no-label "否" \
--yesno "是否切换 Stable-Diffusion-Webui 版本 ?" \
$(get_dialog_size)); then
git_ver_switch && \
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 版本切换选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 版本切换完成, 当前版本为: $(git_branch_display)" \
$(get_dialog_size)
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 版本切换选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 非 Git 安装, 无法切换版本" \
$(get_dialog_size)
fi
;;
6)
if is_git_repo; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新源切换选项" \
--yes-label "是" --no-label "否" \
--yesno "是否切换 Stable-Diffusion-WebUI 更新源 ?" \
$(get_dialog_size)); then
sd_webui_remote_revise
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 更新源切换选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 非 Git 安装, 无法切换更新源" \
$(get_dialog_size)
fi
;;
7)
if is_git_repo; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 分支切换选项" \
--yes-label "是" --no-label "否" \
--yesno "是否切换 Stable-Diffusion-WebUI 分支 ?" \
$(get_dialog_size)); then
sd_webui_branch_switch
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 分支切换选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 非 Git 安装, 无法切换分支" \
$(get_dialog_size)
fi
;;
8)
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 依赖更新选项" \
--yes-label "是" --no-label "否" \
--yesno "是否更新 Stable-Diffusion-WebUI 的依赖 ?" \
$(get_dialog_size)); then
sd_webui_update_depend
fi
;;
9)
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 的 Python 软件包安装 / 重装 / 卸载选项" \
--yes-label "是" --no-label "否" \
--yesno "是否进入 Python 软件包安装 / 重装 / 卸载选项 ?" \
$(get_dialog_size)); then
python_package_manager
fi
;;
10)
python_package_ver_backup_manager
;;
11)
pytorch_reinstall
;;
12)
if is_use_venv; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 虚拟环境修复选项" \
--yes-label "是" --no-label "否" \
--yesno "是否修复 Stable-Diffusion-WebUI 的虚拟环境" \
$(get_dialog_size)); then
fix_venv
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 虚拟环境修复选项" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 虚拟环境修复完成" \
$(get_dialog_size)
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 虚拟环境修复选项" \
--ok-label "确认" \
--msgbox "虚拟环境功能已禁用, 无法使用该功能" \
$(get_dialog_size)
fi
;;
13)
if is_use_venv; then
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 虚拟环境重建选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重建 Stable-Diffusion-WebUI 的虚拟环境 ?" \
$(get_dialog_size));then
sd_webui_venv_rebuild
fi
else
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 虚拟环境重建选项" \
--ok-label "确认" \
--msgbox "虚拟环境功能已禁用, 无法使用该功能" \
$(get_dialog_size)
fi
;;
14)
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 后端组件重装选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重新安装 Stable-Diffusion-WebUI 后端组件 ?" \
$(get_dialog_size)); then
sd_webui_backend_repo_reinstall "${sd_webui_branch_point}"
fi
;;
15)
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 重新安装选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重新安装 Stable-Diffusion-WebUI ?" \
$(get_dialog_size)); then
cd "${START_PATH}"
rm -f "${START_PATH}/term-sd/task/sd_webui_install.sh"
exit_venv
install_sd_webui
break
fi
;;
16)
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 删除选项" \
--yes-label "是" --no-label "否" \
--yesno "是否删除 Stable-Diffusion-WebUI ?" \
$(get_dialog_size)); then
term_sd_echo "请再次确认是否删除 Stable-Diffusion-WebUI (yes/no) ?"
term_sd_echo "警告: 该操作将永久删除 Stable-Diffusion-WebUI"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
yes|y|YES|Y)
term_sd_echo "删除 Stable-Diffusion-WebUI 中"
exit_venv
cd ..
rm -rf "${SD_WEBUI_ROOT_PATH}"
dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 删除选项" \
--ok-label "确认" \
--msgbox "删除 Stable-Diffusion-WebUI 完成" \
$(get_dialog_size)
break
;;
*)
term_sd_echo "取消删除操作"
;;
esac
fi
;;
*)
break
;;
esac
done
else #找不到stable-diffusion-webui目录
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 安装选项" \
--yes-label "是" --no-label "否" \
--yesno "检测到当前未安装 Stable-Diffusion-WebUI , 是否进行安装 ?" \
$(get_dialog_size)); then
install_sd_webui
fi
fi
}
# SD WebUI 依赖更新功能
sd_webui_update_depend() {
# 更新前的准备
download_mirror_select # 下载镜像源选择
pip_install_mode_select upgrade # 安装方式选择
if term_sd_install_confirm "是否更新 Stable-Diffusion-WebUI 依赖 ?"; then
term_sd_print_line "Stable-Diffusion-WebUI 依赖更新"
term_sd_echo "更新 Stable-Diffusion-WebUI 依赖中"
term_sd_tmp_disable_proxy
enter_venv
python_package_update "requirements_versions.txt"
install_python_package git+$(git_format_repository_url "${GITHUB_MIRROR}" https://github.com/openai/CLIP)
exit_venv
term_sd_tmp_enable_proxy
term_sd_echo "更新 Stable-Diffusion-WebUI 依赖结束"
term_sd_pause
fi
clean_install_config # 清理安装参数
}
# SD WebUI 后端组件重装
# 使用:
# sd_webui_backend_repo_reinstall <分支名称>
sd_webui_backend_repo_reinstall() {
local branch=$@
download_mirror_select # 下载镜像源选择
if term_sd_install_confirm "是否重新安装 Stable-Diffusion-WebUI 后端组件 ?"; then
term_sd_print_line "Stable-Diffusion-WebUI 后端组件重装"
term_sd_echo "删除原有 Stable-Diffusion-WebUI 后端组件中"
rm -rf "${SD_WEBUI_ROOT_PATH}"/repositories/*
term_sd_echo "重新下载 Stable-Diffusion-WebUI 后端组件中"
git_clone_repository https://github.com/salesforce/BLIP "${SD_WEBUI_ROOT_PATH}"/repositories BLIP
git_clone_repository https://github.com/Stability-AI/stablediffusion "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-stability-ai
git_clone_repository https://github.com/Stability-AI/generative-models "${SD_WEBUI_ROOT_PATH}"/repositories generative-models
git_clone_repository https://github.com/crowsonkb/k-diffusion "${SD_WEBUI_ROOT_PATH}"/repositories k-diffusion
git_clone_repository https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-webui-assets
case "${branch}" in
sd_webui|sd_webui_forge|sd_webui_amdgpu)
git_clone_repository https://github.com/salesforce/BLIP "${SD_WEBUI_ROOT_PATH}"/repositories BLIP
git_clone_repository https://github.com/Stability-AI/stablediffusion "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-stability-ai
git_clone_repository https://github.com/Stability-AI/generative-models "${SD_WEBUI_ROOT_PATH}"/repositories generative-models
git_clone_repository https://github.com/crowsonkb/k-diffusion "${SD_WEBUI_ROOT_PATH}"/repositories k-diffusion
git_clone_repository https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-webui-assets
;;
sd_next)
git_clone_repository https://github.com/salesforce/BLIP "${SD_WEBUI_ROOT_PATH}"/repositories blip
git_clone_repository https://github.com/Stability-AI/stablediffusion "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-stability-ai
git_clone_repository https://github.com/Stability-AI/generative-models "${SD_WEBUI_ROOT_PATH}"/repositories generative-models
git_clone_repository https://github.com/crowsonkb/k-diffusion "${SD_WEBUI_ROOT_PATH}"/repositories k-diffusion
git_clone_repository https://github.com/AUTOMATIC1111/stable-diffusion-webui-assets "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-webui-assets
;;
sd_webui_forge)
git_clone_repository https://github.com/salesforce/BLIP "${SD_WEBUI_ROOT_PATH}"/repositories BLIP
git_clone_repository https://github.com/Stability-AI/stablediffusion "${SD_WEBUI_ROOT_PATH}"/repositories stable-diffusion-stability-ai
git_clone_repository https://github.com/Stability-AI/generative-models "${SD_WEBUI_ROOT_PATH}"/repositories generative-models
git_clone_repository https://github.com/crowsonkb/k-diffusion "${SD_WEBUI_ROOT_PATH}"/repositories k-diffusion
git_clone_repository https://github.com/lllyasviel/huggingface_guess "${SD_WEBUI_ROOT_PATH}"/repositories huggingface_guess
git_clone_repository https://github.com/lllyasviel/google_blockly_prototypes "${SD_WEBUI_ROOT_PATH}"/repositories google_blockly_prototypes
;;
sd_webui_forge_classic)
true
;;
esac
term_sd_echo "重装 Stable-Diffusion-WebUI 后端组件结束"
term_sd_pause
fi
clean_install_config # 清理安装参数
}
|
2301_81996401/term-sd
|
modules/sd_webui_manager.sh
|
Shell
|
agpl-3.0
| 21,922
|
#!/bin/bash
# SD WebUI reForge 启动参数配置
# 启动参数将保存在 <Start Path>/term-sd/config/sd-webui-reforge-launch.conf
sd_webui_reforge_launch_args_setting() {
local arg
local dialog_arg
local launch_args
local i
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--checklist "请选择 Stable-Diffusion-WebUI-reForge 启动参数, 确认之后将覆盖原有启动参数配置" \
$(get_dialog_size_menu) \
"1" "(update-all-extensions) 启动时更新所有扩展" OFF \
"2" "(skip-python-version-check) 跳过检查 Python 版本" OFF \
"3" "(skip-torch-cuda-test) 跳过 CUDA 可用性检查" OFF \
"4" "(reinstall-xformers) 启动时重新安装 xFormers" OFF \
"5" "(reinstall-torch) 启动时重新安装 PyTorch" OFF \
"6" "(update-check) 启动时检查更新" OFF \
"7" "(test-server) 配置测试服务器" OFF \
"8" "(log-startup) 显示详细启动日志" OFF \
"9" "(skip-prepare-environment) 跳过所有环境准备工作" OFF \
"10" "(skip-install) 跳过软件包的安装" OFF \
"11" "(dump-sysinfo) 将系统信息文件保存到磁盘并退出" OFF \
"12" "(do-not-download-clip) 跳过下载 CLIP 模型" OFF \
"13" "(no-half) 关闭 UNet 半精度优化" OFF \
"14" "(no-half-vae) 关闭 VAE 模型半精度优化" OFF \
"15" "(no-progressbar-hiding) 不隐藏 Gradio UI 中进度条" OFF \
"16" "(allow-code) 允许从 WebUI 执行自定义脚本" OFF \
"17" "(medvram) 启用显存优化 (显存 < 6g 时推荐使用)" OFF \
"18" "(medvram-sdxl) 仅在 SDXL 模型启用显存优化 (显存 < 8g 时推荐使用)" OFF \
"19" "(lowvram) 启用显存优化 (显存 < 4g 时推荐使用)" OFF \
"20" "(lowram) 将模型加载到显存中而不是内存中" OFF \
"21" "(precision full) 使用模型全精度" OFF \
"22" "(upcast-sampling) 使用向上采样法提高精度" OFF \
"23" "(share) 通过 Gradio 共享" OFF \
"24" "(enable-insecure-extension-access) 允许在开放远程访问时安装插件" OFF \
"25" "(xformers) 尝试使用 xFormers 优化" OFF \
"26" "(force-enable-xformers) 强制使用 xFormers 优化" OFF \
"27" "(xformers-flash-attention) 使用 xFormers-Flash优化 (仅支持 SD2.x 以上)" OFF \
"28" "(opt-split-attention) 使用 Split 优化" OFF \
"29" "(opt-sub-quad-attention) 使用 Sub-Quad 优化" OFF \
"30" "(opt-split-attention-invokeai) 使用 Sub-Quad-InvokeAI 优化" OFF \
"31" "(opt-split-attention-v1) 使用 Sub-Quad-V1 优化" OFF \
"32" "(opt-sdp-attention) 使用 Sdp 优化 (仅限 PyTorch2.0 以上)" OFF \
"33" "(opt-sdp-no-mem-attention) 使用无高效内存使用的 Sdp 优化" OFF \
"34" "(disable-opt-split-attention) 禁用 Split 优化" OFF \
"35" "(disable-nan-check) 禁用潜空间 NAN 检查" OFF \
"36" "(use-cpu) 使用 CPU 进行生图" OFF \
"37" "(disable-model-loading-ram-optimization) 禁用减少内存使用的优化" OFF \
"38" "(listen) 开放远程连接" OFF \
"39" "(hide-ui-dir-config) 隐藏 WebUI 目录配置" OFF \
"40" "(freeze-settings) 冻结 WebUI 设置" OFF \
"41" "(gradio-debug) 以 Debug 模式启用 Gradio" OFF \
"42" "(opt-channelslast) 使用 ChannelsLast 内存格式优化" OFF \
"43" "(autolaunch) 启动 WebUI 完成后自动启动浏览器" OFF \
"44" "(theme dark) 使用黑暗主题" OFF \
"45" "(use-textbox-seed) 使用文本框在 WebUI 中生成的种子" OFF \
"46" "(disable-console-progressbars) 禁用控制台进度条显示" OFF \
"47" "(enable-console-prompts) 启用在生图时输出提示词到控制台" OFF \
"48" "(disable-safe-unpickle) 禁用检查模型是否包含恶意代码" OFF \
"49" "(api) 启用 API" OFF \
"50" "(api-log) 启用输出所有 API 请求的日志记录" OFF \
"51" "(nowebui) 不加载 WebUI 界面" OFF \
"52" "(ui-debug-mode) 不加载模型启动 WebUI (UI Debug)" OFF \
"53" "(administrator) 启用管理员权限" OFF \
"54" "(disable-tls-verify) 禁用 TLS 证书验证" OFF \
"55" "(no-gradio-queue) 禁用 Gradio 队列" OFF \
"56" "(skip-version-check) 禁用 PyTorch, xFormers 版本检查" OFF \
"57" "(no-hashing) 禁用模型 Hash 检查" OFF \
"58" "(no-download-sd-model) 禁用自动下载模型, 即使模型路径无模型" OFF \
"59" "(add-stop-route) 添加 /_stop 路由以停止服务器" OFF \
"60" "(api-server-stop) 通过 API 启用服务器停止 / 重启 / 终止功能" OFF \
"61" "(disable-all-extensions) 禁用所有扩展运行" OFF \
"62" "(disable-extra-extensions) 禁用非内置的扩展运行" OFF \
"63" "(use-ipex) 使用 Intel XPU 作为生图后端" OFF \
"64" "(skip-load-model-at-start) 启动 WebUI 时不加载模型, 加速启动" OFF \
"65" "(in-browser) 启动 WebUI 完成后自动启动浏览器" OFF \
"66" "(disable-in-browser) 禁用在启动 WebUI 完成后自动启动浏览器" OFF \
"67" "(async-cuda-allocation) 启用 CUDA 流顺序内存分配器" OFF \
"68" "(disable-async-cuda-allocation) 禁用 CUDA 流顺序内存分配器" OFF \
"69" "(disable-attention-upcast) 禁用向上注意力优化" OFF \
"70" "(all-in-fp32) 强制使用 FP32" OFF \
"71" "(all-in-fp16) 强制使用 FP16" OFF \
"72" "(unet-in-bf16) 使用 BF16 精度运行 UNet" OFF \
"73" "(unet-in-fp16) 使用 FP16 精度运行 UNet" OFF \
"74" "(unet-in-fp8-e4m3fn) 使用 FP8(e4m3fn) 精度运行 UNet" OFF \
"75" "(unet-in-fp8-e5m2) 使用 FP8(e5m2) 精度运行 UNet" OFF \
"76" "(vae-in-fp16) 使用 FP16 精度运行 VAE" OFF \
"77" "(vae-in-fp32) 使用 FP32 精度运行 VAE" OFF \
"78" "(vae-in-bf16) 使用 BF16 精度运行 VAE" OFF \
"79" "(vae-in-cpu) 将 VAE 移至 CPU" OFF \
"80" "(clip-in-fp8-e4m3fn) 使用 FP8(e4m3fn) 精度运行 CLIP" OFF \
"81" "(clip-in-fp8-e5m2) 使用 FP8(e5m2) 精度运行 CLIP" OFF \
"82" "(clip-in-fp16) 使用 FP16 精度运行 CLIP" OFF \
"83" "(clip-in-fp32) 使用 FP32 精度运行 CLIP" OFF \
"84" "(disable-ipex-hijack) 禁用 IEPX 修复" OFF \
"85" "(preview-option none) 不使用图片预览" OFF \
"86" "(preview-option fast) 使用快速图片预览" OFF \
"87" "(preview-option taesd) 使用 TAESD 图片预览" OFF \
"88" "(attention-split) 使用 Split 优化" OFF \
"89" "(attention-quad) 使用 Quad 优化" OFF \
"90" "(attention-pytorch) 使用 PyTorch 方案优化" OFF \
"91" "(disable-xformers) 禁用 xFormers 优化" OFF \
"92" "(always-gpu) 将所有模型, 文本编码器储存在 GPU 中" OFF \
"93" "(always-high-vram) 不使用显存优化" OFF \
"94" "(always-normal-vram) 使用默认显存优化" OFF \
"95" "(always-low-vram) 使用显存优化 (将会降低生图速度)" OFF \
"96" "(always-no-vram) 使用显存优化 (将会大量降低生图速度)" OFF \
"97" "(always-cpu) 使用 CPU 进行生图" OFF \
"98" "(always-offload-from-vram) 生图完成后将模型从显存中卸载" OFF \
"99" "(pytorch-deterministic) 将 PyTorch 配置为使用确定性算法" OFF \
"100" "(disable-server-log) 禁用服务端日志输出" OFF \
"101" "(debug-mode) 启用 Debug 模式" OFF \
"102" "(is-windows-embedded-python) 启用 Windows 独占功能" OFF \
"103" "(disable-server-info) 禁用服务端信息输出" OFF \
"104" "(multi-user) 启用多用户模式" OFF \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
for i in ${dialog_arg}; do
case "${i}" in
1)
arg="--update-all-extensions"
;;
2)
arg="--skip-python-version-check"
;;
3)
arg="--skip-torch-cuda-test"
;;
4)
arg="--reinstall-xformers"
;;
5)
arg="--reinstall-torch"
;;
6)
arg="--update-check"
;;
7)
arg="--test-server"
;;
8)
arg="--log-startup"
;;
9)
arg="--skip-prepare-environment"
;;
10)
arg="--skip-install"
;;
11)
arg="--dump-sysinfo"
;;
12)
arg="--do-not-download-clip"
;;
13)
arg="--no-half"
;;
14)
arg="--no-half-vae"
;;
15)
arg="--no-progressbar-hiding"
;;
16)
arg="--allow-code"
;;
17)
arg="--medvram"
;;
18)
arg="--medvram-sdxl"
;;
19)
arg="--lowvram"
;;
20)
arg="--lowram"
;;
21)
arg="--precision full"
;;
22)
arg="--upcast-sampling"
;;
23)
arg="--share"
;;
24)
arg="--enable-insecure-extension-access"
;;
25)
arg="--xformers"
;;
26)
arg="--force-enable-xformers"
;;
27)
arg="--xformers-flash-attention"
;;
28)
arg="--opt-split-attention"
;;
29)
arg="--opt-sub-quad-attention"
;;
30)
arg="--opt-split-attention-invokeai"
;;
31)
arg="--opt-split-attention-v1"
;;
32)
arg="--opt-sdp-attention"
;;
33)
arg="--opt-sdp-no-mem-attention"
;;
34)
arg="--disable-opt-split-attention"
;;
35)
arg="--disable-nan-check"
;;
36)
arg="--use-cpu all"
;;
37)
arg="--disable-model-loading-ram-optimization"
;;
38)
arg="--listen"
;;
39)
arg="--hide-ui-dir-config"
;;
40)
arg="--freeze-settings"
;;
41)
arg="--gradio-debug"
;;
42)
arg="--opt-channelslast"
;;
43)
arg="--autolaunch"
;;
44)
arg="--theme dark"
;;
45)
arg="--use-textbox-seed"
;;
46)
arg="--disable-console-progressbars"
;;
47)
arg="--enable-console-prompts"
;;
48)
arg="--disable-safe-unpickle"
;;
49)
arg="--api"
;;
50)
arg="--api-log"
;;
51)
arg="--nowebui"
;;
52)
arg="--ui-debug-mode"
;;
53)
arg="--administrator"
;;
54)
arg="--disable-tls-verify"
;;
55)
arg="--no-gradio-queue"
;;
56)
arg="--skip-version-check"
;;
57)
arg="--no-hashing"
;;
58)
arg="--no-download-sd-model"
;;
59)
arg="--add-stop-route"
;;
60)
arg="--api-server-stop"
;;
61)
arg="--disable-all-extensions"
;;
62)
arg="--disable-extra-extensions"
;;
63)
arg="--use-ipex"
;;
64)
arg="--skip-load-model-at-start"
;;
65)
arg="--in-browser"
;;
66)
arg="--disable-in-browser"
;;
67)
arg="--async-cuda-allocation"
;;
68)
arg="--disable-async-cuda-allocation"
;;
69)
arg="--disable-attention-upcast"
;;
70)
arg="--all-in-fp32"
;;
71)
arg="--all-in-fp16"
;;
72)
arg="--unet-in-bf16"
;;
73)
arg="--unet-in-fp16"
;;
74)
arg="--unet-in-fp8-e4m3fn"
;;
75)
arg="--unet-in-fp8-e5m2"
;;
76)
arg="--vae-in-fp16"
;;
77)
arg="--vae-in-fp32"
;;
78)
arg="--vae-in-bf16"
;;
79)
arg="--vae-in-cpu"
;;
80)
arg="--clip-in-fp8-e4m3fn"
;;
81)
arg="--clip-in-fp8-e5m2"
;;
82)
arg="--clip-in-fp16"
;;
83)
arg="--clip-in-fp32"
;;
84)
arg="--disable-ipex-hijack"
;;
85)
arg="--preview-option none"
;;
86)
arg="--preview-option fast"
;;
87)
arg="--preview-option taesd"
;;
88)
arg="--attention-split"
;;
89)
arg="--attention-quad"
;;
90)
arg="--attention-pytorch"
;;
91)
arg="--disable-xformers"
;;
92)
arg="--always-gpu"
;;
93)
arg="--always-high-vram"
;;
94)
arg="--always-normal-vram"
;;
95)
arg="--always-low-vram"
;;
96)
arg="--always-no-vram"
;;
97)
arg="--always-cpu"
;;
98)
arg="--always-offload-from-vram"
;;
99)
arg="--pytorch-deterministic"
;;
100)
arg="--disable-server-log"
;;
101)
arg="--debug-mode"
;;
102)
arg="--is-windows-embedded-python"
;;
103)
arg="--disable-server-info"
;;
104)
arg="--multi-user"
;;
esac
launch_args="${arg} ${launch_args}"
done
# 生成启动脚本
term_sd_echo "设置 Stable-Diffusion-WebUI-reForge 启动参数: ${launch_args}"
echo "launch.py ${launch_args}" > "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf
else
term_sd_echo "取消设置 Stable-Diffusion-WebUI-reForge 启动参数"
fi
}
# SD WebUI reForge 启动界面
sd_webui_reforge_launch() {
local dialog_arg
local launch_args
add_sd_webui_reforge_normal_launch_args
while true; do
launch_args=$(cat "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf)
if is_use_venv; then
launch_args="python ${launch_args}"
else
launch_args="${TERM_SD_PYTHON_PATH} ${launch_args}"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择启动 Stable-Diffusion-WebUI-reForge / 修改 Stable-Diffusion-WebUI-reForge 启动参数\n当前启动参数: ${launch_args}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启动" \
"2" "> 配置预设启动参数" \
"3" "> 修改自定义启动参数" \
"4" "> 重置启动参数" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_launch
;;
2)
sd_webui_reforge_launch_args_setting
;;
3)
sd_webui_reforge_launch_args_revise
;;
4)
restore_sd_webui_reforge_launch_args
;;
*)
break
;;
esac
done
}
# SD WebUI reForge 启动参数修改
sd_webui_reforge_launch_args_revise() {
local dialog_arg
local launch_args
launch_args=$(cat "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf | awk '{sub("launch.py ","")}1')
dialog_arg=$(dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 自定义启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 Stable-Diffusion-WebUI-reForge 启动参数" \
$(get_dialog_size) \
"${launch_args}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
term_sd_echo "设置 Stable-Diffusion-WebUI-reForge 启动参数: ${dialog_arg}"
echo "launch.py ${dialog_arg}" > "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf
else
term_sd_echo "取消修改 Stable-Diffusion-WebUI-reForge 启动参数"
fi
}
# 添加默认启动参数配置
add_sd_webui_reforge_normal_launch_args() {
if [[ ! -f "${START_PATH}/term-sd/config/sd-webui-reforge-launch.conf" ]]; then # 找不到启动配置时默认生成一个
echo "launch.py --theme dark --autolaunch --xformers --api" > "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf
fi
}
# 重置启动参数
restore_sd_webui_reforge_launch_args() {
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 重置启动参数选项选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 Stable-Diffusion-WebUI-reForge 启动参数" \
$(get_dialog_size)); then
term_sd_echo "重置 Stable-Diffusion-WebUI-reForge 启动参数"
rm -f "${START_PATH}"/term-sd/config/sd-webui-reforge-launch.conf
add_sd_webui_reforge_normal_launch_args
else
term_sd_echo "取消重置 Stable-Diffusion-WebUI-reForge 启动参数操作"
fi
}
|
2301_81996401/term-sd
|
modules/sd_webui_reforge_launch.sh
|
Shell
|
agpl-3.0
| 21,241
|
#!/bin/bash
# 获取 CUDA 内存分配器配置
get_pytorch_cuda_memory_conf() {
local status
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/check_cuda_malloc_avaliable.py")
echo "${status}"
}
# CUDA 内存分配设置
# 参考:
# https://blog.csdn.net/MirageTanker/article/details/127998036
# https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Optimizations
# CUDA 内存分配配置保存在 <Start Path>/term-sd/config/set-cuda-memory-alloc.lock
cuda_memory_alloc_setting() {
local dialog_arg
local cuda_alloc_info
while true; do
if [[ -f "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock" ]]; then
cuda_alloc_info="启用"
else
cuda_alloc_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "CUDA 内存分配设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于更换底层 CUDA 内存分配器 (仅支持 Nvidia 显卡, 且 CUDA 版本需要大于 11.4)\n当前内存分配器设置: ${cuda_alloc_info}\n是否启用 CUDA 内存分配器 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
touch "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "CUDA 内存分配设置界面" \
--ok-label "确认" \
--msgbox "启用 CUDA 内存分配器成功" \
$(get_dialog_size)
;;
2)
rm -f "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "CUDA 内存分配设置界面" \
--ok-label "确认" \
--msgbox "禁用 CUDA 内存分配器成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
|
2301_81996401/term-sd
|
modules/term_sd_check_cuda_malloc_avaliable.sh
|
Shell
|
agpl-3.0
| 2,277
|
#!/bin/bash
# 自定义 AI 软件安装路径设置
# SD WebUI 自定义安装路径配置保存在 <Start Path>/term-sd/config/sd-webui-path.conf
# ComfyUI 自定义安装路径配置保存在 <Start Path>/term-sd/config/comfyui-path.conf
# InvokeAI 自定义安装路径配置保存在 <Start Path>/term-sd/config/invokeai-path.conf
# Fooocus 自定义安装路径配置保存在 <Start Path>/term-sd/config/fooocus-path.conf
# lora-scripts 自定义安装路径配置保存在 <Start Path>/term-sd/config/lora-scripts-path.conf
# kohya_ss 自定义安装路径配置保存在 <Start Path>/term-sd/config/kohya_ss-path.conf
custom_install_path_setting() {
local dialog_arg
local custom_install_path
local sd_webui_info
local comfyui_info
local invokeai_info
local fooocus_info
local lora_scripts_info
local kohya_ss_info
while true; do
if [[ -f "${START_PATH}/term-sd/config/sd-webui-path.conf" ]]; then
sd_webui_info="自定义"
else
sd_webui_info="默认"
fi
if [[ -f "${START_PATH}/term-sd/config/comfyui-path.conf" ]]; then
comfyui_info="自定义"
else
comfyui_info="默认"
fi
if [[ -f "${START_PATH}/term-sd/config/invokeai-path.conf" ]]; then
invokeai_info="自定义"
else
invokeai_info="默认"
fi
if [[ -f "${START_PATH}/term-sd/config/fooocus-path.conf" ]]; then
fooocus_info="自定义"
else
fooocus_info="默认"
fi
if [[ -f "${START_PATH}/term-sd/config/lora-scripts-path.conf" ]]; then
lora_scripts_info="自定义"
else
lora_scripts_info="默认"
fi
if [[ -f "${START_PATH}/term-sd/config/kohya_ss-path.conf" ]]; then
kohya_ss_info="自定义"
else
kohya_ss_info="默认"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "自定义安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于自定义 AI 软件的安装路径, 当保持默认时, AI 软件的安装路径与 Term-SD 所在路径同级\n当前 Term-SD 所在路径: ${START_PATH}/term-sd\n注: 路径最好使用绝对路径" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> Stable-Diffusion-WebUI 安装路径设置 (当前配置: ${sd_webui_info})" \
"2" "> ComfyUI 安装路径设置 (当前配置: ${comfyui_info})" \
"3" "> InvokeAI 安装路径设置 (当前配置: ${invokeai_info})" \
"4" "> Fooocus 安装路径设置 (当前配置: ${fooocus_info})" \
"5" "> lora-scripts 安装路径设置 (当前配置: ${lora_scripts_info})" \
"6" "> kohya_ss 安装路径设置 (当前配置: ${kohya_ss_info})" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
sd_webui_custom_install_path_setting
;;
2)
comfyui_custom_install_path_setting
;;
3)
invokeai_custom_install_path_setting
;;
4)
fooocus_custom_install_path_setting
;;
5)
lora_scripts_custom_install_path_setting
;;
6)
kohya_ss_custom_install_path_setting
;;
*)
break
;;
esac
done
}
# SD WebUI 安装路径设置
sd_webui_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/sd-webui-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/sd-webui-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 Stable-Diffusion-WebUI 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${COMFYUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${INVOKEAI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${FOOOCUS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${LORA_SCRIPTS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${KOHYA_SS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他 AI 软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
SD_WEBUI_ROOT_PATH=$custom_install_path
SD_WEBUI_FOLDER=$(basename "${SD_WEBUI_ROOT_PATH}")
SD_WEBUI_PARENT_PATH=$(dirname "${SD_WEBUI_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/sd-webui-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "Stable-Diffusion-WebUI 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 Stable-Diffusion-WebUI 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/sd-webui-path.conf"
SD_WEBUI_ROOT_PATH="${START_PATH}/stable-diffusion-webui"
SD_WEBUI_FOLDER="stable-diffusion-webui"
SD_WEBUI_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Diffusion-WebUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 Stable-Diffusion-WebUI 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# ComfyUI 安装路径设置
comfyui_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/comfyui-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/comfyui-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(
dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 ComfyUI 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${SD_WEBUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${INVOKEAI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${FOOOCUS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${LORA_SCRIPTS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${KOHYA_SS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他 AI 软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
COMFYUI_ROOT_PATH=$custom_install_path
COMFYUI_FOLDER=$(basename "${COMFYUI_ROOT_PATH}")
COMFYUI_PARENT_PATH=$(dirname "${COMFYUI_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/comfyui-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "ComfyUI 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 ComfyUI 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/comfyui-path.conf"
COMFYUI_ROOT_PATH="${START_PATH}/ComfyUI"
COMFYUI_FOLDER="ComfyUI"
COMFYUI_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 ComfyUI 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# InvokeAI 安装路径设置
invokeai_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/invokeai-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/invokeai-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 InvokeAI 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${SD_WEBUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${COMFYUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${FOOOCUS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${LORA_SCRIPTS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${KOHYA_SS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他AI软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
INVOKEAI_ROOT_PATH=$custom_install_path
INVOKEAI_FOLDER=$(basename "${INVOKEAI_ROOT_PATH}")
INVOKEAI_PARENT_PATH=$(dirname "${INVOKEAI_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/invokeai-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "InvokeAI 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 InvokeAI 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/invokeai-path.conf"
INVOKEAI_ROOT_PATH="${START_PATH}/InvokeAI"
INVOKEAI_FOLDER="InvokeAI"
INVOKEAI_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "InvokeAI 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 InvokeAI 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# Fooocus 安装路径设置
fooocus_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/fooocus-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/fooocus-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 Fooocus 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${SD_WEBUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${COMFYUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${INVOKEAI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${LORA_SCRIPTS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${KOHYA_SS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他 AI 软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
FOOOCUS_ROOT_PATH=$custom_install_path
FOOOCUS_FOLDER=$(basename "${FOOOCUS_ROOT_PATH}")
FOOOCUS_PARENT_PATH=$(dirname "${FOOOCUS_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/fooocus-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" \
--msgbox "Fooocus 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 Fooocus 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/fooocus-path.conf"
FOOOCUS_ROOT_PATH="${START_PATH}/Fooocus"
FOOOCUS_FOLDER="Fooocus"
FOOOCUS_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 Fooocus 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# lora-scripts 安装路径设置
lora_scripts_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/lora-scripts-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/lora-scripts-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 lora-scripts 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${SD_WEBUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${COMFYUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${INVOKEAI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${FOOOCUS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${KOHYA_SS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他 AI 软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
LORA_SCRIPTS_ROOT_PATH=$custom_install_path
LORA_SCRIPTS_FOLDER=$(basename "${LORA_SCRIPTS_ROOT_PATH}")
LORA_SCRIPTS_PARENT_PATH=$(dirname "${LORA_SCRIPTS_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/lora-scripts-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" \
--msgbox "lora-scripts 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 lora-scripts 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/lora-scripts-path.conf"
LORA_SCRIPTS_ROOT_PATH="${START_PATH}/lora-scripts"
LORA_SCRIPTS_FOLDER="lora-scripts"
LORA_SCRIPTS_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 lora-scripts 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# kohya_ss安装路径设置
kohya_ss_custom_install_path_setting() {
local custom_install_path
local dialog_arg
local path_info
local install_path
while true; do
if [[ -f "${START_PATH}/term-sd/config/lora-scripts-path.conf" ]];then
path_info=$(cat "${START_PATH}/term-sd/config/lora-scripts-path.conf")
install_path=$path_info
else
path_info="默认"
unset install_path
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择配置选项\n当前自定义安装路径: ${path_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置安装路径" \
"2" "> 恢复默认安装路径设置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
custom_install_path=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 kohya_ss 安装路径\n注: 请使用绝对路径" \
$(get_dialog_size) \
"${install_path}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${custom_install_path}" ]]; then
if [[ "${custom_install_path}" == "/" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" \
--msgbox "禁止将根目录设置为安装路径" \
$(get_dialog_size)
elif [[ "${custom_install_path}" == "${SD_WEBUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${COMFYUI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${INVOKEAI_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${FOOOCUS_ROOT_PATH}" ]] \
|| [[ "${custom_install_path}" == "${LORA_SCRIPTS_ROOT_PATH}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" \
--msgbox "安装路径和其他AI软件的安装目录相同, 请重新设置" \
$(get_dialog_size)
else
KOHYA_SS_ROOT_PATH=$custom_install_path
KOHYA_SS_FOLDER=$(basename "${KOHYA_SS_ROOT_PATH}")
KOHYA_SS_PARENT_PATH=$(dirname "${KOHYA_SS_ROOT_PATH}")
echo "${custom_install_path}" > "${START_PATH}/term-sd/config/kohya_ss-path.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" \
--msgbox "kohya_ss 安装路径设置成功\n安装路径: ${custom_install_path}\n$(custom_install_path_is_rel_path_warning "${custom_install_path}")" \
$(get_dialog_size)
fi
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 kohya_ss 安装路径 ?" \
$(get_dialog_size)); then
rm -f "${START_PATH}/term-sd/config/kohya_ss-path.conf"
KOHYA_SS_ROOT_PATH="${START_PATH}/kohya_ss"
KOHYA_SS_FOLDER="kohya_ss"
KOHYA_SS_PARENT_PATH=$START_PATH
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 安装路径设置界面" \
--ok-label "确认" \
--msgbox "重置 kohya_ss 安装路径成功" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# 检测是否为相对路径, 是相对路径则返回0, 不是则返回1
term_sd_is_rel_path() {
if [[ ! "$(echo $@ | awk '{print substr($0,1,1)}')" == "/" ]]; then
# 路径不是 "/"" 开头
if is_windows_platform; then
return 1
else
return 0
fi
else
return 1
fi
}
# 输入的自定义安装路径为相对路径时返回警告信息
custom_install_path_is_rel_path_warning() {
if term_sd_is_rel_path "$@"; then
echo "检测到安装路径不是绝对路径, 可能会导致一些问题, 建议将安装路径修改为绝对路径"
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_custom_install_path_setting.sh
|
Shell
|
agpl-3.0
| 32,485
|
#!/bin/bash
# 检查 ComfyUI 环境完整性
# 如果出现缺失依赖, 将依赖文件路径保存在 <Term-SD>/term-sd/task/comfyui_depend_path_list.sh
# 如何出现冲突依赖, 将分析出来的冲突情况保存在 <Term-SD>/term-sd/task/comfyui_has_conflict_requirement_notice.sh
check_comfyui_env() {
term_sd_echo "检测 ComfyUI 依赖完整性中"
rm -f "${START_PATH}/term-sd/task/comfyui_has_conflict_requirement_notice.sh"
rm -f "${START_PATH}/term-sd/task/comfyui_depend_path_list.sh"
term_sd_python "${START_PATH}/term-sd/python_modules/check_comfyui_env.py" \
--comfyui-path "${COMFYUI_ROOT_PATH}" \
--conflict-depend-notice-path "${START_PATH}/term-sd/task/comfyui_has_conflict_requirement_notice.sh" \
--requirement-list-path "${START_PATH}/term-sd/task/comfyui_depend_path_list.sh"
if [[ -f "${START_PATH}/term-sd/task/comfyui_has_conflict_requirement_notice.sh" ]]; then
term_sd_echo "检测到当前 ComfyUI 环境中安装的插件之间存在依赖冲突情况, 该问题并非致命, 但建议只保留一个插件, 否则部分功能可能无法正常使用"
term_sd_echo "可在 Term-SD 中的 ComfyUI 管理 -> 管理自定义节点 -> 管理自定义节点 中禁用插件或者卸载插件"
term_sd_echo "您可以选择按顺序安装依赖, 由于这将向环境中安装不符合版本要求的组件, 您将无法完全解决此问题, 但可避免组件由于依赖缺失而无法启动的情况"
term_sd_echo "您通常情况下可以选择忽略该警告并继续运行"
term_sd_print_line "依赖冲突"
term_sd_echo "检测到冲突的依赖:"
cat "${START_PATH}/term-sd/task/comfyui_has_conflict_requirement_notice.sh"
term_sd_print_line
term_sd_echo "是否按顺序安装冲突依赖 (yes/no) ?"
term_sd_echo "提示:"
term_sd_echo "如果不选择按顺序安装冲突依赖, 则跳过安装冲突依赖直接运行 ComfyUI"
term_sd_echo "输入 yes 或 no 后回车"
case $(term_sd_read) in
yes|YES|y|Y)
term_sd_echo "选择按顺序安装依赖"
;;
*)
term_sd_echo "忽略警告并继续启动 ComfyUI"
return 0
;;
esac
fi
if [[ -f "${START_PATH}/term-sd/task/comfyui_depend_path_list.sh" ]]; then
install_comfyui_requirement "${START_PATH}/term-sd/task/comfyui_depend_path_list.sh"
else
term_sd_echo "ComfyUI 依赖完整性检测完成"
fi
rm -f "${START_PATH}/term-sd/task/comfyui_has_conflict_requirement_notice.sh"
rm -f "${START_PATH}/term-sd/task/comfyui_depend_path_list.sh"
}
# 安装 ComfyUI 缺失的依赖
# 使用:
# install_comfyui_requirement <ComfyUI 依赖路径记录表文件路径>
install_comfyui_requirement() {
local requirements_list_path=$@
local requirement_path
local cmd_point
local cmd_sum
local requirement_name
cmd_sum=$(cat "${requirements_list_path}" | wc -l) # 统计内容行数
for (( cmd_point=1; cmd_point <= cmd_sum; cmd_point++ )); do
requirement_path=$(cat "${requirements_list_path}" | awk 'NR=='${cmd_point}' {print $0}')
requirement_parent_path=$(dirname "${requirement_path}")
requirement_name=$(basename "${requirement_parent_path}")
cd "${requirement_parent_path}"
term_sd_echo "[${cmd_point}/${cmd_sum}] 安装 ${requirement_name} 依赖中"
install_python_package -r requirements.txt
if [[ "$?" == 0 ]]; then
term_sd_echo "[${cmd_point}/${cmd_sum}] 安装 ${requirement_name} 依赖成功"
else
term_sd_echo "[${cmd_point}/${cmd_sum}] 安装 ${requirement_name} 依赖失败, 这可能会影响部分功能"
fi
if [[ -f "install.py" ]]; then
term_sd_echo "[${cmd_point}/${cmd_sum}] 执行 ${requirement_name} 安装脚本中"
term_sd_try term_sd_python install.py
if [[ "$?" == 0 ]]; then
term_sd_echo "[${cmd_point}/${cmd_sum}] 执行 ${requirement_name} 安装脚本成功"
else
term_sd_echo "[${cmd_point}/${cmd_sum}] 执行 ${requirement_name} 安装脚本失败, 这可能会影响部分功能"
fi
fi
done
term_sd_echo "安装 ComfyUI 依赖结束"
cd "${COMFYUI_ROOT_PATH}"
}
# 回滚 Numpy 版本
fallback_numpy_version() {
local np_major_ver
term_sd_echo "检测 Numpy 版本中"
np_major_ver=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_numpy_ver.py")
if (( np_major_ver > 1 )); then
term_sd_echo "检测到 Numpy 版本过高, 尝试回退版本中"
install_python_package numpy==1.26.4
if [[ "$?" == 0 ]]; then
term_sd_echo "Numpy 版本回退成功"
else
term_sd_echo "Numpy 版本回退失败"
fi
else
term_sd_echo "Numpy 无版本问题"
fi
}
# 修复 PyTorch 的 libomp 问题
fix_pytorch() {
if is_windows_platform; then
term_sd_echo "检测 PyTorch 的 libomp 问题"
term_sd_python "${START_PATH}/term-sd/python_modules/fix_torch.py"
fi
}
# 验证内核依赖完整新
# 使用:
# validate_requirements <依赖表文件路径>
validate_requirements() {
local path=$@
local status
local current_path=$(pwd)
local dir_path
term_sd_echo "检测 ${TERM_SD_MANAGE_OBJECT} 内核依赖完整性中"
if [[ ! -f "${path}" ]]; then
term_sd_echo "依赖表文件缺失, 无法进行检测"
return 1
fi
dir_path=$(dirname "${path}")
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/validate_requirements.py" \
--requirement-path "${path}" \
)
if [[ "${status}" == "False" ]]; then
term_sd_echo "检测到 ${TERM_SD_MANAGE_OBJECT} 依赖有缺失, 将安装依赖"
cd "${dir_path}"
install_python_package -r "${path}"
if [[ "$?" == 0 ]]; then
term_sd_echo "${TERM_SD_MANAGE_OBJECT} 依赖安装成功"
else
term_sd_echo "${TERM_SD_MANAGE_OBJECT} 依赖安装失败"
fi
else
term_sd_echo "${TERM_SD_MANAGE_OBJECT} 无缺失依赖"
fi
cd "${current_path}"
term_sd_echo "检测 ${TERM_SD_MANAGE_OBJECT} 内核依赖完整性检测结束"
}
# 检查 onnxruntime-gpu 版本
check_onnxruntime_gpu_ver() {
local status
local args=$@
term_sd_echo "检测 onnxruntime-gpu 所支持的 CUDA 版本是否匹配 PyTorch 所支持的 CUDA 版本"
if [[ "${args}" == "force_check" ]]; then
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/check_onnxruntime_gpu.py" --ignore-ort-install)
else
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/check_onnxruntime_gpu.py")
fi
if [[ "${status}" == "cu118" ]]; then
term_sd_echo "检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作"
uninstall_onnxruntime_gpu
term_sd_echo "重新安装 onnxruntime-gpu"
if term_sd_is_use_uv; then
term_sd_uv_install onnxruntime-gpu==1.18.1 --no-cache-dir
if check_uv_install_failed_and_warning; then
term_sd_try term_sd_pip install onnxruntime-gpu==1.18.1 --no-cache-dir
fi
else
term_sd_try term_sd_pip install onnxruntime-gpu==1.18.1 --no-cache-dir
fi
elif [[ "${status}" == "cu121cudnn9" ]]; then
term_sd_echo "检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作"
uninstall_onnxruntime_gpu
term_sd_echo "重新安装 onnxruntime-gpu"
if term_sd_is_use_uv; then
term_sd_uv_install "onnxruntime-gpu>=1.19.0" --no-cache-dir
if check_uv_install_failed_and_warning; then
term_sd_try term_sd_pip install "onnxruntime-gpu>=1.19.0" --no-cache-dir
fi
else
term_sd_try term_sd_pip install "onnxruntime-gpu>=1.19.0" --no-cache-dir
fi
elif [[ "${status}" == "cu121cudnn8" ]]; then
term_sd_echo "检测到 onnxruntime-gpu 所支持的 CUDA 版本 和 PyTorch 所支持的 CUDA 版本不匹配, 将执行重装操作"
uninstall_onnxruntime_gpu
term_sd_echo "重新安装 onnxruntime-gpu"
if term_sd_is_use_uv; then
UV_DEFAULT_INDEX="https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/" \
term_sd_try term_sd_uv_install onnxruntime-gpu==1.17.1 --no-cache-dir
if check_uv_install_failed_and_warning; then
PIP_INDEX_URL="https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/" \
term_sd_try term_sd_pip install onnxruntime-gpu==1.17.1 --no-cache-dir
fi
else
PIP_INDEX_URL="https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/" \
term_sd_try term_sd_pip install onnxruntime-gpu==1.17.1 --no-cache-dir
fi
else
term_sd_echo "onnxruntime-gpu 无版本问题"
return 0
fi
if [[ "$?" == 0 ]]; then
term_sd_echo "重新安装 onnxruntime-gpu 成功"
else
term_sd_echo "重新安装 onnxruntime-gpu 失败, 这可能导致部分功能无法正常使用, 如使用反推模型无法正常调用 GPU 导致推理降速"
fi
}
# 卸载原有的 onnxruntime-gpu
uninstall_onnxruntime_gpu() {
if get_python_env_pkg 2> /dev/null | grep -q "onnxruntime-gpu"; then
term_sd_echo "卸载原有 onnxruntime-gpu"
term_sd_try term_sd_pip uninstall onnxruntime-gpu -y
fi
}
# 获取 SD WebUI 的 PYTHONPATH
get_sd_webui_python_path() {
local path
path=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_sd_webui_python_path.py")
echo "${path}"
}
# 安装 SD WebUI 的插件依赖
# 使用:
# check_sd_webui_extension_requirement_legacy <SD WebUI 参数配置文件>
check_sd_webui_extension_requirement_legacy() {
local py_path
local extension_name
local i
local status
local launch_sd_config=$@
local cancel_install_extension_requirement=0
local install_script_path
local count=0
local sum=0
py_path=$(get_sd_webui_python_path)
# 统计需要安装依赖的插件数量
for i in "${SD_WEBUI_ROOT_PATH}/extensions"/*; do
[[ -f "${i}" ]] && continue
[[ -f "${i}/install.py" ]] && sum=$(( sum + 1 ))
done
# 检查启动参数中是否包含禁用所有插件的启动参数
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-all\-extensions" &> /dev/null \
|| cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-extra\-extensions" &> /dev/null; then
cancel_install_extension_requirement=1
fi
if ! is_sd_webui_disable_all_extension && [[ "${cancel_install_extension_requirement}" == 0 ]]; then
term_sd_echo "检查 ${TERM_SD_MANAGE_OBJECT} 插件依赖中"
for i in "${SD_WEBUI_ROOT_PATH}/extensions"/*; do
if [[ -f "${i}" ]]; then
continue
fi
extension_name=$(basename "${i}")
install_script_path="${i}/install.py"
if [[ -f "${install_script_path}" ]]; then
count=$(( count + 1 ))
if ! is_sd_webui_extension_disabled "${extension_name}"; then
term_sd_echo "[${count}/${sum}] 执行 ${extension_name} 插件的依赖安装脚本中"
PYTHONPATH=$py_path term_sd_try term_sd_python "${install_script_path}"
if [[ "$?" == 0 ]]; then
term_sd_echo "[${count}/${sum}] ${extension_name} 插件的依赖安装脚本执行成功"
else
term_sd_echo "[${count}/${sum}] ${extension_name} 插件的依赖安装脚本执行失败, 这可能会导致 ${extension_name} 插件部分功能无法正常使用"
fi
else
term_sd_echo "[${count}/${sum}] ${extension_name} 插件已禁用, 不执行该插件的依赖安装脚本"
fi
fi
done
fi
}
# 安装 SD WebUI 的插件依赖
# 使用:
# check_sd_webui_extension_requirement_legacy <SD WebUI 参数配置文件>
check_sd_webui_extension_requirement() {
local i
local status
local launch_sd_config=$@
local cancel_install_extension_requirement=0
local install_script_path
local count=0
local sum=0
local disable_extra_extensions_arg=""
local disable_all_extensions_arg=""
# 检查启动参数中是否包含禁用所有插件的启动参数
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-all\-extensions" &> /dev/null; then
disable_all_extensions_arg="--disable-all-extensions"
fi
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-extra\-extensions" &> /dev/null; then
disable_extra_extensions_arg="--disable-extra-extensions"
fi
term_sd_echo "检查 ${TERM_SD_MANAGE_OBJECT} 扩展依赖中"
term_sd_python "${START_PATH}/term-sd/python_modules/install_sd_webui_extension_requirement.py" \
--sd-webui-base-path "${SD_WEBUI_ROOT_PATH}" \
${disable_extra_extensions_arg} \
${disable_all_extensions_arg}
if [[ "$?" == 0 ]]; then
term_sd_echo "检查 ${TERM_SD_MANAGE_OBJECT} 扩展依赖完成"
else
term_sd_echo "执行 ${TERM_SD_MANAGE_OBJECT} 扩展依赖检查脚本时发送错误"
fi
}
# 检查 SD WebUI Forge 内置插件依赖
# 使用:
# check_sd_webui_built_in_extension_requirement <SD WebUI 参数配置文件>
check_sd_webui_built_in_extension_requirement() {
local py_path
local extension_name
local i
local status
local launch_sd_config=$@
local cancel_install_extension_requirement=0
local install_script_path
local count=0
local sum=0
py_path=$(get_sd_webui_python_path)
# 统计需要安装依赖的插件数量
for i in "${SD_WEBUI_ROOT_PATH}/extensions-builtin"/*; do
[[ -f "${i}" ]] && continue
[[ -f "${i}/install.py" ]] && sum=$(( sum + 1 ))
done
# 检查启动参数中是否包含禁用所有插件的启动参数
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-all\-extensions" &> /dev/null \
|| cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-disable\-extra\-extensions" &> /dev/null; then
cancel_install_extension_requirement=1
fi
if ! is_sd_webui_disable_all_extension && [[ "${cancel_install_extension_requirement}" == 0 ]]; then
term_sd_echo "检查 ${TERM_SD_MANAGE_OBJECT} 内置插件依赖中"
for i in "${SD_WEBUI_ROOT_PATH}/extensions-builtin"/*; do
if [[ -f "${i}" ]]; then
continue
fi
extension_name=$(basename "${i}")
install_script_path="${i}/install.py"
if [[ -f "${install_script_path}" ]]; then
count=$(( count + 1 ))
if ! is_sd_webui_extension_disabled "${extension_name}"; then
term_sd_echo "[${count}/${sum}] 执行 ${extension_name} 内置插件的依赖安装脚本中"
PYTHONPATH=$py_path term_sd_try term_sd_python "${install_script_path}"
if [[ "$?" == 0 ]]; then
term_sd_echo "[${count}/${sum}] ${extension_name} 内置插件的依赖安装脚本执行成功"
else
term_sd_echo "[${count}/${sum}] ${extension_name} 内置插件的依赖安装脚本执行失败, 这可能会导致 ${extension_name} 内置插件部分功能无法正常使用"
fi
else
term_sd_echo "[${count}/${sum}] ${extension_name} 内置插件已禁用, 不执行该内置插件的依赖安装脚本"
fi
fi
done
fi
}
# 查询 SD WebUI 是否禁用了所有插件
is_sd_webui_disable_all_extension() {
local status
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_sd_webui_disable_all_extension_status.py" \
--config-path "${SD_WEBUI_ROOT_PATH}/config.json" \
)
if [[ "${status}" == "True" ]]; then
return 0
else
return 1
fi
}
# 检查 controlnet_aux
check_controlnet_aux() {
local controlnet_aux_ver
term_sd_echo "检查 controlnet_aux 模块是否已安装"
controlnet_aux_ver=$(term_sd_python "${START_PATH}/term-sd/python_modules/check_controlnet_aux.py")
if [[ "${controlnet_aux_ver}" == "None" ]]; then
term_sd_echo "controlnet_aux 已安装"
else
term_sd_echo "检测到 controlnet_aux 缺失, 尝试安装中"
term_sd_python -m pip uninstall controlnet_aux -y
install_python_package "${controlnet_aux_ver}" --use-pep517 --no-cache-dir
if [[ "$?" == 0 ]]; then
term_sd_echo "controlnet_aux 安装成功"
else
term_sd_echo "controlnet_aux 安装失败, 可能会导致 InvokeAI 启动异常"
fi
fi
}
# 运行环境检测设置
env_check_setting() {
local dialog_arg
local env_check_info
while true; do
if [[ ! -f "${START_PATH}/term-sd/config/disable-env-check.lock" ]]; then
env_check_info="启用"
else
env_check_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "运行环境检测设置" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置运行环境检测设置, 运行环境检查包括: Numpy 版本检测, 依赖完整性检测, 冲突组件检测, PyTorch libomp 问题检测, onnxruntime-gpu 版本检测. 这些检测将找出运行环境中出现的问题并修复, 注意, 禁用后可能会导致 Term-SD 无法发现并修复运行环境中存在的问题, 导致部分功能不可用\n当前运行环境检测: ${env_check_info}\n是否启用运行环境检测 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
rm -f "${START_PATH}/term-sd/config/disable-env-check.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "运行环境检测设置" \
--ok-label "确认" \
--msgbox "启用运行环境检测成功" \
$(get_dialog_size)
;;
2)
touch "${START_PATH}/term-sd/config/disable-env-check.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "运行环境检测设置" \
--ok-label "确认" \
--msgbox "禁用运行环境检测成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
|
2301_81996401/term-sd
|
modules/term_sd_env_check.sh
|
Shell
|
agpl-3.0
| 19,499
|
#!/bin/bash
# 获取当前目录下的所有文件夹
# 使用:
# get_dir_folder_list <路径>
# 执行完成后返回一个全局变量(数组) LOCAL_DIR_LIST
# 使用 ${LOCAL_DIR_LIST[@]} 进行调用
# 在 Bash 版本低于 4 时需要使用 ${LOCAL_DIR_LIST} 进行调用
get_dir_folder_list() {
local i
local path
local file_name
local list
unset LOCAL_DIR_LIST
if [[ -z "$@" ]]; then
path="."
else
path=$@
fi
if term_sd_is_debug; then
if term_sd_is_dir_empty "${path}"; then
term_sd_echo "路径 ${path} 为空"
else
list=$(ls "${path}")
term_sd_echo "路径 ${path} 中存在的文件和文件夹: ${list}"
fi
fi
term_sd_echo "检索当前目录中"
if term_sd_is_bash_ver_lower; then # Bash 4 版本才支持使用数组, 当 Bash 版本低于 4 时使用旧版获取列表方案
LOCAL_DIR_LIST=$(ls -l "${path}" --time-style=+"%Y-%m-%d" | awk '{ print $7 " " $6 }')
else
if ! term_sd_is_dir_empty "${path}"; then
for i in "${path}"/*; do
if [[ -d "${i}" ]]; then # 将文件夹添加到列表里
file_name=${i#${path}/}
LOCAL_DIR_LIST+=("${file_name}" "<---------")
fi
done
fi
fi
}
# 获取当前路径中所有的文件和文件夹
# 使用:
# get_dir_folder_list <路径>
# 执行完成后返回一个全局变量(数组) LOCAL_DIR_LIST
# 使用 ${LOCAL_DIR_LIST[@]} 进行调用
# 在 Bash 版本低于 4 时需要使用 ${LOCAL_DIR_LIST} 进行调用
get_dir_list() {
local i
local path
local file_name
local list
unset LOCAL_DIR_LIST
if [[ -z "$@" ]]; then
path="."
else
path=$@
fi
if term_sd_is_debug; then
if term_sd_is_dir_empty "${path}"; then
term_sd_echo "路径 ${path} 为空"
else
list=$(ls "${path}")
term_sd_echo "路径 ${path} 中存在的文件和文件夹: ${list}"
fi
fi
term_sd_echo "检索当前目录中"
if term_sd_is_bash_ver_lower; then # Bash 4 版本才支持使用数组, 当 Bash 版本低于 4 时使用旧版获取列表方案
LOCAL_DIR_LIST=$(ls -l "${path}" --time-style=+"%Y-%m-%d" | awk '{ print $7 " " $6 }')
else
if ! term_sd_is_dir_empty "${path}"; then
for i in "${path}"/*; do
file_name=${i#${path}/}
LOCAL_DIR_LIST+=("${file_name}" "<---------")
done
fi
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_get_dir_list.sh
|
Shell
|
agpl-3.0
| 2,582
|
#!/bin/bash
# Git 版本切换
# 使用:
# git_ver_switch <仓库路径>
git_ver_switch() {
local dialog_arg
local origin_branch
local ref
local path
local name
local current_commit_hash
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
if is_git_repo "${path}"; then # 检测目录中是否有.git文件夹
name=$(git -C "${path}" remote get-url origin | awk -F '/' '{print $NF}')
name=${name%.git}
term_sd_echo "获取 ${name} 版本信息"
current_commit_hash=$(git -C "${path}" show -s --format="%h %cd" --date=format:"%Y-%m-%d %H:%M:%S")
# 获取当前所在分支
ref=$(git -C "${path}" symbolic-ref --quiet HEAD 2> /dev/null)
if [[ "$?" == 0 ]]; then # 未出现分支游离
origin_branch="origin/${ref#refs/heads/}"
else # 出现分支游离时查询HEAD所指的分支
origin_branch="origin/$(git -C "${path}" branch -a | grep "/HEAD" | awk -F '/' '{print $NF}')"
fi
dialog_arg=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "${name} 切换版本选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择要切换的版本\n当前版本: ${current_commit_hash}" \
$(get_dialog_size_menu) \
"-->返回<--" "<-------------------" \
$(git -C "${path}" log "${origin_branch}" --date=short --pretty=format:"%h %cd" --date=format:"%Y-%m-%d|%H:%M:%S") \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
if [ ! "${dialog_arg}" == "-->返回<--" ]; then
term_sd_echo "切换 ${name} 版本中"
git -C "${path}" reset --recurse-submodules --hard "${dialog_arg}"
term_sd_echo "版本切换完成, ${name} 版本日期: $(git -C "${path}" show -s --format="%ai" ${dialog_arg})"
return 0
else
term_sd_echo "取消 ${name} 版本切换操作"
return 1
fi
else
term_sd_echo "取消 ${name} 版本切换操作"
return 1
fi
else
term_sd_echo "$(basename "$(pwd)") 非 Git 安装, 无法切换版本"
return 10
fi
}
# Git 分支游离恢复
# git_fix_pointer_offset <仓库路径>
git_fix_pointer_offset() {
local repo_main_branch
local path
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
# 当git在子文件夹中找不到.git文件夹时,将会自动在父文件夹中寻找,以此类推,直到找到.git文件夹。用户的安装方式可能是直接下载源码压缩包,导致安装后的文件夹没有.git文件夹,直接执行git会导致不良的后果
if is_git_repo "${path}"; then # 检测目录中是否有.git文件夹
name=$(git -C "${path}" remote get-url origin | awk -F '/' '{print $NF}')
name=${name%.git}
term_sd_echo "修复 ${name} 分支游离状态"
git -C "${path}" remote prune origin # 删除无用分支
git -C "${path}" submodule init # 初始化 Git 子模块
repo_main_branch=$(git -C "${path}" branch -a | grep "/HEAD" | awk -F '/' '{print $NF}') # 查询 HEAD 所指分支
git -C "${path}" checkout ${repo_main_branch} # 切换到主分支
git -C "${path}" reset --recurse-submodules --hard origin/${repo_main_branch} # 回退到远程分支的版本
term_sd_echo "修复 ${name} 完成"
else
term_sd_echo "$(basename "$(pwd)") 非 Git 安装, 无法修复分支游离"
return 10
fi
}
# Git 获取项目信息(用户名, 项目名称)
# 使用 GIT_REPO_USER, GIT_REPO_NAME 全局变量保存仓库的信息
git_get_repository_url_info() {
GIT_REPO_USER=$(echo $@ | awk -F '/' '{print $(NF-1)}') # 从链接获取项目所属的用户名
GIT_REPO_NAME=$(echo $@ | awk -F '/' '{print $NF}') # 从链接获取项目的名称
}
# Git 格式化链接
# 格式链接: https://github.com/term_sd_git_user/term_sd_git_repo
# 使用格式: git_format_repository_url <链接格式> <原链接>
# 使用 git_get_repository_url_info 函数返回的 GIT_REPO_USER, GIT_REPO_NAME 全局变量获取仓库的用户名和仓库名
git_format_repository_url() {
local url_format=$1
local url=$2
git_get_repository_url_info "${url}" # 获取项目用户名和项目名称(得到 GIT_REPO_USER, GIT_REPO_NAME)
url=$(echo ${url_format} | awk '{sub("term_sd_git_user","'$GIT_REPO_USER'") ; sub("term_sd_git_repo","'$GIT_REPO_NAME'")}1') # 生成格式化之后的链接
unset GIT_REPO_USER
unset GIT_REPO_NAME
echo "${url}"
}
# Git 克隆项目(使用格式化链接)
# 使用格式:
# git_clone_repository <--disable-submod> <原链接> <下载路径> <文件夹名称>
git_clone_repository() {
local url # 链接
local path # 下载路径
local name # 要保存的名称
local repo_path
local use_submodules
if [[ "$1" == "--disable-submod" ]]; then
url=$2
path=$3
name=$4
else
use_submodules="--recurse-submodules"
url=$1
path=$2
name=$3
fi
if [[ -z "${path}" ]]; then # 下载路径为空时
path=$(pwd)
name=$(basename "${url}")
repo_path="${path}/${name}"
elif [[ -z "${name}" ]]; then # 要保存的名称为空时
# 去除下载路径中末尾的 / 字符
path=$(awk '{ if (substr($0, length($0), 1) == "/") { print substr($0, 1, length($0) - 1) } else { print $0 } }' <<< ${path})
name=$(basename "${url}")
repo_path="${path}/${name}"
else
# 去除下载路径中末尾的 / 字符
path=$(awk '{ if (substr($0, length($0), 1) == "/") { print substr($0, 1, length($0) - 1) } else { print $0 } }' <<< ${path})
repo_path="${path}/${name}"
fi
url=$(git_format_repository_url "${GITHUB_MIRROR}" "${url}")
if term_sd_is_debug; then
term_sd_echo "下载信息:"
term_sd_echo "url: ${url}"
term_sd_echo "path: ${path}"
term_sd_echo "name: ${name}"
term_sd_echo "repo_path: ${repo_path}"
term_sd_echo "GITHUB_MIRROR: ${GITHUB_MIRROR}"
term_sd_echo "use_submodules: ${use_submodules}"
term_sd_echo "cmd: git clone ${use_submodules} ${url} ${repo_path}"
fi
if [[ ! -d "${repo_path}" ]] || term_sd_is_dir_empty "${repo_path}"; then
term_sd_echo "开始下载 ${name}, 路径: ${repo_path}"
term_sd_try git clone ${use_submodules} "${url}" "${repo_path}"
if [[ "$?" == 0 ]]; then
term_sd_echo "${name} 下载成功"
else
term_sd_echo "${name} 下载失败"
return 1
fi
else
term_sd_echo "${name} 已存在, 路径: ${repo_path}"
fi
}
# Git 远程源替换
# 使用格式: git_repository_remote_revise <链接格式>
git_repository_remote_revise() {
local repo_url
local repo_modify_url
local url_format=$@
local GIT_CONFIG_GLOBAL= # 临时取消 Git 配置, 防止影响远程源的判断
repo_url=$(git remote get-url origin) # 获取远程源链接
repo_modify_url=$(git_format_repository_url "${url_format}" "${repo_url}") # 生成格式化后的链接
if [[ "${repo_url}" == "${repo_modify_url}" ]]; then # 当原链接和修改后的链接相同时不执行替换
return 1
else # 修改远程源
if term_sd_is_debug; then
term_sd_echo "cmd: git remote set-url origin ${repo_modify_url}"
fi
git remote set-url origin "${repo_modify_url}"
return 0
fi
}
# Git 拉取更新
# 当检测到出现分支游离时将自动修复
# 使用:
# git_pull_repository <仓库路径>
git_pull_repository() {
local path
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
if is_git_repo "${path}"; then
git_auto_fix_pointer_offset "${path}" # 检测分支是否游离并修复
git_get_latest_ver "${path}"
else
term_sd_echo "$(basename "${path}") 非 Git 安装, 无法更新"
return 10
fi
}
# Git 拉取更新内容并应用
# 使用:
# git_get_latest_ver <仓库路径>
git_get_latest_ver() {
local commit_hash
local origin_branch
local ref
local use_submodules
local local_commit_hash
local req
local path
local name
local author="origin"
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
name=$(git -C "${path}" remote get-url origin | awk -F '/' '{print $NF}')
if is_git_repo "${path}"; then
if [[ ! -z "$(git -C "${path}" submodule status)" ]]; then # 检测是否有子模块
term_sd_echo "初始化 Git 子模块"
use_submodules="--recurse-submodules"
git -C "${path}" submodule init # 初始化 Git 子模块
fi
term_sd_echo "拉取 ${name} 远端更新内容"
term_sd_try git -C "${path}" fetch ${use_submodules} --all
if [[ "$?" == 0 ]]; then
term_sd_echo "应用 ${name} 远端更新内容"
ref=$(git -C "${path}" symbolic-ref --quiet HEAD 2> /dev/null)
if git_is_repo_on_origin_branch "${path}"; then
origin_branch="${author}/${ref#refs/heads/}"
else
origin_branch="${ref#refs/heads/}"
# 获取分支对应的远程源名称
author=$(git -C "${path}" config --get "branch.${origin_branch}.remote" 2> /dev/null)
if [[ -z "${author}" ]]; then
author="null"
else
origin_branch=$(git -C "${path}" rev-parse --abbrev-ref "${origin_branch}@{upstream}")
fi
fi
commit_hash=$(git -C "${path}" log "${origin_branch}" --max-count 1 --format="%h")
local_commit_hash=$(git -C "${path}" show -s --format="%h")
if term_sd_is_debug; then
term_sd_echo "ref: ${ref}"
term_sd_echo "author: ${author}"
term_sd_echo "commit_hash: ${commit_hash}"
term_sd_echo "local_commit_hash: ${local_commit_hash}"
term_sd_echo "origin_branch: ${origin_branch}"
fi
git -C "${path}" reset ${use_submodules} --hard "${origin_branch}"
req=$?
if [[ "${commit_hash}" == "${local_commit_hash}" ]]; then
term_sd_echo "${name} 已是最新"
else
term_sd_echo "${name} 版本变动: ${local_commit_hash} -> ${commit_hash}"
fi
return ${req}
else
term_sd_echo "拉取 ${name} 远端更新内容失败"
return 1
fi
fi
}
# 展示 Git 分支
# 使用:
# git_branch_display <仓库路径>
# 执行后返回仓库所在分支, Hash 值, 分支游离状态
git_branch_display() {
local ref
local git_commit_hash
local git_pointer_status
local path
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
if is_git_repo "${path}"; then
ref=$(git -C "${path}" symbolic-ref --quiet HEAD 2> /dev/null)
if [[ "$?" == 0 ]]; then
git_commit_hash=$(git -C "${path}" show -s --format="%h %cd" --date=format:"%Y-%m-%d %H:%M:%S")
else
ref=$(git -C "${path}" rev-parse --short HEAD 2> /dev/null)
git_commit_hash=$(git -C "${path}" show -s --format="%cd" --date=format:"%Y-%m-%d %H:%M:%S")
git_pointer_status="(分支游离)"
fi
echo ${ref#refs/heads/} ${git_pointer_status} ${git_commit_hash}
else
echo "非 Git 安装, 无分支"
fi
}
# Git 远程源地址展示
# 使用:
# git_remote_display <仓库路径>
git_remote_display() {
local path
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
if is_git_repo "${path}"; then
echo "$(git -C "${path}" remote get-url origin)"
else
echo "非 Git 安装, 无更新源"
fi
}
# 检测需要克隆的仓库是否已存在本地, 已存在返回 0, 否则返回 1
term_sd_is_git_repository_exist() {
local i
local folder_name=$(basename "$@")
folder_name=${folder_name%.git}
if term_sd_is_debug; then
term_sd_echo "待检测是否存在的仓库: ${folder_name}"
for i in ./*; do
term_sd_echo "当前路径存在仓库: ${i}"
done
fi
for i in ./*; do # 检测本地同名的文件夹
if [[ "$(basename "${i}")" == "${folder_name}" ]] && ! term_sd_is_dir_empty "${folder_name}"; then
return 0
fi
done
return 1
}
# Git 分支游离自动修复
git_auto_fix_pointer_offset() {
local path
local name
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
name=$(git -C "${path}" remote get-url origin | awk -F '/' '{print $NF}')
if ! git -C "${path}" symbolic-ref HEAD &> /dev/null; then
term_sd_echo "检测到 ${name} 出现分支游离, 尝试修复中"
git_fix_pointer_offset "${path}"
fi
}
# 检测是否为 Git 仓库
is_git_repo() {
if [[ -z "$@" ]]; then
if [[ -d ".git" ]] && git rev-parse &> /dev/null; then
return 0
else
return 1
fi
else
if [[ -d "$@/.git" ]] && git -C "$@" rev-parse &> /dev/null; then
return 0
else
return 1
fi
fi
}
# Git 切换仓库分支
# 使用:
# git_switch_branch <切换成的的远程源> <要切换的分支> <--submod>
git_switch_branch() {
local name
local preview_url
local remote_url=$1
local branch=$2
local use_submodules=$3
preview_url=$(GIT_CONFIG_GLOBAL="" git remote get-url origin)
name=$(awk -F '/' '{print $NF}' <<< ${preview_url})
if [[ "$3" == "--submod" ]]; then
use_submod=1
use_submodules="--recurse-submodules"
else
use_submod=0
unset use_submodules
fi
if term_sd_is_debug; then
term_sd_echo "branch: ${branch}"
term_sd_echo "remote_url: ${remote_url}"
term_sd_echo "use_submodules: ${use_submodules}"
fi
term_sd_echo "${name} 远程源替换: ${preview_url} -> ${remote_url}"
git remote set-url origin "${remote_url}" # 替换远程源
# 处理 Git 子模块
if [[ "${use_submod}" == 1 ]]; then
term_sd_echo "更新 ${name} 的 Git 子模块信息"
git submodule update --init --recursive
else
term_sd_echo "禁用 ${name} 的 Git 子模块"
git submodule deinit --all -f
fi
term_sd_echo "拉取远程源更新"
term_sd_try git fetch # 拉取远程源内容
if [[ "$?" == 0 ]]; then
if [[ "${use_submod}" == 1 ]]; then
git submodule deinit --all -f
fi
term_sd_echo "切换分支至 ${branch}"
# 本地分支不存在时创建一个分支
if ! git show-ref --verify --quiet "refs/heads/${branch}"; then
git branch "${branch}"
fi
git checkout "${branch}" --force # 切换分支
term_sd_echo "应用远程源的更新"
if [[ "${use_submod}" == 1 ]]; then
term_sd_echo "更新 ${name} 的 Git 子模块信息"
git reset --hard "origin/${branch}"
git submodule deinit --all -f
term_sd_try git submodule update --init --recursive
fi
git reset ${use_submodules} --hard "origin/${branch}" # 切换到最新的提交内容上
if term_sd_is_debug; then
term_sd_echo "cmd: git fetch ${use_submodules}"
term_sd_echo "cmd: git checkout ${branch} --force"
term_sd_echo "cmd: git reset ${use_submodules} --hard origin/${branch}"
fi
else
term_sd_echo "拉取 ${name} 远程源更新失败, 取消分支切换"
term_sd_echo "尝试回退 ${name} 的更改"
git remote set-url origin "${preview_url}"
if [[ "${use_submod}" == 1 ]]; then
git submodule deinit --all -f
else
git submodule update --init --recursive
fi
term_sd_echo "回退更改完成"
return 1
fi
}
# 移动 Git 子模块的配置文件到主仓库
git_init_submodule() {
local path
local name
if [[ -z "$@" ]]; then
path=$(pwd)
else
path=$@
fi
name=$(git -C "${path}" remote get-url origin | awk -F '/' '{print $NF}')
term_sd_echo "初始化 ${name} 的 Git 子模块"
git -C "${path}" submodule init
term_sd_try git -C "${path}" submodule update
term_sd_try git -C "${path}" reset --hard --recurse-submodules
}
# 检查分支是否在 origin 上
git_is_repo_on_origin_branch() {
git -C "$@" show-ref --verify --quiet "refs/remotes/origin/$(git -C "$@" branch --show-current)"
}
|
2301_81996401/term-sd
|
modules/term_sd_git.sh
|
Shell
|
agpl-3.0
| 16,948
|
#!/bin/bash
# 远程源的种类检测
# 如果是 Github 链接则返回 0, 不是则返回 1
git_remote_url_type_is_github() {
local GIT_CONFIG_GLOBAL= # 临时取消 Git 配置, 防止影响远程源的判断
if [[ ! -z "$(git remote get-url origin | grep github.com)" ]]; then # 检测远程源的原地址是否属于 Github 地址
return 0
else
return 1
fi
}
# 修改远程源(先判断远程源是否符合修改要求)
# 使用格式: git_repo_remote_revise <链接格式>
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量保存替换更新源的结果
git_repo_remote_revise() {
local name
local url_format=$1
name=$(git remote get-url origin | awk -F '/' '{print $NF}') # 获取项目名称
name=${name%.git}
if git_remote_url_type_is_github; then # 判断远程源种类
git_repository_remote_revise "${url_format}" # 执行远程源替换
if [[ "$?" == 0 ]]; then
term_sd_echo "替换 ${name} 更新源为 $(echo ${url_format} | awk '{sub("https://","") ; gsub(/\//," ")}1' | awk '{print $1}') 源"
GIT_REPO_REMOTE_REVISE_MESSAGE="${GIT_REPO_REMOTE_REVISE_MESSAGE} ${name} 更新源替换成功\n"
else
term_sd_echo "${name} 更新源无需替换"
GIT_REPO_REMOTE_REVISE_MESSAGE="${GIT_REPO_REMOTE_REVISE_MESSAGE} ${name} 更新源无需替换\n"
fi
else
term_sd_echo "${name} 更新源非 Github 地址, 不执行替换"
GIT_REPO_REMOTE_REVISE_MESSAGE="${GIT_REPO_REMOTE_REVISE_MESSAGE} ${name} 更新源非 Github 地址, 不执行替换\n"
fi
}
# Git 远程源选择
# 将修改远程源的命令保存在 GIT_REPO_REMOTE_REVISE_CMD 全局变量
git_remote_url_select() {
local dialog_arg
unset GIT_REPO_REMOTE_REVISE_CMD
unset GIT_REPO_REMOTE_REVISE_MESSAGE # 清除运行结果
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "更新源选择界面" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "选择要修改成的更新源\n当前将要修改更新源的 AI 软件: ${TERM_SD_MANAGE_OBJECT}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 官方源 (github.com)" \
"2" "> 镜像源 1 (ghfast.top)" \
"3" "> 镜像源 2 (mirror.ghproxy.com)" \
"4" "> 镜像源 3 (gitclone.com)" \
"5" "> 镜像源 4 (gh-proxy.com)" \
"6" "> 镜像源 5 (ghps.cc)" \
"7" "> 镜像源 6 (gh.idayer.com)" \
"8" "> 镜像源 7 (ghproxy.net)" \
"9" "> 镜像源 8 (gh.api.99988866.xyz)" \
"10" "> 镜像源 9 (ghproxy.1888866.xyz)" \
"11" "> 镜像源 10 (slink.ltd)" \
"12" "> 镜像源 11 (github.boki.moe)" \
"13" "> 镜像源 12 (github.moeyy.xyz)" \
"14" "> 镜像源 13 (gh-proxy.net)" \
"15" "> 镜像源 14 (gh-proxy.ygxz.in)" \
"16" "> 镜像源 15 (wget.la)" \
"17" "> 镜像源 16 (kkgithub.com)" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
2)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://ghfast.top/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
3)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://mirror.ghproxy.com/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
4)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gitclone.com/github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
5)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gh-proxy.com/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
6)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://ghps.cc/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
7)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gh.idayer.com/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
8)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://ghproxy.net/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
9)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gh.api.99988866.xyz/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
10)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://ghproxy.1888866.xyz/github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
11)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://slink.ltd/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
12)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://github.boki.moe/github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
13)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://github.moeyy.xyz/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
14)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gh-proxy.net/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
15)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://gh-proxy.ygxz.in/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
16)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://wget.la/https://github.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
17)
term_sd_print_line "更新源一键替换"
GIT_REPO_REMOTE_REVISE_CMD="git_repo_remote_revise https://kkgithub.com/term_sd_git_user/term_sd_git_repo"
return 0
;;
*)
term_sd_echo "取消替换 $(basename "$(pwd)") 更新源操作"
return 1 # 不执行替换
;;
esac
}
# Git 远程源选择(针对单个插件/自定义节点)
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
git_remote_url_select_single() {
local dialog_arg
local remote_url
unset GIT_REPO_REMOTE_REVISE_MESSAGE # 清除运行结果
if is_git_repo; then # 检测目录中是否有.git文件夹
remote_url=$(git remote get-url origin)
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "更新源选择界面" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "选择要修改成的更新源\n当前更新源: ${remote_url}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 官方源 (github.com)" \
"2" "> 镜像源 1 (ghfast.top)" \
"3" "> 镜像源 2 (mirror.ghproxy.com)" \
"4" "> 镜像源 3 (gitclone.com)" \
"5" "> 镜像源 4 (gh-proxy.com)" \
"6" "> 镜像源 5 (ghps.cc)" \
"7" "> 镜像源 6 (gh.idayer.com)" \
"8" "> 镜像源 7 (ghproxy.net)" \
"9" "> 镜像源 8 (gh.api.99988866.xyz)" \
"10" "> 镜像源 9 (ghproxy.1888866.xyz)" \
"11" "> 镜像源 10 (slink.ltd)" \
"12" "> 镜像源 11 (github.boki.moe)" \
"13" "> 镜像源 12 (github.moeyy.xyz)" \
"14" "> 镜像源 13 (gh-proxy.net)" \
"15" "> 镜像源 14 (gh-proxy.ygxz.in)" \
"16" "> 镜像源 15 (wget.la)" \
"17" "> 镜像源 16 (kkgithub.com)" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
git_repo_remote_revise https://github.com/term_sd_git_user/term_sd_git_repo
;;
2)
git_repo_remote_revise https://ghfast.top/https://github.com/term_sd_git_user/term_sd_git_repo
;;
3)
git_repo_remote_revise https://mirror.ghproxy.com/https://github.com/term_sd_git_user/term_sd_git_repo
;;
4)
git_repo_remote_revise https://gitclone.com/github.com/term_sd_git_user/term_sd_git_repo
;;
5)
git_repo_remote_revise https://gh-proxy.com/https://github.com/term_sd_git_user/term_sd_git_repo
;;
6)
git_repo_remote_revise https://ghps.cc/https://github.com/term_sd_git_user/term_sd_git_repo
;;
7)
git_repo_remote_revise https://gh.idayer.com/https://github.com/term_sd_git_user/term_sd_git_repo
;;
8)
git_repo_remote_revise https://ghproxy.net/https://github.com/term_sd_git_user/term_sd_git_repo
;;
9)
git_repo_remote_revise https://gh.api.99988866.xyz/https://github.com/term_sd_git_user/term_sd_git_repo
;;
10)
git_repo_remote_revise https://ghproxy.1888866.xyz/github.com/term_sd_git_user/term_sd_git_repo
;;
11)
git_repo_remote_revise https://slink.ltd/https://github.com/term_sd_git_user/term_sd_git_repo
;;
12)
git_repo_remote_revise https://github.boki.moe/github.com/term_sd_git_user/term_sd_git_repo
;;
13)
git_repo_remote_revise https://github.moeyy.xyz/https://github.com/term_sd_git_user/term_sd_git_repo
;;
14)
git_repo_remote_revise https://gh-proxy.net/https://github.com/term_sd_git_user/term_sd_git_repo
;;
15)
git_repo_remote_revise https://gh-proxy.ygxz.in/https://github.com/term_sd_git_user/term_sd_git_repo
;;
16)
git_repo_remote_revise https://wget.la/https://github.com/term_sd_git_user/term_sd_git_repo
;;
17)
git_repo_remote_revise https://kkgithub.com/term_sd_git_user/term_sd_git_repo
;;
*)
term_sd_echo "取消替换更新源操作"
return 0
;;
esac
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
else
term_sd_echo "$(basename "$(pwd)") 非 Git 安装, 无法切换更新源"
return 10
fi
}
# SD WebUI 远程源替换
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
sd_webui_remote_revise() {
local i
if git_remote_url_select; then # 选择更新源
term_sd_echo "开始替换 Stable-Diffusion-WebUI 更新源"
# 执行替换功能
# 主体部分
${GIT_REPO_REMOTE_REVISE_CMD}
# 组件部分
for i in "${SD_WEBUI_ROOT_PATH}"/repositories/*; do
if is_git_repo "${i}"; then
cd "${i}"
${GIT_REPO_REMOTE_REVISE_CMD}
cd - &> /dev/null
fi
done
# 插件部分
for i in "${SD_WEBUI_ROOT_PATH}"/extensions/*; do
if is_git_repo "${i}"; then
cd "${i}"
${GIT_REPO_REMOTE_REVISE_CMD}
cd - &> /dev/null
fi
done
term_sd_echo "Stable-Duffusion-WebUI 更新源替换结束"
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Stable-Duffusion-WebUI 更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
unset GIT_REPO_REMOTE_REVISE_CMD
fi
}
# ComfyUI 远程源替换功能
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
comfyui_remote_revise() {
local i
if git_remote_url_select; then # 选择更新源
term_sd_echo "开始替换 ComfyUI 更新源"
# 执行替换功能
# 主体部分
${GIT_REPO_REMOTE_REVISE_CMD}
# 插件
for i in "$COMFYUI_ROOT_PATH"/web/extensions/*; do
if is_git_repo "${i}"; then
cd "${i}"
${GIT_REPO_REMOTE_REVISE_CMD}
cd - &> /dev/null
fi
done
# 自定义节点
for i in "$COMFYUI_ROOT_PATH"/custom_nodes/*; do
if is_git_repo "${i}"; then
cd "${i}"
${GIT_REPO_REMOTE_REVISE_CMD}
cd - &> /dev/null
fi
done
term_sd_echo "ComfyUI 更新源替换结束"
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "ComfyUI 更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
unset GIT_REPO_REMOTE_REVISE_CMD
fi
}
# lora-scripts 远程源替换功能
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
lora_scripts_remote_revise() {
if git_remote_url_select; then # 选择更新源
term_sd_echo "开始替换 lora-scripts 更新源"
${GIT_REPO_REMOTE_REVISE_CMD}
cd "$LORA_SCRIPTS_ROOT_PATH"/frontend
${GIT_REPO_REMOTE_REVISE_CMD}
cd "$LORA_SCRIPTS_ROOT_PATH"/mikazuki/dataset-tag-editor
${GIT_REPO_REMOTE_REVISE_CMD}
term_sd_echo "lora-scripts 更新源替换结束"
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "lora-scripts 更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
unset GIT_REPO_REMOTE_REVISE_CMD
fi
}
# Fooocus 切换更新源功能
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
fooocus_remote_revise() {
if git_remote_url_select; then # 选择更新源
term_sd_echo "开始替换 Fooocus 更新源"
${GIT_REPO_REMOTE_REVISE_CMD}
term_sd_echo "Fooocus 更新源替换结束"
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Fooocus 更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
unset GIT_REPO_REMOTE_REVISE_CMD
fi
}
# kohya_ss 切换更新源功能
# 使用 GIT_REPO_REMOTE_REVISE_MESSAGE 全局变量显示替换更新源的结果
kohya_ss_remote_revise() {
if git_remote_url_select; then # 选择更新源
term_sd_echo "开始替换 kohya_ss 更新源"
${GIT_REPO_REMOTE_REVISE_CMD}
term_sd_echo "kohya_ss 更新源替换结束"
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "kohya_ss 更新源替换结果" \
--ok-label "确认" \
--msgbox "当前更新源替换情况列表\n${TERM_SD_DELIMITER}\n$GIT_REPO_REMOTE_REVISE_MESSAGE${TERM_SD_DELIMITER}" \
$(get_dialog_size)
unset GIT_REPO_REMOTE_REVISE_MESSAGE
unset GIT_REPO_REMOTE_REVISE_CMD
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_git_repo_change.sh
|
Shell
|
agpl-3.0
| 17,370
|
#!/bin/bash
# Git 全局镜像源设置
# Git 镜像源配置保存在 <Start Path>/term-sd/config/set-global-github-mirror.conf
# Git 配置保存在 <Start Path>/term-sd/config/.gitconfig
# 动态 Git 镜像源配置保存在 <Start Path>/term-sd/config/set-dynamic-global-github-mirror.lock
# 设置 GIT_CONFIG_GLOBAL 环境变量指定 Git 使用的配置文件
# 使用 TERM_SD_GITHUB_MIRROR 全局变量获取镜像源地址
term_sd_git_global_mirror_setting() {
local dialog_arg
local github_mirror_status
local dynamic_github_mirror_status
while true; do
if [[ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]]; then
github_mirror_status=$(cat "${START_PATH}/term-sd/config/set-global-github-mirror.conf" | awk '{sub("/https://github.com","") ; sub("/github.com","")}1')
else
github_mirror_status="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
dynamic_github_mirror_status="启用"
else
dynamic_github_mirror_status="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Github 镜像源选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置 Github 镜像源, 加速国内下载 Github 文件的速度\n当前 Github 镜像源配置: ${github_mirror_status}\n动态 Github 镜像源: ${dynamic_github_mirror_status}\n请选择对 Github 镜像源的操作" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置 Github 镜像源" \
"2" "> 删除 Github 镜像源配置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_set_github_mirror
if [[ "$?" == 0 ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Github 镜像源选项" \
--ok-label "确认" \
--msgbox "设置 Github 镜像源代理完成\n当前使用的 Github 镜像源: $(echo ${TERM_SD_GITHUB_MIRROR} | awk '{sub("/https://github.com","") sub("/github.com","")}1')" \
$(get_dialog_size)
else
term_sd_echo "取消设置 Github 镜像源"
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Github 镜像源选项" \
--yes-label "是" --no-label "否" \
--yesno "是否删除 Github 镜像源配置 ?" \
$(get_dialog_size)); then
term_sd_echo "删除 Github 镜像源"
rm -f "${START_PATH}"/term-sd/config/.gitconfig
rm -f "${START_PATH}"/term-sd/config/set-global-github-mirror.conf
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-github-mirror.lock
unset GIT_CONFIG_GLOBAL
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Github 镜像源选项" \
--ok-label "确认" \
--msgbox "删除 Github 镜像源配置完成" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
unset TERM_SD_GITHUB_MIRROR
}
# Github 镜像源选择
# 使用 TERM_SD_GITHUB_MIRROR 全局变量保存选择的镜像源
term_sd_set_github_mirror() {
local dialog_arg
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Github 镜像源选项" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "选择要使用的 Github 镜像源, 推荐设置动态 Github 镜像源" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置动态 Github 镜像源" \
"2" "> 自动选择 Github 镜像源" \
"3" "> 镜像源 1 (ghfast.top)" \
"4" "> 镜像源 2 (mirror.ghproxy.com)" \
"5" "> 镜像源 3 (gitclone.com)" \
"6" "> 镜像源 4 (gh-proxy.com)" \
"7" "> 镜像源 5 (ghps.cc)" \
"8" "> 镜像源 6 (gh.idayer.com)" \
"9" "> 镜像源 7 (ghproxy.net)" \
"10" "> 镜像源 8 (gh.api.99988866.xyz)" \
"11" "> 镜像源 9 (ghproxy.1888866.xyz)" \
"12" "> 镜像源 10 (slink.ltd)" \
"13" "> 镜像源 11 (github.boki.moe)" \
"14" "> 镜像源 12 (github.moeyy.xyz)" \
"15" "> 镜像源 13 (gh-proxy.net)" \
"16" "> 镜像源 14 (gh-proxy.ygxz.in)" \
"17" "> 镜像源 15 (wget.la)" \
"18" "> 镜像源 16 (kkgithub.com)" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_echo "启用 Github 动态镜像源中"
touch "${START_PATH}"/term-sd/config/set-dynamic-global-github-mirror.lock
term_sd_auto_setup_github_mirror
if [ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]; then
TERM_SD_GITHUB_MIRROR=$(cat "${START_PATH}/term-sd/config/set-global-github-mirror.conf")
else
TERM_SD_GITHUB_MIRROR="无"
fi
term_sd_echo "启用 Github 动态镜像源完成"
return 0
;;
2)
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-github-mirror.lock
term_sd_echo "测试可用 Github 镜像源"
term_sd_test_avaliable_github_mirror
term_sd_echo "设置 Github 镜像源"
export GIT_CONFIG_GLOBAL="${START_PATH}/term-sd/config/.gitconfig"
rm -f "${START_PATH}"/term-sd/config/.gitconfig
set_normal_git_config
git config --global url."${TERM_SD_GITHUB_MIRROR}".insteadOf "https://github.com"
echo "${TERM_SD_GITHUB_MIRROR}" > "${START_PATH}"/term-sd/config/set-global-github-mirror.conf
return 0
;;
3)
process_github_mirror "https://ghfast.top/https://github.com"
return 0
;;
4)
process_github_mirror "https://mirror.ghproxy.com/https://github.com"
return 0
;;
5)
process_github_mirror "https://gitclone.com/github.com"
return 0
;;
6)
process_github_mirror "https://gh-proxy.com/https://github.com"
return 0
;;
7)
process_github_mirror "https://ghps.cc/https://github.com"
return 0
;;
8)
process_github_mirror "https://gh.idayer.com/https://github.com"
return 0
;;
9)
process_github_mirror "https://ghproxy.net/https://github.com"
return 0
;;
10)
process_github_mirror "https://gh.api.99988866.xyz/https://github.com"
return 0
;;
11)
process_github_mirror "https://ghproxy.1888866.xyz/github.com"
return 0
;;
12)
process_github_mirror "https://slink.ltd/https://github.com"
return 0
;;
13)
process_github_mirror "https://github.boki.moe/github.com"
return 0
;;
14)
process_github_mirror "https://github.moeyy.xyz/https://github.com"
return 0
;;
15)
process_github_mirror "https://gh-proxy.net/https://github.com"
return 0
;;
16)
process_github_mirror "https://gh-proxy.ygxz.in/https://github.com"
return 0
;;
17)
process_github_mirror "https://wget.la/https://github.com"
return 0
;;
18)
process_github_mirror "https://kkgithub.com"
return 0
;;
*)
return 1
;;
esac
}
# 配置 Github 镜像源
# 使用:
# process_github_mirror <Github 镜像源地址>
# 运行后设置 TERM_SD_GITHUB_MIRROR 全局变量保存 Github 镜像源地址
process_github_mirror() {
TERM_SD_GITHUB_MIRROR=$@
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-github-mirror.lock
term_sd_echo "设置 Github 镜像源"
export GIT_CONFIG_GLOBAL="${START_PATH}/term-sd/config/.gitconfig"
rm -f "${START_PATH}"/term-sd/config/.gitconfig
set_normal_git_config
git config --global url."${TERM_SD_GITHUB_MIRROR}".insteadOf "https://github.com"
echo "${TERM_SD_GITHUB_MIRROR}" > "${START_PATH}"/term-sd/config/set-global-github-mirror.conf
}
# 测试可用的 Github 镜像源
# 将选择的镜像 Github 镜像源保存在 TERM_SD_GITHUB_MIRROR 全局变量
term_sd_test_avaliable_github_mirror() {
# 镜像源列表
local mirror_list=$GITHUB_MIRROR_LIST
local git_req
local HTTP_PROXY
local HTTPS_PROXY
local i
HTTP_PROXY= # 临时清除配置好的代理, 防止干扰测试
HTTPS_PROXY=
rm -rf "${START_PATH}/term-sd/task/github_mirror_test" &> /dev/null
for i in ${mirror_list}; do
git clone $(git_format_repository_url ${i} https://github.com/licyk/empty) "${START_PATH}/term-sd/task/github_mirror_test" --depth=1 &> /dev/null # 测试镜像源是否正常连接
git_req=$?
rm -rf "${START_PATH}/term-sd/task/github_mirror_test" &> /dev/null
if [[ "${git_req}" == 0 ]]; then
TERM_SD_GITHUB_MIRROR=$(awk '{sub("/term_sd_git_user/term_sd_git_repo","")}1' <<< ${i})
return
fi
done
TERM_SD_GITHUB_MIRROR="https://ghfast.top/https://github.com"
}
|
2301_81996401/term-sd
|
modules/term_sd_github_mirror.sh
|
Shell
|
agpl-3.0
| 9,958
|
#!/bin/bash
# HuggingFace 全局镜像源设定
# 使用 HF_ENDPOINT 环境变量设置 HuggingFace Api 使用的镜像源
# 使用 TERM_SD_HUGGINGFACE_MIRROR 全局变量获取使用的 HuggingFace 镜像源
term_sd_huggingface_global_mirror_setting() {
local dialog_arg
local huggingface_mirror_status
local dynamic_huggingface_mirror_status
while true; do
if [[ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]]; then
huggingface_mirror_status=$HF_ENDPOINT
else
huggingface_mirror_status="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
dynamic_huggingface_mirror_status="启用"
else
dynamic_huggingface_mirror_status="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "HuggingFace 镜像源选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置 HuggingFace 镜像源, 加速国内下载 HuggingFace 文件的速度\n当前 HuggingFace 镜像源配置: ${huggingface_mirror_status}\n动态 HuggingFace 镜像源: ${dynamic_huggingface_mirror_status}\n请选择对 HuggingFace 镜像源的操作" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置 HuggingFace 镜像源" \
"2" "> 删除 HuggingFace 镜像源配置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_set_huggingface_mirror
if [[ "$?" == 0 ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "HuggingFace 镜像源选项" \
--ok-label "确认" \
--msgbox "设置 HuggingFace 镜像源代理完成\n当前使用的 HuggingFace 镜像源: ${TERM_SD_HUGGINGFACE_MIRROR}" \
$(get_dialog_size)
else
term_sd_echo "取消设置 HuggingFace 镜像源"
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "HuggingFace 镜像源选项" \
--yes-label "是" --no-label "否" \
--yesno "是否删除 HuggingFace 镜像源配置 ?" \
$(get_dialog_size)); then
term_sd_echo "删除 HuggingFace 镜像源"
rm -f "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
unset HF_ENDPOINT
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "HuggingFace 镜像源选项" \
--ok-label "确认" \
--msgbox "删除 HuggingFace 镜像源配置完成" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
unset TERM_SD_HUGGINGFACE_MIRROR
}
# HuggingFace 镜像源选择
# 使用 TERM_SD_HUGGINGFACE_MIRROR 全局变量保存选择的 HuggingFace 镜像源
term_sd_set_huggingface_mirror() {
local dialog_arg
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "HuggingFace 镜像源选项" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "选择要使用的 HuggingFace 镜像源, 推荐设置动态 HuggingFace 镜像源" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置动态 HuggingFace 镜像源" \
"2" "> 自动选择 HuggingFace 镜像源" \
"3" "> HuggingFace 镜像源1 (hf-mirror.com)" \
"4" "> HuggingFace 镜像源2 (huggingface.sukaka.top)" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_echo "启用动态 HuggingFace 镜像源中"
touch "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
term_sd_auto_setup_huggingface_mirror
if [ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]; then
TERM_SD_HUGGINGFACE_MIRROR=$(cat "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf")
else
TERM_SD_HUGGINGFACE_MIRROR="无"
fi
term_sd_echo "启用动态 HuggingFace 镜像源完成"
return 0
;;
2)
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
term_sd_echo "测试可用 HuggingFace 镜像源"
term_sd_test_avaliable_huggingface_mirror
echo "$TERM_SD_HUGGINGFACE_MIRROR" > "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
export HF_ENDPOINT=$TERM_SD_HUGGINGFACE_MIRROR
return 0
;;
3)
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
TERM_SD_HUGGINGFACE_MIRROR="https://hf-mirror.com"
echo "$TERM_SD_HUGGINGFACE_MIRROR" > "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
export HF_ENDPOINT=$TERM_SD_HUGGINGFACE_MIRROR
return 0
;;
4)
rm -f "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
TERM_SD_HUGGINGFACE_MIRROR="https://huggingface.sukaka.top"
echo "$TERM_SD_HUGGINGFACE_MIRROR" > "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
export HF_ENDPOINT=$TERM_SD_HUGGINGFACE_MIRROR
return 0
;;
*)
return 1
;;
esac
}
# 测试可用的 HuggingFace 镜像源
# 使用 TERM_SD_HUGGINGFACE_MIRROR 全局变量保存测试出来的 HuggingFace 镜像源
term_sd_test_avaliable_huggingface_mirror() {
local mirror_list=$HUGGINGFACE_MIRROR_LIST
local req
local i
local HTTP_PROXY
local HTTPS_PROXY
HTTP_PROXY= # 临时清除配置好的代理,防止干扰测试
HTTPS_PROXY=
for i in ${mirror_list} ;do
curl ${i}/licyk/sd-model/resolve/main/README.md -o /dev/null --connect-timeout 10 --silent
if [[ "$?" == 0 ]]; then
TERM_SD_HUGGINGFACE_MIRROR=$i
return
fi
done
TERM_SD_HUGGINGFACE_MIRROR="https://hf-mirror.com"
}
|
2301_81996401/term-sd
|
modules/term_sd_huggingface_mirror.sh
|
Shell
|
agpl-3.0
| 6,661
|
#!/bin/bash
# 启动 AI 软件
# 使用 TERM_SD_MANAGE_OBJECT 全局变量判断要启动的 AI 软件
# 根据对应的 AI 软件读取对应的启动配置文件
# 使用的配置文件:
# A1111 SD WebUI: <Start Path>/term-sd/config/sd-webui-launch.conf
# Vlad SD WebUI: <Start Path>/term-sd/config/vlad-sd-webui-launch.conf
# SD WebUI DirectML: <Start Path>/term-sd/config/sd-webui-directml-launch.conf
# SD WebUI Forge: <Start Path>/term-sd/config/sd-webui-forge-launch.conf
# SD WebUI reForge: <Start Path>/term-sd/config/sd-webui-reforge-launch.conf
# SD WebUI Forge Classic: <Start Path>/term-sd/config/sd-webui-forge-classic-launch.conf
# ComfyUI: <Start Path>/term-sd/config/comfyui-launch.conf
# InvokeAI: <Start Path>/term-sd/config/invokeai-launch.conf
# Fooocus: <Start Path>/term-sd/config/fooocus-launch.conf
# lora-scripts: <Start Path>/term-sd/config/lora-scripts-launch.conf
# kohya_ss: <Start Path>/term-sd/config/kohya_ss-launch.conf
# 读取 <Start Path>/term-sd/config/set-global-github-mirror.conf 配置文件用于设置 SD WebUI 的插件列表的镜像源
# 使用 WEBUI_EXTENSIONS_INDEX 环境变量进行设置
# 读取 <Start Path>/term-sd/config/set-global-huggingface-mirror.conf 配置文件用于设置 Fooocus 的 HuggingFace 镜像源
# 使用 --hf-mirror <hf_mirror> 启动参数进行设置
term_sd_launch() {
local launch_sd_config
local use_mirror_for_sd_webui=0
local use_mirror_for_sd_webui_state=1
local use_cuda_malloc=0
local sd_webui_extension_list_url
local github_mirror_url
local i
local ignore_github_mirror
local hf_mirror_for_fooocus
local is_sdnext=0
local github_mirror
local cuda_memory_alloc_config
local launch_args
local current
local in_quote
local quote_char
local launch_args_string
local char
local sd_webui_requirement_file
term_sd_print_line "${TERM_SD_MANAGE_OBJECT} 启动"
term_sd_echo "提示: 可以按下 Ctrl + C 键终止 AI 软件的运行"
case "${TERM_SD_MANAGE_OBJECT}" in
InvokeAI)
;;
*)
enter_venv
;;
esac
case "${TERM_SD_MANAGE_OBJECT}" in
stable-diffusion-webui)
case "$(git remote get-url origin | awk -F '/' '{print $NF}')" in # 分支判断
stable-diffusion-webui|stable-diffusion-webui.git)
launch_sd_config="sd-webui-launch.conf"
;;
automatic|automatic.git)
launch_sd_config="vlad-sd-webui-launch.conf"
is_sdnext=1
;;
stable-diffusion-webui-directml|stable-diffusion-webui-directml.git)
launch_sd_config="sd-webui-directml-launch.conf"
;;
stable-diffusion-webui-forge|stable-diffusion-webui-forge.git)
launch_sd_config="sd-webui-forge-launch.conf"
;;
stable-diffusion-webui-reForge|stable-diffusion-webui-reForge.git)
launch_sd_config="sd-webui-reforge-launch.conf"
;;
sd-webui-forge-classic|sd-webui-forge-classic.git)
launch_sd_config="sd-webui-forge-classic-launch.conf"
;;
*)
launch_sd_config="sd-webui-launch.conf"
;;
esac
if [[ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]]; then # 检测是否设置了github全局镜像源
ignore_github_mirror="gitclone.com"
# 判断是否为可使用的镜像源
for i in ${ignore_github_mirror}; do
if [ ! -z "$(cat "${START_PATH}"/term-sd/config/set-global-github-mirror.conf | grep ${i})" ]; then
use_mirror_for_sd_webui_state=0
fi
done
if [[ "${use_mirror_for_sd_webui_state}" == 1 ]]; then
use_mirror_for_sd_webui=1
github_mirror="$(cat "${START_PATH}"/term-sd/config/set-global-github-mirror.conf)//term_sd_git_user/term_sd_git_repo"
fi
fi
# 为sd webui的插件列表设置镜像源
if [[ "${use_mirror_for_sd_webui}" == 1 ]]; then
term_sd_echo "检测到启用了 Github 镜像源, 为 Stable Diffusion WebUI 可下载的插件列表设置镜像源"
github_mirror_url=$(cat "${START_PATH}"/term-sd/config/set-global-github-mirror.conf | awk '{sub("github.com","raw.githubusercontent.com")}1')
if [[ "${is_sdnext}" == 0 ]]; then
export WEBUI_EXTENSIONS_INDEX="${github_mirror_url}/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json"
fi
export CLIP_PACKAGE="git+$(git_format_repository_url "${github_mirror}" https://github.com/openai/CLIP)"
fi
# 为 ControlNet 插件的依赖安装设置镜像源
is_windows_platform && export INSIGHTFACE_WHEEL="insightface"
export DEPTH_ANYTHING_WHEEL="depth_anything"
export HANDREFINER_WHEEL="handrefinerportable"
export DEPTH_ANYTHING_V2_WHEEL="depth_anything_v2"
export DSINE_WHEEL="dsine"
;;
ComfyUI)
launch_sd_config="comfyui-launch.conf"
;;
InvokeAI)
launch_sd_config="invokeai-launch.conf"
;;
Fooocus)
launch_sd_config="fooocus-launch.conf"
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-language zh" &> /dev/null; then # 添加中文配置
set_fooocus_lang_config
fi
if cat "${START_PATH}"/term-sd/config/${launch_sd_config} | grep "\-\-preset term_sd" &> /dev/null; then # 添加 Term-SD 风格的预设
set_fooocus_preset
fi
if [[ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]]; then
term_sd_echo "检测到启用了 HuggingFace 镜像源, 为 Fooocus 设置 HuggingFace 镜像源"
hf_mirror_for_fooocus="--hf-mirror ${HF_ENDPOINT}"
fi
;;
lora-scripts)
launch_sd_config="lora-scripts-launch.conf"
;;
kohya_ss)
launch_sd_config="kohya_ss-launch.conf"
;;
esac
if [[ -f "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock" ]]; then
term_sd_echo "检查显卡是否为 Nvidia 显卡"
cuda_memory_alloc_config=$(get_pytorch_cuda_memory_conf)
case "${cuda_memory_alloc_config}" in
cuda_malloc)
use_cuda_malloc=1
term_sd_echo "设置 CUDA 内存分配器为 CUDA 内置异步分配器"
export PYTORCH_CUDA_ALLOC_CONF="backend:cudaMallocAsync"
;;
pytorch_malloc)
use_cuda_malloc=1
term_sd_echo "设置 CUDA 内存分配器为 PyTorch 原生分配器"
export PYTORCH_CUDA_ALLOC_CONF="garbage_collection_threshold:0.9,max_split_size_mb:512"
;;
*)
term_sd_echo "显卡非 Nvidia 显卡, 无法设置 CUDA 内存分配器"
;;
esac
fi
# 启动参数处理
if term_sd_is_bash_ver_lower; then
launch_args=$(cat "${START_PATH}/term-sd/config/${launch_sd_config}")
else
launch_args_string=$(cat "${START_PATH}/term-sd/config/${launch_sd_config}")
# eval 非安全解析
# eval "launch_args=($launch_args_string)"
# 手动解析
for (( i=0; i<${#launch_args_string}; i++ )); do
char="${launch_args_string:$i:1}"
term_sd_is_debug && printf "位置 %2d: 字符 [%s] | 引号状态 %d | 当前缓冲 [%s]\n" $i "$char" $in_quote "$current"
# 处理引号逻辑
if [[ "$char" == \" || "$char" == "'" ]]; then
if (( in_quote )); then
if [[ "$char" == "$quote_char" ]]; then # 结束引号
in_quote=0
quote_char=""
launch_args+=("$current") # 保存引号内内容
current=""
else # 其他引号字符作为普通字符
current+="$char"
fi
else # 开始引号
if [[ -n "$current" ]]; then # 保存引号前的内容
launch_args+=("$current")
current=""
fi
in_quote=1
quote_char="$char"
fi
# 处理空格逻辑
elif [[ "$char" == " " ]]; then
if (( in_quote )); then # 引号内空格保留
current+="$char"
else # 非引号空格作为分隔符
if [[ -n "$current" ]]; then
launch_args+=("$current")
current=""
fi
fi
else # 普通字符累积
current+="$char"
fi
done
# 处理最后未完成的缓存
[[ -n "$current" ]] && launch_args+=("$current")
fi
if term_sd_is_debug; then
term_sd_print_line
echo "当前配置:"
echo "launch_sd_config: ${launch_sd_config}"
term_sd_is_bash_ver_lower && echo "launch_args: ${launch_args}" || echo "launch_args: ${launch_args[@]}"
echo "github_mirror: ${github_mirror}"
echo "WEBUI_EXTENSIONS_INDEX: ${WEBUI_EXTENSIONS_INDEX}"
echo "CLIP_PACKAGE: ${CLIP_PACKAGE}"
echo "INSIGHTFACE_WHEEL: ${INSIGHTFACE_WHEEL}"
echo "DEPTH_ANYTHING_WHEEL: ${DEPTH_ANYTHING_WHEEL}"
echo "DEPTH_ANYTHING_V2_WHEEL: ${DEPTH_ANYTHING_V2_WHEEL}"
echo "DSINE_WHEEL: ${DSINE_WHEEL}"
echo "HANDREFINER_WHEEL: ${HANDREFINER_WHEEL}"
echo "PYTORCH_CUDA_ALLOC_CONF: ${PYTORCH_CUDA_ALLOC_CONF}"
term_sd_print_line
echo "环境变量:"
echo "ENV:"
env 2> /dev/null
fi
case "${TERM_SD_MANAGE_OBJECT}" in
InvokeAI)
if [[ ! -f "${START_PATH}/term-sd/config/disable-env-check.lock" ]]; then
term_sd_echo "检测 ${TERM_SD_MANAGE_OBJECT} 运行环境中"
fix_pytorch
check_onnxruntime_gpu_ver
# check_controlnet_aux
fallback_numpy_version
term_sd_echo "结束运行环境检测, 启动 ${TERM_SD_MANAGE_OBJECT} 中"
fi
term_sd_print_line
if term_sd_is_bash_ver_lower; then
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
launch_invokeai_web ${launch_args}
else
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
launch_invokeai_web "${launch_args[@]}"
fi
[[ ! "$?" == 0 ]] && term_sd_echo "${TERM_SD_MANAGE_OBJECT} 退出状态异常"
;;
*)
if [[ ! -f "${START_PATH}/term-sd/config/disable-env-check.lock" ]]; then
term_sd_echo "检测 ${TERM_SD_MANAGE_OBJECT} 运行环境中"
case "${TERM_SD_MANAGE_OBJECT}" in
stable-diffusion-webui)
if [[ -f "${SD_WEBUI_ROOT_PATH}/requirements_versions.txt" ]]; then
sd_webui_requirement_file="${SD_WEBUI_ROOT_PATH}/requirements_versions.txt"
elif [[ -f "${SD_WEBUI_ROOT_PATH}/requirements.txt" ]]; then
sd_webui_requirement_file="${SD_WEBUI_ROOT_PATH}/requirements.txt"
else
sd_webui_requirement_file="${SD_WEBUI_ROOT_PATH}/requirements_versions.txt"
fi
validate_requirements "${sd_webui_requirement_file}"
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
check_sd_webui_extension_requirement "${launch_sd_config}"
check_onnxruntime_gpu_ver
;;
ComfyUI)
validate_requirements "${COMFYUI_ROOT_PATH}/requirements.txt"
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
check_comfyui_env
check_onnxruntime_gpu_ver
;;
Fooocus)
validate_requirements "${FOOOCUS_ROOT_PATH}/requirements_versions.txt"
check_onnxruntime_gpu_ver
;;
lora-scripts)
validate_requirements "${LORA_SCRIPTS_ROOT_PATH}/requirements.txt"
check_onnxruntime_gpu_ver force_check
;;
kohya_ss)
validate_requirements "${KOHYA_SS_ROOT_PATH}/requirements.txt"
check_onnxruntime_gpu_ver force_check
;;
esac
fix_pytorch
fallback_numpy_version
term_sd_echo "结束运行环境检测, 启动 ${TERM_SD_MANAGE_OBJECT} 中"
fi
term_sd_print_line
if term_sd_is_bash_ver_lower; then
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
term_sd_python ${launch_args} ${hf_mirror_for_fooocus}
else
PIP_FIND_LINKS="${PIP_FIND_LINKS} ${TERM_SD_PYPI_MIRROR}" \
term_sd_python "${launch_args[@]}" ${hf_mirror_for_fooocus}
fi
[[ ! "$?" == 0 ]] && term_sd_echo "${TERM_SD_MANAGE_OBJECT} 退出状态异常"
;;
esac
if [[ "${use_mirror_for_sd_webui}" == 1 ]]; then # 取消 SD WebUI 的插件列表镜像源
unset WEBUI_EXTENSIONS_INDEX
unset CLIP_PACKAGE
fi
if [[ "${use_cuda_malloc}" == 1 ]];then
unset PYTORCH_CUDA_ALLOC_CONF
fi
unset INSIGHTFACE_WHEEL
unset DEPTH_ANYTHING_WHEEL
unset DEPTH_ANYTHING_V2_WHEEL
unset DSINE_WHEEL
unset HANDREFINER_WHEEL
case "${TERM_SD_MANAGE_OBJECT}" in
InvokeAI)
;;
*)
exit_venv
;;
esac
term_sd_pause
}
# Aria2 下载工具
# 使用格式: aria2_download <下载链接> <下载路径> <文件名>
# 使用 ARIA2_MULTI_THREAD 全局变量设置 Aria2 的下载线程数
aria2_download() {
local url=$1 # 链接
local path=$2 # 下载路径
local name=$3 # 要保存的名称
local aria2_tmp_path # Aria2 缓存文件
local file_path # 下载到本地的文件
if [[ -z "${path}" ]]; then # 下载路径为空时
path=$(pwd)
name=$(basename "${url}")
elif [[ -z "${name}" ]]; then # 要保存的名称为空时
# 去除下载路径中末尾的 / 字符
path=$(awk '{ if (substr($0, length($0), 1) == "/") { print substr($0, 1, length($0) - 1) } else { print $0 } }' <<< ${path})
name=$(basename "${url}")
else
# 去除下载路径中末尾的 / 字符
path=$(awk '{ if (substr($0, length($0), 1) == "/") { print substr($0, 1, length($0) - 1) } else { print $0 } }' <<< ${path})
fi
aria2_tmp_path="${path}/${name}.aria2"
file_path="${path}/${name}"
if term_sd_is_debug; then
term_sd_echo "url: ${url}"
term_sd_echo "name: ${name}"
term_sd_echo "path: ${path}"
term_sd_echo "aria2_tmp_path: ${aria2_tmp_path}"
term_sd_echo "file_path: ${file_path}"
term_sd_echo "ARIA2_MULTI_THREAD: ${ARIA2_MULTI_THREAD}"
term_sd_echo "cmd: aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x ${ARIA2_MULTI_THREAD} -k 1M ${url} -d ${path} -o ${name}"
fi
if [[ ! -f "${file_path}" ]]; then
term_sd_echo "下载 ${name} 中, 路径: ${file_path}"
term_sd_try aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x "${ARIA2_MULTI_THREAD}" -k 1M "${url}" -d "${path}" -o "${name}"
if [[ "$?" == 0 ]]; then
term_sd_echo "${name} 下载成功"
else
term_sd_echo "${name} 下载失败"
return 1
fi
else
if [[ -f "${aria2_tmp_path}" ]]; then
term_sd_echo "恢复下载 ${name} 中, 路径: ${file_path}"
term_sd_try aria2c --file-allocation=none --summary-interval=0 --console-log-level=error -s 64 -c -x "${ARIA2_MULTI_THREAD}" -k 1M "${url}" -d "${path}" -o "${name}"
if [[ "$?" == 0 ]]; then
term_sd_echo "${name} 下载成功"
else
term_sd_echo "${name} 下载失败"
return 1
fi
else
term_sd_echo "${name} 文件已存在, 路径: ${file_path}"
fi
fi
}
# 显示版本信息
term_sd_version() {
local platform_info
local term_sd_ver
local python_ver
local python_major_version
local python_minor_version
local pip_ver
local aria2_ver
local git_ver
local dialog_ver
local curl_ver
term_sd_echo "统计版本信息中"
platform_info=$(is_windows_platform && echo Windows || uname -o)
term_sd_ver="${TERM_SD_VER} - $(git -C term-sd show -s --format="%cd" --date=format:"%Y-%m-%d %H:%M:%S")"
python_ver=$(term_sd_python --version | awk 'NR==1 {print $2}')
python_major_version=$(echo ${python_ver} | awk -F '.' '{print $1}')
python_minor_version=$(echo ${python_ver} | awk -F '.' '{print $2}')
if (( python_major_version == 3 )); then
if (( python_minor_version >= 9 )) && (( python_minor_version <= 11 )); then
true
else
python_ver="${python_ver} (版本不兼容!)"
fi
else
python_ver="${python_ver} (版本不兼容!)"
fi
pip_ver=$(term_sd_pip --version | awk 'NR==1{print $2}')
aria2_ver=$(aria2c --version | awk 'NR==1{print $3}')
git_ver=$(git --version | awk 'NR==1{print $3}')
dialog_ver=$(dialog --version | awk 'NR==1{print $2}')
curl_ver=$(curl --version | awk 'NR==1{print $2}')
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 开始界面" \
--ok-label "确认" \
--msgbox "版本信息:\n\n
系统: ${platform_info}\n
Term-SD: ${term_sd_ver}\n
Python: ${python_ver}\n
Pip: ${pip_ver}\n
Aria2: ${aria2_ver}\n
Git: ${git_ver}\n
Dialog: ${dialog_ver}\n
Curl: ${curl_ver}\n
\n
提示:\n
使用方向键, Tab 键移动光标, 方向键 / F, B 键翻页 (鼠标滚轮无法翻页) , Enter 键进行选择, Space 键勾选或取消勾选 (已勾选时显示 [*] ), Ctrl + Shift + V 快捷键粘贴文本, 鼠标左键可点击按钮 (右键无效)\n
第一次使用 Term-SD 时先在主界面选择 Term-SD 帮助查看使用说明, 参数说明和注意的地方, 内容不定期更新" \
$(get_dialog_size)
}
# 主界面
term_sd_manager() {
local dialog_arg
local proxy_address_available
local github_mirror_info
local huggingface_mirror_info
local venv_info
local proxy_info
while true; do
cd "${START_PATH}" # 回到最初路径
exit_venv # 确保进行下一步操作前已退出其他虚拟环境
# 检测代理地址是否可用
if [[ ! -z "${HTTP_PROXY}" ]]; then
term_sd_echo "测试代理地址连通性中"
curl -s --connect-timeout 1 "${HTTP_PROXY}"
if [[ "$?" == 0 ]]; then
proxy_address_available="(可用 ✓)"
else
proxy_address_available="(连接异常 ×)"
fi
fi
if is_use_venv; then
venv_info="启用"
else
venv_info="禁用"
fi
if [[ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]]; then
github_mirror_info=$(cat "${START_PATH}/term-sd/config/set-global-github-mirror.conf" | awk '{sub("/https://github.com","") sub("/github.com","")}1')
else
github_mirror_info="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
github_mirror_info="${github_mirror_info} (动态配置)"
fi
if [[ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]]; then
huggingface_mirror_info=$HF_ENDPOINT
else
huggingface_mirror_info="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
huggingface_mirror_info="${huggingface_mirror_info} (动态配置)"
fi
if [[ ! -z "${HTTP_PROXY}" ]]; then
proxy_info="${HTTP_PROXY} ${proxy_address_available}"
else
proxy_info="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
proxy_info="${proxy_info} (动态配置)"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "主界面" \
--ok-label "确认" --cancel-label "退出" \
--menu "请选择 Term-SD 的功能\n当前虚拟环境状态: ${venv_info}\n当前 Github 镜像源设置: ${github_mirror_info}\n当前 HuggingFace 镜像源设置: ${huggingface_mirror_info}\n当前代理设置: ${proxy_info}" \
$(get_dialog_size_menu) \
"0" "> Term-SD 更新管理" \
"1" "> Stable-Diffusion-WebUI 管理" \
"2" "> ComfyUI 管理" \
"3" "> InvokeAI 管理" \
"4" "> Fooocus 管理" \
"5" "> lora-scripts 管理" \
"6" "> kohya_ss 管理" \
"7" "> Term-SD 设置" \
"8" "> Term-SD 帮助" \
"9" "> 退出 Term-SD" \
3>&1 1>&2 2>&3 )
case "${dialog_arg}" in
0)
# 选择 Term-SD 更新
term_sd_update_manager
;;
1)
# 选择 Stable-Diffusion-WebUI
term_sd_install_task_manager stable-diffusion-webui
;;
2)
# 选择 ComfyUI
term_sd_install_task_manager ComfyUI
;;
3)
# 选择 InvokeAI
term_sd_install_task_manager InvokeAI
;;
4)
# 选择 Fooocus
term_sd_install_task_manager Fooocus
;;
5)
# 选择 lora-scripts
term_sd_install_task_manager lora-scripts
;;
6)
# 选择 kohya_ss
term_sd_install_task_manager kohya_ss
;;
7)
# 选择设置
term_sd_setting
;;
8)
# 选择帮助
term_sd_help
;;
*)
# 选择退出
term_sd_print_line
term_sd_echo "退出 Term-SD"
exit 0
;;
esac
done
}
# 帮助列表
# 帮助文件保存在 <Start Path>/term-sd/help
term_sd_help() {
local dialog_arg
local tmp_docs_path
while true; do
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "请选择帮助" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 关于 Term-SD" \
"2" "> Term-SD 使用方法" \
"3" "> 目录说明" \
"4" "> Stable-Diffusion-WebUI 插件说明" \
"5" "> ComfyUI 插件 / 自定义节点说明" \
"6" "> InvokeAI 自定义节点说明" \
"7" "> 用户协议" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/about.md)" \
$(get_dialog_size)
;;
2)
tmp_docs_path=$(term_sd_merge_tips_to_help_docs "${START_PATH}"/term-sd/help/how_to_use_term_sd.md)
less --mouse --use-color \
--prompt="[Term-SD] Notice\: Use keyboard arrow keys \/ U, D key \/ mouse wheel to flip pages, enter Q key return help docs" \
"${tmp_docs_path}"
rm -f "${tmp_docs_path}"
;;
3)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/directory_description.md)" \
$(get_dialog_size)
;;
4)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/sd_webui_extension_description.md)" \
$(get_dialog_size)
;;
5)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/comfyui_extension_description.md)" \
$(get_dialog_size)
;;
6)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/invokeai_custom_node_description.md)" \
$(get_dialog_size)
;;
7)
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 帮助选项" \
--ok-label "确认" \
--msgbox "$(cat "${START_PATH}"/term-sd/help/user_agreement.md)" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# 合并 less 命令操作信息到帮助信息中
term_sd_merge_tips_to_help_docs() {
local origin_docs_path=$@
local docs_name=$(basename "${origin_docs_path}")
local docs_path
docs_path="${START_PATH}/term-sd/task/${docs_name}"
touch "${docs_path}"
cat "${START_PATH}/term-sd/help/tips.md" > "${docs_path}"
echo "" >> "${docs_path}"
cat "${origin_docs_path}" >> "${docs_path}"
echo "${docs_path}"
}
# 检测 Term-SD 是否处于 Debug 模式, 如果是则返回 0
term_sd_is_debug() {
if [[ "${TERM_SD_ENABLE_DEBUG}" == 1 ]];then
return 0
else
return 1
fi
}
# 返回 Bash 的版本是否小于 4, 如果小于 4 则返回 0
term_sd_is_bash_ver_lower() {
if (( BASH_MAJOR_VERSION < 4 )); then
return 0
else
return 1
fi
}
# 获取系统平台
get_system_platform() {
local system_platform
system_platform=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_platform.py")
echo "${system_platform}"
}
# 获取 PyTorch 版本
get_pytorch_version() {
local torch_ver
torch_ver=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_pytorch_ver.py")
echo "${torch_ver}"
}
# 获取 xFormers 版本
get_xformers_version() {
local xformers_ver
xformers_ver=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_xformers_ver.py")
echo "${xformers_ver}"
}
|
2301_81996401/term-sd
|
modules/term_sd_manager.sh
|
Shell
|
agpl-3.0
| 28,338
|
#!/bin/bash
# 在安装过程中, 只有 HuggingFace / Github 的访问有问题
#若全程保持代理, 可能会导致安装速度下降, 因为 Python 软件包的下载没必要走代理, 走代理后代理的速度可能比镜像源的速度慢
# 临时取消代理配置
term_sd_tmp_disable_proxy() {
if [[ ! -z "${HTTP_PROXY}" ]] && is_use_only_proxy; then
term_sd_echo "HuggingFace / Github 下载源独占代理已启用, 临时取消代理配置"
unset HTTP_PROXY # 将代理配置删除
unset HTTPS_PROXY
fi
}
# 恢复原有代理配置
# 使用 TERM_SD_PROXY 全局变量读取代理地址
# 并重新设置 HTTP_PROXY, HTTPS_PROXY 环境变量
term_sd_tmp_enable_proxy() {
if [[ ! -z $TERM_SD_PROXY ]] && is_use_only_proxy; then
term_sd_echo "恢复代理配置"
export HTTP_PROXY=$TERM_SD_PROXY # 从临时变量恢复代理配置
export HTTPS_PROXY=$TERM_SD_PROXY
fi
}
# 获取系统代理地址并返回
get_proxy_config() {
local gsettings_proxy_status
local gsettings_http_host
local gsettings_http_port
local gsettings_http_proxy_config
local gsettings_socks_host
local gsettings_socks_port
local gsettings_socks_proxy_config
local kde_proxy_status
local kde_http_proxy_config
local kde_socks_proxy_config
local windows_proxy_config
local macos_proxy_config
if [[ "$(get_system_platform)" == "win32" ]]; then
windows_proxy_config=$(powershell -ExecutionPolicy Bypass \
-File "${START_PATH}/term-sd/modules/get_windows_proxy_config.ps1" \
2> /dev/null \
)
echo "${windows_proxy_config}"
elif [[ "$(get_system_platform)" == "linux" ]]; then
# 获取代理设置状态
gsettings_proxy_status=$(gsettings get org.gnome.system.proxy mode 2> /dev/null | sed "s/'//g") # Gnome
kde_proxy_status=$(cat ~/.config/kioslaverc 2> /dev/null | grep "ProxyType" | awk -F 'ProxyType=' '{print $NF}') # KDE
# 判断代理设置
if [[ "${gsettings_proxy_status}" == "manual" ]]; then
gsettings_http_host=$(gsettings get org.gnome.system.proxy.http host 2> /dev/null | sed "s/'//g")
gsettings_http_port=$(gsettings get org.gnome.system.proxy.http port 2> /dev/null)
gsettings_socks_host=$(gsettings get org.gnome.system.proxy.socks host 2> /dev/null | sed "s/'//g")
gsettings_socks_port=$(gsettings get org.gnome.system.proxy.socks port 2> /dev/null)
gsettings_http_proxy_config="http://${gsettings_http_host}:${gsettings_http_port}"
gsettings_socks_proxy_config="socks://${gsettings_socks_host}:${gsettings_socks_port}"
if [[ ! -z "${gsettings_http_host}" ]] && [[ ! -z "${gsettings_http_port}" ]]; then
echo "${gsettings_http_proxy_config}"
elif [[ ! -z "${gsettings_socks_host}" ]] && [[ ! -z "${gsettings_socks_port}" ]]; then
echo "${gsettings_socks_proxy_config}"
fi
elif [[ "${kde_proxy_status}" == 1 ]]; then
kde_http_proxy_config=$(cat ~/.config/kioslaverc 2> /dev/null |\
grep "httpProxy=" |\
awk -F 'httpProxy=' '{gsub(/ /, ":"); print $NF}' \
)
kde_socks_proxy_config=$(cat ~/.config/kioslaverc 2> /dev/null |\
grep "socksProxy=" |\
awk -F 'socksProxy=' '{gsub(/ /, ":"); print $NF}' \
)
if [[ ! -z "${kde_http_proxy_config}" ]]; then
echo "${kde_http_proxy_config}"
elif [[ ! -z "${kde_socks_proxy_config}" ]]; then
echo "${kde_socks_proxy_config}"
fi
fi
elif [[ "$(get_system_platform)" == "darwin" ]]; then
macos_proxy_config=$(scutil --proxy 2> /dev/null | awk ' \
/HTTPEnable/ { http_enabled = $3; } \
/HTTPProxy/ { http_server = $3; } \
/HTTPPort/ { http_port = $3; } \
/SOCKSEnable/ { socks_enabled = $3; } \
/SOCKSProxy/ { socks_server = $3; } \
/SOCKSPort/ { socks_port = $3; } \
END { \
if (http_enabled == "1") { \
print "http://" http_server ":" http_port; \
} else if (socks_enabled == "1") { \
print "socks://" socks_server ":" socks_port; \
} \
}' \
)
echo "${macos_proxy_config}"
fi
}
# 动态设置代理
# 自动检测系统代理配置并设置, 当配置不可用时则自动清除
# 当 <Start Path>/term-sd/config/enable-dynamic-proxy.lock 不存在时则不执行
# 检测到可用的系统代理后将设置 HTTP_PROXY, HTTPS_PROXY 环境变量, 使用 TERM_SD_PROXY 全局变量临时存储代理地址
# 代理地址保存在 <Start Path>/term-sd/config/proxy.conf
dynamic_configure_proxy() {
local proxy_config
if [[ ! -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
return
fi
term_sd_echo "检测本地系统代理配置中"
proxy_config=$(get_proxy_config)
if [[ ! -z "${proxy_config}" ]]; then
term_sd_echo "检测到本地系统代理配置, 设置代理中"
export HTTP_PROXY=$proxy_config
export HTTPS_PROXY=$proxy_config
TERM_SD_PROXY=$HTTPS_PROXY
echo "${proxy_config}" > "${START_PATH}/term-sd/config/proxy.conf"
term_sd_echo "测试代理连通性中"
curl -s --connect-timeout 1 "${HTTP_PROXY}"
if [[ "$?" == 0 ]]; then
term_sd_echo "代理配置可用"
else
term_sd_echo "代理连接异常, 清除代理配置中"
unset HTTP_PROXY
unset HTTPS_PROXY
unset TERM_SD_PROXY
rm -f "${START_PATH}/term-sd/config/proxy.conf"
term_sd_echo "清除代理配置完成"
fi
else
term_sd_echo "检测到系统代理已禁用, 清除代理中"
unset HTTP_PROXY
unset HTTPS_PROXY
unset TERM_SD_PROXY
rm -f "${START_PATH}/term-sd/config/proxy.conf"
term_sd_echo "清除代理配置完成"
fi
}
# 代理设置
# 使用 HTTP_PROXY, HTTP_PROXY 环境变量设置代理
# 将代理地址保存到 TERM_SD_PROXY 全局变量作为恢复代理时使用的参数
# <Start Path>/term-sd/config/proxy.conf 配置文件用于保存代理地址
term_sd_proxy_setting() {
local term_sd_proxy_config
local dialog_arg
local is_proxy_available
local proxy_info
local dynamic_proxy_info
while true; do
if [[ ! -z "${HTTP_PROXY}" ]]; then
term_sd_echo "测试代理地址连通性中"
curl -s --connect-timeout 1 "${HTTP_PROXY}"
if [[ "$?" == 0 ]]; then
is_proxy_available="(可用 ✓)"
else
is_proxy_available="(连接异常 ×)"
fi
fi
if [[ ! -z "${HTTP_PROXY}" ]]; then
proxy_info="${HTTP_PROXY} ${is_proxy_available}"
else
proxy_info="未设置"
fi
if [[ -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
dynamic_proxy_info="启用"
else
dynamic_proxy_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "代理设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置代理服务器, 解决 AI 软件和 Term-SD 因网络环境导致无法连接上服务器, 而出现报错的问题\n注意: 动态设置代理可自动检测系统代理并设置, 并且将覆盖手动设置的代理地址, 如需手动设置代理, 需将动态设置代理禁用\n当前代理设置: ${proxy_info}\n当前动态代理设置: ${dynamic_proxy_info}\n请选择要设置的代理协议" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 动态设置代理" \
"2" "> 设置 Http 协议代理" \
"3" "> 设置 Socks 协议代理" \
"4" "> 设置 Socks5 协议代理" \
"5" "> 设置自定义协议代理" \
"6" "> 删除代理参数" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
dynamic_configure_proxy_setting
;;
2)
term_sd_proxy_config=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入代理地址\n格式: <IP>:<端口>" \
$(get_dialog_size) \
"$(echo ${HTTP_PROXY} | awk -F '://' '{print $NF}')" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${term_sd_proxy_config}" ]]; then
term_sd_proxy_config=$(echo ${term_sd_proxy_config} | awk '{gsub(/[:]/, ":") ; gsub(/[。]/, ".")}1') # 防止用户输入中文冒号,句号后导致错误
export HTTP_PROXY="http://${term_sd_proxy_config}"
export HTTPS_PROXY="http://${term_sd_proxy_config}"
TERM_SD_PROXY=$HTTPS_PROXY
echo "http://${term_sd_proxy_config}" > "${START_PATH}/term-sd/config/proxy.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" \
--msgbox "代理地址: ${HTTP_PROXY}\n代理协议: $(echo ${HTTP_PROXY} | awk -F '://' '{print$NR}')\n设置代理完成" \
$(get_dialog_size)
fi
;;
3)
term_sd_proxy_config=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入代理地址\n格式: <IP>:<端口>" \
$(get_dialog_size) "$(echo ${HTTP_PROXY} | awk -F'://' '{print $NF}')" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "$term_sd_proxy_config" ]]; then
term_sd_proxy_config=$(echo ${term_sd_proxy_config} | awk '{gsub(/[:]/, ":") ; gsub(/[。]/, ".")}1') # 防止用户输入中文冒号,句号后导致错误
export HTTP_PROXY="socks://${term_sd_proxy_config}"
export HTTPS_PROXY="socks://${term_sd_proxy_config}"
TERM_SD_PROXY=$HTTPS_PROXY
echo "socks://${term_sd_proxy_config}" > "${START_PATH}/term-sd/config/proxy.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" \
--msgbox "代理地址: ${HTTP_PROXY}\n代理协议: $(echo ${HTTP_PROXY} | awk -F '://' '{print$NR}')\n设置代理完成" \
$(get_dialog_size)
fi
;;
4)
term_sd_proxy_config=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入代理地址\n格式: <IP>:<端口>" \
$(get_dialog_size) "$(echo ${HTTP_PROXY} | awk -F'://' '{print $NF}')" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${term_sd_proxy_config}" ]]; then
term_sd_proxy_config=$(echo ${term_sd_proxy_config} | awk '{gsub(/[:]/, ":") ; gsub(/[。]/, ".")}1') # 防止用户输入中文冒号, 句号后导致错误
export HTTP_PROXY="socks5://${term_sd_proxy_config}"
export HTTPS_PROXY="socks5://${term_sd_proxy_config}"
TERM_SD_PROXY=$HTTPS_PROXY
echo "socks5://${term_sd_proxy_config}" > "${START_PATH}/term-sd/config/proxy.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" \
--msgbox "代理地址: ${HTTP_PROXY}\n代理协议: $(echo ${HTTP_PROXY} | awk -F '://' '{print $NR}')\n设置代理完成" \
$(get_dialog_size)
fi
;;
5)
term_sd_proxy_config=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入代理地址\n格式: <代理协议>://<IP>:<端口>" \
$(get_dialog_size) \
"${HTTP_PROXY}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]] && [[ ! -z "${term_sd_proxy_config}" ]]; then
term_sd_proxy_config=$(echo ${term_sd_proxy_config} | awk '{gsub(/[:]/, ":") ; gsub(/[。]/, ".")}1') # 防止用户输入中文冒号, 句号后导致错误
export HTTP_PROXY="${term_sd_proxy_config}"
export HTTPS_PROXY="${term_sd_proxy_config}"
TERM_SD_PROXY=$HTTPS_PROXY
echo "${term_sd_proxy_config}" > "${START_PATH}/term-sd/config/proxy.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" \
--msgbox "代理地址: ${HTTP_PROXY}\n代理协议: $(echo ${HTTP_PROXY} | awk -F '://' '{print $NR}')\n设置代理完成" \
$(get_dialog_size)
fi
;;
6)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数删除界面" \
--yes-label "是" --no-label "否" \
--yesno "是否删除代理配置 ?" \
$(get_dialog_size)); then
unset HTTP_PROXY
unset HTTPS_PROXY
unset TERM_SD_PROXY
rm -f "${START_PATH}/term-sd/config/proxy.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "代理参数设置界面" \
--ok-label "确认" \
--msgbox "清除设置代理完成" \
$(get_dialog_size)
fi
;;
*)
break
;;
esac
done
}
# 动态代理设置
dynamic_configure_proxy_setting() {
local dialog_arg
local dynamic_proxy_info
local dynamic_proxy_msg
while true; do
if [[ -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
dynamic_proxy_info="启用"
else
dynamic_proxy_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "动态代理设置界面" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "该功能将检测系统代理并自动应用, 当系统代理禁用后将自动取消代理\n注意: 启用后自动检测到的代理配置将覆盖原先的代理配置, 如需手动设置代理, 需禁用动态代理设置\n当前状态: ${dynamic_proxy_info}\n是否启用动态代理 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
touch -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock"
term_sd_echo "检测系统代理中"
dynamic_configure_proxy # 检测系统代理并设置
if [[ -z "${HTTP_PROXY}" ]]; then
dynamic_proxy_msg="当前未检测到系统代理, 已自动清除代理配置"
else
dynamic_proxy_msg="检测到系统代理并可用, 已设置代理\n代理地址: ${HTTP_PROXY}"
fi
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "动态代理设置界面" \
--ok-label "确认" \
--msgbox "启用成功\n${dynamic_proxy_msg}" \
$(get_dialog_size)
;;
2)
rm -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "动态代理设置界面" \
--ok-label "确认" \
--msgbox "禁用成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
|
2301_81996401/term-sd
|
modules/term_sd_proxy.sh
|
Shell
|
agpl-3.0
| 17,476
|
#!/bin/bash
# 处理 Python 命令
# 使用 TERM_SD_PYTHON_PATH 全局变量读取 Python 的路径
term_sd_python() {
# 检测是否在虚拟环境中
if [[ ! -z "${VIRTUAL_ENV}" ]]; then # 当处在虚拟环境时
# 检测使用哪种命令调用python
# 调用虚拟环境的python
if [[ ! -z "$(python --version 2> /dev/null)" ]]; then
python "$@" # 加双引号防止运行报错
elif [[ ! -z "$(python3 --version 2> /dev/null)" ]]; then
python3 "$@"
fi
else # 不在虚拟环境时
#调 用系统中存在的python
"${TERM_SD_PYTHON_PATH}" "$@"
fi
}
# 处理 Pip 命令
# 使用 TERM_SD_PYTHON_PATH 全局变量读取 Python 的路径
term_sd_pip() {
# 检测是否在虚拟环境中
if [[ ! -z "${VIRTUAL_ENV}" ]]; then
# 调用虚拟环境的pip
if [[ ! -z "$(python --version 2> /dev/null)" ]]; then
python -m pip "$@"
elif [[ ! -z "$(python3 --version 2> /dev/null)" ]]; then
python3 -m pip "$@"
fi
else
# 调用系统中存在的pip
"${TERM_SD_PYTHON_PATH}" -m pip "$@"
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_python_cmd.sh
|
Shell
|
agpl-3.0
| 1,171
|
#!/bin/bash
# 虚拟环境设置
# 使用 ENABLE_VENV 全局变量保存虚拟环境的启用状态
python_venv_setting() {
local dialog_arg
while true; do
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "虚拟环境设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于给 AI 软件启用虚拟环境, 隔离不同 AI 软件的 Python 库, 防止 Python 库中软件包版本和 AI 软件的版本要求不对应\n当前虚拟环境状态: $(is_use_venv && echo "启用" || echo "禁用")\n是否启用虚拟环境 ? (推荐启用)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
ENABLE_VENV=1
rm -f "${START_PATH}/term-sd/config/term-sd-venv-disable.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "虚拟环境设置界面" \
--ok-label "确认" \
--msgbox "启用成功" \
$(get_dialog_size)
;;
2)
ENABLE_VENV=0
touch "${START_PATH}/term-sd/config/term-sd-venv-disable.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "虚拟环境设置界面" \
--ok-label "确认" \
--msgbox "禁用成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# PyPI 镜像源选项(配置文件)
pip_mirrors_setting() {
local dialog_arg
local pip_mirror_setup_info
while true; do
term_sd_echo "获取 Pip 全局配置"
pip_mirror_setup_info=$(term_sd_pip config list)
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (配置文件) 选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "(已弃用该选项, 该设置将不会生效) 该功能用于设置 PyPI 镜像源 (环境变量) (优先级小于环境变量配置), 加速国内下载 Python 软件包的速度\n当前 Pip 全局配置:\n${pip_mirror_setup_info}\n请选择设置的 PyPI 镜像源 (配置文件)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置官方源" \
"2" "> 设置国内镜像源" \
"3" "> 删除镜像源配置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_echo "设置 PyPI 镜像源为官方源"
term_sd_pip config set global.index-url "https://pypi.python.org/simple"
term_sd_pip config unset global.extra-index-url
term_sd_pip config set global.find-links "https://download.pytorch.org/whl/torch_stable.html"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (配置文件) 选项" \
--ok-label "确认" \
--msgbox "设置 PyPI 镜像源为官方源完成" \
$(get_dialog_size)
;;
2)
term_sd_echo "设置 PyPI 镜像源为国内镜像源"
term_sd_pip config set global.index-url "${TERM_SD_PIP_INDEX_URL}"
term_sd_pip config set global.extra-index-url "${TERM_SD_PIP_EXTRA_INDEX_URL}"
term_sd_pip config set global.find-links "${TERM_SD_PIP_FIND_LINKS}"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (配置文件) 选项" \
--ok-label "确认" \
--msgbox "设置 PyPI 镜像源为国内镜像源完成" \
$(get_dialog_size)
;;
3)
term_sd_echo "删除镜像源配置"
term_sd_pip config unset global.extra-index-url
term_sd_pip config unset global.index-url
term_sd_pip config unset global.find-links
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (配置文件) 选项" \
--ok-label "确认" \
--msgbox "删除 PyPI 镜像源配置完成" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# PyPI 镜像源设置(环境变量)
# 使用 PIP_INDEX_URL, PIP_EXTRA_INDEX_URL, PIP_FIND_LINKS 环境变量设置 PyPI 镜像源
# 环境变量中 PyPI 镜像源设置的优先级高于 Pip 配置文件中的镜像源设置
# PyPI 镜像源配置保存在 <Start Path>/term-sd/config/term-sd-pip-mirror.conf
# 存储的值为 1 时,使用官方源, 为 2 时使用镜像源
pip_mirrors_env_setting() {
local dialog_arg
local pip_mirror_setup_info
while true; do
if [[ -z "${PIP_INDEX_URL}" ]]; then
pip_mirror_setup_info="未设置"
elif [[ ! -z "$(grep "pypi.python.org" <<< ${PIP_INDEX_URL})" ]]; then
pip_mirror_setup_info="官方源"
else
pip_mirror_setup_info="国内镜像源"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (环境变量) 选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置 PyPI 镜像源 (环境变量) (优先级大于全局配置), 加速国内下载 Python 软件包的速度\n当前 Pip 环境变量配置: $pip_mirror_setup_info\n请选择设置的 PyPI 镜像源 (环境变量)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 设置官方源" \
"2" "> 设置国内镜像源 (默认)" \
"3" "> 删除镜像源配置" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
export PIP_INDEX_URL="https://pypi.python.org/simple"
export PIP_EXTRA_INDEX_URL=""
export PIP_FIND_LINKS="https://download.pytorch.org/whl/torch_stable.html"
echo "1" > "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (环境变量) 选项" \
--ok-label "确认" \
--msgbox "设置 PyPI 镜像源为官方源成功" \
$(get_dialog_size)
;;
2)
export PIP_INDEX_URL=$TERM_SD_PIP_INDEX_URL
export PIP_EXTRA_INDEX_URL=$TERM_SD_PIP_EXTRA_INDEX_URL
export PIP_FIND_LINKS=$TERM_SD_PIP_FIND_LINKS
echo "2" > "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (环境变量) 选项" \
--ok-label "确认" \
--msgbox "设置 PyPI 镜像源为国内镜像源成功" \
$(get_dialog_size)
;;
3)
unset PIP_INDEX_URL
unset PIP_EXTRA_INDEX_URL
unset PIP_FIND_LINKS
rm -f "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "PyPI 镜像源 (环境变量) 选项" \
--ok-label "确认" \
--msgbox "删除镜像源配置成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# Pip 缓存清理功能
pip_cache_clean() {
local pip_cache_info
local pip_cache_path_v23
local pip_cache_path
local pip_cache_size
local pip_http_file_count
local pip_built_wheel_path
local pip_built_wheel_size
local pip_built_wheel_count
local uv_cache_dir
term_sd_echo "统计 Pip / uv 缓存信息"
pip_cache_info=$(term_sd_python "${START_PATH}/term-sd/python_modules/get_pip_cache_info.py")
pip_cache_path_v23=$(awk -F ';' '{print $1}' <<< "${pip_cache_info}")
pip_cache_path=$(awk -F ';' '{print $2}' <<< "${pip_cache_info}")
pip_cache_size=$(awk -F ';' '{print $3}' <<< "${pip_cache_info}")
pip_http_file_count=$(awk -F ';' '{print $4}' <<< "${pip_cache_info}")
pip_built_wheel_path=$(awk -F ';' '{print $5}' <<< "${pip_cache_info}")
pip_built_wheel_size=$(awk -F ';' '{print $6}' <<< "${pip_cache_info}")
pip_built_wheel_count=$(awk -F ';' '{print $7}' <<< "${pip_cache_info}")
uv_cache_dir=$(awk -F ';' '{print $8}' <<< "${pip_cache_info}")
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Pip / uv 缓存清理选项" \
--yes-label "是" --no-label "否" \
--yesno "Pip 缓存信息:\n包索引页面缓存位置 (Pip v23.3+): ${pip_cache_path_v23}\n包索引页面缓存位置 (旧版 Pip): ${pip_cache_path}\n包索引页面缓存大小: ${pip_cache_size}\nHTTP 文件数量: ${pip_http_file_count}\n本地构建的 wheel 文件位置: ${pip_built_wheel_path}\n本地构建的 wheel 文件大小: ${pip_built_wheel_size}\n本地构建的 wheel 文件数量: ${pip_built_wheel_count}\nuv 缓存路径: ${uv_cache_dir}\n是否删除 Pip / uv 缓存 ?" \
$(get_dialog_size)); then
term_sd_echo "清理 Pip 缓存中"
term_sd_pip cache purge
term_sd_echo "清理 uv 缓存中"
if which uv &> /dev/null; then
term_sd_uv cache clean
else
[[ -d "${UV_CACHE_DIR}" ]] && rm -rf "${UV_CACHE_DIR}/"
fi
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Pip / uv 缓存清理选项" \
--ok-label "确认" \
--msgbox "清理 Pip / uv 缓存完成" \
$(get_dialog_size)
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_python_config.sh
|
Shell
|
agpl-3.0
| 10,396
|
#!/bin/bash
# Term-SD 设置
term_sd_setting() {
local dialog_arg
local pip_mirror_setup_info
local venv_setup_info
local python_package_manager_info
local proxy_setup_info
local github_mirror_setup_info
local term_sd_cmd_retry_setup_info
local term_sd_enable_strict_install_mode_setup_info
local aria2_thread_setup_info
local term_sd_path_redirect_setup_info
local cuda_memory_alloc_setup_info
local env_check_setup_info
while true; do
if is_use_venv; then
venv_setup_info="启用"
else
venv_setup_info="禁用"
fi
if [[ -z "${PIP_INDEX_URL}" ]]; then
pip_mirror_setup_info="未设置"
elif [[ ! -z "$(echo ${PIP_INDEX_URL} | grep "pypi.python.org")" ]]; then
pip_mirror_setup_info="官方源"
else
pip_mirror_setup_info="国内镜像源"
fi
if [[ -f "${START_PATH}/term-sd/config/disable-uv.lock" ]]; then
python_package_manager_info="Pip"
else
python_package_manager_info="uv"
fi
if [[ -z "${HTTP_PROXY}" ]]; then
if [[ -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
proxy_setup_info="无 (动态配置)"
else
proxy_setup_info="无"
fi
else
if [[ -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
proxy_setup_info="动态代理地址: $(echo ${HTTP_PROXY} | awk '{print substr($1,1,40)}')"
else
proxy_setup_info="代理地址: $(echo ${HTTP_PROXY} | awk '{print substr($1,1,40)}')"
fi
fi
if [[ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]]; then
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
github_mirror_setup_info="动态镜像源: $(cat "${START_PATH}/term-sd/config/set-global-github-mirror.conf")"
else
github_mirror_setup_info="镜像源: $(cat "${START_PATH}/term-sd/config/set-global-github-mirror.conf")"
fi
else
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
github_mirror_setup_info="未设置 (动态配置)"
else
github_mirror_setup_info="未设置"
fi
fi
if [[ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]]; then
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
huggingface_mirror_setup_info="动态镜像源: ${HF_ENDPOINT}"
else
huggingface_mirror_setup_info="镜像源: ${HF_ENDPOINT}"
fi
else
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
huggingface_mirror_setup_info="未设置 (动态配置)"
else
huggingface_mirror_setup_info="未设置"
fi
fi
if [[ -f "${START_PATH}/term-sd/config/term-sd-watch-retry.conf" ]]; then
term_sd_cmd_retry_setup_info="启用(重试次数: $(cat "${START_PATH}/term-sd/config/term-sd-watch-retry.conf"))"
else
term_sd_cmd_retry_setup_info="禁用"
fi
if [[ ! -f "${START_PATH}/term-sd/config/term-sd-disable-strict-install-mode.lock" ]]; then
term_sd_enable_strict_install_mode_setup_info="严格模式"
else
term_sd_enable_strict_install_mode_setup_info="宽容模式"
fi
if [[ -f "${START_PATH}/term-sd/config/set-aria2-thread.conf" ]]; then
aria2_thread_setup_info="启用 (线程数: $(cat "${START_PATH}/term-sd/config/set-aria2-thread.conf"))"
else
aria2_thread_setup_info="禁用"
fi
if [[ ! -f "${START_PATH}/term-sd/config/disable-cache-path-redirect.lock" ]]; then
term_sd_path_redirect_setup_info="启用"
else
term_sd_path_redirect_setup_info="禁用"
fi
if [[ -f "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock" ]]; then
cuda_memory_alloc_setup_info="启用"
else
cuda_memory_alloc_setup_info="禁用"
fi
if [[ ! -f "${START_PATH}/term-sd/config/disable-env-check.lock" ]]; then
env_check_setup_info="启用"
else
env_check_setup_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 设置选项" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "请选择 Term-SD 设置" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 虚拟环境设置 (${venv_setup_info})" \
"3" "> PyPI 镜像源设置 (${pip_mirror_setup_info})" \
"4" "> Python 包管理器选择设置 (${python_package_manager_info})" \
"5" "> Pip / uv 缓存清理" \
"6" "> 代理设置 (${proxy_setup_info})" \
"7" "> Github 镜像源设置 (${github_mirror_setup_info})" \
"8" "> HuggingFace 镜像源设置 (${huggingface_mirror_setup_info})" \
"9" "> 命令执行监测设置 (${term_sd_cmd_retry_setup_info})" \
"10" "> Term-SD 安装模式 (${term_sd_enable_strict_install_mode_setup_info})" \
"11" "> Aria2 线程设置 (${aria2_thread_setup_info})" \
"12" "> 缓存重定向设置 (${term_sd_path_redirect_setup_info})" \
"13" "> CUDA 内存分配设置 (${cuda_memory_alloc_setup_info})" \
"14" "> 运行环境检测设置 (${env_check_setup_info})" \
"15" "> 自定义安装路径" \
"16" "> 空间占用分析" \
"17" "> 网络连接测试" \
"18" "> 卸载 Term-SD" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
python_venv_setting
;;
2)
pip_mirrors_setting
;;
3)
pip_mirrors_env_setting
;;
4)
python_package_install_manager_setting
;;
5)
pip_cache_clean
;;
6)
term_sd_proxy_setting
;;
7)
term_sd_git_global_mirror_setting
;;
8)
term_sd_huggingface_global_mirror_setting
;;
9)
term_sd_try_setting
;;
10)
term_sd_enable_strict_install_mode_setting
;;
11)
aria2_multi_threaded_setting
;;
12)
term_sd_cache_redirect_setting
;;
13)
cuda_memory_alloc_setting
;;
14)
env_check_setting
;;
15)
custom_install_path_setting
;;
16)
term_sd_disk_space_stat
;;
17)
term_sd_network_test
;;
18)
term_sd_uninstall_interface
;;
*)
break
;;
esac
done
}
# 安装模式设置
# 使用 TERM_SD_ENABLE_STRICT_INSTALL_MODE 全局变量保存 Term-SD 安装模式的选择情况
# 使用 <Start Path>/term-sd/config/term-sd-disable-strict-install-mode.lock 文件保存安装模式配置
term_sd_enable_strict_install_mode_setting() {
local dialog_arg
export TERM_SD_ENABLE_STRICT_INSTALL_MODE
local enable_strict_mode_info
while true; do
if [[ ! -f "${START_PATH}/term-sd/config/term-sd-disable-strict-install-mode.lock" ]]; then
enable_strict_mode_info="严格模式"
else
enable_strict_mode_info="宽容模式"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "安装模式设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置 Term-SD 安装 AI 软件的工作模式。当启用 \"严格模式\" 后, Term-SD 在安转 AI 软件时出现执行失败的命令时将停止安装进程 (Term-SD 支持断点恢复, 可恢复上次安装进程中断的位置), 而 \"宽容模式\" 在安转 AI 软件时出现执行失败的命令时忽略执行失败的命令, 继续执行完成安装任务\n当前安装模式: $()\n请选择要设置的安装模式 (默认启用严格模式)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 严格模式" \
"2" "> 宽容模式" \
3>&1 1>&2 2>&3)
case $dialog_arg in
1)
TERM_SD_ENABLE_STRICT_INSTALL_MODE=1
rm -f "${START_PATH}/term-sd/config/term-sd-disable-strict-install-mode.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "安装模式设置界面" \
--ok-label "确认" \
--msgbox "启用严格模式完成" \
$(get_dialog_size)
;;
2)
TERM_SD_ENABLE_STRICT_INSTALL_MODE=0
touch "${START_PATH}/term-sd/config/term-sd-disable-strict-install-mode.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "安装模式设置界面" \
--ok-label "确认" \
--msgbox "启用宽容模式完成" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# Aria2 线程设置
# 使用 ARIA2_MULTI_THREAD 全局变量设置 Aria2 线程数量
# Aria2 线程配置保存在 <Start Path>/term-sd/config/set-aria2-thread.conf
aria2_multi_threaded_setting() {
local dialog_arg
local aria2_multi_threaded_value
local aria2_thread_info
local aria2_config
while true; do
if [[ -f "${START_PATH}/term-sd/config/set-aria2-thread.conf" ]]; then
aria2_thread_info="启用 (线程数: $(cat "${START_PATH}/term-sd/config/set-aria2-thread.conf"))"
else
aria2_thread_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Aria2线程设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于增加 Term-SD 在使用 Aria2 下载模型时的线程数, 在一定程度上提高下载速度\n当前状态: ${aria2_thread_info}\n是否启用 Aria2 多线程下载 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
if [[ -f "${START_PATH}/term-sd/config/set-aria2-thread.conf" ]]; then
aria2_config=$(cat "${START_PATH}/term-sd/config/set-aria2-thread.conf")
else
unset aria2_config
fi
aria2_multi_threaded_value=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入线程数 (仅输入数字, 不允许输入负数和其他非数字的字符)" \
$(get_dialog_size) \
"${aria2_config}" \
3>&1 1>&2 2>&3)
if [[ ! -z "$(awk '{gsub(/[0-9]/, "")}1' <<< ${aria2_multi_threaded_value})" ]] \
|| (( aria2_multi_threaded_value <= 0)); then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" \
--msgbox "输入格式错误, 线程数只能为数字且不能为负数" \
$(get_dialog_size)
else
if [[ ! -z "${aria2_multi_threaded_value}" ]]; then
if (( $aria2_multi_threaded_value <= 16 )); then
echo "${aria2_multi_threaded_value}" > "${START_PATH}/term-sd/config/set-aria2-thread.conf"
ARIA2_MULTI_THREAD=$aria2_multi_threaded_value
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" \
--msgbox "启用 Aria2 多线程下载成功, Aria2 线程数: ${ARIA2_MULTI_THREAD}" \
$(get_dialog_size)
else
echo "16" > "${START_PATH}/term-sd/config/set-aria2-thread.conf"
ARIA2_MULTI_THREAD=16
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" \
--msgbox "启用 Aria2 多线程下载成功, Aria2 线程数: ${ARIA2_MULTI_THREAD}" \
$(get_dialog_size)
fi
else
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" \
--msgbox "未输入, 请重试" \
$(get_dialog_size)
fi
fi
;;
2)
rm -f "${START_PATH}/term-sd/config/set-aria2-thread.conf"
ARIA2_MULTI_THREAD=1
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Aria2 线程设置界面" \
--ok-label "确认" \
--msgbox "禁用 Aria2 多线程下载成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# 缓存重定向设置
# 通过以下环境变量设置缓存路径:
# CACHE_HOME, HF_HOME, MATPLOTLIBRC
# MODELSCOPE_CACHE, MS_CACHE_HOME, SYCL_CACHE_DIR
# TORCH_HOME, U2NET_HOME, XDG_CACHE_HOME, PIP_CACHE_DIR, PYTHONPYCACHEPREFIX
# 缓存重定向的配置保存在 <Start Path>/term-sd/config/disable-cache-path-redirect.lock
term_sd_cache_redirect_setting() {
local dialog_arg
local cache_redirect_info
while true; do
if [[ ! -f "${START_PATH}/term-sd/config/disable-cache-path-redirect.lock" ]]; then
cache_redirect_info="启用"
else
cache_redirect_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "缓存重定向设置界面" \
--ok-label "确认" \
--cancel-label "取消" \
--menu "该功能将会把 AI 软件产生的缓存重定向至 Term-SD 中 (便于清理)\n当前状态: ${cache_redirect_info}\n是否启用缓存重定向 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
rm -f "${START_PATH}/term-sd/config/disable-cache-path-redirect.lock"
export CACHE_HOME="${START_PATH}/term-sd/cache"
export HF_HOME="${START_PATH}/term-sd/cache/huggingface"
export MATPLOTLIBRC="${START_PATH}/term-sd/cache"
export MODELSCOPE_CACHE="${START_PATH}/term-sd/cache/modelscope/hub"
export MS_CACHE_HOME="${START_PATH}/term-sd/cache/modelscope/hub"
export SYCL_CACHE_DIR="${START_PATH}/term-sd/cache/libsycl_cache"
export TORCH_HOME="${START_PATH}/term-sd/cache/torch"
export U2NET_HOME="${START_PATH}/term-sd/cache/u2net"
export XDG_CACHE_HOME="${START_PATH}/term-sd/cache"
export PIP_CACHE_DIR="${START_PATH}/term-sd/cache/pip"
export PYTHONPYCACHEPREFIX="${START_PATH}/term-sd/cache/pycache"
export TORCHINDUCTOR_CACHE_DIR="${START_PATH}/term-sd/cache/torchinductor"
export TRITON_CACHE_DIR="${START_PATH}/term-sd/cache/triton"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "缓存重定向设置界面" \
--ok-label "确认" \
--msgbox "启用成功" \
$(get_dialog_size)
;;
2)
touch -f "${START_PATH}/term-sd/config/disable-cache-path-redirect.lock"
unset CACHE_HOME
unset HF_HOME
unset MATPLOTLIBRC
unset MODELSCOPE_CACHE
unset MS_CACHE_HOME
unset SYCL_CACHE_DIR
unset TORCH_HOME
unset U2NET_HOME
unset XDG_CACHE_HOME
unset PIP_CACHE_DIR
unset PYTHONPYCACHEPREFIX
unset TORCHINDUCTOR_CACHE_DIR
unset TRITON_CACHE_DIR
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "缓存重定向设置界面" \
--ok-label "确认" \
--msgbox "禁用成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# 储存占用分析
term_sd_disk_space_stat() {
local disk_free_space_stat
local term_sd_space_stat
local sd_webui_space_stat
local comfyui_space_stat
local invokeai_space_stat
local fooocus_space_stat
local lora_scripts_space_stat
local kohya_ss_space_stat
term_sd_echo "统计空间占用中"
term_sd_echo "统计当前目录剩余空间"
disk_free_space_stat=$(df -h | awk 'NR==2{print$4}')
term_sd_echo "统计 Term-SD 缓存目录空间占用"
term_sd_space_stat=$([ -d "term-sd/cache" ] && du -sh term-sd/cache | awk '{print $1}' || echo "无")
term_sd_echo "统计 Stable-Diffusion-WebUI 占用"
sd_webui_space_stat=$([ -d "${SD_WEBUI_ROOT_PATH}" ] && du -sh "${SD_WEBUI_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
term_sd_echo "统计 ComfyUI 占用"
comfyui_space_stat=$([ -d "${COMFYUI_ROOT_PATH}" ] && du -sh "${COMFYUI_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
term_sd_echo "统计 InvokeAI 占用"
invokeai_space_stat=$([ -d "${INVOKEAI_ROOT_PATH}" ] && du -sh "${INVOKEAI_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
term_sd_echo "统计 Fooocus 占用"
fooocus_space_stat=$([ -d "${FOOOCUS_ROOT_PATH}" ] && du -sh "${FOOOCUS_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
term_sd_echo "统计 lora-scripts 占用"
lora_scripts_space_stat=$([ -d "${LORA_SCRIPTS_ROOT_PATH}" ] && du -sh "${LORA_SCRIPTS_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
term_sd_echo "统计 kohya_ss 占用"
kohya_ss_space_stat=$([ -d "${KOHYA_SS_ROOT_PATH}" ] && du -sh "${KOHYA_SS_ROOT_PATH}" | awk '{print $1}' || echo "未安装")
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 空间占用分析" \
--ok-label "确认" \
--msgbox "项目空间占用分析:\n
当前目录剩余空间: ${disk_free_space_stat}\n
Term-SD (重定向) 缓存目录: ${term_sd_space_stat}\n
Stable-Diffusion-WebUI: ${sd_webui_space_stat}\n
ComfyUI: ${comfyui_space_stat}\n
InvokeAI: ${invokeai_space_stat}\n
Fooocus: ${fooocus_space_stat}\n
lora-scripts: ${lora_scripts_space_stat}\n
kohya_ss: ${kohya_ss_space_stat}\n
" $(get_dialog_size)
}
# 网络连接测试
term_sd_network_test() {
local http_return_code
local req
local i
local network_test_url
local count
local sum
local ip
local country
local region
local city
local org
count=1
network_test_url="\
google.com \
huggingface.co \
modelscope.cn \
github.com \
gh.api.99988866.xyz \
ghfast.top \
mirror.ghproxy.com \
gitclone.com \
gh-proxy.com \
ghps.cc \
gh.idayer.com \
ghproxy.net \
gh.api.99988866.xyz \
ghproxy.1888866.xyz \
slink.ltd \
github.boki.moe \
github.moeyy.xyz \
gh-proxy.net \
gh-proxy.ygxz.in \
wget.la \
kkgithub.com \
hf-mirror.com \
huggingface.sukaka.top \
"
sum=$(echo ${network_test_url} | wc -w)
term_sd_echo "获取网络信息"
[[ -f "${START_PATH}/term-sd/task/ipinfo.sh" ]] && rm -f "${START_PATH}/term-sd/task/ipinfo.sh"
curl -s ipinfo.io >> "${START_PATH}/term-sd/task/ipinfo.sh"
term_sd_echo "测试网络中"
for i in ${network_test_url}; do
term_sd_echo "[${count}/${sum}] 测试链接访问: ${i}"
count=$(( count + 1 ))
http_return_code=$(curl --connect-timeout 10 -s -o /dev/null -w "%{http_code}" https://${i})
case ${http_return_code} in
200|301)
req="${req} ${i}: 成功 ✓\n"
;;
*)
req="${req} ${i}: 失败 ×\n"
;;
esac
done
ip=$(cat "${START_PATH}/term-sd/task/ipinfo.sh" | grep \"ip\"\: | awk '{gsub(/[\\"]/,"") ; sub("ip:","IP: ")}1')
country=$(cat "${START_PATH}/term-sd/task/ipinfo.sh" | grep \"country\"\: | awk '{gsub(/[\\"]/,"") ; sub("country:","地址: ")}1')
region=$(cat "${START_PATH}/term-sd/task/ipinfo.sh" | grep \"region\"\: | awk '{gsub(/[\\"]/,"") ; sub("region:","")}1')
city=$(cat "${START_PATH}/term-sd/task/ipinfo.sh" | grep \"city\"\: | awk '{gsub(/[\\"]/,"") ; sub("city:","")}1')
org=$(cat "${START_PATH}/term-sd/task/ipinfo.sh" | grep \"org\"\: | awk '{gsub(/[\\"]/,"") ; sub("org:","网络提供商: ")}1')
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 网络测试" \
--ok-label "确认" \
--msgbox "网络测试结果:\n
${TERM_SD_DELIMITER}\n
网络信息:\n
${ip}\n
${country}\
${region}\
${city}\n
${org}\n
${TERM_SD_DELIMITER}\n
网站访问:\n
${req}\
${TERM_SD_DELIMITER}\n
" $(get_dialog_size)
rm -f "${START_PATH}/term-sd/task/ipinfo.sh"
}
# 卸载 Term-SD 选项
term_sd_uninstall_interface() {
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 卸载界面" \
--yes-label "是" --no-label "否" \
--yesno "警告: 该操作将永久删除 Term-SD 目录中的所有文件, 包括 AI 软件下载的部分模型文件 (存在于 Term-SD 目录中的 cache 文件夹, 如有必要, 请备份该文件夹)\n是否卸载 Term-SD ?" \
$(get_dialog_size)); then
term_sd_echo "请再次确认是否删除 Term-SD (yes/no) ?"
term_sd_echo "警告: 该操作将永久删除 Term-SD"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case $(term_sd_read) in
y|yes|YES|Y)
term_sd_echo "开始卸载 Term-SD"
rm -rf "${START_PATH}/term-sd"
rm -f "${START_PATH}/term-sd.sh"
USER_SHELL=$(echo ${SHELL} | awk -F "/" '{print $NF}') # 读取用户所使用的shell
if [ "${USER_SHELL}" = bash ] || [[ "${USER_SHELL}" == zsh ]]; then
sed -i '/# Term-SD/d' ~/."${USER_SHELL}"rc
sed -i '/term_sd(){/d' ~/."${USER_SHELL}"rc
sed -i '/alias tsd/d' ~/."${USER_SHELL}"rc
fi
term_sd_echo "Term-SD 卸载完成"
exec "${SHELL}"
exit 0
;;
*)
term_sd_echo "取消卸载操作"
;;
esac
fi
}
# 是否启用了严格安装模式, 如果启用了则返回 0
term_sd_is_use_strict_install_mode() {
if [[ "${TERM_SD_ENABLE_STRICT_INSTALL_MODE}" == 1 ]]; then
return 0
else
return 1
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_setting.sh
|
Shell
|
agpl-3.0
| 24,918
|
#!/bin/bash
# 安装任务管理
# 命令后面需加上 AI 软件名称
# 使用 TERM_SD_MANAGE_OBJECT 全局变量设置正在管理的 AI 软件名称
# 调用时将检测 <Start Path>/term-sd/task/ 中是否存在未完成的安装任务
# 如果存在, 则提示是否继续进行安装
# 如果不存在, 则进入管理界面
# 使用:
# term_sd_install_task_manager <AI 软件的名称>
# 可用名称: stable-diffusion-webui, ComfyUI, InvokeAI, Fooocus, lora-scripts, kohya_ss
# 对应的安装任务配置: sd_webui_install.sh, comfyui_install.sh, invokeai_install.sh, fooocus_install.sh, lora_scripts_install.sh, kohya_ss_install.sh
term_sd_install_task_manager() {
local dialog_arg
local install_task_file_path
local install_exec_cmd
local manager_exec_cmd
local install_task_name
case $@ in
stable-diffusion-webui)
install_task_file_path="${START_PATH}/term-sd/task/sd_webui_install.sh"
install_exec_cmd="install_sd_webui"
manager_exec_cmd="sd_webui_manager"
install_task_name="Stable-Diffusion-WebUI"
TERM_SD_MANAGE_OBJECT="stable-diffusion-webui"
;;
ComfyUI)
install_task_file_path="${START_PATH}/term-sd/task/comfyui_install.sh"
install_exec_cmd="install_comfyui"
manager_exec_cmd="comfyui_manager"
install_task_name="ComfyUI"
TERM_SD_MANAGE_OBJECT="ComfyUI"
;;
InvokeAI)
install_task_file_path="${START_PATH}/term-sd/task/invokeai_install.sh"
install_exec_cmd="install_invokeai"
manager_exec_cmd="invokeai_manager"
install_task_name="InvokeAI"
TERM_SD_MANAGE_OBJECT="InvokeAI"
;;
Fooocus)
install_task_file_path="${START_PATH}/term-sd/task/fooocus_install.sh"
install_exec_cmd="install_fooocus"
manager_exec_cmd="fooocus_manager"
install_task_name="Fooocus"
TERM_SD_MANAGE_OBJECT="Fooocus"
;;
lora-scripts)
install_task_file_path="${START_PATH}/term-sd/task/lora_scripts_install.sh"
install_exec_cmd="install_lora_scripts"
manager_exec_cmd="lora_scripts_manager"
install_task_name="lora-scripts"
TERM_SD_MANAGE_OBJECT="lora-scripts"
;;
kohya_ss)
install_task_file_path="${START_PATH}/term-sd/task/kohya_ss_install.sh"
install_exec_cmd="install_kohya_ss"
manager_exec_cmd="kohya_ss_manager"
install_task_name="kohya_ss"
TERM_SD_MANAGE_OBJECT="kohya_ss"
;;
esac
if [[ -f "${install_task_file_path}" ]]; then
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "AI 软件安装提示界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "检测到 ${install_task_name} 有未完成的安装任务, 是否继续进行 ?" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 继续执行安装任务" \
"2" "> 重新设置安装参数并进行安装" \
"3" "> 删除安装任务并进入管理界面" \
"4" "> 跳过安装任务并进入管理界面" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
# 寻找任务队列表并执行
"${install_exec_cmd}"
;;
2)
# 删除原有的任务队列表并进入安装参数设置界面
rm -f "${install_task_file_path}"
"${install_exec_cmd}"
;;
3)
# 删除原有的任务队列表并进入管理界面
rm -f "${install_task_file_path}"
"${manager_exec_cmd}"
;;
4)
# 直接进入管理界面
"${manager_exec_cmd}"
;;
esac
else
"${manager_exec_cmd}"
fi
unset TERM_SD_MANAGE_OBJECT
}
# 安装任务命令队列格式处理(除去前面的标识)
term_sd_get_task_cmd() {
local task_cmd_sign
local task_cmd
task_cmd_sign=$(echo $@ | awk '{print $1}')
task_cmd=$(echo $@ | awk '{sub("'${task_cmd_sign}' ","")}1')
echo "${task_cmd}"
}
# 安装命令执行
# 使用:
# term_sd_exec_cmd <命令文件> <指定行数>
term_sd_exec_cmd() {
local cmd_file=$1
local cmd_point=$2
local install_cmd
local exec_req
install_cmd=$(term_sd_get_task_cmd $(cat "${cmd_file}" | awk 'NR=='${cmd_point}' {print $0}'))
if [[ -z "$(cat "${cmd_file}" | awk 'NR=='${cmd_point}' {print $1}' | grep -o __term_sd_task_done_ )" ]]; then # 检测命令是否需要执行
term_sd_is_debug && term_sd_echo "执行命令: \"${install_cmd}\""
eval "${install_cmd}" # 执行命令
else
term_sd_is_debug && term_sd_echo "跳过执行命令: \"${install_cmd}\""
true
fi
exec_req=$?
if [[ "${exec_req}" == 0 ]]; then # 检测命令是否执行成功
term_sd_task_cmd_revise "${cmd_file}" ${cmd_point} # 将执行成功的命令标记为完成
fi
return $exec_req
}
# 安装任务命令标记修改(将未完成标记为已完成)
# 使用格式: term_sd_task_cmd_revise <文件路径> <指定行数>
term_sd_task_cmd_revise() {
sed -i ''$2's/__term_sd_task_pre_/__term_sd_task_done_/' "$1" > /dev/null
}
# 设置安装时使用的环境变量
# 变量来源于 modules/install_prepare.sh
term_sd_set_install_env_value() {
cat<<EOF
__term_sd_task_sys PIP_INDEX_MIRROR="${PIP_INDEX_MIRROR}"
__term_sd_task_sys PIP_EXTRA_INDEX_MIRROR="${PIP_EXTRA_INDEX_MIRROR}"
__term_sd_task_sys PIP_FIND_LINKS_MIRROR="${PIP_FIND_LINKS_MIRROR}"
__term_sd_task_sys UV_INDEX_MIRROR="${UV_INDEX_MIRROR}"
__term_sd_task_sys UV_EXTRA_INDEX_MIRROR="${UV_EXTRA_INDEX_MIRROR}"
__term_sd_task_sys UV_FIND_LINKS_MIRROR="${UV_FIND_LINKS_MIRROR}"
__term_sd_task_sys USE_PIP_MIRROR=${USE_PIP_MIRROR}
__term_sd_task_sys PIP_BREAK_SYSTEM_PACKAGE_ARG="${PIP_BREAK_SYSTEM_PACKAGE_ARG}"
__term_sd_task_sys PIP_USE_PEP517_ARG="${PIP_USE_PEP517_ARG}"
__term_sd_task_sys PIP_FORCE_REINSTALL_ARG="${PIP_FORCE_REINSTALL_ARG}"
__term_sd_task_sys PIP_UPDATE_PACKAGE_ARG="${PIP_UPDATE_PACKAGE_ARG}"
__term_sd_task_sys GITHUB_MIRROR="${GITHUB_MIRROR}"
__term_sd_task_sys INSTALL_PYTORCH_VERSION="${INSTALL_PYTORCH_VERSION}"
__term_sd_task_sys INSTALL_XFORMERS_VERSION="${INSTALL_XFORMERS_VERSION}"
__term_sd_task_sys PYTORCH_TYPE="${PYTORCH_TYPE}"
__term_sd_task_sys TERM_SD_ENABLE_ONLY_PROXY=${TERM_SD_ENABLE_ONLY_PROXY}
__term_sd_task_sys USE_MODELSCOPE_MODEL_SRC=${USE_MODELSCOPE_MODEL_SRC}
__term_sd_task_sys SD_WEBUI_REPO="${SD_WEBUI_REPO}"
__term_sd_task_sys SD_WEBUI_BRANCH="${SD_WEBUI_BRANCH}"
EOF
}
# 为安装命令列表添加空行
term_sd_add_blank_line() {
echo "" >> "$@"
}
# 在安装过程中检测ai软件是否下载下来,当检测到未下载下来时返回错误并终止,防止文件散落
is_sd_repo_exist() {
if [[ ! -d "$@" ]]; then
term_sd_echo "检测到核心未能成功下载, 为了防止接下来的安装操作产生的文件散落出来, Term-SD 将终止安装进程"
term_sd_echo "已终止安装进程"
term_sd_echo "退出 Term-SD"
exit 1
else
true
fi
}
|
2301_81996401/term-sd
|
modules/term_sd_task_manager.sh
|
Shell
|
agpl-3.0
| 7,440
|
#!/bin/bash
# 命令自动重试功能
# 使用 TERM_SD_CMD_RETRY 全局变量获取重试次数
term_sd_try() {
local count=0
if (( TERM_SD_CMD_RETRY == 0 )); then
"$@" # 执行输入的命令
else
while (( count <= TERM_SD_CMD_RETRY ));do
count=$(( count + 1 ))
"$@" # 执行输入的命令
if [[ "$?" == 0 ]]; then
break # 运行成功并中断循环
else
if (( count > TERM_SD_CMD_RETRY )); then
term_sd_echo "超出重试次数, 终止重试"
term_sd_is_debug && term_sd_echo "执行失败的命令: \"$@\""
return 1
fi
term_sd_echo "[${count}/${TERM_SD_CMD_RETRY}] 命令执行失败, 重试中"
fi
done
fi
}
# 命令自动重试功能设置
# 使用 TERM_SD_CMD_RETRY 全局变量设置自动重试次数
term_sd_try_setting() {
local dialog_arg
local term_sd_try_value
local term_sd_try_info
local config_value
while true; do
if [[ -f "${START_PATH}/term-sd/config/term-sd-watch-retry.conf" ]]; then
term_sd_try_info="启用 (重试次数: $(cat "${START_PATH}/term-sd/config/term-sd-watch-retry.conf"))"
else
term_sd_try_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于监测命令的运行情况, 若设置了重试次数, Term-SD 将重试执行失败的命令 (有些命令需要联网, 在网络不稳定的时候容易导致命令执行失败), 保证命令执行成功\n当前状态: ${term_sd_try_info}\n是否启用命令执行监测? (推荐启用)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
config_value=$(cat "${START_PATH}/term-sd/config/term-sd-watch-retry.conf")
term_sd_try_value=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入重试次数 (仅输入数字, 不允许输入负数和其他非数字的字符)" \
$(get_dialog_size) \
"${config_value}" \
3>&1 1>&2 2>&3)
if [[ ! -z "$(echo ${term_sd_try_value} | awk '{gsub(/[0-9]/, "")}1')" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" \
--msgbox "输入格式错误, 重试次数只能为数字且不能为负数" \
$(get_dialog_size)
else
if [[ ! -z "${term_sd_try_value}" ]]; then
echo "${term_sd_try_value}" > "${START_PATH}/term-sd/config/term-sd-watch-retry.conf"
TERM_SD_CMD_RETRY=$term_sd_try_value
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" \
--msgbox "Term-SD 命令执行监测启用成功, 重试次数: ${TERM_SD_CMD_RETRY}" \
$(get_dialog_size)
else
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" \
--msgbox "未输入, 请重试" \
$(get_dialog_size)
fi
fi
;;
2)
rm -f "${START_PATH}/term-sd/config/term-sd-watch-retry.conf"
TERM_SD_CMD_RETRY=0
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "命令执行监测设置界面" \
--ok-label "确认" \
--msgbox "Term-SD 命令执行监测禁用成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
|
2301_81996401/term-sd
|
modules/term_sd_try.sh
|
Shell
|
agpl-3.0
| 4,681
|
#!/bin/bash
# Term-SD 更新功能
term_sd_update_manager() {
local dialog_arg
local req
local commit_hash
local local_commit_hash
local origin_branch
local ref
local auto_update_info
if is_git_repo "${START_PATH}/term-sd"; then
while true; do
if [[ -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock" ]]; then
auto_update_info="启用"
else
auto_update_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 更新选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择 Term-SD 的操作\nTerm-SD 更新源: $(git_remote_display "${START_PATH}/term-sd")\nTerm-SD 分支: $(git_branch_display "${START_PATH}/term-sd")\nTerm-SD 自动更新: ${auto_update_info}\nTerm-SD 版本: ${TERM_SD_VER}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 更新" \
"2" "> 修复更新" \
"3" "> 自动更新设置" \
"4" "> 切换更新源" \
"5" "> 切换分支" \
"6" "> 重启" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_echo "更新 Term-SD 中"
if [[ -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock" ]]; then
date +'%Y-%m-%d %H:%M:%S' > "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf" # 记录更新时间
fi
commit_hash=$(git -C "${START_PATH}/term-sd" show -s --format="%h")
git_pull_repository "${START_PATH}/term-sd"
if [[ "$?" == 0 ]]; then
local_commit_hash=$(git -C "${START_PATH}/term-sd" show -s --format="%h")
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}"
chmod +x "${START_PATH}/term-sd.sh"
if [[ "${commit_hash}" == "${local_commit_hash}" ]]; then
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新结果" \
--ok-label "确定" \
--msgbox "Term-SD 已是最新版本" \
$(get_dialog_size)
else
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新结果" \
--ok-label "确定" \
--msgbox "Term-SD 更新成功, 选择确定后重启" \
$(get_dialog_size)
. "${START_PATH}/term-sd/term-sd.sh"
fi
else
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新结果" \
--ok-label "确定" \
--msgbox "Term-SD 更新失败" \
$(get_dialog_size)
fi
;;
2)
git_fix_pointer_offset "${START_PATH}/term-sd"
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}"
chmod +x "${START_PATH}/term-sd.sh"
;;
3)
term_sd_auto_update_setting
;;
4)
term_sd_remote_revise
;;
5)
term_sd_branch_switch
;;
6)
term_sd_echo "重载 Term-SD 启动脚本中"
. "${START_PATH}/term-sd/term-sd.sh"
;;
*)
break
;;
esac
done
else # 检测到没有该文件夹, 无法进行更新, 提示用户修复
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新选项" \
--ok-label "确定" \
--msgbox "Term-SD 文件损坏, 无法进行更新, 请重启 Term-SD 并按提示修复问题" \
$(get_dialog_size)
fi
}
# Term-SD 更新源切换功能
term_sd_remote_revise() {
local dialog_arg
while true; do
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 更新源切换选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择 Term-SD 的分支\n当前 Term-SD 更新源: $(cd term-sd ; git_remote_display)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> Github 源" \
"2" "> Gitee 源" \
"4" "> Gitlab 源" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
git -C "${START_PATH}/term-sd" remote set-url origin "https://github.com/licyk/term-sd"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新源切换选项" \
--ok-label "确认" \
--msgbox "Term-SD 更新源切换完成" \
$(get_dialog_size)
;;
2)
git -C "${START_PATH}/term-sd" remote set-url origin "https://gitee.com/licyk/term-sd"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新源切换选项" \
--ok-label "确认" \
--msgbox "Term-SD 更新源切换完成" \
$(get_dialog_size)
;;
3)
git -C "${START_PATH}/term-sd" remote set-url origin "https://licyk@bitbucket.org/licyks/term-sd"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新源切换选项" \
--ok-label "确认" \
--msgbox "Term-SD 更新源切换完成" \
$(get_dialog_size)
;;
4)
git -C "${START_PATH}/term-sd" remote set-url origin "https://gitlab.com/licyk/term-sd"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 更新源切换选项" \
--ok-label "确认" \
--msgbox "Term-SD 更新源切换完成" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# Term-SD 分支切换
term_sd_branch_switch() {
local dialog_arg
while true; do
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 分支切换界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择 Term-SD 的分支\n当前 Term-SD 分支: $(git_branch_display "${START_PATH}/term-sd")" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 主分支" \
"2" "> 测试分支" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
case "${dialog_arg}" in
1)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 分支切换界面" \
--yes-label "是" --no-label "否" \
--yesno "是否切换 Term-SD 的主分支 ?" \
$(get_dialog_size)); then
git -C "${START_PATH}/term-sd" checkout main
git -C "${START_PATH}/term-sd" reset --hard origin/main
cp -f term-sd/term-sd.sh .
chmod +x term-sd.sh
term_sd_echo "切换到 Term-SD 主分支"
term_sd_echo "即将重启 Term-SD"
term_sd_sleep 3
. "${START_PATH}/term-sd/term-sd.sh"
else
term_sd_echo "取消切换 Term-SD 分支操作"
fi
;;
2)
if (dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 分支切换界面" \
--yes-label "是" --no-label "否" \
--yesno "是否切换 Term-SD 的测试分支 ?" \
$(get_dialog_size)); then
git -C "${START_PATH}/term-sd" checkout dev
git -C "${START_PATH}/term-sd" reset --hard origin/dev
cp -f term-sd/term-sd.sh .
chmod +x term-sd.sh
term_sd_echo "切换到 Term-SD 测试分支"
term_sd_echo "即将重启 Term-SD"
term_sd_sleep 3
. "${START_PATH}/term-sd/term-sd.sh"
else
term_sd_echo "取消切换 Term-SD 分支操作"
fi
;;
*)
break
;;
esac
else
break
fi
done
}
# Term-SD 自动更新设置
# Term-SD 自动更新配置保存在 <Start Path>/term-sd/config/term-sd-auto-update.lock
# <Start Path>/term-sd/config/term-sd-auto-update-time.conf 保存上一次自动更新的时间
term_sd_auto_update_setting() {
local dialog_arg
local auto_update_info
while true; do
if [[ -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock" ]]; then
auto_update_info="启用"
else
auto_update_info="禁用"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Term-SD 自动更新选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "是否启用 Term-SD 自动更新 ?\nTerm-SD 自动更新: ${auto_update_info}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启用" \
"2" "> 禁用" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
touch "${START_PATH}/term-sd/config/term-sd-auto-update.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 自动更新选项" \
--ok-label "确认" \
--msgbox "启用 Term-SD 自动更新成功" \
$(get_dialog_size)
;;
2)
rm -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock"
rm -f "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Term-SD 自动更新选项" \
--ok-label "确认" \
--msgbox "禁用 Term-SD 自动更新成功" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
|
2301_81996401/term-sd
|
modules/term_sd_update.sh
|
Shell
|
agpl-3.0
| 11,739
|
#!/bin/bash
# 处理 uv 命令
term_sd_uv() {
if [[ ! -z "${VIRTUAL_ENV}" ]]; then
uv "$@"
else
UV_PYTHON=$TERM_SD_PYTHON_PATH uv "$@"
fi
}
# 处理 uv 安装命令
term_sd_uv_install() {
check_uv_upgrade
term_sd_uv pip install "$@"
}
# 安装 uv
term_sd_init_uv() {
term_sd_pip install uv --upgrade
}
# 检查 uv 更新
# 使用 TERM_SD_UV_MININUM_VER 全局变量确定最低的 uv 版本
check_uv_upgrade() {
local status
status=$(term_sd_python "${START_PATH}/term-sd/python_modules/check_uv_version.py" --uv-mininum-ver "${TERM_SD_UV_MININUM_VER}")
if [[ "${status}" == "True" ]]; then
term_sd_echo "更新 uv 中"
if term_sd_init_uv; then
term_sd_echo "uv 更新成功"
return 0
else
term_sd_echo "uv 更新失败, 可能会导致 Python 软件包的安装问题"
return 1
fi
fi
}
# 检测是否使用 uv 作为包管理器
term_sd_is_use_uv() {
[[ "${USE_UV_TO_MANAGE_PACKAGE}" == 1 ]] && return 0 || return 1
}
# 设置安装 Python 软件包时使用的包管理器
# 通过 USE_UV_TO_MANAGE_PACKAGE 全局变量设置使用的 Python 包管理器类型
python_package_install_manager_setting() {
local dialog_arg
while true; do
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Term-SD" \
--backtitle "Python 包管理器设置界面" \
--ok-label "确认" --cancel-label "取消" \
--menu "该功能用于设置 Term-SD 安装 Python 软件包时使用的 Python 包管理器, Pip 为传统的 Python 包管理器, uv 为速度更快的包管理器\n当前使用的 Python 包管理器: $(term_sd_is_use_uv && echo "uv" || echo "Pip")\n请选择使用的 Python 包管理器 (推荐使用 uv)" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 使用 Pip 包管理器" \
"2" "> 使用 uv 包管理器" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
USE_UV_TO_MANAGE_PACKAGE=0
touch "${START_PATH}/term-sd/config/disable-uv.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Python 包管理器设置界面" \
--ok-label "确认" \
--msgbox "设置 Python 包管理器为 Pip 完成" \
$(get_dialog_size)
;;
2)
USE_UV_TO_MANAGE_PACKAGE=1
rm -f "${START_PATH}/term-sd/config/disable-uv.lock"
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "Python 包管理器设置界面" \
--ok-label "确认" \
--msgbox "设置 Python 包管理器为 uv 完成" \
$(get_dialog_size)
;;
*)
break
;;
esac
done
}
# 检测 uv 是否出现安装失败, 并显示警告信息
check_uv_install_failed_and_warning() {
if [[ ! "$?" == 0 ]]; then
term_sd_echo "检测到 uv 安装 Python 软件包失败, 尝试回滚到 Pip 重试 Python 软件包安装"
return 0
fi
return 1
}
|
2301_81996401/term-sd
|
modules/term_sd_uv.sh
|
Shell
|
agpl-3.0
| 3,315
|
#!/bin/bash
# 一键更新全部插件功能
# 该功能在 SD WebUI, ComfyUI 中共用的
# 使用 TERM_SD_MANAGE_OBJECT 全局变量显示要更新插件的 AI 软件
update_all_extension() {
local extension_update_req
local sum=0
local count=0
local success_count=0
local fail_count=0
local i
local is_invokeai_node_disable=0
term_sd_print_line "${TERM_SD_MANAGE_OBJECT} 插件一键更新"
# 统计需要更新的数量
for i in ./*; do
if is_git_repo "${i}"; then
sum=$(( sum + 1 ))
fi
done
# 更新插件
for i in ./*; do
if is_git_repo "${i}"; then # 检测到目录中包含.git文件夹再执行更新操作
count=$(( count + 1 ))
term_sd_echo "[${count}/${sum}] 更新 $(basename "${i}") 插件中"
extension_update_req="${extension_update_req}$(basename "${i}") 插件:"
# 当 InvokeAI 自定义节点禁用时恢复启用状态
if [[ "${TERM_SD_MANAGE_OBJECT}" == "InvokeAI" ]] && [[ -f "${i}/__init__.py.bak" ]]; then
mv -f "${i}/__init__.py.bak" "${i}/__init__.py" &> /dev/null
is_invokeai_node_disable=1
fi
git_pull_repository "${i}" # 更新插件
if [[ "$?" == 0 ]]; then
extension_update_req="${extension_update_req} 更新成功 ✓\n"
success_count=$(( success_count + 1 ))
else
extension_update_req="${extension_update_req} 更新失败 ×\n"
fail_count=$(( fail_count + 1 ))
fi
# 恢复 InvokeAI 自定义节点的禁用状态
if [[ "${TERM_SD_MANAGE_OBJECT}" == "InvokeAI" ]] && [[ "${is_invokeai_node_disable}" == 1 ]] && [[ -f "${i}/__init__.py" ]]; then
mv -f "${i}/__init__.py" "${i}/__init__.py.bak" &> /dev/null
is_invokeai_node_disable=0
fi
fi
done
term_sd_print_line
dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "插件 / 自定义节点更新结果" \
--ok-label "确认" \
--msgbox "当前插件 / 自定义节点的更新情况列表\n[●: ${sum} | ✓: ${success_count} | ×: ${fail_count}]\n${TERM_SD_DELIMITER}\n${extension_update_req}${TERM_SD_DELIMITER}" \
$(get_dialog_size)
}
|
2301_81996401/term-sd
|
modules/update_all_extension.sh
|
Shell
|
agpl-3.0
| 2,376
|
#!/bin/bash
# Vlad SD WebUI 启动参数配置
# 启动参数保存在 <Start Path>/term-sd/config/vlad-sd-webui-launch.conf
vlad_sd_webui_launch_args_setting() {
local dialog_arg
local arg
local launch_args
local i
# 展示启动参数选项
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--checklist "请选择 SD.NEXT 启动参数, 确认之后将覆盖原有启动参数配置" \
$(get_dialog_size_menu) \
"1" "(medvram) 启用显存优化 (显存 < 6g 时推荐使用)" OFF \
"2" "(lowvram) 启用显存优化(显存 <4g 时推荐使用)" OFF \
"3" "(allow-code) 允许从 WebUI 执行自定义脚本" OFF \
"4" "(share) 通过 Gradio 共享" OFF \
"5" "(insecure) 启用扩展标签" OFF \
"6" "(use-cpu) 使用 CPU 进行生图" OFF \
"7" "(listen) 开放远程连接" OFF \
"8" "(freeze) 冻结 WebUI 设置" OFF \
"9" "(autolaunch) 启动 WebUI 完成后自动启动浏览器" OFF \
"10" "(docs) 在 /docs 处挂载 Gradio 文档" OFF \
"11" "(api-only) 在无 WebUI 界面时启用 API" OFF \
"12" "(api-log) 启用输出所有 API 请求的日志记录" OFF \
"13" "(tls-selfsign) 使用自签名证书启用 TLS" OFF \
"14" "(no-hashing) 禁用模型 Hash 检查" OFF \
"15" "(no-metadata) 禁用从模型中读取元数据" OFF \
"16" "(no-download) 禁用自动下载模型, 即使模型路径无模型" OFF \
"17" "(profile) 运行分析器" OFF \
"18" "(disable-queue) 禁用 Gradio 队列" OFF \
"19" "(backend original) 使用原始后端进行生图" OFF \
"20" "(backend diffusers) 使用 Diffusers 后端进行生图" OFF \
"21" "(debug) 以 Debug 模式运行安装程序" OFF \
"22" "(reset) 将 WebUI 主仓库重置为最新版本" OFF \
"23" "(upgrade) 将 WebUI 主仓库升级为最新版本" OFF \
"24" "(requirements) 强制检查依赖" OFF \
"25" "(quick) 仅运行启动模块" OFF \
"26" "(use-directml) 使用 DirectML 作为后端进行生图" OFF \
"27" "(use-openvino) 使用 OpenVINO 作为后端进行生图" OFF \
"28" "(use-ipex) 使用 IPEX 作为后端进行生图" OFF \
"29" "(use-cuda) 使用 CUDA 作为后端进行生图" OFF \
"30" "(use-rocm) 使用 ROCM 作为后端进行生图" OFF \
"31" "(use-xformers) 使用 xFormers 优化" OFF \
"32" "(skip-requirements) 跳过依赖检查" OFF \
"33" "(skip-extensions) 跳过运行单个扩展安装程序" OFF \
"34" "(skip-git) 跳过所有 Git 操作" OFF \
"35" "(skip-torch) 跳过 PyTorch 检查" OFF \
"36" "(skip-all) 跳过运行所有检查" OFF \
"37" "(experimental) 允许使用不受支持版本的库" OFF \
"38" "(reinstall) 强制重新安装所有要求" OFF \
"39" "(test) 仅运行测试并退出" OFF \
"40" "(ignore) 忽略任何错误并尝试继续" OFF \
"41" "(safe) 在安全模式下运行, 不使用用户扩展" OFF \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
for i in ${dialog_arg}; do
case "${i}" in
1)
arg="--medvram"
;;
2)
arg="--lowvram"
;;
3)
arg="--allow-code"
;;
4)
arg="--share"
;;
5)
arg="--insecure"
;;
6)
arg="--use-cpu all"
;;
7)
arg="--listen"
;;
8)
arg="--freeze"
;;
9)
arg="--autolaunch"
;;
10)
arg="--docs"
;;
11)
arg="--api-only"
;;
12)
arg="--api-log"
;;
13)
arg="--tls-selfsign"
;;
14)
arg="--no-hashing"
;;
15)
arg="--no-metadata"
;;
16)
arg="--no-download"
;;
17)
arg="--profile"
;;
18)
arg="--disable-queue"
;;
19)
arg="--backend original"
;;
20)
arg="--backend diffusers"
;;
21)
arg="--debug"
;;
22)
arg="--reset"
;;
23)
arg="--upgrade"
;;
24)
arg="--requirements"
;;
25)
arg="--quick"
;;
26)
arg="--use-directml"
;;
27)
arg="--use-openvino"
;;
28)
arg="--use-ipex"
;;
29)
arg="--use-cuda"
;;
30)
arg="--use-rocm"
;;
31)
arg="--use-xformers"
;;
32)
arg="--skip-requirements"
;;
33)
arg="--skip-extensions"
;;
34)
arg="--skip-git"
;;
35)
arg="--skip-torch"
;;
36)
arg="--skip-all"
;;
37)
arg="--experimental"
;;
38)
arg="--reinstall"
;;
39)
arg="--test"
;;
40)
arg="--ignore"
;;
41)
arg="--safe"
;;
esac
launch_args="${arg} ${launch_args}"
done
# 生成启动脚本
term_sd_echo "设置 SD.NEXT 启动参数: ${launch_args}"
echo "launch.py ${launch_args}" > "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf
else
term_sd_echo "取消设置 SD.NEXT 启动参数"
fi
}
# Vlad SD WebUI 启动界面
vlad_sd_webui_launch() {
local dialog_arg
local launch_args
add_vlad_sd_webui_normal_launch_args
while true; do
launch_args=$(cat "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf)
if is_use_venv; then
launch_args="python ${launch_args}"
else
launch_args="${TERM_SD_PYTHON_PATH} ${launch_args}"
fi
dialog_arg=$(dialog --erase-on-exit --notags \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 启动选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择启动 SD.NEXT / 修改 SD.NEXT 启动参数\n当前启动参数: ${launch_args}" \
$(get_dialog_size_menu) \
"0" "> 返回" \
"1" "> 启动" \
"2" "> 配置预设启动参数" \
"3" "> 修改自定义启动参数" \
"4" "> 重置启动参数" \
3>&1 1>&2 2>&3)
case "${dialog_arg}" in
1)
term_sd_launch
;;
2)
vlad_sd_webui_launch_args_setting
;;
3)
vlad_sd_webui_launch_args_revise
;;
4)
add_vlad_sd_webui_normal_launch_args
;;
*)
break
;;
esac
done
}
# Vlad SD WebUI 启动参数修改界面
# 修改前从 <Start Path>/term-sd/config/vlad-sd-webui-launch.conf 读取启动参数
# 可在上次的基础上修改
vlad_sd_webui_launch_args_revise() {
local dialog_arg
local launch_args
launch_args=$(cat "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf | awk '{sub("launch.py ","")}1')
dialog_arg=$(dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 自定义启动参数选项" \
--ok-label "确认" --cancel-label "取消" \
--inputbox "请输入 SD.NEXT 启动参数" \
$(get_dialog_size) \
"${launch_args}" \
3>&1 1>&2 2>&3)
if [[ "$?" == 0 ]]; then
term_sd_echo "设置 SD.NEXT 启动参数: ${dialog_arg}"
echo "launch.py ${dialog_arg}" > "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf
else
term_sd_echo "取消修改 SD.NEXT 启动参数"
fi
}
# 添加默认启动参数配置
add_vlad_sd_webui_normal_launch_args() {
if [[ ! -f "${START_PATH}/term-sd/config/vlad-sd-webui-launch.conf" ]]; then # 找不到启动配置时默认生成一个
echo "launch.py --autolaunch --use-cuda --use-xformers" > "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf
fi
}
# 重置启动参数
restore_vlad_sd_webui_launch_args() {
if (dialog --erase-on-exit \
--title "Stable-Diffusion-WebUI 管理" \
--backtitle "Stable-Diffusion-WebUI 重置启动参数选项选项" \
--yes-label "是" --no-label "否" \
--yesno "是否重置 SD.NEXT 启动参数" \
$(get_dialog_size)); then
term_sd_echo "重置启动参数"
rm -f "${START_PATH}"/term-sd/config/vlad-sd-webui-launch.conf
add_vlad_sd_webui_normal_launch_args
else
term_sd_echo "取消重置操作"
fi
}
|
2301_81996401/term-sd
|
modules/vlad_sd_webui_launch.sh
|
Shell
|
agpl-3.0
| 10,404
|
"""ComfyUI 运行环境检查"""
import re
import os
import sys
import copy
import logging
import argparse
import importlib.metadata
from collections import namedtuple
from pathlib import Path
from typing import Optional, TypedDict, Union
def get_args() -> argparse.Namespace:
"""获取命令行参数输入参数输入"""
parser = argparse.ArgumentParser(description="ComfyUI 运行环境检查")
def normalized_filepath(filepath):
return str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--comfyui-path", type=normalized_filepath, default=None, help="ComfyUI 路径"
)
parser.add_argument(
"--conflict-depend-notice-path",
type=normalized_filepath,
default=None,
help="保存 ComfyUI 扩展依赖冲突信息的文件路径",
)
parser.add_argument(
"--requirement-list-path",
type=normalized_filepath,
default=None,
help="保存 ComfyUI 需要安装扩展依赖的路径列表",
)
parser.add_argument("--debug-mode", action="store_true", help="显示调试信息")
return parser.parse_args()
COMMAND_ARGS = get_args()
class ColoredFormatter(logging.Formatter):
"""Logging 格式化"""
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
def format(self, record):
colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = "{}{}{}".format(seq, levelname, self.COLORS["RESET"])
return super().format(colored_record)
def get_logger(
name: str,
level: int = logging.INFO,
) -> logging.Logger:
"""获取 Loging 对象
参数:
name (`str`):
Logging 名称
"""
logger = logging.getLogger(name)
logger.propagate = False
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
ColoredFormatter(
"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s", "%H:%M:%S"
)
)
logger.addHandler(handler)
logger.setLevel(level)
logger.debug("Logger initialized.")
return logger
logger = get_logger(
"ComfyUI Env Checker", logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO
)
# 提取版本标识符组件的正则表达式
# ref:
# https://peps.python.org/pep-0440
# https://packaging.python.org/en/latest/specifications/version-specifiers
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
# 编译正则表达式
package_version_parse_regex = re.compile(
r"^\s*" + VERSION_PATTERN + r"\s*$",
re.VERBOSE | re.IGNORECASE,
)
# 定义版本组件的命名元组
VersionComponent = namedtuple(
"VersionComponent",
[
"epoch",
"release",
"pre_l",
"pre_n",
"post_n1",
"post_l",
"post_n2",
"dev_l",
"dev_n",
"local",
"is_wildcard",
],
)
def parse_version(version_str: str) -> VersionComponent:
"""解释 Python 软件包版本号
参数:
version_str (`str`):
Python 软件包版本号
返回值:
`VersionComponent`: 版本组件的命名元组
异常:
`ValueError`: 如果 Python 版本号不符合 PEP440 规范
"""
# 检测并剥离通配符
wildcard = version_str.endswith(".*") or version_str.endswith("*")
clean_str = version_str.rstrip("*").rstrip(".") if wildcard else version_str
match = package_version_parse_regex.match(clean_str)
if not match:
logger.error(f"未知的版本号字符串: {version_str}")
raise ValueError(f"Invalid version string: {version_str}")
components = match.groupdict()
# 处理 release 段 (允许空字符串)
release_str = components["release"] or "0"
release_segments = [int(seg) for seg in release_str.split(".")]
# 构建命名元组
return VersionComponent(
epoch=int(components["epoch"] or 0),
release=release_segments,
pre_l=components["pre_l"],
pre_n=int(components["pre_n"]) if components["pre_n"] else None,
post_n1=int(components["post_n1"]) if components["post_n1"] else None,
post_l=components["post_l"],
post_n2=int(components["post_n2"]) if components["post_n2"] else None,
dev_l=components["dev_l"],
dev_n=int(components["dev_n"]) if components["dev_n"] else None,
local=components["local"],
is_wildcard=wildcard,
)
def compare_version_objects(v1: VersionComponent, v2: VersionComponent) -> int:
"""比较两个版本字符串 Python 软件包版本号
参数:
v1 (`VersionComponent`):
第 1 个 Python 版本号标识符组件
v2 (`VersionComponent`):
第 2 个 Python 版本号标识符组件
返回值:
`int`: 如果版本号 1 大于 版本号 2, 则返回`1`, 小于则返回`-1`, 如果相等则返回`0`
"""
# 比较 epoch
if v1.epoch != v2.epoch:
return v1.epoch - v2.epoch
# 对其 release 长度, 缺失部分补 0
if len(v1.release) != len(v2.release):
for _ in range(abs(len(v1.release) - len(v2.release))):
if len(v1.release) < len(v2.release):
v1.release.append(0)
else:
v2.release.append(0)
# 比较 release
for n1, n2 in zip(v1.release, v2.release):
if n1 != n2:
return n1 - n2
# 如果 release 长度不同,较短的版本号视为较小 ?
# 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15]
# 计算结果就会变成 len([0, 15, 0]) > len([0, 15])
# 但 0.15.0 和 0.15 实际上是一样的版本
# if len(v1.release) != len(v2.release):
# return len(v1.release) - len(v2.release)
# 比较 pre-release
if v1.pre_l and not v2.pre_l:
return -1 # pre-release 小于正常版本
elif not v1.pre_l and v2.pre_l:
return 1
elif v1.pre_l and v2.pre_l:
pre_order = {
"a": 0,
"b": 1,
"c": 2,
"rc": 3,
"alpha": 0,
"beta": 1,
"pre": 0,
"preview": 0,
}
if pre_order[v1.pre_l] != pre_order[v2.pre_l]:
return pre_order[v1.pre_l] - pre_order[v2.pre_l]
elif v1.pre_n is not None and v2.pre_n is not None:
return v1.pre_n - v2.pre_n
elif v1.pre_n is None and v2.pre_n is not None:
return -1
elif v1.pre_n is not None and v2.pre_n is None:
return 1
# 比较 post-release
if v1.post_n1 is not None:
post_n1 = v1.post_n1
elif v1.post_l:
post_n1 = int(v1.post_n2) if v1.post_n2 else 0
else:
post_n1 = 0
if v2.post_n1 is not None:
post_n2 = v2.post_n1
elif v2.post_l:
post_n2 = int(v2.post_n2) if v2.post_n2 else 0
else:
post_n2 = 0
if post_n1 != post_n2:
return post_n1 - post_n2
# 比较 dev-release
if v1.dev_l and not v2.dev_l:
return -1 # dev-release 小于 post-release 或正常版本
elif not v1.dev_l and v2.dev_l:
return 1
elif v1.dev_l and v2.dev_l:
if v1.dev_n is not None and v2.dev_n is not None:
return v1.dev_n - v2.dev_n
elif v1.dev_n is None and v2.dev_n is not None:
return -1
elif v1.dev_n is not None and v2.dev_n is None:
return 1
# 比较 local version
if v1.local and not v2.local:
return -1 # local version 小于 dev-release 或正常版本
elif not v1.local and v2.local:
return 1
elif v1.local and v2.local:
local1 = v1.local.split(".")
local2 = v2.local.split(".")
# 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0
if len(local1) != len(local2):
for _ in range(abs(len(local1) - len(local2))):
if len(local1) < len(local2):
local1.append(0)
else:
local2.append(0)
for l1, l2 in zip(local1, local2):
if l1.isdigit() and l2.isdigit():
l1, l2 = int(l1), int(l2)
if l1 != l2:
return (l1 > l2) - (l1 < l2)
return len(local1) - len(local2)
return 0 # 版本相同
def compare_versions(version1: str, version2: str) -> int:
"""比较两个版本字符串 Python 软件包版本号
参数:
version1 (`str`):
版本号 1
version2 (`str`):
版本号 2
返回值:
`int`: 如果版本号 1 大于 版本号 2, 则返回`1`, 小于则返回`-1`, 如果相等则返回`0`
"""
v1 = parse_version(version1)
v2 = parse_version(version2)
return compare_version_objects(v1, v2)
def compatible_version_matcher(spec_version: str):
"""PEP 440 兼容性版本匹配 (~= 操作符)
返回值:
`_is_compatible(version_str: str) -> bool`: 一个接受 version_str (`str`) 参数的判断函数
"""
# 解析规范版本
spec = parse_version(spec_version)
# 获取有效release段 (去除末尾的零)
clean_release = []
for num in spec.release:
if num != 0 or (clean_release and clean_release[-1] != 0):
clean_release.append(num)
# 确定最低版本和前缀匹配规则
if len(clean_release) == 0:
logger.error("解析到错误的兼容性发行版本号")
raise ValueError("Invalid version for compatible release clause")
# 生成前缀匹配模板 (忽略后缀)
prefix_length = len(clean_release) - 1
if prefix_length == 0:
# 处理类似 ~= 2 的情况 (实际 PEP 禁止,但这里做容错)
prefix_pattern = [spec.release[0]]
min_version = parse_version(f"{spec.release[0]}")
else:
prefix_pattern = list(spec.release[:prefix_length])
min_version = spec
def _is_compatible(version_str: str) -> bool:
target = parse_version(version_str)
# 主版本前缀检查
target_prefix = target.release[: len(prefix_pattern)]
if target_prefix != prefix_pattern:
return False
# 最低版本检查 (自动忽略 pre/post/dev 后缀)
return compare_version_objects(target, min_version) >= 0
return _is_compatible
def version_match(spec: str, version: str) -> bool:
"""PEP 440 版本前缀匹配
参数:
spec (`str`): 版本匹配表达式 (e.g. '1.1.*')
version (`str`): 需要检测的实际版本号 (e.g. '1.1a1')
返回值:
`bool`: 是否匹配
"""
# 分离通配符和本地版本
spec_parts = spec.split("+", 1)
spec_main = spec_parts[0].rstrip(".*") # 移除通配符
has_wildcard = spec.endswith(".*") and "+" not in spec
# 解析规范版本 (不带通配符)
try:
spec_ver = parse_version(spec_main)
except ValueError:
return False
# 解析目标版本 (忽略本地版本)
target_ver = parse_version(version.split("+", 1)[0])
# 前缀匹配规则
if has_wildcard:
# 生成补零后的 release 段
spec_release = spec_ver.release.copy()
while len(spec_release) < len(target_ver.release):
spec_release.append(0)
# 比较前 N 个 release 段 (N 为规范版本长度)
return (
target_ver.release[: len(spec_ver.release)] == spec_ver.release
and target_ver.epoch == spec_ver.epoch
)
else:
# 严格匹配时使用原比较函数
return compare_versions(spec_main, version) == 0
def is_v1_ge_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于或等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号大于或等于 v2 版本号则返回`True`
e.g.:
1.1, 1.0 -> True
1.0, 1.0 -> True
0.9, 1.0 -> False
"""
return compare_versions(v1, v2) >= 0
def is_v1_gt_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号大于 v2 版本号则返回`True`
e.g.:
1.1, 1.0 -> True
1.0, 1.0 -> False
"""
return compare_versions(v1, v2) > 0
def is_v1_eq_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号等于 v2 版本号则返回`True`
e.g.:
1.0, 1.0 -> True
0.9, 1.0 -> False
1.1, 1.0 -> False
"""
return compare_versions(v1, v2) == 0
def is_v1_lt_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否小于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号小于 v2 版本号则返回`True`
e.g.:
0.9, 1.0 -> True
1.0, 1.0 -> False
"""
return compare_versions(v1, v2) < 0
def is_v1_le_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否小于或等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号小于或等于 v2 版本号则返回`True`
e.g.:
0.9, 1.0 -> True
1.0, 1.0 -> True
1.1, 1.0 -> False
"""
return compare_versions(v1, v2) <= 0
def is_v1_c_eq_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配)
参数:
v1 (`str`):
第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号等于 v2 版本号则返回`True`
e.g.:
1.0*, 1.0a1 -> True
0.9*, 1.0 -> False
"""
func = compatible_version_matcher(v1)
return func(v2)
def version_string_is_canonical(version: str) -> bool:
"""判断版本号标识符是否符合标准
参数:
version (`str`):
版本号字符串
返回值:
`bool`: 如果版本号标识符符合 PEP 440 标准, 则返回`True`
"""
return (
re.match(
r"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$",
version,
)
is not None
)
def is_package_has_version(package: str) -> bool:
"""检查 Python 软件包是否指定版本号
参数:
package (`str`):
Python 软件包名
返回值:
`bool`: 如果 Python 软件包存在版本声明, 如`torch==2.3.0`, 则返回`True`
"""
return package != (
package.replace("===", "")
.replace("~=", "")
.replace("!=", "")
.replace("<=", "")
.replace(">=", "")
.replace("<", "")
.replace(">", "")
.replace("==", "")
)
def get_package_name(package: str) -> str:
"""获取 Python 软件包的包名, 去除末尾的版本声明
参数:
package (`str`):
Python 软件包名
返回值:
`str`: 返回去除版本声明后的 Python 软件包名
"""
return (
package.split("===")[0]
.split("~=")[0]
.split("!=")[0]
.split("<=")[0]
.split(">=")[0]
.split("<")[0]
.split(">")[0]
.split("==")[0]
.strip()
)
def get_package_version(package: str) -> str:
"""获取 Python 软件包的包版本号
参数:
package (`str`):
Python 软件包名
返回值:
`str`: 返回 Python 软件包的包版本号
"""
return (
package.split("===")
.pop()
.split("~=")
.pop()
.split("!=")
.pop()
.split("<=")
.pop()
.split(">=")
.pop()
.split("<")
.pop()
.split(">")
.pop()
.split("==")
.pop()
.strip()
)
WHEEL_PATTERN = r"""
^ # 字符串开始
(?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段)
- # 分隔符
(?: # 版本号和可选构建号组合
(?P<version>[^-]+) # 版本号 (至少一个非连字符段)
(?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头)
)
- # 分隔符
(?P<python>[^-]+) # Python 版本标签
- # 分隔符
(?P<abi>[^-]+) # ABI 标签
- # 分隔符
(?P<platform>[^-]+) # 平台标签
\.whl$ # 固定后缀
"""
def parse_wheel_filename(filename: str) -> str:
"""解析 Python wheel 文件名并返回 distribution 名称
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: distribution 名称, 例如 pydantic
异常:
`ValueError`: 如果文件名不符合 PEP491 规范
"""
match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE)
if not match:
logger.error("未知的 Wheel 文件名: %s", filename)
raise ValueError(f"Invalid wheel filename: {filename}")
return match.group("distribution")
def parse_wheel_version(filename: str) -> str:
"""解析 Python wheel 文件名并返回 version 名称
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: version 名称, 例如 1.10.15
异常:
`ValueError`: 如果文件名不符合 PEP491 规范
"""
match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE)
if not match:
logger.error("未知的 Wheel 文件名: %s", filename)
raise ValueError(f"Invalid wheel filename: {filename}")
return match.group("version")
def parse_wheel_to_package_name(filename: str) -> str:
"""解析 Python wheel 文件名并返回 <distribution>==<version>
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: <distribution>==<version> 名称, 例如 pydantic==1.10.15
"""
distribution = parse_wheel_filename(filename)
version = parse_wheel_version(filename)
return f"{distribution}=={version}"
def remove_optional_dependence_from_package(filename: str) -> str:
"""移除 Python 软件包声明中可选依赖
参数:
filename (`str`):
Python 软件包名
返回值:
`str`: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2
"""
return re.sub(r"\[.*?\]", "", filename)
def parse_requirement_list(requirements: list) -> list:
"""将 Python 软件包声明列表解析成标准 Python 软件包名列表
参数:
requirements (`list`):
Python 软件包名声明列表
e.g:
```python
requirements = [
'torch==2.3.0',
'diffusers[torch]==0.10.2',
'NUMPY',
'-e .',
'--index-url https://pypi.python.org/simple',
'--extra-index-url https://download.pytorch.org/whl/cu124',
'--find-links https://download.pytorch.org/whl/torch_stable.html',
'-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds',
'git+https://github.com/WASasquatch/img2texture.git',
'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl',
'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer',
'protobuf<5,>=4.25.3',
]
```
返回值:
`list`: 将 Python 软件包名声明列表解析成标准声明列表
e.g. 上述例子中的软件包名声明列表将解析成:
```python
requirements = [
'torch==2.3.0',
'diffusers==0.10.2',
'numpy',
'mgds',
'img2texture',
'pydantic==1.10.15',
'prodigy-plus-schedule-free==1.9.1',
'protobuf<5',
'protobuf>=4.25.3',
]
```
"""
package_list = []
canonical_package_list = []
requirement: str
for requirement in requirements:
requirement = requirement.strip()
logger.debug("原始 Python 软件包名: %s", requirement)
if (
requirement is None
or requirement == ""
or requirement.startswith("#")
or "# skip_verify" in requirement
or requirement.startswith("--index-url")
or requirement.startswith("--extra-index-url")
or requirement.startswith("--find-links")
or requirement.startswith("-e .")
):
continue
# -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds
# git+https://github.com/WASasquatch/img2texture.git -> img2texture
# git+https://github.com/deepghs/waifuc -> waifuc
if requirement.startswith("-e git+http") or requirement.startswith("git+http"):
egg_match = re.search(r"egg=([^#&]+)", requirement)
if egg_match:
package_list.append(egg_match.group(1).split("-")[0])
continue
package_name = os.path.basename(requirement)
package_name = (
package_name.split(".git")[0]
if package_name.endswith(".git")
else package_name
)
package_list.append(package_name)
continue
# https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15
if requirement.startswith("https://") or requirement.startswith("http://"):
package_name = parse_wheel_to_package_name(os.path.basename(requirement))
package_list.append(package_name)
continue
# 常规 Python 软件包声明
# prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1
cleaned_requirements = re.sub(r"\s*#.*$", "", requirement).strip().split(",")
if len(cleaned_requirements) > 1:
package_name = get_package_name(cleaned_requirements[0].strip())
for package_name_with_version_marked in cleaned_requirements:
version_symbol = str.replace(
package_name_with_version_marked, package_name, "", 1
)
format_package_name = remove_optional_dependence_from_package(
f"{package_name}{version_symbol}".strip()
)
package_list.append(format_package_name)
else:
format_package_name = remove_optional_dependence_from_package(
cleaned_requirements[0].strip()
)
package_list.append(format_package_name)
# 处理包名大小写并统一成小写, 并去除前后空格
for p in package_list:
p: str = p.lower().strip()
logger.debug("预处理后的 Python 软件包名: %s", p)
if not is_package_has_version(p):
logger.debug("%s 无版本声明", p)
canonical_package_list.append(p)
continue
if version_string_is_canonical(get_package_version(p)):
canonical_package_list.append(p)
else:
logger.debug("%s 软件包名的版本不符合标准", p)
return canonical_package_list
def remove_duplicate_object_from_list(origin: list) -> list:
"""对`list`进行去重
参数:
origin (`list`):
原始的`list`
返回值:
`list`: 去重后的`list`, e.g. [1, 2, 3, 2] -> [1, 2, 3]
"""
return list(set(origin))
def read_packages_from_requirements_file(file_path: Union[str, Path]) -> list:
"""从 requirements.txt 文件中读取 Python 软件包版本声明列表
参数:
file_path (`str`, `Path`):
requirements.txt 文件路径
返回值:
`list`: 从 requirements.txt 文件中读取的 Python 软件包声明列表
"""
try:
with open(file_path, "r", encoding="utf-8") as f:
return f.readlines()
except Exception as e:
logger.error("打开 %s 时出现错误: %s\n请检查文件是否出现损坏", file_path, e)
return []
def get_package_version_from_library(package_name: str) -> Union[str, None]:
"""获取已安装的 Python 软件包版本号
参数:
package_name (`str`):
返回值:
(`str` | `None`): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回`None`
"""
try:
ver = importlib.metadata.version(package_name)
except:
ver = None
if ver is None:
try:
ver = importlib.metadata.version(package_name.lower())
except:
ver = None
if ver is None:
try:
ver = importlib.metadata.version(package_name.replace("_", "-"))
except:
ver = None
return ver
class ComponentEnvironmentDetails(TypedDict):
"""ComfyUI 组件的环境信息结构"""
requirement_path: str # 依赖文件路径
is_disabled: bool # 组件是否禁用
requires: list[str] # 需要的依赖列表
has_missing_requires: bool # 是否存在缺失依赖
missing_requires: list[str] # 具体缺失的依赖项
has_conflict_requires: bool # 是否存在冲突依赖
conflict_requires: list[str] # 具体冲突的依赖项
ComfyUIEnvironmentComponent = dict[
str, ComponentEnvironmentDetails
] # ComfyUI 环境组件表字典
def create_comfyui_environment_dict(
comfyui_path: Union[str, Path],
) -> ComfyUIEnvironmentComponent:
"""创建 ComfyUI 环境组件表字典
参数:
comfyui_path (`str`, `Path`):
ComfyUI 根路径
返回值:
`ComfyUIEnvironmentComponent`: ComfyUI 环境组件表字典
"""
comfyui_env_data: ComfyUIEnvironmentComponent = {
"ComfyUI": {
"requirement_path": os.path.join(comfyui_path, "requirements.txt"),
"is_disabled": False,
"requires": [],
"has_missing_requires": False,
"missing_requires": [],
"has_conflict_requires": False,
"conflict_requires": [],
},
}
custom_nodes_path = os.path.join(comfyui_path, "custom_nodes")
for custom_node in os.listdir(custom_nodes_path):
if os.path.isfile(os.path.join(custom_nodes_path, custom_node)):
continue
custom_node_requirement_path = os.path.join(
custom_nodes_path, custom_node, "requirements.txt"
)
custom_node_is_disabled = True if custom_node.endswith(".disabled") else False
comfyui_env_data[custom_node] = {
"requirement_path": (
custom_node_requirement_path
if os.path.exists(custom_node_requirement_path)
else None
),
"is_disabled": custom_node_is_disabled,
"requires": [],
"has_missing_requires": False,
"missing_requires": [],
"has_conflict_requires": False,
"conflict_requires": [],
}
return comfyui_env_data
def update_comfyui_environment_dict(
env_data: ComfyUIEnvironmentComponent,
component_name: str,
requirement_path: Optional[str] = None,
is_disabled: Optional[bool] = None,
requires: Optional[list[str]] = None,
has_missing_requires: Optional[bool] = None,
missing_requires: Optional[list[str]] = None,
has_conflict_requires: Optional[bool] = None,
conflict_requires: Optional[list[str]] = None,
) -> None:
"""更新 ComfyUI 环境组件表字典
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
component_name (`str`):
ComfyUI 组件名称
requirement_path (`str`, `None`):
ComfyUI 组件依赖文件路径
is_disabled (`bool`, `None`):
ComfyUI 组件是否被禁用
requires (`list[str]`, `None`):
ComfyUI 组件需要的依赖列表
has_missing_requires (`bool`, `None`):
ComfyUI 组件是否存在缺失依赖
missing_requires (`list[str]`, `None`):
ComfyUI 组件缺失依赖列表
has_conflict_requires (`bool`, `None`):
ComfyUI 组件是否存在冲突依赖
conflict_requires (`list[str]`, `None`):
ComfyUI 组件冲突依赖列表
"""
env_data[component_name] = {
"requirement_path": (
requirement_path
if requirement_path
else env_data.get(component_name).get("requirement_path")
),
"is_disabled": (
is_disabled
if is_disabled
else env_data.get(component_name).get("is_disabled")
),
"requires": (
requires if requires else env_data.get(component_name).get("requires")
),
"has_missing_requires": (
has_missing_requires
if has_missing_requires
else env_data.get(component_name).get("has_missing_requires")
),
"missing_requires": (
missing_requires
if missing_requires
else env_data.get(component_name).get("missing_requires")
),
"has_conflict_requires": (
has_conflict_requires
if has_conflict_requires
else env_data.get(component_name).get("has_conflict_requires")
),
"conflict_requires": (
conflict_requires
if conflict_requires
else env_data.get(component_name).get("conflict_requires")
),
}
def update_comfyui_component_requires_list(
env_data: ComfyUIEnvironmentComponent,
) -> None:
"""更新 ComfyUI 环境组件表字典, 根据字典中的 requirement_path 确定 Python 软件包版本声明文件, 并解析后写入 requires 字段
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
"""
for component_name, details in env_data.items():
if details.get("is_disabled"):
continue
requirement_path = details.get("requirement_path")
if requirement_path is None:
continue
origin_requires = read_packages_from_requirements_file(requirement_path)
requires = parse_requirement_list(origin_requires)
update_comfyui_environment_dict(
env_data=env_data,
component_name=component_name,
requires=requires,
)
def update_comfyui_component_missing_requires_list(
env_data: ComfyUIEnvironmentComponent,
) -> None:
"""更新 ComfyUI 环境组件表字典, 根据字典中的 requires 检查缺失的 Python 软件包, 并保存到 missing_requires 字段和设置 has_missing_requires 状态
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
"""
for component_name, details in env_data.items():
if details.get("is_disabled"):
continue
requires = details.get("requires")
has_missing_requires = False
missing_requires = []
for package in requires:
if not is_package_installed(package):
has_missing_requires = True
missing_requires.append(package)
update_comfyui_environment_dict(
env_data=env_data,
component_name=component_name,
has_missing_requires=has_missing_requires,
missing_requires=missing_requires,
)
def update_comfyui_component_conflict_requires_list(
env_data: ComfyUIEnvironmentComponent, conflict_package_list: list
) -> None:
"""更新 ComfyUI 环境组件表字典, 根据 conflicconflict_package_listt_package 检查 ComfyUI 组件冲突的 Python 软件包, 并保存到 conflict_requires 字段和设置 has_conflict_requires 状态
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
conflict_package_list (`list`):
冲突的 Python 软件包列表
"""
for component_name, details in env_data.items():
if details.get("is_disabled"):
continue
requires = details.get("requires")
has_conflict_requires = False
conflict_requires = []
for conflict_package in conflict_package_list:
for package in requires:
if is_package_has_version(package) and get_package_name(
conflict_package
) == get_package_name(package):
has_conflict_requires = True
conflict_requires.append(package)
update_comfyui_environment_dict(
env_data=env_data,
component_name=component_name,
has_conflict_requires=has_conflict_requires,
conflict_requires=conflict_requires,
)
def get_comfyui_component_requires_list(
env_data: ComfyUIEnvironmentComponent,
) -> list:
"""从 ComfyUI 环境组件表字典读取所有组件的 requires
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
返回值:
`list`: ComfyUI 环境组件的 Python 软件包列表
"""
package_list = []
for _, details in env_data.items():
if details.get("is_disabled"):
continue
package_list += details.get("requires")
return remove_duplicate_object_from_list(package_list)
def statistical_need_install_require_component(
env_data: ComfyUIEnvironmentComponent,
) -> list:
"""根据 ComfyUI 环境组件表字典中的 has_missing_requires 和 has_conflict_requires 字段确认需要安装依赖的列表
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
返回值:
`list`: ComfyUI 环境组件的依赖文件路径列表
"""
requirement_list = []
for _, details in env_data.items():
if details.get("has_missing_requires") or details.get("has_conflict_requires"):
requirement_list.append(Path(details.get("requirement_path")).as_posix())
return requirement_list
def statistical_has_conflict_component(
env_data: ComfyUIEnvironmentComponent, conflict_package_list: list
) -> list:
"""根据 ComfyUI 环境组件表字典中的 has_conflict_requires 字段确认需要安装依赖的列表
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
返回值:
`list`: ComfyUI 环境组件的依赖文件路径列表
"""
content = []
for conflict_package in conflict_package_list:
content.append(get_package_name(f"{conflict_package}:"))
for component_name, details in env_data.items():
for conflict_component_package in details.get("conflict_requires"):
if get_package_name(conflict_component_package) == conflict_package:
content.append(f" - {component_name}: {conflict_component_package}")
return content[:-1] if len(content) > 0 and content[-1] == "" else content
def is_package_installed(package: str) -> bool:
"""判断 Python 软件包是否已安装在环境中
参数:
package (`str`):
Python 软件包名
返回值:
`bool`: 如果 Python 软件包未安装或者未安装正确的版本, 则返回`False`
"""
# 分割 Python 软件包名和版本号
if "===" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("===")]
elif "~=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("~=")]
elif "!=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("!=")]
elif "<=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("<=")]
elif ">=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split(">=")]
elif "<" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("<")]
elif ">" in package:
pkg_name, pkg_version = [x.strip() for x in package.split(">")]
elif "==" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("==")]
else:
pkg_name, pkg_version = package.strip(), None
env_pkg_version = get_package_version_from_library(pkg_name)
logger.debug(
"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s",
pkg_name,
env_pkg_version,
pkg_version,
)
if env_pkg_version is None:
logger.debug("%s 未安装到环境中", package)
return False
if pkg_version is not None:
# ok = env_pkg_version === / == pkg_version
if "===" in package or "==" in package:
logger.debug("包含条件: === / ==")
if is_v1_eq_v2(env_pkg_version, pkg_version):
logger.debug("%s == %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version ~= pkg_version
if "~=" in package:
logger.debug("包含条件: ~=")
if is_v1_c_eq_v2(pkg_version, env_pkg_version):
logger.debug("%s ~= %s", pkg_version, env_pkg_version)
return True
# ok = env_pkg_version != pkg_version
if "!=" in package:
logger.debug("包含条件: !=")
if not is_v1_eq_v2(env_pkg_version, pkg_version):
logger.debug("%s != %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version <= pkg_version
if "<=" in package:
logger.debug("包含条件: <=")
if is_v1_le_v2(env_pkg_version, pkg_version):
logger.debug("%s <= %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version >= pkg_version
if ">=" in package:
logger.debug("包含条件: >=")
if is_v1_ge_v2(env_pkg_version, pkg_version):
logger.debug("%s >= %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version < pkg_version
if "<" in package:
logger.debug("包含条件: <")
if is_v1_lt_v2(env_pkg_version, pkg_version):
logger.debug("%s < %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version > pkg_version
if ">" in package:
logger.debug("包含条件: >")
if is_v1_gt_v2(env_pkg_version, pkg_version):
logger.debug("%s > %s", env_pkg_version, pkg_version)
return True
logger.debug("%s 需要安装正确版本", package)
return False
return True
def fitter_has_version_package(package_list: list) -> list:
"""过滤不包含版本的 Python 软件包, 仅保留包含版本号声明的 Python 软件包
参数:
package_list (`list`):
Python 软件包列表
返回值:
`list`: 仅包含版本号的 Python 软件包列表
"""
return [p for p in package_list if is_package_has_version(p)]
def detect_conflict_package(pkg1: str, pkg2: str) -> bool:
"""检测 Python 软件包版本号声明是否存在冲突
参数:
pkg1 (`str`):
第 1 个 Python 软件包名称
pkg2 (`str`):
第 2 个 Python 软件包名称
返回值:
`bool`: 如果 Python 软件包版本声明出现冲突则返回`True`
"""
# 进行 2 次循环, 第 2 次循环时交换版本后再进行判断
for i in range(2):
if i == 1:
if pkg1 == pkg2:
break
else:
pkg1, pkg2 = pkg2, pkg1
ver1 = get_package_version(pkg1)
ver2 = get_package_version(pkg2)
logger.debug(
"冲突依赖检测: pkg1: %s, pkg2: %s, ver1: %s, ver2: %s",
pkg1,
pkg2,
ver1,
ver2,
)
# >=, <=
if ">=" in pkg1 and "<=" in pkg2:
if is_v1_gt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2
)
return True
# >=, <
if ">=" in pkg1 and "<" in pkg2 and "=" not in pkg2:
if is_v1_ge_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2
)
return True
# >, <=
if ">" in pkg1 and "=" not in pkg1 and "<=" in pkg2:
if is_v1_ge_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2
)
return True
# >, <
if ">" in pkg1 and "=" not in pkg1 and "<" in pkg2 and "=" not in pkg2:
if is_v1_ge_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2
)
return True
# >, ==
if ">" in pkg1 and "=" not in pkg1 and "==" in pkg2:
if is_v1_ge_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2
)
return True
# >=, ==
if ">=" in pkg1 and "==" in pkg2:
if is_v1_gt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2
)
return True
# <, ==
if "<" in pkg1 and "=" not in pkg1 and "==" in pkg2:
if is_v1_le_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s <= %s", pkg1, pkg2, ver1, ver2
)
return True
# <=, ==
if "<=" in pkg1 and "==" in pkg2:
if is_v1_lt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s < %s", pkg1, pkg2, ver1, ver2
)
return True
# !=, ==
if "!=" in pkg1 and "==" in pkg2:
if is_v1_eq_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s == %s", pkg1, pkg2, ver1, ver2
)
return True
# >, ~=
if ">" in pkg1 and "=" not in pkg1 and "~=" in pkg2:
if is_v1_ge_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s >= %s", pkg1, pkg2, ver1, ver2
)
return True
# >=, ~=
if ">=" in pkg1 and "~=" in pkg2:
if is_v1_gt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2
)
return True
# <, ~=
if "<" in pkg1 and "=" not in pkg1 and "~=" in pkg2:
if is_v1_le_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s <= %s", pkg1, pkg2, ver1, ver2
)
return True
# <=, ~=
if "<=" in pkg1 and "~=" in pkg2:
if is_v1_lt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s < %s", pkg1, pkg2, ver1, ver2
)
return True
# !=, ~=
# 这个也没什么必要
# if '!=' in pkg1 and '~=' in pkg2:
# if is_v1_c_eq_v2(ver1, ver2):
# logger.debug(
# '冲突依赖: %s, %s, 版本冲突: %s ~= %s',
# pkg1, pkg2, ver1, ver2)
# return True
# ~=, == / ~=, ===
if ("~=" in pkg1 and "==" in pkg2) or ("~=" in pkg1 and "===" in pkg2):
if is_v1_gt_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s > %s", pkg1, pkg2, ver1, ver2
)
return True
# ~=, ~=
# ~= 类似 >= V.N, == V.*, 所以该部分的比较没必要使用
# if '~=' in pkg1 and '~=' in pkg2:
# if not is_v1_c_eq_v2(ver1, ver2):
# logger.debug(
# '冲突依赖: %s, %s, 版本冲突: %s !~= %s',
# pkg1, pkg2, ver1, ver2)
# return True
# ==, == / ===, ===
if ("==" in pkg1 and "==" in pkg2) or ("===" in pkg1 and "===" in pkg2):
if not is_v1_eq_v2(ver1, ver2):
logger.debug(
"冲突依赖: %s, %s, 版本冲突: %s != %s", pkg1, pkg2, ver1, ver2
)
return True
return False
def detect_conflict_package_from_list(package_list: list) -> list:
"""检测 Python 软件包版本声明列表中存在冲突的软件包
参数:
package_list (`list`):
Python 软件包版本声明列表
返回值:
`list`: 冲突的 Python 软件包列表
"""
conflict_package = []
for i in package_list:
for j in package_list:
if get_package_name(i) == get_package_name(j) and detect_conflict_package(
i, j
):
conflict_package.append(get_package_name(i))
return remove_duplicate_object_from_list(conflict_package)
def display_comfyui_environment_dict(
env_data: ComfyUIEnvironmentComponent,
) -> None:
"""列出 ComfyUI 环境组件字典内容
参数:
env_data (`ComfyUIEnvironmentComponent`):
ComfyUI 环境组件表字典
"""
logger.debug("ComfyUI 环境组件表")
for component_name, details in env_data.items():
logger.debug("Component: %s", component_name)
logger.debug(" - requirement_path: %s", details["requirement_path"])
logger.debug(" - is_disabled: %s", details["is_disabled"])
logger.debug(" - requires: %s", details["requires"])
logger.debug(" - has_missing_requires: %s", details["has_missing_requires"])
logger.debug(" - missing_requires: %s", details["missing_requires"])
logger.debug(" - has_conflict_requires: %s", details["has_conflict_requires"])
logger.debug(" - conflict_requires: %s", details["conflict_requires"])
print()
def display_check_result(requirement_list: list, conflict_result: list) -> None:
"""显示 ComfyUI 运行环境检查结果
参数:
requirement_list (`list`):
ComfyUI 组件依赖文件路径列表
conflict_result (`list`):
冲突组件统计信息
"""
if len(requirement_list) > 0:
logger.debug("需要安装 ComfyUI 组件列表")
for requirement in requirement_list:
component_name = requirement.split("/")[-2]
logger.debug("%s:", component_name)
logger.debug(" - %s", requirement)
print()
if len(conflict_result) > 0:
logger.debug("ComfyUI 冲突组件")
for text in conflict_result:
logger.debug(text)
print()
def write_content_to_file(content: list, path: Union[str, Path]) -> None:
"""将内容列表写入到文件中
参数:
content (`list`):
内容列表
path (`str`, `Path`):
保存内容的路径
"""
if len(content) == 0:
return
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path, exist_ok=True)
try:
logger.debug("写入文件到 %s", path)
with open(path, "w", encoding="utf-8") as f:
for item in content:
f.write(item + "\n")
except Exception as e:
logger.error("写入文件到 %s 时出现了错误: %s", path, e)
def main() -> None:
comfyui_root_path = COMMAND_ARGS.comfyui_path
comfyui_conflict_notice = COMMAND_ARGS.conflict_depend_notice_path
comfyui_requirement_path = COMMAND_ARGS.requirement_list_path
debug_mode = COMMAND_ARGS.debug_mode
if not os.path.exists(os.path.join(comfyui_root_path, "requirements.txt")):
logger.error("ComfyUI 依赖文件缺失, 请检查 ComfyUI 是否安装完整")
sys.exit(1)
if not os.path.exists(os.path.join(comfyui_root_path, "custom_nodes")):
logger.error("ComfyUI 自定义节点文件夹未找到, 请检查 ComfyUI 是否安装完整")
sys.exit(1)
if not comfyui_conflict_notice or not comfyui_requirement_path:
logger.error(
"未配置 --conflict-depend-notice-path / --requirement-list-path, 无法进行环境检测"
)
sys.exit(1)
logger.debug("检测 ComfyUI 环境中")
env_data = create_comfyui_environment_dict(comfyui_root_path)
update_comfyui_component_requires_list(env_data)
update_comfyui_component_missing_requires_list(env_data)
pkg_list = get_comfyui_component_requires_list(env_data)
has_version_pkg = fitter_has_version_package(pkg_list)
conflict_pkg = detect_conflict_package_from_list(has_version_pkg)
update_comfyui_component_conflict_requires_list(env_data, conflict_pkg)
req_list = statistical_need_install_require_component(env_data)
conflict_info = statistical_has_conflict_component(env_data, conflict_pkg)
write_content_to_file(conflict_info, comfyui_conflict_notice)
write_content_to_file(req_list, comfyui_requirement_path)
if debug_mode:
display_comfyui_environment_dict(env_data)
display_check_result(req_list, conflict_info)
logger.debug("ComfyUI 环境检查完成")
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/check_comfyui_env.py
|
Python
|
agpl-3.0
| 52,426
|
try:
import controlnet_aux # noqa: F401
success = True
except:
success = False
if not success:
from importlib.metadata import requires
try:
invokeai_requires = requires("invokeai")
except:
invokeai_requires = []
controlnet_aux_ver = None
for req in invokeai_requires:
if req.startswith("controlnet-aux=="):
controlnet_aux_ver = req.split(";")[0].strip()
break
if success:
print(None)
else:
if controlnet_aux_ver is None:
print("controlnet_aux")
else:
print(controlnet_aux_ver)
|
2301_81996401/term-sd
|
python_modules/check_controlnet_aux.py
|
Python
|
agpl-3.0
| 593
|
import os
import importlib.util
import subprocess
# Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
def get_gpu_names():
if os.name == "nt":
import ctypes
# Define necessary C structures and types
class DISPLAY_DEVICEA(ctypes.Structure):
_fields_ = [
("cb", ctypes.c_ulong),
("DeviceName", ctypes.c_char * 32),
("DeviceString", ctypes.c_char * 128),
("StateFlags", ctypes.c_ulong),
("DeviceID", ctypes.c_char * 128),
("DeviceKey", ctypes.c_char * 128),
]
# Load user32.dll
user32 = ctypes.windll.user32
# Call EnumDisplayDevicesA
def enum_display_devices():
device_info = DISPLAY_DEVICEA()
device_info.cb = ctypes.sizeof(device_info)
device_index = 0
gpu_names = set()
while user32.EnumDisplayDevicesA(
None, device_index, ctypes.byref(device_info), 0
):
device_index += 1
gpu_names.add(device_info.DeviceString.decode("utf-8"))
return gpu_names
return enum_display_devices()
else:
gpu_names = set()
out = subprocess.check_output(["nvidia-smi", "-L"])
for l in out.split(b"\n"):
if len(l) > 0:
gpu_names.add(l.decode("utf-8").split(" (UUID")[0])
return gpu_names
blacklist = {
"GeForce GTX TITAN X",
"GeForce GTX 980",
"GeForce GTX 970",
"GeForce GTX 960",
"GeForce GTX 950",
"GeForce 945M",
"GeForce 940M",
"GeForce 930M",
"GeForce 920M",
"GeForce 910M",
"GeForce GTX 750",
"GeForce GTX 745",
"Quadro K620",
"Quadro K1200",
"Quadro K2200",
"Quadro M500",
"Quadro M520",
"Quadro M600",
"Quadro M620",
"Quadro M1000",
"Quadro M1200",
"Quadro M2000",
"Quadro M2200",
"Quadro M3000",
"Quadro M4000",
"Quadro M5000",
"Quadro M5500",
"Quadro M6000",
"GeForce MX110",
"GeForce MX130",
"GeForce 830M",
"GeForce 840M",
"GeForce GTX 850M",
"GeForce GTX 860M",
"GeForce GTX 1650",
"GeForce GTX 1630",
"Tesla M4",
"Tesla M6",
"Tesla M10",
"Tesla M40",
"Tesla M60",
}
def cuda_malloc_supported():
try:
names = get_gpu_names()
except:
names = set()
for x in names:
if "NVIDIA" in x:
for b in blacklist:
if b in x:
return False
return True
def is_nvidia_device():
try:
names = get_gpu_names()
except:
names = set()
for x in names:
if "NVIDIA" in x:
return True
return False
def get_pytorch_cuda_alloc_conf(is_cuda=True):
if is_nvidia_device():
if cuda_malloc_supported():
if is_cuda:
return "cuda_malloc"
else:
return "pytorch_malloc"
else:
return "pytorch_malloc"
else:
return None
def main():
try:
version = ""
torch_spec = importlib.util.find_spec("torch")
for folder in torch_spec.submodule_search_locations:
ver_file = os.path.join(folder, "version.py")
if os.path.isfile(ver_file):
spec = importlib.util.spec_from_file_location(
"torch_version_import", ver_file
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
version = module.__version__
if int(version[0]) >= 2: # enable by default for torch version 2.0 and up
if "+cu" in version: # only on cuda torch
print(get_pytorch_cuda_alloc_conf())
else:
print(get_pytorch_cuda_alloc_conf(False))
else:
print(None)
except Exception as _:
print(None)
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/check_cuda_malloc_avaliable.py
|
Python
|
agpl-3.0
| 4,067
|
from importlib.metadata import version
try:
tmp = version("invokeai")
print(True)
except:
print(False)
|
2301_81996401/term-sd
|
python_modules/check_invokeai_installed.py
|
Python
|
agpl-3.0
| 116
|
import re
import argparse
import importlib.metadata
from pathlib import Path
from enum import Enum
def get_args() -> argparse.Namespace:
"""获取命令行参数
:return `argparse.Namespace`: 命令行参数命名空间
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--ignore-ort-install",
action="store_true",
help="忽略 onnxruntime-gpu 未安装的状态, 强制进行检查",
)
return parser.parse_args()
def get_onnxruntime_version_file() -> Path | None:
"""获取记录 onnxruntime 版本的文件路径
:return Path | None: 记录 onnxruntime 版本的文件路径
"""
package = "onnxruntime-gpu"
version_file = "onnxruntime/capi/version_info.py"
try:
util = [p for p in importlib.metadata.files(package) if version_file in str(p)][
0
]
info_path = Path(util.locate())
except Exception as _:
info_path = None
return info_path
def get_onnxruntime_support_cuda_version() -> tuple[str | None, str | None]:
"""获取 onnxruntime 支持的 CUDA, cuDNN 版本
:return tuple[str | None, str | None]: onnxruntime 支持的 CUDA, cuDNN 版本
"""
ver_path = get_onnxruntime_version_file()
cuda_ver = None
cudnn_ver = None
try:
with open(ver_path, "r", encoding="utf8") as f:
for line in f:
if "cuda_version" in line:
cuda_ver = get_value_from_variable(line, "cuda_version")
if "cudnn_version" in line:
cudnn_ver = get_value_from_variable(line, "cudnn_version")
except Exception as _:
pass
return cuda_ver, cudnn_ver
def get_value_from_variable(content: str, var_name: str) -> str | None:
"""从字符串 (Python 代码片段) 中找出指定字符串变量的值
:param content(str): 待查找的内容
:param var_name(str): 待查找的字符串变量
:return str | None: 返回字符串变量的值
"""
pattern = rf'{var_name}\s*=\s*"([^"]+)"'
match = re.search(pattern, content)
return match.group(1) if match else None
def compare_versions(version1: str, version2: str) -> int:
"""对比两个版本号大小
:param version1(str): 第一个版本号
:param version2(str): 第二个版本号
:return int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样
"""
# 将版本号拆分成数字列表
try:
nums1 = (
re.sub(r"[a-zA-Z]+", "", version1)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
nums2 = (
re.sub(r"[a-zA-Z]+", "", version2)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
except Exception as _:
return 0
for i in range(max(len(nums1), len(nums2))):
num1 = int(nums1[i]) if i < len(nums1) else 0 # 如果版本号 1 的位数不够, 则补 0
num2 = int(nums2[i]) if i < len(nums2) else 0 # 如果版本号 2 的位数不够, 则补 0
if num1 == num2:
continue
elif num1 > num2:
return 1 # 版本号 1 更大
else:
return -1 # 版本号 2 更大
return 0 # 版本号相同
def get_torch_cuda_ver() -> tuple[str | None, str | None, str | None]:
"""获取 Torch 的本体, CUDA, cuDNN 版本
:return tuple[str | None, str | None, str | None]: Torch, CUDA, cuDNN 版本
"""
try:
import torch
torch_ver = torch.__version__
cuda_ver = torch.version.cuda
cudnn_ver = torch.backends.cudnn.version()
return (
str(torch_ver) if torch_ver is not None else None,
str(cuda_ver) if cuda_ver is not None else None,
str(cudnn_ver) if cudnn_ver is not None else None,
)
except Exception as _:
return None, None, None
class OrtType(str, Enum):
"""onnxruntime-gpu 的类型
版本说明:
- CU121CUDNN8: CUDA 12.1 + cuDNN8
- CU121CUDNN9: CUDA 12.1 + cuDNN9
- CU118: CUDA 11.8
"""
CU121CUDNN8 = "cu121cudnn8"
CU121CUDNN9 = "cu121cudnn9"
CU118 = "cu118"
def __str__(self):
return self.value
def need_install_ort_ver(ignore_ort_install: bool = True) -> OrtType | None:
"""判断需要安装的 onnxruntime 版本
:param ignore_ort_install(bool): 当 onnxruntime 未安装时跳过检查
:return OrtType: 需要安装的 onnxruntime-gpu 类型
"""
# 检测是否安装了 Torch
torch_ver, cuda_ver, cuddn_ver = get_torch_cuda_ver()
# 缺少 Torch / CUDA / cuDNN 版本时取消判断
if torch_ver is None or cuda_ver is None or cuddn_ver is None:
if not ignore_ort_install:
try:
_ = importlib.metadata.version("onnxruntime-gpu")
except Exception as _:
# onnxruntime-gpu 没有安装时
return OrtType.CU121CUDNN9
return None
# onnxruntime 记录的 cuDNN 支持版本只有一位数, 所以 Torch 的 cuDNN 版本只能截取一位
cuddn_ver = cuddn_ver[0]
# 检测是否安装了 onnxruntime-gpu
ort_support_cuda_ver, ort_support_cudnn_ver = get_onnxruntime_support_cuda_version()
# 通常 onnxruntime 的 CUDA 版本和 cuDNN 版本会同时存在, 所以只需要判断 CUDA 版本是否存在即可
if ort_support_cuda_ver is not None:
# 当 onnxruntime 已安装
# 判断 Torch 中的 CUDA 版本
if compare_versions(cuda_ver, "12.0") >= 0:
# CUDA >= 12.0
# 比较 onnxtuntime 支持的 CUDA 版本是否和 Torch 中所带的 CUDA 版本匹配
if compare_versions(ort_support_cuda_ver, "12.0") >= 0:
# CUDA 版本为 12.x, torch 和 ort 的 CUDA 版本匹配
# 判断 Torch 和 onnxruntime 的 cuDNN 是否匹配
if compare_versions(ort_support_cudnn_ver, cuddn_ver) > 0:
# ort cuDNN 版本 > torch cuDNN 版本
return OrtType.CU121CUDNN8
elif compare_versions(ort_support_cudnn_ver, cuddn_ver) < 0:
# ort cuDNN 版本 < torch cuDNN 版本
return OrtType.CU121CUDNN9
else:
# 版本相等, 无需重装
return None
else:
# CUDA 版本非 12.x, 不匹配
if compare_versions(cuddn_ver, "8") > 0:
return OrtType.CU121CUDNN9
else:
return OrtType.CU121CUDNN8
else:
# CUDA <= 11.8
if compare_versions(ort_support_cuda_ver, "12.0") < 0:
return None
else:
return OrtType.CU118
else:
if ignore_ort_install:
return None
if compare_versions(cuda_ver, "12.0") >= 0:
if compare_versions(cuddn_ver, "8") > 0:
return OrtType.CU121CUDNN9
else:
return OrtType.CU121CUDNN8
else:
return OrtType.CU118
if __name__ == "__main__":
arg = get_args()
print(need_install_ort_ver(not arg.ignore_ort_install))
|
2301_81996401/term-sd
|
python_modules/check_onnxruntime_gpu.py
|
Python
|
agpl-3.0
| 7,368
|
import re
import argparse
from importlib.metadata import version
def get_args() -> argparse.Namespace:
"""获取命令行参数
:return `argparse.Namespace`: 命令行参数命名空间
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--pip-mininum-ver", type=str, default="25.0", help="Pip 最低版本"
)
return parser.parse_args()
def compare_versions(version1: str, version2: str) -> int:
"""对比两个版本号大小
:param version1(str): 第一个版本号
:param version2(str): 第二个版本号
:return int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样
"""
# 将版本号拆分成数字列表
try:
nums1 = (
re.sub(r"[a-zA-Z]+", "", version1)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
nums2 = (
re.sub(r"[a-zA-Z]+", "", version2)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
except Exception as _:
return 0
for i in range(max(len(nums1), len(nums2))):
num1 = int(nums1[i]) if i < len(nums1) else 0 # 如果版本号 1 的位数不够, 则补 0
num2 = int(nums2[i]) if i < len(nums2) else 0 # 如果版本号 2 的位数不够, 则补 0
if num1 == num2:
continue
elif num1 > num2:
return 1 # 版本号 1 更大
else:
return -1 # 版本号 2 更大
return 0 # 版本号相同
def need_upgrade_pip_ver() -> bool:
arg = get_args()
try:
pip_ver = version("pip")
except Exception as _:
return False
if compare_versions(pip_ver, arg.pip_mininum_ver) < 0:
return True
return False
if __name__ == "__main__":
print(need_upgrade_pip_ver())
|
2301_81996401/term-sd
|
python_modules/check_pip_need_upgrade.py
|
Python
|
agpl-3.0
| 1,949
|
import os
import pathlib
import json
import argparse
from pathlib import Path
# 参数输入
def get_args():
parser = argparse.ArgumentParser()
normalized_filepath = lambda filepath: str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--config-path",
type=normalized_filepath,
default=None,
help="SD WebUI 配置文件路径",
)
parser.add_argument("--extension", type=str, default=None, help="SD WebUI 插件名称")
return parser.parse_args()
def get_key_map(file_path):
file_name = pathlib.Path(file_path)
if os.path.exists(file_name):
try:
with open(file_name, "r", encoding="utf8") as file:
data = json.load(file)
except Exception:
# json 文件格式出现问题
data = {}
else:
data = {}
return data
def search_key(data, key, value):
key_map = data.get(key)
if key_map is not None:
for i in key_map:
if value in i:
return True
return False
else:
return False
if __name__ == "__main__":
args = get_args()
json_path = args.config_path
key_name = "disabled_extensions"
extension_name = args.extension
if search_key(get_key_map(json_path), key_name, extension_name):
print(True)
else:
print(False)
|
2301_81996401/term-sd
|
python_modules/check_sd_webui_extension_disabled.py
|
Python
|
agpl-3.0
| 1,377
|
import re
import argparse
from importlib.metadata import version
def get_args() -> argparse.Namespace:
"""获取命令行参数
:return `argparse.Namespace`: 命令行参数命名空间
"""
parser = argparse.ArgumentParser()
parser.add_argument("--uv-mininum-ver", type=str, default="0.1", help="uv 最低版本")
return parser.parse_args()
def compare_versions(version1: str, version2: str) -> int:
"""对比两个版本号大小
:param version1(str): 第一个版本号
:param version2(str): 第二个版本号
:return int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样
"""
# 将版本号拆分成数字列表
try:
nums1 = (
re.sub(r"[a-zA-Z]+", "", version1)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
nums2 = (
re.sub(r"[a-zA-Z]+", "", version2)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
except Exception as _:
return 0
for i in range(max(len(nums1), len(nums2))):
num1 = int(nums1[i]) if i < len(nums1) else 0 # 如果版本号 1 的位数不够, 则补 0
num2 = int(nums2[i]) if i < len(nums2) else 0 # 如果版本号 2 的位数不够, 则补 0
if num1 == num2:
continue
elif num1 > num2:
return 1 # 版本号 1 更大
else:
return -1 # 版本号 2 更大
return 0 # 版本号相同
def is_uv_need_update() -> bool:
arg = get_args()
try:
uv_ver = version("uv")
except Exception as _:
return True
if compare_versions(uv_ver, arg.uv_mininum_ver) < 0:
return True
return False
if __name__ == "__main__":
print(is_uv_need_update())
|
2301_81996401/term-sd
|
python_modules/check_uv_version.py
|
Python
|
agpl-3.0
| 1,921
|
import os
import re
import argparse
from pathlib import Path
def get_args():
parser = argparse.ArgumentParser()
normalized_filepath = lambda filepath: str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--venv-bin-path",
type=normalized_filepath,
default=None,
help="虚拟环境的 bin 路径",
)
parser.add_argument(
"--venv-path", type=normalized_filepath, default=None, help="虚拟环境的路径"
)
return parser.parse_args()
# 打开文件并读取内容
def read_content_from_file(path: str) -> list:
lines = []
try:
with open(path, "r", encoding="utf-8") as file:
for line in file:
# 去除每行的换行符并添加到列表中
lines.append(line.strip())
except:
pass
return lines
def get_value_from_variable(content: str, var_name: str) -> str | None:
"""从字符串 (Python 代码片段) 中找出指定字符串变量的值
:param content(str): 待查找的内容
:param var_name(str): 待查找的字符串变量
:return str | None: 返回字符串变量的值
"""
# 匹配三种情况:单引号/双引号/无引号
pattern = rf"{re.escape(var_name)}\s*=\s*(?:['\"]([^'\"]*)['\"]|([^ \n'\"]+))"
match = re.search(pattern, content)
return match.group(1) or match.group(2) if match else None
# 获取 activate 文件中的虚拟环境路径
def get_virtual_env_sh(content: list) -> str:
for line in content:
line = line.strip()
if line.startswith("VIRTUAL_ENV"):
return get_value_from_variable(line, "VIRTUAL_ENV")
return None
# 获取 activate.bat 文件中虚拟环境的路径
def get_virtual_env_bat(content: list) -> str:
for line in content:
line = line.strip()
if line.startswith("set VIRTUAL_ENV="):
line = line.split("set VIRTUAL_ENV=").pop()
return line
return None
if __name__ == "__main__":
args = get_args()
venv_bin_path = Path(args.venv_bin_path)
venv_path = Path(args.venv_path)
activate_sh_path = os.path.join(venv_bin_path, "activate")
activate_bat_path = os.path.join(venv_bin_path, "activate.bat")
venv_broken = False
sh_file_content = read_content_from_file(activate_sh_path)
bat_file_content = read_content_from_file(activate_bat_path)
venv_path_sh = get_virtual_env_sh(sh_file_content)
venv_path_bat = get_virtual_env_bat(bat_file_content)
if venv_path_sh is not None and Path(venv_path_sh) != Path(venv_path):
venv_broken = True
if venv_path_bat is not None and Path(venv_path_bat) != Path(venv_path):
venv_broken = True
print(venv_broken)
|
2301_81996401/term-sd
|
python_modules/check_venv_path_invalid.py
|
Python
|
agpl-3.0
| 2,746
|
import importlib.util
import shutil
import os
import ctypes
import logging
try:
torch_spec = importlib.util.find_spec("torch")
for folder in torch_spec.submodule_search_locations:
lib_folder = os.path.join(folder, "lib")
test_file = os.path.join(lib_folder, "fbgemm.dll")
dest = os.path.join(lib_folder, "libomp140.x86_64.dll")
if os.path.exists(dest):
break
with open(test_file, "rb") as f:
contents = f.read()
if b"libomp140.x86_64.dll" not in contents:
break
try:
mydll = ctypes.cdll.LoadLibrary(test_file)
except FileNotFoundError as e:
logging.warning("检测到 PyTorch 版本存在 libomp 问题, 进行修复")
shutil.copyfile(os.path.join(lib_folder, "libiomp5md.dll"), dest)
except Exception as _:
pass
|
2301_81996401/term-sd
|
python_modules/fix_torch.py
|
Python
|
agpl-3.0
| 871
|
from importlib.metadata import requires
def get_package_name(package: str) -> str:
"""从 Python 包版本声明中获取包名
:param package`(str)`: Python 包版本声明
:return `str`: Python 包名
"""
return (
package.split("~=")[0]
.split("===")[0]
.split("!=")[0]
.split("<=")[0]
.split(">=")[0]
.split("<")[0]
.split(">")[0]
.split("==")[0]
)
def get_pytorch() -> str:
"""获取 InvokeAI 所依赖的 PyTorch 包版本声明
:param `str`: PyTorch 包版本声明
"""
pytorch_ver = []
try:
invokeai_requires = requires("invokeai")
except Exception as _:
invokeai_requires = []
torch_added = False
torchvision_added = False
torchaudio_added = False
for require in invokeai_requires:
require = require.split(";")[0].strip()
package_name = get_package_name(require)
if package_name == "torch" and not torch_added:
pytorch_ver.append(require)
torch_added = True
if package_name == "torchvision" and not torchvision_added:
pytorch_ver.append(require)
torchvision_added = True
if package_name == "torchaudio" and not torchaudio_added:
pytorch_ver.append(require)
torchaudio_added = True
return " ".join([str(x).strip() for x in pytorch_ver])
def main() -> None:
"""主函数"""
print(get_pytorch())
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/get_invokeai_require_pytorch.py
|
Python
|
agpl-3.0
| 1,523
|
from importlib.metadata import requires
def get_package_name(package: str) -> str:
"""从 Python 包版本声明中获取包名
:param package`(str)`: Python 包版本声明
:return `str`: Python 包名
"""
return (
package.split("~=")[0]
.split("===")[0]
.split("!=")[0]
.split("<=")[0]
.split(">=")[0]
.split("<")[0]
.split(">")[0]
.split("==")[0]
)
def get_pytorch() -> str:
"""获取 InvokeAI 所依赖的 PyTorch 包版本声明
:param `str`: PyTorch 包版本声明
"""
pytorch_ver = []
try:
invokeai_requires = requires("invokeai")
except Exception as _:
invokeai_requires = []
xformers_added = False
for require in invokeai_requires:
require = require.split(";")[0].strip()
package_name = get_package_name(require)
if package_name == "xformers" and not xformers_added:
pytorch_ver.append(require)
xformers_added = True
return " ".join([str(x).strip() for x in pytorch_ver])
def main() -> None:
"""主函数"""
print(get_pytorch())
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/get_invokeai_require_xformers.py
|
Python
|
agpl-3.0
| 1,187
|
from importlib.metadata import version
try:
ver = version("invokeai")
except:
ver = None
print(ver)
|
2301_81996401/term-sd
|
python_modules/get_invokeai_version.py
|
Python
|
agpl-3.0
| 110
|
import importlib.metadata
from importlib.metadata import version
try:
print(version("numpy").split(".")[0])
except importlib.metadata.PackageNotFoundError:
print("-1")
|
2301_81996401/term-sd
|
python_modules/get_numpy_ver.py
|
Python
|
agpl-3.0
| 177
|
import re
import sys
import subprocess
try:
output = subprocess.check_output(
[sys.executable, "-m", "pip", "cache", "info"], text=True
)
except Exception as _:
output = []
try:
uv_output = subprocess.check_output(["uv", "cache", "dir"], text=True)
except Exception as _:
uv_output = ""
pattern_list = [
r"^Package index page cache location(?: \(pip v23\.3\+\))?:\s*(.*)$",
r"^Package index page cache location \(older pips\):\s*(.*)$",
r"^Package index page cache size:\s*(.*)$",
r"^Number of HTTP files:\s*(.*)$",
r"^Locally built wheels location:\s*(.*)$",
r"^Locally built wheels size:\s*(.*)$",
r"^Number of locally built wheels:\s*(.*)$",
]
value_list = []
for p in pattern_list:
match = re.search(p, output, flags=re.MULTILINE)
value_list.append(match.group(1)) if match else value_list.append(None)
value_list.append(uv_output)
print(";".join([i if i is not None else " " for i in value_list]))
|
2301_81996401/term-sd
|
python_modules/get_pip_cache_info.py
|
Python
|
agpl-3.0
| 976
|
import sys
p = sys.platform
if p in ["win32", "linux", "darwin"]:
print(p)
else:
print("other")
|
2301_81996401/term-sd
|
python_modules/get_platform.py
|
Python
|
agpl-3.0
| 106
|
import importlib.metadata
import pathlib
package = "pypatchmatch"
try:
# dist = importlib.metadata.files("ll")
util = [p for p in importlib.metadata.files(package) if "__init__.py" in str(p)][0]
path = pathlib.Path(util.locate()).parents[0]
print(path.as_posix())
except importlib.metadata.PackageNotFoundError:
print("None")
|
2301_81996401/term-sd
|
python_modules/get_pypatchmatch_path.py
|
Python
|
agpl-3.0
| 348
|
import re
import argparse
import subprocess
from importlib.metadata import requires
from typing import Literal
DeviceType = Literal["cuda", "rocm", "xpu", "cpu"]
def get_args() -> argparse.Namespace:
"""获取命令行参数
:return `argparse.Namespace`: 命令行参数命名空间
"""
parser = argparse.ArgumentParser()
parser.add_argument("--device-type", type=str, default="cuda", help="显卡类型")
return parser.parse_args()
def version_increment(version: str) -> str:
"""增加版本号大小
:param version`(str)`: 初始版本号
:return `str`: 增加后的版本号
"""
version = "".join(re.findall(r"\d|\.", version))
ver_parts = list(map(int, version.split(".")))
ver_parts[-1] += 1
for i in range(len(ver_parts) - 1, 0, -1):
if ver_parts[i] == 10:
ver_parts[i] = 0
ver_parts[i - 1] += 1
return ".".join(map(str, ver_parts))
def version_decrement(version: str) -> str:
"""减小版本号大小
:param version`(str)`: 初始版本号
:return `str`: 减小后的版本号
"""
version = "".join(re.findall(r"\d|\.", version))
ver_parts = list(map(int, version.split(".")))
ver_parts[-1] -= 1
for i in range(len(ver_parts) - 1, 0, -1):
if ver_parts[i] == -1:
ver_parts[i] = 9
ver_parts[i - 1] -= 1
while len(ver_parts) > 1 and ver_parts[0] == 0:
ver_parts.pop(0)
return ".".join(map(str, ver_parts))
def has_version(version: str) -> bool:
"""判断包名是否包含版本号
:param version`(str)`: Python 包名
:return `bool`: 包名包含版本号时返回`True`
"""
return version != (
version.replace("~=", "")
.replace("===", "")
.replace("!=", "")
.replace("<=", "")
.replace(">=", "")
.replace("<", "")
.replace(">", "")
.replace("==", "")
)
def get_package_name(package: str) -> str:
"""从 Python 包版本声明中获取包名
:param package`(str)`: Python 包版本声明
:return `str`: Python 包名
"""
return (
package.split("~=")[0]
.split("===")[0]
.split("!=")[0]
.split("<=")[0]
.split(">=")[0]
.split("<")[0]
.split(">")[0]
.split("==")[0]
)
def get_package_version(package: str) -> str:
"""从 Python 包版本声明中获取版本号
:param package`(str)`: Python 包版本声明
:return `str`: Python 包版本号
"""
return (
package.split("~=")
.pop()
.split("===")
.pop()
.split("!=")
.pop()
.split("<=")
.pop()
.split(">=")
.pop()
.split("<")
.pop()
.split(">")
.pop()
.split("==")
.pop()
)
def get_invokeai_require_torch_version() -> str:
"""获取 InvokeAI 依赖的 PyTorch 版本
:return `str`: PyTorch 版本
"""
try:
invokeai_requires = requires("invokeai")
except Exception as _:
return "2.2.2"
torch_version = "torch==2.2.2"
for require in invokeai_requires:
if get_package_name(require) == "torch" and has_version(require):
torch_version = require.split(";")[0]
break
if torch_version.startswith("torch>") and not torch_version.startswith("torch>="):
return version_increment(get_package_version(torch_version))
elif torch_version.startswith("torch<") and not torch_version.startswith("torch<="):
return version_decrement(get_package_version(torch_version))
elif torch_version.startswith("torch!="):
return version_increment(get_package_version(torch_version))
else:
return get_package_version(torch_version)
def compare_versions(version1: str, version2: str) -> int:
"""对比两个版本号大小
:param version1(str): 第一个版本号
:param version2(str): 第二个版本号
:return int: 版本对比结果, 1 为第一个版本号大, -1 为第二个版本号大, 0 为两个版本号一样
"""
# 将版本号拆分成数字列表
try:
nums1 = (
re.sub(r"[a-zA-Z]+", "", version1)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
nums2 = (
re.sub(r"[a-zA-Z]+", "", version2)
.replace("-", ".")
.replace("_", ".")
.replace("+", ".")
.split(".")
)
except Exception as _:
return 0
for i in range(max(len(nums1), len(nums2))):
num1 = int(nums1[i]) if i < len(nums1) else 0 # 如果版本号 1 的位数不够, 则补 0
num2 = int(nums2[i]) if i < len(nums2) else 0 # 如果版本号 2 的位数不够, 则补 0
if num1 == num2:
continue
elif num1 > num2:
return 1 # 版本号 1 更大
else:
return -1 # 版本号 2 更大
return 0 # 版本号相同
def get_cuda_comp_cap() -> float:
"""
Returns float of CUDA Compute Capability using nvidia-smi
Returns 0.0 on error
CUDA Compute Capability
ref https://developer.nvidia.com/cuda-gpus
ref https://en.wikipedia.org/wiki/CUDA
Blackwell consumer GPUs should return 12.0 data-center GPUs should return 10.0
:return `float`: Comp Cap 版本
"""
try:
return max(
map(
float,
subprocess.check_output(
["nvidia-smi", "--query-gpu=compute_cap", "--format=noheader,csv"],
text=True,
).splitlines(),
)
)
except Exception as _:
return 0.0
def get_cuda_version() -> float:
"""获取驱动支持的 CUDA 版本
:return `float`: CUDA 支持的版本
"""
try:
# 获取 nvidia-smi 输出
output = subprocess.check_output(["nvidia-smi", "-q"], text=True)
match = re.search(r"CUDA Version\s+:\s+(\d+\.\d+)", output)
if match:
return float(match.group(1))
return 0.0
except Exception as _:
return 0.0
def get_pytorch_mirror_type_cuda(torch_ver: str) -> str:
"""获取 CUDA 类型的 PyTorch 镜像源类型
:param torch_ver`(str)`: PyTorch 版本
:return `str`: CUDA 类型的 PyTorch 镜像源类型
"""
# cu118: 2.0.0 ~ 2.4.0
# cu121: 2.1.1 ~ 2.4.0
# cu124: 2.4.0 ~ 2.6.0
# cu126: 2.6.0 ~ 2.7.1
# cu128: 2.7.0 ~ 2.7.1
# cu129: 2.8.0 ~
cuda_comp_cap = get_cuda_comp_cap()
cuda_support_ver = get_cuda_version()
if compare_versions(torch_ver, "2.0.0") == -1:
# torch < 2.0.0: default cu11x
return "other"
if (
compare_versions(torch_ver, "2.0.0") >= 0
and compare_versions(torch_ver, "2.3.1") == -1
):
# 2.0.0 <= torch < 2.3.1: default cu118
return "cu118"
if (
compare_versions(torch_ver, "2.3.0") >= 0
and compare_versions(torch_ver, "2.4.1") == -1
):
# 2.3.0 <= torch < 2.4.1: default cu121
if compare_versions(str(int(cuda_support_ver * 10)), "cu121") < 0:
if compare_versions(str(int(cuda_support_ver * 10)), "cu118") >= 0:
return "cu118"
return "cu121"
if (
compare_versions(torch_ver, "2.4.0") >= 0
and compare_versions(torch_ver, "2.6.0") == -1
):
# 2.4.0 <= torch < 2.6.0: default cu124
if compare_versions(str(int(cuda_support_ver * 10)), "cu124") < 0:
if compare_versions(str(int(cuda_support_ver * 10)), "cu121") >= 0:
return "cu121"
if compare_versions(str(int(cuda_support_ver * 10)), "cu118") >= 0:
return "cu118"
return "cu124"
if (
compare_versions(torch_ver, "2.6.0") >= 0
and compare_versions(torch_ver, "2.7.0") == -1
):
# 2.6.0 <= torch < 2.7.0: default cu126
if compare_versions(str(int(cuda_support_ver * 10)), "cu126") < 0:
if compare_versions(str(int(cuda_support_ver * 10)), "cu124") >= 0:
return "cu124"
if compare_versions(cuda_comp_cap, "10.0") > 0:
if compare_versions(str(int(cuda_support_ver * 10)), "cu128") >= 0:
return "cu128"
return "cu126"
if (
compare_versions(torch_ver, "2.7.0") >= 0
and compare_versions(torch_ver, "2.8.0") == -1
):
# 2.7.0 <= torch < 2.8.0: default cu128
if compare_versions(str(int(cuda_support_ver * 10)), "cu128") < 0:
if compare_versions(str(int(cuda_support_ver * 10)), "cu126") >= 0:
return "cu126"
return "cu128"
if compare_versions(torch_ver, "2.8.0") >= 0:
# torch >= 2.8.0: default cu129
return "cu129"
return "cu129"
def get_pytorch_mirror_type_rocm(torch_ver: str) -> str:
"""获取 ROCm 类型的 PyTorch 镜像源类型
:param torch_ver`(str)`: PyTorch 版本
:return `str`: ROCm 类型的 PyTorch 镜像源类型
"""
if compare_versions(torch_ver, "2.4.0") < 0:
# torch < 2.4.0
return "other"
if (
compare_versions(torch_ver, "2.4.0") >= 0
and compare_versions(torch_ver, "2.5.0") < 0
):
# 2.4.0 <= torch < 2.5.0
return "rocm61"
if (
compare_versions(torch_ver, "2.5.0") >= 0
and compare_versions(torch_ver, "2.6.0") < 0
):
# 2.5.0 <= torch < 2.6.0
return "rocm62"
if (
compare_versions(torch_ver, "2.6.0") >= 0
and compare_versions(torch_ver, "2.7.0") < 0
):
# 2.6.0 < torch < 2.7.0
return "rocm624"
if compare_versions(torch_ver, "2.7.0") >= 0:
# torch >= 2.7.0
return "rocm63"
return "rocm63"
def get_pytorch_mirror_type_ipex(torch_ver: str) -> str:
"""获取 IPEX 类型的 PyTorch 镜像源类型
:param torch_ver`(str)`: PyTorch 版本
:return `str`: IPEX 类型的 PyTorch 镜像源类型
"""
if compare_versions(torch_ver, "2.0.0") < 0:
# torch < 2.0.0
return "other"
if compare_versions(torch_ver, "2.0.0") == 0:
# torch == 2.0.0
return "ipex_legacy_arc"
if (
compare_versions(torch_ver, "2.0.0") > 0
and compare_versions(torch_ver, "2.1.0") < 0
):
# 2.0.0 < torch < 2.1.0
return "other"
if compare_versions(torch_ver, "2.1.0") == 0:
# torch == 2.1.0
return "ipex_legacy_arc"
if compare_versions(torch_ver, "2.6.0") >= 0:
# torch >= 2.6.0
return "xpu"
return "xpu"
def get_pytorch_mirror_type_cpu(torch_ver: str) -> str:
"""获取 CPU 类型的 PyTorch 镜像源类型
:param torch_ver`(str)`: PyTorch 版本
:return `str`: CPU 类型的 PyTorch 镜像源类型
"""
_ = torch_ver
return "cpu"
def get_pytorch_mirror_type(device_type: DeviceType) -> str:
"""获取 PyTorch 镜像源类型
:param device_type`(DeviceType)`: 显卡类型
:return `str`: PyTorch 镜像源类型
"""
torch_ver = get_invokeai_require_torch_version()
if device_type == "cuda":
return get_pytorch_mirror_type_cuda(torch_ver)
if device_type == "rocm":
return get_pytorch_mirror_type_rocm(torch_ver)
if device_type == "xpu":
return get_pytorch_mirror_type_ipex(torch_ver)
if device_type == "cpu":
return get_pytorch_mirror_type_cpu(torch_ver)
return "other"
def main() -> None:
"""主函数"""
arg = get_args()
print(get_pytorch_mirror_type(arg.device_type))
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/get_pytorch_mirror_type.py
|
Python
|
agpl-3.0
| 11,717
|
def get_pytorch_version() -> str | None:
"""获取 PyTorch 的版本号
:return `str|None`: PyTorch 版本号
"""
try:
import torch
return torch.__version__
except Exception as _:
return None
def get_pytorch_type() -> str:
"""获取 PyTorch 版本号对应的类型
:return `str`: PyTorch 类型
"""
torch_ipex_legacy_ver_list = [
"2.0.0a0+gite9ebda2",
"2.1.0a0+git7bcf7da",
"2.1.0a0+cxx11.abi",
"2.0.1a0",
"2.1.0.post0",
]
torch_ver = get_pytorch_version()
if torch_ver is None:
return "cuda"
torch_type = torch_ver.split("+").pop()
if torch_ver in torch_ipex_legacy_ver_list:
return "xpu"
if "cu" in torch_type:
return "cuda"
if "rocm" in torch_type:
return "rocm"
if "xpu" in torch_type:
return "xpu"
if "cpu" in torch_type:
return "cpu"
return "cuda"
def main() -> None:
"""主函数"""
print(get_pytorch_type())
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/get_pytorch_type.py
|
Python
|
agpl-3.0
| 1,066
|
from importlib.metadata import version
try:
print(version("torch"))
except:
print("无")
|
2301_81996401/term-sd
|
python_modules/get_pytorch_ver.py
|
Python
|
agpl-3.0
| 98
|
import argparse
import json
from pathlib import Path
# 参数输入
def get_args():
parser = argparse.ArgumentParser()
normalized_filepath = lambda filepath: str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--config-path",
type=normalized_filepath,
default=None,
help="SD WebUI 配置文件路径",
)
return parser.parse_args()
def is_sd_webui_disable_all_extension(path: str) -> bool:
settings = {}
try:
with open(path, "r", encoding="utf8") as file:
settings = json.load(file)
except:
pass
disable_all_extensions = settings.get("disable_all_extensions", "none")
if disable_all_extensions != "none":
return True
else:
return False
if __name__ == "__main__":
args = get_args()
path = args.config_path
print(is_sd_webui_disable_all_extension(path))
|
2301_81996401/term-sd
|
python_modules/get_sd_webui_disable_all_extension_status.py
|
Python
|
agpl-3.0
| 905
|
import os
print(f"{os.getcwd()}{os.pathsep}{os.environ.get('PYTHONPATH', '')}")
|
2301_81996401/term-sd
|
python_modules/get_sd_webui_python_path.py
|
Python
|
agpl-3.0
| 81
|
from importlib.metadata import version
try:
print(version("xformers"))
except:
print("无")
|
2301_81996401/term-sd
|
python_modules/get_xformers_ver.py
|
Python
|
agpl-3.0
| 101
|
import os
import sys
import json
import copy
import shlex
import inspect
import logging
import argparse
import traceback
import subprocess
from pathlib import Path
from typing import Optional
def get_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Stable Diffusion WebUI 扩展依赖安装脚本"
)
def normalized_filepath(filepath):
return str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--disable-extra-extensions",
action="store_true",
help="禁用额外 Stable Diffusion WebUI 扩展",
)
parser.add_argument(
"--disable-all-extensions",
action="store_true",
help="禁用所有 Stable Diffusion WebUI 扩展",
)
parser.add_argument(
"--sd-webui-base-path",
type=normalized_filepath,
default=os.getcwd(),
help="Stable Diffusion WebUI 根目录",
)
return parser.parse_args()
class ColoredFormatter(logging.Formatter):
"""Logging 格式化"""
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
def format(self, record):
colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = "{}{}{}".format(seq, levelname, self.COLORS["RESET"])
return super().format(colored_record)
def get_logger(
name: str | None = None,
level: int = logging.INFO,
) -> logging.Logger:
"""获取 Loging 对象
:param name`(str)`: Logging 名称
:return `logging.Logger`: Logging 对象
"""
stack = inspect.stack()
calling_filename = os.path.basename(stack[1].filename)
if name is None:
name = calling_filename
logger = logging.getLogger(name)
logger.propagate = False
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
ColoredFormatter(
"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s", "%H:%M:%S"
)
)
logger.addHandler(handler)
logger.setLevel(level)
logger.debug("Logger 初始化完成")
return logger
logger = get_logger("Term-SD")
def run_cmd(
command: str | list[str],
desc: str | None = None,
errdesc: str | None = None,
custom_env: dict[str, str] | None = None,
live: bool | None = True,
shell: bool | None = None,
) -> str | None:
"""执行 Shell 命令
:param command`(str|list[str])`: 要执行的命令
:param desc`(str|None)`: 执行命令的描述
:param errdesc`(str|None)`: 执行命令报错时的描述
:param custom_env`(dict[str,str]|None)`: 自定义环境变量
:param live`(bool|None)`: 是否实时输出命令执行日志
:param shell`(bool|None)`: 是否使用内置 Shell 执行命令
:return `str|None`: 命令执行时输出的内容
:raises RuntimeError: 当命令执行失败时
"""
if shell is None:
shell = sys.platform != "win32"
if desc is not None:
logger.info(desc)
if custom_env is None:
custom_env = os.environ
if sys.platform == "win32":
# 在 Windows 平台上不使用 shlex 处理成字符串
command_to_exec = command
else:
# 把列表转换为字符串, 避免 subprocss 只把使用列表第一个元素作为命令
command_to_exec = shlex.join(command) if isinstance(command, list) else command
if live:
result: subprocess.CompletedProcess[bytes] = subprocess.run(
command_to_exec,
shell=shell,
env=custom_env,
)
if result.returncode != 0:
raise RuntimeError(f"""{errdesc or "执行命令时发生错误"}
命令: {command_to_exec}
错误代码: {result.returncode}""")
return ""
result: subprocess.CompletedProcess[bytes] = subprocess.run(
command_to_exec,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
env=custom_env,
)
if result.returncode != 0:
message = f"""{errdesc or "执行命令时发生错误"}
命令: {command_to_exec}
错误代码: {result.returncode}
标准输出: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout) > 0 else ""}
错误输出: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr) > 0 else ""}
"""
raise RuntimeError(message)
return result.stdout.decode(encoding="utf8", errors="ignore")
def run_extension_installer(sd_webui_base_path: Path, extension_dir: Path) -> bool:
"""执行扩展依赖安装脚本
:param sd_webui_base_path`(Path)`: SD WebUI 跟目录, 用于导入自身模块
:param extension_dir`(Path)`: 要执行安装脚本的扩展路径
:return `bool`: 扩展依赖安装结果
"""
path_installer = extension_dir / "install.py"
if not path_installer.is_file():
return
try:
env = os.environ.copy()
py_path = env.get("PYTHONPATH", "")
env["PYTHONPATH"] = f"{sd_webui_base_path}{os.pathsep}{py_path}"
env["WEBUI_LAUNCH_LIVE_OUTPUT"] = "1"
run_cmd(
command=[Path(sys.executable).as_posix(), path_installer.as_posix()],
custom_env=env,
)
return True
except Exception as e:
logger.info("执行 %s 扩展依赖安装脚本时发生错误: %s", extension_dir.name, e)
traceback.print_exc()
return False
def install_extension_requirements(
sd_webui_base_path: Path,
arg_disable_extra_extensions: bool = False,
arg_disable_all_extensions: bool = False,
) -> None:
"""安装 SD WebUI 扩展依赖
:param sd_webui_base_path`(Path)`: SD WebUI 根目录
:param arg_disable_extra_extensions`(bool)`: 是否禁用 SD WebUI 额外扩展
:param arg_disable_all_extensions`(bool)`: 是否禁用 SD WebUI 所有扩展
"""
settings_file = sd_webui_base_path / "config.json"
extensions_dir = sd_webui_base_path / "extensions"
builtin_extensions_dir = sd_webui_base_path / "extensions-builtin"
ext_install_list = []
ext_builtin_install_list = []
settings = {}
try:
with open(settings_file, "r", encoding="utf8") as file:
settings = json.load(file)
except Exception as e:
logger.warning("Stable Diffusion WebUI 配置文件无效: %s", e)
disabled_extensions = set(settings.get("disabled_extensions", []))
disable_all_extensions = settings.get("disable_all_extensions", "none")
if disable_all_extensions == "all" or arg_disable_all_extensions:
logger.info("已禁用所有 Stable Diffusion WebUI 扩展, 不执行扩展依赖检查")
return
if (
extensions_dir.is_dir()
and disable_all_extensions != "extra"
and not arg_disable_extra_extensions
):
ext_install_list = [
x
for x in extensions_dir.glob("*")
if x.name not in disabled_extensions and (x / "install.py").is_file()
]
if builtin_extensions_dir.is_dir():
ext_builtin_install_list = [
x
for x in builtin_extensions_dir.glob("*")
if x.name not in disabled_extensions and (x / "install.py").is_file()
]
install_list = ext_install_list + ext_builtin_install_list
extension_count = len(install_list)
if extension_count == 0:
logger.info("无待安装依赖的 Stable Diffusion WebUI 扩展")
return
count = 0
for ext in install_list:
count += 1
ext_name = ext.name
logger.info(
"[%s/%s] 执行 %s 扩展的依赖安装脚本中", count, extension_count, ext_name
)
if run_extension_installer(
sd_webui_base_path=sd_webui_base_path,
extension_dir=ext,
):
logger.info(
"[%s/%s] 执行 %s 扩展的依赖安装脚本成功",
count,
extension_count,
ext_name,
)
else:
logger.warning(
"[%s/%s] 执行 %s 扩展的依赖安装脚本失败, 可能会导致该扩展运行异常",
count,
extension_count,
ext_name,
)
logger.info(
"[%s/%s] 安装 Stable Diffusion WebUI 扩展依赖结束", count, extension_count
)
def main() -> None:
"""主函数"""
args = get_args()
base_path = args.sd_webui_base_path
if base_path is None:
logger.error("未通过 --sd-webui-base-path 参数指定 Stable Diffusion WebUI 路径")
return
install_extension_requirements(
sd_webui_base_path=Path(base_path),
arg_disable_extra_extensions=args.disable_extra_extensions,
arg_disable_all_extensions=args.disable_all_extensions,
)
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/install_sd_webui_extension_requirement.py
|
Python
|
agpl-3.0
| 9,175
|
import re
import sys
from invokeai.app.run_app import run_app
if __name__ == "__main__":
sys.argv[0] = re.sub(r"(-script\.pyw|\.exe)?$", "", sys.argv[0])
sys.exit(run_app())
|
2301_81996401/term-sd
|
python_modules/launch_invokeai.py
|
Python
|
agpl-3.0
| 183
|
import os
import json
import argparse
from pathlib import Path
def get_args():
parser = argparse.ArgumentParser()
normalized_filepath = lambda filepath: str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--config-path",
type=normalized_filepath,
default=None,
help="SD WebUI 配置文件路径",
)
parser.add_argument("--extension", type=str, default=None, help="SD WebUI 插件名称")
parser.add_argument(
"--status", type=str, default=None, help="设置 SD WebUI 插件的状态"
)
return parser.parse_args()
def get_key_map(file_path):
file_name = Path(file_path)
if os.path.exists(file_name):
try:
with open(file_name, "r", encoding="utf8") as file:
data = json.load(file)
except Exception:
# json 文件格式出现问题
data = {}
else:
data = {}
return data
def check_json(file_path):
file_name = Path(file_path)
if os.path.exists(file_name):
try:
with open(file_name, "r", encoding="utf8") as file:
_ = json.load(file)
return True
except Exception:
# json 文件格式出现问题
return False
else:
return False
def search_key(data, key, value):
key_map = data.get(key)
if key_map is not None:
if value in key_map:
return True
else:
return False
else:
return False
def save(data, filename):
with open(filename, "w", encoding="utf8") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
def set_extension_status(json_path, extension_name, status):
key_name = "disabled_extensions"
# 检查 json 格式是否正确
if check_json(json_path):
data = get_key_map(json_path)
# 缺少 disabled_extensions 这个值时自动补上
if data.get(key_name) is None:
data[key_name] = []
if status:
if search_key(data, key_name, extension_name):
data[key_name].remove(extension_name)
save(data, json_path)
else:
if search_key(data, key_name, extension_name) is False:
data[key_name].append(extension_name)
save(data, json_path)
print(True)
else:
print(False)
if __name__ == "__main__":
args = get_args()
json_path = args.config_path
extension_name = args.extension
status = args.status
status = True if status == "True" else False
set_extension_status(json_path, extension_name, status)
|
2301_81996401/term-sd
|
python_modules/set_sd_webui_extension_status.py
|
Python
|
agpl-3.0
| 2,655
|
"""运行环境检查"""
import re
import os
import sys
import copy
import logging
import argparse
import importlib.metadata
from collections import namedtuple
from pathlib import Path
from typing import Optional, TypedDict, Union
def get_args() -> argparse.Namespace:
"""获取命令行参数输入参数输入"""
parser = argparse.ArgumentParser(description="运行环境检查")
def normalized_filepath(filepath):
return str(Path(filepath).absolute().as_posix())
parser.add_argument(
"--requirement-path",
type=normalized_filepath,
default=None,
help="依赖文件路径",
)
parser.add_argument("--debug-mode", action="store_true", help="显示调试信息")
return parser.parse_args()
COMMAND_ARGS = get_args()
class ColoredFormatter(logging.Formatter):
"""Logging 格式化"""
COLORS = {
"DEBUG": "\033[0;36m", # CYAN
"INFO": "\033[0;32m", # GREEN
"WARNING": "\033[0;33m", # YELLOW
"ERROR": "\033[0;31m", # RED
"CRITICAL": "\033[0;37;41m", # WHITE ON RED
"RESET": "\033[0m", # RESET COLOR
}
def format(self, record):
colored_record = copy.copy(record)
levelname = colored_record.levelname
seq = self.COLORS.get(levelname, self.COLORS["RESET"])
colored_record.levelname = "{}{}{}".format(seq, levelname, self.COLORS["RESET"])
return super().format(colored_record)
def get_logger(
name: str,
level: int = logging.INFO,
) -> logging.Logger:
"""获取 Loging 对象
参数:
name (`str`):
Logging 名称
"""
logger = logging.getLogger(name)
logger.propagate = False
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
ColoredFormatter(
"[%(name)s]-|%(asctime)s|-%(levelname)s: %(message)s", "%H:%M:%S"
)
)
logger.addHandler(handler)
logger.setLevel(level)
logger.debug("Logger initialized.")
return logger
logger = get_logger(
"Env Checker", logging.DEBUG if COMMAND_ARGS.debug_mode else logging.INFO
)
# 提取版本标识符组件的正则表达式
# ref:
# https://peps.python.org/pep-0440
# https://packaging.python.org/en/latest/specifications/version-specifiers
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
# 编译正则表达式
package_version_parse_regex = re.compile(
r"^\s*" + VERSION_PATTERN + r"\s*$",
re.VERBOSE | re.IGNORECASE,
)
# 定义版本组件的命名元组
VersionComponent = namedtuple(
"VersionComponent",
[
"epoch",
"release",
"pre_l",
"pre_n",
"post_n1",
"post_l",
"post_n2",
"dev_l",
"dev_n",
"local",
"is_wildcard",
],
)
def parse_version(version_str: str) -> VersionComponent:
"""解释 Python 软件包版本号
参数:
version_str (`str`):
Python 软件包版本号
返回值:
`VersionComponent`: 版本组件的命名元组
异常:
`ValueError`: 如果 Python 版本号不符合 PEP440 规范
"""
# 检测并剥离通配符
wildcard = version_str.endswith(".*") or version_str.endswith("*")
clean_str = version_str.rstrip("*").rstrip(".") if wildcard else version_str
match = package_version_parse_regex.match(clean_str)
if not match:
logger.error(f"未知的版本号字符串: {version_str}")
raise ValueError(f"Invalid version string: {version_str}")
components = match.groupdict()
# 处理 release 段 (允许空字符串)
release_str = components["release"] or "0"
release_segments = [int(seg) for seg in release_str.split(".")]
# 构建命名元组
return VersionComponent(
epoch=int(components["epoch"] or 0),
release=release_segments,
pre_l=components["pre_l"],
pre_n=int(components["pre_n"]) if components["pre_n"] else None,
post_n1=int(components["post_n1"]) if components["post_n1"] else None,
post_l=components["post_l"],
post_n2=int(components["post_n2"]) if components["post_n2"] else None,
dev_l=components["dev_l"],
dev_n=int(components["dev_n"]) if components["dev_n"] else None,
local=components["local"],
is_wildcard=wildcard,
)
def compare_version_objects(v1: VersionComponent, v2: VersionComponent) -> int:
"""比较两个版本字符串 Python 软件包版本号
参数:
v1 (`VersionComponent`):
第 1 个 Python 版本号标识符组件
v2 (`VersionComponent`):
第 2 个 Python 版本号标识符组件
返回值:
`int`: 如果版本号 1 大于 版本号 2, 则返回`1`, 小于则返回`-1`, 如果相等则返回`0`
"""
# 比较 epoch
if v1.epoch != v2.epoch:
return v1.epoch - v2.epoch
# 对其 release 长度, 缺失部分补 0
if len(v1.release) != len(v2.release):
for _ in range(abs(len(v1.release) - len(v2.release))):
if len(v1.release) < len(v2.release):
v1.release.append(0)
else:
v2.release.append(0)
# 比较 release
for n1, n2 in zip(v1.release, v2.release):
if n1 != n2:
return n1 - n2
# 如果 release 长度不同,较短的版本号视为较小 ?
# 但是这样是行不通的! 比如 0.15.0 和 0.15, 处理后就会变成 [0, 15, 0] 和 [0, 15]
# 计算结果就会变成 len([0, 15, 0]) > len([0, 15])
# 但 0.15.0 和 0.15 实际上是一样的版本
# if len(v1.release) != len(v2.release):
# return len(v1.release) - len(v2.release)
# 比较 pre-release
if v1.pre_l and not v2.pre_l:
return -1 # pre-release 小于正常版本
elif not v1.pre_l and v2.pre_l:
return 1
elif v1.pre_l and v2.pre_l:
pre_order = {
"a": 0,
"b": 1,
"c": 2,
"rc": 3,
"alpha": 0,
"beta": 1,
"pre": 0,
"preview": 0,
}
if pre_order[v1.pre_l] != pre_order[v2.pre_l]:
return pre_order[v1.pre_l] - pre_order[v2.pre_l]
elif v1.pre_n is not None and v2.pre_n is not None:
return v1.pre_n - v2.pre_n
elif v1.pre_n is None and v2.pre_n is not None:
return -1
elif v1.pre_n is not None and v2.pre_n is None:
return 1
# 比较 post-release
if v1.post_n1 is not None:
post_n1 = v1.post_n1
elif v1.post_l:
post_n1 = int(v1.post_n2) if v1.post_n2 else 0
else:
post_n1 = 0
if v2.post_n1 is not None:
post_n2 = v2.post_n1
elif v2.post_l:
post_n2 = int(v2.post_n2) if v2.post_n2 else 0
else:
post_n2 = 0
if post_n1 != post_n2:
return post_n1 - post_n2
# 比较 dev-release
if v1.dev_l and not v2.dev_l:
return -1 # dev-release 小于 post-release 或正常版本
elif not v1.dev_l and v2.dev_l:
return 1
elif v1.dev_l and v2.dev_l:
if v1.dev_n is not None and v2.dev_n is not None:
return v1.dev_n - v2.dev_n
elif v1.dev_n is None and v2.dev_n is not None:
return -1
elif v1.dev_n is not None and v2.dev_n is None:
return 1
# 比较 local version
if v1.local and not v2.local:
return -1 # local version 小于 dev-release 或正常版本
elif not v1.local and v2.local:
return 1
elif v1.local and v2.local:
local1 = v1.local.split(".")
local2 = v2.local.split(".")
# 和 release 的处理方式一致, 对其 local version 长度, 缺失部分补 0
if len(local1) != len(local2):
for _ in range(abs(len(local1) - len(local2))):
if len(local1) < len(local2):
local1.append(0)
else:
local2.append(0)
for l1, l2 in zip(local1, local2):
if l1.isdigit() and l2.isdigit():
l1, l2 = int(l1), int(l2)
if l1 != l2:
return (l1 > l2) - (l1 < l2)
return len(local1) - len(local2)
return 0 # 版本相同
def compare_versions(version1: str, version2: str) -> int:
"""比较两个版本字符串 Python 软件包版本号
参数:
version1 (`str`):
版本号 1
version2 (`str`):
版本号 2
返回值:
`int`: 如果版本号 1 大于 版本号 2, 则返回`1`, 小于则返回`-1`, 如果相等则返回`0`
"""
v1 = parse_version(version1)
v2 = parse_version(version2)
return compare_version_objects(v1, v2)
def compatible_version_matcher(spec_version: str):
"""PEP 440 兼容性版本匹配 (~= 操作符)
返回值:
`_is_compatible(version_str: str) -> bool`: 一个接受 version_str (`str`) 参数的判断函数
"""
# 解析规范版本
spec = parse_version(spec_version)
# 获取有效 release 段 (去除末尾的零)
clean_release = []
for num in spec.release:
if num != 0 or (clean_release and clean_release[-1] != 0):
clean_release.append(num)
# 确定最低版本和前缀匹配规则
if len(clean_release) == 0:
logger.error("解析到错误的兼容性发行版本号")
raise ValueError("Invalid version for compatible release clause")
# 生成前缀匹配模板 (忽略后缀)
prefix_length = len(clean_release) - 1
if prefix_length == 0:
# 处理类似 ~= 2 的情况 (实际 PEP 禁止,但这里做容错)
prefix_pattern = [spec.release[0]]
min_version = parse_version(f"{spec.release[0]}")
else:
prefix_pattern = list(spec.release[:prefix_length])
min_version = spec
def _is_compatible(version_str: str) -> bool:
target = parse_version(version_str)
# 主版本前缀检查
target_prefix = target.release[: len(prefix_pattern)]
if target_prefix != prefix_pattern:
return False
# 最低版本检查 (自动忽略 pre/post/dev 后缀)
return compare_version_objects(target, min_version) >= 0
return _is_compatible
def version_match(spec: str, version: str) -> bool:
"""PEP 440 版本前缀匹配
参数:
spec (`str`): 版本匹配表达式 (e.g. '1.1.*')
version (`str`): 需要检测的实际版本号 (e.g. '1.1a1')
返回值:
`bool`: 是否匹配
"""
# 分离通配符和本地版本
spec_parts = spec.split("+", 1)
spec_main = spec_parts[0].rstrip(".*") # 移除通配符
has_wildcard = spec.endswith(".*") and "+" not in spec
# 解析规范版本 (不带通配符)
try:
spec_ver = parse_version(spec_main)
except ValueError:
return False
# 解析目标版本 (忽略本地版本)
target_ver = parse_version(version.split("+", 1)[0])
# 前缀匹配规则
if has_wildcard:
# 生成补零后的 release 段
spec_release = spec_ver.release.copy()
while len(spec_release) < len(target_ver.release):
spec_release.append(0)
# 比较前 N 个 release 段 (N 为规范版本长度)
return (
target_ver.release[: len(spec_ver.release)] == spec_ver.release
and target_ver.epoch == spec_ver.epoch
)
else:
# 严格匹配时使用原比较函数
return compare_versions(spec_main, version) == 0
def is_v1_ge_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于或等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号大于或等于 v2 版本号则返回`True`
e.g.:
1.1, 1.0 -> True
1.0, 1.0 -> True
0.9, 1.0 -> False
"""
return compare_versions(v1, v2) >= 0
def is_v1_gt_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号大于 v2 版本号则返回`True`
e.g.:
1.1, 1.0 -> True
1.0, 1.0 -> False
"""
return compare_versions(v1, v2) > 0
def is_v1_eq_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号等于 v2 版本号则返回`True`
e.g.:
1.0, 1.0 -> True
0.9, 1.0 -> False
1.1, 1.0 -> False
"""
return compare_versions(v1, v2) == 0
def is_v1_lt_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否小于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号小于 v2 版本号则返回`True`
e.g.:
0.9, 1.0 -> True
1.0, 1.0 -> False
"""
return compare_versions(v1, v2) < 0
def is_v1_le_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否小于或等于 v2
参数:
v1 (`str`):
第 1 个 Python 软件包版本号
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号小于或等于 v2 版本号则返回`True`
e.g.:
0.9, 1.0 -> True
1.0, 1.0 -> True
1.1, 1.0 -> False
"""
return compare_versions(v1, v2) <= 0
def is_v1_c_eq_v2(v1: str, v2: str) -> bool:
"""查看 Python 版本号 v1 是否大于等于 v2, (兼容性版本匹配)
参数:
v1 (`str`):
第 1 个 Python 软件包版本号, 该版本由 ~= 符号指定
v2 (`str`):
第 2 个 Python 软件包版本号
返回值:
`bool`: 如果 v1 版本号等于 v2 版本号则返回`True`
e.g.:
1.0*, 1.0a1 -> True
0.9*, 1.0 -> False
"""
func = compatible_version_matcher(v1)
return func(v2)
def version_string_is_canonical(version: str) -> bool:
"""判断版本号标识符是否符合标准
参数:
version (`str`):
版本号字符串
返回值:
`bool`: 如果版本号标识符符合 PEP 440 标准, 则返回`True`
"""
return (
re.match(
r"^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$",
version,
)
is not None
)
def is_package_has_version(package: str) -> bool:
"""检查 Python 软件包是否指定版本号
参数:
package (`str`):
Python 软件包名
返回值:
`bool`: 如果 Python 软件包存在版本声明, 如`torch==2.3.0`, 则返回`True`
"""
return package != (
package.replace("===", "")
.replace("~=", "")
.replace("!=", "")
.replace("<=", "")
.replace(">=", "")
.replace("<", "")
.replace(">", "")
.replace("==", "")
)
def get_package_name(package: str) -> str:
"""获取 Python 软件包的包名, 去除末尾的版本声明
参数:
package (`str`):
Python 软件包名
返回值:
`str`: 返回去除版本声明后的 Python 软件包名
"""
return (
package.split("===")[0]
.split("~=")[0]
.split("!=")[0]
.split("<=")[0]
.split(">=")[0]
.split("<")[0]
.split(">")[0]
.split("==")[0]
.strip()
)
def get_package_version(package: str) -> str:
"""获取 Python 软件包的包版本号
参数:
package (`str`):
Python 软件包名
返回值:
`str`: 返回 Python 软件包的包版本号
"""
return (
package.split("===")
.pop()
.split("~=")
.pop()
.split("!=")
.pop()
.split("<=")
.pop()
.split(">=")
.pop()
.split("<")
.pop()
.split(">")
.pop()
.split("==")
.pop()
.strip()
)
WHEEL_PATTERN = r"""
^ # 字符串开始
(?P<distribution>[^-]+) # 包名 (匹配第一个非连字符段)
- # 分隔符
(?: # 版本号和可选构建号组合
(?P<version>[^-]+) # 版本号 (至少一个非连字符段)
(?:-(?P<build>\d\w*))? # 可选构建号 (以数字开头)
)
- # 分隔符
(?P<python>[^-]+) # Python 版本标签
- # 分隔符
(?P<abi>[^-]+) # ABI 标签
- # 分隔符
(?P<platform>[^-]+) # 平台标签
\.whl$ # 固定后缀
"""
def parse_wheel_filename(filename: str) -> str:
"""解析 Python wheel 文件名并返回 distribution 名称
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: distribution 名称, 例如 pydantic
异常:
`ValueError`: 如果文件名不符合 PEP491 规范
"""
match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE)
if not match:
logger.error("未知的 Wheel 文件名: %s", filename)
raise ValueError(f"Invalid wheel filename: {filename}")
return match.group("distribution")
def parse_wheel_version(filename: str) -> str:
"""解析 Python wheel 文件名并返回 version 名称
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: version 名称, 例如 1.10.15
异常:
`ValueError`: 如果文件名不符合 PEP491 规范
"""
match = re.fullmatch(WHEEL_PATTERN, filename, re.VERBOSE)
if not match:
logger.error("未知的 Wheel 文件名: %s", filename)
raise ValueError(f"Invalid wheel filename: {filename}")
return match.group("version")
def parse_wheel_to_package_name(filename: str) -> str:
"""解析 Python wheel 文件名并返回 <distribution>==<version>
参数:
filename (`str`):
wheel 文件名, 例如 pydantic-1.10.15-py3-none-any.whl
返回值:
`str`: <distribution>==<version> 名称, 例如 pydantic==1.10.15
"""
distribution = parse_wheel_filename(filename)
version = parse_wheel_version(filename)
return f"{distribution}=={version}"
def remove_optional_dependence_from_package(filename: str) -> str:
"""移除 Python 软件包声明中可选依赖
参数:
filename (`str`):
Python 软件包名
返回值:
`str`: 移除可选依赖后的软件包名, e.g. diffusers[torch]==0.10.2 -> diffusers==0.10.2
"""
return re.sub(r"\[.*?\]", "", filename)
def parse_requirement_list(requirements: list) -> list:
"""将 Python 软件包声明列表解析成标准 Python 软件包名列表
参数:
requirements (`list`):
Python 软件包名声明列表
e.g:
```python
requirements = [
'torch==2.3.0',
'diffusers[torch]==0.10.2',
'NUMPY',
'-e .',
'--index-url https://pypi.python.org/simple',
'--extra-index-url https://download.pytorch.org/whl/cu124',
'--find-links https://download.pytorch.org/whl/torch_stable.html',
'-e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds',
'git+https://github.com/WASasquatch/img2texture.git',
'https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl',
'prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer',
'protobuf<5,>=4.25.3',
]
```
返回值:
`list`: 将 Python 软件包名声明列表解析成标准声明列表
e.g. 上述例子中的软件包名声明列表将解析成:
```python
requirements = [
'torch==2.3.0',
'diffusers==0.10.2',
'numpy',
'mgds',
'img2texture',
'pydantic==1.10.15',
'prodigy-plus-schedule-free==1.9.1',
'protobuf<5',
'protobuf>=4.25.3',
]
```
"""
package_list = []
canonical_package_list = []
requirement: str
for requirement in requirements:
requirement = requirement.strip()
logger.debug("原始 Python 软件包名: %s", requirement)
if (
requirement is None
or requirement == ""
or requirement.startswith("#")
or "# skip_verify" in requirement
or requirement.startswith("--index-url")
or requirement.startswith("--extra-index-url")
or requirement.startswith("--find-links")
or requirement.startswith("-e .")
):
continue
# -e git+https://github.com/Nerogar/mgds.git@2c67a5a#egg=mgds -> mgds
# git+https://github.com/WASasquatch/img2texture.git -> img2texture
# git+https://github.com/deepghs/waifuc -> waifuc
if requirement.startswith("-e git+http") or requirement.startswith("git+http"):
egg_match = re.search(r"egg=([^#&]+)", requirement)
if egg_match:
package_list.append(egg_match.group(1).split("-")[0])
continue
package_name = os.path.basename(requirement)
package_name = (
package_name.split(".git")[0]
if package_name.endswith(".git")
else package_name
)
package_list.append(package_name)
continue
# https://github.com/Panchovix/pydantic-fixreforge/releases/download/main_v1/pydantic-1.10.15-py3-none-any.whl -> pydantic==1.10.15
if requirement.startswith("https://") or requirement.startswith("http://"):
package_name = parse_wheel_to_package_name(os.path.basename(requirement))
package_list.append(package_name)
continue
# 常规 Python 软件包声明
# prodigy-plus-schedule-free==1.9.1 # prodigy+schedulefree optimizer -> prodigy-plus-schedule-free==1.9.1
cleaned_requirements = re.sub(r"\s*#.*$", "", requirement).strip().split(",")
if len(cleaned_requirements) > 1:
package_name = get_package_name(cleaned_requirements[0].strip())
for package_name_with_version_marked in cleaned_requirements:
version_symbol = str.replace(
package_name_with_version_marked, package_name, "", 1
)
format_package_name = remove_optional_dependence_from_package(
f"{package_name}{version_symbol}".strip()
)
package_list.append(format_package_name)
else:
format_package_name = remove_optional_dependence_from_package(
cleaned_requirements[0].strip()
)
package_list.append(format_package_name)
# 处理包名大小写并统一成小写
for p in package_list:
p: str = p.lower().strip()
logger.debug("预处理后的 Python 软件包名: %s", p)
if not is_package_has_version(p):
logger.debug("%s 无版本声明", p)
canonical_package_list.append(p)
continue
if version_string_is_canonical(get_package_version(p)):
canonical_package_list.append(p)
else:
logger.debug("%s 软件包名的版本不符合标准", p)
return canonical_package_list
def remove_duplicate_object_from_list(origin: list) -> list:
"""对`list`进行去重
参数:
origin (`list`):
原始的`list`
返回值:
`list`: 去重后的`list`, e.g. [1, 2, 3, 2] -> [1, 2, 3]
"""
return list(set(origin))
def read_packages_from_requirements_file(file_path: Union[str, Path]) -> list:
"""从 requirements.txt 文件中读取 Python 软件包版本声明列表
参数:
file_path (`str`, `Path`):
requirements.txt 文件路径
返回值:
`list`: 从 requirements.txt 文件中读取的 Python 软件包声明列表
"""
try:
with open(file_path, "r", encoding="utf-8") as f:
return f.readlines()
except Exception as e:
logger.error("打开 %s 时出现错误: %s\n请检查文件是否出现损坏", file_path, e)
return []
def get_package_version_from_library(package_name: str) -> Union[str, None]:
"""获取已安装的 Python 软件包版本号
参数:
package_name (`str`):
返回值:
(`str` | `None`): 如果获取到 Python 软件包版本号则返回版本号字符串, 否则返回`None`
"""
try:
ver = importlib.metadata.version(package_name)
except:
ver = None
if ver is None:
try:
ver = importlib.metadata.version(package_name.lower())
except:
ver = None
if ver is None:
try:
ver = importlib.metadata.version(package_name.replace("_", "-"))
except:
ver = None
return ver
def is_package_installed(package: str) -> bool:
"""判断 Python 软件包是否已安装在环境中
参数:
package (`str`):
Python 软件包名
返回值:
`bool`: 如果 Python 软件包未安装或者未安装正确的版本, 则返回`False`
"""
# 分割 Python 软件包名和版本号
if "===" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("===")]
elif "~=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("~=")]
elif "!=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("!=")]
elif "<=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("<=")]
elif ">=" in package:
pkg_name, pkg_version = [x.strip() for x in package.split(">=")]
elif "<" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("<")]
elif ">" in package:
pkg_name, pkg_version = [x.strip() for x in package.split(">")]
elif "==" in package:
pkg_name, pkg_version = [x.strip() for x in package.split("==")]
else:
pkg_name, pkg_version = package.strip(), None
env_pkg_version = get_package_version_from_library(pkg_name)
logger.debug(
"已安装 Python 软件包检测: pkg_name: %s, env_pkg_version: %s, pkg_version: %s",
pkg_name,
env_pkg_version,
pkg_version,
)
if env_pkg_version is None:
return False
if pkg_version is not None:
# ok = env_pkg_version === / == pkg_version
if "===" in package or "==" in package:
logger.debug("包含条件: === / ==")
if is_v1_eq_v2(env_pkg_version, pkg_version):
logger.debug("%s == %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version ~= pkg_version
if "~=" in package:
logger.debug("包含条件: ~=")
if is_v1_c_eq_v2(pkg_version, env_pkg_version):
logger.debug("%s ~= %s", pkg_version, env_pkg_version)
return True
# ok = env_pkg_version != pkg_version
if "!=" in package:
logger.debug("包含条件: !=")
if not is_v1_eq_v2(env_pkg_version, pkg_version):
logger.debug("%s != %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version <= pkg_version
if "<=" in package:
logger.debug("包含条件: <=")
if is_v1_le_v2(env_pkg_version, pkg_version):
logger.debug("%s <= %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version >= pkg_version
if ">=" in package:
logger.debug("包含条件: >=")
if is_v1_ge_v2(env_pkg_version, pkg_version):
logger.debug("%s >= %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version < pkg_version
if "<" in package:
logger.debug("包含条件: <")
if is_v1_lt_v2(env_pkg_version, pkg_version):
logger.debug("%s < %s", env_pkg_version, pkg_version)
return True
# ok = env_pkg_version > pkg_version
if ">" in package:
logger.debug("包含条件: >")
if is_v1_gt_v2(env_pkg_version, pkg_version):
logger.debug("%s > %s", env_pkg_version, pkg_version)
return True
logger.debug("%s 需要安装", package)
return False
return True
def validate_requirements(requirement_path: Union[str, Path]) -> bool:
"""检测环境依赖是否完整
参数:
requirement_path (`str`, `Path`):
依赖文件路径
返回值:
`bool`: 如果有缺失依赖则返回`False`
"""
origin_requires = read_packages_from_requirements_file(requirement_path)
requires = parse_requirement_list(origin_requires)
for package in requires:
if not is_package_installed(package):
return False
return True
def main() -> None:
requirement_path = COMMAND_ARGS.requirement_path
if not os.path.isfile(requirement_path):
logger.error("依赖文件未找到, 无法检查运行环境")
sys.exit(1)
logger.debug("检测运行环境中")
print(validate_requirements(requirement_path))
logger.debug("环境检查完成")
if __name__ == "__main__":
main()
|
2301_81996401/term-sd
|
python_modules/validate_requirements.py
|
Python
|
agpl-3.0
| 31,440
|
#!/bin/bash
# Term-SD 启动参数处理
# 设置 TERM_SD_SCRIPT_NAME 全局变量读取要启动的 Term-SD 扩展脚本
term_sd_launch_arg_parse() {
local argument_input
local argument
local i
# 用别的方法实现了 getopt 命令的功能
# 加一个 --null 是为了增加一次循环, 保证那些需要参数的选项能成功执行
for i in "$@" "--null"; do
argument=$i # 用作判断是参数还是选项
# 参数检测部分
if [[ ! -z "${argument_input}" ]]; then
if term_sd_is_launch_arg "${argument}"; then # 测试输入值是参数还是选项
unset argument # 检测到选项的下一项是选项, 直接清除
fi
# 检测输入的选项
case "${argument_input}" in
--set-python-path)
set_python_path "${argument}"
;;
--extra)
TERM_SD_SCRIPT_NAME=$argument
;;
--bar)
term_sd_loading_bar_setting "${argument}"
;;
esac
unset argument_input # 清除选项, 留给下一次判断
fi
####################
# 选项检测部分(如果选项要跟参数值,则将启动选项赋值给 argument_input)
case "${i}" in
--help)
term_sd_print_line
term_sd_args_help
term_sd_print_line
exit 0
;;
--reinstall-term-sd)
# 防止重启后再执行重装
case "${TERM_SD_IS_REINSTALL}" in
1)
;;
*)
TERM_SD_IS_REINSTALL=1
term_sd_reinstall
;;
esac
;;
--set-python-path)
argument_input="--set-python-path"
;;
--unset-python-path)
rm -f "${START_PATH}/term-sd/config/python-path.conf"
term_sd_echo "已删除自定义 Python 解释器路径配置"
;;
--bar)
argument_input="--bar"
;;
--update-pip)
ENABLE_PIP_VER_CHECK=1
PIP_DISABLE_PIP_VERSION_CHECK=0
term_sd_echo "进入虚拟环境时将更新 Python 软件包管理器"
;;
--remove-term-sd)
term_sd_remove
;;
--quick-cmd)
install_cmd_to_shell
exit 0
;;
--extra)
argument_input="--extra"
;;
--debug)
term_sd_echo "显示 Term-SD 调试信息"
TERM_SD_ENABLE_DEBUG=1
;;
--unset-tcmalloc)
USE_TCMALLOC=0
term_sd_echo "禁用加载 TCMalloc 内存优化"
;;
*)
term_sd_unknown_args_echo ${i}
;;
esac
done
}
# Term-SD 命令行帮助信息
term_sd_args_help() {
cat<<EOF
Term-SD 启动参数使用方法:
term-sd.sh [--help] [--extra script_name] [--reinstall-term-sd] [--remove-term-sd] [--quick-cmd] [--set-python-path python_path] [--unset-python-path] [--update-pip] [--bar display_mode] [--debug]
选项:
--help
显示启动参数帮助
--extra script_name
启动扩展脚本选择列表, 当选项后面输入了脚本名, 则直接启动指定的脚本, 否则启动扩展脚本选择界面
--reinstall-term-sd
重新安装 Term-SD
--remove-term-sd
卸载 Term-SD
--quick-cmd
添加 Term-SD 快捷启动命令到 Shell
--set-python-path python_path
手动指定 Python 解释器路径, 当选项后面输入了路径, 则直接使用输入的路径来设置 Python 解释器路径 (建议用" "把路径括起来, 防止路径输入错误), 否则启动设置界面
--unset-python-path
删除自定义 Python 解释器路径配置
--update-pip
进入虚拟环境时更新 Python 软件包管理器
--bar display_mode
设置 Term-SD 初始化进度条的显示样式, 有以下显示模式:
none: 禁用进度条显示
normal: 使用默认的显示模式
new: 使用新的进度条显示
--debug
显示 Term-SD 安装 AI 软件时使用的命令
--unset-tcmalloc
禁用加载内存优化
EOF
}
# Term-SD 扩展脚本启动功能
term_sd_extra_scripts_launch() {
if [[ -z "$@" ]]; then
term_sd_extra_scripts
else
if [[ -f "term-sd/extra/${@%.sh}.sh" ]]; then
term_sd_print_line "${@%.sh} 脚本启动"
term_sd_echo "启动 ${@%.sh} 脚本中"
. "${START_PATH}/term-sd/extra/${@%.sh}.sh"
term_sd_print_line
term_sd_echo "退出 ${@%.sh} 脚本"
exit 0
else
term_sd_print_line
term_sd_echo "未找到 ${@%.sh} 脚本"
term_sd_echo "退出 Term-SD"
exit 1
fi
fi
}
# 扩展脚本选择
term_sd_extra_scripts() {
local extra_script
extra_script=$(dialog --erase-on-exit \
--title "Term-SD" \
--backtitle "扩展脚本选项" \
--ok-label "确认" --cancel-label "取消" \
--menu "请选择要启动的脚本" \
$(get_dialog_size_menu) \
"Term-SD" "<---------" \
$(ls -l "term-sd/extra" --time-style=+"%Y-%m-%d" | awk '{ print $7 " " $6 }') \
"退出" "<---------" \
3>&1 1>&2 2>&3)
case "$?" in
0)
case "${extra_script}" in
Term-SD)
. "${START_PATH}/term-sd/modules/init.sh"
term_sd_version
main
;;
退出)
term_sd_print_line
term_sd_echo "退出Term-SD"
exit 0
;;
*)
term_sd_print_line "${extra_script%.sh} 脚本启动"
. "${START_PATH}/term-sd/extra/"${extra_script}""
term_sd_print_line
term_sd_echo "退出 ${extra_script%.sh} 脚本"
exit 0
esac
;;
*)
term_sd_echo "退出 Term-SD"
exit 0
;;
esac
}
# 格式化信息输出
# 使用:
# term_sd_echo <输出信息>
term_sd_echo() {
echo -e "[\033[33m$(date "+%Y-%m-%d %H:%M:%S")\033[0m][\033[36mTerm-SD\033[0m]\033[36m::\033[0m $@"
}
# 键盘输入读取
# 回车接收读取到的输入并输出
term_sd_read() {
local input_text
read -p "===============================> " input_text
echo "${input_text}"
}
# 暂停运行(用于显示运行结果)
term_sd_pause() {
term_sd_print_line
term_sd_echo "执行结束, 请按回车键继续"
read
}
# 测试输入值是参数还是选项, 是选项返回 0, 是参返回 1 (用于实现 getopt 命令的功能)
term_sd_is_launch_arg() {
if [[ "$(echo $@ | awk '{for (i = 1; i <= NF; i++) {if (substr($i, 1, 2) == "--") {print "0"} else {print "1"}}}')" == 0 ]]; then
return 0
else
return 1
fi
}
# 提示未知启动参数
term_sd_unknown_args_echo() {
if term_sd_is_launch_arg "$@" && [[ ! "$@" == "--null" ]]; then # 测试输入值是参数还是选项
term_sd_echo "未知参数: $@"
fi
}
# 创建目录
# 如果目录不存在则自动创建一个
# 使用:
# term_sd_mkdir <需创建的文件夹名>
term_sd_mkdir() {
if [[ ! -d "$@" ]]; then
mkdir -p "$@"
else
true
fi
}
# 暂停执行
# 使用:
# term_sd_sleep <暂停的时间>
term_sd_sleep() {
local pause_time=$1
local i
for (( i = pause_time; i >= 0; i-- )); do
printf "[\033[33m$(date "+%Y-%m-%d %H:%M:%S")\033[0m][\033[36mTerm-SD\033[0m]\033[36m::\033[0m 等待中: ${i} \r"
sleep 1
done
printf " \r"
}
# 路径格式转换(将 Windows 风格的文件路径转换成 Linux / Unix 风格的路径)
term_sd_win2unix_path() {
if is_windows_platform; then
if which cygpath &> /dev/null; then
# cygpath 可用于将 Windows 风格的路径转换成 Linux / Unix 风格的路径, 参考: https://cygwin.com/cygwin-ug-net/cygpath.html
# cygpath -w "${origin_path}" -> Windows style path
# cygpath -u "${origin_path}" -> *nix style path
echo "$(cygpath -a -u "$@")"
else
echo "$(cd "$(dirname "$@" 2> /dev/null)" ; pwd)/$(basename "$@" 2> /dev/null)"
fi
else
echo "$@"
fi
}
# 检测目录是否为空, 为空是返回 0, 不为空返回 1
term_sd_is_dir_empty() {
if [[ $(ls "$@" -al --format=horizontal | wc --words) -le 2 ]]; then
return 0
else
return 1
fi
}
# 系统判断
# 当 Term-SD 未初始化完成时(term_sd_python 命令未能使用), 使用 OS 环境变量判断系统的类型
is_windows_platform() {
local sys_platform
if term_sd_python --version &> /dev/null; then
sys_platform=$(term_sd_python -c "$(py_is_windows_platform)")
else
case "${OS}" in
"Windows_NT")
sys_platform="win32"
;;
*)
sys_platform="other"
;;
esac
fi
if [[ "${sys_platform}" = "win32" ]]; then
return 0
else
return 1
fi
}
# 系统判断(Python)
py_is_windows_platform() {
cat<<EOF
import sys
if sys.platform == "win32":
print("win32")
else:
print("other")
EOF
}
# 加载进度条设置
# 配置保存在 <Start Path>/term-sd/config/term-sd-bar.conf
term_sd_loading_bar_setting() {
if [[ -z "$@" ]]; then
term_sd_echo "未指定 Term-SD 初始化进度条的显示模式"
else
case "$@" in
"none")
echo "none" > "${START_PATH}/term-sd/config/term-sd-bar.conf"
term_sd_echo "禁用 Term-SD 初始化进度显示"
;;
"normal")
rm -f "${START_PATH}/term-sd/config/term-sd-bar.conf"
term_sd_echo "使用默认 Term-SD 初始化进度显示模式"
;;
"new")
echo "new" > "${START_PATH}/term-sd/config/term-sd-bar.conf"
term_sd_echo "使用新的 Term-SD 初始化进度显示模式"
;;
*)
term_sd_echo "未知的 Term-SD 初始化进度条显示模式"
;;
esac
fi
}
# 终端横线显示功能
# 使用:
# term_sd_print_line <输出的文本>
# 使用 SHELL_WIDTH 全局变量获取终端宽度
term_sd_print_line() {
local shell_width
local input_text
local input_text_length
local input_zh_text_length
local shell_width_info
local text_length_info
local print_mode
if [[ -z "$@" ]]; then # 输出方法选择
print_mode=1
else
shell_width=$SHELL_WIDTH # 获取终端宽度
input_text=$(echo "$@" | awk '{gsub(/ /,"-")}1') # 将空格转换为"-"
input_text_length=$(( $(echo "${input_text}" | wc -c) - 1 )) # 总共的字符长度
input_zh_text_length=$(( $(echo "${input_text}" | awk '{gsub(/[a-zA-Z]/,"") ; gsub(/[0-9]/, "") ; gsub(/[=+()()、。,./\-_\\]/, "")}1' | wc -c) - 1 )) # 计算中文字符的长度
input_text_length=$(( input_text_length - input_zh_text_length )) # 除去中文之后的长度
# 中文的字符长度为3,但终端中只占2个字符位
input_zh_text_length=$(( input_zh_text_length / 3 * 2 )) # 转换中文在终端占用的实际字符长度
input_text_length=$(( input_text_length + input_zh_text_length )) # 最终显示文字的长度
# 横线输出长度的计算
shell_width=$(( (shell_width - input_text_length) / 2 )) # 除去输出字符后的横线宽度
# 判断终端宽度大小是否是单双数
shell_width_info=$(( shell_width % 2 ))
# 判断字符宽度大小是否是单双数
text_length_info=$(( input_text_length % 2 ))
case "${shell_width_info}" in
0)
# 如果终端宽度大小是双数
case "${text_length_info}" in
0)
# 如果字符宽度大小是双数
print_mode=2
;;
1)
# 如果字符宽度大小是单数
print_mode=3
;;
esac
;;
1)
# 如果终端宽度大小是单数数
case "${text_length_info}" in
0)
# 如果字符宽度大小是双数
print_mode=2
;;
1)
# 如果字符宽度大小是单数
print_mode=3
;;
esac
;;
esac
fi
# 输出
case "${print_mode}" in
1)
shell_width=$SHELL_WIDTH # 获取终端宽度
yes "-" | sed $shell_width'q' | tr -d '\n' # 输出横杠
;;
2)
# 解决显示字符为单数时少显示一个字符导致不对成的问题
echo "$(yes "-" | sed "${shell_width}"'q' | tr -d '\n')"$@"$(yes "-" | sed "${shell_width}"'q' | tr -d '\n')"
;;
3)
echo "$(yes "-" | sed "${shell_width}"'q' | tr -d '\n')"$@"$(yes "-" | sed $(( shell_width + 1 ))'q' | tr -d '\n')"
;;
esac
}
# Term-SD 自动更新触发功能
# 使用 <Start Path>/term-sd/config/term-sd-auto-update.lock 检测是否启用的自动更新
# 使用 <Start Path>/term-sd/config/term-sd-auto-update-time.conf 获取上次更新的时间
term_sd_auto_update_trigger() {
local start_time
local end_time
local start_time_sec
local end_time_sec
local time_span
local normal_time_span=3600 # 检查更新时间间隔
if [[ -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock" ]] && [[ -d "${START_PATH}/term-sd/.git" ]]; then # 找到自动更新配置
if [[ -f "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf" ]]; then # 有上次运行记录
start_time=`date +'%Y-%m-%d %H:%M:%S'` # 查看当前时间
end_time=$(cat "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf") # 获取上次更新时间
start_time_sec=$(date --date="${start_time}" +%s) # 转换时间单位
end_time_sec=$(date --date="${end_time}" +%s)
time_span=$(( start_time_sec - end_time_sec )) # 计算相隔时间
if (( time_span >= normal_time_span )); then # 判断时间间隔
term_sd_auto_update
date +'%Y-%m-%d %H:%M:%S' > "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf" # 记录自动更新功能的启动时间
fi
else # 没有时直接执行
term_sd_auto_update
date +'%Y-%m-%d %H:%M:%S' > "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf" # 记录自动更新功能的启动时间
fi
fi
}
# Term-SD 自动更新功能
term_sd_auto_update() {
local ref
local origin_branch
local commit_hash
local local_commit_hash
term_sd_echo "检查更新中"
git -C term-sd fetch || HTTP_PROXY="" HTTPS_PROXY="" git -C term-sd fetch
if [[ "$?" = 0 ]]; then # 拉取远端内容成功后再更新
ref=$(git -C "${START_PATH}/term-sd" symbolic-ref --quiet HEAD 2> /dev/null)
if [[ "$?" = 0 ]]; then # 未出现分支游离
origin_branch="origin/${ref#refs/heads/}"
else # 出现分支游离时查询HEAD所指的分支
origin_branch="origin/$(git -C "${START_PATH}/term-sd" branch -a | grep "/HEAD" | awk -F '/' '{print $NF}')"
fi
commit_hash=$(git -C "${START_PATH}/term-sd" log "${origin_branch}" --max-count 1 --format="%h")
local_commit_hash=$(git -C "${START_PATH}/term-sd" show -s --format="%h")
if [[ ! "${commit_hash}" == "${local_commit_hash}" ]]; then
term_sd_echo "检测到 Term-SD 有新版本"
term_sd_echo "是否选择更新 (yes/no) ?"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
yes|y|YES|Y)
term_sd_echo "更新 Term-SD 中"
git -C "${START_PATH}/term-sd" reset --hard "${commit_hash}"
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}/"
chmod +x "${START_PATH}/term-sd.sh"
TERM_SD_TO_RESTART=1
term_sd_echo "Term-SD 更新完成"
;;
*)
term_sd_echo "跳过 Term-SD 的更新"
;;
esac
else
term_sd_echo "Term-SD 已经是最新版本"
fi
else
term_sd_echo "Term-SD 连接更新源失败, 跳过更新"
term_sd_echo "提示: 请检查网络连接是否正常, 若网络正常, 可尝试更换更新源或使用科学上网解决"
fi
}
# Term-SD 安装功能
term_sd_install() {
if [[ ! -d "${START_PATH}/term-sd" ]]; then
term_sd_echo "检测到 Term-SD 组件未安装, 开始下载组件中"
term_sd_clone_modules
if [[ "$?" == 0 ]]; then
term_sd_set_up_normal_setting
TERM_SD_TO_RESTART=1
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}/"
chmod +x "${START_PATH}/term-sd.sh"
term_sd_echo "Term-SD 安装成功"
else
term_sd_echo "Term-SD 安装失败, 可尝试重新运行"
exit 1
fi
elif [[ ! -d "${START_PATH}/term-sd/.git" ]]; then
term_sd_echo "检测到 Term-SD 的 .git 目录不存在, 将会导致 Term-SD 无法更新, 是否重新安装 (yes/no) ?"
term_sd_echo "警告: 该操作将永久删除 Term-SD 目录中的所有文件 (除了 Term-SD 缓存文件夹和配置文件将备份到临时文件夹并在安装完成还原)"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
yes|y|YES|Y)
term_sd_backup_config
term_sd_echo "清除 Term-SD 文件中"
rm -rf "${START_PATH}/term-sd"
term_sd_echo "Term-SD 文件清除完成"
term_sd_clone_modules
if [[ "$?" == 0 ]]; then
term_sd_restore_config
TERM_SD_TO_RESTART=1
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}/"
chmod +x "${START_PATH}/term-sd.sh"
term_sd_echo "Term-SD 重新安装成功"
else
term_sd_echo "Term-SD 重新安装失败"
exit 1
fi
;;
*)
term_sd_echo "取消重新安装 Term-SD 操作"
;;
esac
fi
}
# Term-SD 重新安装功能
# 使用 TERM_SD_TO_RESTART 全局变量标记 Term-SD 需要进行重载
term_sd_reinstall() {
if which git &> /dev/null; then
term_sd_echo "是否重新安装 Term-SD (yes/no) ?"
term_sd_echo "警告: 该操作将永久删除 Term-SD 目录中的所有文件 (除了 Term-SD 缓存文件夹和配置文件将备份到临时文件夹并在安装完成还原)"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
yes|y|YES|Y)
term_sd_backup_config
term_sd_echo "清除 Term-SD 文件中"
rm -rf "${START_PATH}/term-sd"
term_sd_echo "Term-SD 文件清除完成"
term_sd_clone_modules
if [[ "$?" == 0 ]]; then
term_sd_restore_config
TERM_SD_TO_RESTART=1
cp -f "${START_PATH}/term-sd/term-sd.sh" "${START_PATH}/"
chmod +x "${START_PATH}/term-sd.sh"
term_sd_echo "Term-SD 重新安装成功"
else
term_sd_echo "Term-SD 重新安装失败"
exit 1
fi
;;
*)
term_sd_echo "退出 Term-SD"
exit 0
;;
esac
else
term_sd_echo "缺少 Git, 无法重新安装 Term-SD"
fi
}
# 下载 Term-SD
term_sd_clone_modules() {
local i
local count=0
local repo_urls="https://github.com/licyk/term-sd https://gitee.com/licyk/term-sd https://gitlab.com/licyk/term-sd"
term_sd_echo "下载 Term-SD 中"
for i in ${repo_urls}; do
count=$((count + 1))
git clone "${i}" "${START_PATH}/term-sd"
if [[ "$?" == 0 ]]; then
term_sd_echo "Term-SD 下载成功"
return 0
else
term_sd_echo "Term-SD 下载失败"
if [[ "${count}" -lt "$(echo "${repo_urls}" | wc --words)" ]]; then
term_sd_echo "更换 Term-SD 下载源进行下载中"
else
return 1
fi
fi
done
}
# 备份 cache 文件夹
# 备份的 cache 文件夹保存在 <Start Path>/term-sd-tmp
term_sd_backup_config() {
term_sd_echo "备份 Term-SD 缓存文件夹和配置文件中"
term_sd_mkdir "${START_PATH}/term-sd-tmp"
term_sd_mkdir "${START_PATH}/term-sd-tmp/config"
rm -f "${START_PATH}/term-sd/config/note.md"
[[ -d "${START_PATH}/term-sd/config" ]] && mv -f "${START_PATH}"/term-sd/config/* "${START_PATH}"/term-sd-tmp/config
[[ -d "${START_PATH}/term-sd/cache" ]] && mv -f "${START_PATH}"/term-sd/cache "${START_PATH}"/term-sd-tmp
[[ -d "${START_PATH}/term-sd/requirements-backup" ]] && mv -f "${START_PATH}"/term-sd/requirements-backup "${START_PATH}"/term-sd-tmp
[[ -d "${START_PATH}/term-sd/backup" ]] && mv -f "${START_PATH}"/term-sd/backup "${START_PATH}"/term-sd-tmp
}
# 恢复 cache 文件夹
# 从 <Start Path>/term-sd-tmp 恢复文件到 <Start Path>/term-sd 中
term_sd_restore_config() {
term_sd_echo "恢复 Term-SD 缓存文件夹和配置文件中"
[[ -d "${START_PATH}/term-sd-tmp/cache" ]] && mv -f "${START_PATH}/term-sd-tmp/cache" "${START_PATH}/term-sd"
[[ -d "${START_PATH}/term-sd-tmp/config" ]] && mv -f "${START_PATH}"/term-sd-tmp/config/* "${START_PATH}/term-sd/config"
[[ -d "${START_PATH}/term-sd-tmp/requirements-backup" ]] && mv -f "${START_PATH}/term-sd-tmp/requirements-backup" "${START_PATH}/term-sd"
[[ -d "${START_PATH}/term-sd-tmp/backup" ]] && mv -f "${START_PATH}/term-sd-tmp/backup" "${START_PATH}/term-sd"
rm -rf "${START_PATH}/term-sd-tmp"
}
# 设置默认 Term-SD 设置
# 设置完成后使用 <Start Path>/term-sd/config/install-by-launch-script.lock 标记已执行设置
term_sd_set_up_normal_setting() {
if [[ ! -f "${START_PATH}/term-sd/config/term-sd-watch-retry.conf" ]]; then
echo "3" > "${START_PATH}/term-sd/config/term-sd-watch-retry.conf"
TERM_SD_CMD_RETRY=3
term_sd_echo "Term-SD 命令执行监测设置已自动设置"
fi
if [[ ! -f "${START_PATH}/term-sd/config/term-sd-auto-update.lock" ]]; then
touch "${START_PATH}/term-sd/config/term-sd-auto-update.lock"
date +'%Y-%m-%d %H:%M:%S' > "${START_PATH}/term-sd/config/term-sd-auto-update-time.conf"
term_sd_echo "Term-SD 自动更新已自动设置"
fi
if [[ ! -f "${START_PATH}/term-sd/config/set-aria2-thread.conf" ]]; then
echo "16" > "${START_PATH}/term-sd/config/set-aria2-thread.conf"
term_sd_echo "Term-SD 设置 Aria2 下载线程为 16"
fi
if [[ ! -f "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf" ]]; then
echo "2" > "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf"
term_sd_echo "Term-SD 设置 PyPI 镜像源为国内镜像源"
fi
if [[ ! -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
touch "${START_PATH}"/term-sd/config/set-dynamic-global-github-mirror.lock
term_sd_echo "Term-SD 启用 Github 镜像源"
fi
if [[ ! -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
touch "${START_PATH}"/term-sd/config/set-dynamic-global-huggingface-mirror.lock
term_sd_echo "Term-SD 启用 HuggingFace 镜像源"
fi
if [[ ! -f "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock" ]];then
touch "${START_PATH}/term-sd/config/set-cuda-memory-alloc.lock"
term_sd_echo "Term-SD 启用 CUDA 内存分配器设置"
fi
if [[ ! -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock" ]]; then
touch -f "${START_PATH}/term-sd/config/enable-dynamic-proxy.lock"
term_sd_echo "Term-SD 启动动态代理设置"
fi
touch "${START_PATH}/term-sd/config/install-by-launch-script.lock"
}
# Term-SD 卸载功能
term_sd_remove() {
term_sd_echo "是否卸载 Term-SD ?"
term_sd_echo "警告: 该操作将永久删除 Term-SD 目录中的所有文件, 包括 AI 软件下载的部分模型文件 (存在于 Term-SD 目录中的 cache 文件夹, 如有必要, 请备份该文件夹)"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
y|yes|YES|Y)
term_sd_echo "开始卸载 Term-SD"
rm -rf "${START_PATH}/term-sd"
rm -rf "${START_PATH}/term-sd.sh"
if [[ "${USER_SHELL}" == "bash" ]] || [[ "${USER_SHELL}" == "zsh" ]]; then
remove_config_from_shell
fi
term_sd_echo "Term-SD 卸载完成"
;;
*)
term_sd_echo "取消操作"
;;
esac
exit 0
}
# Term-SD 添加快捷命令功能
# 仅支持在 Bash, Zsh 中添加快捷启动 Term-SD 命令
# 快捷启动命令保存在 .bashrc / .zshrc 文件中
install_cmd_to_shell() {
while true; do
case "${USER_SHELL}" in
bash|zsh)
term_sd_echo "是否将 Term-SD 快捷启动命令添加到 Shell 环境中 ?"
term_sd_echo "添加后可使用 term_sd, tsd 命令启动 Term-SD"
term_sd_echo "1、添加"
term_sd_echo "2、删除"
term_sd_echo "3、退出"
term_sd_echo "提示: 输入数字后回车"
case "$(term_sd_read)" in
1)
if cat ~/."${USER_SHELL}"rc | grep term_sd > /dev/null; then
term_sd_echo "Term-SD 快捷启动命令已存在, 是否刷新 (yes/no) ? "
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
y|yes|YES|Y)
remove_config_from_shell
install_config_to_shell
term_sd_echo "Term-SD 快捷启动命令刷新完成, 可使用 term_sd, tsd 命令启动 Term-SD, 退出 Term-SD 并重启 Shell"
exec "${SHELL}"
;;
*)
term_sd_echo "取消更新 Term-SD 快捷启动命令操作"
;;
esac
else
install_config_to_shell
term_sd_echo "Term-SD 快捷启动命令添加完成, 可使用 term_sd, tsd 命令启动 Term-SD, 退出 Term-SD 并重启 Shell"
exec "${SHELL}"
fi
break
;;
2)
remove_config_from_shell
term_sd_echo "Term-SD 快捷启动命令已删除, 退出 Term-SD 并重启 Shell"
exec "${SHELL}"
break
;;
3)
exit 0
;;
*)
term_sd_echo "输入有误, 请重试"
;;
esac
;;
*)
term_sd_echo "不支持该 Shell"
;;
esac
done
}
# 将快捷命令写入 Shell 配置文件中
install_config_to_shell() {
cat<<EOF >> ~/."${USER_SHELL}"rc
# Term-SD
term_sd(){ [[ "\${OSTYPE}" == "darwin"* ]] && export PATH="/usr/local/bin:\${PATH}"; "\$(which bash)" "$(pwd)/term-sd.sh" "\$@" || echo -e "[\033[33m\$(date "+%Y-%m-%d %H:%M:%S")\033[0m][\033[36mTerm-SD\033[0m]\033[36m::\033[0m Term-SD 异常退出" ; }
alias tsd="term_sd"
EOF
}
# 将快捷命令从 Shell 配置文件中删除
remove_config_from_shell() {
sed -i '/# Term-SD/d' ~/."${USER_SHELL}"rc
sed -i '/term_sd(){/d' ~/."${USER_SHELL}"rc
sed -i '/alias tsd/d' ~/."${USER_SHELL}"rc
}
# 手动指定 Python 路径功能
# 如果 Python 可用, 则使用 TERM_SD_PYTHON_PATH 全局变量保存 Python 路径
# 将 Python 路径保存在 <Start Path>/term-sd/config/python-path.conf 文件中
set_python_path() {
local input_python_path
while true; do
if [[ -z "$@" ]]; then
term_sd_echo "请输入 Python 解释器的路径"
term_sd_echo "提示: 输入完后请回车保存, 或者输入 exit 退出"
read -p "===============================> " input_python_path
if [[ -z "${input_python_path}" ]]; then
term_sd_echo "未输入, 请重试"
elif [[ "${input_python_path}" = "exit" ]]; then
term_sd_echo "退出 Python 解释器路径指定功能"
break
elif [[ -f "${input_python_path}" ]]; then
TERM_SD_PYTHON_PATH=$(term_sd_win2unix_path "${input_python_path}")
echo "${TERM_SD_PYTHON_PATH}" > "${START_PATH}/term-sd/config/python-path.conf"
term_sd_echo "Python 解释器路径指定完成"
term_sd_echo "提示:"
term_sd_echo "使用 --set-python-path 重新设置 Python 解释器路径"
term_sd_echo "使用 --unset-python-path 删除 Python 解释器路径设置"
break
else
term_sd_echo "输入的路径有误, 请重试"
fi
else # 直接将选项后面的参数作为路径
if [[ -f "$@" ]]; then
term_sd_echo "设置 Python 解释器路径: $@"
TERM_SD_PYTHON_PATH=$(term_sd_win2unix_path "$@")
echo "$TERM_SD_PYTHON_PATH" > "${START_PATH}/term-sd/config/python-path.conf"
term_sd_echo "Python 解释器路径指定完成"
term_sd_echo "提示:"
term_sd_echo "使用 --set-python-path 重新设置 Python 解释器路径"
term_sd_echo "使用 --unset-python-path 删除 Python 解释器路径设置"
break
else
term_sd_echo "输入的路径有误, 跳过指定 Python 解释器路径"
break
fi
fi
done
}
# 配置内存优化(仅限 Linux)
prepare_tcmalloc() {
local LIBC_VER
local libc_vernum
local libc_v234
local TCMALLOC_LIBS
local lib
local TCMALLOC
local TC_INFO
case "${USE_TCMALLOC}" in
0)
term_sd_echo "取消加载内存优化"
;;
*)
if [[ "${OSTYPE}" == "linux"* ]] && [[ -z "${LD_PRELOAD}" ]]; then
term_sd_echo "检测到系统为 Linux, 尝试启用内存优化"
# 检查glibc版本
LIBC_VER=$(echo $(ldd --version | awk 'NR==1 {print $NF}') | grep -oP '\d+\.\d+')
term_sd_echo "glibc 版本为 ${LIBC_VER}"
libc_vernum=$(expr ${LIBC_VER})
# 从 2.34 开始,libpthread 已经集成到 libc.so 中
libc_v234=2.34
# 定义 Tcmalloc 库数组
TCMALLOC_LIBS=("libtcmalloc(_minimal|)\.so\.\d" "libtcmalloc\.so\.\d")
# 遍历数组
for lib in "${TCMALLOC_LIBS[@]}"
do
# 确定库支持的 Tcmalloc 类型
TCMALLOC="$(PATH=/usr/sbin:${PATH} ldconfig -p | grep -P "${lib}" | head -n 1)"
TC_INFO=(${TCMALLOC//=>/})
if [[ ! -z "${TC_INFO}" ]]; then
term_sd_echo "检查 TCMalloc: ${TC_INFO}"
# 确定库是否链接到 libpthread 和解析未定义符号: pthread_key_create
if [ $(echo "$libc_vernum < $libc_v234" | bc) -eq 1 ]; then
# glibc < 2.34,pthread_key_create 在 libpthread.so 中。检查链接到 libpthread.so
if ldd ${TC_INFO[2]} | grep -q 'libpthread'; then
term_sd_echo "$TC_INFO 链接到 libpthread, 执行 LD_PRELOAD=${TC_INFO[2]}"
# 设置完整路径 LD_PRELOAD
export LD_PRELOAD="${TC_INFO[2]}"
break
else
term_sd_echo "${TC_INFO} 没有链接到 libpthread, 将触发未定义符号: pthread_Key_create 错误"
fi
else
# libc.so(glibc)的2.34版本已将pthread库集成到glibc内部。在Ubuntu 22.04系统以及现代Linux系统和WSL(Windows Subsystem for Linux)环境下
# libc.so(glibc)链接了一个几乎能在所有Linux用户态环境中运行的库,因此通常无需额外检查
term_sd_echo "${TC_INFO} 链接到 libc.so, 执行 LD_PRELOAD=${TC_INFO[2]}"
# 设置完整路径 LD_PRELOAD
export LD_PRELOAD="${TC_INFO[2]}"
break
fi
fi
done
if [[ -z "${LD_PRELOAD}" ]]; then
term_sd_echo "无法定位 TCMalloc。未在系统上找到 tcmalloc 或 google-perftool"
term_sd_echo "取消加载内存优化"
term_sd_echo "提示: 可根据 Term-SD 帮助文档安装 google-perftool"
[[ ! "${TERM_SD_DISABLE_COUNTDOWN}" == 1 ]] && term_sd_sleep 3
fi
fi
;;
esac
}
# 配置默认 Git 配置
set_normal_git_config() {
git config --global --add safe.directory "*"
git config --global core.longpaths true
}
# 自动选择 Github 镜像源
# 如果有可用的镜像源, 则使用 GIT_CONFIG_GLOBAL 环境变量指定 Git 配置文件路径
# 使用 <Start Path>/term-sd/config/set-global-github-mirror.conf 保存镜像源地址
term_sd_auto_setup_github_mirror() {
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]]; then
export GIT_CONFIG_GLOBAL="${START_PATH}/term-sd/config/.gitconfig"
local mirror_status=0
local i
local url
local github_mirror
local HTTP_PROXY
local HTTPS_PROXY
HTTP_PROXY=
HTTPS_PROXY=
rm -f "${START_PATH}"/term-sd/config/.gitconfig
rm -f "${START_PATH}"/term-sd/config/set-global-github-mirror.conf
for i in ${GITHUB_MIRROR_LIST}; do
rm -rf "${START_PATH}/term-sd/task/github_mirror_test" &> /dev/null
github_mirror=$(echo ${i} | awk '{sub("/term_sd_git_user/term_sd_git_repo","")}1')
term_sd_echo "测试 Github 镜像源: ${github_mirror}"
url=$(echo ${i} | awk '{sub("term_sd_git_user","licyk")}1' | awk '{sub("term_sd_git_repo","empty")}1') # 生成格式化之后的链接
git clone "${url}" "${START_PATH}/term-sd/task/github_mirror_test" --depth=1 &> /dev/null # 测试镜像源是否正常连接
git_req=$?
rm -rf "${START_PATH}/term-sd/task/github_mirror_test" &> /dev/null
if [[ "${git_req}" == 0 ]]; then
term_sd_echo "该 Github 镜像源可用"
mirror_status=1
break
fi
done
if [[ "${mirror_status}" == 1 ]]; then
term_sd_echo "设置 Github 镜像源"
set_normal_git_config
git config --global url."${github_mirror}".insteadOf "https://github.com"
echo "${github_mirror}" > "${START_PATH}"/term-sd/config/set-global-github-mirror.conf
else
term_sd_echo "无可用 Github 镜像源, 取消使用 Github 镜像源"
unset GIT_CONFIG_GLOBAL
fi
fi
}
# 自动选择 HuggingFace 镜像源
# 如果有可用的 HuggingFace 镜像, 则使用 HF_ENDPOINT 环境变量指定 HuggingFace 镜像源
# 使用 <Start Path>/term-sd/config/set-global-huggingface-mirror.conf 保存镜像源地址
term_sd_auto_setup_huggingface_mirror() {
if [[ -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]]; then
local mirror_status=0
local i
local huggingface_mirror
local HTTP_PROXY
local HTTPS_PROXY
HTTP_PROXY=
HTTPS_PROXY=
rm -f "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
for i in ${HUGGINGFACE_MIRROR_LIST}; do
term_sd_echo "测试 HuggingFace 镜像源: ${i}"
curl ${i}/licyk/sd-model/resolve/main/README.md -o /dev/null --connect-timeout 10 --silent
if [[ "$?" == 0 ]]; then
term_sd_echo "该 HuggingFace 镜像源可用"
huggingface_mirror=$i
mirror_status=1
break
fi
done
if [[ "${mirror_status}" == 1 ]]; then
term_sd_echo "设置 HuggingFace 镜像源"
export HF_ENDPOINT=$huggingface_mirror
echo "${huggingface_mirror}" > "${START_PATH}"/term-sd/config/set-global-huggingface-mirror.conf
else
term_sd_echo "无可用 HuggingFace 镜像源, 取消设置 HuggingFace 镜像源"
fi
fi
}
# 用户协议
# 同意用户协议后使用 <Start Path>/term-sd/config/agree-user-agreement.lock 标记
term_sd_user_agreement() {
if [[ ! -f "${START_PATH}/term-sd/config/agree-user-agreement.lock" ]]; then
term_sd_print_line "用户协议"
cat term-sd/help/user_agreement.md
echo
term_sd_print_line
term_sd_echo "是否同意该用户协议 (yes/no) ?"
case "$(term_sd_read)" in
yes|y|YES|Y)
touch "${START_PATH}/term-sd/config/agree-user-agreement.lock"
term_sd_echo "确认同意该用户协议"
;;
*)
term_sd_echo "取消同意该用户协议"
term_sd_echo "退出 Term-SD"
exit 0
;;
esac
fi
}
# 获取 Dialog 的宽高度
get_dialog_size() {
echo "${DIALOG_HEIGHT}" "${DIALOG_WIDTH}"
}
# 获取 Dialog 的宽高度(附带 Dialog 菜单高度)
get_dialog_size_menu() {
echo "${DIALOG_HEIGHT}" "${DIALOG_WIDTH}" "${DIALOG_MENU_HEIGHT}"
}
# 为 Pip / uv 创建空的配置文件
term_sd_init_pip_and_uv_config_file() {
local pip_config_file_path=$(dirname "${PIP_CONFIG_FILE}")
local uv_config_file_path=$(dirname "${UV_CONFIG_FILE}")
[[ ! -d "${pip_config_file_path}" ]] && term_sd_mkdir "${pip_config_file_path}"
[[ ! -d "${uv_config_file_path}" ]] && term_sd_mkdir "${uv_config_file_path}"
[[ ! -f "${PIP_CONFIG_FILE}" ]] && touch "${PIP_CONFIG_FILE}"
[[ ! -f "${UV_CONFIG_FILE}" ]] && touch "${UV_CONFIG_FILE}"
}
main() {
# 切换到 term-sd.sh 文件所在位置
cd "$(cd "$(dirname "$0")" ; pwd)"
# 目录结构检测, 发现错误时修正路径
if [[ ! -d "term-sd" ]] \
&& [[ -d "modules" ]] \
&& [[ -f "modules/init.sh" ]] \
&& [[ -d "python_modules" ]] \
&& [[ -d "extra" ]] \
&& [[ -d "install" ]] \
&& [[ -d "task" ]] \
&& [[ -d "help" ]] \
&& [[ -d "config" ]]; then
cd ..
fi
# 为 MacOS 配置 gawk
if [[ ! "${TERM_SD_IS_PREPARE_ENV}" == 1 ]] && [[ "${OSTYPE}" == "darwin"* ]]; then
export PATH="${HOMEBREW_PREFIX}/opt/gawk/libexec/gnubin:${PATH}"
fi
# root 权限检测
if [[ $(id -u) -eq 0 ]] && [[ ! "${TERM_SD_ALLOW_ROOT_LAUNCH}" == 1 ]]; then
term_sd_echo "检测到使用 root 权限运行 Term-SD, 这可能会导致不良后果"
term_sd_echo "是否继续运行 Term-SD (yes/no) ?"
term_sd_echo "提示: 输入 yes 或 no 后回车"
case "$(term_sd_read)" in
yes|y|YES|Y)
TERM_SD_ALLOW_ROOT_LAUNCH=1 # 避免多次弹出提示
term_sd_echo "继续初始化 Term-SD"
;;
*)
term_sd_echo "终止 Term-SD 初始化进程"
term_sd_echo "退出 Term-SD"
exit 0
;;
esac
fi
# 变量初始化
TERM_SD_VER="1.4.16" # Term-SD 版本
TERM_SD_UV_MININUM_VER="0.8" # 设置 uv 的最低版本
TERM_SD_PIP_MININUM_VER="25.0" # 设置 Pip 的最低版本
USER_SHELL=$(basename "${SHELL}") # 读取用户所使用的 Shell
START_PATH=$(pwd) # 设置启动时脚本路径
export PYTHONUTF8=1 # 强制 Python 解释器使用 UTF-8 编码来处理字符串, 避免乱码问题
export PYTHONIOENCODING="utf-8"
export PYTHONUNBUFFERED=1 # 禁用 Python 标准输出缓存
export PYTHONNOUSERSITE=1 # 禁用将用户 site-packages 目录添加到 sys.path
export PYTHONFAULTHANDLER=1 # 启用 Python 回溯信息转储
export PIP_TIMEOUT=30 # 设置 Pip 的超时时间
export PIP_RETRIES=5 # 设置 Pip 的重试次数
export PIP_DISABLE_PIP_VERSION_CHECK # Pip 版本版本检查
export SAFETENSORS_FAST_GPU=1 # 强制所有模型使用 GPU 加载
export PIP_CONFIG_FILE="${START_PATH}/term-sd/config/pip.ini" # 屏蔽本地的 Pip 配置文件
export PIP_PREFER_BINARY=1 # 设置 Pip 优先使用二进制包
export PIP_YES=1 # Pip 卸载软件包时始终确认
export PIP_NO_WARN_SCRIPT_LOCATION=0 # 禁用 Pip 不在 PATH 时的警告
export UV_HTTP_TIMEOUT=30 # 设置 uv 的超时时间
export UV_CONCURRENT_DOWNLOADS=50 # 设置 uv 的下载线程数
export UV_INDEX_STRATEGY="unsafe-best-match" # 设置 uv 匹配 Python 软件包的模式
export UV_CONFIG_FILE="${START_PATH}/term-sd/config/uv.toml" # 屏蔽本地的 uv 配置文件
export GRADIO_ANALYTICS_ENABLED="False" # 禁用 Gradio 新版本提醒
export HF_HUB_DISABLE_SYMLINKS_WARNING=1 # 关闭 HuggingFace 库的禁用 syslinks 警告
export BITSANDBYTES_NOWELCOME=1 # 禁用 bitsandbytes 欢迎信息
export ClDeviceGlobalMemSizeAvailablePercent=100 # 设置内存可用率
export CUDA_MODULE_LOADING="LAZY" # 启用 CUDA 模块懒加载
export TORCH_CUDNN_V8_API_ENABLED=1 # 启用 CUDDN v8 API
export USE_LIBUV=0 # 禁用 PyTorch 使用 libuv
export SYCL_CACHE_PERSISTENT=1 # 启用持久化缓存
export TF_CPP_MIN_LOG_LEVEL=3 # 设置 TensorFlow 日志等级
TERM_SD_PIP_INDEX_URL="https://mirrors.cloud.tencent.com/pypi/simple" # 保存 PyPI 镜像源地址
# TERM_SD_PIP_EXTRA_INDEX_URL="https://mirror.baidu.com/pypi/simple"
TERM_SD_PIP_EXTRA_INDEX_URL="https://mirrors.cernet.edu.cn/pypi/web/simple"
# TERM_SD_PIP_FIND_LINKS="https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html"
TERM_SD_PIP_FIND_LINKS="https://mirrors.aliyun.com/pytorch-wheels/torch_stable.html"
TERM_SD_PYPI_MIRROR="https://licyk.github.io/t/pypi/index.html"
TERM_SD_PIP_INDEX_URL_ARG="" # 用于设置 PyPI 镜像源的命令参数
TERM_SD_PIP_EXTRA_INDEX_URL_ARG=""
TERM_SD_PIP_FIND_LINKS_ARG=""
TERM_SD_UV_INDEX_URL_ARG=""
TERM_SD_UV_EXTRA_INDEX_URL_ARG=""
TERM_SD_UV_FIND_LINKS_ARG=""
# Github 镜像源列表
GITHUB_MIRROR_LIST="\
https://ghfast.top/https://github.com/term_sd_git_user/term_sd_git_repo \
https://mirror.ghproxy.com/https://github.com/term_sd_git_user/term_sd_git_repo \
https://ghproxy.net/https://github.com/term_sd_git_user/term_sd_git_repo \
https://gh.api.99988866.xyz/https://github.com/term_sd_git_user/term_sd_git_repo \
https://gh-proxy.com/https://github.com/term_sd_git_user/term_sd_git_repo \
https://ghps.cc/https://github.com/term_sd_git_user/term_sd_git_repo \
https://gh.idayer.com/https://github.com/term_sd_git_user/term_sd_git_repo \
https://ghproxy.1888866.xyz/github.com/term_sd_git_user/term_sd_git_repo \
https://slink.ltd/https://github.com/term_sd_git_user/term_sd_git_repo \
https://github.boki.moe/github.com/term_sd_git_user/term_sd_git_repo \
https://github.moeyy.xyz/https://github.com/term_sd_git_user/term_sd_git_repo \
https://gh-proxy.net/https://github.com/term_sd_git_user/term_sd_git_repo \
https://gh-proxy.ygxz.in/https://github.com/term_sd_git_user/term_sd_git_repo \
https://wget.la/https://github.com/term_sd_git_user/term_sd_git_repo \
https://kkgithub.com/term_sd_git_user/term_sd_git_repo \
https://gitclone.com/github.com/term_sd_git_user/term_sd_git_repo \
"
HUGGINGFACE_MIRROR_LIST="https://hf-mirror.com https://huggingface.sukaka.top" # HuggingFace 镜像源列表
local term_sd_is_missing_dep=0 # 依赖缺失标记
local term_sd_is_missing_macos_dep=0
TERM_SD_TO_RESTART=0 # Term-SD 是否需要重启的标志
SHELL_WIDTH=$(stty size | awk '{print $2}') # 获取终端宽度
SHELL_HEIGHT=$(stty size | awk '{print $1}') # 获取终端高度
local term_sd_depend="git aria2c dialog curl" # Term-SD 依赖的软件包
local term_sd_depend_macos="wget rustc cmake protoc" # (MacOS)
local term_sd_depend_python="venv tkinter pip" # (Python 模块)
local missing_depend_name
local i
local vc_runtime_dll_path
# 在使用 HTTP_PROXY 变量后, 会出现 ValueError: When localhost is not accessible, a shareable link must be created. Please set share=True
# 导致启动异常
# 需要设置 NO_PROXY 让 localhost,127.0.0.1,::1 不走 HTTP_PROXY
# 参考: https://github.com/microsoft/TaskMatrix/issues/250
# 除了避免 HTTP_PROXY 变量的影响, 也避免了代理软件的影响(在启动 SD WebUI 前开启代理软件可能会导致无法生图(启动后再开启没有影响), 并报错, 设置该变量后完美解决该问题)
export NO_PROXY="localhost,127.0.0.1,::1"
term_sd_print_line "Term-SD"
# 判断直接启动 Term-SD 还是重启 Term-SD
if [[ "${TERM_SD_IS_PREPARE_ENV}" == 1 ]]; then
# 检测到是重启
term_sd_echo "重启 Term-SD 中"
else
term_sd_echo "Term-SD 初始化中"
TERM_SD_SCRIPT_NAME="null" # Term-SD 扩展脚本
term_sd_launch_arg_parse "$@" # 处理用户输入的参数
fi
# Dialog 使用文档: https://manpages.debian.org/bookworm/dialog/dialog.1.en.html
# 设置 Dialog 界面的大小
DIALOG_MENU_HEIGHT=10 # Dialog 列表高度
if [[ $(( SHELL_WIDTH -20 )) -le 12 ]]; then # Dialog 宽度
DIALOG_WIDTH=-1
else
DIALOG_WIDTH=$(( SHELL_WIDTH -20 ))
fi
if [[ $(( SHELL_HEIGHT - 6 )) -le 6 ]]; then # Dialog 高度
DIALOG_HEIGHT=-1
else
DIALOG_HEIGHT=$(( SHELL_HEIGHT - 6 ))
fi
# 分隔符变量
TERM_SD_DELIMITER=$(yes "-" | sed $(( DIALOG_WIDTH - 4 ))'q' | tr -d '\n') # 分隔符号
# 设置 Term-SD 的 Debug 模式的环境变量设置
if [[ -z "${TERM_SD_ENABLE_DEBUG}" ]]; then
TERM_SD_ENABLE_DEBUG=0
fi
# 设置 Pip 自动更新的环境变量设置
if [[ -z "${ENABLE_PIP_VER_CHECK}" ]]; then
ENABLE_PIP_VER_CHECK=0
PIP_DISABLE_PIP_VERSION_CHECK=1
fi
# 存在 Python 自定义路径配置文件时自动读取到变量中
if [[ -f "${START_PATH}/term-sd/config/python-path.conf" ]]; then
TERM_SD_PYTHON_PATH=$(cat "${START_PATH}/term-sd/config/python-path.conf")
fi
if [[ -f "${START_PATH}/term-sd/config/proxy.conf" ]]; then # 读取代理设置并设置代理
export HTTP_PROXY=$(cat "${START_PATH}/term-sd/config/proxy.conf")
export HTTPS_PROXY=$(cat "${START_PATH}/term-sd/config/proxy.conf")
# 代理变量的说明: https://blog.csdn.net/Dancen/article/details/128045261
fi
TERM_SD_PROXY=$HTTPS_PROXY # 代理地址储存到特殊变量中, 用于恢复代理时作为参数使用
# 设置 Term-SD 安装重试次数
if [[ -f "${START_PATH}/term-sd/config/term-sd-watch-retry.conf" ]]; then
TERM_SD_CMD_RETRY=$(cat "${START_PATH}/term-sd/config/term-sd-watch-retry.conf")
else # 没有配置文件时使用默认值
TERM_SD_CMD_RETRY=0
fi
# 设置虚拟环境的启用状态
if [[ -f "${START_PATH}/term-sd/config/term-sd-venv-disable.lock" ]]; then
ENABLE_VENV=0
else
ENABLE_VENV=1
fi
# 设置 Term-SD 执行安装时使用的安装模式
if [[ -f "${START_PATH}/term-sd/config/term-sd-disable-strict-install-mode.lock" ]]; then
TERM_SD_ENABLE_STRICT_INSTALL_MODE=0
else
TERM_SD_ENABLE_STRICT_INSTALL_MODE=1
fi
# 设置 Term-SD 使用的 Python 包管理器
if [[ -f "${START_PATH}/term-sd/config/disable-uv.lock" ]]; then
USE_UV_TO_MANAGE_PACKAGE=0 # 使用 Pip 进行 Python 包管理
else
USE_UV_TO_MANAGE_PACKAGE=1 # 使用 uv 进行 Python 包管理
fi
# 生成设置 PyPI 镜像源的参数
for i in ${TERM_SD_PIP_INDEX_URL}; do
TERM_SD_PIP_INDEX_URL_ARG="${TERM_SD_PIP_INDEX_URL_ARG} --index-url ${i}"
TERM_SD_UV_INDEX_URL_ARG="${TERM_SD_UV_INDEX_URL_ARG} --default-index ${i}"
done
TERM_SD_PIP_INDEX_URL_ARG=$(echo "${TERM_SD_PIP_INDEX_URL_ARG}")
TERM_SD_UV_INDEX_URL_ARG=$(echo "${TERM_SD_UV_INDEX_URL_ARG}")
for i in ${TERM_SD_PIP_EXTRA_INDEX_URL}; do
TERM_SD_PIP_EXTRA_INDEX_URL_ARG="${TERM_SD_PIP_EXTRA_INDEX_URL_ARG} --extra-index-url ${i}"
TERM_SD_UV_EXTRA_INDEX_URL_ARG="${TERM_SD_UV_EXTRA_INDEX_URL_ARG} --index ${i}"
done
TERM_SD_PIP_EXTRA_INDEX_URL_ARG=$(echo "${TERM_SD_PIP_EXTRA_INDEX_URL_ARG}")
TERM_SD_UV_EXTRA_INDEX_URL_ARG=$(echo "${TERM_SD_UV_EXTRA_INDEX_URL_ARG}")
for i in ${TERM_SD_PIP_FIND_LINKS}; do
TERM_SD_PIP_FIND_LINKS_ARG="${TERM_SD_PIP_FIND_LINKS_ARG} --find-links ${i}"
TERM_SD_UV_FIND_LINKS_ARG="${TERM_SD_UV_FIND_LINKS_ARG} --find-links ${i}"
done
TERM_SD_PIP_FIND_LINKS_ARG=$(echo "${TERM_SD_PIP_FIND_LINKS_ARG}")
TERM_SD_UV_FIND_LINKS_ARG=$(echo "${TERM_SD_UV_FIND_LINKS_ARG}")
# 为 uv / Pip 生成空的配置文件
term_sd_init_pip_and_uv_config_file
# 设置 AI 软件路径
if [[ -f "${START_PATH}/term-sd/config/sd-webui-path.conf" ]]; then
SD_WEBUI_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/sd-webui-path.conf")
SD_WEBUI_FOLDER=$(basename "${SD_WEBUI_ROOT_PATH}")
SD_WEBUI_PARENT_PATH=$(dirname "${SD_WEBUI_ROOT_PATH}")
else
SD_WEBUI_ROOT_PATH="${START_PATH}/stable-diffusion-webui"
SD_WEBUI_FOLDER="stable-diffusion-webui"
SD_WEBUI_PARENT_PATH=${START_PATH}
fi
if [[ -f "${START_PATH}/term-sd/config/comfyui-path.conf" ]]; then
COMFYUI_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/comfyui-path.conf")
COMFYUI_FOLDER=$(basename "${COMFYUI_ROOT_PATH}")
COMFYUI_PARENT_PATH=$(dirname "${COMFYUI_ROOT_PATH}")
export COMFYUI_PATH=${COMFYUI_ROOT_PATH} # 为 ComfyUI-Manager 设置 ComfyUI 路径
else
COMFYUI_ROOT_PATH="${START_PATH}/ComfyUI"
COMFYUI_FOLDER="ComfyUI"
COMFYUI_PARENT_PATH=${START_PATH}
export COMFYUI_PATH=${COMFYUI_ROOT_PATH} # 为 ComfyUI-Manager 设置 ComfyUI 路径
fi
if [[ -f "${START_PATH}/term-sd/config/invokeai-path.conf" ]]; then
INVOKEAI_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/invokeai-path.conf")
INVOKEAI_FOLDER=$(basename "${INVOKEAI_ROOT_PATH}")
INVOKEAI_PARENT_PATH=$(dirname "${INVOKEAI_ROOT_PATH}")
else
INVOKEAI_ROOT_PATH="${START_PATH}/InvokeAI"
INVOKEAI_FOLDER="InvokeAI"
INVOKEAI_PARENT_PATH=${START_PATH}
fi
if [[ -f "${START_PATH}/term-sd/config/fooocus-path.conf" ]]; then
FOOOCUS_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/fooocus-path.conf")
FOOOCUS_FOLDER=$(basename "${FOOOCUS_ROOT_PATH}")
FOOOCUS_PARENT_PATH=$(dirname "${FOOOCUS_ROOT_PATH}")
else
FOOOCUS_ROOT_PATH="${START_PATH}/Fooocus"
FOOOCUS_FOLDER="Fooocus"
FOOOCUS_PARENT_PATH=${START_PATH}
fi
if [[ -f "${START_PATH}/term-sd/config/lora-scripts-path.conf" ]]; then
LORA_SCRIPTS_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/lora-scripts-path.conf")
LORA_SCRIPTS_FOLDER=$(basename "${LORA_SCRIPTS_ROOT_PATH}")
LORA_SCRIPTS_PARENT_PATH=$(dirname "${LORA_SCRIPTS_ROOT_PATH}")
else
LORA_SCRIPTS_ROOT_PATH="${START_PATH}/lora-scripts"
LORA_SCRIPTS_FOLDER="lora-scripts"
LORA_SCRIPTS_PARENT_PATH=${START_PATH}
fi
if [[ -f "${START_PATH}/term-sd/config/kohya_ss-path.conf" ]]; then
KOHYA_SS_ROOT_PATH=$(cat "${START_PATH}/term-sd/config/kohya_ss-path.conf")
KOHYA_SS_FOLDER=$(basename "${KOHYA_SS_ROOT_PATH}")
KOHYA_SS_PARENT_PATH=$(dirname "${KOHYA_SS_ROOT_PATH}")
else
KOHYA_SS_ROOT_PATH="${START_PATH}/kohya_ss"
KOHYA_SS_FOLDER="kohya_ss"
KOHYA_SS_PARENT_PATH=${START_PATH}
fi
# 获取 Bash 主版本
BASH_MAJOR_VERSION=$(awk -F '.' '{print $1}' <<< ${BASH_VERSION})
# 使用的 Windows 系统时将 uv 安装软件包的模式修改为复制模式
if is_windows_platform; then
export UV_LINK_MODE="copy"
fi
# 依赖检测
if [[ ! "${TERM_SD_IS_PREPARE_ENV}" == 1 ]]; then # 判断启动状态
term_sd_echo "检测依赖软件是否安装"
# 检测可用的 Python命令, 并检测是否手动指定 Python 路径
if [[ -z "${TERM_SD_PYTHON_PATH}" ]]; then
if python3 --version &> /dev/null || python --version &> /dev/null; then # 判断是否有可用的 Python
if [[ ! -z "$(python3 --version 2> /dev/null)" ]]; then
TERM_SD_PYTHON_PATH=$(which python3)
elif [[ ! -z "$(python --version 2> /dev/null)" ]]; then
TERM_SD_PYTHON_PATH=$(which python)
fi
else
term_sd_is_missing_dep=1
missing_depend_name="${missing_depend_name} python,"
fi
else
if "${TERM_SD_PYTHON_PATH}" --version &> /dev/null; then
term_sd_echo "使用自定义 Python 解释器路径: ${TERM_SD_PYTHON_PATH}"
else
term_sd_echo "手动指定的 Python 路径错误"
term_sd_echo "提示:"
term_sd_echo "使用 --set-python-path 重新设置 Python 解释器路径"
term_sd_echo "使用 --unset-python-path 删除 Python 解释器路径设置"
term_sd_is_missing_dep=1
missing_depend_name="${missing_depend_name} python,"
fi
fi
# 检测 Python 模块是否安装
for i in ${term_sd_depend_python}; do
if ! "$TERM_SD_PYTHON_PATH" -c "import ${i}" &> /dev/null; then
term_sd_is_missing_dep=1
missing_depend_name="${missing_depend_name} python_module:${i},"
fi
done
#判断系统是否安装必须使用的软件
for i in ${term_sd_depend}; do
if ! which "${i}" &> /dev/null; then
case "${i}" in
aria2c)
i=aria2
;;
esac
missing_depend_name="${missing_depend_name} ${i},"
term_sd_is_missing_dep=1
fi
done
# 依赖检测(MacOS)
if [[ "${OSTYPE}" == "darwin"* ]]; then
export PYTORCH_ENABLE_MPS_FALLBACK=1 # 启用自动回滚运算
for i in ${term_sd_depend_macos}; do
if ! which "${i}" &> /dev/null; then
# 转换名称
case "${i}" in
rustc)
i=rust
;;
protoc)
i=protobuf
;;
esac
MISSING_DEPEND_MACOS_NAME="${MISSING_DEPEND_MACOS_NAME} ${i},"
term_sd_is_missing_macos_dep=1
fi
done
if [[ "${term_sd_is_missing_macos_dep}" == 1 ]]; then
print_line_to_shell "缺少以下依赖"
for i in ${MISSING_DEPEND_MACOS_NAME}; do
echo "${i}"
done
unset MISSING_DEPEND_MACOS_NAME
print_line_to_shell
term_sd_echo "缺少依赖将影响 AI 软件的安装, 请退出 Term-SD 并使用 Homebrew (如果没有 Homebrew, 则先安装 Homebrew, 再用 Homebrew 去安装其他缺少依赖) 安装缺少的依赖后重试"
[[ ! "${TERM_SD_DISABLE_COUNTDOWN}" == 1 ]] && term_sd_sleep 3
fi
fi
# 依赖检测(Windows)
if is_windows_platform; then
if [[ ! -z "${SYSTEMROOT}" ]]; then
vc_runtime_dll_path="$(term_sd_win2unix_path "${SYSTEMROOT}")/System32/vcruntime140_1.dll"
else
vc_runtime_dll_path="/c/Windows/System32/vcruntime140_1.dll"
fi
if [[ ! -f "${vc_runtime_dll_path}" ]]; then
term_sd_echo "检测到 Microsoft Visual C++ Redistributable 未安装, 这可能会导致部分功能异常或无法正常启动, 请安装 Microsoft Visual C++ Redistributable 后再试"
[[ ! "${TERM_SD_DISABLE_COUNTDOWN}" == 1 ]] && term_sd_sleep 3
fi
fi
# 判断依赖检测结果
if [[ "${term_sd_is_missing_dep}" == 0 ]]; then
term_sd_echo "依赖检测完成, 无缺失依赖"
prepare_tcmalloc # 配置内存优化(Linux)
term_sd_install
if [[ -d "${START_PATH}/term-sd/modules" ]]; then # 找到目录后才启动
term_sd_auto_update_trigger
TERM_SD_IS_PREPARE_ENV=1 # 用于检测 Term-SD 的启动状态, 设置后不再重新执行依赖检测
else
term_sd_echo "Term-SD 模块丢失, 输入 ./term-sd.sh --reinstall-term-sd 重新安装 Term-SD"
exit 1
fi
else
term_sd_print_line "缺少以下依赖"
for i in ${missing_depend_name}; do
echo "${i}"
done
term_sd_print_line
term_sd_echo "请安装缺少的依赖后重试"
exit 1
fi
if [[ ! -f "${START_PATH}/term-sd/config/install-by-launch-script.lock" ]]; then # 检测是否通过启动脚本安装 Term-SD
term_sd_set_up_normal_setting # 非启动脚本安装时设置默认 Term-SD 设置
fi
term_sd_auto_setup_github_mirror # 配置 Github 镜像源
term_sd_auto_setup_huggingface_mirror # 配置 HuggingFace 镜像源
term_sd_user_agreement # 用户协议
fi
# 放在依赖检测之后, 解决一些奇怪的问题
# 设置缓存路径的环境变量
if [[ ! -f "${START_PATH}/term-sd/config/disable-cache-path-redirect.lock" ]]; then
export CACHE_HOME="${START_PATH}/term-sd/cache"
export HF_HOME="${START_PATH}/term-sd/cache/huggingface"
export MATPLOTLIBRC="${START_PATH}/term-sd/cache"
export MODELSCOPE_CACHE="${START_PATH}/term-sd/cache/modelscope/hub"
export MS_CACHE_HOME="${START_PATH}/term-sd/cache/modelscope/hub"
export SYCL_CACHE_DIR="${START_PATH}/term-sd/cache/libsycl_cache"
export TORCH_HOME="${START_PATH}/term-sd/cache/torch"
export U2NET_HOME="${START_PATH}/term-sd/cache/u2net"
export XDG_CACHE_HOME="${START_PATH}/term-sd/cache"
export PIP_CACHE_DIR="${START_PATH}/term-sd/cache/pip"
export PYTHONPYCACHEPREFIX="${START_PATH}/term-sd/cache/pycache"
export TORCHINDUCTOR_CACHE_DIR="${START_PATH}/term-sd/cache/torchinductor"
export TRITON_CACHE_DIR="${START_PATH}/term-sd/cache/triton"
export UV_CACHE_DIR="${START_PATH}/term-sd/cache/uv"
# export TRANSFORMERS_CACHE="${START_PATH}/term-sd/cache/huggingface/transformers"
fi
# 设置 PyPI 镜像源的环境变量
if [[ -f "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf" ]]; then
case "$(cat "${START_PATH}/term-sd/config/term-sd-pip-mirror.conf")" in
1)
export PIP_INDEX_URL="https://pypi.python.org/simple"
export PIP_EXTRA_INDEX_URL=""
export PIP_FIND_LINKS="https://download.pytorch.org/whl/torch_stable.html"
export UV_DEFAULT_INDEX="https://pypi.python.org/simple"
export UV_INDEX=""
export UV_FIND_LINKS="https://download.pytorch.org/whl/torch_stable.html"
;;
2)
export PIP_INDEX_URL=$TERM_SD_PIP_INDEX_URL
export PIP_EXTRA_INDEX_URL=$TERM_SD_PIP_EXTRA_INDEX_URL
export PIP_FIND_LINKS=$TERM_SD_PIP_FIND_LINKS
export UV_DEFAULT_INDEX=$TERM_SD_PIP_INDEX_URL
export UV_INDEX=$TERM_SD_PIP_EXTRA_INDEX_URL
export UV_FIND_LINKS=$TERM_SD_PIP_FIND_LINKS
;;
*)
export PIP_INDEX_URL=$TERM_SD_PIP_INDEX_URL
export PIP_EXTRA_INDEX_URL=$TERM_SD_PIP_EXTRA_INDEX_URL
export PIP_FIND_LINKS=$TERM_SD_PIP_FIND_LINKS
export UV_DEFAULT_INDEX=$TERM_SD_PIP_INDEX_URL
export UV_INDEX=$TERM_SD_PIP_EXTRA_INDEX_URL
export UV_FIND_LINKS=$TERM_SD_PIP_FIND_LINKS
;;
esac
fi
# Github 镜像源设置
if [[ ! -f "${START_PATH}/term-sd/config/set-dynamic-global-github-mirror.lock" ]] && [[ -f "${START_PATH}/term-sd/config/set-global-github-mirror.conf" ]]; then
export GIT_CONFIG_GLOBAL="${START_PATH}/term-sd/config/.gitconfig"
fi
# HuggingFace 镜像源设置
if [[ ! -f "${START_PATH}/term-sd/config/set-dynamic-global-huggingface-mirror.lock" ]] && [[ -f "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf" ]]; then
export HF_ENDPOINT=$(cat "${START_PATH}/term-sd/config/set-global-huggingface-mirror.conf")
fi
# 设置安装 AI 软件时调用 Aria2 下载模型的线程数
if [[ -f "${START_PATH}/term-sd/config/set-aria2-thread.conf" ]]; then
ARIA2_MULTI_THREAD=$(cat "${START_PATH}/term-sd/config/set-aria2-thread.conf")
else
ARIA2_MULTI_THREAD=1
fi
#############################
# 自动更新成功时重载环境
if [[ "${TERM_SD_TO_RESTART}" == 1 ]]; then
term_sd_echo "重载 Term-SD 启动脚本中"
. "${START_PATH}/term-sd/term-sd.sh"
fi
term_sd_echo "Term-SD 版本: ${TERM_SD_VER}"
if [[ -d "${START_PATH}/term-sd/.git" ]]; then
term_sd_echo "Commit: $(git --git-dir="${START_PATH}/term-sd/.git" show -s --format="%h %cd" --date=format:"%Y-%m-%d %H:%M:%S")"
fi
# TERM_SD_SCRIPT_NAME 全局变量不为空时执行启动 Term-SD 扩展脚本的功能
case "${TERM_SD_SCRIPT_NAME}" in
null)
. "${START_PATH}"/term-sd/modules/init.sh # 加载 Term-SD 模块
;;
*)
term_sd_extra_scripts_launch "${TERM_SD_SCRIPT_NAME}"
;;
esac
# 当启动动态代理时将自动检测并使用系统代理
dynamic_configure_proxy
# 启动 Term-SD
term_sd_echo "启动 Term-SD 中"
term_sd_version
term_sd_manager
}
main "$@"
|
2301_81996401/term-sd
|
term-sd.sh
|
Shell
|
agpl-3.0
| 65,133
|
__version__ = '1.5.0'
__description__ = 'Monitors, analyzes and limits the bandwidth of devices on the local network'
|
2301_82206160/evillimite
|
evillimiter/__init__.py
|
Python
|
mit
| 117
|
import evillimiter.console.shell as shell
BROADCAST = 'ff:ff:ff:ff:ff:ff'
BIN_TC = shell.locate_bin('tc')
BIN_IPTABLES = shell.locate_bin('iptables')
BIN_SYSCTL = shell.locate_bin('sysctl')
IP_FORWARD_LOC = 'net.ipv4.ip_forward'
|
2301_82206160/evillimite
|
evillimiter/common/globals.py
|
Python
|
mit
| 231
|
from .io import IO
_MAIN_BANNER = r"""{}
███████╗██╗ ██╗██╗██╗ ██╗ ██╗███╗ ███╗██╗████████╗███████╗██████╗
██╔════╝██║ ██║██║██║ ██║ ██║████╗ ████║██║╚══██╔══╝██╔════╝██╔══██╗
█████╗ ██║ ██║██║██║ ██║ ██║██╔████╔██║██║ ██║ █████╗ ██████╔╝
██╔══╝ ╚██╗ ██╔╝██║██║ ██║ ██║██║╚██╔╝██║██║ ██║ ██╔══╝ ██╔══██╗
███████╗ ╚████╔╝ ██║███████╗ ███████╗██║██║ ╚═╝ ██║██║ ██║ ███████╗██║ ██║
╚══════╝ ╚═══╝ ╚═╝╚══════╝ ╚══════╝╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
{}by bitbrute ~ limit devices on your network :3
v[_V_]
""".format(IO.Fore.LIGHTRED_EX, IO.Style.RESET_ALL + IO.Style.BRIGHT)
def get_main_banner(version):
return _MAIN_BANNER.replace('[_V_]', version)
|
2301_82206160/evillimite
|
evillimiter/console/banner.py
|
Python
|
mit
| 1,519
|
from evillimiter.console.io import IO
class BarChart(object):
def __init__(self, draw_char='▇', max_bar_length=30):
self.draw_char = draw_char
self.max_bar_length = max_bar_length
self._data = []
def add_value(self, value, prefix, suffix=''):
self._data.append({ 'value': value, 'prefix': prefix, 'suffix': suffix })
def get(self, reverse=False):
def remap(n, old_min, old_max, new_min, new_max):
return (((n - old_min) * (new_max - new_min)) / (old_max - old_min)) + new_min
self._data.sort(reverse=reverse, key=lambda x: x['value'])
max_value = self._data[0]['value'] if reverse else self._data[-1]['value']
max_prefix_length = max([len(x['prefix']) for x in self._data]) + 1
chart = ''
for value in self._data:
if max_value == 0:
bar_length = 0
else:
bar_length = round(remap(value['value'], 0, max_value, 0, self.max_bar_length))
chart += '{}{}: {} {}\n'.format(
value['prefix'],
' ' * (max_prefix_length - len(value['prefix'])),
self.draw_char * bar_length,
value['suffix']
)
return chart[:-1]
|
2301_82206160/evillimite
|
evillimiter/console/chart.py
|
Python
|
mit
| 1,304
|
import re
import colorama
from . import shell
class IO(object):
_ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?')
Back = colorama.Back
Fore = colorama.Fore
Style = colorama.Style
colorless = False
@staticmethod
def initialize(colorless=False):
"""
Initializes console input and output.
"""
IO.colorless = colorless
if not colorless:
colorama.init(autoreset=True)
@staticmethod
def print(text, end='\n', flush=False):
"""
Writes a given string to the console.
"""
if IO.colorless:
text = IO._remove_colors(text)
print(text, end=end, flush=flush)
@staticmethod
def ok(text, end='\n'):
"""
Print a success status message
"""
IO.print('{}OK{} {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTGREEN_EX, IO.Style.RESET_ALL, text), end=end)
@staticmethod
def error(text):
"""
Print an error status message
"""
IO.print('{}ERR{} {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTRED_EX, IO.Style.RESET_ALL, text))
@staticmethod
def spacer():
"""
Prints a blank line for attraction purposes
"""
IO.print('')
@staticmethod
def input(prompt):
"""
Prompts the user for input.
"""
if IO.colorless:
prompt = IO._remove_colors(prompt)
return input(prompt)
@staticmethod
def clear():
"""
Clears the terminal screen
"""
shell.execute('clear')
@staticmethod
def _remove_colors(text):
edited = text
for match in IO._ANSI_CSI_RE.finditer(text):
s, e = match.span()
edited = edited.replace(text[s:e], '')
return edited
|
2301_82206160/evillimite
|
evillimiter/console/io.py
|
Python
|
mit
| 1,847
|
import os
import subprocess
from evillimiter.console.io import IO
DEVNULL = open(os.devnull, 'w')
def execute(command, root=True):
return subprocess.call('sudo ' + command if root else command, shell=True)
def execute_suppressed(command, root=True):
return subprocess.call('sudo ' + command if root else command, shell=True, stdout=DEVNULL, stderr=DEVNULL)
def output(command, root=True):
return subprocess.check_output('sudo ' + command if root else command, shell=True).decode('utf-8')
def output_suppressed(command, root=True):
return subprocess.check_output('sudo ' + command if root else command, shell=True, stderr=DEVNULL).decode('utf-8')
def locate_bin(name):
try:
return output_suppressed('which {}'.format(name)).replace('\n', '')
except subprocess.CalledProcessError:
IO.error('missing util: {}, check your PATH'.format(name))
|
2301_82206160/evillimite
|
evillimiter/console/shell.py
|
Python
|
mit
| 888
|
import re
import os
import os.path
import argparse
import platform
import collections
import pkg_resources
import evillimiter.networking.utils as netutils
from evillimiter.menus.main_menu import MainMenu
from evillimiter.console.banner import get_main_banner
from evillimiter.console.io import IO
InitialArguments = collections.namedtuple('InitialArguments', 'interface, gateway_ip, netmask, gateway_mac')
def get_init_content():
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), '__init__.py'), 'r') as f:
return f.read()
def get_version():
version_match = re.search(r'^__version__ = [\'"](\d\.\d\.\d)[\'"]', get_init_content(), re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to locate version string.')
def get_description():
desc_match = re.search(r'^__description__ = [\'"]((.)*)[\'"]', get_init_content(), re.M)
if desc_match:
return desc_match.group(1)
raise RuntimeError('Unable to locate description string.')
def is_privileged():
return os.geteuid() == 0
def is_linux():
return platform.system() == 'Linux'
def parse_arguments():
"""
Parses the main command-line arguments (sys.argv)
using argparse
"""
parser = argparse.ArgumentParser(description=get_description())
parser.add_argument('-i', '--interface', help='network interface connected to the target network. automatically resolved if not specified.')
parser.add_argument('-g', '--gateway-ip', dest='gateway_ip', help='default gateway ip address. automatically resolved if not specified.')
parser.add_argument('-m', '--gateway-mac', dest='gateway_mac', help='gateway mac address. automatically resolved if not specified.')
parser.add_argument('-n', '--netmask', help='netmask for the network. automatically resolved if not specified.')
parser.add_argument('-f', '--flush', action='store_true', help='flush current iptables (firewall) and tc (traffic control) settings.')
parser.add_argument('--colorless', action='store_true', help='disable colored output.')
return parser.parse_args()
def process_arguments(args):
"""
Processes the specified command-line arguments, adds them to a named tuple
and returns.
Executes actions specified in the command line, e.g. flush network settings
"""
if args.interface is None:
interface = netutils.get_default_interface()
if interface is None:
IO.error('default interface could not be resolved. specify manually (-i).')
return
else:
interface = args.interface
if not netutils.exists_interface(interface):
IO.error('interface {}{}{} does not exist.'.format(IO.Fore.LIGHTYELLOW_EX, interface, IO.Style.RESET_ALL))
return
IO.ok('interface: {}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, interface, IO.Style.RESET_ALL))
if args.gateway_ip is None:
gateway_ip = netutils.get_default_gateway()
if gateway_ip is None:
IO.error('default gateway address could not be resolved. specify manually (-g).')
return
else:
gateway_ip = args.gateway_ip
IO.ok('gateway ip: {}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, gateway_ip, IO.Style.RESET_ALL))
if args.gateway_mac is None:
gateway_mac = netutils.get_mac_by_ip(interface, gateway_ip)
if gateway_mac is None:
IO.error('gateway mac address could not be resolved.')
return
else:
if netutils.validate_mac_address(args.gateway_mac):
gateway_mac = args.gateway_mac.lower()
else:
IO.error('gateway mac is invalid.')
return
IO.ok('gateway mac: {}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, gateway_mac, IO.Style.RESET_ALL))
if args.netmask is None:
netmask = netutils.get_default_netmask(interface)
if netmask is None:
IO.error('netmask could not be resolved. specify manually (-n).')
return
else:
netmask = args.netmask
IO.ok('netmask: {}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, netmask, IO.Style.RESET_ALL))
if args.flush:
netutils.flush_network_settings(interface)
IO.spacer()
IO.ok('flushed network settings')
return InitialArguments(interface=interface, gateway_ip=gateway_ip, gateway_mac=gateway_mac, netmask=netmask)
def initialize(interface):
"""
Sets up requirements, e.g. IP-Forwarding, 3rd party applications
"""
if not netutils.create_qdisc_root(interface):
IO.spacer()
IO.error('qdisc root handle could not be created. maybe flush network settings (--flush).')
return False
if not netutils.enable_ip_forwarding():
IO.spacer()
IO.error('ip forwarding could not be enabled.')
return False
return True
def cleanup(interface):
"""
Resets what has been initialized
"""
netutils.delete_qdisc_root(interface)
netutils.disable_ip_forwarding()
def run():
"""
Main entry point of the application
"""
version = get_version()
args = parse_arguments()
IO.initialize(args.colorless)
IO.print(get_main_banner(version))
if not is_linux():
IO.error('run under linux.')
return
if not is_privileged():
IO.error('run as root.')
return
args = process_arguments(args)
if args is None:
return
if initialize(args.interface):
IO.spacer()
menu = MainMenu(version, args.interface, args.gateway_ip, args.gateway_mac, args.netmask)
menu.start()
cleanup(args.interface)
if __name__ == '__main__':
run()
|
2301_82206160/evillimite
|
evillimiter/evillimiter.py
|
Python
|
mit
| 5,700
|
import time
import socket
import curses
import netaddr
import threading
import collections
from terminaltables import SingleTable
import evillimiter.networking.utils as netutils
from .menu import CommandMenu
from evillimiter.networking.utils import BitRate
from evillimiter.console.io import IO
from evillimiter.console.chart import BarChart
from evillimiter.console.banner import get_main_banner
from evillimiter.networking.host import Host
from evillimiter.networking.limit import Limiter, Direction
from evillimiter.networking.spoof import ARPSpoofer
from evillimiter.networking.scan import HostScanner, ScanIntensity
from evillimiter.networking.monitor import BandwidthMonitor
from evillimiter.networking.watch import HostWatcher
class MainMenu(CommandMenu):
def __init__(self, version, interface, gateway_ip, gateway_mac, netmask):
super().__init__()
self.prompt = '({}Main{}) >>> '.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
self.parser.add_subparser('clear', self._clear_handler)
hosts_parser = self.parser.add_subparser('hosts', self._hosts_handler)
hosts_parser.add_flag('--force', 'force')
scan_parser = self.parser.add_subparser('scan', self._scan_handler)
scan_parser.add_parameterized_flag('--range', 'iprange')
scan_parser.add_parameterized_flag('--intensity', 'intensity')
limit_parser = self.parser.add_subparser('limit', self._limit_handler)
limit_parser.add_parameter('id')
limit_parser.add_parameter('rate')
limit_parser.add_flag('--upload', 'upload')
limit_parser.add_flag('--download', 'download')
block_parser = self.parser.add_subparser('block', self._block_handler)
block_parser.add_parameter('id')
block_parser.add_flag('--upload', 'upload')
block_parser.add_flag('--download', 'download')
free_parser = self.parser.add_subparser('free', self._free_handler)
free_parser.add_parameter('id')
add_parser = self.parser.add_subparser('add', self._add_handler)
add_parser.add_parameter('ip')
add_parser.add_parameterized_flag('--mac', 'mac')
monitor_parser = self.parser.add_subparser('monitor', self._monitor_handler)
monitor_parser.add_parameter('id')
monitor_parser.add_parameterized_flag('--interval', 'interval')
analyze_parser = self.parser.add_subparser('analyze', self._analyze_handler)
analyze_parser.add_parameter('id')
analyze_parser.add_parameterized_flag('--duration', 'duration')
watch_parser = self.parser.add_subparser('watch', self._watch_handler)
watch_add_parser = watch_parser.add_subparser('add', self._watch_add_handler)
watch_add_parser.add_parameter('id')
watch_remove_parser = watch_parser.add_subparser('remove', self._watch_remove_handler)
watch_remove_parser.add_parameter('id')
watch_set_parser = watch_parser.add_subparser('set', self._watch_set_handler)
watch_set_parser.add_parameter('attribute')
watch_set_parser.add_parameter('value')
self.parser.add_subparser('help', self._help_handler)
self.parser.add_subparser('?', self._help_handler)
self.parser.add_subparser('quit', self._quit_handler)
self.parser.add_subparser('exit', self._quit_handler)
self.version = version # application version
self.interface = interface # specified IPv4 interface
self.gateway_ip = gateway_ip
self.gateway_mac = gateway_mac
self.netmask = netmask
# range of IP address calculated from gateway IP and netmask
self.iprange = list(netaddr.IPNetwork('{}/{}'.format(self.gateway_ip, self.netmask)))
self.host_scanner = HostScanner(self.interface, self.iprange)
self.arp_spoofer = ARPSpoofer(self.interface, self.gateway_ip, self.gateway_mac)
self.limiter = Limiter(self.interface)
self.bandwidth_monitor = BandwidthMonitor(self.interface, 1)
self.host_watcher = HostWatcher(self.interface, self.iprange, self._reconnect_callback)
# holds discovered hosts
self.hosts = []
self.hosts_lock = threading.Lock()
self._print_help_reminder()
# start the spoof thread
self.arp_spoofer.start()
# start the bandwidth monitor thread
self.bandwidth_monitor.start()
# start the host watch thread
self.host_watcher.start()
def interrupt_handler(self, ctrl_c=True):
if ctrl_c:
IO.spacer()
IO.ok('cleaning up... stand by...')
self.arp_spoofer.stop()
self.bandwidth_monitor.stop()
for host in self.hosts:
self._free_host(host)
def _scan_handler(self, args):
"""
Handles 'scan' command-line argument
(Re)scans for hosts on the network
"""
if args.iprange:
iprange = self._parse_iprange(args.iprange)
if iprange is None:
IO.error('invalid ip range.')
return
else:
iprange = None
if args.intensity:
intensity = self._parse_scan_intensity(args.intensity)
if intensity is None:
IO.error('invalid intensity level.')
return
else:
intensity = ScanIntensity.NORMAL
self.host_scanner.set_intensity(intensity)
with self.hosts_lock:
for host in self.hosts:
self._free_host(host)
IO.spacer()
hosts = self.host_scanner.scan(iprange)
self.hosts_lock.acquire()
self.hosts = hosts
self.hosts_lock.release()
IO.ok('{}{}{} hosts discovered.'.format(IO.Fore.LIGHTYELLOW_EX, len(hosts), IO.Style.RESET_ALL))
IO.spacer()
def _hosts_handler(self, args):
"""
Handles 'hosts' command-line argument
Displays discovered hosts
"""
table_data = [[
'{}ID{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}IP address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}MAC address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}Hostname{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}Status{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
]]
with self.hosts_lock:
for host in self.hosts:
table_data.append([
'{}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, self._get_host_id(host, lock=False), IO.Style.RESET_ALL),
host.ip,
host.mac,
host.name,
self.limiter.pretty_status(host)
])
table = SingleTable(table_data, 'Hosts')
if not args.force and not table.ok:
IO.error('table does not fit terminal. resize or decrease font size. you can also force the display (--force).')
return
IO.spacer()
IO.print(table.table)
IO.spacer()
def _limit_handler(self, args):
"""
Handles 'limit' command-line argument
Limits bandwith of host to specified rate
"""
hosts = self._get_hosts_by_ids(args.id)
if hosts is None or len(hosts) == 0:
return
try:
rate = BitRate.from_rate_string(args.rate)
except Exception:
IO.error('limit rate is invalid.')
return
direction = self._parse_direction_args(args)
for host in hosts:
self.arp_spoofer.add(host)
self.limiter.limit(host, direction, rate)
self.bandwidth_monitor.add(host)
IO.ok('{}{}{r} {} {}limited{r} to {}.'.format(IO.Fore.LIGHTYELLOW_EX, host.ip, Direction.pretty_direction(direction), IO.Fore.LIGHTRED_EX, rate, r=IO.Style.RESET_ALL))
def _block_handler(self, args):
"""
Handles 'block' command-line argument
Blocks internet communication for host
"""
hosts = self._get_hosts_by_ids(args.id)
direction = self._parse_direction_args(args)
if hosts is not None and len(hosts) > 0:
for host in hosts:
if not host.spoofed:
self.arp_spoofer.add(host)
self.limiter.block(host, direction)
self.bandwidth_monitor.add(host)
IO.ok('{}{}{r} {} {}blocked{r}.'.format(IO.Fore.LIGHTYELLOW_EX, host.ip, Direction.pretty_direction(direction), IO.Fore.RED, r=IO.Style.RESET_ALL))
def _free_handler(self, args):
"""
Handles 'free' command-line argument
Frees the host from all limitations
"""
hosts = self._get_hosts_by_ids(args.id)
if hosts is not None and len(hosts) > 0:
for host in hosts:
self._free_host(host)
def _add_handler(self, args):
"""
Handles 'add' command-line argument
Adds custom host to host list
"""
ip = args.ip
if not netutils.validate_ip_address(ip):
IO.error('invalid ip address.')
return
if args.mac:
mac = args.mac
if not netutils.validate_mac_address(mac):
IO.error('invalid mac address.')
return
else:
mac = netutils.get_mac_by_ip(self.interface, ip)
if mac is None:
IO.error('unable to resolve mac address. specify manually (--mac).')
return
name = None
try:
host_info = socket.gethostbyaddr(ip)
name = None if host_info is None else host_info[0]
except socket.herror:
pass
host = Host(ip, mac, name)
with self.hosts_lock:
if host in self.hosts:
IO.error('host does already exist.')
return
self.hosts.append(host)
IO.ok('host added.')
def _monitor_handler(self, args):
"""
Handles 'monitor' command-line argument
Monitors hosts bandwidth usage
"""
def get_bandwidth_results():
with self.hosts_lock:
return sorted(
[x for x in [(y, self.bandwidth_monitor.get(y)) for y in self.hosts] if x[1] is not None],
key=lambda h: not (h[0].limited or h[0].blocked)
)
def display(stdscr, interval):
host_results = get_bandwidth_results()
hname_max_len = max([len(x[0].name) for x in host_results])
header_off = [
('ID', 5), ('IP address', 18), ('Hostname', hname_max_len + 2),
('Current (per s)', 20), ('Total', 16), ('Packets', 0)
]
y_rst = 1
x_rst = 2
while True:
y_off = y_rst
x_off = x_rst
stdscr.clear()
for header in header_off:
stdscr.addstr(y_off, x_off, header[0])
x_off += header[1]
y_off += 2
x_off = x_rst
temps_reached = False
for host, result in host_results:
result_data = [
str(self._get_host_id(host)),
host.ip,
host.name,
'{}↑ {}↓'.format(result.upload_rate, result.download_rate),
'{}↑ {}↓'.format(result.upload_total_size, result.download_total_size),
'{}↑ {}↓'.format(result.upload_total_count, result.download_total_count)
]
if not temps_reached and host in hosts_to_be_freed:
temps_reached = True
y_off += 1
for j, string in enumerate(result_data):
stdscr.addstr(y_off, x_off, string)
x_off += header_off[j][1]
y_off += 1
x_off = x_rst
y_off += 2
stdscr.addstr(y_off, x_off, 'press \'ctrl+c\' to exit.')
try:
stdscr.refresh()
time.sleep(interval)
host_results = get_bandwidth_results()
except KeyboardInterrupt:
return
hosts = self._get_hosts_by_ids(args.id)
hosts_to_be_freed = set()
interval = 0.5 # in s
if args.interval:
if not args.interval.isdigit():
IO.error('invalid interval.')
return
interval = int(args.interval) / 1000 # from ms to s
for host in hosts:
if not host.spoofed:
hosts_to_be_freed.add(host)
self.arp_spoofer.add(host)
self.bandwidth_monitor.add(host)
if len(get_bandwidth_results()) == 0:
IO.error('no hosts to be monitored.')
return
try:
curses.wrapper(display, interval)
except curses.error:
IO.error('monitor error occurred. maybe terminal too small?')
for host in hosts_to_be_freed:
self._free_host(host)
def _analyze_handler(self, args):
hosts = self._get_hosts_by_ids(args.id)
if hosts is None or len(hosts) == 0:
IO.error('no hosts to be analyzed.')
return
duration = 30 # in s
if args.duration:
if not args.duration.isdigit():
IO.error('invalid duration.')
return
duration = int(args.duration)
hosts_to_be_freed = set()
host_values = {}
for host in hosts:
if not host.spoofed:
hosts_to_be_freed.add(host)
self.arp_spoofer.add(host)
self.bandwidth_monitor.add(host)
host_result = self.bandwidth_monitor.get(host)
host_values[host] = {}
host_values[host]['prev'] = (host_result.upload_total_size, host_result.download_total_size)
IO.ok('analyzing traffic for {}s.'.format(duration))
time.sleep(duration)
error_occurred = False
for host in hosts:
host_result = self.bandwidth_monitor.get(host)
if host_result is None:
# host reconnected during analysis
IO.error('host reconnected during analysis.')
error_occurred = True
else:
host_values[host]['current'] = (host_result.upload_total_size, host_result.download_total_size)
IO.ok('cleaning up...')
for host in hosts_to_be_freed:
self._free_host(host)
if error_occurred:
return
upload_chart = BarChart(max_bar_length=29)
download_chart = BarChart(max_bar_length=29)
for host in hosts:
upload_value = host_values[host]['current'][0] - host_values[host]['prev'][0]
download_value = host_values[host]['current'][1] - host_values[host]['prev'][1]
prefix = '{}{}{} ({}, {})'.format(
IO.Fore.LIGHTYELLOW_EX, self._get_host_id(host), IO.Style.RESET_ALL,
host.ip,
host.name
)
upload_chart.add_value(upload_value.value, prefix, upload_value)
download_chart.add_value(download_value.value, prefix, download_value)
upload_table = SingleTable([[upload_chart.get()]], 'Upload')
download_table = SingleTable([[download_chart.get()]], 'Download')
upload_table.inner_heading_row_border = False
download_table.inner_heading_row_border = False
IO.spacer()
IO.print(upload_table.table)
IO.print(download_table.table)
IO.spacer()
def _watch_handler(self, args):
if len(args) == 0:
watch_table_data = [[
'{}ID{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}IP address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}MAC address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
]]
set_table_data = [[
'{}Attribute{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}Value{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
]]
hist_table_data = [[
'{}ID{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}Old IP address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}New IP address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
'{}Time{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
]]
iprange = self.host_watcher.iprange
interval = self.host_watcher.interval
intensity = self.host_watcher.intensity
set_table_data.append([
'{}range{}'.format(IO.Fore.LIGHTYELLOW_EX, IO.Style.RESET_ALL),
'{} addresses'.format(len(iprange)) if iprange is not None else 'default'
])
set_table_data.append([
'{}interval{}'.format(IO.Fore.LIGHTYELLOW_EX, IO.Style.RESET_ALL),
'{}s'.format(interval)
])
set_table_data.append([
'{}intensity{}'.format(IO.Fore.LIGHTYELLOW_EX, IO.Style.RESET_ALL),
intensity
])
for host in self.host_watcher.hosts:
watch_table_data.append([
'{}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, self._get_host_id(host), IO.Style.RESET_ALL),
host.ip,
host.mac
])
for recon in self.host_watcher.log_list:
hist_table_data.append([
recon['old'].mac,
recon['old'].ip,
recon['new'].ip,
recon['time']
])
watch_table = SingleTable(watch_table_data, "Watchlist")
set_table = SingleTable(set_table_data, "Settings")
hist_table = SingleTable(hist_table_data, 'Reconnection History')
IO.spacer()
IO.print(watch_table.table)
IO.spacer()
IO.print(set_table.table)
IO.spacer()
IO.print(hist_table.table)
IO.spacer()
def _watch_add_handler(self, args):
"""
Handles 'watch add' command-line argument
Adds host to the reconnection watch list
"""
hosts = self._get_hosts_by_ids(args.id)
if hosts is None or len(hosts) == 0:
return
for host in hosts:
self.host_watcher.add(host)
def _watch_remove_handler(self, args):
"""
Handles 'watch remove' command-line argument
Removes host from the reconnection watch list
"""
hosts = self._get_hosts_by_ids(args.id)
if hosts is None or len(hosts) == 0:
return
for host in hosts:
self.host_watcher.remove(host)
def _watch_set_handler(self, args):
"""
Handles 'watch set' command-line argument
Modifies settings of the reconnection reconnection watcher
"""
if args.attribute.lower() in ('range', 'iprange', 'ip_range'):
iprange = self._parse_iprange(args.value)
if iprange is not None:
self.host_watcher.iprange = iprange
else:
IO.error('invalid ip range.')
elif args.attribute.lower() in ('interval'):
if args.value.isdigit():
self.host_watcher.interval = int(args.value)
else:
IO.error('invalid interval.')
elif args.attribute.lower() in ('intensity', 'scan_intensity'):
intensity = self._parse_scan_intensity(args.value)
if intensity is not None:
self.host_watcher.intensity = intensity
else:
IO.error('invalid scan intensity level.')
else:
IO.error('{}{}{} is an invalid settings attribute.'.format(IO.Fore.LIGHTYELLOW_EX, args.attribute, IO.Style.RESET_ALL))
def _reconnect_callback(self, old_host, new_host):
"""
Callback that is called when a watched host reconnects
Method will run in a separate thread
"""
with self.hosts_lock:
if old_host in self.hosts:
self.hosts[self.hosts.index(old_host)] = new_host
else:
return
self.arp_spoofer.remove(old_host, restore=False)
self.arp_spoofer.add(new_host)
self.host_watcher.remove(old_host)
self.host_watcher.add(new_host)
self.limiter.replace(old_host, new_host)
self.bandwidth_monitor.replace(old_host, new_host)
def _clear_handler(self, args):
"""
Handler for the 'clear' command-line argument
Clears the terminal window and re-prints the banner
"""
IO.clear()
IO.print(get_main_banner(self.version))
self._print_help_reminder()
def _help_handler(self, args):
"""
Handles 'help' command-line argument
Prints help message including commands and usage
"""
spaces = ' ' * 35
IO.print(
"""
{y}scan (--range [IP range]){r}{}scans for online hosts on your network.
{y} (--intensity [(1,2,3)]){r}{}required to find the hosts you want to limit.
{b}{s}e.g.: scan
{s} scan --range 192.168.178.1-192.168.178.50
{s} scan --range 192.168.178.1/24 --intensity 3{r}
{y}hosts (--force){r}{}lists all scanned hosts.
{s}contains host information, including IDs.
{y}limit [ID1,ID2,...] [rate]{r}{}limits bandwith of host(s) (uload/dload).
{y} (--upload) (--download){r}{}{b}e.g.: limit 4 100kbit
{s} limit 2,3,4 1gbit --download
{s} limit all 200kbit --upload{r}
{y}block [ID1,ID2,...]{r}{}blocks internet access of host(s).
{y} (--upload) (--download){r}{}{b}e.g.: block 3,2
{s} block all --upload{r}
{y}free [ID1,ID2,...]{r}{}unlimits/unblocks host(s).
{b}{s}e.g.: free 3
{s} free all{r}
{y}add [IP] (--mac [MAC]){r}{}adds custom host to host list.
{s}mac resolved automatically.
{b}{s}e.g.: add 192.168.178.24
{s} add 192.168.1.50 --mac 1c:fc:bc:2d:a6:37{r}
{y}monitor [ID1,ID2,...]{r}{}monitors bandwidth usage of host(s).
{y} (--interval [time in ms]){r}{}{b}e.g.: monitor all --interval 600{r}
{y}analyze [ID1,ID2,...]{r}{}analyzes traffic of host(s) without limiting
{y} (--duration [time in s]){r}{}to determine who uses how much bandwidth.
{b}{s}e.g.: analyze 2,3 --duration 120{r}
{y}watch{r}{}detects host reconnects with different IP.
{y}watch add [ID1,ID2,...]{r}{}adds host to the reconnection watchlist.
{b}{s}e.g.: watch add 3,4{r}
{y}watch remove [ID1,ID2,...]{r}{}removes host from the reconnection watchlist.
{b}{s}e.g.: watch remove all{r}
{y}watch set [attr] [value]{r}{}changes reconnect watch settings.
{b}{s}e.g.: watch set interval 120
{s} watch set intensity 1{r}
{y}clear{r}{}clears the terminal window.
{y}quit{r}{}quits the application.
""".format(
spaces[len('scan (--range [IP range])'):],
spaces[len(' (--intensity [(1,2,3)])'):],
spaces[len('hosts (--force)'):],
spaces[len('limit [ID1,ID2,...] [rate]'):],
spaces[len(' (--upload) (--download)'):],
spaces[len('block [ID1,ID2,...]'):],
spaces[len(' (--upload) (--download)'):],
spaces[len('free [ID1,ID2,...]'):],
spaces[len('add [IP] (--mac [MAC])'):],
spaces[len('monitor [ID1,ID2,...]'):],
spaces[len(' (--interval [time in ms])'):],
spaces[len('analyze [ID1,ID2,...]'):],
spaces[len(' (--duration [time in s])'):],
spaces[len('watch'):],
spaces[len('watch add [ID1,ID2,...]'):],
spaces[len('watch remove [ID1,ID2,...]'):],
spaces[len('watch set [attr] [value]'):],
spaces[len('clear'):],
spaces[len('quit'):],
y=IO.Fore.LIGHTYELLOW_EX, r=IO.Style.RESET_ALL, b=IO.Style.BRIGHT,
s=spaces
)
)
def _quit_handler(self, args):
self.interrupt_handler(False)
self.stop()
def _get_host_id(self, host, lock=True):
ret = None
if lock:
self.hosts_lock.acquire()
for i, host_ in enumerate(self.hosts):
if host_ == host:
ret = i
break
if lock:
self.hosts_lock.release()
return ret
def _print_help_reminder(self):
IO.print('type {Y}help{R} or {Y}?{R} to show command information.'.format(Y=IO.Fore.LIGHTYELLOW_EX, R=IO.Style.RESET_ALL))
def _get_hosts_by_ids(self, ids_string):
if ids_string == 'all':
with self.hosts_lock:
return self.hosts.copy()
ids = ids_string.split(',')
hosts = set()
with self.hosts_lock:
for id_ in ids:
is_mac = netutils.validate_mac_address(id_)
is_ip = netutils.validate_ip_address(id_)
is_id_ = id_.isdigit()
if not is_mac and not is_ip and not is_id_:
IO.error('invalid identifier(s): \'{}\'.'.format(ids_string))
return
if is_mac or is_ip:
found = False
for host in self.hosts:
if host.mac == id_.lower() or host.ip == id_:
found = True
hosts.add(host)
break
if not found:
IO.error('no host matching {}{}{}.'.format(IO.Fore.LIGHTYELLOW_EX, id_, IO.Style.RESET_ALL))
return
else:
id_ = int(id_)
if len(self.hosts) == 0 or id_ not in range(len(self.hosts)):
IO.error('no host with id {}{}{}.'.format(IO.Fore.LIGHTYELLOW_EX, id_, IO.Style.RESET_ALL))
return
hosts.add(self.hosts[id_])
return hosts
def _parse_direction_args(self, args):
direction = Direction.NONE
if args.upload:
direction |= Direction.OUTGOING
if args.download:
direction |= Direction.INCOMING
return Direction.BOTH if direction == Direction.NONE else direction
def _parse_iprange(self, range):
try:
if '-' in range:
return list(netaddr.iter_iprange(*range.split('-')))
else:
return list(netaddr.IPNetwork(range))
except netaddr.core.AddrFormatError:
return
def _parse_scan_intensity(self, value):
if value.isdigit() and int(value) in (ScanIntensity.QUICK, ScanIntensity.NORMAL, ScanIntensity.INTENSE):
return int(value)
def _free_host(self, host):
"""
Stops ARP spoofing and unlimits host
"""
if host.spoofed:
self.arp_spoofer.remove(host)
self.limiter.unlimit(host, Direction.BOTH)
self.bandwidth_monitor.remove(host)
self.host_watcher.remove(host)
|
2301_82206160/evillimite
|
evillimiter/menus/main_menu.py
|
Python
|
mit
| 28,519
|
import enum
import collections
from .parser import CommandParser
from evillimiter.console.io import IO
class CommandMenu(object):
def __init__(self):
self.prompt = '>>> '
self.parser = CommandParser()
self._active = False
def argument_handler(self, args):
"""
Handles command-line arguments.
"""
pass
def interrupt_handler(self):
"""
Handles a keyboard interrupt in the input loop.
"""
self.stop()
def start(self):
"""
Starts the menu input loop.
Commands will be processed and handled.
"""
self._active = True
while self._active:
try:
command = IO.input(self.prompt)
except KeyboardInterrupt:
self.interrupt_handler()
break
# split command by spaces and parse the arguments
parsed_args = self.parser.parse(command.split())
if parsed_args is not None:
self.argument_handler(parsed_args)
def stop(self):
"""
Breaks the menu input loop
"""
self._active = False
|
2301_82206160/evillimite
|
evillimiter/menus/menu.py
|
Python
|
mit
| 1,180
|
import enum
import collections
from evillimiter.console.io import IO
class CommandParser(object):
class CommandType(enum.Enum):
PARAMETER_COMMAND = 1
FLAG_COMMAND = 2
PARAMETERIZED_FLAG_COMMAND = 3
FlagCommand = collections.namedtuple('FlagCommand', 'type, identifier, name')
ParameterCommand = collections.namedtuple('ParameterCommand', 'type name')
Subparser = collections.namedtuple('Subparser', 'identifier subparser handler')
def __init__(self):
self._flag_commands = []
self._parameter_commands = []
self._subparsers = []
def add_parameter(self, name):
"""
Adds a parameter command that does not require an identifier.
It is required to cover all parameter commands.
E.g. '24' or 'hello'
Both are standalone values (parameters).
"""
command = CommandParser.ParameterCommand(
type=CommandParser.CommandType.PARAMETER_COMMAND,
name=name
)
self._parameter_commands.append(command)
def add_flag(self, identifier, name):
"""
Adds a flag command that does not carry any value.
Flags are optional.
E.g. '-verbose'
"""
command = CommandParser.FlagCommand(
type=CommandParser.CommandType.FLAG_COMMAND,
identifier=identifier,
name=name
)
self._flag_commands.append(command)
def add_parameterized_flag(self, identifier, name):
"""
Adds a parameterized flag that carries a value.
Parameterized flags are optional.
E.g. '-ip 192.168.0.0.1'
"""
command = CommandParser.FlagCommand(
type=CommandParser.CommandType.PARAMETERIZED_FLAG_COMMAND,
identifier=identifier,
name=name
)
self._flag_commands.append(command)
def add_subparser(self, identifier, handler=None):
"""
Creates a subparser and adds a command to this parser, making it its parent.
A subparser is a standalone parser that can contain commands itself.
E.g. 'git clone'
In this case 'git' is the parent and 'clone' the subparser
"""
subparser = CommandParser()
command = CommandParser.Subparser(
identifier=identifier,
subparser=subparser,
handler=handler
)
self._subparsers.append(command)
return subparser
def parse(self, command):
"""
Parses a given list of arguments
"""
names = [x.name for x in (self._flag_commands + self._parameter_commands)]
result_dict = dict.fromkeys(names, None)
# indicates whether or not to skip the next command argument
skip_next = False
for i, arg in enumerate(command):
if skip_next:
skip_next = False
continue
if i == 0:
# check if the first argument is a subparser
for sp in self._subparsers:
if sp.identifier == arg:
# if subparser present, parse arguments there
result = sp.subparser.parse(command[(i + 1):])
if result is not None and sp.handler is not None:
# call the subparser's handler if available
sp.handler(result)
return result
# indicates whether or not the argument has been processed
is_arg_processed = False
for cmd in self._flag_commands:
if cmd.identifier == arg:
if cmd.type == CommandParser.CommandType.FLAG_COMMAND:
# if its a flag, set the flag to true
result_dict[cmd.name] = True
is_arg_processed = True
break
elif cmd.type == CommandParser.CommandType.PARAMETERIZED_FLAG_COMMAND:
if (len(command) - 1) < (i + 1):
# no more command arguments to process
IO.error('parameter for flag {}{}{} is missing'.format(IO.Fore.LIGHTYELLOW_EX, cmd.name, IO.Style.RESET_ALL))
return
# if parameterized flag, set value to next argument
value = command[i + 1]
result_dict[cmd.name] = value
# skip the next argument (already processed)
skip_next = True
is_arg_processed = True
break
if not is_arg_processed:
for cmd in self._parameter_commands:
# parameter command, since a flag could not be found
if result_dict[cmd.name] is None:
# set parameter value
result_dict[cmd.name] = arg
is_arg_processed = True
break
if not is_arg_processed:
IO.error('{}{}{} is an unknown command.'.format(IO.Fore.LIGHTYELLOW_EX, arg, IO.Style.RESET_ALL))
return
# check if there are any parameters missing
for cmd in self._parameter_commands:
if result_dict[cmd.name] is None:
IO.error('parameter {}{}{} is missing'.format(IO.Fore.LIGHTYELLOW_EX, cmd.name, IO.Style.RESET_ALL))
return
# set unspecified flags to False instead of None
for cmd in self._flag_commands:
if cmd.type == CommandParser.CommandType.FLAG_COMMAND:
if result_dict[cmd.name] is None:
result_dict[cmd.name] = False
result_tuple = collections.namedtuple('ParseResult', sorted(result_dict))
return result_tuple(**result_dict)
|
2301_82206160/evillimite
|
evillimiter/menus/parser.py
|
Python
|
mit
| 5,965
|
from evillimiter.console.io import IO
class Host(object):
def __init__(self, ip, mac, name):
self.ip = ip
self.mac = mac
self.name = name
self.spoofed = False
self.limited = False
self.blocked = False
self.watched = False
def __eq__(self, other):
return self.ip == other.ip
def __hash__(self):
return hash((self.mac, self.ip))
|
2301_82206160/evillimite
|
evillimiter/networking/host.py
|
Python
|
mit
| 414
|
import threading
import evillimiter.console.shell as shell
from .host import Host
from evillimiter.common.globals import BIN_TC, BIN_IPTABLES
from evillimiter.console.io import IO
class Limiter(object):
class HostLimitIDs(object):
def __init__(self, upload_id, download_id):
self.upload_id = upload_id
self.download_id = download_id
def __init__(self, interface):
self.interface = interface
self._host_dict = {}
self._host_dict_lock = threading.Lock()
def limit(self, host, direction, rate):
"""
Limits the uload/dload traffic of a host
to a specified rate
"""
host_ids = self._new_host_limit_ids(host, direction)
if (direction & Direction.OUTGOING) == Direction.OUTGOING:
# add a class to the root qdisc with specified rate
shell.execute_suppressed('{} class add dev {} parent 1:0 classid 1:{} htb rate {r} burst {b}'.format(BIN_TC, self.interface, host_ids.upload_id, r=rate, b=rate * 1.1))
# add a fw filter that filters packets marked with the corresponding ID
shell.execute_suppressed('{} filter add dev {} parent 1:0 protocol ip prio {id} handle {id} fw flowid 1:{id}'.format(BIN_TC, self.interface, id=host_ids.upload_id))
# marks outgoing packets
shell.execute_suppressed('{} -t mangle -A POSTROUTING -s {} -j MARK --set-mark {}'.format(BIN_IPTABLES, host.ip, host_ids.upload_id))
if (direction & Direction.INCOMING) == Direction.INCOMING:
# add a class to the root qdisc with specified rate
shell.execute_suppressed('{} class add dev {} parent 1:0 classid 1:{} htb rate {r} burst {b}'.format(BIN_TC, self.interface, host_ids.download_id, r=rate, b=rate * 1.1))
# add a fw filter that filters packets marked with the corresponding ID
shell.execute_suppressed('{} filter add dev {} parent 1:0 protocol ip prio {id} handle {id} fw flowid 1:{id}'.format(BIN_TC, self.interface, id=host_ids.download_id))
# marks incoming packets
shell.execute_suppressed('{} -t mangle -A PREROUTING -d {} -j MARK --set-mark {}'.format(BIN_IPTABLES, host.ip, host_ids.download_id))
host.limited = True
with self._host_dict_lock:
self._host_dict[host] = { 'ids': host_ids, 'rate': rate, 'direction': direction }
def block(self, host, direction):
host_ids = self._new_host_limit_ids(host, direction)
if (direction & Direction.OUTGOING) == Direction.OUTGOING:
# drops forwarded packets with matching source
shell.execute_suppressed('{} -t filter -A FORWARD -s {} -j DROP'.format(BIN_IPTABLES, host.ip))
if (direction & Direction.INCOMING) == Direction.INCOMING:
# drops forwarded packets with matching destination
shell.execute_suppressed('{} -t filter -A FORWARD -d {} -j DROP'.format(BIN_IPTABLES, host.ip))
host.blocked = True
with self._host_dict_lock:
self._host_dict[host] = { 'ids': host_ids, 'rate': None, 'direction': direction }
def unlimit(self, host, direction):
if not host.limited and not host.blocked:
return
with self._host_dict_lock:
host_ids = self._host_dict[host]['ids']
if (direction & Direction.OUTGOING) == Direction.OUTGOING:
self._delete_tc_class(host_ids.upload_id)
self._delete_iptables_entries(host, direction, host_ids.upload_id)
if (direction & Direction.INCOMING) == Direction.INCOMING:
self._delete_tc_class(host_ids.download_id)
self._delete_iptables_entries(host, direction, host_ids.download_id)
del self._host_dict[host]
host.limited = False
host.blocked = False
def replace(self, old_host, new_host):
self._host_dict_lock.acquire()
info = self._host_dict[old_host] if old_host in self._host_dict else None
self._host_dict_lock.release()
if info is not None:
self.unlimit(old_host, Direction.BOTH)
if info['rate'] is None:
self.block(new_host, info['direction'])
else:
self.limit(new_host, info['direction'], info['rate'])
def pretty_status(self, host):
"""
Gets the host limitation status in a formatted and colored string
"""
with self._host_dict_lock:
if host in self._host_dict:
rate = self._host_dict[host]['rate']
direction = self._host_dict[host]['direction']
uload = None
dload = None
final = ''
if direction in (Direction.BOTH, Direction.OUTGOING):
uload = '0bit' if rate is None else rate
if direction in (Direction.BOTH, Direction.INCOMING):
dload = '0bit' if rate is None else rate
if uload is not None:
final += '{}↑'.format(uload)
if dload is not None:
final += ' {}↓'.format(dload)
return '{}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, final.strip(), IO.Style.RESET_ALL)
else:
return '{}Free{}'.format(IO.Fore.LIGHTGREEN_EX, IO.Style.RESET_ALL)
def _new_host_limit_ids(self, host, direction):
"""
Get limit information for corresponding host
If not present, create new
"""
host_ids = None
self._host_dict_lock.acquire()
present = host in self._host_dict
self._host_dict_lock.release()
if present:
host_ids = self._host_dict[host]['ids']
self.unlimit(host, direction)
return Limiter.HostLimitIDs(*self._create_ids()) if host_ids is None else host_ids
def _create_ids(self):
"""
Returns unique IDs that are
currently not in use
"""
def generate_id(*exc):
"""
Generates a unique, unused ID
exc: IDs that will not be used (exceptions)
"""
id_ = 1
with self._host_dict_lock:
while True:
if id_ not in exc:
v = (x for x in self._host_dict.values())
ids = (x['ids'] for x in v)
if id_ not in (x for y in ids for x in [y.upload_id, y.download_id]):
return id_
id_ += 1
id1 = generate_id()
return (id1, generate_id(id1))
def _delete_tc_class(self, id_):
"""
Deletes the tc class and applied filters
for a given ID (host)
"""
shell.execute_suppressed('{} filter del dev {} parent 1:0 prio {}'.format(BIN_TC, self.interface, id_))
shell.execute_suppressed('{} class del dev {} parent 1:0 classid 1:{}'.format(BIN_TC, self.interface, id_))
def _delete_iptables_entries(self, host, direction, id_):
"""
Deletes iptables rules for a given ID (host)
"""
if (direction & Direction.OUTGOING) == Direction.OUTGOING:
shell.execute_suppressed('{} -t mangle -D POSTROUTING -s {} -j MARK --set-mark {}'.format(BIN_IPTABLES, host.ip, id_))
shell.execute_suppressed('{} -t filter -D FORWARD -s {} -j DROP'.format(BIN_IPTABLES, host.ip))
if (direction & Direction.INCOMING) == Direction.INCOMING:
shell.execute_suppressed('{} -t mangle -D PREROUTING -d {} -j MARK --set-mark {}'.format(BIN_IPTABLES, host.ip, id_))
shell.execute_suppressed('{} -t filter -D FORWARD -d {} -j DROP'.format(BIN_IPTABLES, host.ip))
class Direction:
NONE = 0
OUTGOING = 1
INCOMING = 2
BOTH = 3
def pretty_direction(direction):
if direction == Direction.OUTGOING:
return 'upload'
elif direction == Direction.INCOMING:
return 'download'
elif direction == Direction.BOTH:
return 'upload / download'
else:
return '-'
|
2301_82206160/evillimite
|
evillimiter/networking/limit.py
|
Python
|
mit
| 8,379
|
import time
import threading
from scapy.all import sniff, IP # pylint: disable=no-name-in-module
from .utils import ValueConverter, BitRate, ByteValue
class BandwidthMonitor(object):
class BandwidthMonitorResult(object):
def __init__(self):
self.upload_rate = BitRate()
self.upload_total_size = ByteValue()
self.upload_total_count = 0
self.download_rate = BitRate()
self.download_total_size = ByteValue()
self.download_total_count = 0
self._upload_temp_size = ByteValue()
self._download_temp_size = ByteValue()
def __init__(self, interface, interval):
self.interface = interface
self._host_result_dict = {}
self._host_result_lock = threading.Lock()
self._running = False
def add(self, host):
with self._host_result_lock:
if host not in self._host_result_dict:
self._host_result_dict[host] = { 'result': BandwidthMonitor.BandwidthMonitorResult(), 'last_now': time.time() }
def remove(self, host):
with self._host_result_lock:
self._host_result_dict.pop(host, None)
def replace(self, old_host, new_host):
with self._host_result_lock:
if old_host in self._host_result_dict:
self._host_result_dict[new_host] = self._host_result_dict[old_host]
del self._host_result_dict[old_host]
def start(self):
if self._running:
return
sniff_thread = threading.Thread(target=self._sniff, args=[], daemon=True)
sniff_thread.start()
self._running = True
def stop(self):
self._running = False
def get(self, host):
with self._host_result_lock:
if host in self._host_result_dict:
last_now = self._host_result_dict[host]['last_now']
time_passed = time.time() - last_now
result = self._host_result_dict[host]['result']
result.upload_rate = BitRate(int(ValueConverter.byte_to_bit(result._upload_temp_size.value) / time_passed))
result.download_rate = BitRate(int(ValueConverter.byte_to_bit(result._download_temp_size.value) / time_passed))
result._upload_temp_size *= 0
result._download_temp_size *= 0
self._host_result_dict[host]['last_now'] = time.time()
return result
def _sniff(self):
def pkt_handler(pkt):
if pkt.haslayer(IP):
with self._host_result_lock:
for host in self._host_result_dict:
result = self._host_result_dict[host]['result']
if host.ip == pkt[IP].src:
result.upload_total_size += len(pkt)
result.upload_total_count += 1
result._upload_temp_size += len(pkt)
elif host.ip == pkt[IP].dst:
result.download_total_size += len(pkt)
result.download_total_count += 1
result._download_temp_size += len(pkt)
def stop_filter(pkt):
return not self._running
sniff(iface=self.interface, prn=pkt_handler, stop_filter=stop_filter, store=0)
|
2301_82206160/evillimite
|
evillimiter/networking/monitor.py
|
Python
|
mit
| 3,474
|
import sys
import socket
import threading
import collections
from tqdm import tqdm
from netaddr import IPAddress
from scapy.all import sr1, ARP # pylint: disable=no-name-in-module
from concurrent.futures import ThreadPoolExecutor
from .host import Host
from evillimiter.console.io import IO
class HostScanner(object):
Settings = collections.namedtuple('Settings', 'max_workers retries timeout')
def __init__(self, interface, iprange):
self.interface = interface
self.iprange = iprange
self._quick_settings = HostScanner.Settings(max_workers=80, retries=0, timeout=2)
self._normal_settings = HostScanner.Settings(max_workers=80, retries=1, timeout=3)
self._intense_settings = HostScanner.Settings(max_workers=80, retries=5, timeout=10)
self._settings = self._normal_settings
self._settings_lock = threading.Lock()
@property
def settings(self):
with self._settings_lock:
return self._settings
@settings.setter
def settings(self, value):
with self._settings_lock:
self._settings = value
def set_intensity(self, intensity):
if intensity == ScanIntensity.QUICK:
self.settings = self._quick_settings
elif intensity == ScanIntensity.NORMAL:
self.settings = self._normal_settings
elif intensity == ScanIntensity.INTENSE:
self.settings = self._intense_settings
def scan(self, iprange=None):
with ThreadPoolExecutor(max_workers=self.settings.max_workers) as executor:
hosts = []
iprange = [str(x) for x in (self.iprange if iprange is None else iprange)]
iterator = tqdm(
iterable=executor.map(self._sweep, iprange),
total=len(iprange),
ncols=45,
bar_format='{percentage:3.0f}% |{bar}| {n_fmt}/{total_fmt}'
)
try:
for host in iterator:
if host is not None:
try:
host_info = socket.gethostbyaddr(host.ip)
name = '' if host_info is None else host_info[0]
host.name = name
except socket.herror:
pass
hosts.append(host)
except KeyboardInterrupt:
iterator.close()
IO.ok('aborted. waiting for shutdown...')
return hosts
def scan_for_reconnects(self, hosts, iprange=None):
with ThreadPoolExecutor(max_workers=self.settings.max_workers) as executor:
scanned_hosts = []
iprange = [str(x) for x in (self.iprange if iprange is None else iprange)]
for host in executor.map(self._sweep, iprange):
if host is not None:
scanned_hosts.append(host)
reconnected_hosts = {}
for host in hosts:
for s_host in scanned_hosts:
if host.mac == s_host.mac and host.ip != s_host.ip:
s_host.name = host.name
reconnected_hosts[host] = s_host
return reconnected_hosts
def _sweep(self, ip):
"""
Sends ARP packet and listens for answer,
if present the host is online
"""
settings = self.settings
packet = ARP(op=1, pdst=ip)
answer = sr1(packet, retry=settings.retries, timeout=settings.timeout, verbose=0, iface=self.interface)
if answer is not None:
return Host(ip, answer.hwsrc, '')
class ScanIntensity:
QUICK = 1
NORMAL = 2
INTENSE = 3
|
2301_82206160/evillimite
|
evillimiter/networking/scan.py
|
Python
|
mit
| 3,735
|
import time
import threading
from scapy.all import ARP, send # pylint: disable=no-name-in-module
from .host import Host
from evillimiter.common.globals import BROADCAST
class ARPSpoofer(object):
def __init__(self, interface, gateway_ip, gateway_mac):
self.interface = interface
self.gateway_ip = gateway_ip
self.gateway_mac = gateway_mac
# interval in s spoofed ARP packets are sent to targets
self.interval = 2
self._hosts = set()
self._hosts_lock = threading.Lock()
self._running = False
def add(self, host):
with self._hosts_lock:
self._hosts.add(host)
host.spoofed = True
def remove(self, host, restore=True):
with self._hosts_lock:
self._hosts.discard(host)
if restore:
self._restore(host)
host.spoofed = False
def start(self):
thread = threading.Thread(target=self._spoof, args=[], daemon=True)
self._running = True
thread.start()
def stop(self):
self._running = False
def _spoof(self):
while self._running:
self._hosts_lock.acquire()
# make a deep copy to reduce lock time
hosts = self._hosts.copy()
self._hosts_lock.release()
for host in hosts:
if not self._running:
return
self._send_spoofed_packets(host)
time.sleep(self.interval)
def _send_spoofed_packets(self, host):
# 2 packets = 1 gateway packet, 1 host packet
packets = [
ARP(op=2, psrc=host.ip, pdst=self.gateway_ip, hwdst=self.gateway_mac),
ARP(op=2, psrc=self.gateway_ip, pdst=host.ip, hwdst=host.mac)
]
[send(x, verbose=0, iface=self.interface) for x in packets]
def _restore(self, host):
"""
Remaps host and gateway to their actual addresses
"""
# 2 packets = 1 gateway packet, 1 host packet
packets = [
ARP(op=2, psrc=host.ip, hwsrc=host.mac, pdst=self.gateway_ip, hwdst=BROADCAST),
ARP(op=2, psrc=self.gateway_ip, hwsrc=self.gateway_mac, pdst=host.ip, hwdst=BROADCAST)
]
[send(x, verbose=0, iface=self.interface, count=3) for x in packets]
|
2301_82206160/evillimite
|
evillimiter/networking/spoof.py
|
Python
|
mit
| 2,330
|
import re
import netifaces
from scapy.all import ARP, sr1 # pylint: disable=no-name-in-module
import evillimiter.console.shell as shell
from evillimiter.common.globals import BIN_TC, BIN_IPTABLES, BIN_SYSCTL, IP_FORWARD_LOC
def get_default_interface():
"""
Returns the default IPv4 interface
"""
gateways = netifaces.gateways()
if 'default' in gateways and netifaces.AF_INET in gateways['default']:
return gateways['default'][netifaces.AF_INET][1]
def get_default_gateway():
"""
Returns the default IPv4 gateway address
"""
gateways = netifaces.gateways()
if 'default' in gateways and netifaces.AF_INET in gateways['default']:
return gateways['default'][netifaces.AF_INET][0]
def get_default_netmask(interface):
"""
Returns the default IPv4 netmask associated to an interface
"""
ifaddrs = netifaces.ifaddresses(interface)
if netifaces.AF_INET in ifaddrs:
return ifaddrs[netifaces.AF_INET][0].get('netmask')
def get_mac_by_ip(interface, address):
"""
Resolves hardware address from IP by sending ARP request
and receiving ARP response
"""
# ARP packet with operation 1 (who-is)
packet = ARP(op=1, pdst=address)
response = sr1(packet, timeout=3, verbose=0, iface=interface)
if response is not None:
return response.hwsrc
def exists_interface(interface):
"""
Determines whether or not a given interface exists
"""
return interface in netifaces.interfaces()
def flush_network_settings(interface):
"""
Flushes all iptable rules and traffic control entries
related to the given interface
"""
# reset default policy
shell.execute_suppressed('{} -P INPUT ACCEPT'.format(BIN_IPTABLES))
shell.execute_suppressed('{} -P OUTPUT ACCEPT'.format(BIN_IPTABLES))
shell.execute_suppressed('{} -P FORWARD ACCEPT'.format(BIN_IPTABLES))
# flush all chains in all tables (including user-defined)
shell.execute_suppressed('{} -t mangle -F'.format(BIN_IPTABLES))
shell.execute_suppressed('{} -t nat -F'.format(BIN_IPTABLES))
shell.execute_suppressed('{} -F'.format(BIN_IPTABLES))
shell.execute_suppressed('{} -X'.format(BIN_IPTABLES))
# delete root qdisc for given interface
shell.execute_suppressed('{} qdisc del dev {} root'.format(BIN_TC, interface))
def validate_ip_address(ip):
return re.match(r'^(\d{1,3}\.){3}(\d{1,3})$', ip) is not None
def validate_mac_address(mac):
return re.match(r'^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$', mac) is not None
def create_qdisc_root(interface):
"""
Creates a root htb qdisc in traffic control for a given interface
"""
return shell.execute_suppressed('{} qdisc add dev {} root handle 1:0 htb'.format(BIN_TC, interface)) == 0
def delete_qdisc_root(interface):
return shell.execute_suppressed('{} qdisc del dev {} root handle 1:0 htb'.format(BIN_TC, interface))
def enable_ip_forwarding():
return shell.execute_suppressed('{} -w {}=1'.format(BIN_SYSCTL, IP_FORWARD_LOC)) == 0
def disable_ip_forwarding():
return shell.execute_suppressed('{} -w {}=0'.format(BIN_SYSCTL, IP_FORWARD_LOC)) == 0
class ValueConverter:
@staticmethod
def byte_to_bit(v):
return v * 8
class BitRate(object):
def __init__(self, rate=0):
self.rate = rate
def __repr__(self):
return self.__str__()
def __str__(self):
counter = 0
r = self.rate
while True:
if r >= 1000:
r /= 1000
counter += 1
else:
unit = ''
if counter == 0:
unit = 'bit'
elif counter == 1:
unit = 'kbit'
elif counter == 2:
unit = 'mbit'
elif counter == 3:
unit = 'gbit'
return '{}{}'.format(int(r), unit)
if counter > 3:
raise Exception('Bitrate limit exceeded')
def __mul__(self, other):
if isinstance(other, BitRate):
return BitRate(int(self.rate * other.rate))
return BitRate(int(self.rate * other))
def fmt(self, fmt):
string = self.__str__()
end = len([_ for _ in string if _.isdigit()])
num = int(string[:end])
return '{}{}'.format(fmt % num, string[end:])
@classmethod
def from_rate_string(cls, rate_string):
return cls(BitRate._bit_value(rate_string))
@staticmethod
def _bit_value(rate_string):
number = 0 # rate number
offset = 0 # string offset
for c in rate_string:
if c.isdigit():
number = number * 10 + int(c)
offset += 1
else:
break
unit = rate_string[offset:].lower()
if unit == 'bit':
return number
elif unit == 'kbit':
return number * 1000
elif unit == 'mbit':
return number * 1000 ** 2
elif unit == 'gbit':
return number * 1000 ** 3
else:
raise Exception('Invalid bitrate')
class ByteValue(object):
def __init__(self, value=0):
self.value = value
def __repr__(self):
return self.__str__()
def __str__(self):
counter = 0
v = self.value
while True:
if v >= 1024:
v /= 1024
counter += 1
else:
unit = ''
if counter == 0:
unit = 'b'
elif counter == 1:
unit = 'kb'
elif counter == 2:
unit = 'mb'
elif counter == 3:
unit = 'gb'
elif counter == 4:
unit = 'tb'
return '{}{}'.format(int(v), unit)
if counter > 3:
raise Exception('Byte value limit exceeded')
def __int__(self):
return self.value
def __add__(self, other):
if isinstance(other, ByteValue):
return ByteValue(int(self.value + other.value))
return ByteValue(int(self.value + other))
def __sub__(self, other):
if isinstance(other, ByteValue):
return ByteValue(int(self.value - other.value))
return ByteValue(int(self.value - other))
def __mul__(self, other):
if isinstance(other, ByteValue):
return ByteValue(int(self.value * other.value))
return ByteValue(int(self.value * other))
def __ge__(self, other):
if isinstance(other, ByteValue):
return self.value >= other.value
return self.value >= other
def fmt(self, fmt):
string = self.__str__()
end = len([_ for _ in string if _.isdigit()])
num = int(string[:end])
return '{}{}'.format(fmt % num, string[end:])
@classmethod
def from_byte_string(cls, byte_string):
return cls(ByteValue._byte_value(byte_string))
@staticmethod
def _byte_value(byte_string):
number = 0 # rate number
offset = 0 # string offset
for c in byte_string:
if c.isdigit():
number = number * 10 + int(c)
offset += 1
else:
break
unit = byte_string[offset:].lower()
if unit == 'b':
return number
elif unit == 'kb':
return number * 1024
elif unit == 'mb':
return number * 1024 ** 2
elif unit == 'gb':
return number * 1024 ** 3
elif unit == 'tb':
return number * 1024 ** 4
else:
raise Exception('Invalid byte string')
|
2301_82206160/evillimite
|
evillimiter/networking/utils.py
|
Python
|
mit
| 8,088
|
import time
import threading
from .scan import HostScanner, ScanIntensity
class HostWatcher(object):
def __init__(self, interface, iprange, reconnection_callback):
self._scanner = HostScanner(interface, iprange)
self._reconnection_callback = reconnection_callback
self._hosts = set()
self._hosts_lock = threading.Lock()
self._interval = 45 # scan interval in s
self._iprange = iprange # custom ip range to be watched
self._intensity = ScanIntensity.NORMAL # scan intensity (speed)
self._settings_lock = threading.Lock()
self._log_list = []
self._log_list_lock = threading.Lock()
self._running = False
@property
def interval(self):
with self._settings_lock:
return self._interval
@interval.setter
def interval(self, value):
with self._settings_lock:
self._interval = value
@property
def iprange(self):
with self._settings_lock:
return self._iprange
@iprange.setter
def iprange(self, value):
with self._settings_lock:
self._iprange = value
@property
def intensity(self):
return self._intensity
@intensity.setter
def intensity(self, value):
self._scanner.set_intensity(value)
self._intensity = value
@property
def hosts(self):
with self._hosts_lock:
return self._hosts.copy()
@property
def log_list(self):
with self._log_list_lock:
return self._log_list.copy()
def add(self, host):
with self._hosts_lock:
self._hosts.add(host)
host.watched = True
def remove(self, host):
with self._hosts_lock:
self._hosts.discard(host)
host.watched = False
def start(self):
thread = threading.Thread(target=self._watch, args=[], daemon=True)
self._running = True
thread.start()
def stop(self):
self._running = False
def _watch(self):
while self._running:
self._hosts_lock.acquire()
hosts = self._hosts.copy()
self._hosts_lock.release()
if len(hosts) > 0:
reconnected_hosts = self._scanner.scan_for_reconnects(hosts, self.iprange)
for old_host, new_host in reconnected_hosts.items():
self._reconnection_callback(old_host, new_host)
with self._log_list_lock:
self._log_list.append({ 'old': old_host, 'new': new_host, 'time': time.strftime('%Y-%m-%d %H:%M %p') })
time.sleep(self.interval)
|
2301_82206160/evillimite
|
evillimiter/networking/watch.py
|
Python
|
mit
| 2,708
|
import os
import re
from setuptools import setup, find_packages, Command
class CleanCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
os.system('rm -vrf ./build ./dist ./*.pyc ./*.pyo ./*.pyd ./*.tgz ./*.egg-info `find -type d -name __pycache__`')
def get_init_content():
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'evillimiter', '__init__.py'), 'r') as f:
return f.read()
def get_version():
version_match = re.search(r'^__version__ = [\'"](\d\.\d\.\d)[\'"]', get_init_content(), re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to locate version string.')
def get_description():
desc_match = re.search(r'^__description__ = [\'"]((.)*)[\'"]', get_init_content(), re.M)
if desc_match:
return desc_match.group(1)
raise RuntimeError('Unable to locate description string.')
NAME = 'evillimiter'
AUTHOR = 'bitbrute'
AUTHOR_EMAIL = 'bitbrute@gmail.com'
LICENSE = 'MIT'
VERSION = get_version()
URL = 'https://github.com/bitbrute/evillimiter'
DESCRIPTION = get_description()
KEYWORDS = ["evillimiter", "limit", "bandwidth", "network"]
PACKAGES = find_packages()
INCLUDE_PACKAGE_DATA = True
CLASSIFIERS = ['Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: System Administrators',
'Intended Audience :: Developers'
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: Unix',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3 :: Only',
'Topic :: System :: Networking',
]
PYTHON_REQUIRES = '>= 3'
ENTRY_POINTS = { 'console_scripts': ['evillimiter = evillimiter.evillimiter:run'] }
INSTALL_REQUIRES = ['colorama',
'netaddr',
'netifaces',
'tqdm',
'scapy',
'terminaltables'
]
CMDCLASS = { 'clean': CleanCommand }
setup(
name=NAME,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
description=DESCRIPTION,
license=LICENSE,
keywords=KEYWORDS,
packages=PACKAGES,
include_package_data=INCLUDE_PACKAGE_DATA,
version=VERSION,
python_requires=PYTHON_REQUIRES,
entry_points=ENTRY_POINTS,
install_requires=INSTALL_REQUIRES,
classifiers=CLASSIFIERS,
url=URL,
cmdclass=CMDCLASS,
)
|
2301_82206160/evillimite
|
setup.py
|
Python
|
mit
| 2,682
|
#pragma once
#include "../Base/BaseData.hpp"
using namespace base;
template <typename TArray, typename TElemType>
class MasterArray {
public:
virtual Status initArray(TArray& a, int n) = 0;
virtual Status destoryArray(TArray& a) = 0;
virtual Status Value(const TArray a, TElemType& e) = 0;
virtual Status Assign(TArray& a, TElemType e) = 0;
};
|
2301_82205515/CppDataLearn
|
Array/MasterArray.hpp
|
C++
|
unknown
| 363
|
#pragma once
#include <string>
namespace base {
const int IntDefault = 0;
const char CharDefault = '\0';
const std::string StrDefault = "\0";
const int StringMaxSize = 255;
const int QueueMaxSize = 100;
const int ListMaxSize = 100;
const int TreeMaxSize = 100;
enum Status {
Ok,
Err,
};
}
|
2301_82205515/CppDataLearn
|
Base/BaseData.hpp
|
C++
|
unknown
| 302
|
#ifndef LINK_LIST_HPP
#define LINK_LIST_HPP
#include <cstddef>
typedef int LElemType;
typedef struct Node {
LElemType data;
struct Node* next;
} Node, *LinkedList;
typedef enum {
Ok,
Err
} Status;
class LinkList {
public:
LinkList(LElemType e)
{
l = new Node;
l->data = e;
l->next = NULL;
}
bool isInit()
{
return l == nullptr;
}
Status addNode(LElemType e)
{
if (isInit()) {
return Status::Err;
}
LinkedList newNode = new Node;
LinkedList ptr = l;
while (ptr->next != nullptr) {
ptr = ptr->next;
}
newNode->data = e;
newNode->next = nullptr;
ptr->next = newNode;
return Status::Ok;
}
int Max()
{
if (l == nullptr)
return -1;
LElemType tempMax = l->data;
LinkedList ptr = l->next;
while (ptr != nullptr) {
tempMax = tempMax > ptr->data ? tempMax : ptr->data;
ptr = ptr->next;
}
return tempMax;
}
int Count()
{
if (l == nullptr)
return 0;
LinkedList ptr = l;
int count = 0;
while (ptr != nullptr) {
count++;
ptr = ptr->next;
}
return count;
}
double Average()
{
if (l == nullptr)
return 0;
LinkedList ptr = l;
int sum = 0;
while (ptr != nullptr) {
sum += ptr->data;
ptr = ptr->next;
}
return (double)sum / (double)Count();
}
private:
LinkedList l;
};
#endif
|
2301_82205515/CppDataLearn
|
LinkList.hpp
|
C++
|
unknown
| 1,648
|
#ifndef DULINK_LIST_HPP
#define DULINK_LIST_HPP
#include "MasterList.hpp"
typedef int ElemType;
typedef struct DuLNode{
ElemType data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode, *DuLinkList;
class DuLinkListC : public MasterList<DuLinkList, ElemType>{
public:
};
#endif
|
2301_82205515/CppDataLearn
|
List/DuLinkList.hpp
|
C++
|
unknown
| 300
|
#pragma once
#include "MasterList.hpp"
#include <iostream>
#include <cstdlib>
typedef int ElemType;
const ElemType Default = 0;
typedef struct LNode {
ElemType data;
struct LNode* next;
} LNode, *LinkList;
class LinkListC : public MasterList<LinkList, ElemType> {
private:
LinkList temp;
public:
Status initList(LinkList& l) override
{
l = new LNode;
l->next = nullptr;
return Status::Ok;
}
Status destoryList(LinkList& l) override
{
while (l != nullptr) {
temp = l;
l = l->next;
delete temp;
}
return Status::Ok;
}
Status clearList(LinkList& l) override
{
temp = l;
while (l != nullptr) {
l->data = Default;
l = l->next;
}
l = temp;
return Status::Ok;
}
bool listEmpty(const LinkList l) override
{
return l == nullptr || l->next == nullptr;
}
int listLength(const LinkList l) override
{
if (l == nullptr)
return Status::Err;
int count = 0;
temp = l;
while (temp != nullptr) {
temp = temp->next;
count++;
}
return count;
}
Status getElem(const LinkList l, int i, ElemType& e) override
{
if (l == nullptr || i < 0 || i > listLength(l))
return Status::Err;
int count = 0;
temp = l;
while (temp != nullptr) {
if (count == i) {
e = temp->data;
}
count++;
temp = temp->next;
}
return Status::Ok;
}
int locateElem(const LinkList l, const ElemType e) override
{
if (l == nullptr)
return Status::Err;
int count = 0;
temp = l;
while (temp != nullptr) {
if (temp->data == e) {
return count;
}
count++;
temp = temp->next;
}
return Status::Ok;
}
Status priorElem(const LinkList l, const ElemType cur_e, ElemType& pre_e) override
{
if (l == nullptr)
return Status::Err;
temp = l;
while (temp->next != nullptr) {
if (temp->next->data == cur_e) {
pre_e = temp->data;
}
temp = temp->next;
}
return Status::Ok;
}
Status nextElem(const LinkList l, const ElemType cur_e, ElemType& next_e) override
{
if (l == nullptr)
return Status::Err;
temp = l;
while (temp->next != nullptr) {
if (temp->data == cur_e) {
next_e = temp->next->data;
}
temp = temp->next;
}
return Status::Ok;
}
Status listInsert(LinkList& l, int i, ElemType e) override
{
if (l == nullptr || i < 0 || i > listLength(l))
return Status::Err;
LinkList VLNode = new LNode;
VLNode->next = l;
int count = 0;
temp = VLNode;
while (temp->next != nullptr) {
if (count == i) {
LinkList mark = temp->next;
temp->next = new LNode;
temp->next->data = e;
temp->next->next = mark;
delete VLNode;
return Status::Ok;
}
count++;
temp = temp->next;
}
return Status::Err;
}
Status listDelete(LinkList& l, int i) override
{
if (l == nullptr || i < 0 || i > listLength(l))
return Status::Err;
LinkList VLNode = new LNode;
VLNode->next = l;
int count;
temp = VLNode;
while (temp->next != nullptr) {
if (count == i) {
LinkList mark = temp->next;
temp->next = temp->next->next;
delete mark;
delete VLNode;
return Status::Ok;
}
count++;
temp = temp->next;
}
return Status::Err;
}
Status traverseList(const LinkList l) override
{
if (l == nullptr)
return Status::Err;
temp = l;
while (temp != nullptr) {
std::cout << temp->data << std::endl;
temp = temp->next;
}
return Status::Ok;
}
};
|
2301_82205515/CppDataLearn
|
List/LinkList.hpp
|
C++
|
unknown
| 4,379
|
#pragma once
#include "../Base/BaseData.hpp"
using namespace base;
template <typename TList, typename TElemType>
class MasterList {
public:
virtual ~MasterList() = default;
virtual Status initList(TList& l) = 0;
virtual Status destoryList(TList& l) = 0;
virtual Status clearList(TList& l) = 0;
virtual bool listEmpty(const TList l) = 0;
virtual int listLength(const TList l) = 0;
virtual Status getElem(const TList l, int i, TElemType& e) = 0;
virtual int locateElem(const TList l, const TElemType e) = 0;
virtual Status priorElem(const TList l, const TElemType cur_e, TElemType& pre_e) = 0;
virtual Status nextElem(const TList l, const TElemType cur_e, TElemType& next_e) = 0;
virtual Status listInsert(TList& l, int i, TElemType e) = 0;
virtual Status listDelete(TList& l, int i) = 0;
virtual Status traverseList(const TList l) = 0;
};
|
2301_82205515/CppDataLearn
|
List/MasterList.hpp
|
C++
|
unknown
| 894
|
#pragma once
#include "MasterList.hpp"
#include <iostream>
#include <cstdlib>
typedef int ElemType;
typedef struct {
ElemType* elem;
int length;
} SqList;
class SqListC : public MasterList<SqList, ElemType> {
public:
Status initList(SqList& l) override
{
l.elem = new ElemType[ListMaxSize];
if (!l.elem)
exit(0);
l.length = 0;
return Status::Ok;
}
Status destoryList(SqList& l) override
{
delete[] l.elem;
l.elem = nullptr;
l.length = 0;
return Status::Ok;
}
Status clearList(SqList& l) override
{
delete[] l.elem;
l.elem = new ElemType[ListMaxSize];
l.length = 0;
return Status::Ok;
}
inline bool listEmpty(const SqList l) override
{
return l.length == 0;
}
inline int listLength(const SqList l) override
{
return l.length;
}
Status getElem(const SqList l, int i, ElemType& e) override
{
if (!l.elem || l.length < i || i < 0)
return Status::Err;
e = l.elem[i];
return Status::Ok;
}
int locateElem(const SqList l, const ElemType e) override
{
if (!l.elem)
return -1;
for (int i = 0; i < l.length; i++) {
if (l.elem[i] == e)
return i;
}
return -1;
}
Status priorElem(const SqList l, const ElemType cur_e, ElemType& pre_e) override
{
if (!l.elem)
return Status::Err;
for (int i = 0; i < l.length - 1; i++) {
if (l.elem[i + 1] == cur_e) {
pre_e = l.elem[i];
return Status::Ok;
}
}
return Status::Err;
}
Status nextElem(const SqList l, const ElemType cur_e, ElemType& next_e) override
{
if (!l.elem)
return Status::Err;
for (int i = 0; i < l.length - 1; i++) {
if (l.elem[i] == cur_e) {
next_e = l.elem[i + 1];
return Status::Ok;
}
}
return Status::Err;
}
Status listInsert(SqList& l, int i, ElemType e) override
{
if (!l.elem || l.length < i || i < 0)
return Status::Err;
for (int j = l.length; j > i; j++) {
l.elem[j - 1] = l.elem[j];
}
l.elem[i] = e;
l.length++;
return Status::Ok;
}
Status listDelete(SqList& l, int i) override
{
if (!l.elem || l.length < i || i < 0)
return Status::Err;
for (int j = i; j < l.length - 1; j++) {
l.elem[j] = l.elem[j + 1];
}
l.length--;
return Status::Ok;
}
Status traverseList(const SqList l) override
{
if (!l.elem)
return Status::Err;
for (int i = 0; i < l.length; i++) {
std::cout << l.elem[i] << std::endl;
}
return Status::Ok;
}
};
|
2301_82205515/CppDataLearn
|
List/SqList.hpp
|
C++
|
unknown
| 2,962
|
#ifndef DEQUE_HPP
#define DEQUE_HPP
#include "SqQueue.hpp"
class Deque : public SqQueueC {
public:
Deque() {
initQueue(q);
}
Status deFront(QElemType &e) {
deQueue(q, e);
return Status::Ok;
}
Status deRear(QElemType &e) {
if (queueEmpty(q)) {
return Status::Err;
}
q.rear = (q.rear - 1 + QueueMaxSize) % QueueMaxSize;
e = q.base[q.rear];
return Status::Ok;
}
Status enFront(QElemType e) {
if ((q.front -1 + QueueMaxSize) %QueueMaxSize == q.rear) {
return Status::Err;
}
q.front = (q.front -1 +QueueMaxSize) %QueueMaxSize;
q.base[q.front] = e;
return Status::Ok;
}
Status enRear(QElemType e) {
enQueue(q, e);
return Status::Ok;
}
~Deque() {
destoryQueue(q);
}
private:
Queue q;
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/Deque.hpp
|
C++
|
unknown
| 902
|
#ifndef LINK_QUEUE_HPP
#define LINK_QUEUE_HPP
#include "MasterQueue.hpp"
#include <cstddef>
#include <cstdlib>
#include <iostream>
typedef int QElemType;
typedef struct QNode {
QElemType data;
struct QNode* next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
} LinkQueue;
class LinkQueueC : public MasterQueue<LinkQueue, QElemType> {
public:
Status initQueue(LinkQueue& q) override
{
q.front = q.rear = new QNode;
q.front->next = nullptr;
return Status::Ok;
}
Status destoryQueue(LinkQueue& q) override
{
while (q.front)
{
QueuePtr temp = q.front;
q.front = q.front->next;
delete temp;
}
q.rear = nullptr;
return Status::Ok;
}
Status clearQueue(LinkQueue& q) override
{
while (q.front != q.rear) {
QueuePtr temp = q.front;
q.front = q.front->next;
temp->next = nullptr;
temp->data = {};
}
return Status::Ok;
}
inline bool queueEmpty(const LinkQueue& q) override {
return !q.front || q.front->next == nullptr;
}
int queueLength(const LinkQueue& q) override {
QueuePtr temp = q.front;
int len;
for (len = 1; temp != q.rear; len++){
temp = temp->next;
}
return len;
}
QElemType getHead(LinkQueue& q) override
{
if (q.front != nullptr){
return q.front->data;
}
return {};
}
Status enQueue(LinkQueue& q, QElemType e) override
{
QueuePtr temp = new QNode;
temp->next = nullptr;
q.rear->data = e;
q.rear->next = temp;
q.rear = temp;
return Status::Ok;
}
Status deQueue(LinkQueue& q, QElemType& e) override
{
if (q.front == nullptr) {
return Status::Err;
}
QueuePtr temp = q.front;
e = q.front->data;
q.front = q.front->next;
delete temp;
return Status::Ok;
}
Status queueTraverse(const LinkQueue q) override
{
if (q.front == nullptr) {
return Status::Err;
}
while (q.front != q.rear) {
std::cout << q.front->data << " " << std::endl;
}
return Status::Ok;
}
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/LinkQueue.hpp
|
C++
|
unknown
| 2,367
|
#ifndef MASTER_QUEUE_HPP
#define MASTER_QUEUE_HPP
#include "../Base/BaseData.hpp"
using namespace base;
template<typename TQueue, typename TElemType>
class MasterQueue {
public:
virtual ~MasterQueue() = default;
virtual Status initQueue(TQueue &q) = 0;
virtual Status destoryQueue(TQueue &q) = 0;
virtual Status clearQueue(TQueue &q) = 0;
virtual bool queueEmpty(const TQueue &q) = 0;
virtual int queueLength(const TQueue &q) = 0;
virtual TElemType getHead(TQueue &q) = 0;
virtual Status enQueue(TQueue &q, TElemType e) = 0;
virtual Status deQueue(TQueue &q, TElemType &e) = 0;
virtual Status queueTraverse(const TQueue q) = 0;
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/MasterQueue.hpp
|
C++
|
unknown
| 683
|
#ifndef REAR_QUEUE_HPP
#define REAR_QUEUE_HPP
#include "LinkQueue.hpp"
#include <iostream>
#include <ostream>
typedef struct
{
QueuePtr rear;
} rearQueue;
class RearQueue : public LinkQueueC {
private:
rearQueue q;
public:
RearQueue()
{
initRearQueue();
}
Status initRearQueue()
{
q.rear = new QNode;
q.rear->next = q.rear;
return Status::Ok;
}
bool rearQueueEmpty()
{
return q.rear->next == q.rear;
}
Status enRearQueue(QElemType e)
{
QueuePtr s = new QNode;
s->data = e;
s->next = q.rear->next;
q.rear->next = s;
q.rear = s;
return Status::Ok;
}
Status deRearQueue(QElemType& e)
{
if (rearQueueEmpty()) {
std::cout << "RearQueue is empty, Failed!!!" << std::endl;
return Status::Err;
}
QueuePtr front = q.rear->next->next;
e = front->data;
q.rear->next->next = front->next;
if (front == q.rear) {
q.rear = q.rear->next;
}
delete front;
return Status::Ok;
}
Status clearRearQueue()
{
std::cout << "clear queue" << std::endl;
while (!rearQueueEmpty()) {
QElemType e;
deRearQueue(e);
}
return Status::Ok;
}
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/RearQueue.hpp
|
C++
|
unknown
| 1,358
|
#ifndef SQ_QUEUE_HPP
#define SQ_QUEUE_HPP
#include "MasterQueue.hpp"
#include <iostream>
#include <cstdlib>
typedef int QElemType;
typedef struct {
QElemType* base;
int front;
int rear;
} Queue;
class SqQueueC: public MasterQueue<Queue, QElemType> {
public:
Status initQueue(Queue& q) override
{
q.base = new QElemType[QueueMaxSize];
if (!q.base)
exit(0);
q.front = q.rear = 0;
return Status::Ok;
}
Status destoryQueue(Queue& q) override
{
if (!q.base)
return Status::Err;
delete[] q.base;
q.base = nullptr;
q.front = q.rear = 0;
return Status::Ok;
}
Status clearQueue(Queue& q) override
{
q.front = q.rear = 0;
return Status::Ok;
}
inline bool queueEmpty(const Queue& q) override
{
return q.front == q.rear ? true : false;
}
int queueLength(const Queue& q) override
{
return (q.rear - q.front + QueueMaxSize) % QueueMaxSize;
}
QElemType getHead(Queue& q) override
{
if (q.front != q.rear)
return q.base[q.front];
return {};
}
Status enQueue(Queue& q, QElemType e) override
{
if ((q.rear + 1) % QueueMaxSize == q.front)
return Status::Err;
q.base[q.rear] = e;
q.rear = (q.rear + 1) % QueueMaxSize;
return Status::Ok;
}
Status deQueue(Queue& q, QElemType& e) override
{
if (q.front == q.rear)
return Status::Err;
e = q.base[q.front];
q.front = (q.front + 1) % QueueMaxSize;
return Status::Ok;
}
Status queueTraverse(const Queue q) override
{
if (q.base == nullptr) {
return Status::Err;
}
for (int i = q.front; i != q.rear; i = (i+1)%QueueMaxSize){
std::cout << q.base[i] << std::endl;
}
return Status::Ok;
}
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/SqQueue.hpp
|
C++
|
unknown
| 1,968
|
#ifndef TAG_QUEUE_HPP
#define TAG_QUEUE_HPP
#include "SqQueue.hpp"
class TagQueue : public SqQueueC {
public:
TagQueue() {
initQueue(q);
tag = 0;
}
bool isEmpty() {
return queueEmpty(q) && tag == 0;
}
bool isFull() {
return queueEmpty(q) && tag == 1;
}
Status enTagQueue(QElemType e) {
if (isFull()) {
std::cout << "queue is full!" << std::endl;
return Status::Err;
}
enQueue(q, e);
if (q.rear == q.front) {
tag = 1;
}
return Status::Ok;
}
Status deTagQueue(QElemType& e) {
if (isEmpty()) {
std::cout << "queue is empty" << std::endl;
return Status::Err;
}
deQueue(q, e);
if (q.front == q.rear) {
tag = 0;
}
return Status::Ok;
}
private:
Queue q;
int tag;
};
#endif
|
2301_82205515/CppDataLearn
|
Queue/TagQueue.hpp
|
C++
|
unknown
| 933
|
#ifndef LINK_STACK_HPP
#define LINK_STACK_HPP
#include "MasterStack.hpp"
#include "SqStack.hpp"
typedef int ElemType;
typedef struct StackNode{
ElemType data;
struct StackNode *next;
} StackNode, *LinkStack;
class LinkStackC : public MasterStack<LinkStack, ElemType>{
public:
};
#endif
|
2301_82205515/CppDataLearn
|
Stack/LinkStack.hpp
|
C++
|
unknown
| 305
|
#ifndef MASTER_STACK_HPP
#define MASTER_STACK_HPP
#include "../Base/BaseData.hpp"
using namespace base;
template <typename TStack, typename TElemType>
class MasterStack {
public:
virtual ~MasterStack() = default;
virtual Status initStack(TStack &s) = 0;
virtual Status destoryStack(TStack &s) = 0;
virtual Status clearStack(TStack &s) = 0;
virtual bool stackEmpty(const TStack s) = 0;
virtual int stackLength(const TStack s) = 0;
virtual TElemType getTop(const TStack s) = 0;
virtual Status push(TStack &s, TElemType e) = 0;
virtual Status pop(TStack &s, TElemType &e) = 0;
virtual Status StackTraverse(TStack s) = 0;
};
#endif
|
2301_82205515/CppDataLearn
|
Stack/MasterStack.hpp
|
C++
|
unknown
| 677
|
#ifndef SQ_STACK_HPP
#define SQ_STACK_HPP
#include "MasterStack.hpp"
typedef int ElemType;
typedef struct {
ElemType* base;
ElemType* top;
int stacksize;
} SqStack;
class SqStackC : public MasterStack<SqStack, ElemType> {
public:
};
#endif
|
2301_82205515/CppDataLearn
|
Stack/SqStack.hpp
|
C++
|
unknown
| 257
|
#ifndef H_STRING_HPP
#define H_STRING_HPP
#include "MasterString.hpp"
#define MAXSIZE 255
typedef struct {
char* ch;
int length;
}HString;
class HStringC : public MasterString<HString>{
public:
};
#endif
|
2301_82205515/CppDataLearn
|
String/HString.hpp
|
C++
|
unknown
| 219
|
#ifndef L_STRING_HPP
#define L_STRING_HPP
#include "MasterString.hpp"
using namespace base;
typedef struct Chunk {
char ch[StringMaxSize];
struct Chunk *next;
} Chunk;
typedef struct {
Chunk *head, *tail;
int length;
}LString;
class LStringC : public MasterString<LString> {
public:
};
#endif
|
2301_82205515/CppDataLearn
|
String/LString.hpp
|
C++
|
unknown
| 315
|
#ifndef MASTER_STRING_HPP
#define MASTER_STRING_HPP
#include "../Base/BaseData.hpp"
using namespace base;
template <typename TString>
class MasterString {
public:
enum CompareE {
Less = -1,
Equal = 0,
More = 1,
};
virtual ~MasterString() = default;
virtual Status strAssign(TString& t, const char* chars) = 0;
virtual Status strCopy(TString& t, const TString s) = 0;
virtual bool strEmpty(const TString s) = 0;
virtual CompareE strCompare(const TString s, const TString t) = 0;
virtual int strLength(const TString s) = 0;
virtual Status clearString(TString& s) = 0;
virtual Status concat(TString& s, const TString s1, const TString s2) = 0;
virtual Status subString(TString& sub, const TString s, int pos,int len) = 0;
virtual int index(const TString s, const TString t, int pos) = 0;
virtual Status replace(TString& s, TString t, TString v) = 0;
virtual Status strInsert(TString& s, int pos, TString t) = 0;
virtual Status strDelete(TString& s, int pos, int len) = 0;
virtual Status destoryString(TString& s) = 0;
};
#endif
|
2301_82205515/CppDataLearn
|
String/MasterString.hpp
|
C++
|
unknown
| 1,119
|
#ifndef S_STRING_HPP
#define S_STRING_HPP
#include "MasterString.hpp"
#include <cstring>
#define MAXSIZE 255
typedef struct {
char ch[MAXSIZE + 1];
int length;
} SString;
class SStringC : public MasterString<SString> {
protected:
public:
Status strAssign(SString& t, const char* chars) override
{
if (!chars)
return Status::Err;
int len = strlen(chars);
if (len == 0) {
t.ch[0] = '\0';
t.length = 0;
return Status::Ok;
}
if (len > StringMaxSize)
return Status::Err;
strcpy(t.ch, chars);
t.length = len;
return Status::Ok;
}
Status strCopy(SString& t, SString s) override
{
return strAssign(t, s.ch);
}
inline bool strEmpty(const SString s) override
{
return s.length == 0;
}
CompareE strCompare(const SString s, const SString t) override
{
int result = strcmp(s.ch, t.ch);
if (result < 0)
return CompareE::Less;
else if (result > 0)
return CompareE::More;
else
return CompareE::Equal;
}
inline int strLength(const SString s) override
{
return s.length;
}
Status clearString(SString& s) override
{
s.ch[0] = '\0';
s.length = 0;
return Status::Ok;
}
Status concat(SString& s, const SString s1, const SString s2) override
{
int len1 = s1.length;
int len2 = s2.length;
if (len1 + len2 + 1 > StringMaxSize)
return Status::Err;
if (len1 + len2 == 0) {
s.ch[0] = '\0';
s.length = 0;
return Status::Ok;
}
if (len1 > 0)
strcpy(s.ch, s1.ch);
if (len2 > 0)
strcpy(s.ch + len1, s2.ch);
s.length = len1 + len2;
return Status::Ok;
}
Status subString(SString& sub, const SString s, int pos, int len) override
{
if (pos < 1 || pos > s.length || len < 0 || len > s.length - pos + 1)
return Status::Err;
if (len == 0) {
sub.ch[0] = '\0';
sub.length = 0;
return Status::Ok;
}
strncpy(sub.ch, s.ch + pos - 1, len);
sub.ch[len] = '\0';
sub.length = len;
return Status::Ok;
}
int index(const SString s, const SString t, int pos) override
{
int i = pos, j = 1;
while (i <= s.length && j <= t.length) {
if (s.ch[i] == t.ch[j]) {
++i;
++j;
} else {
i = i - j + 2;
j = 1;
}
}
if (j > t.length)
return i - t.length;
else
return 0;
}
int index_kmp(const SString s, const SString t, int pos)
{
int i = pos, j = 1;
while (i <= s.length && j <= t.length) {
if (j == 0 || s.ch[i] == t.ch[j]) {
++i;
++j;
} else {
}
}
return 0;
}
Status replace(SString& s, SString t, SString v) override
{
return Status::Ok;
}
Status strInsert(SString& s, int pos, SString t) override
{
return Status::Ok;
}
Status strDelete(SString& s, int pos, int len) override
{
return Status::Ok;
}
Status destoryString(SString& s) override
{
return Status::Ok;
}
};
#endif
|
2301_82205515/CppDataLearn
|
String/SString.hpp
|
C++
|
unknown
| 3,504
|
#pragma once
#include "MasterBinaryTree.hpp"
#include <cctype>
#include <stack>
#include <vector>
typedef int ElemType;
typedef struct BiNode {
ElemType data;
struct BiNode *lchild, *rchild;
} BiNode, *BiTree;
class LinkBiTree : public MasterBinaryTree<BiTree, ElemType> {
public:
Status initBiTree(BiTree& t) override
{
t = nullptr;
return Status::Ok;
}
Status destoryBiTree(BiTree& t) override
{
if (t == nullptr)
return Status::Err;
std::stack<BiTree> nodeStack;
std::vector<BiTree> deleteList;
nodeStack.push(t);
while (!nodeStack.empty()) {
BiTree current = nodeStack.top();
nodeStack.pop();
deleteList.push_back(current);
if (current->lchild)
nodeStack.push(current->lchild);
if (current->rchild)
nodeStack.push(current->rchild);
}
for (auto it = deleteList.rbegin(); it != deleteList.rend(); ++it) {
delete *it;
}
t = nullptr;
return Status::Ok;
}
Status createBiTree(BiTree& t, const std::string& definition) override
{
static size_t pos = 0;
if (pos >= definition.size())
return Status::Err;
while (pos < definition.size() && std::isspace(definition[pos])) {
++pos;
}
if (pos >= definition.size())
return Status::Err;
if (definition[pos] == '#') {
++pos;
t = nullptr;
return Status::Ok;
}
int value = 0;
bool negative = false;
if (definition[pos] == '-') {
negative = true;
++pos;
}
while (pos < definition.size() && std::isdigit(definition[pos])) {
value = value * 10 + (definition[pos] - '0');
++pos;
}
if (negative) {
value = -value;
}
t = new BiNode;
t->data = value;
t->lchild = t->rchild = nullptr;
if (createBiTree(t->lchild, definition) != Status::Ok
|| createBiTree(t->rchild, definition) != Status::Ok) {
destoryBiTree(t);
return Status::Err;
}
return Status::Ok;
}
Status clearBiTree(BiTree& t) override
{
destoryBiTree(t);
return initBiTree(t);
}
bool biTreeEmpty(const BiTree t) override
{
return t == nullptr;
}
int biTreeDepth(const BiTree t) override
{
if (t == nullptr)
return Status::Err;
int left = biTreeDepth(t->lchild);
int right = biTreeDepth(t->rchild);
return (left > right ? left : right) + 1;
}
BiTree root(const BiTree t) override
{
return t;
}
ElemType value(const BiTree t, ElemType e) override{
}
};
|
2301_82205515/CppDataLearn
|
Tree/LinkBiTree.hpp
|
C++
|
unknown
| 2,890
|
#pragma once
#include "../Base/BaseData.hpp"
using namespace base;
template <typename TTree, typename TElemType>
class MasterBinaryTree {
public:
virtual ~MasterBinaryTree() = default;
virtual Status initBiTree(TTree& t) = 0;
virtual Status destoryBiTree(TTree& t) = 0;
virtual Status createBiTree(TTree& t, const std::string& definition) = 0;
virtual Status clearBiTree(TTree& t) = 0;
virtual bool biTreeEmpty(const TTree t) = 0;
virtual int biTreeDepth(const TTree t) = 0;
virtual TTree root(const TTree t) = 0;
virtual TElemType value(const TTree t, TElemType e) = 0;
virtual Status assign(const TTree t, TElemType& e, TElemType value) = 0;
virtual Status parent(const TTree t, TElemType e) = 0;
virtual Status leftChild(const TTree t, TElemType e) = 0;
virtual Status rightChild(const TTree t, TElemType e) = 0;
virtual Status leftSibling(const TTree t, TElemType e) = 0;
virtual Status rightSibling(const TTree t, TElemType e) = 0;
virtual Status insertChild(TTree& t) = 0;
virtual Status deleteChild(TTree& t) = 0;
virtual Status preOrderTraverse(const TTree t) = 0;
virtual Status inOrderTraverse(const TTree t) = 0;
virtual Status postOrderTraverse(const TTree t) = 0;
virtual Status levelOrderTraverse(const TTree t) = 0;
};
|
2301_82205515/CppDataLearn
|
Tree/MasterBinaryTree.hpp
|
C++
|
unknown
| 1,322
|
#pragma once
#include "MasterBinaryTree.hpp"
typedef int ElemType ;
typedef ElemType SqBiTree[TreeMaxSize];
|
2301_82205515/CppDataLearn
|
Tree/SqBiTree.hpp
|
C++
|
unknown
| 112
|
#include "../Queue/Deque.hpp"
#include "../LinkList.hpp"
#include "../Queue/LinkQueue.hpp"
#include "../Queue/RearQueue.hpp"
#include "../Queue/TagQueue.hpp"
#include <iostream>
using namespace std;
void hw4_1()
{
RearQueue rq;
cout << "队列是否为空?" << (rq.rearQueueEmpty() ? "是" : "否") << endl;
rq.enRearQueue(10);
rq.enRearQueue(20);
rq.enRearQueue(30);
cout << "队列是否为空?" << (rq.rearQueueEmpty() ? "是" : "否") << endl;
QElemType e;
rq.deRearQueue(e);
cout << "出队元素: " << e << endl;
cout << "队列是否为空?" << (rq.rearQueueEmpty() ? "是" : "否") << endl;
rq.clearRearQueue();
cout << "队列是否为空?" << (rq.rearQueueEmpty() ? "是" : "否") << endl;
}
void hw4_2()
{
TagQueue tq;
cout << "入队元素: ";
for (int i = 0; i < 100; i++) {
if (tq.enTagQueue(i) == tq.Status::Ok) {
cout << i << " ";
}
}
cout << endl;
if (!tq.enTagQueue(101)) {
cout << "队列已满,入队操作失败!" << endl;
}
cout << "出队元素: ";
QElemType e;
while (!tq.isEmpty()) {
if (tq.deTagQueue(e) == tq.Status::Ok) {
cout << e << " ";
}
}
cout << endl;
if (tq.deTagQueue(e) == tq.Status::Err)
cout << "队列为空,出队操作失败" << endl;
}
void hw4_3()
{
Deque dq;
dq.enRear(10);
dq.enRear(20);
dq.enFront(5);
QElemType e;
dq.deRear(e);
cout << "队列尾部出列元素为: " << e << endl;
dq.deFront(e);
cout << "队列头部出列元素为: " << e << endl;
}
void hw4_4()
{
LinkList ll(3);
ll.addNode(5);
ll.addNode(2);
ll.addNode(8);
cout << "最大值: " << ll.Max() << endl;
cout << "元素数量: " << ll.Count() << endl;
cout << "平均值: " << ll.Average() << endl;
}
int main()
{
hw4_4();
return 0;
}
|
2301_82205515/CppDataLearn
|
example/hw4.cpp
|
C++
|
unknown
| 1,923
|
#include "../String/SString.hpp"
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
void question1()
{
SStringC proceesor;
SString str;
proceesor.strAssign(str, "2468_WE_ARE_APPRECIATE_BBNO$");
int values[36] = { 0 };
char* temp = str.ch;
while (*temp != '\0') {
if (*temp >= 'A' && *temp <= 'Z') {
values[(*temp) - 'A']++;
} else if (*temp >= '0' && *temp <= '9') {
values[(*temp) - '0' + 26]++;
}
temp++;
}
ofstream file("question1.txt");
if (!file.is_open()) {
cerr << "打开文件失败!" << endl;
return;
}
for (int i = 0; i < 26; ++i) {
if (values[i] > 0) {
file << char('A' + i) << ": " << values[i] << endl;
}
}
for (int i = 0; i < 10; ++i) {
if (values[i + 26] > 0)
file << char('0' + i) << ": " << values[i + 26] << endl;
}
file.close();
cout << "文件保存成功!" << endl;
}
void question2Reversed(char* s, int left, int right);
void question2()
{
SString str;
SStringC proceesor;
proceesor.strAssign(str, "ABCDefGhiJK");
cout << "原始字符串: " << str.ch << endl;
question2Reversed(str.ch, 0, str.length - 1);
cout << "逆序字符串:" << str.ch << endl;
}
void question2Reversed(char* s, int left, int right)
{
if (left >= right)
return;
char temp = s[left];
s[left] = s[right];
s[right] = temp;
question2Reversed(s, left + 1, right - 1);
}
void question3_insert(char* s, char* t, int pos)
{
int s_len = 0, t_len = 0;
char *p = s, *q = t;
while (*p != '\0'){
s_len++;
p++;
}
while (*q != '\0'){
t_len++;
q++;
}
for (int i=s_len; i>=pos; i--) {
s[i+t_len] = s[i];
}
for (int j=0; j<t_len;j++){
s[pos+j] = t[j];
}
}
void question3()
{
SString s;
SString t;
SStringC proceesor;
proceesor.strAssign(s, "ISpeed");
proceesor.strAssign(t, "Show");
cout << "原始字符串s: " << s.ch << " | 长度: " << s.length << endl;
cout << "原始字符串t: " << t.ch << " | 长度: " << t.length << endl;
int pos = 1;
if (pos < 0 || pos > s.length)
return;
question3_insert(s.ch, t.ch, 1);
cout << "插入后字符串s: " << s.ch << " | 长度: " << strlen(s.ch) << endl;
}
int main()
{
question3();
return 0;
}
|
2301_82205515/CppDataLearn
|
example/hw5.cpp
|
C++
|
unknown
| 2,477
|
#include <cctype>
#include <iostream>
#include <stack>
using namespace std;
typedef struct BiNode {
char data;
struct BiNode *lchild, *rchild;
} BiNode, *BiTree;
bool In(char ch);
char GetTop(stack<char> s);
int Precede(char op1, char op2);
void CreateExpTree(BiTree& T, BiTree a, BiTree b, char theta);
int GetValue(char op, int l, int r);
void InitExpTree(BiTree& T)
{
char ch;
stack<BiTree> EXPT;
stack<char> OPTR;
OPTR.push('#');
cin >> ch;
while (ch != '#' || GetTop(OPTR) != '#') {
if (!In(ch)) {
BiTree leaf = new BiNode;
leaf->data = ch;
leaf->lchild = leaf->rchild = nullptr;
EXPT.push(leaf);
cin >> ch;
} else {
switch (Precede(GetTop(OPTR), ch)) {
case '<':
OPTR.push(ch);
cin >> ch;
break;
case '>': {
char theta = OPTR.top();
OPTR.pop();
BiTree b = EXPT.top();
EXPT.pop();
BiTree a = EXPT.top();
EXPT.pop();
BiTree node = new BiNode;
node->data = theta;
node->lchild = a;
node->rchild = b;
EXPT.push(node);
break;
}
case '=':
OPTR.pop();
cin >> ch;
break;
}
}
}
T = EXPT.top();
}
int EvaluateExpTree(BiTree t)
{
if (t->lchild == nullptr && t->rchild == nullptr) {
return t->data - '0';
}
int lvalue = EvaluateExpTree(t->lchild);
int rvalue = EvaluateExpTree(t->rchild);
return GetValue(t->data, lvalue, rvalue);
}
bool In(char ch)
{
return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')' || ch == '#';
}
char GetTop(stack<char> s)
{
if (s.empty())
return '#';
return s.top();
}
int Precede(char op1, char op2)
{
const char priority[7][7] = {
// + - * / ( ) #
{ '>', '>', '<', '<', '<', '>', '>' }, // +
{ '>', '>', '<', '<', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '<', '<', '<', '<', '<', '=', ' ' },
{ '>', '>', '>', '>', ' ', '>', '>' },
{ '<', '<', '<', '<', '<', ' ', '=' }
};
int i, j;
switch (op1) {
case '+':
i = 0;
break;
case '-':
i = 1;
break;
case '*':
i = 2;
break;
case '/':
i = 3;
break;
case '(':
i = 4;
break;
case ')':
i = 5;
break;
case '#':
i = 6;
break;
}
switch (op2) {
case '+':
j = 0;
break;
case '-':
j = 1;
break;
case '*':
j = 2;
break;
case '/':
j = 3;
break;
case '(':
j = 4;
break;
case ')':
j = 5;
break;
case '#':
j = 6;
break;
}
return priority[i][j];
}
void CreateExpTree(BiTree& T, BiTree a, BiTree b, char theta)
{
T = new BiNode;
T->data = theta;
T->lchild = a;
T->rchild = b;
}
int GetValue(char op, int l, int r)
{
switch (op) {
case '+':
return l + r;
case '-':
return l - r;
case '*':
return l * r;
case '/':
return l / r;
default:
return 0;
}
}
int main()
{
BiTree T;
cout << "输入表达式(以#结束,如:3*(7-2)#): ";
InitExpTree(T);
cout << "表达式结果: " << EvaluateExpTree(T) << endl;
return 0;
}
|
2301_82205515/CppDataLearn
|
example/st4_22.cpp
|
C++
|
unknown
| 3,711
|
<script>
export default {
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}
</script>
<style>
/*每个页面公共css */
</style>
|
2301_82115348/VendingMachine_1023
|
App.vue
|
Vue
|
unknown
| 254
|
function formatMsg(tag, msg){
const time = new Date().toLocaleTimeString();
return `${tag}${time}${msg}`;
}
export default{
info(tag, msg){
console.log(`[INFO] ${formatMsg(tag,msg)}`);
},
error(tag,msg){
console.error(`[ERROR] ${formatMsg(tag,msg)}`);
}
}
|
2301_82115348/VendingMachine_1023
|
components/log/log.js
|
JavaScript
|
unknown
| 268
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
|
2301_82115348/VendingMachine_1023
|
index.html
|
HTML
|
unknown
| 675
|
import App from './App'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import log from "./components/log/log.js"
import constant from './models/constant'
export function createApp() {
const app = createSSRApp(App)
app.config.globalProperties.$log = log
app.config.globalProperties.constant = constant
return {
app
}
}
// #endif
|
2301_82115348/VendingMachine_1023
|
main.js
|
JavaScript
|
unknown
| 527
|
export default {
BASE_URL: "https://vending.neumooc.com/prod-api/",
MACHINE_NO: "49f4b29ccfcb4207a35e73327f7cb0b2"
}
|
2301_82115348/VendingMachine_1023
|
models/constant.js
|
JavaScript
|
unknown
| 118
|
export default class Product {
constructor(id, name, price, imageUrl, stock) {
this.id = id;
this.name = name;
this.price = price;
this.imageUrl = imageUrl;
this.stock = stock;
}
}
|
2301_82115348/VendingMachine_1023
|
models/product.js
|
JavaScript
|
unknown
| 192
|