Skip to content

Commit

Permalink
Apply silly micro-optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
WyattBlue committed Jan 21, 2025
1 parent 2bfd867 commit 325f924
Show file tree
Hide file tree
Showing 22 changed files with 45 additions and 47 deletions.
4 changes: 2 additions & 2 deletions auto_editor/cmds/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions auto_editor/cmds/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/cmds/levels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_:
Expand Down
6 changes: 3 additions & 3 deletions auto_editor/cmds/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions auto_editor/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/ffwrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/formats/fcp11.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"

Expand Down
4 changes: 2 additions & 2 deletions auto_editor/formats/fcp7.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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("<effect> requires: <effectid> <name> and one <parameter>")
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/formats/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions auto_editor/lang/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
10 changes: 5 additions & 5 deletions auto_editor/lang/palet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}`")
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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]))
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/lang/stdenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:]
Expand Down
2 changes: 0 additions & 2 deletions auto_editor/lib/data_structs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "()"
Expand All @@ -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 "#()"
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/render/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions auto_editor/render/subtitle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.*)")
Expand Down Expand Up @@ -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}")
Expand Down
8 changes: 4 additions & 4 deletions auto_editor/render/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion auto_editor/utils/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
8 changes: 4 additions & 4 deletions auto_editor/utils/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/utils/func.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
6 changes: 3 additions & 3 deletions auto_editor/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion auto_editor/vanparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
6 changes: 3 additions & 3 deletions auto_editor/wavfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 325f924

Please sign in to comment.