format.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import re
  2. import hashlib
  3. from typing import Dict, Callable, NamedTuple
  4. from pathlib import Path
  5. class Info(NamedTuple):
  6. path: Path
  7. output_ext: str
  8. def hash(i: Info, algo='sha1') -> str:
  9. try:
  10. hash = hashlib.new(algo)
  11. except ImportError:
  12. raise ValueError(f"'{algo}' is invalid hash algorithm")
  13. # TODO: is okay to hash large image?
  14. with open(i.path, 'rb') as file:
  15. hash.update(file.read())
  16. return hash.hexdigest()
  17. pattern = re.compile(r'\[([\w:]+)\]')
  18. # all function must returns string or raise TypeError or ValueError
  19. # other errors will cause the extension error
  20. available_formats: Dict[str, Callable] = {
  21. 'name': lambda i: i.path.stem,
  22. 'extension': lambda i: i.path.suffix[1:],
  23. 'hash': hash,
  24. 'output_extension': lambda i: i.output_ext
  25. }
  26. def format(match: re.Match, info: Info) -> str:
  27. matches = match[1].split(':')
  28. name, args = matches[0], matches[1:]
  29. if name not in available_formats:
  30. return match[0]
  31. return available_formats[name](info, *args)