Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from .utils.moviepy_wrappers.composite_clip import clips_array_maybe_none
if len(videos) % num_rows != 0:
raise ValueError('Number of videos (%s) is not evenly divisible by '
'--num_rows (%s). This is not supported right now.' %
(len(videos), num_rows))
num_cols = len(videos) / num_rows
from moviepy.video.io.VideoFileClip import VideoFileClip
grid = [[] for _ in range(num_rows)]
for i, video in enumerate(videos):
row = int(i // num_cols)
if video != blank_path:
clip = VideoFileClip(str(video))
else:
clip = None
grid[row].append(clip)
set_image_clip_duration(grid)
output_clip = clips_array_maybe_none(grid)
if not save_audio:
output_clip = output_clip.without_audio()
output_clip.write_videofile(output, verbose=verbose, progress_bar=verbose)
def test_PR_515():
# Won't actually work until video is in download_media
with VideoFileClip("media/fire2.mp4", fps_source='tbr') as clip:
assert clip.fps == 90000
with VideoFileClip("media/fire2.mp4", fps_source='fps') as clip:
assert clip.fps == 10.51
def test_remote_video(self):
video_url = 'https://raw.githubusercontent.com/johndyer/mediaelement-files/master/big_buck_bunny.mp4'
video_content, size, duration, thumbnail_content = media.prepare_video(
video_url, aspect_ratios=1.0, max_duration=10.0)
self.assertEqual(duration, 10.0, 'Invalid duration.')
self.assertEqual(size[0], size[1], 'Invalid width/length.')
self.assertGreater(len(video_content), 0, 'No video content returned.')
self.assertGreater(len(thumbnail_content), 0, 'No thumbnail content returned.')
# Save video, thumbnail content and verify attributes
video_output = tempfile.NamedTemporaryFile(prefix='ipae_test_', suffix='.mp4', delete=False)
video_output.write(video_content)
video_output.close()
with VideoFileClip(video_output.name) as vidclip_output:
self.assertAlmostEqual(duration, vidclip_output.duration, places=0)
self.assertEqual(size[0], vidclip_output.size[0])
self.assertEqual(size[1], vidclip_output.size[1])
im = Image.open(io.BytesIO(thumbnail_content))
self.assertEqual(size[0], im.size[0])
self.assertEqual(size[1], im.size[1])
def test_prepare_video3(self):
video_content, size, duration, thumbnail_content = media.prepare_video(
self.TEST_VIDEO_PATH, max_size=None, max_duration=1000.0,
skip_reencoding=True, min_size=None)
self.assertEqual(size[0], self.TEST_VIDEO_SIZE[0], 'Width changed.')
self.assertEqual(size[1], self.TEST_VIDEO_SIZE[1], 'Height changed.')
self.assertGreater(len(video_content), 0, 'No video content returned.')
self.assertGreater(len(thumbnail_content), 0, 'No thumbnail content returned.')
# Save video, thumbnail content and verify attributes
video_output = tempfile.NamedTemporaryFile(prefix='ipae_test_', suffix='.mp4', delete=False)
video_output.write(video_content)
video_output.close()
with VideoFileClip(video_output.name) as vidclip_output:
self.assertAlmostEqual(duration, vidclip_output.duration, places=0)
self.assertEqual(size[0], vidclip_output.size[0])
self.assertEqual(size[1], vidclip_output.size[1])
im = Image.open(io.BytesIO(thumbnail_content))
self.assertEqual(size[0], im.size[0])
self.assertEqual(size[1], im.size[1])
self.assertEqual(
os.path.getsize(video_output.name),
os.path.getsize(self.TEST_VIDEO_PATH))
def test_withoutaudio():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.6)
new_clip = clip.without_audio()
assert new_clip.audio is None
close_all_clips(locals())
Lead a video into a numpy array
:param full_path: Full path to the video
:param size: A 2-tuple of width-height, indicating the desired size of the ouput
:param resize_mode: The mode with which to get the video to the desired size. Can be:
'squeeze', 'preserve_aspect', 'crop', 'scale_crop'. See resize_image in image_ops.py for more info.
:param cut_edges: True if you want to cut the dark edges from the video
:param cut_edges_thresh: If cut_edges, this is the threshold at which you'd like to cut them.
:return: A (n_frames, height, width, 3) numpy array
"""
try:
from moviepy.video.io.VideoFileClip import VideoFileClip
except ImportError:
raise ImportError("You need to install moviepy to read videos. In the virtualenv, go `pip install moviepy`")
assert os.path.exists(full_path)
video = VideoFileClip(full_path)
images = []
edge_crops = None
for frame in video.iter_frames():
if cut_edges:
if edge_crops is None:
edge_crops = get_dark_edge_slice(frame, cut_edges_thresh=cut_edges_thresh)
else:
frame = frame[edge_crops[0], edge_crops[1]]
if size is not None:
width, height = size
frame = resize_image(frame, width=width, height=height, mode=resize_mode)
images.append(frame)
return images
def create_supercut(composition, outputfile, padding):
print ("[+] Creating clips.")
demo_supercut(composition, padding)
# add padding when necessary
for (clip, nextclip) in zip(composition, composition[1:]):
if ((nextclip['file'] == clip['file']) and (nextclip['start'] < clip['end'])):
nextclip['start'] += padding
# put all clips together:
all_filenames = set([c['file'] for c in composition])
videofileclips = dict([(f, VideoFileClip(f)) for f in all_filenames])
cut_clips = [videofileclips[c['file']].subclip(c['start'], c['end']) for c in composition]
print "[+] Concatenating clips."
final_clip = concatenate(cut_clips)
print "[+] Writing ouput file."
final_clip.to_videofile(outputfile, codec="libx264", temp_audiofile='temp-audio.m4a', remove_temp=True, audio_codec='aac')
def summarize(filepath, new_filename, hotclips):
"""
Inputs a filepath for a video and generates a new shorter video
in that same filepath.
"""
# Only open the file once!
video = VideoFileClip(filepath)
chunks = [video.subclip(start, end)
for (start, end) in hotclips]
final_clip = concatenate(chunks)
# txt_clip = ( TextClip("Generated by vSummarize",
# fontsize=20, color='white')
# .set_pos('bottom')
# .set_duration(5))
# final_clip = CompositeVideoClip([summarized_video, txt_clip])
# Use the to_videofile default codec, libx264
# libx264 is much better than mpeg4, and still writes .mp4
# Use the fps of the original video.
final_clip.to_videofile(new_filename,
def gif_image_search(bot: Bot, update: Update):
"""Send a reverse image search link for the GIF sent to us
Args:
bot (:obj:`telegram.bot.Bot`): Telegram Api Bot Object.
update (:obj:`telegram.update.Update`): Telegram Api Update Object
"""
update.message.reply_text('Please wait for your results ...')
bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.TYPING)
document = update.message.document or update.message.video
video = bot.getFile(document.file_id)
with NamedTemporaryFile() as video_file:
video.download(out=video_file)
video_clip = VideoFileClip(video_file.name, audio=False)
with NamedTemporaryFile(suffix='.gif') as gif_file:
video_clip.write_gif(gif_file.name)
dirname = os.path.dirname(gif_file.name)
file_name = os.path.splitext(gif_file.name)[0]
compressed_gif_path = os.path.join(dirname, file_name + '-min.gif')
os.system('gifsicle -O3 --lossy=50 -o {dst} {src}'.format(dst=compressed_gif_path, src=gif_file.name))
if os.path.isfile(compressed_gif_path):
general_image_search(bot, update, compressed_gif_path, 'gif')
else:
general_image_search(bot, update, gif_file.name, 'gif')
def main():
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
args = docopt(__doc__)
input_file = args['FILE']
out_dir = args['OUT_DIR']
max_d = float(args['--max-time'])
min_d = float(args['--min-time'])
time_distance = float(args['--time-distance'])
num_hashes = int(args['--num-hashes'])
nproc = mp.cpu_count()
duration = VideoFileClip(input_file).duration
print 'Finding loops...'
match_procs = []
for i in range(nproc):
(recv, send) = mp.Pipe()
progress = mp.Value('f')
start_time = (duration / float(nproc)) * i
end_time = min(duration, (duration / float(nproc)) * (i + 1) + max_d)
p = mp.Process(target=find_matches,
args=(input_file, start_time, end_time, max_d, min_d,
num_hashes, progress, send))
p.start()
match_procs.append((p, recv, progress))
matches = []
with tqdm(total=100) as progress: