Skip to content

Commit

Permalink
提交
Browse files Browse the repository at this point in the history
  • Loading branch information
cgf120 committed Oct 21, 2024
1 parent 1f67ff7 commit 333ce92
Show file tree
Hide file tree
Showing 8 changed files with 4,324 additions and 18 deletions.
1 change: 0 additions & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 14 additions & 9 deletions pod-cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import zipfile

from const.app_config import PodConfig, get_app_type_by_identity_key, CIVIAI_API_KEY
from utils.util import clone_and_checkout, download_file, path_cover, query_cache_path
from utils.util import clone_and_checkout, download_file, path_cover, query_cache_path, link_file

logging.basicConfig(filename='pod-cloud.log',
level=logging.INFO,
Expand Down Expand Up @@ -35,25 +35,33 @@ def load_pod_from_json(file_path: str) -> PodConfig:
for plugin in pod_config.plugins:
print(f'插件:{plugin.name}')
clone_and_checkout(plugin.remote_url,plugin.commit_log,plugins_dir)

# 安装依赖
print(f'安装依赖')
for package in pod_config.packages:
print(f'安装依赖:{package.name}')
if package.name is not None and package.version is not None and str.startswith(package.name,'jupyter'):
os.system(f'{pod_config.python} -m pip install {package.name}=={package.version}')

# 处理模型,缓存不存在,C站存在就下载,缓存存在就用缓存做软连接,其他的就用客户上传的模型做软连接
print(f'模型预处理,模型目录:{os.path.join(cloud_app_dir,app_config_val.model_dir)}')
for model in pod_config.models:
# 模型默认路径是客户上传的模型
model_file = os.path.join(base_dir,path_cover(model.file_path[0],pod_config.app_dir))
model_file = os.path.join(base_dir,"models",model.file_path[0])
# C站缓存在客户端处理的时候已经添加到模型管理了,在这里只需要查询下缓存文件路径即可
if model.cache_path is None and model.download_url is not None:
model.cache_path = query_cache_path(model.sha256)
# 如果缓存存在就使用缓存文件
if model.cache_path is not None:
os.symlink(model.cache_path,model_file)
link_file(model.cache_path,model_file)
model_file = model.cache_path
#处理软连接
if len(model.file_path) > 1:
print(f'缓存模型:{model.cache_path}')
for i in range(1,len(model.file_path)):
target_model_file = os.path.join(base_dir,path_cover(model.file_path[i],pod_config.app_dir))
target_model_file = os.path.join(base_dir,"models",model.file_path[i])
print(f'重复模型,软连接:{model_file}->{target_model_file}')
os.symlink(model_file,target_model_file)
link_file(model_file,target_model_file)
# print(f'模型预处理完成')
print(f'模型映射:把/poddata下的模型及软连接,再次软连接到应用目录下')
for root_dir, dirs, files in os.walk(os.path.join(base_dir,app_config_val.model_dir)):
Expand All @@ -65,8 +73,5 @@ def load_pod_from_json(file_path: str) -> PodConfig:
print(os.path.join(root_dir, file))
source_file = os.path.join(root_dir,file)
target_file = os.path.join(cloud_app_dir,os.path.relpath(source_file,base_dir))
dest_dir = os.path.dirname(target_file)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir, exist_ok=True)
print(f'软连接:{source_file}->{target_file}')
os.symlink(source_file,target_file)
link_file(source_file,target_file)
1 change: 0 additions & 1 deletion pod_client/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ def load_models(self):
file_list = []
for root_dir, dirs, files in os.walk(self.model_dir.get()):
for file in files:

file_list.append(os.path.join(root_dir, file))
self.log_text.insert("1.0", f"【提示】模型目录:{self.model_dir.get()},共需要处理模型{len(file_list)}\n")
for index, model_path in enumerate(file_list):
Expand Down
192 changes: 192 additions & 0 deletions pod_client_cmd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import argparse
import os.path
import subprocess
import json
import time
import zipfile
import datetime

from const.app_config import PodConfig, Model, Plugin, PythonPackage
from utils.util import calculate_sha256, civitai_query_model, query_cache_path, add_models, get_git_repo_info, \
parse_python_packages



pod_config = PodConfig(
app_dir="",
app_type="",
model_dir="",
plugin_dir="",
python="",
python_version="",
models=list(),
plugins=list(),
packages=list(),
)

def reset_timestamp_if_needed(file_path):
"""
Resets the file's timestamp to a date after 1980 if it's older.
"""
stat = os.stat(file_path)
if stat.st_mtime <= time.mktime(datetime.datetime(2000, 1, 1).timetuple()):
os.utime(file_path, (time.time(), time.time())) # Update to current time



def load_python_info(python_executable):
"""执行python --version 获取python版本"""
python_version = subprocess.run([python_executable, '--version'], stdout=subprocess.PIPE, text=True).stdout.strip()
return python_version

# 加载模型
def load_models():
file_list = []
for root_dir, dirs, files in os.walk(pod_config.model_dir):
for file in files:
file_list.append(os.path.join(root_dir, file))
print( f"共需要处理模型{len(file_list)}个")
models = {}
for index, model_path in enumerate(file_list):
model_name = os.path.basename(model_path)
print(f"【提示】处理模型[{index + 1}/{len(file_list)}]:{model_path}")
sha256 = calculate_sha256(model_path)
model_id, download_url = civitai_query_model(sha256)
cache_path = query_cache_path(sha256)
if cache_path is None and download_url is not None:
# 云端不存在,C站存在,添加到云端
add_models(sha256)
model_relpath = os.path.relpath(model_path, pod_config.model_dir)

if sha256 not in models:
models[sha256] = Model(model_name=model_name, model_id=model_id, sha256=sha256, cache_path=cache_path, file_path = [model_relpath], download_url= download_url)
else:
print(f"【警告】重复模型:{model_name},只记录路径,后续做映射\n")
models[sha256].file_path.append(model_relpath)
print(f"【提示】模型信息[{index + 1}/{len(file_list)}]:{models.get(sha256)}\n")
pod_config.models = list(models.values())

def load_plugins():
items = os.listdir(pod_config.plugin_dir)
repo_dirs = [d for d in items if os.path.isdir(os.path.join(pod_config.plugin_dir, d))]
print(f"【提示】插件目录:{pod_config.plugin_dir},共需要处理插件{len(repo_dirs)}个")
for index, repo_dir in enumerate(repo_dirs):
repo_path = os.path.join(pod_config.plugin_dir, repo_dir)
print( f"【提示】处理插件[{index + 1}/{len(repo_dirs)}]:{repo_path}")
name, remote_url, commit_log = get_git_repo_info(repo_path)
plugin = Plugin(name=name, remote_url=remote_url, commit_log=commit_log)
pod_config.plugins.append(plugin)
print(f"【提示】插件信息[{index + 1}/{len(repo_dirs)}]:{plugin}")

def load_python_packages():
result = subprocess.check_output([pod_config.python, "-m", "pip", "freeze"], text=True).strip()
packages = result.strip().split("\n")
print(f"【提示】Python包数量:{len(packages)}\n")
for index, line in enumerate(packages):
print( f"【提示】Python包[{index + 1}/{len(packages)}]:{line}\n")
name, version, remote_url, package_type, err = parse_python_packages(line)
if err is not None:
print(f"【警告】Python包解析失败:{err},忽略\n")
continue
package = PythonPackage(name=name, version=version, remote_url=remote_url, type=package_type,full_text=line)
print(f"【提示】Python包信息[{index + 1}/{len(packages)}]:{package}\n")
pod_config.packages.append(package)

def package_zip():
pod_config_file = os.path.join(pod_config.app_dir, "pod_config.json")
with open(pod_config_file, "w") as f:
json.dump(pod_config.model_dump(), f, indent=4) #

pod_zip_file = os.path.join(pod_config.app_dir, "pod_config.zip")
with zipfile.ZipFile(pod_zip_file, "w") as z:
z.write(pod_config_file, "pod_config.json")
for model in pod_config.models:
if model.cache_path is not None:
print(f"【提示】模型{model.model_name}云端已存在,忽略打包\n")
elif model.download_url is not None:
print(f"【警告】模型{model.model_name}C站已存在,忽略打包\n")
else:
file_path = os.path.join(pod_config.model_dir, model.file_path[0])
# 获取file_path 相对于model_dir的相对路径
relative_path = os.path.relpath(file_path, pod_config.model_dir)
reset_timestamp_if_needed(file_path)
z.write(file_path, f"models/{relative_path}")
print(f"【提示】模型{model.model_name}打包完成\n")


def init(app_dir, python):
if not os.path.exists(app_dir):
raise Exception(f"应用目录不存在:{app_dir}")
pod_config.app_dir = app_dir
print(f"应用目录:{pod_config.app_dir}")

# 模型目录
model_dir = os.path.join(app_dir, "models")
if not os.path.exists(model_dir):
raise Exception(f"模型目录不存在:{model_dir}")
pod_config.model_dir = model_dir
print(f"模型目录:{pod_config.model_dir}")

# 插件目录
plugins_dir = os.path.join(app_dir, "custom_nodes")
if not os.path.exists(plugins_dir):
raise Exception(f"插件目录不存在:{plugins_dir}")
pod_config.plugin_dir = plugins_dir
print(f"插件目录:{pod_config.plugin_dir}")

# python环境目录
if not python:
python = "python"
python_version = load_python_info(python)
if python_version is None:
raise Exception(f"获取python版本失败:{python}")
pod_config.python = python
print(f"python环境:{pod_config.python}")

if __name__ == "__main__":
parser = argparse.ArgumentParser(description='仙宫云ComfyUI数据采集。')
# 添加命令行参数
parser.add_argument('--app_dir', help='应用目录。',required=True)
parser.add_argument('--python', help='python执行程序,比如 /usr/bin/python,默认 python。')
parser.add_argument('--pod_config', help='根据配置文件读取。')
args = parser.parse_args()
# 应用目录
app_dir = args.app_dir
python = args.python
config = args.pod_config
if config is None:
# 初始化
print("初始化...")
init(app_dir, python)
print("初始化完成")

print("加载模型...")
load_models()
print("加载模型完成")

print("加载插件...")
load_plugins()
print("加载插件完成")

print("加载python包...")
load_python_packages()
print("加载python包完成")
else:
with open(config, "r") as f:
data= json.load(f)
pod_config = PodConfig(**data)
print(pod_config.app_dir)
# 打包
print("打包...")
print()
package_zip()
print("打包完成")









Loading

0 comments on commit 333ce92

Please sign in to comment.