alucho_images.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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', 'category', 'description', 'main', 'filenames'])
  30. # Functions
  31. def images(section):
  32. sec_path = Path(STATIC, IMAGE_PATH, section)
  33. for path in sec_path.iterdir():
  34. if path.name.startswith('_'):
  35. continue
  36. metafile = path.joinpath('_metadata.json')
  37. if metafile.exists():
  38. img_base = path.relative_to(STATIC)
  39. metadata = from_json(metafile.read_text())
  40. key = path.name.split()[0]
  41. key = int(key) if key.isnumeric() else 0
  42. img = Image(
  43. # key should always be the first field to sort images
  44. key,
  45. metadata.get('name'),
  46. metadata.get('year'),
  47. metadata.get('category'),
  48. metadata.get('description'),
  49. img_base.joinpath(normalize('NFC', metadata.get('main'))) if 'main' in metadata else None,
  50. [img_base.joinpath(normalize('NFC', img_name)) for img_name in metadata.get('images', [])])
  51. yield img
  52. def init_plugin(env, config):
  53. global STATIC
  54. # update var STATIC
  55. STATIC = config['STATIC']
  56. functions = [
  57. images,
  58. sorted,
  59. map,
  60. str,
  61. list
  62. ]
  63. for f in functions:
  64. env.globals[f.__name__] = f