Skip to content

Instantly share code, notes, and snippets.

@nerodono
Created July 13, 2024 19:08
Show Gist options
  • Save nerodono/ffc3b1fdd73bf0b1080aa08848f47e01 to your computer and use it in GitHub Desktop.
Save nerodono/ffc3b1fdd73bf0b1080aa08848f47e01 to your computer and use it in GitHub Desktop.
VienDesu! VNTools compressor implementation hint
import typing as t
import dataclasses as dtc
from functools import reduce
from pathlib import Path
class FileIsNotSupportedError(Exception):
def __init__(self, path: Path) -> None:
self.path = path
super().__init__(f"files of that kind are not supported by this compressor (path: {path})")
@dtc.dataclass(frozen=True)
class Diff:
before: int
now: int
# Compression ratio
@property
def ratio(self) -> float:
return self.before / self.now
class Compressor(t.Protocol):
def __call__(self, source: Path, dest: Path) -> Diff:
...
class Or(Compressor):
def __init__(self, lhs: Compressor, rhs: Compressor) -> None:
self.lhs = lhs
self.rhs = rhs
def __call__(self, source: Path, dest: Path) -> Diff:
try:
return self.lhs(source, dest)
except FileIsNotSupportedError as lhs_exc:
try:
return self.rhs(source, dest)
except FileIsNotSupportedError as rhs_exc:
raise rhs_exc from lhs_exc
# Creates one compressor from many compressors
def alt(first: Compressor, *others: Compressor) -> Compressor:
return reduce(Or, others, first)
compress = alt(images, videos, audio)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment