alucho_images.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from collections import namedtuple
  2. from json import loads as from_json
  3. from pathlib import Path
  4. from unicodedata import normalize
  5. '''
  6. This plugin helps loading images for each section.
  7. Images should be located at
  8. <static-folder>/<image-path>/<section-name>/<image-folder>
  9. eg.
  10. static/image/section1/folder-for-my-image/
  11. static/image/section2/subsection/folder-for-another-image/
  12. ...
  13. Each image folder should contain a file named `_metadata.json`
  14. with the following information
  15. {
  16. "name": "<image-name>",
  17. "year": "<year>",
  18. "category": "<category-name>",
  19. "images": ["<main-image-name>", "<image-variant-1>", "<image-variant-2>", ...]
  20. }
  21. Along with the image files which should be called
  22. <main-image-name>
  23. <image-variant-1>
  24. <image-variant-2>
  25. ...
  26. '''
  27. IMAGE_PATH = 'image' # relative to the static path
  28. STATIC = ''
  29. Image = namedtuple('Image', ['key', 'name', 'year',
  30. 'category', 'description', 'main', 'filenames'])
  31. # Functions
  32. def images(section):
  33. sec_path = Path(STATIC, IMAGE_PATH, section)
  34. for path in sec_path.iterdir():
  35. if path.name.startswith('_'):
  36. continue
  37. metafile = path.joinpath('_metadata.json')
  38. if metafile.exists():
  39. img_base = path.relative_to(STATIC)
  40. metadata = from_json(metafile.read_text())
  41. key = path.name.split()[0]
  42. key = int(key) if key.isnumeric() else 0
  43. img = Image(
  44. # key should always be the first field to sort images
  45. key,
  46. metadata.get('name'),
  47. metadata.get('year'),
  48. metadata.get('category'),
  49. metadata.get('description'),
  50. img_base.joinpath(normalize('NFC', metadata.get(
  51. 'main'))) if 'main' in metadata else None,
  52. [img_base.joinpath(normalize('NFC', img_name)) for img_name in metadata.get('images', [])])
  53. yield img
  54. def init_plugin(env, config):
  55. global STATIC
  56. # update var STATIC
  57. STATIC = config['STATIC']
  58. functions = [
  59. images,
  60. sorted,
  61. map,
  62. str,
  63. list
  64. ]
  65. for f in functions:
  66. env.globals[f.__name__] = f