Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edd0303f59 | ||
|
|
be6f47a333 | ||
|
|
4cd6a072ca | ||
|
|
743a82efe9 | ||
|
|
9589f28ef7 | ||
|
|
35492c5671 | ||
|
|
db1e695bf3 | ||
|
|
ecc4aec43b | ||
|
|
fc063c2205 | ||
|
|
4d60ce138a | ||
|
|
2afd24f6e4 | ||
|
|
437acd023a | ||
|
|
b00523ae14 | ||
|
|
4405a74993 | ||
|
|
cb16090868 | ||
|
|
396e510dce | ||
|
|
3b9790b969 | ||
|
|
a35d07a7ac | ||
|
|
6d004c61fc | ||
|
|
ffdd06da1b | ||
|
|
f03f34cacb | ||
|
|
0c86ea849e | ||
|
|
0efa4c38c0 | ||
|
|
6092ab7793 | ||
|
|
929def87eb | ||
|
|
be074ccff7 | ||
|
|
3445199393 |
@@ -6,13 +6,18 @@
|
||||
|
||||
##### `最新`:
|
||||
|
||||
- App模式增加batch prompt,批量提示词,可以把动态提示词批量组成后运行
|
||||
|
||||

|
||||
|
||||
- 增加 SiliconflowLLM,可以使用由Siliconflow提供的免费LLM
|
||||
|
||||
- 增加 Edit Mask,方便在生成的时候手动绘制 mask [workflow](./workflow/edit-mask-workflow.json)
|
||||
|
||||
<!-- - ChatGPT 节点支持 Local LLM(llama.cpp),Phi3、llama3 都可以直接一个节点运行了。模型下载后,放置到 `models/llamafile/` -->
|
||||
|
||||
- ChatGPT 节点支持 Local LLM(llama.cpp),Phi3、llama3 都可以直接一个节点运行了。模型下载后,放置到 `models/llamafile/`
|
||||
|
||||
- 右键菜单支持 text-to-text,方便对 prompt 词补全
|
||||
|
||||
<!-- - 右键菜单支持 text-to-text,方便对 prompt 词补全 -->
|
||||
<!--
|
||||
强烈推荐:
|
||||
[Phi-3-mini-4k-instruct-function-calling-GGUF](https://huggingface.co/nold/Phi-3-mini-4k-instruct-function-calling-GGUF)
|
||||
|
||||
@@ -21,7 +26,7 @@
|
||||
- 右键菜单支持 image-to-text,使用多模态模型,多模态使用 [llava-phi-3-mini-gguf](https://huggingface.co/xtuner/llava-phi-3-mini-gguf/tree/main),注意需要把llava-phi-3-mini-mmproj-f16.gguf也下载
|
||||
|
||||

|
||||

|
||||
 -->
|
||||
|
||||
|
||||
#### `相关插件推荐`
|
||||
@@ -114,7 +119,7 @@ https://github.com/shadowcz007/comfyui-mixlab-nodes/assets/12645064/e7e77f90-e43
|
||||
|
||||
[workflow-5](./workflow/5-gpt-workflow.json)
|
||||
|
||||
最新:ChatGPT 节点支持 Local LLM(llama.cpp),Phi3、llama3 都可以直接一个节点运行了。
|
||||
<!-- 最新:ChatGPT 节点支持 Local LLM(llama.cpp),Phi3、llama3 都可以直接一个节点运行了。
|
||||
|
||||
Model download,move to :`models/llamafile/`
|
||||
|
||||
@@ -142,7 +147,7 @@ pip install 'llama-cpp-python[server]'
|
||||
```
|
||||
pip install llama-cpp-python \
|
||||
--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/metal
|
||||
```
|
||||
``` -->
|
||||
|
||||
## Prompt
|
||||
|
||||
|
||||
+283
-127
@@ -3,12 +3,14 @@ import os
|
||||
import subprocess
|
||||
import importlib.util
|
||||
import sys,json
|
||||
import urllib
|
||||
import execution
|
||||
import uuid
|
||||
import hashlib
|
||||
import datetime
|
||||
import folder_paths
|
||||
import logging
|
||||
import base64,io,re
|
||||
import random
|
||||
from PIL import Image
|
||||
from comfy.cli_args import args
|
||||
python = sys.executable
|
||||
@@ -24,12 +26,12 @@ llama_port=None
|
||||
llama_model=""
|
||||
llama_chat_format=""
|
||||
|
||||
try:
|
||||
from .nodes.ChatGPT import get_llama_models,get_llama_model_path,llama_cpp_client
|
||||
llama_cpp_client("")
|
||||
# try:
|
||||
# from .nodes.ChatGPT import get_llama_models,get_llama_model_path,llama_cpp_client
|
||||
# llama_cpp_client("")
|
||||
|
||||
except:
|
||||
print("##nodes.ChatGPT ImportError")
|
||||
# except:
|
||||
# print("##nodes.ChatGPT ImportError")
|
||||
|
||||
|
||||
from .nodes.RembgNode import get_rembg_models,U2NET_HOME,run_briarmbg,run_rembg
|
||||
@@ -171,8 +173,7 @@ def create_for_https():
|
||||
os.mkdir(https_key_path)
|
||||
if not os.path.exists(crt):
|
||||
create_key(key,crt)
|
||||
|
||||
print('https_key OK: ', crt,key)
|
||||
# print('https_key OK: ', crt,key)
|
||||
return (crt,key)
|
||||
|
||||
|
||||
@@ -309,9 +310,10 @@ def get_my_workflow_for_app(filename="my_workflow_app.json",category="",is_all=F
|
||||
print('app_workflow_path: ',app_workflow_path)
|
||||
try:
|
||||
with open(app_workflow_path) as json_file:
|
||||
json_data=json.load(json_file)
|
||||
apps = [{
|
||||
'filename':filename,
|
||||
'data':json.load(json_file)
|
||||
'data':json_data
|
||||
}]
|
||||
except Exception as e:
|
||||
print("发生异常:", str(e))
|
||||
@@ -521,9 +523,17 @@ async def new_start(self, address, port, verbose=True, call_on_start=None):
|
||||
logging.info("\n")
|
||||
logging.info("\n\nStarting server")
|
||||
|
||||
import socket
|
||||
|
||||
hostname = socket.gethostname()
|
||||
ip_address = socket.gethostbyname(hostname)
|
||||
|
||||
# print(f"本机的IP地址是: {ip_address}")
|
||||
|
||||
|
||||
# print("\033[93mStarting server\n")
|
||||
logging.info("\033[93mTo see the GUI go to: http://{}:{}".format(address, http_port))
|
||||
logging.info("\033[93mTo see the GUI go to: https://{}:{}\033[0m".format(address, https_port))
|
||||
logging.info("\033[93mTo see the GUI go to: http://{}:{} or http://{}:{}".format(ip_address, http_port,address,http_port))
|
||||
logging.info("\033[93mTo see the GUI go to: https://{}:{} or https://{}:{}\033[0m".format(ip_address, https_port,address,https_port))
|
||||
|
||||
# print("\033[93mTo see the GUI go to: http://{}:{}".format(address, http_port))
|
||||
# print("\033[93mTo see the GUI go to: https://{}:{}\033[0m".format(address, https_port))
|
||||
@@ -608,13 +618,34 @@ async def mixlab_workflow_hander(request):
|
||||
category=data['category']
|
||||
if 'admin' in data:
|
||||
admin=data['admin']
|
||||
|
||||
ds=get_my_workflow_for_app(filename,category,admin)
|
||||
data=[]
|
||||
for json_data in ds:
|
||||
# 不传给前端
|
||||
if 'output' in json_data['data']:
|
||||
del json_data['data']['output']
|
||||
if 'workflow' in json_data['data']:
|
||||
del json_data['data']['workflow']
|
||||
data.append(json_data)
|
||||
|
||||
result={
|
||||
'data':get_my_workflow_for_app(filename,category,admin),
|
||||
'data':data,
|
||||
'status':'success',
|
||||
}
|
||||
elif data['task']=='list':
|
||||
ds=get_workflows()
|
||||
data=[]
|
||||
for json_data in ds:
|
||||
# 不传给前端
|
||||
if 'output' in json_data['data']:
|
||||
del json_data['data']['output']
|
||||
if 'workflow' in json_data['data']:
|
||||
del json_data['data']['workflow']
|
||||
data.append(json_data)
|
||||
|
||||
result={
|
||||
'data':get_workflows(),
|
||||
'data':data,
|
||||
'status':'success',
|
||||
}
|
||||
except Exception as e:
|
||||
@@ -648,11 +679,11 @@ async def get_checkpoints(request):
|
||||
except Exception as e:
|
||||
print('/mixlab/folder_paths',False,e)
|
||||
|
||||
try:
|
||||
if data['type']=='llamafile':
|
||||
names=get_llama_models()
|
||||
except:
|
||||
print("llamafile none")
|
||||
# try:
|
||||
# if data['type']=='llamafile':
|
||||
# names=get_llama_models()
|
||||
# except:
|
||||
# print("llamafile none")
|
||||
|
||||
try:
|
||||
if data['type']=='rembg':
|
||||
@@ -699,135 +730,258 @@ async def rembg_hander(request):
|
||||
|
||||
return web.json_response(result)
|
||||
|
||||
|
||||
@routes.post("/mixlab/prompt_result")
|
||||
async def post_prompt_result(request):
|
||||
data = await request.json()
|
||||
res=None
|
||||
# print(data)
|
||||
try:
|
||||
action=data['action']
|
||||
if action=='save':
|
||||
result=data['data']
|
||||
res=save_prompt_result(result['prompt_id'],result)
|
||||
elif action=='all':
|
||||
res=get_prompt_result()
|
||||
except Exception as e:
|
||||
print('/mixlab/prompt_result',False,e)
|
||||
# 保存运行结果?暂时去掉
|
||||
# @routes.post("/mixlab/prompt_result")
|
||||
# async def post_prompt_result(request):
|
||||
# data = await request.json()
|
||||
# res=None
|
||||
# # print(data)
|
||||
# try:
|
||||
# action=data['action']
|
||||
# if action=='save':
|
||||
# result=data['data']
|
||||
# res=save_prompt_result(result['prompt_id'],result)
|
||||
# elif action=='all':
|
||||
# res=get_prompt_result()
|
||||
# except Exception as e:
|
||||
# print('/mixlab/prompt_result',False,e)
|
||||
|
||||
return web.json_response({"result":res})
|
||||
# return web.json_response({"result":res})
|
||||
|
||||
# 种子设置
|
||||
def random_seed(seed, data):
|
||||
max_seed = 4294967295
|
||||
|
||||
async def start_local_llm(data):
|
||||
global llama_port,llama_model,llama_chat_format
|
||||
if llama_port and llama_model and llama_chat_format:
|
||||
return {"port":llama_port,"model":llama_model,"chat_format":llama_chat_format}
|
||||
|
||||
import threading
|
||||
import uvicorn
|
||||
from llama_cpp.server.app import create_app
|
||||
from llama_cpp.server.settings import (
|
||||
Settings,
|
||||
ServerSettings,
|
||||
ModelSettings,
|
||||
ConfigFileSettings,
|
||||
)
|
||||
for id, value in data.items():
|
||||
# print(seed,id)
|
||||
if 'seed' in value['inputs'] and not isinstance(value['inputs']['seed'], list) and seed[id] in ['increment', 'decrement', 'randomize']:
|
||||
value['inputs']['seed'] = round(random.random() * max_seed)
|
||||
|
||||
if 'noise_seed' in value['inputs'] and not isinstance(value['inputs']['noise_seed'], list) and seed[id] in ['increment', 'decrement', 'randomize']:
|
||||
value['inputs']['noise_seed'] = round(random.random() * max_seed)
|
||||
|
||||
if value.get('class_type') == "Seed_" and seed[id] in ['increment', 'decrement', 'randomize']:
|
||||
value['inputs']['seed'] = round(random.random() * max_seed)
|
||||
|
||||
print('new Seed', value)
|
||||
|
||||
if not "model" in data and "model_path" in data:
|
||||
data['model']= os.path.basename(data["model_path"])
|
||||
model=data["model_path"]
|
||||
|
||||
elif "model" in data:
|
||||
model=get_llama_model_path(data['model'])
|
||||
|
||||
n_gpu_layers=-1
|
||||
|
||||
if "n_gpu_layers" in data:
|
||||
n_gpu_layers=data['n_gpu_layers']
|
||||
return data
|
||||
|
||||
|
||||
chat_format="chatml"
|
||||
# 运行工作流,代替官方的prompt接口
|
||||
@routes.post("/mixlab/prompt")
|
||||
async def mixlab_post_prompt(request):
|
||||
p_intance=PromptServer.instance
|
||||
logging.info("got prompt")
|
||||
resp_code = 200
|
||||
out_string = ""
|
||||
json_data = await request.json()
|
||||
# json_data = p_intance.trigger_on_prompt(json_data)
|
||||
# filename,category, client_id ,input
|
||||
# workflow 的 filename,category
|
||||
|
||||
model_alias=os.path.basename(model)
|
||||
# 输入的参数
|
||||
input_data=json_data['input'] if "input" in json_data else []
|
||||
# 种子
|
||||
seed=json_data['seed'] if "seed" in json_data else {}
|
||||
|
||||
# 多模态
|
||||
clip_model_path=None
|
||||
apps=get_my_workflow_for_app(json_data['filename'],json_data['category'],False)
|
||||
|
||||
prefix = "llava-phi-3-mini"
|
||||
file_name = prefix+"-mmproj-"
|
||||
if model_alias.startswith(prefix):
|
||||
for file in os.listdir(os.path.dirname(model)):
|
||||
if file.startswith(file_name):
|
||||
clip_model_path=os.path.join(os.path.dirname(model),file)
|
||||
chat_format='llava-1-5'
|
||||
# print('#clip_model_path',chat_format,clip_model_path,model)
|
||||
prompt=json_data['prompt'] if 'prompt' in json_data else None
|
||||
|
||||
address="127.0.0.1"
|
||||
port=9090
|
||||
success = False
|
||||
for i in range(11): # 尝试最多11次
|
||||
if await check_port_available(address, port + i):
|
||||
port = port + i
|
||||
success = True
|
||||
break
|
||||
if len(apps)==1:
|
||||
# 取到prompt
|
||||
prompt=apps[0]['data']['output']
|
||||
# 更新input_data到prompt里
|
||||
'''
|
||||
{
|
||||
"inputs": {
|
||||
"number": 512,
|
||||
"min_value": 512,
|
||||
"max_value": 2048,
|
||||
"step": 1
|
||||
},
|
||||
"class_type": "IntNumber",
|
||||
"id": "22"
|
||||
},
|
||||
'''
|
||||
|
||||
if success == False:
|
||||
return {"port":None,"model":""}
|
||||
for inp in input_data:
|
||||
id=inp['id']
|
||||
if prompt[id]['class_type']==inp['class_type']:
|
||||
prompt[id]['inputs'].update(inp['inputs'])
|
||||
|
||||
|
||||
if prompt==None:
|
||||
return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
|
||||
else:
|
||||
# 种子更新
|
||||
'''
|
||||
"seed": {
|
||||
"45": "randomize",
|
||||
"46": "randomize"
|
||||
}
|
||||
'''
|
||||
json_data["prompt"]=random_seed(seed,prompt)
|
||||
|
||||
# print("#json_data",prompt)
|
||||
# 需要把apps处理成 prompt
|
||||
# 注意seed的处理
|
||||
|
||||
if "number" in json_data:
|
||||
number = float(json_data['number'])
|
||||
else:
|
||||
number = p_intance.number
|
||||
if "front" in json_data:
|
||||
if json_data['front']:
|
||||
number = -number
|
||||
|
||||
p_intance.number += 1
|
||||
|
||||
if "prompt" in json_data:
|
||||
prompt = json_data["prompt"]
|
||||
valid = execution.validate_prompt(prompt)
|
||||
extra_data = {}
|
||||
if "extra_data" in json_data:
|
||||
extra_data = json_data["extra_data"]
|
||||
|
||||
if "client_id" in json_data:
|
||||
extra_data["client_id"] = json_data["client_id"]
|
||||
if valid[0]:
|
||||
prompt_id = str(uuid.uuid4())
|
||||
outputs_to_execute = valid[2]
|
||||
p_intance.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
|
||||
response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
|
||||
return web.json_response(response)
|
||||
else:
|
||||
logging.warning("invalid prompt: {}".format(valid[1]))
|
||||
return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
|
||||
else:
|
||||
return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
|
||||
|
||||
|
||||
# AR页面
|
||||
# @routes.get('/mixlab/AR')
|
||||
async def handle_ar_page(request):
|
||||
html_file = os.path.join(current_path, "web/ar.html")
|
||||
if os.path.exists(html_file):
|
||||
with open(html_file, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
html_data = f.read()
|
||||
return web.Response(text=html_data, content_type='text/html')
|
||||
else:
|
||||
return web.Response(text="HTML file not found", status=404)
|
||||
|
||||
|
||||
# async def start_local_llm(data):
|
||||
# global llama_port,llama_model,llama_chat_format
|
||||
# if llama_port and llama_model and llama_chat_format:
|
||||
# return {"port":llama_port,"model":llama_model,"chat_format":llama_chat_format}
|
||||
|
||||
# import threading
|
||||
# import uvicorn
|
||||
# from llama_cpp.server.app import create_app
|
||||
# from llama_cpp.server.settings import (
|
||||
# Settings,
|
||||
# ServerSettings,
|
||||
# ModelSettings,
|
||||
# ConfigFileSettings,
|
||||
# )
|
||||
|
||||
# if not "model" in data and "model_path" in data:
|
||||
# data['model']= os.path.basename(data["model_path"])
|
||||
# model=data["model_path"]
|
||||
|
||||
# elif "model" in data:
|
||||
# model=get_llama_model_path(data['model'])
|
||||
|
||||
# n_gpu_layers=-1
|
||||
|
||||
# if "n_gpu_layers" in data:
|
||||
# n_gpu_layers=data['n_gpu_layers']
|
||||
|
||||
|
||||
# chat_format="chatml"
|
||||
|
||||
# model_alias=os.path.basename(model)
|
||||
|
||||
# # 多模态
|
||||
# clip_model_path=None
|
||||
|
||||
# prefix = "llava-phi-3-mini"
|
||||
# file_name = prefix+"-mmproj-"
|
||||
# if model_alias.startswith(prefix):
|
||||
# for file in os.listdir(os.path.dirname(model)):
|
||||
# if file.startswith(file_name):
|
||||
# clip_model_path=os.path.join(os.path.dirname(model),file)
|
||||
# chat_format='llava-1-5'
|
||||
# # print('#clip_model_path',chat_format,clip_model_path,model)
|
||||
|
||||
# address="127.0.0.1"
|
||||
# port=9090
|
||||
# success = False
|
||||
# for i in range(11): # 尝试最多11次
|
||||
# if await check_port_available(address, port + i):
|
||||
# port = port + i
|
||||
# success = True
|
||||
# break
|
||||
|
||||
# if success == False:
|
||||
# return {"port":None,"model":""}
|
||||
|
||||
|
||||
server_settings=ServerSettings(host=address,port=port)
|
||||
# server_settings=ServerSettings(host=address,port=port)
|
||||
|
||||
name, ext = os.path.splitext(os.path.basename(model))
|
||||
if name:
|
||||
# print('#model',name)
|
||||
app = create_app(
|
||||
server_settings=server_settings,
|
||||
model_settings=[
|
||||
ModelSettings(
|
||||
model=model,
|
||||
model_alias=name,
|
||||
n_gpu_layers=n_gpu_layers,
|
||||
n_ctx=4098,
|
||||
chat_format=chat_format,
|
||||
embedding=False,
|
||||
clip_model_path=clip_model_path
|
||||
)])
|
||||
# name, ext = os.path.splitext(os.path.basename(model))
|
||||
# if name:
|
||||
# # print('#model',name)
|
||||
# app = create_app(
|
||||
# server_settings=server_settings,
|
||||
# model_settings=[
|
||||
# ModelSettings(
|
||||
# model=model,
|
||||
# model_alias=name,
|
||||
# n_gpu_layers=n_gpu_layers,
|
||||
# n_ctx=4098,
|
||||
# chat_format=chat_format,
|
||||
# embedding=False,
|
||||
# clip_model_path=clip_model_path
|
||||
# )])
|
||||
|
||||
def run_uvicorn():
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=os.getenv("HOST", server_settings.host),
|
||||
port=int(os.getenv("PORT", server_settings.port)),
|
||||
ssl_keyfile=server_settings.ssl_keyfile,
|
||||
ssl_certfile=server_settings.ssl_certfile,
|
||||
)
|
||||
# def run_uvicorn():
|
||||
# uvicorn.run(
|
||||
# app,
|
||||
# host=os.getenv("HOST", server_settings.host),
|
||||
# port=int(os.getenv("PORT", server_settings.port)),
|
||||
# ssl_keyfile=server_settings.ssl_keyfile,
|
||||
# ssl_certfile=server_settings.ssl_certfile,
|
||||
# )
|
||||
|
||||
# 创建一个子线程
|
||||
thread = threading.Thread(target=run_uvicorn)
|
||||
# # 创建一个子线程
|
||||
# thread = threading.Thread(target=run_uvicorn)
|
||||
|
||||
# 启动子线程
|
||||
thread.start()
|
||||
# # 启动子线程
|
||||
# thread.start()
|
||||
|
||||
llama_port=port
|
||||
llama_model=data['model']
|
||||
llama_chat_format=chat_format
|
||||
# llama_port=port
|
||||
# llama_model=data['model']
|
||||
# llama_chat_format=chat_format
|
||||
|
||||
return {"port":llama_port,"model":llama_model,"chat_format":llama_chat_format}
|
||||
# return {"port":llama_port,"model":llama_model,"chat_format":llama_chat_format}
|
||||
|
||||
# llam服务的开启
|
||||
@routes.post('/mixlab/start_llama')
|
||||
async def my_hander_method(request):
|
||||
data =await request.json()
|
||||
# print(data)
|
||||
if llama_port and llama_model and llama_chat_format:
|
||||
return web.json_response({"port":llama_port,"model":llama_model,"chat_format":llama_chat_format} )
|
||||
try:
|
||||
result=await start_local_llm(data)
|
||||
except:
|
||||
result= {"port":None,"model":"","llama_cpp_error":True}
|
||||
print('start_local_llm error')
|
||||
# @routes.post('/mixlab/start_llama')
|
||||
# async def my_hander_method(request):
|
||||
# data =await request.json()
|
||||
# # print(data)
|
||||
# if llama_port and llama_model and llama_chat_format:
|
||||
# return web.json_response({"port":llama_port,"model":llama_model,"chat_format":llama_chat_format} )
|
||||
# try:
|
||||
# result=await start_local_llm(data)
|
||||
# except:
|
||||
# result= {"port":None,"model":"","llama_cpp_error":True}
|
||||
# print('start_local_llm error')
|
||||
|
||||
return web.json_response(result)
|
||||
# return web.json_response(result)
|
||||
|
||||
# 重启服务
|
||||
@routes.post('/mixlab/re_start')
|
||||
@@ -991,7 +1145,7 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"IncrementingListNode_":"Create Incrementing Number List ♾️Mixlab",
|
||||
"LoadImagesToBatch":"Load Images(base64) ♾️Mixlab",
|
||||
"PreviewMask_":"Preview Mask",
|
||||
"AudioPlay":"Audio Play ♾️Mixlab",
|
||||
"AudioPlay":"Preview Audio ♾️Mixlab",
|
||||
|
||||
"MultiplicationNode":"Math Operation ♾️Mixlab",
|
||||
}
|
||||
@@ -1005,11 +1159,12 @@ logging.info('\033[91m ### Mixlab Nodes: \033[93mLoaded')
|
||||
# print('\033[91m ### Mixlab Nodes: \033[93mLoaded')
|
||||
|
||||
try:
|
||||
from .nodes.ChatGPT import ChatGPTNode,ShowTextForGPT,CharacterInText,TextSplitByDelimiter
|
||||
from .nodes.ChatGPT import ChatGPTNode,ShowTextForGPT,CharacterInText,TextSplitByDelimiter,SiliconflowFreeNode
|
||||
logging.info('ChatGPT.available True')
|
||||
|
||||
NODE_CLASS_MAPPINGS_V = {
|
||||
"ChatGPTOpenAI":ChatGPTNode,
|
||||
"SiliconflowLLM":SiliconflowFreeNode,
|
||||
"ShowTextForGPT":ShowTextForGPT,
|
||||
"CharacterInText":CharacterInText,
|
||||
"TextSplitByDelimiter":TextSplitByDelimiter,
|
||||
@@ -1018,6 +1173,7 @@ try:
|
||||
# 一个包含节点友好/可读的标题的字典
|
||||
NODE_DISPLAY_NAME_MAPPINGS_V = {
|
||||
"ChatGPTOpenAI":"ChatGPT & Local LLM ♾️Mixlab",
|
||||
"SiliconflowLLM":"LLM Siliconflow ♾️Mixlab",
|
||||
"ShowTextForGPT":"Show Text ♾️MixlabApp",
|
||||
"CharacterInText":"Character In Text",
|
||||
"TextSplitByDelimiter":"Text Split By Delimiter",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 537 KiB |
Binary file not shown.
Binary file not shown.
+2
-2
@@ -11,9 +11,9 @@ if exist "%python_exec%" (
|
||||
%python_exec% -s -m pip install "%%i" -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
)
|
||||
|
||||
%python_exec% -s -m pip install --upgrade --force llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121
|
||||
@REM %python_exec% -s -m pip install --upgrade --force llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu121
|
||||
|
||||
%python_exec% -s -m pip install --upgrade --force llama-cpp-python[server]
|
||||
@REM %python_exec% -s -m pip install --upgrade --force llama-cpp-python[server]
|
||||
|
||||
|
||||
) else (
|
||||
|
||||
+7
-2
@@ -90,7 +90,7 @@ class AudioPlayNode:
|
||||
# {'waveform': tensor([], size=(1, 1, 0)), 'sample_rate': 44100}
|
||||
is_tensor=True
|
||||
|
||||
if is_tensor:
|
||||
if is_tensor and (not 'audio_path' in audio):
|
||||
filename_prefix=""
|
||||
# 保存
|
||||
filename_prefix += self.prefix_append
|
||||
@@ -108,7 +108,12 @@ class AudioPlayNode:
|
||||
})
|
||||
|
||||
else:
|
||||
results=[audio]
|
||||
results=[{
|
||||
"filename": audio['filename'],
|
||||
"subfolder":audio['subfolder'],
|
||||
"type": audio['type'],
|
||||
"audio_path":audio['audio_path']
|
||||
}]
|
||||
|
||||
|
||||
# print(audio)
|
||||
|
||||
+148
-57
@@ -53,8 +53,8 @@ def azure_client(key,url):
|
||||
|
||||
def openai_client(key,url):
|
||||
client = openai.OpenAI(
|
||||
api_key=key,
|
||||
base_url=url
|
||||
api_key=key,
|
||||
base_url=url
|
||||
)
|
||||
return client
|
||||
|
||||
@@ -97,73 +97,74 @@ def get_llama_path():
|
||||
except:
|
||||
return os.path.join(folder_paths.models_dir, "llamafile")
|
||||
|
||||
def get_llama_models():
|
||||
res=[]
|
||||
# def get_llama_models():
|
||||
# res=[]
|
||||
|
||||
model_path=get_llama_path()
|
||||
if os.path.exists(model_path):
|
||||
files = os.listdir(model_path)
|
||||
for file in files:
|
||||
if os.path.isfile(os.path.join(model_path, file)):
|
||||
res.append(file)
|
||||
res=phi_sort(res)
|
||||
return res
|
||||
# model_path=get_llama_path()
|
||||
# if os.path.exists(model_path):
|
||||
# files = os.listdir(model_path)
|
||||
# for file in files:
|
||||
# if os.path.isfile(os.path.join(model_path, file)):
|
||||
# res.append(file)
|
||||
# res=phi_sort(res)
|
||||
# return res
|
||||
|
||||
llama_modes_list=get_llama_models()
|
||||
# llama_modes_list=get_llama_models()
|
||||
# llama_modes_list=[]
|
||||
|
||||
def get_llama_model_path(file_name):
|
||||
model_path=get_llama_path()
|
||||
mp=os.path.join(model_path,file_name)
|
||||
return mp
|
||||
# def get_llama_model_path(file_name):
|
||||
# model_path=get_llama_path()
|
||||
# mp=os.path.join(model_path,file_name)
|
||||
# return mp
|
||||
|
||||
def llama_cpp_client(file_name):
|
||||
try:
|
||||
if is_installed('llama_cpp')==False:
|
||||
import subprocess
|
||||
# def llama_cpp_client(file_name):
|
||||
# try:
|
||||
# if is_installed('llama_cpp')==False:
|
||||
# import subprocess
|
||||
|
||||
# 安装
|
||||
print('#pip install llama-cpp-python')
|
||||
# # 安装
|
||||
# print('#pip install llama-cpp-python')
|
||||
|
||||
result = subprocess.run([sys.executable, '-s', '-m', 'pip',
|
||||
'install',
|
||||
'llama-cpp-python',
|
||||
'--extra-index-url',
|
||||
'https://abetlen.github.io/llama-cpp-python/whl/cu121'
|
||||
], capture_output=True, text=True)
|
||||
# result = subprocess.run([sys.executable, '-s', '-m', 'pip',
|
||||
# 'install',
|
||||
# 'llama-cpp-python',
|
||||
# '--extra-index-url',
|
||||
# 'https://abetlen.github.io/llama-cpp-python/whl/cu121'
|
||||
# ], capture_output=True, text=True)
|
||||
|
||||
#检查命令执行结果
|
||||
if result.returncode == 0:
|
||||
print("#install success")
|
||||
from llama_cpp import Llama
|
||||
# #检查命令执行结果
|
||||
# if result.returncode == 0:
|
||||
# print("#install success")
|
||||
# from llama_cpp import Llama
|
||||
|
||||
subprocess.run([sys.executable, '-s', '-m', 'pip',
|
||||
'install',
|
||||
'llama-cpp-python[server]'
|
||||
], capture_output=True, text=True)
|
||||
# subprocess.run([sys.executable, '-s', '-m', 'pip',
|
||||
# 'install',
|
||||
# 'llama-cpp-python[server]'
|
||||
# ], capture_output=True, text=True)
|
||||
|
||||
else:
|
||||
print("#install error")
|
||||
# else:
|
||||
# print("#install error")
|
||||
|
||||
else:
|
||||
from llama_cpp import Llama
|
||||
except:
|
||||
print("#install llama-cpp-python error")
|
||||
# else:
|
||||
# from llama_cpp import Llama
|
||||
# except:
|
||||
# print("#install llama-cpp-python error")
|
||||
|
||||
if file_name:
|
||||
mp=get_llama_model_path(file_name)
|
||||
# file_name=get_llama_models()[0]
|
||||
# model_path=os.path.join(folder_paths.models_dir, "llamafile")
|
||||
# mp=os.path.join(model_path,file_name)
|
||||
# if file_name:
|
||||
# mp=get_llama_model_path(file_name)
|
||||
# # file_name=get_llama_models()[0]
|
||||
# # model_path=os.path.join(folder_paths.models_dir, "llamafile")
|
||||
# # mp=os.path.join(model_path,file_name)
|
||||
|
||||
llm = Llama(model_path=mp, chat_format="chatml",n_gpu_layers=-1,n_ctx=512)
|
||||
# llm = Llama(model_path=mp, chat_format="chatml",n_gpu_layers=-1,n_ctx=512)
|
||||
|
||||
return llm
|
||||
# return llm
|
||||
|
||||
|
||||
|
||||
|
||||
def chat(client, model_name,messages ):
|
||||
|
||||
print('#chat',model_name,messages)
|
||||
try_count = 0
|
||||
while True:
|
||||
try_count += 1
|
||||
@@ -215,7 +216,7 @@ class ChatGPTNode:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
model_list=llama_modes_list+[
|
||||
model_list=[
|
||||
"gpt-3.5-turbo",
|
||||
"gpt-3.5-turbo-16k",
|
||||
"gpt-4o",
|
||||
@@ -236,7 +237,11 @@ class ChatGPTNode:
|
||||
"moonshot-v1-8k",
|
||||
"moonshot-v1-32k",
|
||||
"moonshot-v1-128k",
|
||||
"deepseek-chat"
|
||||
"deepseek-chat",
|
||||
"Qwen/Qwen2-7B-Instruct",
|
||||
"THUDM/glm-4-9b-chat",
|
||||
"01-ai/Yi-1.5-9B-Chat-16K",
|
||||
"meta-llama/Meta-Llama-3.1-8B-Instruct"
|
||||
]
|
||||
return {
|
||||
"required": {
|
||||
@@ -295,12 +300,12 @@ class ChatGPTNode:
|
||||
if model == "glm-4" :
|
||||
client = ZhipuAI_client(api_key) # 使用 Zhipuai 的接口
|
||||
print('using Zhipuai interface')
|
||||
elif model in llama_modes_list:
|
||||
#
|
||||
client=llama_cpp_client(model)
|
||||
# elif model in llama_modes_list:
|
||||
# #
|
||||
# client=llama_cpp_client(model)
|
||||
else :
|
||||
client = openai_client(api_key,api_url) # 使用 ChatGPT 的接口
|
||||
print('using ChatGPT interface')
|
||||
# print('using ChatGPT interface',api_key,api_url)
|
||||
|
||||
# 把用户的提示添加到会话历史中
|
||||
# 调用API时传递整个会话历史
|
||||
@@ -316,6 +321,7 @@ class ChatGPTNode:
|
||||
session_history=crop_list_tail(self.session_history,context_size)
|
||||
|
||||
messages=[{"role": "system", "content": self.system_content}]+session_history+[{"role": "user", "content": prompt}]
|
||||
|
||||
response_content = chat(client,model,messages)
|
||||
|
||||
self.session_history=self.session_history+[{"role": "user", "content": prompt}]+[{'role':'assistant',"content":response_content}]
|
||||
@@ -336,6 +342,91 @@ class ChatGPTNode:
|
||||
return (response_content,json.dumps(messages, indent=4),json.dumps(self.session_history, indent=4),)
|
||||
|
||||
|
||||
class SiliconflowFreeNode:
|
||||
def __init__(self):
|
||||
# self.__client = OpenAI()
|
||||
self.session_history = [] # 用于存储会话历史的列表
|
||||
# self.seed=0
|
||||
self.system_content="You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
model_list= [
|
||||
"Qwen/Qwen2-7B-Instruct",
|
||||
"THUDM/glm-4-9b-chat",
|
||||
"01-ai/Yi-1.5-9B-Chat-16K",
|
||||
"meta-llama/Meta-Llama-3.1-8B-Instruct"
|
||||
]
|
||||
return {
|
||||
"required": {
|
||||
"api_key":("KEY", {"default": "", "multiline": True,"dynamicPrompts": False}),
|
||||
"prompt": ("STRING", {"multiline": True,"dynamicPrompts": False}),
|
||||
"system_content": ("STRING",
|
||||
{
|
||||
"default": "You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.",
|
||||
"multiline": True,"dynamicPrompts": False
|
||||
}),
|
||||
"model": ( model_list,
|
||||
{"default": model_list[0]}),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "step": 1}),
|
||||
"context_size":("INT", {"default": 1, "min": 0, "max":30, "step": 1}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO",
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING","STRING","STRING",)
|
||||
RETURN_NAMES = ("text","messages","session_history",)
|
||||
FUNCTION = "generate_contextual_text"
|
||||
CATEGORY = "♾️Mixlab/GPT"
|
||||
INPUT_IS_LIST = False
|
||||
OUTPUT_IS_LIST = (False,False,False,)
|
||||
|
||||
|
||||
def generate_contextual_text(self,
|
||||
api_key,
|
||||
prompt,
|
||||
system_content,
|
||||
model,
|
||||
seed,context_size,unique_id = None, extra_pnginfo=None):
|
||||
|
||||
api_url="https://api.siliconflow.cn/v1"
|
||||
|
||||
# 把系统信息和初始信息添加到会话历史中
|
||||
if system_content:
|
||||
self.system_content=system_content
|
||||
# self.session_history=[]
|
||||
# self.session_history.append({"role": "system", "content": system_content})
|
||||
|
||||
#
|
||||
client = openai_client(api_key,api_url) # 使用 ChatGPT 的接口
|
||||
# print('using ChatGPT interface',api_key,api_url)
|
||||
|
||||
# 把用户的提示添加到会话历史中
|
||||
# 调用API时传递整个会话历史
|
||||
|
||||
def crop_list_tail(lst, size):
|
||||
if size >= len(lst):
|
||||
return lst
|
||||
elif size==0:
|
||||
return []
|
||||
else:
|
||||
return lst[-size:]
|
||||
|
||||
session_history=crop_list_tail(self.session_history,context_size)
|
||||
|
||||
messages=[{"role": "system", "content": self.system_content}]+session_history+[{"role": "user", "content": prompt}]
|
||||
|
||||
response_content = chat(client,model,messages)
|
||||
|
||||
self.session_history=self.session_history+[{"role": "user", "content": prompt}]+[{'role':'assistant',"content":response_content}]
|
||||
|
||||
return (response_content,json.dumps(messages, indent=4),json.dumps(self.session_history, indent=4),)
|
||||
|
||||
|
||||
|
||||
|
||||
class ShowTextForGPT:
|
||||
@classmethod
|
||||
|
||||
+37
-16
@@ -30,17 +30,20 @@ def opencv_to_pil(image):
|
||||
return pil_image
|
||||
|
||||
# 列出目录下面的所有文件
|
||||
def get_files_with_extension(directory, extension):
|
||||
def get_files_with_extension(directory, extensions):
|
||||
file_list = []
|
||||
# 确保extensions参数是一个list,即使只有一个元素
|
||||
if not isinstance(extensions, (tuple, list)):
|
||||
extensions = [extensions]
|
||||
for root, dirs, files in os.walk(directory):
|
||||
# print(f"Files at {root}: {files}") # 确认files是一个字符串列表
|
||||
for file in files:
|
||||
if file.endswith(extension):
|
||||
file = os.path.splitext(file)[0]
|
||||
file_path = os.path.join(root, file)
|
||||
file_name = os.path.relpath(file_path, directory)
|
||||
file_list.append(file_name)
|
||||
# 检查文件是否以任何一个提供的扩展名结尾
|
||||
if any(file.endswith(ext) for ext in extensions):
|
||||
# 直接将文件名添加到列表中
|
||||
file_list.append(file)
|
||||
return file_list
|
||||
|
||||
|
||||
def composite_images(foreground, background, mask, is_multiply_blend=False, position="overall", scale=0.25):
|
||||
width, height = foreground.size
|
||||
bg_image = background
|
||||
@@ -909,7 +912,7 @@ def resize_image(layer_image, scale_option, width, height,color="white"):
|
||||
return layer_image
|
||||
|
||||
|
||||
def generate_text_image(text, font_path, font_size, text_color, vertical=True, stroke=False, stroke_color=(0, 0, 0), stroke_width=1, spacing=0, padding=4):
|
||||
def generate_text_image(text, font_path, font_size, text_color, vertical=True, stroke=False, stroke_color=(0, 0, 0), stroke_width=1, spacing=0, line_spacing=0,padding=4):
|
||||
# Split text into lines based on line breaks
|
||||
lines = text.split("\n")
|
||||
|
||||
@@ -935,9 +938,13 @@ def generate_text_image(text, font_path, font_size, text_color, vertical=True, s
|
||||
char_coordinates.append((x, y))
|
||||
y += char_height + spacing
|
||||
max_height = max(max_height, y + padding)
|
||||
x += max_char_width + spacing
|
||||
x += max_char_width + line_spacing
|
||||
y = padding
|
||||
max_width = x
|
||||
total_line_width = sum(font.getsize(line)[1] for line in lines)
|
||||
total_spacing = line_spacing * (len(lines) - 1)
|
||||
# 确保左边和右边的padding都被计入max_width
|
||||
max_width = total_line_width + total_spacing + padding * 2
|
||||
else:
|
||||
for line in lines:
|
||||
line_width, line_height = font.getsize(line)
|
||||
@@ -946,9 +953,13 @@ def generate_text_image(text, font_path, font_size, text_color, vertical=True, s
|
||||
char_coordinates.append((x, y))
|
||||
x += char_width + spacing
|
||||
max_width = max(max_width, x + padding)
|
||||
y += line_height + spacing
|
||||
y += line_height + line_spacing
|
||||
x = padding
|
||||
max_height = y
|
||||
# max_height = y
|
||||
total_line_heights = sum(font.getsize(line)[1] for line in lines)
|
||||
total_spacing = line_spacing * (len(lines) - 1)
|
||||
# 确保顶部和底部的padding都被计入max_height
|
||||
max_height = total_line_heights + total_spacing + padding * 2
|
||||
|
||||
# 3. Create image with calculated width and height
|
||||
image = Image.new('RGBA', (max_width, max_height), (255, 255, 255, 0))
|
||||
@@ -1288,6 +1299,9 @@ class LoadImages_:
|
||||
image=pil2tensor(image)
|
||||
ims.append(image)
|
||||
|
||||
if len(ims)==0:
|
||||
image1 = Image.new('RGB', (512, 512), color='black')
|
||||
return (pil2tensor(image1),)
|
||||
image1 = ims[0]
|
||||
for image2 in ims[1:]:
|
||||
if image1.shape[1:] != image2.shape[1:]:
|
||||
@@ -1498,7 +1512,7 @@ class TextImage:
|
||||
return {"required": {
|
||||
|
||||
"text": ("STRING",{"multiline": True,"default": "龍馬精神迎新歲","dynamicPrompts": False}),
|
||||
"font": (get_files_with_extension(FONT_PATH,'.ttf'),),#后缀为 ttf
|
||||
"font": (get_files_with_extension(FONT_PATH,['.ttf','.otf']),),#后缀为 ttf
|
||||
"font_size": ("INT",{
|
||||
"default":100,
|
||||
"min": 100, #Minimum value
|
||||
@@ -1513,6 +1527,13 @@ class TextImage:
|
||||
"step": 1, #Slider's step
|
||||
"display": "number" # Cosmetic only: display as "number" or "slider"
|
||||
}),
|
||||
"line_spacing": ("INT",{
|
||||
"default":12,
|
||||
"min": -200, #Minimum value
|
||||
"max": 200, #Maximum value
|
||||
"step": 1, #Slider's step
|
||||
"display": "number" # Cosmetic only: display as "number" or "slider"
|
||||
}),
|
||||
"padding": ("INT",{
|
||||
"default":8,
|
||||
"min": 0, #Minimum value
|
||||
@@ -1536,14 +1557,14 @@ class TextImage:
|
||||
INPUT_IS_LIST = False
|
||||
OUTPUT_IS_LIST = (False,False,)
|
||||
|
||||
def run(self,text,font,font_size,spacing,padding,text_color,vertical,stroke):
|
||||
def run(self,text,font,font_size,spacing,line_spacing,padding,text_color,vertical,stroke):
|
||||
|
||||
font_path=os.path.join(FONT_PATH,font+'.ttf')
|
||||
font_path=os.path.join(FONT_PATH,font)
|
||||
|
||||
if text=="":
|
||||
text=" "
|
||||
# stroke=False, stroke_color=(0, 0, 0), stroke_width=1, spacing=0
|
||||
img,mask=generate_text_image(text,font_path,font_size,text_color,vertical,stroke,(0, 0, 0),1,spacing,padding)
|
||||
img,mask=generate_text_image(text,font_path,font_size,text_color,vertical,stroke,(0, 0, 0),1,spacing,line_spacing,padding)
|
||||
|
||||
img=pil2tensor(img)
|
||||
mask=pil2tensor(mask)
|
||||
@@ -3201,4 +3222,4 @@ class ImageListToBatch_:
|
||||
|
||||
out = torch.cat(out, dim=0)
|
||||
|
||||
return (out,)
|
||||
return (out,)
|
||||
|
||||
+44
-16
@@ -545,20 +545,24 @@ class LoadAndCombinedAudio_:
|
||||
if duration > -1:
|
||||
crop_audio(audio_file, start_time, duration)
|
||||
|
||||
return (audio_file, {
|
||||
"filename": audio_file_name,
|
||||
"subfolder": "",
|
||||
"type": "output",
|
||||
"audio_path":audio_file
|
||||
} ,)
|
||||
waveform, sample_rate = torchaudio.load(audio_file)
|
||||
audio = {
|
||||
"filename": audio_file_name,
|
||||
"subfolder": "",
|
||||
"type": "output",
|
||||
"audio_path":audio_file,
|
||||
"waveform": waveform.unsqueeze(0),
|
||||
"sample_rate": sample_rate}
|
||||
|
||||
return (audio_file,audio ,)
|
||||
|
||||
class CombineAudioVideo:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
|
||||
return {"required": {
|
||||
"video_file_path": ("STRING", {"forceInput": True}),
|
||||
"audio_file_path": ("STRING", {"forceInput": True}),
|
||||
"video": ("SCENE_VIDEO",),
|
||||
"audio": ("AUDIO", ),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -566,23 +570,46 @@ class CombineAudioVideo:
|
||||
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "run"
|
||||
RETURN_TYPES = ()
|
||||
RETURN_NAMES = ()
|
||||
RETURN_TYPES = ("SCENE_VIDEO",)
|
||||
RETURN_NAMES = ("SCENE_VIDEO",)
|
||||
|
||||
def run(self,video_file_path, audio_file_path):
|
||||
def run(self,video, audio):
|
||||
|
||||
output_dir = folder_paths.get_output_directory()
|
||||
|
||||
counter=get_new_counter(output_dir,'video_final_')
|
||||
|
||||
# 判断是否是 Tensor 类型
|
||||
is_tensor = not isinstance(audio, dict)
|
||||
# print('#判断是否是 Tensor 类型',is_tensor,audio)
|
||||
if not is_tensor and 'waveform' in audio and 'sample_rate' in audio:
|
||||
# {'waveform': tensor([], size=(1, 1, 0)), 'sample_rate': 44100}
|
||||
is_tensor=True
|
||||
|
||||
if "audio_path" in audio:
|
||||
is_tensor=False
|
||||
audio_file_path=audio["audio_path"]
|
||||
|
||||
if is_tensor:
|
||||
filename_prefix="audio_tmp"
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
folder_paths.get_temp_directory())
|
||||
|
||||
filename_with_batch_num = filename.replace("%batch_num%", str(1))
|
||||
file = f"{filename_with_batch_num}_{counter:05}_.wav"
|
||||
|
||||
audio_file_path=os.path.join(full_output_folder, file)
|
||||
|
||||
torchaudio.save(audio_file_path, audio['waveform'].squeeze(0), audio["sample_rate"])
|
||||
|
||||
# 获取文件名和扩展名
|
||||
base, ext = os.path.splitext(video_file_path)
|
||||
base, ext = os.path.splitext(video)
|
||||
counter=get_new_counter(output_dir,'video_final_')
|
||||
|
||||
v_file = f"video_final_{counter:05}{ext}"
|
||||
|
||||
v_file_path=os.path.join(output_dir, v_file)
|
||||
|
||||
combine_audio_video(audio_file_path,video_file_path,v_file_path)
|
||||
combine_audio_video(audio_file_path,video,v_file_path)
|
||||
|
||||
previews = [
|
||||
{
|
||||
@@ -592,7 +619,8 @@ class CombineAudioVideo:
|
||||
"format": get_mime_type(v_file),
|
||||
}
|
||||
]
|
||||
return {"ui": {"gifs": previews}}
|
||||
|
||||
return {"ui": {"gifs": previews},"result":(v_file_path,)}
|
||||
|
||||
# The code is based on ComfyUI-VideoHelperSuite modification.
|
||||
class VideoCombine_Adv:
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-mixlab-nodes"
|
||||
description = "3D, ScreenShareNode & FloatingVideoNode, SpeechRecognition & SpeechSynthesis, GPT, LoadImagesFromLocal, Layers, Other Nodes, ..."
|
||||
version = "0.30.3"
|
||||
version = "0.33.0"
|
||||
license = "MIT"
|
||||
dependencies = ["numpy", "pyOpenSSL", "watchdog", "opencv-python-headless", "matplotlib", "openai", "simple-lama-inpainting", "clip-interrogator==0.6.0", "transformers>=4.36.0", "lark-parser", "imageio-ffmpeg", "rembg[gpu]", "omegaconf==2.3.0", "Pillow>=9.5.0", "einops==0.7.0", "trimesh>=4.0.5", "huggingface-hub", "scikit-image"]
|
||||
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Mixlab AR</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<script type="module">
|
||||
|
||||
import { api } from "../../../scripts/api.js";
|
||||
import Command from '/extensions/comfyui-mixlab-nodes/javascript/command.js'
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+501
-687
File diff suppressed because it is too large
Load Diff
@@ -256,7 +256,9 @@ async function extractInputAndOutputData (
|
||||
node.type === 'KSampler' ||
|
||||
node.type == 'SamplerCustom' ||
|
||||
node.type === 'ChinesePrompt_Mix' ||
|
||||
node.type === 'Seed_'
|
||||
node.type === 'Seed_'||
|
||||
node.type==='SiliconflowLLM'||
|
||||
node.type==='ChatGPTOpenAI'
|
||||
) {
|
||||
// seed 的类型收集
|
||||
try {
|
||||
@@ -466,19 +468,18 @@ app.registerExtension({
|
||||
const { input, output } = getInputsAndOutputs()
|
||||
input_ids.value = input.join('\n')
|
||||
output_ids.value = output.join('\n')
|
||||
|
||||
const widget = {
|
||||
type: 'div',
|
||||
name: 'AppInfoRun',
|
||||
draw (ctx, node, widget_width, y, widget_height) {
|
||||
Object.assign(
|
||||
this.div.style,
|
||||
get_position_style(
|
||||
{...get_position_style(
|
||||
ctx,
|
||||
widget_width,
|
||||
node.size[1] - widget_height,
|
||||
node.size[1]
|
||||
)
|
||||
),zIndex:1}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,6 +555,7 @@ app.registerExtension({
|
||||
e.preventDefault()
|
||||
let inputAudio = document.createElement('input')
|
||||
inputAudio.type = 'file'
|
||||
inputAudio.accept = "audio/*"
|
||||
inputAudio.style.display = 'none'
|
||||
inputAudio.addEventListener('change', async e => {
|
||||
e.preventDefault()
|
||||
|
||||
@@ -3,7 +3,7 @@ import { app } from '../../../scripts/app.js'
|
||||
const repoOwner = 'shadowcz007' // 替换为仓库的所有者
|
||||
const repoName = 'comfyui-mixlab-nodes' // 替换为仓库的名称
|
||||
|
||||
const version = 'v0.30.3'
|
||||
const version = 'v0.33.0'
|
||||
|
||||
fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/releases/latest`)
|
||||
.then(response => response.json())
|
||||
|
||||
@@ -0,0 +1,680 @@
|
||||
function get_url () {
|
||||
let api_host = `${window.location.hostname}:${window.location.port}`
|
||||
let api_base = ''
|
||||
let url = `${window.location.protocol}//${api_host}${api_base}`
|
||||
return url
|
||||
}
|
||||
|
||||
function getFilenameAndCategoryFromUrl (url) {
|
||||
const queryString = url.split('?')[1]
|
||||
if (!queryString) {
|
||||
return {}
|
||||
}
|
||||
|
||||
const params = new URLSearchParams(queryString)
|
||||
|
||||
const filename = params.get('filename')
|
||||
? decodeURIComponent(params.get('filename'))
|
||||
: null
|
||||
const category = params.get('category')
|
||||
? decodeURIComponent(params.get('category') || '')
|
||||
: ''
|
||||
|
||||
return { category, filename }
|
||||
}
|
||||
|
||||
async function get_my_app (category = '', filename = null) {
|
||||
let url = get_url()
|
||||
const res = await fetch(`${url}/mixlab/workflow`, {
|
||||
method: 'POST',
|
||||
mode: 'cors', // 允许跨域请求
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
task: 'my_app',
|
||||
filename,
|
||||
category
|
||||
})
|
||||
})
|
||||
let result = await res.json()
|
||||
let data = []
|
||||
try {
|
||||
for (const res of result.data) {
|
||||
let { output, app } = res.data
|
||||
if (app.filename)
|
||||
data.push({
|
||||
...app,
|
||||
data: output,
|
||||
date: res.date
|
||||
})
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
async function getAppInit () {
|
||||
const { category, filename } = getFilenameAndCategoryFromUrl(
|
||||
window.location.href
|
||||
)
|
||||
return await get_my_app(category, filename)
|
||||
}
|
||||
|
||||
function success (isSuccess, btn, text) {
|
||||
isSuccess ? (btn.innerText = 'success') : text
|
||||
setTimeout(() => {
|
||||
btn.innerText = text
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
async function interrupt () {
|
||||
try {
|
||||
await fetch(`${get_url()}/interrupt`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: undefined
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function getQueue (clientId) {
|
||||
try {
|
||||
const res = await fetch(`${get_url()}/queue`)
|
||||
const data = await res.json()
|
||||
return {
|
||||
// Running action uses a different endpoint for cancelling
|
||||
Running: Array.from(data.queue_running, prompt => {
|
||||
if (prompt[3].client_id === clientId) {
|
||||
let prompt_id = prompt[1]
|
||||
return {
|
||||
prompt_id,
|
||||
remove: () => interrupt()
|
||||
}
|
||||
}
|
||||
}),
|
||||
Pending: data.queue_pending.map(prompt => ({ prompt }))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return { Running: [], Pending: [] }
|
||||
}
|
||||
}
|
||||
|
||||
// 请求历史数据
|
||||
async function getPromptResult (category) {
|
||||
let url = get_url()
|
||||
try {
|
||||
const response = await fetch(`${url}/mixlab/prompt_result`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'all'
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
console.log('#getPromptResult:', category, data)
|
||||
|
||||
return data.result.filter(r => r.appInfo.category == category)
|
||||
// 处理返回的数据
|
||||
} else {
|
||||
console.log('Error:', response.status)
|
||||
// 处理错误情况
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Error:', error)
|
||||
// 处理异常情况
|
||||
}
|
||||
}
|
||||
|
||||
// 新的运行工作流的接口
|
||||
function queuePromptNew (filename, category, seed, input, client_id) {
|
||||
let url = get_url()
|
||||
// var filename = "Text-to-Image_1.json", category = "";
|
||||
|
||||
// 随机seed
|
||||
// promptWorkflow = randomSeed(seed, promptWorkflow);
|
||||
|
||||
const data = JSON.stringify({ filename, category, seed, input, client_id })
|
||||
return new Promise((res, rej) => {
|
||||
fetch(`${url}/mixlab/prompt`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: data
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
// Handle HTTP error responses
|
||||
if (response.status === 400) {
|
||||
return response.json().then(errorData => {
|
||||
// Process the error data
|
||||
console.error('Error 400:', errorData)
|
||||
alert(JSON.stringify(errorData, null, 2))
|
||||
res(null)
|
||||
})
|
||||
}
|
||||
throw new Error('Network response was not ok')
|
||||
}
|
||||
return response.json() // Process the response data
|
||||
})
|
||||
.then(data => {
|
||||
// Handle the response data
|
||||
console.log('Success:', data)
|
||||
res(true)
|
||||
})
|
||||
.catch(error => {
|
||||
// Handle fetch errors
|
||||
console.error('Fetch error:', error)
|
||||
res(null)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 保存历史数据
|
||||
async function savePromptResult (data) {
|
||||
let url = get_url()
|
||||
try {
|
||||
const response = await fetch(`${url}/mixlab/prompt_result`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'save',
|
||||
data
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
const res = await response.json()
|
||||
console.log('Response:', res)
|
||||
return res
|
||||
// 处理返回的数据
|
||||
} else {
|
||||
console.log('Error:', response.status)
|
||||
// 处理错误情况
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Error:', error)
|
||||
// 处理异常情况
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadImage (blob, fileType = '.png', filename) {
|
||||
const body = new FormData()
|
||||
body.append(
|
||||
'image',
|
||||
new File([blob], (filename || new Date().getTime()) + fileType)
|
||||
)
|
||||
|
||||
const url = get_url()
|
||||
|
||||
const resp = await fetch(`${url}/upload/image`, {
|
||||
method: 'POST',
|
||||
body
|
||||
})
|
||||
|
||||
let data = await resp.json()
|
||||
// console.log(data)
|
||||
let { name, subfolder } = data
|
||||
let src = `${url}/view?filename=${encodeURIComponent(
|
||||
name
|
||||
)}&type=input&subfolder=${subfolder}&rand=${Math.random()}`
|
||||
|
||||
return { url: src, name }
|
||||
}
|
||||
|
||||
async function uploadMask (arrayBuffer, imgurl) {
|
||||
const body = new FormData()
|
||||
const filename = 'clipspace-mask-' + performance.now() + '.png'
|
||||
|
||||
let original_url = new URL(imgurl)
|
||||
|
||||
const original_ref = { filename: original_url.searchParams.get('filename') }
|
||||
|
||||
let original_subfolder = original_url.searchParams.get('subfolder')
|
||||
if (original_subfolder) original_ref.subfolder = original_subfolder
|
||||
|
||||
let original_type = original_url.searchParams.get('type')
|
||||
if (original_type) original_ref.type = original_type
|
||||
|
||||
body.append('image', arrayBuffer, filename)
|
||||
body.append('original_ref', JSON.stringify(original_ref))
|
||||
body.append('type', 'input')
|
||||
body.append('subfolder', 'clipspace')
|
||||
|
||||
const url = get_url()
|
||||
|
||||
const resp = await fetch(`${url}/upload/mask`, {
|
||||
method: 'POST',
|
||||
body
|
||||
})
|
||||
|
||||
// console.log(resp)
|
||||
let data = await resp.json()
|
||||
let { name, subfolder, type } = data
|
||||
let src = `${url}/view?filename=${encodeURIComponent(
|
||||
name
|
||||
)}&type=${type}&subfolder=${subfolder}&rand=${Math.random()}`
|
||||
|
||||
return { url: src, name: 'clipspace/' + name }
|
||||
}
|
||||
|
||||
const parseImageToBase64 = url => {
|
||||
return new Promise((res, rej) => {
|
||||
fetch(url)
|
||||
.then(response => response.blob())
|
||||
.then(blob => {
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
const base64data = reader.result
|
||||
res(base64data)
|
||||
// 在这里可以将base64数据用于进一步处理或显示图片
|
||||
}
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('发生错误:', error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function createImage (url) {
|
||||
let im = new Image()
|
||||
return new Promise((res, rej) => {
|
||||
im.onload = () => res(im)
|
||||
im.src = url
|
||||
})
|
||||
}
|
||||
|
||||
function convertImageToBlackBasedOnAlpha (image) {
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')
|
||||
|
||||
// Draw the image onto the canvas
|
||||
canvas.width = image.width
|
||||
canvas.height = image.height
|
||||
ctx.drawImage(image, 0, 0)
|
||||
|
||||
// Get the image data from the canvas
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
|
||||
const pixels = imageData.data
|
||||
|
||||
// Modify the RGB values based on the alpha channel
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
const alpha = pixels[i + 3]
|
||||
if (alpha !== 0) {
|
||||
// Set non-transparent pixels to black
|
||||
pixels[i] = 0 // Red
|
||||
pixels[i + 1] = 0 // Green
|
||||
pixels[i + 2] = 0 // Blue
|
||||
}
|
||||
}
|
||||
|
||||
// Put the modified image data back onto the canvas
|
||||
ctx.putImageData(imageData, 0, 0)
|
||||
|
||||
// Convert the modified canvas to base64 data URL
|
||||
const base64ImageData = canvas.toDataURL('image/png') // Replace 'png' with your desired image format
|
||||
|
||||
return base64ImageData
|
||||
}
|
||||
|
||||
const blobToBase64 = blob => {
|
||||
return new Promise((res, rej) => {
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
const base64data = reader.result
|
||||
res(base64data)
|
||||
// 在这里可以将base64数据用于进一步处理或显示图片
|
||||
}
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
function base64ToBlob (base64) {
|
||||
// 去除base64编码中的前缀
|
||||
const base64WithoutPrefix = base64.replace(/^data:image\/\w+;base64,/, '')
|
||||
|
||||
// 将base64编码转换为字节数组
|
||||
const byteCharacters = atob(base64WithoutPrefix)
|
||||
|
||||
// 创建一个存储字节数组的数组
|
||||
const byteArrays = []
|
||||
|
||||
// 将字节数组放入数组中
|
||||
for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
|
||||
const slice = byteCharacters.slice(offset, offset + 1024)
|
||||
|
||||
const byteNumbers = new Array(slice.length)
|
||||
for (let i = 0; i < slice.length; i++) {
|
||||
byteNumbers[i] = slice.charCodeAt(i)
|
||||
}
|
||||
|
||||
const byteArray = new Uint8Array(byteNumbers)
|
||||
byteArrays.push(byteArray)
|
||||
}
|
||||
|
||||
// 创建blob对象
|
||||
const blob = new Blob(byteArrays, { type: 'image/png' }) // 根据实际情况设置MIME类型
|
||||
|
||||
return blob
|
||||
}
|
||||
|
||||
async function calculateImageHash (blob) {
|
||||
const buffer = await blob.arrayBuffer()
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
const hashHex = hashArray
|
||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
return hashHex
|
||||
}
|
||||
|
||||
// 获取 rembg 模型
|
||||
async function get_rembg_models () {
|
||||
try {
|
||||
const response = await fetch(`${get_url()}/mixlab/folder_paths`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
type: 'rembg'
|
||||
})
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
// console.log(data)
|
||||
return data.names
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
//自动抠图
|
||||
async function run_rembg (model, base64) {
|
||||
try {
|
||||
const response = await fetch(`${get_url()}/mixlab/rembg`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
base64
|
||||
})
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
// console.log(data)
|
||||
return data.data
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
function copyHtmlWithImagesToClipboard (data, cb) {
|
||||
// 创建一个临时div元素
|
||||
const tempDiv = document.createElement('div')
|
||||
|
||||
// 将HTML字符串赋值给div的innerHTML属性
|
||||
tempDiv.innerHTML = data
|
||||
|
||||
// 获取div中的所有图像元素
|
||||
const images = tempDiv.getElementsByTagName('img')
|
||||
|
||||
// 遍历图像元素,并将图像数据转换为Base64编码
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
const image = images[i]
|
||||
const canvas = document.createElement('canvas')
|
||||
const context = canvas.getContext('2d')
|
||||
|
||||
// 设置canvas尺寸与图像尺寸相同
|
||||
canvas.width = image.width
|
||||
canvas.height = image.height
|
||||
|
||||
// 在canvas上绘制图像
|
||||
context.drawImage(image, 0, 0)
|
||||
|
||||
// 将canvas转换为Base64编码
|
||||
const imageData = canvas.toDataURL()
|
||||
|
||||
// 将Base64编码替换图像元素的src属性
|
||||
image.src = imageData
|
||||
}
|
||||
|
||||
let richText = tempDiv.innerHTML
|
||||
|
||||
// 创建一个新的Blob对象,并将富文本字符串作为数据传递进去
|
||||
const blob = new Blob([richText], { type: 'text/html' })
|
||||
|
||||
// 创建一个ClipboardItem对象,并将Blob对象添加到其中
|
||||
const clipboardItem = new ClipboardItem({ 'text/html': blob })
|
||||
|
||||
// 使用Clipboard API将内容复制到剪贴板
|
||||
navigator.clipboard
|
||||
.write([clipboardItem])
|
||||
.then(() => {
|
||||
console.log('富文本已成功复制到剪贴板')
|
||||
tempDiv.remove()
|
||||
if (cb) cb(true)
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('复制到剪贴板失败:', error)
|
||||
tempDiv.remove()
|
||||
if (cb) cb(false)
|
||||
})
|
||||
}
|
||||
|
||||
function copyImagesToClipboard (html, cb) {
|
||||
const tempDiv = document.createElement('div')
|
||||
tempDiv.innerHTML = html
|
||||
const images = tempDiv.querySelectorAll('img')
|
||||
const promises = Array.from(images).map(image => {
|
||||
return new Promise(resolve => {
|
||||
const img = new Image()
|
||||
img.src = image.src
|
||||
img.onload = () => {
|
||||
const canvas = document.createElement('canvas')
|
||||
const context = canvas.getContext('2d')
|
||||
canvas.width = img.width
|
||||
canvas.height = img.height
|
||||
context.drawImage(img, 0, 0)
|
||||
canvas.toBlob(blob => {
|
||||
const clipboardItem = new ClipboardItem({ 'image/png': blob })
|
||||
navigator.clipboard
|
||||
.write([clipboardItem])
|
||||
.then(() => {
|
||||
resolve()
|
||||
tempDiv.remove()
|
||||
if (cb) cb(true)
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
tempDiv.remove()
|
||||
if (cb) cb(false)
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
Promise.all([...promises])
|
||||
.then(() => {
|
||||
console.log('所有图片已成功复制到剪贴板')
|
||||
if (cb) cb(true)
|
||||
tempDiv.remove()
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('复制到剪贴板失败:', error)
|
||||
if (cb) cb(false)
|
||||
tempDiv.remove()
|
||||
})
|
||||
}
|
||||
|
||||
function copyTextToClipboard (html, cb) {
|
||||
const tempDiv = document.createElement('div')
|
||||
tempDiv.innerHTML = html
|
||||
|
||||
const text = tempDiv.innerText
|
||||
const textData = new ClipboardItem({
|
||||
'text/plain': new Blob([text], { type: 'text/plain' })
|
||||
})
|
||||
|
||||
navigator.clipboard
|
||||
.write([textData])
|
||||
.then(() => {
|
||||
console.log('所有文本已成功复制到剪贴板', text)
|
||||
if (cb) cb(true)
|
||||
tempDiv.remove()
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('复制到剪贴板失败:', error)
|
||||
if (cb) cb(false)
|
||||
tempDiv.remove()
|
||||
})
|
||||
}
|
||||
|
||||
// ComfyUI\web\extensions\core\dynamicPrompts.js
|
||||
// 官方实现修改
|
||||
// Allows for simple dynamic prompt replacement
|
||||
// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued.
|
||||
|
||||
/*
|
||||
* Strips C-style line and block comments from a string
|
||||
*/
|
||||
function dynamicPrompts (prompt) {
|
||||
prompt = prompt.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '')
|
||||
while (
|
||||
prompt.replace('\\{', '').includes('{') &&
|
||||
prompt.replace('\\}', '').includes('}')
|
||||
) {
|
||||
const startIndex = prompt.replace('\\{', '00').indexOf('{')
|
||||
const endIndex = prompt.replace('\\}', '00').indexOf('}')
|
||||
|
||||
const optionsString = prompt.substring(startIndex + 1, endIndex)
|
||||
const options = optionsString.split('|')
|
||||
|
||||
const randomIndex = Math.floor(Math.random() * options.length)
|
||||
const randomOption = options[randomIndex]
|
||||
|
||||
prompt =
|
||||
prompt.substring(0, startIndex) +
|
||||
randomOption +
|
||||
prompt.substring(endIndex + 1)
|
||||
}
|
||||
return prompt
|
||||
}
|
||||
|
||||
// 遍历所有组合,语法同 动态提示
|
||||
function generateAllCombinations (prompt) {
|
||||
prompt = prompt.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '')
|
||||
|
||||
// Helper function to get all combinations
|
||||
function getAllCombinations (parts) {
|
||||
if (parts.length === 0) return ['']
|
||||
const [firstPart, ...restParts] = parts
|
||||
const restCombinations = getAllCombinations(restParts)
|
||||
const allCombinations = []
|
||||
|
||||
firstPart.forEach(option => {
|
||||
restCombinations.forEach(combination => {
|
||||
allCombinations.push(option + combination)
|
||||
})
|
||||
})
|
||||
|
||||
return allCombinations
|
||||
}
|
||||
|
||||
// Split prompt into static parts and dynamic parts
|
||||
let parts = []
|
||||
let startIndex = 0
|
||||
|
||||
while (
|
||||
prompt.replace('\\{', '').includes('{') &&
|
||||
prompt.replace('\\}', '').includes('}')
|
||||
) {
|
||||
startIndex = prompt.replace('\\{', '00').indexOf('{')
|
||||
const endIndex = prompt.replace('\\}', '00').indexOf('}')
|
||||
const staticPart = prompt.substring(0, startIndex)
|
||||
const optionsString = prompt.substring(startIndex + 1, endIndex)
|
||||
const options = optionsString.split('|')
|
||||
|
||||
parts.push([staticPart])
|
||||
parts.push(options)
|
||||
|
||||
prompt = prompt.substring(endIndex + 1)
|
||||
}
|
||||
|
||||
// Add the remaining static part
|
||||
parts.push([prompt])
|
||||
|
||||
// Get all combinations
|
||||
const combinations = getAllCombinations(parts)
|
||||
|
||||
return combinations
|
||||
}
|
||||
|
||||
const _textNodes = [
|
||||
'TextInput_',
|
||||
'CLIPTextEncode',
|
||||
'PromptSimplification',
|
||||
'ChinesePrompt_Mix'
|
||||
],
|
||||
_loraNodes = ['CheckpointLoaderSimple', 'LoraLoader'],
|
||||
_numberNodes = ['FloatSlider', 'IntNumber'],
|
||||
_slideNodes = ['PromptSlide'],
|
||||
_imageNodes = [
|
||||
'LoadImage',
|
||||
'VHS_LoadVideo',
|
||||
'ImagesPrompt_',
|
||||
'LoadImagesToBatch'
|
||||
],
|
||||
_colorNodes = ['Color'],
|
||||
_audioNodes = ['LoadAndCombinedAudio_']
|
||||
|
||||
export default {
|
||||
get_url,
|
||||
get_my_app,
|
||||
getAppInit,
|
||||
getFilenameAndCategoryFromUrl,
|
||||
success,
|
||||
interrupt,
|
||||
getQueue,
|
||||
queuePromptNew,
|
||||
savePromptResult,
|
||||
uploadImage,
|
||||
uploadMask,
|
||||
run_rembg,
|
||||
get_rembg_models,
|
||||
parseImageToBase64,
|
||||
createImage,
|
||||
convertImageToBlackBasedOnAlpha,
|
||||
blobToBase64,
|
||||
base64ToBlob,
|
||||
calculateImageHash,
|
||||
copyHtmlWithImagesToClipboard,
|
||||
copyImagesToClipboard,
|
||||
copyTextToClipboard,
|
||||
dynamicPrompts,
|
||||
generateAllCombinations,
|
||||
|
||||
_textNodes,
|
||||
_loraNodes,
|
||||
_numberNodes,
|
||||
_slideNodes,
|
||||
_imageNodes,
|
||||
_colorNodes,
|
||||
_audioNodes
|
||||
}
|
||||
@@ -199,6 +199,120 @@ app.registerExtension({
|
||||
url[id] || 'https://api.openai.com/v1'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Mixlab.GPT.SiliconflowLLM',
|
||||
async getCustomWidgets (app) {
|
||||
return {
|
||||
KEY (node, inputName, inputData, app) {
|
||||
// console.log('##inputData', inputData)
|
||||
const widget = {
|
||||
type: inputData[0], // the type, CHEESE
|
||||
name: inputName, // the name, slice
|
||||
size: [128, 32], // a default size
|
||||
draw (ctx, node, width, y) {},
|
||||
computeSize (...args) {
|
||||
return [128, 32] // a method to compute the current size of the widget
|
||||
},
|
||||
async serializeValue (nodeId, widgetIndex) {
|
||||
let data = getLocalData('_mixlab_api_key')
|
||||
return data[node.id] || 'by Mixlab'
|
||||
}
|
||||
}
|
||||
// widget.something = something; // maybe adds stuff to it
|
||||
node.addCustomWidget(widget) // adds it to the node
|
||||
return widget // and returns it.
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
async beforeRegisterNodeDef (nodeType, nodeData, app) {
|
||||
if (nodeType.comfyClass == 'SiliconflowLLM') {
|
||||
const orig_nodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
orig_nodeCreated?.apply(this, arguments)
|
||||
|
||||
const api_key = this.widgets.filter(w => w.name == 'api_key')[0]
|
||||
|
||||
const widget = {
|
||||
type: 'div',
|
||||
name: 'chatgptdiv',
|
||||
draw (ctx, node, widget_width, y, widget_height) {
|
||||
Object.assign(
|
||||
this.div.style,
|
||||
get_position_style(ctx, widget_width, api_key.y, node.size[1])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
widget.div = $el('div', {})
|
||||
|
||||
document.body.appendChild(widget.div)
|
||||
|
||||
const inputDiv = (key, placeholder) => {
|
||||
let div = document.createElement('div')
|
||||
const ip = document.createElement('input')
|
||||
ip.type = placeholder === 'Key' ? 'password' : 'text'
|
||||
ip.className = `${'comfy-multiline-input'} ${placeholder}`
|
||||
div.style = `display: flex;
|
||||
align-items: center;
|
||||
margin: 6px 8px;
|
||||
margin-top: 0;`
|
||||
ip.placeholder = placeholder
|
||||
ip.value = placeholder
|
||||
|
||||
ip.style = `margin-left: 24px;
|
||||
outline: none;
|
||||
border: none;
|
||||
padding: 4px;width: 100%;`
|
||||
const label = document.createElement('label')
|
||||
label.style = 'font-size: 10px;min-width:32px'
|
||||
label.innerText = placeholder
|
||||
div.appendChild(label)
|
||||
div.appendChild(ip)
|
||||
|
||||
ip.addEventListener('change', () => {
|
||||
let data = getLocalData(key)
|
||||
data[this.id] = ip.value.trim()
|
||||
localStorage.setItem(key, JSON.stringify(data))
|
||||
console.log(this.id, key)
|
||||
})
|
||||
return div
|
||||
}
|
||||
|
||||
let inputKey = inputDiv('_mixlab_api_key', 'Key')
|
||||
|
||||
widget.div.appendChild(inputKey)
|
||||
|
||||
this.addCustomWidget(widget)
|
||||
|
||||
const onRemoved = this.onRemoved
|
||||
this.onRemoved = () => {
|
||||
inputKey.remove()
|
||||
widget.div.remove()
|
||||
return onRemoved?.()
|
||||
}
|
||||
|
||||
this.serialize_widgets = true //需要保存参数
|
||||
}
|
||||
}
|
||||
},
|
||||
async loadedGraphNode (node, app) {
|
||||
// Fires every time a node is constructed
|
||||
// You can modify widgets/add handlers/etc here
|
||||
|
||||
if (node.type === 'SiliconflowLLM') {
|
||||
let widget = node.widgets.filter(w => w.div)[0]
|
||||
|
||||
let apiKey = getLocalData('_mixlab_api_key');
|
||||
|
||||
let id = node.id
|
||||
|
||||
widget.div.querySelector('.Key').value = apiKey[id] || 'by Mixlab'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
app.registerExtension({
|
||||
|
||||
+34
-31
@@ -100,7 +100,7 @@ async function start_llama (model = 'Phi-3-mini-4k-instruct-Q5_K_S.gguf') {
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
if (data.llama_cpp_error) {
|
||||
if (data.llama_cpp_error||!data.port) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -163,17 +163,20 @@ async function createMenu () {
|
||||
|
||||
// appsButton.onclick = () =>
|
||||
appsButton.onclick = async () => {
|
||||
if (window._mixlab_llamacpp&&window._mixlab_llamacpp.model&&window._mixlab_llamacpp.model.length>0) {
|
||||
//显示运行的模型
|
||||
createModelsModal([
|
||||
window._mixlab_llamacpp.url,
|
||||
window._mixlab_llamacpp.model
|
||||
])
|
||||
} else {
|
||||
let ms = await get_llamafile_models()
|
||||
ms = ms.filter(m => !m.match('-mmproj-'))
|
||||
if (ms.length > 0) createModelsModal(ms)
|
||||
}
|
||||
// if (window._mixlab_llamacpp&&window._mixlab_llamacpp.model&&window._mixlab_llamacpp.model.length>0) {
|
||||
// //显示运行的模型
|
||||
// createModelsModal([
|
||||
// window._mixlab_llamacpp.url,
|
||||
// window._mixlab_llamacpp.model
|
||||
// ])
|
||||
// } else {
|
||||
// // let ms = await get_llamafile_models()
|
||||
// // ms = ms.filter(m => !m.match('-mmproj-'))
|
||||
// // if (ms.length > 0) createModelsModal(ms)
|
||||
// }
|
||||
createModelsModal([
|
||||
|
||||
])
|
||||
}
|
||||
menu.append(appsButton)
|
||||
}
|
||||
@@ -932,16 +935,16 @@ function createModelsModal (models) {
|
||||
const n_gpu_p = document.createElement('p')
|
||||
n_gpu_p.innerText = 'n_gpu_layers'
|
||||
|
||||
const n_gpu_div = document.createElement('div')
|
||||
n_gpu_div.style = `display: flex;
|
||||
const batchPageBtn = document.createElement('div')
|
||||
batchPageBtn.style = `display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 12px;`
|
||||
n_gpu_div.appendChild(n_gpu_p)
|
||||
n_gpu_div.appendChild(n_gpu)
|
||||
batchPageBtn.innerHTML=`<a href="${get_url()}/mixlab/app" target="_blank" style="color: var(--input-text);
|
||||
background-color: var(--comfy-input-bg);">App</a>`
|
||||
|
||||
const title = document.createElement('p')
|
||||
title.innerText = 'Models'
|
||||
title.innerText = 'Mixlab Nodes'
|
||||
title.style = `font-size: 18px;
|
||||
margin-right: 8px;
|
||||
margin-top: 0;`
|
||||
@@ -953,9 +956,9 @@ function createModelsModal (models) {
|
||||
font-size: 12px;
|
||||
flex-direction: column; `
|
||||
left_d.appendChild(title)
|
||||
title.appendChild(statusIcon)
|
||||
left_d.appendChild(linkIcon)
|
||||
left_d.appendChild(n_gpu_div)
|
||||
// title.appendChild(statusIcon)
|
||||
// left_d.appendChild(linkIcon)
|
||||
left_d.appendChild(batchPageBtn)
|
||||
headTitleElement.appendChild(left_d)
|
||||
|
||||
// headTitleElement.appendChild(n_gpu_div)
|
||||
@@ -1010,24 +1013,24 @@ function createModelsModal (models) {
|
||||
var modalContent = document.createElement('div')
|
||||
modalContent.classList.add('modal-content')
|
||||
|
||||
var input = document.createElement('textarea')
|
||||
input.className = 'comfy-multiline-input'
|
||||
input.style = ` height: 260px;
|
||||
var inputForSystemPrompt = document.createElement('textarea')
|
||||
inputForSystemPrompt.className = 'comfy-multiline-input'
|
||||
inputForSystemPrompt.style = ` height: 260px;
|
||||
width: 480px;
|
||||
font-size: 16px;
|
||||
padding: 18px;`
|
||||
input.value = localStorage.getItem('_mixlab_system_prompt')
|
||||
inputForSystemPrompt.value = localStorage.getItem('_mixlab_system_prompt')
|
||||
|
||||
input.addEventListener('change', e => {
|
||||
inputForSystemPrompt.addEventListener('change', e => {
|
||||
e.stopPropagation()
|
||||
localStorage.setItem('_mixlab_system_prompt', input.value)
|
||||
localStorage.setItem('_mixlab_system_prompt', inputForSystemPrompt.value)
|
||||
})
|
||||
|
||||
input.addEventListener('click', e => {
|
||||
inputForSystemPrompt.addEventListener('click', e => {
|
||||
e.stopPropagation()
|
||||
})
|
||||
|
||||
modalContent.appendChild(input)
|
||||
// modalContent.appendChild(inputForSystemPrompt)
|
||||
|
||||
if (!window._mixlab_llamacpp||(window._mixlab_llamacpp?.model?.length==0)) {
|
||||
for (const m of models) {
|
||||
@@ -1040,10 +1043,10 @@ function createModelsModal (models) {
|
||||
d.addEventListener('click', async e => {
|
||||
e.stopPropagation()
|
||||
div.remove()
|
||||
startLLM(m)
|
||||
// startLLM(m)
|
||||
})
|
||||
|
||||
modalContent.appendChild(d)
|
||||
// modalContent.appendChild(d)
|
||||
}
|
||||
}
|
||||
modal.appendChild(modalContent)
|
||||
@@ -1414,7 +1417,7 @@ app.registerExtension({
|
||||
.setAttribute('title', res.url)
|
||||
})
|
||||
}else{
|
||||
startLLM('')
|
||||
// startLLM('')
|
||||
}
|
||||
|
||||
LGraphCanvas.prototype.helpAboutNode = async function (node) {
|
||||
|
||||
@@ -468,6 +468,8 @@ app.registerExtension({
|
||||
const prefix = 'vhs_gif_preview_'
|
||||
const r = onExecuted ? onExecuted.apply(this, message) : undefined
|
||||
|
||||
if(!this.widgets) this.widgets=[]
|
||||
|
||||
if (this.widgets) {
|
||||
const pos = this.widgets.findIndex(w => w.name === `${prefix}_0`)
|
||||
if (pos !== -1) {
|
||||
@@ -488,6 +490,7 @@ app.registerExtension({
|
||||
params.format || 'image/gif'
|
||||
)
|
||||
)
|
||||
console.log(w)
|
||||
w.parent = this
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user