Repository: yuvraj108c/ComfyUI-Whisper Branch: master Commit: 74aa5a217b1c Files: 14 Total size: 64.3 KB Directory structure: gitextract_roxluuhh/ ├── .github/ │ └── workflows/ │ └── publish.yml ├── .gitignore ├── LICENSE ├── __init__.py ├── add_subtitles_to_background.py ├── add_subtitles_to_frames.py ├── apply_whisper.py ├── example_workflows/ │ └── whisper_video_subtitles_workflow.json ├── pyproject.toml ├── readme.md ├── requirements.txt ├── resize_cropped_subtitles.py ├── save_srt.py └── utils.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish to Comfy registry on: workflow_dispatch: push: branches: - main paths: - "pyproject.toml" jobs: publish-node: name: Publish Custom Node to registry runs-on: ubuntu-latest steps: - name: Check out code uses: actions/checkout@v4 - name: Publish Custom Node uses: Comfy-Org/publish-node-action@main with: ## Add your own personal access token to your Github Repository secrets and reference it here. personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ================================================ FILE: .gitignore ================================================ __pycache__ .DS_Store ================================================ FILE: LICENSE ================================================ Attribution-NonCommercial-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: __init__.py ================================================ from .apply_whisper import ApplyWhisperNode from .add_subtitles_to_frames import AddSubtitlesToFramesNode from .add_subtitles_to_background import AddSubtitlesToBackgroundNode from .resize_cropped_subtitles import ResizeCroppedSubtitlesNode from .save_srt import SaveSRTNode NODE_CLASS_MAPPINGS = { "Apply Whisper" : ApplyWhisperNode, "Add Subtitles To Frames": AddSubtitlesToFramesNode, "Add Subtitles To Background": AddSubtitlesToBackgroundNode, "Resize Cropped Subtitles": ResizeCroppedSubtitlesNode, "Save SRT": SaveSRTNode } NODE_DISPLAY_NAME_MAPPINGS = { "Apply Whisper" : "Apply Whisper", "Add Subtitles To Frames": "Add Subtitles To Frames", "Add Subtitles To Background": "Add Subtitles To Background", "Resize Cropped Subtitles": "Resize Cropped Subtitles", "Save SRT": "Save SRT" } __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] ================================================ FILE: add_subtitles_to_background.py ================================================ from PIL import ImageDraw, ImageFont, Image from .utils import pil2tensor,tensor2pil import math import os import random FONT_DIR = os.path.join(os.path.dirname(__file__),"fonts") class AddSubtitlesToBackgroundNode: @classmethod def INPUT_TYPES(s): return { "required": { "images": ("IMAGE",), "alignment" : ("whisper_alignment",), "font_family": (os.listdir(FONT_DIR),), "num_words": ("INT",{ "default": 25, "step":1, "display": "number" }), "text_displacement": ("INT",{ "default": 10, "step":1, "display": "number" }), "font_size_displacement": ("INT",{ "default": 3, "step":1, "display": "number" }), "min_font_size": ("INT",{ "default": 15, "step":1, "display": "number" }), "max_font_size": ("INT",{ "default": 75, "step":1, "display": "number" }), "video_fps": ("FLOAT",{ "default": 24.0, "step":1, "display": "number" }), } } RETURN_TYPES = ("IMAGE",) RETURN_NAMES = ("IMAGE",) FUNCTION = "add_subtitles_to_background" CATEGORY = "whisper" def add_subtitles_to_background(self, images, alignment, font_family, text_displacement, font_size_displacement,num_words, min_font_size, max_font_size, video_fps): pil_images = tensor2pil(images) frame_width, frame_height = pil_images[0].size bg_image = Image.new("RGB", (frame_width, frame_height), (255, 255, 255)) background_color = (0, 0, 0) text_color = (255,255,255) # Randomly scatter the initial (x, y) positions and font sizes within the image size positions = [(random.randint(0, frame_width - 100), random.randint(0, frame_height - 30)) for _ in range(num_words)] # create N font sizes in defined range font_sizes = [random.randint(min_font_size, max_font_size) for _ in range(100)] final_pil_images = [] if len(alignment) == 0: bg_image = Image.new("RGB", (frame_width, frame_height), background_color) final_pil_images.extend([bg_image]*len(pil_images)) last_frame_no = 0 for x in range(len(alignment)): alignment_obj = alignment[x] start_frame_no = math.floor(alignment_obj["start"] * video_fps) end_frame_no = math.floor(alignment_obj["end"] * video_fps) word = alignment_obj["value"] # create images with no texts for _ in range(last_frame_no, start_frame_no): bg_image = Image.new("RGB", (frame_width, frame_height), background_color) final_pil_images.append(bg_image) for _ in range(start_frame_no,end_frame_no): # Create a blank frame with background color bg_image = Image.new("RGB", (frame_width, frame_height), background_color) draw = ImageDraw.Draw(bg_image) # Create new lists to store the updated positions and font sizes updated_positions = [] updated_font_sizes = [] # Loop to add text at (x, y) positions and sizes without overlapping for i, pos in enumerate(positions): x, y = pos # Unpack the (x, y) position from the tuple # Randomly choose a direction (up, down, left, or right) and apply displacement direction = random.choice(["up", "down", "left", "right"]) if direction == "up": y -= text_displacement elif direction == "down": y += text_displacement elif direction == "left": x -= text_displacement elif direction == "right": x += text_displacement # Ensure that the new (x, y) positions stay within the image boundaries x = max(0, min(x, frame_width - 100)) y = max(0, min(y, frame_height - 30)) # Randomly add/subtract X pixels from the font size font_size = font_sizes[i] + random.choice([-font_size_displacement, font_size_displacement]) font_size = int(max(min_font_size, min(font_size, max_font_size))) # Ensure font size is within the desired range # Calculate the text bounding box font = ImageFont.truetype(os.path.join(FONT_DIR,font_family), size=font_size) text_bbox = draw.textbbox((x, y), word, font=font) # Collision detection: Check if the current text box intersects with any previously added text boxes overlap = any( ( x1 < text_bbox[2] and x2 > text_bbox[0] and y1 < text_bbox[3] and y2 > text_bbox[1] ) for x1, y1, x2, y2 in updated_positions ) # Use a while loop to keep trying to place the word until no overlap is detected while overlap: # Randomly adjust the position and font size x, y = random.randint(0, frame_width - 100), random.randint(0, frame_height - 30) font_size = int(random.randint(min_font_size, max_font_size)) # Recalculate the text bounding box font = ImageFont.truetype(os.path.join(FONT_DIR,font_family), size=font_size) text_bbox = draw.textbbox((x, y), word, font=font) # Check for overlap again overlap = any( ( x1 < text_bbox[2] and x2 > text_bbox[0] and y1 < text_bbox[3] and y2 > text_bbox[1] ) for x1, y1, x2, y2 in updated_positions ) # Add the word to the frame and update the used positions and font sizes lists draw.text((x, y), word, fill=text_color, font=font) updated_positions.append((x, y, text_bbox[2], text_bbox[3])) updated_font_sizes.append(font_size) # Update the positions and font sizes lists with the new positions and font sizes positions = [(x1, y1) for x1, y1, _, _ in updated_positions] font_sizes = updated_font_sizes final_pil_images.append(bg_image) bg_image = Image.new("RGB", (frame_width, frame_height), text_color) last_frame_no = end_frame_no # create missing black images at the end missing_frames_count = len(pil_images) - len(final_pil_images) for _ in range(missing_frames_count): bg_image = Image.new("RGB", (frame_width, frame_height), background_color) final_pil_images.append(bg_image) tensor_images = pil2tensor(final_pil_images) return (tensor_images,) ================================================ FILE: add_subtitles_to_frames.py ================================================ from PIL import ImageDraw, ImageFont, Image from .utils import tensor2pil, pil2tensor, tensor2Mask import math import os FONT_DIR = os.path.join(os.path.dirname(__file__),"fonts") class AddSubtitlesToFramesNode: @classmethod def INPUT_TYPES(s): return { "required": { "images": ("IMAGE",), "alignment" : ("whisper_alignment",), "font_color": ("STRING",{ "default": "white" }), "font_family": (os.listdir(FONT_DIR),), "font_size": ("INT",{ "default": 100, "step":5, "display": "number" }), "x_position": ("INT",{ "default": 100, "step":50, "display": "number" }), "y_position": ("INT",{ "default": 100, "step":50, "display": "number" }), "center_x": ("BOOLEAN", {"default": True}), "center_y": ("BOOLEAN", {"default": True}), "video_fps": ("FLOAT",{ "default": 24.0, "step":1, "display": "number" }), } } RETURN_TYPES = ("IMAGE", "MASK", "IMAGE", "subtitle_coord", ) RETURN_NAMES = ("IMAGE","MASK", "cropped_subtitles","subtitle_coord",) FUNCTION = "add_subtitles_to_frames" CATEGORY = "whisper" def add_subtitles_to_frames(self, images, alignment, font_family, font_size, font_color, x_position, y_position, center_x, center_y, video_fps): pil_images = tensor2pil(images) pil_images_with_text = [] cropped_pil_images_with_text = [] pil_images_masks = [] subtitle_coord = [] font = ImageFont.truetype(os.path.join(FONT_DIR,font_family), font_size) if len(alignment) == 0: pil_images_with_text = pil_images cropped_pil_images_with_text = pil_images subtitle_coord.extend([(0,0,0,0)]*len(pil_images)) # create mask width, height = pil_images[0].size black_img = Image.new('RGB', (width, height), 'black') pil_images_masks.extend([black_img]*len(pil_images)) last_frame_no = 0 for i in range(len(alignment)): alignment_obj = alignment[i] start_frame_no = math.floor(alignment_obj["start"] * video_fps) end_frame_no = math.floor(alignment_obj["end"] * video_fps) # create images without text for i in range(last_frame_no, start_frame_no): img = pil_images[i].convert("RGB") width, height = img.size pil_images_with_text.append(img) # create mask + cropped image black_img = Image.new('RGB', (width, height), 'black') pil_images_masks.append(black_img) black_img = Image.new('RGB', (1, 1), 'black') # to prevent max() from considering these images, use very small size cropped_pil_images_with_text.append(black_img) subtitle_coord.append((0,0,0,0)) for i in range(start_frame_no,end_frame_no): img = pil_images[i].convert("RGB") width, height = img.size d = ImageDraw.Draw(img) # center text text_bbox = d.textbbox((x_position, y_position), alignment_obj["value"], font=font) if center_x: text_width = text_bbox[2] - text_bbox[0] x_position = (width - text_width)/2 if center_y: text_height = text_bbox[3] - text_bbox[1] y_position = (height - text_height)/2 # add text to video frames d.text((x_position, y_position), alignment_obj["value"], fill=font_color,font=font) pil_images_with_text.append(img) # create mask black_img = Image.new('RGB', (width, height), 'black') d = ImageDraw.Draw(black_img) d.text((x_position, y_position), alignment_obj["value"], fill="white",font=font) pil_images_masks.append(black_img) # crop subtitles to black frame text_bbox = d.textbbox((x_position,y_position), alignment_obj["value"], font=font) cropped_text_frame = black_img.crop(text_bbox) cropped_pil_images_with_text.append(cropped_text_frame) subtitle_coord.append(text_bbox) last_frame_no = end_frame_no # add missing frames with no text at end for i in range(len(pil_images_with_text),len(pil_images)): pil_images_with_text.append(pil_images[i]) width,height = pil_images[i].size # create mask + cropped image black_img = Image.new('RGB', (width, height), 'black') pil_images_masks.append(black_img) black_img = Image.new('RGB', (1, 1), 'black') # to prevent max() from considering these images, use very small size cropped_pil_images_with_text.append(black_img) subtitle_coord.append((0,0,0,0)) # make cropped images same size cropped_pil_images_with_text_normalised = [] max_width = max(img.width for img in cropped_pil_images_with_text) max_height = max(img.height for img in cropped_pil_images_with_text) for img in cropped_pil_images_with_text: blank_frame = Image.new("RGB", (max_width, max_height), "black") blank_frame.paste(img, (0,0)) cropped_pil_images_with_text_normalised.append(blank_frame) tensor_images = pil2tensor(pil_images_with_text) cropped_pil_images_with_text_normalised = pil2tensor(cropped_pil_images_with_text_normalised) tensor_masks = tensor2Mask(pil2tensor(pil_images_masks)) return (tensor_images,tensor_masks,cropped_pil_images_with_text_normalised,subtitle_coord,) ================================================ FILE: apply_whisper.py ================================================ import whisper import os import folder_paths import uuid import torchaudio import torch import logging import comfy.model_management as mm import comfy.model_patcher WHISPER_MODEL_SUBDIR = os.path.join("stt", "whisper") logger = logging.getLogger(__name__) WHISPER_PATCHER_CACHE = {} class WhisperModelWrapper(torch.nn.Module): """ A torch.nn.Module wrapper for Whisper models. This allows ComfyUI's model management to treat Whisper models like any other torch module, enabling device placement and memory management. """ def __init__(self, model_name, download_root): super().__init__() self.model_name = model_name self.download_root = download_root self.whisper_model = None self.model_loaded_weight_memory = 0 def load_model(self, device): """Load the Whisper model from disk to the specified device""" self.whisper_model = whisper.load_model( self.model_name, download_root=self.download_root, device=device ) # Estimate model size for memory management model_size = sum(p.numel() * p.element_size() for p in self.whisper_model.parameters()) self.model_loaded_weight_memory = model_size class WhisperPatcher(comfy.model_patcher.ModelPatcher): """ Custom ModelPatcher for Whisper models that integrates with ComfyUI's model management system for proper loading/offloading. """ def __init__(self, model, *args, **kwargs): super().__init__(model, *args, **kwargs) def patch_model(self, device_to=None, *args, **kwargs): """ This method is called by ComfyUI's model manager when it's time to load the model onto the target device (usually the GPU). Our responsibility here is to ensure the model weights are loaded from disk if they haven't been already. """ target_device = self.load_device if self.model.whisper_model is None: logger.info(f"Loading Whisper model '{self.model.model_name}' to {target_device}...") self.model.load_model(target_device) self.size = self.model.model_loaded_weight_memory else: logger.info(f"Whisper model '{self.model.model_name}' already in memory.") return super().patch_model(device_to=target_device, *args, **kwargs) def unpatch_model(self, device_to=None, unpatch_weights=True, *args, **kwargs): """ Offload the Whisper model to free up VRAM. """ if unpatch_weights: logger.info(f"Offloading Whisper model '{self.model.model_name}' to {device_to}...") self.model.whisper_model = None self.model.model_loaded_weight_memory = 0 mm.soft_empty_cache() return super().unpatch_model(device_to, unpatch_weights, *args, **kwargs) class ApplyWhisperNode: languages_by_name = None @classmethod def INPUT_TYPES(s): return { "required": { "audio": ("AUDIO",), "model": (['tiny.en', 'tiny', 'base.en', 'base', 'small.en', 'small', 'medium.en', 'medium', 'large-v1', 'large-v2', 'large-v3', 'large', 'large-v3-turbo', 'turbo'],), }, "optional": { "language": ( ["auto"] + [s.capitalize() for s in sorted(list(whisper.tokenizer.LANGUAGES.values())) ], ), "prompt": ("STRING", {"default":""}), } } RETURN_TYPES = ("STRING", "whisper_alignment", "whisper_alignment") RETURN_NAMES = ("text", "segments_alignment", "words_alignment") FUNCTION = "apply_whisper" CATEGORY = "whisper" def apply_whisper(self, audio, model, language, prompt): # save audio bytes from VHS to file temp_dir = folder_paths.get_temp_directory() os.makedirs(temp_dir, exist_ok=True) audio_save_path = os.path.join(temp_dir, f"{uuid.uuid1()}.wav") torchaudio.save(audio_save_path, audio['waveform'].squeeze( 0), audio["sample_rate"]) cache_key = model if cache_key not in WHISPER_PATCHER_CACHE: load_device = mm.get_torch_device() download_root = os.path.join(folder_paths.models_dir, WHISPER_MODEL_SUBDIR) logger.info(f"Creating Whisper ModelPatcher for {model} on device {load_device}") model_wrapper = WhisperModelWrapper(model, download_root) patcher = WhisperPatcher( model=model_wrapper, load_device=load_device, offload_device=mm.unet_offload_device(), size=0 # Will be set when model loads ) WHISPER_PATCHER_CACHE[cache_key] = patcher patcher = WHISPER_PATCHER_CACHE[cache_key] mm.load_model_gpu(patcher) whisper_model = patcher.model.whisper_model if whisper_model is None: logger.error("Whisper model failed to load. Please check logs for errors.") raise RuntimeError(f"Failed to load Whisper model: {model}") transcribe_args = {"initial_prompt": prompt} if language != "auto": if ApplyWhisperNode.languages_by_name is None: ApplyWhisperNode.languages_by_name = {v.lower(): k for k, v in whisper.tokenizer.LANGUAGES.items()} transcribe_args['language'] = ApplyWhisperNode.languages_by_name[language.lower()] result = whisper_model.transcribe(audio_save_path, word_timestamps=True, **transcribe_args) segments = result['segments'] segments_alignment = [] words_alignment = [] for segment in segments: # create segment alignments segment_dict = { 'value': segment['text'].strip(), 'start': segment['start'], 'end': segment['end'] } segments_alignment.append(segment_dict) # create word alignments for word in segment["words"]: word_dict = { 'value': word["word"].strip(), 'start': word["start"], 'end': word['end'] } words_alignment.append(word_dict) return (result["text"].strip(), segments_alignment, words_alignment) ================================================ FILE: example_workflows/whisper_video_subtitles_workflow.json ================================================ { "id": "13ec9b05-13e3-4ce0-a274-dfe796b6c75d", "revision": 0, "last_node_id": 98, "last_link_id": 212, "nodes": [ { "id": 96, "type": "PreviewAny", "pos": [ 430.93074311336665, -689.8146517902532 ], "size": [ 228.01116943359375, 112 ], "flags": {}, "order": 9, "mode": 0, "inputs": [ { "name": "source", "type": "*", "link": 208 } ], "outputs": [], "title": "Preview Text", "properties": { "cnr_id": "comfy-core", "ver": "0.7.0", "Node name for S&R": "PreviewAny" }, "widgets_values": [ null, null, null ] }, { "id": 94, "type": "Save SRT", "pos": [ 61.578740099496905, -676.7824370623489 ], "size": [ 270, 58 ], "flags": {}, "order": 5, "mode": 0, "inputs": [ { "name": "alignment", "type": "whisper_alignment", "link": 210 } ], "outputs": [ { "name": "srt_path", "type": "STRING", "links": [ 208 ] } ], "properties": { "cnr_id": "ComfyUI-Whisper", "ver": "c67c040559c013833dedb0737df14182dc5043cc", "Node name for S&R": "Save SRT" }, "widgets_values": [ "segments" ] }, { "id": 97, "type": "PreviewAny", "pos": [ 440.12585918152246, -511.7266709878157 ], "size": [ 228.01116943359375, 112 ], "flags": {}, "order": 10, "mode": 0, "inputs": [ { "name": "source", "type": "*", "link": 209 } ], "outputs": [], "title": "Preview Text", "properties": { "cnr_id": "comfy-core", "ver": "0.7.0", "Node name for S&R": "PreviewAny" }, "widgets_values": [ null, null, null ] }, { "id": 95, "type": "Save SRT", "pos": [ 76.26082703869388, -532.2749805280864 ], "size": [ 270, 58 ], "flags": {}, "order": 6, "mode": 0, "inputs": [ { "name": "alignment", "type": "whisper_alignment", "link": 211 } ], "outputs": [ { "name": "srt_path", "type": "STRING", "links": [ 209 ] } ], "properties": { "cnr_id": "ComfyUI-Whisper", "ver": "c67c040559c013833dedb0737df14182dc5043cc", "Node name for S&R": "Save SRT" }, "widgets_values": [ "words" ] }, { "id": 46, "type": "VHS_LoadVideo", "pos": [ -1176.1564131907141, -233.30259048886046 ], "size": [ 260.4306640625, 750.7644287109374 ], "flags": {}, "order": 0, "mode": 0, "inputs": [ { "name": "meta_batch", "shape": 7, "type": "VHS_BatchManager", "link": null }, { "name": "vae", "shape": 7, "type": "VAE", "link": null } ], "outputs": [ { "name": "IMAGE", "type": "IMAGE", "slot_index": 0, "links": [ 200 ] }, { "name": "frame_count", "type": "INT", "slot_index": 1, "links": [] }, { "name": "audio", "type": "AUDIO", "slot_index": 2, "links": [ 104, 205 ] }, { "name": "video_info", "type": "VHS_VIDEOINFO", "links": [ 201 ] } ], "properties": { "cnr_id": "comfyui-videohelpersuite", "ver": "1.7.9", "Node name for S&R": "VHS_LoadVideo" }, "widgets_values": { "video": "sample.mp4", "force_rate": 0, "custom_width": 0, "custom_height": 0, "frame_load_cap": 0, "skip_first_frames": 0, "select_every_nth": 1, "format": "AnimateDiff", "videopreview": { "hidden": false, "paused": false, "params": { "frame_load_cap": 0, "skip_first_frames": 0, "force_rate": 0, "filename": "sample.mp4", "type": "input", "format": "video/mp4", "select_every_nth": 1 } } } }, { "id": 47, "type": "Apply Whisper", "pos": [ -786.8513645382293, -223.6544277301129 ], "size": [ 315, 146 ], "flags": {}, "order": 1, "mode": 0, "inputs": [ { "name": "audio", "type": "AUDIO", "link": 205 } ], "outputs": [ { "name": "text", "type": "STRING", "slot_index": 0, "links": [ 206 ] }, { "name": "segments_alignment", "type": "whisper_alignment", "links": [ 207, 210 ] }, { "name": "words_alignment", "type": "whisper_alignment", "slot_index": 2, "links": [ 126, 211, 212 ] } ], "properties": { "cnr_id": "ComfyUI-Whisper", "ver": "c67c040559c013833dedb0737df14182dc5043cc", "Node name for S&R": "Apply Whisper", "aux_id": "yuvraj108c/ComfyUI-Whisper" }, "widgets_values": [ "large", "auto", "" ] }, { "id": 89, "type": "VHS_VideoInfoLoaded", "pos": [ -764.099326170508, 162.74338824290388 ], "size": [ 255.0166015625, 106 ], "flags": { "collapsed": true }, "order": 2, "mode": 0, "inputs": [ { "name": "video_info", "type": "VHS_VIDEOINFO", "link": 201 } ], "outputs": [ { "name": "fps🟦", "type": "FLOAT", "links": [ 202, 203 ] }, { "name": "frame_count🟦", "type": "INT", "links": null }, { "name": "duration🟦", "type": "FLOAT", "links": null }, { "name": "width🟦", "type": "INT", "links": null }, { "name": "height🟦", "type": "INT", "links": null } ], "properties": { "cnr_id": "comfyui-videohelpersuite", "ver": "1.7.9", "Node name for S&R": "VHS_VideoInfoLoaded" }, "widgets_values": {} }, { "id": 93, "type": "PreviewAny", "pos": [ -293.918388794808, -519.816116619595 ], "size": [ 210, 199.76474871812746 ], "flags": {}, "order": 4, "mode": 0, "inputs": [ { "name": "source", "type": "*", "link": 207 } ], "outputs": [], "title": "Preview Alignments", "properties": { "cnr_id": "comfy-core", "ver": "0.7.0", "Node name for S&R": "PreviewAny" }, "widgets_values": [ null, null, null ] }, { "id": 98, "type": "PreviewAny", "pos": [ -294.2934773362138, -263.61847279346836 ], "size": [ 210, 199.76474871812746 ], "flags": {}, "order": 7, "mode": 0, "inputs": [ { "name": "source", "type": "*", "link": 212 } ], "outputs": [], "title": "Preview Alignments", "properties": { "cnr_id": "comfy-core", "ver": "0.7.0", "Node name for S&R": "PreviewAny" }, "widgets_values": [ null, null, null ] }, { "id": 92, "type": "PreviewAny", "pos": [ -302.28418262947025, -687.8915274330623 ], "size": [ 228.01116943359375, 112 ], "flags": {}, "order": 3, "mode": 0, "inputs": [ { "name": "source", "type": "*", "link": 206 } ], "outputs": [], "title": "Preview Text", "properties": { "cnr_id": "comfy-core", "ver": "0.7.0", "Node name for S&R": "PreviewAny" }, "widgets_values": [ null, null, null ] }, { "id": 61, "type": "Add Subtitles To Frames", "pos": [ -338.79950402064753, 96.42499161147244 ], "size": [ 315, 286 ], "flags": {}, "order": 8, "mode": 0, "inputs": [ { "name": "images", "type": "IMAGE", "link": 200 }, { "name": "alignment", "type": "whisper_alignment", "link": 126 }, { "name": "video_fps", "type": "FLOAT", "widget": { "name": "video_fps" }, "link": 202 } ], "outputs": [ { "name": "IMAGE", "type": "IMAGE", "slot_index": 0, "links": [ 128 ] }, { "name": "MASK", "type": "MASK", "slot_index": 1, "links": [] }, { "name": "cropped_subtitles", "type": "IMAGE", "links": null }, { "name": "subtitle_coord", "type": "subtitle_coord", "links": null } ], "properties": { "cnr_id": "ComfyUI-Whisper", "ver": "c67c040559c013833dedb0737df14182dc5043cc", "Node name for S&R": "Add Subtitles To Frames", "aux_id": "yuvraj108c/ComfyUI-Whisper" }, "widgets_values": [ "red", "YRDZST Semibold.ttf", 200, 100, 600, 24, true, 24 ] }, { "id": 49, "type": "VHS_VideoCombine", "pos": [ 143.79281500131185, -263.3319942053376 ], "size": [ 225.3349609375, 713.0399305555555 ], "flags": {}, "order": 11, "mode": 0, "inputs": [ { "name": "images", "type": "IMAGE", "link": 128 }, { "name": "audio", "shape": 7, "type": "AUDIO", "link": 104 }, { "name": "meta_batch", "shape": 7, "type": "VHS_BatchManager", "link": null }, { "name": "vae", "shape": 7, "type": "VAE", "link": null }, { "name": "frame_rate", "type": "FLOAT", "widget": { "name": "frame_rate" }, "link": 203 } ], "outputs": [ { "name": "Filenames", "type": "VHS_FILENAMES", "links": null } ], "properties": { "cnr_id": "comfyui-videohelpersuite", "ver": "1.7.9", "Node name for S&R": "VHS_VideoCombine" }, "widgets_values": { "frame_rate": 24, "loop_count": 0, "filename_prefix": "AnimateDiff", "format": "video/h264-mp4", "pix_fmt": "yuv420p", "crf": 19, "save_metadata": true, "trim_to_audio": false, "pingpong": false, "save_output": true, "videopreview": { "hidden": false, "paused": false, "params": { "filename": "AnimateDiff_00002-audio.mp4", "subfolder": "", "type": "output", "format": "video/h264-mp4", "frame_rate": 24, "workflow": "AnimateDiff_00002.png", "fullpath": "/workspace/ComfyUI/output/AnimateDiff_00002-audio.mp4" } } } } ], "links": [ [ 104, 46, 2, 49, 1, "VHS_AUDIO" ], [ 126, 47, 2, 61, 1, "whisper_alignment" ], [ 128, 61, 0, 49, 0, "IMAGE" ], [ 200, 46, 0, 61, 0, "IMAGE" ], [ 201, 46, 3, 89, 0, "VHS_VIDEOINFO" ], [ 202, 89, 0, 61, 2, "FLOAT" ], [ 203, 89, 0, 49, 4, "FLOAT" ], [ 205, 46, 2, 47, 0, "AUDIO" ], [ 206, 47, 0, 92, 0, "*" ], [ 207, 47, 1, 93, 0, "*" ], [ 208, 94, 0, 96, 0, "STRING" ], [ 209, 95, 0, 97, 0, "STRING" ], [ 210, 47, 1, 94, 0, "whisper_alignment" ], [ 211, 47, 2, 95, 0, "whisper_alignment" ], [ 212, 47, 2, 98, 0, "whisper_alignment" ] ], "groups": [ { "id": 1, "title": "Save SRT", "bounding": [ 50.185342503076356, -804.9143402108606, 656.2486774493581, 416.28487309316733 ], "color": "#3f789e", "font_size": 24, "flags": {} } ], "config": {}, "extra": { "ds": { "scale": 0.5450529555861997, "offset": [ 1741.826278147595, 911.0259214691794 ] }, "frontendVersion": "1.35.9", "workflowRendererVersion": "LG", "VHS_latentpreview": false, "VHS_latentpreviewrate": 0, "VHS_MetadataImage": true, "VHS_KeepIntermediate": true }, "version": 0.4 } ================================================ FILE: pyproject.toml ================================================ [project] name = "comfyui-whisper" description = "Transcribe audio and add subtitles to videos using Whisper in ComfyUI" version = "1.0.0" license = {file = "LICENSE"} dependencies = ["openai-whisper", "pillow", "uuid"] [project.urls] Repository = "https://github.com/yuvraj108c/ComfyUI-Whisper" # Used by Comfy Registry https://comfyregistry.org [tool.comfy] PublisherId = "yuvraj108c" DisplayName = "ComfyUI-Whisper" Icon = "" ================================================ FILE: readme.md ================================================ # ComfyUI Whisper Transcribe audio and add subtitles to videos using [Whisper](https://github.com/openai/whisper/) in [ComfyUI](https://github.com/comfyanonymous/ComfyUI). Support multiple languages, prompt guidance and multiple whisper models. **Last tested**: 2 January 2026 (ComfyUI v0.7.0@f2fda02 | Torch 2.9.1 | Triton 3.5.1 | Python 3.10.12 | RTX4090 | CUDA 13.0 | Debian 12) ![demo-image](https://github.com/yuvraj108c/ComfyUI-Whisper/blob/assets/recording.gif?raw=true) ## ⭐ Support If you like my projects and wish to see updates and new features, please consider supporting me. It helps a lot! [![ComfyUI-Depth-Anything-Tensorrt](https://img.shields.io/badge/ComfyUI--Depth--Anything--Tensorrt-blue?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Depth-Anything-Tensorrt) [![ComfyUI-Upscaler-Tensorrt](https://img.shields.io/badge/ComfyUI--Upscaler--Tensorrt-blue?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Upscaler-Tensorrt) [![ComfyUI-Dwpose-Tensorrt](https://img.shields.io/badge/ComfyUI--Dwpose--Tensorrt-blue?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Dwpose-Tensorrt) [![ComfyUI-Rife-Tensorrt](https://img.shields.io/badge/ComfyUI--Rife--Tensorrt-blue?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Rife-Tensorrt) [![ComfyUI-Whisper](https://img.shields.io/badge/ComfyUI--Whisper-gray?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Whisper) [![ComfyUI_InvSR](https://img.shields.io/badge/ComfyUI__InvSR-gray?style=flat-square)](https://github.com/yuvraj108c/ComfyUI_InvSR) [![ComfyUI-Thera](https://img.shields.io/badge/ComfyUI--Thera-gray?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Thera) [![ComfyUI-Video-Depth-Anything](https://img.shields.io/badge/ComfyUI--Video--Depth--Anything-gray?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-Video-Depth-Anything) [![ComfyUI-PiperTTS](https://img.shields.io/badge/ComfyUI--PiperTTS-gray?style=flat-square)](https://github.com/yuvraj108c/ComfyUI-PiperTTS) [![buy-me-coffees](https://i.imgur.com/3MDbAtw.png)](https://www.buymeacoffee.com/yuvraj108cZ) [![paypal-donation](https://i.imgur.com/w5jjubk.png)](https://paypal.me/yuvraj108c) --- ## Installation Install via [ComfyUI Manager](https://github.com/ltdrdata/ComfyUI-Manager) ## Usage Load this [workflow](https://github.com/yuvraj108c/ComfyUI-Whisper/blob/master/example_workflows/whisper_video_subtitles_workflow.json) into ComfyUI Models are auto-downloaded to `/ComfyUI/models/stt/whisper` ## Supported Models 'tiny.en', 'tiny', 'base.en', 'base', 'small.en', 'small', 'medium.en', 'medium', 'large-v1', 'large-v2', 'large-v3', 'large', 'large-v3-turbo', 'turbo' ## Nodes ### Apply Whisper Transcribe audio and get timestamps for each segment and word. ### Add Subtitles To Frames Add subtitles on the video frames. You can specify font family, font color and x/y positions. ### Add Subtitles To Background (Experimental) Add subtitles like wordcloud on blank frames ### Save SRT Export alignments as SRT files in `/ComfyUI/output/srt` directory ## Updates ### 2 January 2026 - Export alignments as SRT - Add `torchcodec` to requirements ### 27 August 2025 - Merge https://github.com/yuvraj108c/ComfyUI-Whisper/pull/22 by [@francislabountyjr](https://github.com/francislabountyjr) for model patcher, more whisper models support, comfyui model directory support - Merge https://github.com/yuvraj108c/ComfyUI-Whisper/pull/18 by [@qy8502](https://github.com/qy8502) for Prompt Guidance support - Support YRDZST Semibold Font ### 2 May 2025 - Merge https://github.com/yuvraj108c/ComfyUI-Whisper/pull/15 by [@niknah](https://github.com/niknah) for language selection ## Credits - [comfyanonymous/ComfyUI](https://github.com/comfyanonymous/ComfyUI) - [Kosinkadink/ComfyUI-VideoHelperSuite](https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite) - [melMass/comfy_mtb](https://github.com/melMass/comfy_mtb) ## License [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ================================================ FILE: requirements.txt ================================================ openai-whisper pillow uuid torchcodec ================================================ FILE: resize_cropped_subtitles.py ================================================ from .utils import tensor2pil, pil2tensor from PIL import Image class ResizeCroppedSubtitlesNode: @classmethod def INPUT_TYPES(s): return { "required": { "cropped_subtitles": ("IMAGE",), "original_frames": ("IMAGE",), "subtitle_coord": ("subtitle_coord",), } } RETURN_TYPES = ("IMAGE",) RETURN_NAMES = ("IMAGE",) FUNCTION = "resize_cropped_subtitles" CATEGORY = "whisper" def resize_cropped_subtitles(self,cropped_subtitles, original_frames, subtitle_coord): pil_images_og = tensor2pil(original_frames) pil_images_cropped = tensor2pil(cropped_subtitles) final_images = [] print(len(cropped_subtitles), len(original_frames), len(subtitle_coord)) width, height = pil_images_og[0].size for idx in range(len(pil_images_cropped)): frame = Image.new("RGB", (width, height), "black") frame.paste(pil_images_cropped[idx],(int(subtitle_coord[idx][0]),int(subtitle_coord[idx][1]))) final_images.append(frame) return (pil2tensor(final_images),) ================================================ FILE: save_srt.py ================================================ # mostly generated using claude import folder_paths import json import os class SaveSRTNode: @classmethod def INPUT_TYPES(s): return { "required": { "alignment" : ("whisper_alignment",), "name": ("STRING",{"default": "subtitles"}), } } RETURN_TYPES = ("STRING", ) RETURN_NAMES = ("srt_path",) FUNCTION = "save_srt" CATEGORY = "whisper" def seconds_to_srt_time(self, seconds): """Convert seconds to SRT time format (HH:MM:SS,mmm)""" hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) secs = int(seconds % 60) milliseconds = int((seconds % 1) * 1000) return f"{hours:02d}:{minutes:02d}:{secs:02d},{milliseconds:03d}" def json_to_srt(self, json_data): """Convert JSON subtitle data to SRT format""" # Parse JSON if it's a string if isinstance(json_data, str): data = json.loads(json_data) else: data = json_data # Generate SRT content srt_content = [] for i, entry in enumerate(data, start=1): start_time = self.seconds_to_srt_time(entry['start']) end_time = self.seconds_to_srt_time(entry['end']) text = entry['value'] srt_content.append(f"{i}") srt_content.append(f"{start_time} --> {end_time}") srt_content.append(text) srt_content.append("") # Empty line between entries return srt_content def save_srt(self, alignment, name): subfolder = "srt" output_dir = os.path.join(folder_paths.get_output_directory(), subfolder) os.makedirs(output_dir,exist_ok=True) srt_save_path = os.path.join(output_dir, name) + ".srt" srt_content = self.json_to_srt(alignment) with open(srt_save_path, 'w', encoding='utf-8') as f: f.write('\n'.join(srt_content)) return (srt_save_path,) ================================================ FILE: utils.py ================================================ import torch import numpy as np from PIL import Image # https://github.com/melMass/comfy_mtb/blob/501c3301056b2851555cccd75ab3ff15b1ab8e0c/utils.py#L261-L298 def tensor2pil(image): batch_count = image.size(0) if len(image.shape) > 3 else 1 if batch_count > 1: out = [] for i in range(batch_count): out.extend(tensor2pil(image[i])) return out return [ Image.fromarray( np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8) ) ] def pil2tensor(image): if isinstance(image, list): return torch.cat([pil2tensor(img) for img in image], dim=0) return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) # https://github.com/comfyanonymous/ComfyUI/blob/fc196aac80fd~4bf6c8a39d85d1e809902871cade/comfy_extras/nodes_mask.py#L127 def tensor2Mask(image): return image[:, :, :, 0]