├── LICENSE ├── README.md ├── __init__.py ├── cspnodes.py └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cspnodes 2 | A ComfyUI node pack by cerspense 3 | 4 | This package contains a collection of custom nodes for ComfyUI, designed to enhance your workflow with additional functionalities. Below is a detailed description of each node and its parameters. 5 | 6 | ## Table of Contents 7 | 8 | 1. [TextFileLineIterator](#textfilelineiterator) 9 | 2. [ImageDirIterator](#imagediriterator) 10 | 3. [VidDirIterator](#viddiriterator) 11 | 4. [Modelscopet2v](#modelscopet2v) 12 | 5. [Modelscopev2v](#modelscopev2v) 13 | 6. [SplitImageChannels](#splitimagechannels) 14 | 7. [RemapRange](#remaprange) 15 | 8. [ResizeByImage](#resizebyimage) 16 | 9. [IncrementEveryN](#incrementeveryn) 17 | 10. [DepthToNormalMap](#depthtormalmap) 18 | 19 | ## TextFileLineIterator 20 | 21 | This node iterates through lines in a text file. 22 | 23 | ### Parameters: 24 | - `file_path` (STRING): Path to the text file. 25 | - `line_index` (INT, default: 0): Index of the line to retrieve. 26 | 27 | ### Output: 28 | - (STRING): The selected line from the text file. 29 | 30 | ## ImageDirIterator 31 | 32 | This node iterates through images in a directory or multiple directories, with various sorting and selection options. 33 | 34 | ### Parameters: 35 | - `directory_path` (STRING): Path to the directory containing images. 36 | - `glob_patterns` (STRING, default: "**/*.png, **/*.jpg"): Comma-separated list of glob patterns for selecting files. 37 | - `image_index` (INT, default: 0): Starting index for image selection. 38 | - `sort_by` (["date_modified", "name", "size", "random"]): Method to sort the images. 39 | - `sort_order` (["ascending", "descending"]): Order of sorting. 40 | - `batch_size` (INT, default: 1, min: 1, max: 64): Number of images to select at once. 41 | - `increment_by_batch` (BOOLEAN, default: False): Whether to increment the index by batch size. 42 | - `randomize_final_list` (BOOLEAN, default: False): Whether to randomize the final list of images. 43 | 44 | ### Output: 45 | - (IMAGE): List of selected images. 46 | - (STRING): List of filenames for the selected images. 47 | 48 | ## VidDirIterator 49 | 50 | This node iterates through video files in a directory or multiple directories, with various sorting and selection options. 51 | 52 | ### Parameters: 53 | - `directory_path` (STRING): Path to the directory containing video files. 54 | - `glob_patterns` (STRING, default: "**/*.mp4, **/*.mov"): Comma-separated list of glob patterns for selecting files. 55 | - `video_index` (INT, default: 0): Index of the video to select. 56 | - `sort_by` (["date_modified", "name", "size", "random"]): Method to sort the videos. 57 | - `sort_order` (["ascending", "descending"]): Order of sorting. 58 | - `randomize_final_list` (BOOLEAN, default: False): Whether to randomize the final list of videos. This will allow full randomization across all specified folders and files. Otherwise, it will randomize within each folder before moving on to the next. 59 | 60 | ### Output: 61 | - (STRING): Path to the selected video file. 62 | 63 | ## Modelscopet2v 64 | 65 | This node generates video frames from text using the Modelscope text-to-video model. 66 | 67 | ### Parameters: 68 | - `prompt` (STRING): Text prompt for video generation. 69 | - `negative_prompt` (STRING, default: None): Negative prompt for generation. 70 | - `model_path` (STRING, default: "cerspense/zeroscope_v2_576w"): Path to the model. 71 | - `num_inference_steps` (INT, default: 25): Number of inference steps. 72 | - `guidance_scale` (FLOAT, default: 9.0): Guidance scale for generation. 73 | - `seed` (INT, default: 42): Seed for random generation. 74 | - `width` (INT, default: 576): Width of the generated video. 75 | - `height` (INT, default: 320): Height of the generated video. 76 | - `num_frames` (INT, default: 24): Number of frames to generate. 77 | 78 | ### Output: 79 | - (IMAGE): Generated video frames. 80 | 81 | ## Modelscopev2v 82 | 83 | This node transforms video frames using the Modelscope video-to-video model. 84 | 85 | ### Parameters: 86 | - `video_frames` (IMAGE): Input video frames. 87 | - `prompt` (STRING): Text prompt for video transformation. 88 | - `negative_prompt` (STRING, default: None): Negative prompt for transformation. 89 | - `model_path` (STRING, default: "cerspense/zeroscope_v2_XL"): Path to the model. 90 | - `strength` (FLOAT, default: 0.70): Strength of the transformation. 91 | - `num_inference_steps` (INT, default: 25): Number of inference steps. 92 | - `guidance_scale` (FLOAT, default: 8.50): Guidance scale for transformation. 93 | - `seed` (INT, default: 42): Seed for random generation. 94 | - `enable_forward_chunking` (BOOLEAN, default: False): Enable forward chunking for memory optimization. 95 | - `enable_vae_slicing` (BOOLEAN, default: True): Enable VAE slicing for memory optimization. 96 | 97 | ### Output: 98 | - (IMAGE): Transformed video frames. 99 | 100 | ## SplitImageChannels 101 | 102 | This node splits an image into its red, green, and blue channels. 103 | 104 | ### Parameters: 105 | - `image` (IMAGE): Input image to split. 106 | 107 | ### Output: 108 | - (IMAGE): Red channel as a grayscale image. 109 | - (IMAGE): Green channel as a grayscale image. 110 | - (IMAGE): Blue channel as a grayscale image. 111 | 112 | ## RemapRange 113 | 114 | This node remaps a value from one range to another. 115 | 116 | ### Parameters: 117 | - `value` (FLOAT, default: 0.0, range: -10000.0 to 10000.0): Input value to remap. 118 | - `input_min` (FLOAT, default: 0.0): Minimum of the input range. 119 | - `input_max` (FLOAT, default: 1.0): Maximum of the input range. 120 | - `output_min` (FLOAT, default: 0.0): Minimum of the output range. 121 | - `output_max` (FLOAT, default: 1.0): Maximum of the output range. 122 | - `clamp` (BOOLEAN, default: False): Whether to clamp the output to the output range. 123 | 124 | ### Output: 125 | - (FLOAT): Remapped value. 126 | 127 | ## ResizeByImage 128 | 129 | This node resizes an input image to match the dimensions of a reference image. 130 | 131 | ### Parameters: 132 | - `reference_image` (IMAGE): Image to use as a reference for resizing. 133 | - `input_image` (IMAGE, optional): Image to resize. If not provided, a black image is created. 134 | 135 | ### Output: 136 | - (IMAGE): Resized image matching the dimensions of the reference image. 137 | 138 | ## IncrementEveryN 139 | 140 | This node takes an input integer and outputs a new integer that increments every N steps of the input, with an optional offset. 141 | 142 | ### Parameters: 143 | - `input_value` (INT, default: 0, min: 0): The input integer value that is incrementing. 144 | - `step_size` (INT, default: 1, min: 1): The number of steps in the input required to increment the output by 1. 145 | - `offset` (INT, default: 0): An integer value added to the final output to offset the result. 146 | 147 | ### Output: 148 | - (INT): The incrementing output value. 149 | 150 | ### Behavior: 151 | This node divides the input value by the step size, adds the offset, and returns the integer result. For example: 152 | - If `step_size` is 6 and `offset` is 0: 153 | - Input values 0-5 will output 0 154 | - Input values 6-11 will output 1 155 | - Input values 12-17 will output 2 156 | - And so on... 157 | - If `step_size` is 6 and `offset` is 10: 158 | - Input values 0-5 will output 10 159 | - Input values 6-11 will output 11 160 | - Input values 12-17 will output 12 161 | - And so on... 162 | 163 | This node is useful for creating slower-changing values from rapidly incrementing inputs, which can be helpful in various animation and procedural generation scenarios. The offset parameter allows for further customization of the output range. 164 | 165 | 166 | ## DepthToNormalMap 167 | 168 | This node converts depth maps to normal maps, with options to control intensity, axis flipping, and depth scaling. It's designed to work consistently across different image resolutions. 169 | 170 | ### Parameters: 171 | - `depth_maps` (IMAGE): Input depth map image(s). 172 | - `normal_intensity` (FLOAT, default: 1.0, range: 0.01 to 10.0): Intensity of the normal map effect. Higher values result in more pronounced normal maps. 173 | - `flip_x` (BOOLEAN, default: True): Whether to flip the X-axis of the normal map. 174 | - `flip_y` (BOOLEAN, default: False): Whether to flip the Y-axis of the normal map. Note that the Y-axis is flipped by default in the conversion process. 175 | - `depth_scale` (FLOAT, default: 1.0, range: 0.02 to 2.0): Scaling factor for the depth values. Adjust this to match your depth map's range or to enhance subtle details. 176 | 177 | ### Output: 178 | - (IMAGE): The generated normal map(s). 179 | 180 | ### Behavior: 181 | This node takes depth map images as input and converts them to normal maps using a resolution-independent approach. The conversion process involves calculating gradients using Sobel filters, which provides better edge detection and is less sensitive to noise. 182 | 183 | Key features and notes: 184 | - The Y-axis of the normal map is flipped by default to match common normal map conventions. Use the `flip_y` option to un-flip it if necessary. 185 | - The `depth_scale` parameter allows fine-tuning of the depth range. A value of 1.0 is equivalent to a 0.2 scaling in previous versions. 186 | - The node uses a resolution-independent method, making it suitable for both low and high-resolution images. 187 | - It can handle batches of images, processing multiple depth maps in a single operation. 188 | 189 | Adjusting parameters: 190 | - Start with `normal_intensity` at 1.0 and adjust as needed. Lower values give subtler normal maps, while higher values enhance details. 191 | - Use `depth_scale` to adjust the perceived depth range. Increase it for depth maps with a narrow range of values, or decrease it if the depth variation is too extreme. 192 | - For high-resolution images, lower `normal_intensity` values often work better due to more inherent detail. 193 | - For low-resolution images, you might need to increase `normal_intensity` to make details more apparent. 194 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .cspnodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 2 | 3 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] -------------------------------------------------------------------------------- /cspnodes.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler 4 | from PIL import Image, ImageOps 5 | import numpy as np 6 | import random 7 | import torch.nn.functional as F 8 | import glob 9 | from pymediainfo import MediaInfo 10 | import json 11 | 12 | class GetMP4Prompt: 13 | @classmethod 14 | def INPUT_TYPES(cls): 15 | return { 16 | "required": { 17 | "file_path": ("STRING", {"default": ""}), 18 | "search_title": ("STRING", {"default": "finalprompt"}) 19 | } 20 | } 21 | 22 | RETURN_TYPES = ("STRING",) 23 | FUNCTION = "extract_prompt" 24 | CATEGORY = "metadata" 25 | 26 | def extract_prompt(self, file_path, search_title): 27 | # Validate file path 28 | if not os.path.exists(file_path): 29 | raise ValueError(f"File not found: {file_path}") 30 | 31 | if not file_path.lower().endswith('.mp4'): 32 | raise ValueError("File must be an MP4") 33 | 34 | media_info = MediaInfo.parse(file_path) 35 | result = "No prompt found" 36 | 37 | # Look for the comment field in the General track 38 | for track in media_info.tracks: 39 | if track.track_type == 'General' and hasattr(track, 'comment'): 40 | try: 41 | # Parse the JSON string 42 | comment_json = json.loads(track.comment) 43 | 44 | # Parse the prompt string which contains the workflow 45 | if "prompt" in comment_json: 46 | workflow_data = json.loads(comment_json["prompt"]) 47 | 48 | # Iterate through all nodes 49 | for node_id, node in workflow_data.items(): 50 | if "_meta" in node and "title" in node["_meta"]: 51 | if node["_meta"]["title"] == search_title: 52 | if "inputs" in node and "text2" in node["inputs"]: 53 | result = node["inputs"]["text2"] 54 | break 55 | 56 | except json.JSONDecodeError as e: 57 | raise ValueError(f"Error parsing JSON metadata: {str(e)}") 58 | 59 | return (result,) 60 | 61 | class ImageDirIterator: 62 | @classmethod 63 | def INPUT_TYPES(cls): 64 | return { 65 | "required": { 66 | "directory_path": ("STRING", {}), 67 | "glob_patterns": ("STRING", {"default": "**/*.png, **/*.jpg"}), 68 | "image_index": ("INT", {"default": 0}), 69 | "sort_by": (["date_modified", "name", "size", "random"],), 70 | "sort_order": (["ascending", "descending"],), 71 | "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), 72 | "increment_by_batch": ("BOOLEAN", {"default": False}), 73 | "randomize_final_list": ("BOOLEAN", {"default": False}), 74 | } 75 | } 76 | 77 | RETURN_TYPES = ("IMAGE", "MASK", "STRING") 78 | FUNCTION = "get_images_by_index" 79 | CATEGORY = "cspnodes" 80 | OUTPUT_IS_LIST = (True, True, True) 81 | 82 | def get_images_by_index(self, directory_path, glob_patterns, image_index, sort_by, sort_order, batch_size, increment_by_batch, randomize_final_list): 83 | # Split and clean the glob patterns 84 | patterns = [p.strip() for p in glob_patterns.split(',') if p.strip()] 85 | 86 | # Get list of image files including subdirectories for all patterns 87 | image_files = [] 88 | for pattern in patterns: 89 | image_files.extend(glob.glob(os.path.join(directory_path, pattern), recursive=True)) 90 | 91 | image_files = [f for f in image_files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp'))] 92 | 93 | if len(image_files) == 0: 94 | raise FileNotFoundError(f"No valid image files found in directory '{directory_path}' with patterns '{glob_patterns}'.") 95 | 96 | # Define sorting key functions 97 | sort_functions = { 98 | "date_modified": lambda x: os.path.getmtime(x), 99 | "name": lambda x: int(''.join(filter(str.isdigit, os.path.basename(x))) or 0), 100 | "size": lambda x: os.path.getsize(x), 101 | "random": lambda x: random.random(), 102 | } 103 | 104 | # Group files by subdirectory 105 | subdirs = {} 106 | for file in image_files: 107 | subdir = os.path.dirname(file) 108 | if subdir not in subdirs: 109 | subdirs[subdir] = [] 110 | subdirs[subdir].append(file) 111 | 112 | # Sort files within each subdirectory 113 | sorted_files = [] 114 | for subdir, files in subdirs.items(): 115 | if sort_by == "random": 116 | random.shuffle(files) 117 | else: 118 | files.sort(key=sort_functions[sort_by], reverse=(sort_order == "descending")) 119 | sorted_files.extend(files) 120 | 121 | # Randomize the entire list if requested 122 | if randomize_final_list: 123 | random.shuffle(sorted_files) 124 | 125 | # Calculate the starting index based on the increment_by_batch option 126 | start_index = image_index * batch_size if increment_by_batch else image_index 127 | 128 | # Wrap the index around using modulo 129 | start_index = start_index % len(sorted_files) 130 | 131 | # Select the batch of images 132 | selected_files = [sorted_files[(start_index + i) % len(sorted_files)] for i in range(batch_size)] 133 | 134 | # Load and preprocess the images 135 | images = [] 136 | masks = [] 137 | filenames = [] 138 | has_non_empty_mask = False 139 | 140 | for file in selected_files: 141 | try: 142 | i = Image.open(file) 143 | i = ImageOps.exif_transpose(i) 144 | 145 | # Handle image 146 | image = i.convert("RGB") 147 | image = np.array(image).astype(np.float32) / 255.0 148 | image = torch.from_numpy(image)[None,] 149 | images.append(image) 150 | 151 | # Handle mask 152 | if 'A' in i.getbands(): 153 | mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0 154 | mask = 1. - torch.from_numpy(mask) 155 | has_non_empty_mask = True 156 | else: 157 | mask = torch.zeros((image.shape[1], image.shape[2]), dtype=torch.float32, device="cpu") 158 | masks.append(mask) 159 | 160 | # Handle filename 161 | filename = os.path.splitext(os.path.basename(file))[0] 162 | filename = filename.encode('utf-8').decode('unicode_escape') 163 | filenames.append(filename) 164 | except Exception as e: 165 | print(f"Error loading image {file}: {str(e)}") 166 | 167 | if len(images) == 1: 168 | return (images, [masks[0]], filenames) 169 | elif len(images) > 1: 170 | image_batch = torch.cat(images, dim=0) 171 | 172 | # Process masks 173 | if has_non_empty_mask: 174 | processed_masks = [] 175 | for mask in masks: 176 | if image_batch.shape[1:3] != mask.shape: 177 | mask = torch.nn.functional.interpolate( 178 | mask.unsqueeze(0).unsqueeze(0), 179 | size=(image_batch.shape[1], image_batch.shape[2]), 180 | mode='bilinear', 181 | align_corners=False 182 | ).squeeze(0) 183 | processed_masks.append(mask) 184 | else: 185 | processed_masks = masks 186 | 187 | return (images, processed_masks, filenames) 188 | 189 | return ([], [], []) 190 | 191 | 192 | class VidDirIterator: 193 | @classmethod 194 | def INPUT_TYPES(cls): 195 | return { 196 | "required": { 197 | "directory_path": ("STRING", {}), 198 | "glob_patterns": ("STRING", {"default": "**/*.mp4, **/*.mov"}), 199 | "video_index": ("INT", {"default": 0}), 200 | "sort_by": (["date_modified", "name", "size", "random"],), 201 | "sort_order": (["ascending", "descending"],), 202 | "randomize_final_list": ("BOOLEAN", {"default": False}), 203 | } 204 | } 205 | 206 | RETURN_TYPES = ("STRING",) 207 | FUNCTION = "get_video_path_by_index" 208 | CATEGORY = "cspnodes" 209 | 210 | def get_video_path_by_index(self, directory_path, glob_patterns, video_index, sort_by, sort_order, randomize_final_list): 211 | # Split and clean the glob patterns 212 | patterns = [p.strip() for p in glob_patterns.split(',') if p.strip()] 213 | 214 | # Get list of video files including subdirectories for all patterns 215 | video_files = [] 216 | for pattern in patterns: 217 | video_files.extend(glob.glob(os.path.join(directory_path, pattern), recursive=True)) 218 | 219 | video_files = [f for f in video_files if f.lower().endswith(('.mov', '.mp4'))] 220 | 221 | if len(video_files) == 0: 222 | raise FileNotFoundError(f"No valid video files found in directory '{directory_path}' with patterns '{glob_patterns}'.") 223 | 224 | # Define sorting key functions 225 | sort_functions = { 226 | "date_modified": lambda x: os.path.getmtime(x), 227 | "name": lambda x: int(''.join(filter(str.isdigit, os.path.basename(x))) or 0), 228 | "size": lambda x: os.path.getsize(x), 229 | "random": lambda x: random.random(), 230 | } 231 | 232 | # Sort the video files 233 | if sort_by == "random": 234 | random.shuffle(video_files) 235 | else: 236 | video_files.sort(key=sort_functions[sort_by], reverse=(sort_order == "descending")) 237 | 238 | # Randomize the entire list if requested 239 | if randomize_final_list: 240 | random.shuffle(video_files) 241 | 242 | # Wrap the index around using modulo 243 | video_index = video_index % len(video_files) 244 | 245 | # Return the video file path as a string 246 | return (video_files[video_index],) 247 | 248 | class Modelscopet2v: 249 | @classmethod 250 | def INPUT_TYPES(cls): 251 | return { 252 | "required": { 253 | "prompt": ("STRING", {}), 254 | "negative_prompt": ("STRING", {"default": None}), 255 | "model_path": ("STRING", {"default": "cerspense/zeroscope_v2_576w"}), 256 | "num_inference_steps": ("INT", {"default": 25}), 257 | "guidance_scale": ("FLOAT", {"default": 9.0}), 258 | "seed": ("INT", {"default": 42}), 259 | "width": ("INT", {"default": 576}), 260 | "height": ("INT", {"default": 320}), 261 | "num_frames": ("INT", {"default": 24}), 262 | } 263 | } 264 | 265 | RETURN_TYPES = ("IMAGE",) 266 | FUNCTION = "generate_video_frames" 267 | CATEGORY = "cspnodes/modelscope" 268 | 269 | def generate_video_frames(self, prompt, model_path, num_inference_steps, height, width, num_frames, guidance_scale, negative_prompt, seed): 270 | # Set up the generator for deterministic results if seed is provided 271 | generator = torch.Generator() 272 | if seed is not None: 273 | generator.manual_seed(seed) 274 | 275 | pipe = DiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16) 276 | pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) 277 | pipe.enable_model_cpu_offload() 278 | 279 | # Added generator to the pipe call 280 | video_frames = pipe(prompt, num_inference_steps=num_inference_steps, height=height, width=width, num_frames=num_frames, guidance_scale=guidance_scale, negative_prompt=negative_prompt, generator=generator).frames 281 | 282 | # Ensure video_frames is a PyTorch tensor 283 | if not isinstance(video_frames, torch.Tensor): 284 | video_frames = torch.tensor(video_frames, dtype=torch.float32) 285 | 286 | # Normalize the tensor to have values between 0 and 1 if they are in the range 0-255 287 | if video_frames.max() > 1.0: 288 | video_frames = video_frames / 255.0 289 | 290 | # Remove the unnecessary batch dimension explicitly and permute the dimensions 291 | # The expected shape is (num_frames, height, width, channels) 292 | video_frames = video_frames.squeeze(0).permute(0, 1, 2, 3) 293 | 294 | # Convert the tensor to CPU and to uint8 if it's not already 295 | video_frames = video_frames.to('cpu') 296 | 297 | # return (video_frames_numpy,) 298 | return (video_frames,) 299 | 300 | class Modelscopev2v: 301 | @classmethod 302 | def INPUT_TYPES(cls): 303 | return { 304 | "required": { 305 | "video_frames": ("IMAGE", {}), 306 | "prompt": ("STRING", {}), 307 | "negative_prompt": ("STRING", {"default": None}), 308 | "model_path": ("STRING", {"default": "cerspense/zeroscope_v2_XL"}), 309 | "strength": ("FLOAT", {"default": 0.70}), 310 | "num_inference_steps": ("INT", {"default": 25}), 311 | "guidance_scale": ("FLOAT", {"default": 8.50}), 312 | "seed": ("INT", {"default": 42}), 313 | "enable_forward_chunking": ("BOOLEAN", {"default": False}), 314 | "enable_vae_slicing": ("BOOLEAN", {"default": True}), 315 | } 316 | } 317 | 318 | RETURN_TYPES = ("IMAGE",) 319 | FUNCTION = "transform_video_frames" 320 | CATEGORY = "cspnodes/modelscope" 321 | 322 | def transform_video_frames(self, video_frames, prompt, model_path, strength, num_inference_steps, guidance_scale, negative_prompt, seed, enable_forward_chunking, enable_vae_slicing): 323 | # Set up the generator for deterministic results if seed is provided 324 | generator = torch.Generator() 325 | if seed is not None: 326 | generator.manual_seed(seed) 327 | 328 | # Initialize the diffusion pipeline with the specified model path 329 | pipe = DiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16) 330 | pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) 331 | pipe.enable_model_cpu_offload() 332 | 333 | # Apply memory optimizations based on the toggles 334 | if enable_forward_chunking: 335 | pipe.unet.enable_forward_chunking(chunk_size=1, dim=1) 336 | if enable_vae_slicing: 337 | pipe.enable_vae_slicing() 338 | 339 | # Convert tensor to list of PIL Images 340 | # Assuming video_frames is a float tensor with values in [0, 1] 341 | video_frames_uint8 = (video_frames * 255).byte() 342 | video = [Image.fromarray(frame.numpy(), 'RGB') for frame in video_frames_uint8] 343 | 344 | # Generate new video frames 345 | video_frames = pipe(prompt, video=video, strength=strength, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, negative_prompt=negative_prompt, generator=generator).frames 346 | 347 | # Ensure video_frames is a PyTorch tensor 348 | if not isinstance(video_frames, torch.Tensor): 349 | video_frames = torch.tensor(video_frames, dtype=torch.float32) 350 | 351 | # Normalize the tensor to have values between 0 and 1 if they are in the range 0-255 352 | if video_frames.max() > 1.0: 353 | video_frames = video_frames / 255.0 354 | 355 | # The expected shape is (num_frames, height, width, channels) 356 | video_frames = video_frames.squeeze(0).permute(0, 1, 2, 3) 357 | 358 | # Convert the tensor to CPU and to uint8 if it's not already 359 | video_frames = video_frames.to('cpu') 360 | 361 | # return (video_frames_numpy,) 362 | return (video_frames,) 363 | 364 | class SplitImageChannels: 365 | @classmethod 366 | def INPUT_TYPES(cls): 367 | return { 368 | "required": { 369 | "image": ("IMAGE", {}), 370 | } 371 | } 372 | 373 | RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE") 374 | FUNCTION = "split_channels" 375 | CATEGORY = "cspnodes" 376 | 377 | def split_channels(self, image): 378 | # Split the image into red, green, and blue channels 379 | red_channel = image[:, :, :, 0] 380 | green_channel = image[:, :, :, 1] 381 | blue_channel = image[:, :, :, 2] 382 | 383 | # Convert each channel to a black and white image 384 | red_bw = torch.stack([red_channel, red_channel, red_channel], dim=-1) 385 | green_bw = torch.stack([green_channel, green_channel, green_channel], dim=-1) 386 | blue_bw = torch.stack([blue_channel, blue_channel, blue_channel], dim=-1) 387 | 388 | return red_bw, green_bw, blue_bw 389 | 390 | class RemapRange: 391 | @classmethod 392 | def INPUT_TYPES(cls): 393 | return { 394 | "required": { 395 | "value": ("FLOAT", {"default": 0.0, "min": -10000.0, "max": 10000.0, "step": 0.01}), 396 | "input_min": ("FLOAT", {"default": 0.0, "step": 0.01}), 397 | "input_max": ("FLOAT", {"default": 1.0, "step": 0.01}), 398 | "output_min": ("FLOAT", {"default": 0.0, "step": 0.01}), 399 | "output_max": ("FLOAT", {"default": 1.0, "step": 0.01}), 400 | "clamp": ("BOOLEAN", {"default": False}), 401 | } 402 | } 403 | 404 | RETURN_TYPES = ("FLOAT",) 405 | FUNCTION = "remap_value" 406 | CATEGORY = "cspnodes" 407 | 408 | def remap_value(self, value, input_min, input_max, output_min, output_max, clamp): 409 | # Calculate the input and output ranges 410 | input_range = input_max - input_min 411 | output_range = output_max - output_min 412 | 413 | # Perform the remapping 414 | if input_range == 0: 415 | remapped = output_min 416 | else: 417 | remapped = ((value - input_min) / input_range) * output_range + output_min 418 | 419 | # Clamp the output if requested 420 | if clamp: 421 | remapped = max(min(remapped, output_max), output_min) 422 | 423 | return (remapped,) 424 | 425 | class ResizeByImage: 426 | @classmethod 427 | def INPUT_TYPES(cls): 428 | return { 429 | "required": { 430 | "reference_image": ("IMAGE",), 431 | }, 432 | "optional": { 433 | "input_image": ("IMAGE",), 434 | } 435 | } 436 | 437 | RETURN_TYPES = ("IMAGE",) 438 | FUNCTION = "resize_image" 439 | CATEGORY = "cspnodes" 440 | 441 | def resize_image(self, reference_image, input_image=None): 442 | # Get the dimensions of the reference image 443 | _, height, width, _ = reference_image.shape 444 | 445 | if input_image is None: 446 | # Create a black image batch if no input is provided 447 | resized_image = torch.zeros_like(reference_image) 448 | else: 449 | # Resize the input image batch to match the reference image dimensions 450 | # Convert from (batch, height, width, channels) to (batch, channels, height, width) 451 | input_image = input_image.permute(0, 3, 1, 2) 452 | 453 | # Perform the resize operation on the entire batch 454 | resized_image = F.interpolate(input_image, size=(height, width), mode='bilinear', align_corners=False) 455 | 456 | # Convert back to (batch, height, width, channels) 457 | resized_image = resized_image.permute(0, 2, 3, 1) 458 | 459 | return (resized_image,) 460 | 461 | class IncrementEveryN: 462 | @classmethod 463 | def INPUT_TYPES(cls): 464 | return { 465 | "required": { 466 | "input_value": ("INT", {"default": 0, "min": 0, "step": 1}), 467 | "step_size": ("INT", {"default": 1, "min": 1, "step": 1}), 468 | "offset": ("INT", {"default": 0, "step": 1}), 469 | } 470 | } 471 | 472 | RETURN_TYPES = ("INT",) 473 | FUNCTION = "increment_every_n" 474 | CATEGORY = "cspnodes" 475 | 476 | def increment_every_n(self, input_value, step_size, offset): 477 | output_value = (input_value // step_size) + offset 478 | return (output_value,) 479 | 480 | import torch 481 | import torch.nn.functional as F 482 | 483 | class DepthToNormalMap: 484 | @classmethod 485 | def INPUT_TYPES(cls): 486 | return { 487 | "required": { 488 | "depth_maps": ("IMAGE",), 489 | "normal_intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 10.0, "step": 0.01}), 490 | "flip_x": ("BOOLEAN", {"default": True}), 491 | "flip_y": ("BOOLEAN", {"default": False}), # Changed to False as it's now flipped by default 492 | "depth_scale": ("FLOAT", {"default": 1.0, "min": 0.02, "max": 2.0, "step": 0.01}), 493 | } 494 | } 495 | 496 | RETURN_TYPES = ("IMAGE",) 497 | FUNCTION = "convert_depth_to_normal" 498 | CATEGORY = "cspnodes" 499 | 500 | def convert_depth_to_normal(self, depth_maps, normal_intensity, flip_x, flip_y, depth_scale): 501 | # Ensure depth_maps is a float tensor and normalize to [0, 1] 502 | depth_maps = depth_maps.float() 503 | if depth_maps.max() > 1.0: 504 | depth_maps = depth_maps / 255.0 505 | 506 | # Extract only the first channel if the input has multiple channels 507 | if depth_maps.shape[-1] > 1: 508 | depth_maps = depth_maps[..., 0].unsqueeze(-1) 509 | 510 | # Apply depth scale (divided by 5 to make 1.0 equivalent to the previous 0.2) 511 | depth_maps = depth_maps * (depth_scale / 5) 512 | 513 | # Calculate pixel size based on image dimensions 514 | height, width = depth_maps.shape[1:3] 515 | pixel_size_y = 1.0 / height 516 | pixel_size_x = 1.0 / width 517 | 518 | # Compute gradients using Sobel filters 519 | sobel_x = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32).view(1, 1, 3, 3).to(depth_maps.device) 520 | sobel_y = torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=torch.float32).view(1, 1, 3, 3).to(depth_maps.device) 521 | 522 | grad_x = F.conv2d(depth_maps.permute(0, 3, 1, 2), sobel_x, padding=1) / (8.0 * pixel_size_x) 523 | grad_y = F.conv2d(depth_maps.permute(0, 3, 1, 2), sobel_y, padding=1) / (8.0 * pixel_size_y) 524 | 525 | # Reshape gradients to match input shape 526 | grad_x = grad_x.permute(0, 2, 3, 1) 527 | grad_y = grad_y.permute(0, 2, 3, 1) 528 | 529 | # Create normal map (note the flipped Y-axis by default) 530 | normal_maps = torch.cat([-grad_x * normal_intensity, 531 | grad_y * normal_intensity, # Removed the negative sign to flip Y by default 532 | torch.ones_like(grad_x)], dim=-1) 533 | 534 | # Normalize 535 | normal_maps = F.normalize(normal_maps, p=2, dim=-1) 536 | 537 | # Flip axes if requested 538 | if flip_x: 539 | normal_maps[..., 0] *= -1 540 | if flip_y: 541 | normal_maps[..., 1] *= -1 # This will now un-flip the Y-axis if set to True 542 | 543 | # Scale to [0, 1] range 544 | normal_maps = (normal_maps + 1) / 2 545 | 546 | return (normal_maps,) 547 | 548 | NODE_CLASS_MAPPINGS = { 549 | "GetMP4Prompt": GetMP4Prompt, 550 | "DepthToNormalMap": DepthToNormalMap, 551 | "IncrementEveryN": IncrementEveryN, 552 | "ResizeByImage": ResizeByImage, 553 | "SplitImageChannels": SplitImageChannels, 554 | "RemapRange": RemapRange, 555 | "ImageDirIterator": ImageDirIterator, 556 | "VidDirIterator": VidDirIterator, 557 | "Modelscopet2v": Modelscopet2v, 558 | "Modelscopev2v": Modelscopev2v, 559 | } 560 | 561 | NODE_DISPLAY_NAME_MAPPINGS = { 562 | "GetMP4Prompt": "Get MP4 Prompt", 563 | "DepthToNormalMap": "Depth to Normal Map", 564 | "IncrementEveryN": "Increment Every N", 565 | "ResizeByImage": "Resize By Image", 566 | "SplitImageChannels": "Split Image Channels", 567 | "RemapRange": "Remap Range", 568 | "ImageDirIterator": "Image Dir Iterator", 569 | "VidDirIterator": "Vid Dir Iterator", 570 | "Modelscopet2v": "Modelscope t2v", 571 | "Modelscopev2v": "Modelscope v2v", 572 | } 573 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | diffusers 2 | pymediainfo --------------------------------------------------------------------------------