utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copy from: https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/utils.py
  2. import hashlib
  3. from pathlib import Path
  4. from typing import Union
  5. def generate_filename(directory: Path, original_filename, *options) -> str:
  6. text = str(directory.absolute()) + original_filename
  7. for v in options:
  8. text += "%s" % v
  9. md5_hash = hashlib.md5()
  10. md5_hash.update(text.encode("utf-8"))
  11. return md5_hash.hexdigest() + ".jpg"
  12. def parse_size(size):
  13. if isinstance(size, int):
  14. # If the size parameter is a single number, assume square aspect.
  15. return [size, size]
  16. if isinstance(size, (tuple, list)):
  17. if len(size) == 1:
  18. # If single value tuple/list is provided, exand it to two elements
  19. return size + type(size)(size)
  20. return size
  21. try:
  22. thumbnail_size = [int(x) for x in size.lower().split("x", 1)]
  23. except ValueError:
  24. raise ValueError( # pylint: disable=raise-missing-from
  25. "Bad thumbnail size format. Valid format is INTxINT."
  26. )
  27. if len(thumbnail_size) == 1:
  28. # If the size parameter only contains a single integer, assume square aspect.
  29. thumbnail_size.append(thumbnail_size[0])
  30. return thumbnail_size
  31. def aspect_to_string(size):
  32. if isinstance(size, str):
  33. return size
  34. return "x".join(map(str, size))
  35. IMG_SUFFIX = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"}
  36. def glob_img(p: Union[Path, str], recursive: bool = False):
  37. p = Path(p)
  38. if p.is_file() and p.suffix in IMG_SUFFIX:
  39. yield p
  40. else:
  41. if recursive:
  42. files = Path(p).glob("**/*.*")
  43. else:
  44. files = Path(p).glob("*.*")
  45. for it in files:
  46. if it.suffix not in IMG_SUFFIX:
  47. continue
  48. yield it