photos.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. import logging
  6. from pelican import signals
  7. from pelican.utils import pelican_open
  8. from PIL import Image, ExifTags
  9. from itertools import chain
  10. logger = logging.getLogger(__name__)
  11. queue_resize = dict()
  12. hrefs = None
  13. def initialized(pelican):
  14. p = os.path.expanduser('~/Pictures')
  15. from pelican.settings import DEFAULT_CONFIG
  16. DEFAULT_CONFIG.setdefault('PHOTO_LIBRARY', p)
  17. DEFAULT_CONFIG.setdefault('PHOTO_GALLERY', (1024, 768, 80))
  18. DEFAULT_CONFIG.setdefault('PHOTO_ARTICLE', ( 760, 506, 80))
  19. DEFAULT_CONFIG.setdefault('PHOTO_THUMB', ( 192, 144, 60))
  20. if pelican:
  21. pelican.settings.setdefault('PHOTO_LIBRARY', p)
  22. pelican.settings.setdefault('PHOTO_GALLERY', (1024, 768, 80))
  23. pelican.settings.setdefault('PHOTO_ARTICLE', ( 760, 506, 80))
  24. pelican.settings.setdefault('PHOTO_THUMB', ( 192, 144, 60))
  25. def read_notes(filename, msg=None):
  26. notes = {}
  27. try:
  28. with pelican_open(filename) as text:
  29. for line in text.splitlines():
  30. m = line.split(':', 1)
  31. if len(m) > 1:
  32. pic = m[0].strip()
  33. note = m[1].strip()
  34. if pic and note:
  35. notes[pic] = note
  36. except:
  37. if msg:
  38. logger.warning(msg, filename)
  39. return notes
  40. def enqueue_resize(orig, resized, spec=(640, 480, 80)):
  41. global queue_resize
  42. if resized not in queue_resize:
  43. queue_resize[resized] = (orig, spec)
  44. elif queue_resize[resized] != (orig, spec):
  45. logger.error('photos: resize conflict for {}, {}-{} is not {}-{}',
  46. resized,
  47. queue_resize[resized][0], queue_resize[resized][1],
  48. orig, spec)
  49. def resize_photos(generator, writer):
  50. print('photos: {} photo resizes to consider.'
  51. .format(len(queue_resize.items())))
  52. for resized, what in queue_resize.items():
  53. resized = os.path.join(generator.output_path, resized)
  54. orig, spec = what
  55. if (not os.path.isfile(resized) or
  56. os.path.getmtime(orig) > os.path.getmtime(resized)):
  57. logger.info('photos: make photo %s -> %s', orig, resized)
  58. im = Image.open(orig)
  59. try:
  60. exif = im._getexif()
  61. except Exception:
  62. exif = None
  63. try:
  64. icc_profile = im.info.get("icc_profile")
  65. except Exception:
  66. icc_profile = None
  67. if exif:
  68. for tag, value in exif.items():
  69. decoded = ExifTags.TAGS.get(tag, tag)
  70. if decoded == 'Orientation':
  71. if value == 3: im = im.rotate(180)
  72. elif value == 6: im = im.rotate(270)
  73. elif value == 8: im = im.rotate(90)
  74. break
  75. im.thumbnail((spec[0], spec[1]), Image.ANTIALIAS)
  76. try:
  77. os.makedirs(os.path.split(resized)[0])
  78. except:
  79. pass
  80. im.save(resized, 'JPEG', quality=spec[2], icc_profile=icc_profile)
  81. def detect_content(content):
  82. def replacer(m):
  83. what = m.group('what')
  84. value = m.group('value')
  85. origin = m.group('path')
  86. if what == 'photo':
  87. if value.startswith('/'):
  88. value = value[1:]
  89. path = os.path.join(
  90. os.path.expanduser(settings['PHOTO_LIBRARY']),
  91. value)
  92. if not os.path.isfile(path):
  93. logger.error('photos: No photo %s', path)
  94. else:
  95. photo = os.path.splitext(value)[0].lower() + 'a.jpg'
  96. origin = os.path.join(settings['SITEURL'], 'photos', photo)
  97. enqueue_resize(
  98. path,
  99. os.path.join('photos', photo),
  100. settings['PHOTO_ARTICLE'])
  101. return ''.join((m.group('markup'), m.group('quote'), origin,
  102. m.group('quote')))
  103. global hrefs
  104. if hrefs is None:
  105. regex = r"""
  106. (?P<markup><\s*[^\>]* # match tag with src and href attr
  107. (?:href|src)\s*=)
  108. (?P<quote>["\']) # require value to be quoted
  109. (?P<path>{0}(?P<value>.*?)) # the url value
  110. \2""".format(content.settings['INTRASITE_LINK_REGEX'])
  111. hrefs = re.compile(regex, re.X)
  112. if content._content and '{photo}' in content._content:
  113. settings = content.settings
  114. content._content = hrefs.sub(replacer, content._content)
  115. def process_gallery_photo(generator, article, gallery):
  116. if gallery.startswith('/'):
  117. gallery = gallery[1:]
  118. galleries = gallery.split('{photo}')
  119. article.photo_gallery = []
  120. for gallery in galleries:
  121. # strip whitespaces
  122. gallery = gallery.strip()
  123. dir_gallery = os.path.join(
  124. os.path.expanduser(generator.settings['PHOTO_LIBRARY']),
  125. gallery)
  126. if os.path.isdir(dir_gallery):
  127. logger.info('photos: Gallery detected: %s', gallery)
  128. dir_photo = os.path.join('photos', gallery.lower())
  129. dir_thumb = os.path.join('photos', gallery.lower())
  130. exifs = read_notes(os.path.join(dir_gallery, 'exif.txt'),
  131. msg='photos: No EXIF for gallery %s')
  132. captions = read_notes(os.path.join(dir_gallery, 'captions.txt'))
  133. articleGallery = []
  134. for pic in sorted(os.listdir(dir_gallery)):
  135. if pic.startswith('.'): continue
  136. if pic.endswith('.txt'): continue
  137. photo = os.path.splitext(pic)[0].lower() + '.jpg'
  138. thumb = os.path.splitext(pic)[0].lower() + 't.jpg'
  139. articleGallery.append((
  140. pic,
  141. os.path.join(dir_photo, photo),
  142. os.path.join(dir_thumb, thumb),
  143. exifs.get(pic, ''),
  144. captions.get(pic, '')))
  145. enqueue_resize(
  146. os.path.join(dir_gallery, pic),
  147. os.path.join(dir_photo, photo),
  148. generator.settings['PHOTO_GALLERY'])
  149. enqueue_resize(
  150. os.path.join(dir_gallery, pic),
  151. os.path.join(dir_thumb, thumb),
  152. generator.settings['PHOTO_THUMB'])
  153. article.photo_gallery.append((gallery, articleGallery))
  154. else:
  155. logger.error('photos: Gallery does not exist: %s at %s', gallery, dir_gallery)
  156. def process_gallery_filename(generator, article, gallery):
  157. if gallery.startswith('/'):
  158. gallery = gallery[1:]
  159. else:
  160. gallery = os.path.join(article.relative_dir, gallery)
  161. dir_gallery = os.path.join(generator.path, gallery)
  162. if os.path.isdir(dir_gallery):
  163. logger.info('photos: Gallery detected: %s', gallery)
  164. dir_photo = gallery.lower()
  165. dir_thumb = os.path.join('photos', gallery.lower())
  166. exifs = read_notes(os.path.join(dir_gallery, 'exif.txt'),
  167. msg='photos: No EXIF for gallery %s')
  168. captions = read_notes(os.path.join(dir_gallery, 'captions.txt'))
  169. article.photo_gallery = []
  170. for pic in sorted(os.listdir(dir_gallery)):
  171. if pic.startswith('.'): continue
  172. if pic.endswith('.txt'): continue
  173. photo = pic.lower()
  174. thumb = os.path.splitext(pic)[0].lower() + 't.jpg'
  175. article.photo_gallery.append((
  176. pic,
  177. os.path.join(dir_photo, photo),
  178. os.path.join(dir_thumb, thumb),
  179. exifs.get(pic, ''),
  180. captions.get(pic, '')))
  181. enqueue_resize(
  182. os.path.join(dir_gallery, pic),
  183. os.path.join(dir_thumb, thumb),
  184. generator.settings['PHOTO_THUMB'])
  185. else:
  186. logger.error('photos: Gallery does not exist: %s at %s', gallery, dir_gallery)
  187. def detect_gallery(generator):
  188. for article in chain(generator.articles, generator.drafts):
  189. if 'gallery' in article.metadata:
  190. gallery = article.metadata.get('gallery')
  191. if gallery.startswith('{photo}'):
  192. process_gallery_photo(generator, article, gallery[7:])
  193. elif gallery.startswith('{filename}'):
  194. process_gallery_filename(generator, article, gallery[10:])
  195. elif gallery:
  196. logger.error('photos: Gallery tag not recognized: %s', gallery)
  197. def process_image_photo(generator, article, image):
  198. if image.startswith('/'):
  199. image = image[1:]
  200. path = os.path.join(
  201. os.path.expanduser(generator.settings['PHOTO_LIBRARY']),
  202. image)
  203. if os.path.isfile(path):
  204. photo = os.path.splitext(image)[0].lower() + 'a.jpg'
  205. thumb = os.path.splitext(image)[0].lower() + 't.jpg'
  206. article.photo_image = (
  207. os.path.basename(image).lower(),
  208. os.path.join('photos', photo),
  209. os.path.join('photos', thumb))
  210. enqueue_resize(
  211. path,
  212. os.path.join('photos', photo),
  213. generator.settings['PHOTO_ARTICLE'])
  214. enqueue_resize(
  215. path,
  216. os.path.join('photos', thumb),
  217. generator.settings['PHOTO_THUMB'])
  218. else:
  219. logger.error('photo: No photo for %s at %s', article.source_path, path)
  220. def process_image_filename(generator, article, image):
  221. if image.startswith('/'):
  222. image = image[1:]
  223. else:
  224. image = os.path.join(article.relative_dir, image)
  225. path = os.path.join(generator.path, image)
  226. if os.path.isfile(path):
  227. small = os.path.splitext(image)[0].lower() + 't.jpg'
  228. article.photo_image = (
  229. os.path.basename(image),
  230. image.lower(),
  231. os.path.join('photos', small))
  232. enqueue_resize(
  233. path,
  234. os.path.join('photos', small),
  235. generator.settings['PHOTO_THUMB'])
  236. else:
  237. logger.error('photos: No photo at %s', path)
  238. def detect_image(generator):
  239. for article in chain(generator.articles, generator.drafts):
  240. image = article.metadata.get('image', None)
  241. if image:
  242. if image.startswith('{photo}'):
  243. process_image_photo(generator, article, image[7:])
  244. elif image.startswith('{filename}'):
  245. process_image_filename(generator, article, image[10:])
  246. else:
  247. logger.error('photos: Image tag not recognized: %s', image)
  248. def register():
  249. signals.initialized.connect(initialized)
  250. signals.content_object_init.connect(detect_content)
  251. signals.article_generator_finalized.connect(detect_gallery)
  252. signals.article_generator_finalized.connect(detect_image)
  253. signals.article_writer_finalized.connect(resize_photos)