Please help me write a comfyui plugin with the function of downloading model files from Hugging Face and Modelscope
Assistant
User
Please help me write a comfyui custom node with the ability to download model files from Hugging Face and Modelscope
Assistant
Creating a plugin for ComfyUI that facilitates downloading model files from Hugging Face and Modelscope requires an understanding of both the ComfyUI architecture and the APIs provided by Hugging Face and Modelscope. Below, I’ll guide you through the process of creating a basic plugin. This will be a simplified version and won’t cover all the intricate details, but it should provide a solid foundation.
Prerequisites
Python Environment: Ensure you have a Python environment set up.
ComfyUI Knowledge: Understanding how plugins work within ComfyUI.
APIs Access: Ensure you have API access to both Hugging Face and Modelscope if required.
Step 1: Setting Up Your Plugin
Create a new directory for your plugin, for example, comfyui_plugin.
Step 2: Install Necessary Packages
You'll need to install the requests package to handle HTTP requests:
bash
pip install requests
Step 3: Create a Basic Plugin Structure
Create the necessary files in your plugin directory.
comfyui_plugin/__init__.py:
python
from .download import download_model
def init_plugin():
print("ComfyUI Plugin Initialized: Hugging Face and Modelscope Downloader")
comfyui_plugin/download.py:
python
import requests
import os
def download_file(url, dest_folder):
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
response = requests.get(url, stream=True)
filename = os.path.join(dest_folder, url.split('/')[-1])
with open(filename, 'wb') as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
return filename
def download_huggingface_model(model_name, dest_folder='models'):
base_url = f"https://huggingface.co/{model_name}/resolve/main/"
# Example suffix, this might change based on your needs
file_list = ["model.bin", "config.json", "vocab.txt"]
for file_name in file_list:
url = base_url + file_name
print(f"Downloading {file_name} from Hugging Face.")
download_file(url, dest_folder)
def download_modelscope_model(model_name, dest_folder='models'):
base_url = f"https://modelscope.example.com/{model_name}/"
# Example suffix, this might change based on your needs
file_list = ["checkpoint.pt", "config.yaml"]
for file_name in file_list:
url = base_url + file_name
print(f"Downloading {file_name} from Modelscope.")
download_file(url, dest_folder)
Step 4: Integrate with ComfyUI
You need to make sure your plugin is loaded by ComfyUI. This is typically done by placing your comfyui_plugin directory into a plugins directory which ComfyUI scans for plugins.
Step 5: Test the Plugin
Make sure to test your plugin by running ComfyUI and verifying that the model files are downloaded correctly when you call:
python
from comfyui_plugin import download_huggingface_model, download_modelscope_model
download_huggingface_model("bert-base-uncased")
download_modelscope_model("example-model")
Note
API Authentication: Depending on the model repository settings, you may need to authenticate your requests using an API key or OAuth token for private models.
Error Handling: It's important to add error handling in production code to deal with network issues or unexpected API changes.
Updates and Compatibility: Ensure that you keep your plugin updated with any changes to the ComfyUI architecture or the models' repositories.
Final Thoughts
This basic plugin structure provides a starting point. Ensure you tailor the script to the specific model files you need and include any additional functionality or error handling as per the requirements of your application.
Creating a custom node for ComfyUI that downloads model files from Hugging Face and Modelscope involves understanding both the node structure of ComfyUI and the methods to interact with external APIs. Below is a simplified guide to help you develop a basic custom node for this purpose.
Prerequisites
ComfyUI Environment: Ensure you have ComfyUI set up and understand its basic structure.
Python Environment: Make sure you have a functioning Python environment.
API Access: You might need access credentials for Hugging Face and Modelscope, especially for private models.
Step-by-Step Guide
Step 1: Install Necessary Python Packages
If you haven't already, you need requests to handle HTTP requests:
bash
pip install requests
Step 2: Set Up Your Node Module
Create a directory called comfyui_custom_nodes (or any name you prefer) within the ComfyUI environment.
Step 3: Create the Custom Node
In your new directory, create a Python file, e.g., model_downloader_node.py, and add the following code.
python
import requests
from comfyui import Node
class ModelDownloaderNode(Node):
def __init__(self):
super().__init__()
# Node metadata
self.node_name = "Model Downloader"
self.node_description = "Downloads model files from Hugging Face and Modelscope."
# Node inputs and outputs declaration
self.add_input("source", "select", options=["Hugging Face", "Modelscope"])
self.add_input("model_name", "string")
self.add_output("status", "string")
def process(self, inputs):
source = inputs["source"]
model_name = inputs["model_name"]
if source == "Hugging Face":
status = self.download_huggingface_model(model_name)
elif source == "Modelscope":
status = self.download_modelscope_model(model_name)
else:
status = "Invalid source."
self.set_output("status", status)
def download_file(self, url, dest_folder):
if not os.path.exists(dest_folder):
os.makedirs(dest_folder)
response = requests.get(url, stream=True)
file_name = os.path.join(dest_folder, url.split('/')[-1])
with open(file_name, 'wb') as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
file.write(chunk)
return file_name
def download_huggingface_model(self, model_name, dest_folder='models'):
base_url = f"https://huggingface.co/{model_name}/resolve/main/"
# Define the file list according to your requirements
file_list = ["pytorch_model.bin", "config.json"]
try:
for file_name in file_list:
print(f"Downloading {file_name} from Hugging Face.")
self.download_file(base_url + file_name, dest_folder)
return f"Downloaded {model_name} from Hugging Face."
except Exception as e:
return f"Failed to download from Hugging Face: {str(e)}"
def download_modelscope_model(self, model_name, dest_folder='models'):
base_url = f"https://modelscope.example.com/{model_name}/"
# Define the file list according to your requirements
file_list = ["checkpoint.pt", "config.yaml"]
try:
for file_name in file_list:
print(f"Downloading {file_name} from Modelscope.")
self.download_file(base_url + file_name, dest_folder)
return f"Downloaded {model_name} from Modelscope."
except Exception as e:
return f"Failed to download from Modelscope: {str(e)}"
def register_node():
return ModelDownloaderNode()
Step 4: Integrate with ComfyUI
Register Your Node: Ensure that ComfyUI recognizes your custom node by adding it to the main script or wherever ComfyUI loads the nodes. Typically, this involves the following steps:
Copy the model_downloader_node.py into the ComfyUI nodes folder or ensure the scanning path includes your directory.
Ensure that when ComfyUI starts, it registers your node through the register_node() function.
Step 5: Test Your Node
Run ComfyUI and ensure your custom node appears in the user interface. Test it by selecting sources and model names, observing the download output.
Final Thoughts
Error handling, logging, and specific details might be added or adjusted as per your system requirements and models used. Depending on their availability, you might need credentials or additional error handling to cater to network or permission issues.
Make sure to keep the endpoints and file lists updated as per the respective documentation of Hugging Face and Modelscope APIs. Adjust the node inputs and outputs to fit any specific workflows you have in mind.