This is a gentle fork from https://framagit.org/marienfressinaud/photos.marienfressinaud.fr with a responsive and optimized mindset. https://media.larlet.fr/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

boop.py 8.4KB

6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
6 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #!/usr/bin/env python3
  2. import os
  3. import shutil
  4. import re
  5. import yaml
  6. from operator import itemgetter
  7. from jinja2 import Environment, PackageLoader, select_autoescape
  8. from PIL import Image, ExifTags
  9. from dotenv import load_dotenv
  10. from configuration import SITE_TITLE, SITE_AUTHOR, SITE_AUTHOR_WEBSITE, THEME
  11. # Load env var from .env file
  12. load_dotenv(dotenv_path=".env")
  13. PICTURES_DIR_NAME = "photos"
  14. OUTPUT_DIR_NAME = "output"
  15. # Configure YAML to accept environment variables in metadata files
  16. # Based on https://stackoverflow.com/a/27232341 solution
  17. pattern = re.compile(r"^ENV\[\'(.*)\'\]$")
  18. yaml.add_implicit_resolver("!pathex", pattern)
  19. def pathex_constructor(loader, node):
  20. value = loader.construct_scalar(node)
  21. env_var, = pattern.match(value).groups()
  22. return os.getenv(env_var)
  23. yaml.add_constructor("!pathex", pathex_constructor)
  24. def list_galleries_in(path):
  25. gallery_dirs = [f for f in os.scandir(path) if f.is_dir()]
  26. for gallery_dir in gallery_dirs:
  27. metadata = {}
  28. metadata_path = os.path.join(gallery_dir.path, "metadata.yml")
  29. if os.path.exists(metadata_path):
  30. with open(metadata_path, "r") as metadata_file:
  31. metadata = yaml.load(metadata_file)
  32. private = False
  33. url = f"{gallery_dir.name}.html"
  34. output_path = gallery_dir.name
  35. password = metadata.get("password", None)
  36. if password:
  37. private = True
  38. url = f"{gallery_dir.name}-{password}.html"
  39. output_path = f"{output_path}-{password}"
  40. photos = list(list_photos_in(gallery_dir, output_path))
  41. if len(photos) == 0:
  42. continue
  43. photos.sort(key=itemgetter("name"))
  44. # Try to get cover from metadata, if it doesn't exist, take one by
  45. # default.
  46. cover_photo = None
  47. cover_name = metadata.get("cover")
  48. if cover_name:
  49. cover_photo = find_photo(photos, cover_name)
  50. if cover_photo is None:
  51. cover_index = (len(gallery_dir.name) + 42) % len(photos)
  52. cover_photo = photos[cover_index]
  53. gallery = {
  54. "name": metadata.get("name", gallery_dir.name),
  55. "path": gallery_dir.path,
  56. "output_path": output_path,
  57. "url": url,
  58. "num_photos": len(photos),
  59. "photos": photos,
  60. "cover_photo": cover_photo,
  61. "private": private,
  62. }
  63. yield gallery
  64. def find_photo(photos, photo_name):
  65. for photo in photos:
  66. if photo["name"] == photo_name:
  67. return photo
  68. else:
  69. return None
  70. def list_photos_in(gallery_dir, gallery_output_path):
  71. photo_files = [
  72. f for f in os.scandir(gallery_dir) if re.match(".+\.jpg", f.name, re.I)
  73. ]
  74. for photo_file in photo_files:
  75. url = os.path.join(gallery_output_path, photo_file.name)
  76. thumb_url = os.path.join(gallery_output_path, f"thumb_{photo_file.name}")
  77. photo = {
  78. "name": photo_file.name,
  79. "path": photo_file.path,
  80. "url": url,
  81. "thumb_url": thumb_url,
  82. }
  83. yield photo
  84. def generate_output_dir():
  85. output_path = os.path.join(os.curdir, OUTPUT_DIR_NAME)
  86. if not os.path.isdir(output_path):
  87. os.mkdir(output_path)
  88. return output_path
  89. def generate_style(output_path):
  90. style_path = os.path.join(os.curdir, THEME, "style")
  91. style_output_path = os.path.join(output_path, "style")
  92. if os.path.isdir(style_output_path):
  93. shutil.rmtree(style_output_path)
  94. shutil.copytree(style_path, style_output_path)
  95. def generate_index(output_path, galleries):
  96. index_path = os.path.join(output_path, "index.html")
  97. theme_path = os.path.join(os.curdir, THEME)
  98. jinja_env = Environment(
  99. loader=PackageLoader("boop", theme_path), autoescape=select_autoescape(["html"])
  100. )
  101. index_template = jinja_env.get_template("index.html.j2")
  102. with open(index_path, "w") as index_file:
  103. index_file.write(
  104. index_template.render(
  105. galleries=galleries,
  106. site_title=SITE_TITLE,
  107. site_author=SITE_AUTHOR,
  108. site_author_website=SITE_AUTHOR_WEBSITE,
  109. )
  110. )
  111. def generate_gallery(output_path, gallery):
  112. generate_gallery_index(output_path, gallery)
  113. generate_gallery_dir(output_path, gallery)
  114. def generate_gallery_index(output_path, gallery):
  115. gallery_index_path = os.path.join(output_path, f"{gallery['url']}")
  116. theme_path = os.path.join(os.curdir, THEME)
  117. jinja_env = Environment(
  118. loader=PackageLoader("boop", theme_path), autoescape=select_autoescape(["html"])
  119. )
  120. gallery_template = jinja_env.get_template("gallery.html.j2")
  121. with open(gallery_index_path, "w") as gallery_file:
  122. gallery_file.write(
  123. gallery_template.render(
  124. gallery=gallery,
  125. site_title=SITE_TITLE,
  126. site_author=SITE_AUTHOR,
  127. site_author_website=SITE_AUTHOR_WEBSITE,
  128. )
  129. )
  130. def generate_gallery_dir(output_path, gallery):
  131. gallery_output_path = os.path.join(output_path, gallery["output_path"])
  132. if not os.path.isdir(gallery_output_path):
  133. os.mkdir(gallery_output_path)
  134. for photo in gallery["photos"]:
  135. photo_output_path = os.path.join(output_path, photo["url"])
  136. if not os.path.exists(photo_output_path):
  137. shutil.copyfile(photo["path"], photo_output_path)
  138. thumb_output_path = os.path.join(output_path, photo["thumb_url"])
  139. if not os.path.exists(thumb_output_path):
  140. generate_thumb_file(thumb_output_path, photo)
  141. def generate_thumb_file(output_path, photo):
  142. orientation_key = get_orientation_exif_key()
  143. size = (440, 264)
  144. with Image.open(photo["path"]) as image:
  145. # First, make sure image is correctly oriented
  146. exif = image._getexif()
  147. if exif[orientation_key] == 3:
  148. image = image.rotate(180, expand=True)
  149. elif exif[orientation_key] == 6:
  150. image = image.rotate(270, expand=True)
  151. elif exif[orientation_key] == 8:
  152. image = image.rotate(90, expand=True)
  153. w, h = image.size
  154. if w > size[0] and h > size[1]:
  155. # If the original file is larger in width AND height, we resize
  156. # first the image to the lowest size accepted (both width and
  157. # height stays greater or equal to requested size).
  158. # E.g. 1200x900 is resized to 440x330
  159. # 1200x600 is resized to 528x264
  160. if size[0] / size[1] <= w / h:
  161. w = int(max(size[1] * w / h, 1))
  162. h = 264
  163. else:
  164. h = int(max(size[0] * h / w, 1))
  165. w = 440
  166. new_size = (w, h)
  167. image.draft(None, new_size)
  168. image = image.resize(new_size, Image.BICUBIC)
  169. # We now have an image with at least w = 440 OR h = 264 (unless one of
  170. # the size is smaller). But the image can still be larger than
  171. # requested size, so we have to crop the image in the middle.
  172. crop_box = None
  173. if w > size[0]:
  174. left = (w - size[0]) / 2
  175. right = left + size[0]
  176. crop_box = (left, 0, right, h)
  177. elif h > size[1]:
  178. upper = (h - size[1]) / 2
  179. lower = upper + size[1]
  180. crop_box = (0, upper, w, lower)
  181. if crop_box is not None:
  182. image = image.crop(crop_box)
  183. # And we save the final image.
  184. image.save(output_path)
  185. def get_orientation_exif_key():
  186. for (key, tag) in ExifTags.TAGS.items():
  187. if tag == "Orientation":
  188. return key
  189. def main():
  190. print("Loading galleries... ", end="")
  191. pictures_folder = os.path.join(os.curdir, PICTURES_DIR_NAME)
  192. galleries = list(list_galleries_in(pictures_folder))
  193. if len(galleries) == 0:
  194. return
  195. galleries.sort(key=itemgetter("name"))
  196. print(f"{len(galleries)} galleries found.")
  197. print("Generating output folder... ", end="")
  198. output_path = generate_output_dir()
  199. print("✔️")
  200. print("Generating style folder... ", end="")
  201. generate_style(output_path)
  202. print("✔️")
  203. print("Generating index file... ", end="")
  204. generate_index(output_path, galleries)
  205. print("✔️")
  206. for gallery in galleries:
  207. print(f"Generating {gallery['name']} gallery ({gallery['url']})... ", end="")
  208. generate_gallery(output_path, gallery)
  209. print("✔️")
  210. print("Galleries generated 🎉")
  211. if __name__ == "__main__":
  212. main()