From f132d90373bea7cd75a34a5ce3805371dba8ba75 Mon Sep 17 00:00:00 2001 From: WyattBlue Date: Tue, 21 Jan 2025 01:02:38 -0500 Subject: [PATCH] Apply silly micro-optimization --- auto_editor/cmds/cache.py | 4 ++-- auto_editor/cmds/info.py | 8 ++++---- auto_editor/cmds/levels.py | 2 +- auto_editor/cmds/test.py | 6 +++--- auto_editor/edit.py | 4 ++-- auto_editor/ffwrapper.py | 2 +- auto_editor/formats/fcp11.py | 2 +- auto_editor/formats/fcp7.py | 4 ++-- auto_editor/formats/json.py | 2 +- auto_editor/lang/json.py | 4 ++-- auto_editor/lang/palet.py | 10 +++++----- auto_editor/lang/stdenv.py | 2 +- auto_editor/lib/data_structs.py | 2 -- auto_editor/render/audio.py | 2 +- auto_editor/render/subtitle.py | 4 ++-- auto_editor/render/video.py | 8 ++++---- auto_editor/utils/bar.py | 2 +- auto_editor/utils/container.py | 8 ++++---- auto_editor/utils/func.py | 2 +- auto_editor/utils/types.py | 6 +++--- auto_editor/vanparse.py | 2 +- auto_editor/wavfile.py | 6 +++--- 22 files changed, 45 insertions(+), 47 deletions(-) diff --git a/auto_editor/cmds/cache.py b/auto_editor/cmds/cache.py index b9062d14b..5af422780 100644 --- a/auto_editor/cmds/cache.py +++ b/auto_editor/cmds/cache.py @@ -12,7 +12,7 @@ def main(sys_args: list[str] = sys.argv[1:]) -> None: cache_dir = os.path.join(gettempdir(), f"ae-{__version__}") - if sys_args and sys_args[0] in ("clean", "clear"): + if sys_args and sys_args[0] in {"clean", "clear"}: rmtree(cache_dir, ignore_errors=True) return @@ -26,7 +26,7 @@ def main(sys_args: list[str] = sys.argv[1:]) -> None: return def format_bytes(size: float) -> str: - for unit in ("B", "KiB", "MiB", "GiB", "TiB"): + for unit in {"B", "KiB", "MiB", "GiB", "TiB"}: if size < 1024: return f"{size:.2f} {unit}" size /= 1024 diff --git a/auto_editor/cmds/info.py b/auto_editor/cmds/info.py index 813291a39..4cf8900e9 100644 --- a/auto_editor/cmds/info.py +++ b/auto_editor/cmds/info.py @@ -98,7 +98,7 @@ def main(sys_args: list[str] = sys.argv[1:]) -> None: continue - if ext in (".xml", ".fcpxml", ".mlt"): + if ext in {".xml", ".fcpxml", ".mlt"}: file_info[file] = {"type": "timeline"} continue @@ -169,7 +169,7 @@ def main(sys_args: list[str] = sys.argv[1:]) -> None: return def is_null(key: str, val: object) -> bool: - return val is None or (key in ("bitrate", "duration") and val == 0.0) + return val is None or (key in {"bitrate", "duration"} and val == 0.0) def stream_to_text(text: str, label: str, streams: list[dict[str, Any]]) -> str: if len(streams) > 0: @@ -183,12 +183,12 @@ def stream_to_text(text: str, label: str, streams: list[dict[str, Any]]) -> str: sep = "x" if key == "resolution" else ":" value = sep.join(f"{x}" for x in value) - if key in ( + if key in { "color_range", "color_space", "color_transfer", "color_primaries", - ): + }: if key == "color_range": if value == 1: text += " - color range: 1 (tv)\n" diff --git a/auto_editor/cmds/levels.py b/auto_editor/cmds/levels.py index f1eae4505..b4f7d2fa5 100644 --- a/auto_editor/cmds/levels.py +++ b/auto_editor/cmds/levels.py @@ -59,7 +59,7 @@ def levels_options(parser: ArgumentParser) -> ArgumentParser: def print_arr(arr: NDArray) -> None: print("") print("@start") - if arr.dtype in (np.float64, np.float32, np.float16): + if arr.dtype in {np.float64, np.float32, np.float16}: for a in arr: sys.stdout.write(f"{a:.20f}\n") elif arr.dtype == np.bool_: diff --git a/auto_editor/cmds/test.py b/auto_editor/cmds/test.py index e5d2c5071..2156a6994 100644 --- a/auto_editor/cmds/test.py +++ b/auto_editor/cmds/test.py @@ -723,13 +723,13 @@ def palet_scripts(): tests = [] - if args.category in ("palet", "all"): + if args.category in {"palet", "all"}: tests.extend([palet_python_bridge, palet_scripts]) - if args.category in ("sub", "all"): + if args.category in {"sub", "all"}: tests.extend([info, levels, subdump, desc]) - if args.category in ("cli", "all"): + if args.category in {"cli", "all"}: tests.extend( [ premiere, diff --git a/auto_editor/edit.py b/auto_editor/edit.py index 681d5b47f..566ea89f3 100644 --- a/auto_editor/edit.py +++ b/auto_editor/edit.py @@ -240,7 +240,7 @@ def edit_media(paths: list[str], args: Args, log: Log) -> None: make_json_timeline(export_ops["api"], output, tl, log) return - if export in ("premiere", "resolve-fcp7"): + if export in {"premiere", "resolve-fcp7"}: from auto_editor.formats.fcp7 import fcp7_write_xml is_resolve = export.startswith("resolve") @@ -449,7 +449,7 @@ def append_filename(path: str, val: str) -> str: log.stop_timer() - if not args.no_open and export in ("default", "audio"): + if not args.no_open and export in {"default", "audio"}: if args.player is None: if sys.platform == "win32": try: diff --git a/auto_editor/ffwrapper.py b/auto_editor/ffwrapper.py index 1e3e9f3ed..27b04ad83 100644 --- a/auto_editor/ffwrapper.py +++ b/auto_editor/ffwrapper.py @@ -111,7 +111,7 @@ def initFileInfo(path: str, log: Log) -> FileInfo: vdur = 0.0 fps = v.average_rate - if (fps is None or fps < 1) and v.name in ("png", "mjpeg", "webp"): + if (fps is None or fps < 1) and v.name in {"png", "mjpeg", "webp"}: fps = Fraction(25) if fps is None or fps == 0: fps = Fraction(30) diff --git a/auto_editor/formats/fcp11.py b/auto_editor/formats/fcp11.py index 196b6da68..e5836775e 100644 --- a/auto_editor/formats/fcp11.py +++ b/auto_editor/formats/fcp11.py @@ -36,7 +36,7 @@ def get_colorspace(src: FileInfo) -> str: return "6-1-6 (Rec. 601 NTSC)" if s.color_primaries == 9: # "bt2020" # See: https://video.stackexchange.com/questions/22059/how-to-identify-hdr-video - if s.color_transfer in (16, 18): # "smpte2084" "arib-std-b67" + if s.color_transfer in {16, 18}: # "smpte2084" "arib-std-b67" return "9-18-9 (Rec. 2020 HLG)" return "9-1-9 (Rec. 2020)" diff --git a/auto_editor/formats/fcp7.py b/auto_editor/formats/fcp7.py index 41c397899..99d0e9471 100644 --- a/auto_editor/formats/fcp7.py +++ b/auto_editor/formats/fcp7.py @@ -99,7 +99,7 @@ def set_tb_ntsc(tb: Fraction) -> tuple[int, str]: return 60, "TRUE" ctb = ceil(tb) - if ctb not in (24, 30, 60) and ctb * Fraction(999, 1000) == tb: + if ctb not in {24, 30, 60} and ctb * Fraction(999, 1000) == tb: return ctb, "TRUE" return int(tb), "FALSE" @@ -151,7 +151,7 @@ def speedup(speed: float) -> Element: def read_filters(clipitem: Element, log: Log) -> float: for effect_tag in clipitem: - if effect_tag.tag in ("enabled", "start", "end"): + if effect_tag.tag in {"enabled", "start", "end"}: continue if len(effect_tag) < 3: log.error(" requires: and one ") diff --git a/auto_editor/formats/json.py b/auto_editor/formats/json.py index 66fedd123..bf859d37d 100644 --- a/auto_editor/formats/json.py +++ b/auto_editor/formats/json.py @@ -239,7 +239,7 @@ def read_json(path: str, log: Log) -> v3: def make_json_timeline(ver: int, out: str | int, tl: v3, log: Log) -> None: - if ver not in (3, 1): + if ver not in {3, 1}: log.error(f"Version {ver} is not supported!") if isinstance(out, str): diff --git a/auto_editor/lang/json.py b/auto_editor/lang/json.py index 73fb2eb8a..b08c6a941 100644 --- a/auto_editor/lang/json.py +++ b/auto_editor/lang/json.py @@ -204,7 +204,7 @@ def eat(self) -> None: def expr(self) -> Any: self.current_token - if self.current_token.type in (STR, VAL): + if self.current_token.type in {STR, VAL}: val = self.current_token.value self.eat() return val @@ -215,7 +215,7 @@ def expr(self) -> Any: my_dic = {} while self.current_token.type != RCUR: if self.current_token.type != STR: - if self.current_token.type in (LBRAC, VAL): + if self.current_token.type in {LBRAC, VAL}: self.lexer.error("JSON Objects only allow strings as keys") self.lexer.error("Expected closing `}`") key = self.current_token.value diff --git a/auto_editor/lang/palet.py b/auto_editor/lang/palet.py index 092444e08..48f162bd9 100644 --- a/auto_editor/lang/palet.py +++ b/auto_editor/lang/palet.py @@ -218,10 +218,10 @@ def hash_literal(self) -> Token: self.advance() result = buf.getvalue() - if result in ("t", "T", "true"): + if result in {"t", "T", "true"}: return Token(VAL, True, self.lineno, self.column) - if result in ("f", "F", "false"): + if result in {"f", "F", "false"}: return Token(VAL, False, self.lineno, self.column) self.error(f"Unknown hash literal `#{result}`") @@ -451,7 +451,7 @@ def expr(self) -> Any: self.eat() childs = [] - while self.current_token.type not in (RPAREN, RBRAC, RCUR, EOF): + while self.current_token.type not in {RPAREN, RBRAC, RCUR, EOF}: childs.append(self.expr()) return tuple(childs) @@ -512,7 +512,7 @@ def p_slice( is_iterable = Contract( "iterable?", - lambda v: type(v) in (str, range, list, tuple, dict, Quoted) + lambda v: type(v) in {str, range, list, tuple, dict, Quoted} or isinstance(v, np.ndarray), ) is_boolarr = Contract( @@ -689,7 +689,7 @@ def make_trace(sym: Sym) -> str: length = len(node[1:]) if length > 3: raise MyError(f"{print_str(node[0])}: slice expects 1 argument") - if length in (2, 3): + if length in {2, 3}: return p_slice(oper, *(my_eval(env, c) for c in node[1:])) if length == 1: return ref(oper, my_eval(env, node[1])) diff --git a/auto_editor/lang/stdenv.py b/auto_editor/lang/stdenv.py index a1d402b5a..9002d3e0c 100644 --- a/auto_editor/lang/stdenv.py +++ b/auto_editor/lang/stdenv.py @@ -283,7 +283,7 @@ def syn_define(env: Env, node: Node) -> None: type(node[2]) is tuple and node[2] and type(node[2][0]) is Sym - and node[2][0].val in ("lambda", "λ") + and node[2][0].val in {"lambda", "λ"} ): terms = node[2][1] body = node[2][2:] diff --git a/auto_editor/lib/data_structs.py b/auto_editor/lib/data_structs.py index f77d09c7f..a0ce0461e 100644 --- a/auto_editor/lib/data_structs.py +++ b/auto_editor/lib/data_structs.py @@ -191,7 +191,6 @@ def display_str(val: object) -> str: return f"{float(val)}" if type(val) is Fraction: return f"{val.numerator}/{val.denominator}" - if type(val) is Quoted or type(val) is tuple: if not val: return "()" @@ -201,7 +200,6 @@ def display_str(val: object) -> str: result.write(f" {display_str(item)}") result.write(")") return result.getvalue() - if type(val) is list: if not val: return "#()" diff --git a/auto_editor/render/audio.py b/auto_editor/render/audio.py index 0f63c3dff..c0da2c7a4 100644 --- a/auto_editor/render/audio.py +++ b/auto_editor/render/audio.py @@ -62,7 +62,7 @@ def parse_ebu_bytes(norm: dict, stat: bytes, log: Log) -> tuple[str, str]: except MyError: log.error(f"Invalid loudnorm stats.\n{stat!r}") - for key in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset"): + for key in {"input_i", "input_tp", "input_lra", "input_thresh", "target_offset"}: val = float(parsed[key]) if val == float("-inf"): parsed[key] = -99 diff --git a/auto_editor/render/subtitle.py b/auto_editor/render/subtitle.py index 2022e7bc8..505f48ce9 100644 --- a/auto_editor/render/subtitle.py +++ b/auto_editor/render/subtitle.py @@ -53,7 +53,7 @@ def parse(self, text: str, codec: str) -> None: self.codec = codec self.contents = [] - if codec == "ass" or codec == "ssa": + if codec in {"ass", "ssa"}: time_code = re.compile(r"(.*)(\d+:\d+:[\d.]+)(.*)(\d+:\d+:[\d.]+)(.*)") elif codec == "webvtt": time_code = re.compile(r"()(\d+:[\d.]+)( --> )(\d+:[\d.]+)(\n.*)") @@ -189,7 +189,7 @@ def make_new_subtitles(tl: v3, log: Log) -> list[str]: parser = SubtitleParser(tl.tb) if sub.codec == "ssa": format = "ass" - elif sub.codec in ("webvtt", "ass"): + elif sub.codec in {"webvtt", "ass"}: format = sub.codec else: log.error(f"Unknown subtitle codec: {sub.codec}") diff --git a/auto_editor/render/video.py b/auto_editor/render/video.py index f809e7355..8db995ebe 100644 --- a/auto_editor/render/video.py +++ b/auto_editor/render/video.py @@ -54,7 +54,7 @@ class VideoFrame: def make_solid(width: int, height: int, pix_fmt: str, bg: str) -> av.VideoFrame: hex_color = bg.lstrip("#").upper() - rgb_color = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4)) + rgb_color = tuple(int(hex_color[i : i + 2], 16) for i in {0, 2, 4}) rgb_array = np.full((height, width, 3), rgb_color, dtype=np.uint8) rgb_frame = av.VideoFrame.from_ndarray(rgb_array, format="rgb24") @@ -177,9 +177,9 @@ def render_av( color_prim = src.videos[0].color_primaries color_trc = src.videos[0].color_transfer - if color_range == 1 or color_range == 2: + if color_range in {1, 2}: output_stream.color_range = color_range - if colorspace in (0, 1) or (colorspace >= 3 and colorspace < 16): + if colorspace in {0, 1} or (colorspace >= 3 and colorspace < 16): output_stream.colorspace = colorspace if color_prim == 1 or (color_prim >= 4 and color_prim < 17): output_stream.color_primaries = color_prim @@ -310,7 +310,7 @@ def render_av( roi = array[y_start:y_end, x_start:x_end] # Blend the overlay image with the ROI based on the opacity - roi = (1 - obj.opacity) * roi + obj.opacity * clipped_overlay + roi = (1 - obj.opacity) * roi + obj.opacity * clipped_overlay # type: ignore array[y_start:y_end, x_start:x_end] = roi array = np.clip(array, 0, 255).astype(np.uint8) diff --git a/auto_editor/utils/bar.py b/auto_editor/utils/bar.py index 898a9245d..b48450b4e 100644 --- a/auto_editor/utils/bar.py +++ b/auto_editor/utils/bar.py @@ -31,7 +31,7 @@ def initBar(bar_type: str) -> Bar: part_width = len(chars) - 1 ampm = True - if sys.platform == "darwin" and bar_type in ("modern", "classic", "ascii"): + if sys.platform == "darwin" and bar_type in {"modern", "classic", "ascii"}: try: date_format = get_stdout_bytes( ["defaults", "read", "com.apple.menuextra.clock", "Show24Hour"] diff --git a/auto_editor/utils/container.py b/auto_editor/utils/container.py index 9342432bf..2ac1a9d9c 100644 --- a/auto_editor/utils/container.py +++ b/auto_editor/utils/container.py @@ -47,11 +47,11 @@ class Container: def codec_type(x: str) -> str: - if x in ("vp9", "vp8", "h264", "hevc", "av1", "gif", "apng"): + if x in {"vp9", "vp8", "h264", "hevc", "av1", "gif", "apng"}: return "video" - if x in ("aac", "flac", "mp3"): + if x in {"aac", "flac", "mp3"}: return "audio" - if x in ("ass", "ssa", "srt"): + if x in {"ass", "ssa", "srt"}: return "subtitle" try: @@ -93,7 +93,7 @@ def container_constructor(ext: str) -> Container: if kind == "subtitle": scodecs.add(codec) - allow_image = ext in ("mp4", "mkv") + allow_image = ext in {"mp4", "mkv"} kwargs = containers[ext] if ext in containers else {} return Container( diff --git a/auto_editor/utils/func.py b/auto_editor/utils/func.py index a779bc679..82298bf20 100644 --- a/auto_editor/utils/func.py +++ b/auto_editor/utils/func.py @@ -41,7 +41,7 @@ def to_timecode(secs: float | Fraction, fmt: str) -> str: if h == 0: return f"{sign}{m:02d}:{s:06.3f}" return f"{sign}{h:02d}:{m:02d}:{s:06.3f}" - if fmt == "srt" or fmt == "mov_text": + if fmt in {"srt", "mov_text"}: return f"{sign}{h:02d}:{m:02d}:" + f"{s:06.3f}".replace(".", ",", 1) if fmt == "standard": return f"{sign}{h:02d}:{m:02d}:{s:06.3f}" diff --git a/auto_editor/utils/types.py b/auto_editor/utils/types.py index 342ecb472..9caf9c2ef 100644 --- a/auto_editor/utils/types.py +++ b/auto_editor/utils/types.py @@ -104,7 +104,7 @@ def frame_rate(val: str) -> Fraction: def sample_rate(val: str) -> int: num, unit = _split_num_str(val) - if unit in ("kHz", "KHz"): + if unit in {"kHz", "KHz"}: return natural(num * 1000) _unit_check(unit, ("", "Hz")) return natural(num) @@ -122,9 +122,9 @@ def time(val: str, tb: Fraction) -> int: raise CoerceError(f"'{val}': Invalid time format") num, unit = _split_num_str(val) - if unit in ("s", "sec", "secs", "second", "seconds"): + if unit in {"s", "sec", "secs", "second", "seconds"}: return round(num * tb) - if unit in ("min", "mins", "minute", "minutes"): + if unit in {"min", "mins", "minute", "minutes"}: return round(num * tb * 60) if unit == "hour": return round(num * tb * 3600) diff --git a/auto_editor/vanparse.py b/auto_editor/vanparse.py index c8ec13016..09f6c7aa8 100644 --- a/auto_editor/vanparse.py +++ b/auto_editor/vanparse.py @@ -289,7 +289,7 @@ def parse_value(option: Options | Required, val: str | None) -> Any: key = to_key(option) next_arg = None if i == len(sys_args) - 1 else sys_args[i + 1] - if next_arg in ("-h", "--help"): + if next_arg in {"-h", "--help"}: print_option_help(program_name, ns_obj, option) sys.exit() diff --git a/auto_editor/wavfile.py b/auto_editor/wavfile.py index f1952a108..352cf14af 100644 --- a/auto_editor/wavfile.py +++ b/auto_editor/wavfile.py @@ -90,7 +90,7 @@ def _read_data_chunk( bytes_per_sample = block_align // channels - if bytes_per_sample in (3, 5, 6, 7): + if bytes_per_sample in {3, 5, 6, 7}: raise WavError(f"Unsupported bytes per sample: {bytes_per_sample}") if format_tag == PCM: @@ -103,7 +103,7 @@ def _read_data_chunk( f"Unsupported bit depth: the WAV file has {bit_depth}-bit integer data." ) elif format_tag == IEEE_FLOAT: - if bit_depth in (32, 64): + if bit_depth in {32, 64}: dtype = f"{en}f{bytes_per_sample}" else: raise WavError( @@ -201,7 +201,7 @@ def _handle_pad_byte(fid: Reader, size: int) -> None: def read(fid: Reader) -> tuple[int, AudioData]: file_sig = fid.read(4) - if file_sig in (b"RIFF", b"RIFX"): + if file_sig in {b"RIFF", b"RIFX"}: data_size, file_size, en = _read_riff_chunk(file_sig, fid) elif file_sig == b"RF64": data_size, file_size, en = _read_rf64_chunk(fid)