12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- from collections import namedtuple
- from json import loads as from_json
- from pathlib import Path
- from unicodedata import normalize
- '''
- This plugin helps loading images for each section.
- Images should be located at
- <static-folder>/<image-path>/<section-name>/<image-folder>
- eg.
- static/image/section1/folder-for-my-image/
- static/image/section2/subsection/folder-for-another-image/
- ...
- Each image folder should contain a file named `_metadata.json`
- with the following information
- {
- "name": "<image-name>",
- "year": "<year>",
- "category": "<category-name>",
- "images": ["<main-image-name>", "<image-variant-1>", "<image-variant-2>", ...]
- }
- Along with the image files which should be called
- <main-image-name>
- <image-variant-1>
- <image-variant-2>
- ...
- '''
- IMAGE_PATH = 'image' # relative to the static path
- STATIC = ''
- Image = namedtuple('Image', ['key', 'name', 'year', 'category', 'description', 'main', 'filenames'])
- # Functions
- def images(section):
- sec_path = Path(STATIC, IMAGE_PATH, section)
- for path in sec_path.iterdir():
- if path.name.startswith('_'):
- continue
- metafile = path.joinpath('_metadata.json')
- if metafile.exists():
- img_base = path.relative_to(STATIC)
- metadata = from_json(metafile.read_text())
- key = path.name.split()[0]
- key = int(key) if key.isnumeric() else 0
- img = Image(
- # key should always be the first field to sort images
- key,
- metadata.get('name'),
- metadata.get('year'),
- metadata.get('category'),
- metadata.get('description'),
- img_base.joinpath(normalize('NFC', metadata.get('main'))) if 'main' in metadata else None,
- [img_base.joinpath(normalize('NFC', img_name)) for img_name in metadata.get('images', [])])
- yield img
- def init_plugin(env, config):
- global STATIC
- STATIC = config['STATIC']
- env.globals['images'] = images
- env.globals['sorted'] = sorted
|