import torch
import folder_paths
from PIL import Image, ImageOps
import numpy as np
import safetensors.torch
import hashlib
import os
import cv2
import os
import imageio
import shutil
from moviepy.editor import VideoFileClip, AudioFileClip
import random
import math
import json
from comfy.cli_args import args
import time
import concurrent.futures
import skbuild
YELLOW = '\33[33m'
END = '\33[0m'
Brutally copied from comfy_extras/nodes_rebatch.py and modified
class LatentRebatch:
code
Assistant
@staticmethod
def get_batch(latents, list_ind, offset):
'''prepare a batch out of the list of latents'''
samples = latents[list_ind]['samples']
shape = samples.shape
mask = latents[list_ind]['noise_mask'] if 'noise_mask' in latents[list_ind] else torch.ones((shape[0], 1, shape[2]*8, shape[3]*8), device='cpu')
if mask.shape[-1] != shape[-1] * 8 or mask.shape[-2] != shape[-2]:
torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[-2]*8, shape[-1]*8), mode="bilinear")
if mask.shape[0] < samples.shape[0]:
mask = mask.repeat((shape[0] - 1) // mask.shape[0] + 1, 1, 1, 1)[:shape[0]]
if 'batch_index' in latents[list_ind]:
batch_inds = latents[list_ind]['batch_index']
else:
batch_inds = [x+offset for x in range(shape[0])]
return samples, mask, batch_inds
@staticmethod
def get_slices(indexable, num, batch_size):
'''divides an indexable object into num slices of length batch_size, and a remainder'''
slices = []
for i in range(num):
slices.append(indexable[i*batch_size:(i+1)*batch_size])
if num * batch_size < len(indexable):
return slices, indexable[num * batch_size:]
else:
return slices, None
@staticmethod
def slice_batch(batch, num, batch_size):
result = [LatentRebatch.get_slices(x, num, batch_size) for x in batch]
return list(zip(*result))
@staticmethod
def cat_batch(batch1, batch2):
if batch1[0] is None:
return batch2
result = [torch.cat((b1, b2)) if torch.is_tensor(b1) else b1 + b2 for b1, b2 in zip(batch1, batch2)]
return result
def rebatch(self, latents, batch_size):
batch_size = batch_size[0]
output_list = []
current_batch = (None, None, None)
processed = 0
for i in range(len(latents)):
# fetch new entry of list
#samples, masks, indices = self.get_batch(latents, i)
next_batch = self.get_batch(latents, i, processed)
processed += len(next_batch[2])
# set to current if current is None
if current_batch[0] is None:
current_batch = next_batch
# add previous to list if dimensions do not match
elif next_batch[0].shape[-1] != current_batch[0].shape[-1] or next_batch[0].shape[-2] != current_batch[0].shape[-2]:
sliced, _ = self.slice_batch(current_batch, 1, batch_size)
output_list.append({'samples': sliced[0][0], 'noise_mask': sliced[1][0], 'batch_index': sliced[2][0]})
current_batch = next_batch
# cat if everything checks out
else:
current_batch = self.cat_batch(current_batch, next_batch)
# add to list if dimensions gone above target batch size
if current_batch[0].shape[0] > batch_size:
num = current_batch[0].shape[0] // batch_size
sliced, remainder = self.slice_batch(current_batch, num, batch_size)
for i in range(num):
output_list.append({'samples': sliced[0][i], 'noise_mask': sliced[1][i], 'batch_index': sliced[2][i]})
current_batch = remainder
#add remainder
if current_batch[0] is not None:
sliced, _ = self.slice_batch(current_batch, 1, batch_size)
output_list.append({'samples': sliced[0][0], 'noise_mask': sliced[1][0], 'batch_index': sliced[2][0]})
#get rid of empty masks
for s in output_list:
if s['noise_mask'].mean() == 1.0:
del s['noise_mask']
return output_list
# Ottieni il framerate originale del video
original_fps = int(cap.get(cv2.CAP_PROP_FPS))
# Calcola il rapporto per ridurre il framerate
frame_skip_ratio = original_fps // target_fps
real_frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
frame_count += 1
# Estrai solo ogni "frame_skip_ratio"-esimo fotogramma
if frame_count % frame_skip_ratio == 0:
frame_filename = os.path.join(output_folder, f"{frame_count:07d}.png")
list_files.append(frame_filename)
cv2.imwrite(frame_filename, frame)
real_frame_count += 1
cap.release()
print(f"{real_frame_count} frames have been extracted from the video and saved in {output_folder}")
return list_files
gif_frames = imageio.mimread(gif_path, memtest=False)
frame_count = 0
for frame in gif_frames:
frame_count += 1
frame_filename = os.path.join(output_folder, f"{frame_count:07d}.png")
list_files.append(frame_filename)
cv2.imwrite(frame_filename, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
print(f"{frame_count} frames have been extracted from the GIF and saved in {output_folder}")
return list_files
def get_output_filename(input_file_path, output_folder, file_extension,suffix="") :
existing_files = [f for f in os.listdir(output_folder)]
max_progressive = 0
for filename in existing_files:
parts_ext = filename.split(".")
parts = parts_ext[0]
def create_video_from_frames(frame_folder, output_video, frame_rate = 30.0):
frame_filenames = [os.path.join(frame_folder, filename) for filename in os.listdir(frame_folder) if filename.endswith(".png")]
frame_filenames.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
first_frame = cv2.imread(frame_filenames[0])
height, width, layers = first_frame.shape
code
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, frame_rate, (width, height))
for frame_filename in frame_filenames:
frame = cv2.imread(frame_filename)
out.write(frame)
out.release()
print(f"Frames have been successfully reassembled into {output_video}")
def create_gif_from_frames(frame_folder, output_gif):
frame_filenames = [os.path.join(frame_folder, filename) for filename in os.listdir(frame_folder) if filename.endswith(".png")]
frame_filenames.sort()
code
frames = [imageio.imread(frame_filename) for frame_filename in frame_filenames]
# imageio
imageio.mimsave(output_gif, frames, duration=0.1)
print(f"Frames have been successfully assembled into {output_gif}")
temp_dir= folder_paths.temp_directory
class LoadVideoAdvanced:
def init(self):
pass
code
@classmethod
def INPUT_TYPES(s):
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
return {"required": {"video": (sorted(files), ),
"local_url": ("STRING", {"default": ""} ),
"framerate": (_framerate, {"default": "original"} ),
"resize_by": (_resize_type,{"default": "none"} ),
"size": ("INT", {"default": 512, "min": 512, "step": 64}),
"images_limit": ("INT", {"default": 0, "min": 0, "step": 1}),
"batch_size": ("INT", {"default": 0, "min": 0, "step": 1}),
"starting_frame": ("INT", {"default": 0, "min": 0, "step": 1}),
"autoplay":("BOOLEAN",{"default": True} ),
},}
RETURN_TYPES = ("IMAGE","LATENT","STRING","INT","INT","INT","INT",)
OUTPUT_IS_LIST = (True, True, False, False,False,False,False, )
RETURN_NAMES = ("IMAGES","EMPTY LATENTS","METADATA","WIDTH","HEIGHT","META_FPS","META_N_FRAMES")
CATEGORY = "N-Suite/Video"
FUNCTION = "encode"
TYPE="N-Suite"
@staticmethod
def vae_encode_crop_pixels(pixels):
x = (pixels.shape[1] // 8) * 8
y = (pixels.shape[2] // 8) * 8
if pixels.shape[1] != x or pixels.shape[2] != y:
x_offset = (pixels.shape[1] % 8) // 2
y_offset = (pixels.shape[2] % 8) // 2
pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :]
return pixels
def load_video(self, video,framerate, local_url):
file_path = folder_paths.get_annotated_filepath(os.path.join("n-suite",video))
cap = cv2.VideoCapture(file_path)
# Check if the video was opened successfully
if not cap.isOpened():
print("Unable to open the video.")
else:
# Get the FPS of the video
fps = int(cap.get(cv2.CAP_PROP_FPS))
print(f"The video has {fps} frames per second.")
try:
shutil.rmtree(os.path.join(temp_output_dir,video.split(".")[0]))
except:
print("Video Path already deleted")
full_temp_output_dir = os.path.join(temp_output_dir,video.split(".")[0])
#set new framerate
if "half" in framerate:
fps = fps // 2
print (f"The video has been reduced to {fps} frames per second.")
elif "quarter" in framerate:
fps = fps // 4
print (f"The video has been reduced to {fps} frames per second.")
# Estract frames
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == ".mp4" or file_extension == ".webm":
list_files = extract_frames_from_video(file_path, full_temp_output_dir, target_fps=fps)
audio_clip = VideoFileClip(file_path).audio
try:
#save audio
audio_clip.write_audiofile(os.path.join(temp_output_dir,video.split(".")[0],"audio.mp3"))
except:
print("Could not save audio")
pass
elif file_extension == ".gif":
extract_frames_from_gif(file_path, output_dir)
list_files = extract_frames_from_gif(file_path, output_dir)
#create_gif_from_frames(output_dir, output_video2)
else:
print("Format not supported. Please provide an MP4 or GIF file.")
return list_files,fps
def generate_latent(self, width, height, batch_size=1):
latent = torch.zeros([batch_size, 4, height // 8, width // 8])
return {"samples":latent}
def process_image(self,args):
image_path, width, height = args
# Funzione per ridimensionare e pre-elaborare un'immagine
image = resize_image(image_path, width, height)
image = image_preprocessing(image)
return torch.tensor(image)
def encode(self,video,framerate, local_url, resize_by, size, images_limit,batch_size,starting_frame,autoplay):
metadata = []
FRAMES,fps = self.load_video(video,framerate, local_url)
max_frames = len(FRAMES)
if images_limit>0 and starting_frame>0:
images_limit = images_limit + starting_frame
#if images_limit==0:
# images_limit = max_frames
print(f"images_limit {images_limit}")
#if starting frame is too high do the last frames only
if starting_frame>max_frames:
starting_frame = max_frames-1
print(f"{YELLOW}WARNING: The starting frame is greater than the number of frames in the video. Only the last frame of the video will be used ({starting_frame}). {END}")
#if images_limit > max_frames
if images_limit > max_frames:
images_limit = max_frames
print(f"{YELLOW}WARNING: The number of images to extract is greater than the number of frames in the video. Images_limit has been reduced to the number of frames ({images_limit}). {END}")
#if batch_size > max_frames
if batch_size > max_frames:
print(f"{YELLOW}WARNING: The batch size is greater than the number of frames requested. Batch size has been reduced. {END}")
batch_size = max_frames
#if batch_size > images_limit
if images_limit!=0 and batch_size > images_limit:
print(f"{YELLOW}WARNING: The batch size is greater than the number of frames requested. Batch size has been reduced to the number of images_limit. {END}")
batch_size = images_limit
pool_size=5
t_list = []
i_list = []
i = 0
o = 0
final_count_frame=0
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
width, height = calc_resize_image(FRAMES[0], size, resize_by)
for batch_start in range(0, len(FRAMES), pool_size):
batch_images = FRAMES[batch_start:batch_start + pool_size]
#remove audio if image_limit > 0 or starting_frame>0
if images_limit != 0 or starting_frame != 0:
try:
os.remove(os.path.join(temp_output_dir,video.split(".")[0],"audio.mp3"))
except:
pass
#if o >= images_limit:
# break
for image_path in batch_images:
# loop only when it reaches the starting_frame
if o>=starting_frame and (o<images_limit or images_limit==0):
args = (image_path, width, height)
futures.append(executor.submit(self.process_image, args))
final_count_frame += 1
o += 1
i += len(batch_images)
# Attendi il completamento delle operazioni in parallelo
concurrent.futures.wait(futures)
# Recupera i risultati
for future in futures:
batch_i_tensors = future.result()
i_list.extend(batch_i_tensors)
i_tensor = torch.stack(i_list, dim=0)
if images_limit != 0 or starting_frame != 0:
b_size=final_count_frame
else:
b_size=len(FRAMES)
latent = self.generate_latent( width, height, batch_size=b_size)
metadata.append(fps)
metadata.append(b_size)
try:
metadata.append(video.split(".")[0])
except:
print("No video name")
if batch_size != 0:
rebatcher = LatentRebatch()
rebatched_latent = rebatcher.rebatch([latent], [batch_size])
n_chunks = b_size//batch_size
i_tensor_batches = torch.chunk(i_tensor, n_chunks, dim=0)
return (i_tensor_batches,rebatched_latent,metadata, width, height,)
return ( [i_tensor],[latent],metadata, width, height,fps,b_size,)
File "D:\ComfyUI-aki-v1.1\execution.py", line 153, in recursive_execute
output_data, output_ui = get_output_data(obj, input_data_all)
File "D:\ComfyUI-aki-v1.1\execution.py", line 82, in get_output_data
return_values = map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True)
File "D:\ComfyUI-aki-v1.1\execution.py", line 75, in map_node_over_list
results.append(getattr(obj, func)(**slice_dict(input_data_all, i)))
File "D:\ComfyUI-aki-v1.1\custom_nodes\ComfyUI-N-Nodes\py\video_node_advanced.py", line 631, in save_video
video_clip.write_videofile(self.video_file_path)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\decorator.py", line 232, in fun
return caller(func, *(extras + args), **kw)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\decorators.py", line 54, in requires_duration
return f(clip, *a, **k)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\decorator.py", line 232, in fun
return caller(func, *(extras + args), **kw)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\decorators.py", line 137, in use_clip_fps_by_default
return f(clip, *new_a, **new_kw)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\decorator.py", line 232, in fun
return caller(func, *(extras + args), **kw)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\decorators.py", line 22, in convert_masks_to_RGB
return f(clip, *a, **k)
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\video\VideoClip.py", line 338, in write_videofile
ffmpeg_write_video(self, filename, fps, codec,
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 201, in ffmpeg_write_video
writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,
File "D:\ComfyUI-aki-v1.1\python\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 86, in init
'-r', '%.02f' % fps,
帮我解决下这个问题
The error you've encountered seems to be occurring during the video writing process, triggered by moviepy's write_videofile function. Since the traceback does not contain the actual error message, I can only provide general debugging advice.
Here are few things you can check:
FFmpeg Installation: moviepy relies on FFmpeg, make sure it is installed and properly configured in your environment's PATH. Without FFmpeg, it won't be able to process video files.
File Paths: Ensure that the path where you're trying to save the video (self.video_file_path) is valid and writable. Make sure the directory exists and that you have permissions to write there.
Corrupted Frames: Double-check your frames and make sure none are corrupted and that all are in a compatible format (e.g., all are PNGs).
Codec Issues: Check if the video codec specified in the write_videofile function is compatible with your system and FFmpeg installation.
Verification: Since you're generating filenames dynamically, ensure that the generated filenames are compatible with your filesystem, avoid special characters and excessively long names.
If the above checks don't reveal the issue, try catching the exception to see a more detailed error message. You can modify the save_video function to include a try-except block:
python
def save_video(self, images, METADATA, SaveVideo, SaveFrames, filename_prefix, CompressionLevel, prompt=None, extra_pnginfo=None):
# ... (your existing code) ...
try:
if(file_name_number >= frame_number):
# Your existing code for creating the video
# ...
except Exception as e:
print(f"An error occurred: {e}") # This will print the error message
raise # Optionally, re-raise the exception if you want the program to crash
By adding the try-except block, you will be able to catch any exceptions that occur during the video saving process and print out the error, which will help in further diagnosing the problem.
As for the provided code, please ensure that you're following proper practices for managing files and paths (like exception handling when creating or deleting directories). It's also advisable to clean up temporary files and folders once they're no longer needed, and always consider permission and error-checking when dealing with file I/O operations.
The code is complex and has quite a few dependencies on external modules. If you’re still facing issues and need further debugging, consider isolating the part of the code where the issue occurs and run it with a simple, hard-coded input to ensure it works as expected before reintegrating with the rest of the codebase.