Skip to content

Commit

Permalink
python language updates
Browse files Browse the repository at this point in the history
upgraded a bunch of format strings to f-strings
formatted with black afterwards to meet previous style
all tests pass (Windows 11)
  • Loading branch information
Mark Mayo committed Feb 20, 2023
1 parent 99a9657 commit 5039719
Show file tree
Hide file tree
Showing 33 changed files with 49 additions and 104 deletions.
Binary file added __temp__.mp3
Binary file not shown.
Binary file added __temp__.mp4
Binary file not shown.
Binary file added __temp__.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions examples/dancing_knights.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
)

audio_period = find_audio_period(audio)
print("Analyzed the audio, found a period of %.02f seconds" % audio_period)
print(f"Analyzed the audio, found a period of {audio_period:.02f} seconds")


# LOAD, EDIT, ANALYZE THE VIDEO
Expand All @@ -66,7 +66,7 @@
)

video_period = find_video_period(clip, start_time=0.3)
print("Analyzed the video, found a period of %.02f seconds" % video_period)
print(f"Analyzed the video, found a period of {video_period:.02f} seconds")

edited_right = (
clip.subclip(0, video_period)
Expand Down
10 changes: 2 additions & 8 deletions moviepy/Clip.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ class Clip:
_TEMP_FILES_PREFIX = "TEMP_MPY_"

def __init__(self):

self.start = 0
self.end = None
self.duration = None
Expand Down Expand Up @@ -375,7 +374,6 @@ def is_playing(self, t):
return result

else:

return (t >= self.start) and ((self.end is None) or (t < self.end))

@convert_parameter_to_seconds(["start_time", "end_time"])
Expand Down Expand Up @@ -416,19 +414,17 @@ def subclip(self, start_time=0, end_time=None):

if (self.duration is not None) and (start_time >= self.duration):
raise ValueError(
"start_time (%.02f) " % start_time
f"start_time ({start_time:.02f}) "
+ "should be smaller than the clip's "
+ "duration (%.02f)." % self.duration
+ f"duration ({self.duration:.02f})."
)

new_clip = self.time_transform(lambda t: t + start_time, apply_to=[])

if (end_time is None) and (self.duration is not None):

end_time = self.duration

elif (end_time is not None) and (end_time < 0):

if self.duration is None:
raise ValueError(
(
Expand All @@ -439,11 +435,9 @@ def subclip(self, start_time=0, end_time=None):
)

else:

end_time = self.duration + end_time

if end_time is not None:

new_clip.duration = end_time - start_time
new_clip.end = new_clip.start + new_clip.duration

Expand Down
1 change: 0 additions & 1 deletion moviepy/audio/AudioClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,6 @@ class AudioArrayClip(AudioClip):
"""

def __init__(self, array, fps):

Clip.__init__(self)
self.array = array
self.fps = fps
Expand Down
1 change: 0 additions & 1 deletion moviepy/audio/io/AudioFileClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ class AudioFileClip(AudioClip):
def __init__(
self, filename, decode_file=False, buffersize=200000, nbytes=2, fps=44100
):

AudioClip.__init__(self)

self.filename = filename
Expand Down
2 changes: 1 addition & 1 deletion moviepy/audio/io/ffmpeg_audiowriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def ffmpeg_audiowrite(
else:
logfile = None
logger = proglog.default_bar_logger(logger)
logger(message="MoviePy - Writing audio in %s" % filename)
logger(message=f"MoviePy - Writing audio in {filename}")
writer = FFMPEG_AudioWriter(
filename,
fps,
Expand Down
17 changes: 8 additions & 9 deletions moviepy/audio/io/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,12 @@ def initialize(self, start_time=0):
offset = min(1, start_time)
i_arg = [
"-ss",
"%.05f" % (start_time - offset),
f"{start_time - offset:.05f}",
"-i",
self.filename,
"-vn",
"-ss",
"%.05f" % offset,
f"{offset:.05f}",
]
else:
i_arg = ["-i", self.filename, "-vn"]
Expand Down Expand Up @@ -179,9 +179,9 @@ def get_frame(self, tt):
# Check that the requested time is in the valid range
if not in_time.any():
raise IOError(
"Error in file %s, " % (self.filename)
+ "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])
+ "with clip duration=%f seconds, " % self.duration
f"Error in file {self.filename}, "
+ f"Accessing time t={tt[0]:.02f}-{tt[-1]:.02f} seconds, "
+ f"with clip duration={self.duration:f} seconds, "
)

# The np.round in the next line is super-important.
Expand All @@ -202,10 +202,10 @@ def get_frame(self, tt):

except IndexError as error:
warnings.warn(
"Error in file %s, " % (self.filename)
+ "At time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])
f"Error in file {self.filename}, "
+ f"At time t={tt[0]:.02f}-{tt[-1]:.02f} seconds, "
+ "indices wanted: %d-%d, " % (indices.min(), indices.max())
+ "but len(buffer)=%d\n" % (len(self.buffer))
+ f"but len(buffer)={len(self.buffer)}\n"
+ str(error),
UserWarning,
)
Expand All @@ -216,7 +216,6 @@ def get_frame(self, tt):
return result

else:

ind = int(self.fps * tt)
if ind < 0 or ind > self.n_frames: # out of time: return 0
return np.zeros(self.nchannels)
Expand Down
1 change: 0 additions & 1 deletion moviepy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ def try_cmd(cmd):
FFMPEG_BINARY = get_exe()

elif FFMPEG_BINARY == "auto-detect":

if try_cmd(["ffmpeg"])[0]:
FFMPEG_BINARY = "ffmpeg"
elif not IS_POSIX_OS and try_cmd(["ffmpeg.exe"])[0]:
Expand Down
19 changes: 8 additions & 11 deletions moviepy/video/VideoClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,6 @@ def write_videofile(
logger = proglog.default_bar_logger(logger)

if codec is None:

try:
codec = extensions_dict[ext]["codec"][0]
except KeyError:
Expand Down Expand Up @@ -359,12 +358,12 @@ def write_videofile(
audio_ext = find_extension(audio_codec)
audiofile = os.path.join(
temp_audiofile_path,
name + Clip._TEMP_FILES_PREFIX + "wvf_snd.%s" % audio_ext,
name + Clip._TEMP_FILES_PREFIX + f"wvf_snd.{audio_ext}",
)

# enough cpu for multiprocessing ? USELESS RIGHT NOW, WILL COME AGAIN
# enough_cpu = (multiprocessing.cpu_count() > 1)
logger(message="MoviePy - Building video %s." % filename)
logger(message=f"MoviePy - Building video {filename}.")
if make_audio:
self.audio.write_audiofile(
audiofile,
Expand Down Expand Up @@ -395,7 +394,7 @@ def write_videofile(
if remove_temp and make_audio:
if os.path.exists(audiofile):
os.remove(audiofile)
logger(message="MoviePy - video ready %s" % filename)
logger(message=f"MoviePy - video ready {filename}")

@requires_duration
@use_clip_fps_by_default
Expand Down Expand Up @@ -1044,7 +1043,6 @@ def __init__(
img = imread(img)

if len(img.shape) == 3: # img is (now) a RGB(a) numpy array

if img.shape[2] == 4:
if fromalpha:
img = 1.0 * img[:, :, 3] / 255
Expand Down Expand Up @@ -1244,7 +1242,6 @@ def __init__(
remove_temp=True,
print_cmd=False,
):

if text is not None:
if temptxt is None:
temptxt_fd, temptxt = tempfile.mkstemp(suffix=".txt")
Expand Down Expand Up @@ -1281,11 +1278,11 @@ def __init__(
if font_size is not None:
cmd += ["-pointsize", "%d" % font_size]
if kerning is not None:
cmd += ["-kerning", "%0.1f" % kerning]
cmd += ["-kerning", f"{kerning:0.1f}"]
if stroke_color is not None:
cmd += ["-stroke", stroke_color, "-strokewidth", "%.01f" % stroke_width]
cmd += ["-stroke", stroke_color, "-strokewidth", f"{stroke_width:.01f}"]
if size is not None:
cmd += ["-size", "%sx%s" % (size[0], size[1])]
cmd += ["-size", f"{size[0]}x{size[1]}"]
if align is not None:
cmd += ["-gravity", align]
if interline is not None:
Expand All @@ -1296,10 +1293,10 @@ def __init__(
os.close(tempfile_fd)

cmd += [
"%s:%s" % (method, text),
f"{method}:{text}",
"-type",
"truecolormatte",
"PNG32:%s" % tempfilename,
f"PNG32:{tempfilename}",
]

if print_cmd:
Expand Down
1 change: 0 additions & 1 deletion moviepy/video/compositing/CompositeVideoClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ class CompositeVideoClip(VideoClip):
def __init__(
self, clips, size=None, bg_color=None, use_bgclip=False, is_mask=False
):

if size is None:
size = clips[0].size

Expand Down
2 changes: 0 additions & 2 deletions moviepy/video/fx/freeze_region.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):
"""
if region is not None:

x1, y1, x2, y2 = region
freeze = (
clip.fx(crop, *region)
Expand All @@ -40,7 +39,6 @@ def freeze_region(clip, t=0, region=None, outside_region=None, mask=None):
return CompositeVideoClip([clip, freeze])

elif outside_region is not None:

x1, y1, x2, y2 = outside_region
animated_region = clip.fx(crop, *outside_region).with_position((x1, y1))
freeze = clip.to_ImageClip(t=t).with_duration(clip.duration)
Expand Down
2 changes: 0 additions & 2 deletions moviepy/video/fx/resize.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ def filter(get_frame, t):
new_size = translate_new_size(new_size)

elif height is not None:

if hasattr(height, "__call__"):

def func(t):
Expand All @@ -203,7 +202,6 @@ def func(t):
new_size = [w * height / h, height]

elif width is not None:

if hasattr(width, "__call__"):

def func(t):
Expand Down
7 changes: 0 additions & 7 deletions moviepy/video/io/ImageSequenceClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ def __init__(
is_mask=False,
load_images=False,
):

# CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE

if (fps is None) and (durations is None):
Expand Down Expand Up @@ -111,12 +110,10 @@ def find_image_index(t):
)

if fromfiles:

self.last_index = None
self.last_image = None

def make_frame(t):

index = find_image_index(t)

if index != self.last_index:
Expand All @@ -126,13 +123,11 @@ def make_frame(t):
return self.last_image

if with_mask and (imread(self.sequence[0]).shape[2] == 4):

self.mask = VideoClip(is_mask=True)
self.mask.last_index = None
self.mask.last_image = None

def mask_make_frame(t):

index = find_image_index(t)
if index != self.mask.last_index:
frame = imread(self.sequence[index])[:, :, 3]
Expand All @@ -147,12 +142,10 @@ def mask_make_frame(t):
else:

def make_frame(t):

index = find_image_index(t)
return self.sequence[index][:, :, :3]

if with_mask and (self.sequence[0].shape[2] == 4):

self.mask = VideoClip(is_mask=True)

def mask_make_frame(t):
Expand Down
4 changes: 0 additions & 4 deletions moviepy/video/io/VideoFileClip.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ def __init__(
fps_source="fps",
pixel_format=None,
):

VideoClip.__init__(self)

# Make a reader
Expand All @@ -122,7 +121,6 @@ def __init__(
self.filename = filename

if has_mask:

self.make_frame = lambda t: self.reader.get_frame(t)[:, :, :3]

def mask_make_frame(t):
Expand All @@ -134,12 +132,10 @@ def mask_make_frame(t):
self.mask.fps = self.fps

else:

self.make_frame = lambda t: self.reader.get_frame(t)

# Make a reader for the audio, if any.
if audio and self.reader.infos["audio_found"]:

self.audio = AudioFileClip(
filename,
buffersize=audio_buffersize,
Expand Down
6 changes: 2 additions & 4 deletions moviepy/video/io/ffmpeg_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ def __init__(
resize_algo="bicubic",
fps_source="fps",
):

self.filename = filename
self.proc = None
infos = ffmpeg_parse_infos(
Expand Down Expand Up @@ -87,11 +86,11 @@ def initialize(self, start_time=0):
offset = min(1, start_time)
i_arg = [
"-ss",
"%.06f" % (start_time - offset),
f"{start_time - offset:.06f}",
"-i",
self.filename,
"-ss",
"%.06f" % offset,
f"{offset:.06f}",
]
else:
i_arg = ["-i", self.filename]
Expand Down Expand Up @@ -577,7 +576,6 @@ def parse(self):

# not default audio found, assume first audio stream is the default
if self.result["audio_found"] and not self.result.get("audio_bitrate"):

self.result["audio_bitrate"] = None
for streams_input in self.result["inputs"]:
for stream in streams_input["streams"]:
Expand Down
4 changes: 2 additions & 2 deletions moviepy/video/io/ffmpeg_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def ffmpeg_extract_subclip(
FFMPEG_BINARY,
"-y",
"-ss",
"%0.2f" % start_time,
f"{start_time:0.2f}",
"-i",
inputfile,
"-t",
"%0.2f" % (end_time - start_time),
f"{end_time - start_time:0.2f}",
"-map",
"0",
"-vcodec",
Expand Down
Loading

0 comments on commit 5039719

Please sign in to comment.