photos.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. import itertools
  5. import json
  6. import logging
  7. import multiprocessing
  8. import os
  9. import pprint
  10. import re
  11. import sys
  12. from pelican.generators import ArticlesGenerator
  13. from pelican.generators import PagesGenerator
  14. from pelican.settings import DEFAULT_CONFIG
  15. from pelican import signals
  16. from pelican.utils import pelican_open
  17. logger = logging.getLogger(__name__)
  18. try:
  19. from PIL import Image
  20. from PIL import ImageDraw
  21. from PIL import ImageEnhance
  22. from PIL import ImageFont
  23. except ImportError:
  24. logger.error('PIL/Pillow not found')
  25. try:
  26. import piexif
  27. except ImportError:
  28. ispiexif = False
  29. logger.warning('piexif not found! Cannot use exif manipulation features')
  30. else:
  31. ispiexif = True
  32. logger.debug('piexif found.')
  33. def initialized(pelican):
  34. p = os.path.expanduser('~/Pictures')
  35. DEFAULT_CONFIG.setdefault('PHOTO_LIBRARY', p)
  36. DEFAULT_CONFIG.setdefault('PHOTO_GALLERY', (1024, 768, 80))
  37. DEFAULT_CONFIG.setdefault('PHOTO_ARTICLE', (760, 506, 80))
  38. DEFAULT_CONFIG.setdefault('PHOTO_THUMB', (192, 144, 60))
  39. DEFAULT_CONFIG.setdefault('PHOTO_GALLERY_TITLE', '')
  40. DEFAULT_CONFIG.setdefault('PHOTO_ALPHA_BACKGROUND_COLOR', (255, 255, 255))
  41. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK', False)
  42. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_THUMB', False)
  43. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_TEXT', DEFAULT_CONFIG['SITENAME'])
  44. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_TEXT_COLOR', (255, 255, 255))
  45. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_IMG', '')
  46. DEFAULT_CONFIG.setdefault('PHOTO_WATERMARK_IMG_SIZE', False)
  47. DEFAULT_CONFIG.setdefault('PHOTO_RESIZE_JOBS', 1)
  48. DEFAULT_CONFIG.setdefault('PHOTO_EXIF_KEEP', False)
  49. DEFAULT_CONFIG.setdefault('PHOTO_EXIF_REMOVE_GPS', False)
  50. DEFAULT_CONFIG.setdefault('PHOTO_EXIF_AUTOROTATE', True)
  51. DEFAULT_CONFIG.setdefault('PHOTO_EXIF_COPYRIGHT', False)
  52. DEFAULT_CONFIG.setdefault('PHOTO_EXIF_COPYRIGHT_AUTHOR', DEFAULT_CONFIG['SITENAME'])
  53. DEFAULT_CONFIG.setdefault('PHOTO_LIGHTBOX_GALLERY_ATTR', 'data-lightbox')
  54. DEFAULT_CONFIG.setdefault('PHOTO_LIGHTBOX_CAPTION_ATTR', 'data-title')
  55. DEFAULT_CONFIG['queue_resize'] = {}
  56. DEFAULT_CONFIG['created_galleries'] = {}
  57. DEFAULT_CONFIG['plugin_dir'] = os.path.dirname(os.path.realpath(__file__))
  58. if pelican:
  59. pelican.settings.setdefault('PHOTO_LIBRARY', p)
  60. pelican.settings.setdefault('PHOTO_GALLERY', (1024, 768, 80))
  61. pelican.settings.setdefault('PHOTO_ARTICLE', (760, 506, 80))
  62. pelican.settings.setdefault('PHOTO_THUMB', (192, 144, 60))
  63. pelican.settings.setdefault('PHOTO_GALLERY_TITLE', '')
  64. pelican.settings.setdefault('PHOTO_ALPHA_BACKGROUND_COLOR', (255, 255, 255))
  65. pelican.settings.setdefault('PHOTO_WATERMARK', False)
  66. pelican.settings.setdefault('PHOTO_WATERMARK_THUMB', False)
  67. pelican.settings.setdefault('PHOTO_WATERMARK_TEXT', pelican.settings['SITENAME'])
  68. pelican.settings.setdefault('PHOTO_WATERMARK_TEXT_COLOR', (255, 255, 255))
  69. pelican.settings.setdefault('PHOTO_WATERMARK_IMG', '')
  70. pelican.settings.setdefault('PHOTO_WATERMARK_IMG_SIZE', False)
  71. pelican.settings.setdefault('PHOTO_RESIZE_JOBS', 1)
  72. pelican.settings.setdefault('PHOTO_EXIF_KEEP', False)
  73. pelican.settings.setdefault('PHOTO_EXIF_REMOVE_GPS', False)
  74. pelican.settings.setdefault('PHOTO_EXIF_AUTOROTATE', True)
  75. pelican.settings.setdefault('PHOTO_EXIF_COPYRIGHT', False)
  76. pelican.settings.setdefault('PHOTO_EXIF_COPYRIGHT_AUTHOR', pelican.settings['AUTHOR'])
  77. pelican.settings.setdefault('PHOTO_LIGHTBOX_GALLERY_ATTR', 'data-lightbox')
  78. pelican.settings.setdefault('PHOTO_LIGHTBOX_CAPTION_ATTR', 'data-title')
  79. def read_notes(filename, msg=None):
  80. notes = {}
  81. try:
  82. with pelican_open(filename) as text:
  83. for line in text.splitlines():
  84. if line.startswith('#'):
  85. continue
  86. m = line.split(':', 1)
  87. if len(m) > 1:
  88. pic = m[0].strip()
  89. note = m[1].strip()
  90. if pic and note:
  91. notes[pic] = note
  92. else:
  93. notes[line] = ''
  94. except Exception as e:
  95. if msg:
  96. logger.warning('{} at file {}'.format(msg, filename))
  97. logger.debug('read_notes issue: {} at file {}. Debug message:{}'.format(msg, filename, e))
  98. return notes
  99. def enqueue_resize(orig, resized, spec=(640, 480, 80)):
  100. if resized not in DEFAULT_CONFIG['queue_resize']:
  101. DEFAULT_CONFIG['queue_resize'][resized] = (orig, spec)
  102. elif DEFAULT_CONFIG['queue_resize'][resized] != (orig, spec):
  103. logger.error('photos: resize conflict for {}, {}-{} is not {}-{}'.format(resized, DEFAULT_CONFIG['queue_resize'][resized][0], DEFAULT_CONFIG['queue_resize'][resized][1], orig, spec))
  104. def isalpha(img):
  105. return True if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info) else False
  106. def remove_alpha(img, bg_color):
  107. background = Image.new("RGB", img.size, bg_color)
  108. background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
  109. return background
  110. def ReduceOpacity(im, opacity):
  111. """Reduces Opacity.
  112. Returns an image with reduced opacity.
  113. Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
  114. """
  115. assert opacity >= 0 and opacity <= 1
  116. if isalpha(im):
  117. im = im.copy()
  118. else:
  119. im = im.convert('RGBA')
  120. alpha = im.split()[3]
  121. alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
  122. im.putalpha(alpha)
  123. return im
  124. def watermark_photo(image, settings):
  125. margin = [10, 10]
  126. opacity = 0.6
  127. watermark_layer = Image.new("RGBA", image.size, (0, 0, 0, 0))
  128. draw_watermark = ImageDraw.Draw(watermark_layer)
  129. text_reducer = 32
  130. image_reducer = 8
  131. text_size = [0, 0]
  132. mark_size = [0, 0]
  133. text_position = [0, 0]
  134. if settings['PHOTO_WATERMARK_TEXT']:
  135. font_name = 'SourceCodePro-Bold.otf'
  136. default_font = os.path.join(DEFAULT_CONFIG['plugin_dir'], font_name)
  137. font = ImageFont.FreeTypeFont(default_font, watermark_layer.size[0] // text_reducer)
  138. text_size = draw_watermark.textsize(settings['PHOTO_WATERMARK_TEXT'], font)
  139. text_position = [image.size[i] - text_size[i] - margin[i] for i in [0, 1]]
  140. draw_watermark.text(text_position, settings['PHOTO_WATERMARK_TEXT'], settings['PHOTO_WATERMARK_TEXT_COLOR'], font=font)
  141. if settings['PHOTO_WATERMARK_IMG']:
  142. mark_image = Image.open(settings['PHOTO_WATERMARK_IMG'])
  143. mark_image_size = [watermark_layer.size[0] // image_reducer for size in mark_size]
  144. mark_image_size = settings['PHOTO_WATERMARK_IMG_SIZE'] if settings['PHOTO_WATERMARK_IMG_SIZE'] else mark_image_size
  145. mark_image.thumbnail(mark_image_size, Image.ANTIALIAS)
  146. mark_position = [watermark_layer.size[i] - mark_image.size[i] - margin[i] for i in [0, 1]]
  147. mark_position = tuple([mark_position[0] - (text_size[0] // 2) + (mark_image_size[0] // 2), mark_position[1] - text_size[1]])
  148. if not isalpha(mark_image):
  149. mark_image = mark_image.convert('RGBA')
  150. watermark_layer.paste(mark_image, mark_position, mark_image)
  151. watermark_layer = ReduceOpacity(watermark_layer, opacity)
  152. image.paste(watermark_layer, (0, 0), watermark_layer)
  153. return image
  154. def rotate_image(img, exif_dict):
  155. if "exif" in img.info and piexif.ImageIFD.Orientation in exif_dict["0th"]:
  156. orientation = exif_dict["0th"].pop(piexif.ImageIFD.Orientation)
  157. if orientation == 2:
  158. img = img.transpose(Image.FLIP_LEFT_RIGHT)
  159. elif orientation == 3:
  160. img = img.rotate(180)
  161. elif orientation == 4:
  162. img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
  163. elif orientation == 5:
  164. img = img.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
  165. elif orientation == 6:
  166. img = img.rotate(-90)
  167. elif orientation == 7:
  168. img = img.rotate(90).transpose(Image.FLIP_LEFT_RIGHT)
  169. elif orientation == 8:
  170. img = img.rotate(90)
  171. return (img, exif_dict)
  172. def build_license(license, author):
  173. year = datetime.datetime.now().year
  174. license_file = os.path.join(DEFAULT_CONFIG['plugin_dir'], 'licenses.json')
  175. with open(license_file) as data_file:
  176. licenses = json.load(data_file)
  177. if any(license in k for k in licenses):
  178. return licenses[license]['Text'].format(Author=author, Year=year, URL=licenses[license]['URL'])
  179. else:
  180. return 'Copyright {Year} {Author}, All Rights Reserved'.format(Author=author, Year=year)
  181. def manipulate_exif(img, settings):
  182. try:
  183. exif = piexif.load(img.info['exif'])
  184. except Exception:
  185. logger.debug('EXIF information not found')
  186. exif = {}
  187. if settings['PHOTO_EXIF_AUTOROTATE']:
  188. img, exif = rotate_image(img, exif)
  189. if settings['PHOTO_EXIF_REMOVE_GPS']:
  190. exif.pop('GPS')
  191. if settings['PHOTO_EXIF_COPYRIGHT']:
  192. # We want to be minimally destructive to any preset exif author or copyright information.
  193. # If there is copyright or author information prefer that over everything else.
  194. if not exif['0th'].get(piexif.ImageIFD.Artist):
  195. exif['0th'][piexif.ImageIFD.Artist] = settings['PHOTO_EXIF_COPYRIGHT_AUTHOR']
  196. author = settings['PHOTO_EXIF_COPYRIGHT_AUTHOR']
  197. if not exif['0th'].get(piexif.ImageIFD.Copyright):
  198. license = build_license(settings['PHOTO_EXIF_COPYRIGHT'], author)
  199. exif['0th'][piexif.ImageIFD.Copyright] = license
  200. return (img, piexif.dump(exif))
  201. def resize_worker(orig, resized, spec, settings):
  202. logger.info('photos: make photo {} -> {}'.format(orig, resized))
  203. im = Image.open(orig)
  204. if ispiexif and settings['PHOTO_EXIF_KEEP'] and im.format == 'JPEG': # Only works with JPEG exif for sure.
  205. im, exif_copy = manipulate_exif(im, settings)
  206. else:
  207. exif_copy = b''
  208. icc_profile = im.info.get("icc_profile", None)
  209. im.thumbnail((spec[0], spec[1]), Image.ANTIALIAS)
  210. directory = os.path.split(resized)[0]
  211. if isalpha(im):
  212. im = remove_alpha(im, settings['PHOTO_ALPHA_BACKGROUND_COLOR'])
  213. if not os.path.exists(directory):
  214. try:
  215. os.makedirs(directory)
  216. except Exception:
  217. logger.exception('Could not create {}'.format(directory))
  218. else:
  219. logger.debug('Directory already exists at {}'.format(os.path.split(resized)[0]))
  220. if settings['PHOTO_WATERMARK']:
  221. isthumb = True if spec == settings['PHOTO_THUMB'] else False
  222. if not isthumb or (isthumb and settings['PHOTO_WATERMARK_THUMB']):
  223. im = watermark_photo(im, settings)
  224. im.save(resized, 'JPEG', quality=spec[2], icc_profile=icc_profile, exif=exif_copy)
  225. def resize_photos(generator, writer):
  226. if generator.settings['PHOTO_RESIZE_JOBS'] == -1:
  227. debug = True
  228. generator.settings['PHOTO_RESIZE_JOBS'] = 1
  229. else:
  230. debug = False
  231. pool = multiprocessing.Pool(generator.settings['PHOTO_RESIZE_JOBS'])
  232. logger.debug('Debug Status: {}'.format(debug))
  233. for resized, what in DEFAULT_CONFIG['queue_resize'].items():
  234. resized = os.path.join(generator.output_path, resized)
  235. orig, spec = what
  236. if (not os.path.isfile(resized) or os.path.getmtime(orig) > os.path.getmtime(resized)):
  237. if debug:
  238. resize_worker(orig, resized, spec, generator.settings)
  239. else:
  240. pool.apply_async(resize_worker, (orig, resized, spec, generator.settings))
  241. pool.close()
  242. pool.join()
  243. def detect_content(content):
  244. hrefs = None
  245. def replacer(m):
  246. what = m.group('what')
  247. value = m.group('value')
  248. tag = m.group('tag')
  249. output = m.group(0)
  250. if what in ('photo', 'lightbox'):
  251. if value.startswith('/'):
  252. value = value[1:]
  253. path = os.path.join(
  254. os.path.expanduser(settings['PHOTO_LIBRARY']),
  255. value
  256. )
  257. if os.path.isfile(path):
  258. photo_prefix = os.path.splitext(value)[0].lower()
  259. if what == 'photo':
  260. photo_article = photo_prefix + 'a.jpg'
  261. enqueue_resize(
  262. path,
  263. os.path.join('photos', photo_article),
  264. settings['PHOTO_ARTICLE']
  265. )
  266. output = ''.join((
  267. '<',
  268. m.group('tag'),
  269. m.group('attrs_before'),
  270. m.group('src'),
  271. '=',
  272. m.group('quote'),
  273. os.path.join(settings['SITEURL'], 'photos', photo_article),
  274. m.group('quote'),
  275. m.group('attrs_after'),
  276. ))
  277. elif what == 'lightbox' and tag == 'img':
  278. photo_gallery = photo_prefix + '.jpg'
  279. enqueue_resize(
  280. path,
  281. os.path.join('photos', photo_gallery),
  282. settings['PHOTO_GALLERY']
  283. )
  284. photo_thumb = photo_prefix + 't.jpg'
  285. enqueue_resize(
  286. path,
  287. os.path.join('photos', photo_thumb),
  288. settings['PHOTO_THUMB']
  289. )
  290. lightbox_attr_list = ['']
  291. gallery_name = value.split('/')[0]
  292. lightbox_attr_list.append('{}="{}"'.format(
  293. settings['PHOTO_LIGHTBOX_GALLERY_ATTR'],
  294. gallery_name
  295. ))
  296. captions = read_notes(
  297. os.path.join(os.path.dirname(path), 'captions.txt'),
  298. msg = 'photos: No captions for gallery'
  299. )
  300. caption = captions.get(os.path.basename(path)) if captions else None
  301. if caption:
  302. lightbox_attr_list.append('{}="{}"'.format(
  303. settings['PHOTO_LIGHTBOX_CAPTION_ATTR'],
  304. caption
  305. ))
  306. lightbox_attrs = ' '.join(lightbox_attr_list)
  307. output = ''.join((
  308. '<a href=',
  309. m.group('quote'),
  310. os.path.join(settings['SITEURL'], 'photos', photo_gallery),
  311. m.group('quote'),
  312. lightbox_attrs,
  313. '><img',
  314. m.group('attrs_before'),
  315. 'src=',
  316. m.group('quote'),
  317. os.path.join(settings['SITEURL'], 'photos', photo_thumb),
  318. m.group('quote'),
  319. m.group('attrs_after'),
  320. '</a>'
  321. ))
  322. else:
  323. logger.error('photos: No photo %s', path)
  324. return output
  325. if hrefs is None:
  326. regex = r"""
  327. <\s*
  328. (?P<tag>[^\s\>]+) # detect the tag
  329. (?P<attrs_before>[^\>]*)
  330. (?P<src>href|src) # match tag with src and href attr
  331. \s*=
  332. (?P<quote>["\']) # require value to be quoted
  333. (?P<path>{0}(?P<value>.*?)) # the url value
  334. (?P=quote)
  335. (?P<attrs_after>[^\>]*>)
  336. """.format(
  337. content.settings['INTRASITE_LINK_REGEX']
  338. )
  339. hrefs = re.compile(regex, re.X)
  340. if content._content and ('{photo}' in content._content or '{lightbox}' in content._content):
  341. settings = content.settings
  342. content._content = hrefs.sub(replacer, content._content)
  343. def galleries_string_decompose(gallery_string):
  344. splitter_regex = re.compile(r'[\s,]*?({photo}|{filename})')
  345. title_regex = re.compile(r'{(.+)}')
  346. galleries = map(unicode.strip if sys.version_info.major == 2 else str.strip, filter(None, splitter_regex.split(gallery_string)))
  347. galleries = [gallery[1:] if gallery.startswith('/') else gallery for gallery in galleries]
  348. if len(galleries) % 2 == 0 and ' ' not in galleries:
  349. galleries = zip(zip(['type'] * len(galleries[0::2]), galleries[0::2]), zip(['location'] * len(galleries[0::2]), galleries[1::2]))
  350. galleries = [dict(gallery) for gallery in galleries]
  351. for gallery in galleries:
  352. title = re.search(title_regex, gallery['location'])
  353. if title:
  354. gallery['title'] = title.group(1)
  355. gallery['location'] = re.sub(title_regex, '', gallery['location']).strip()
  356. else:
  357. gallery['title'] = DEFAULT_CONFIG['PHOTO_GALLERY_TITLE']
  358. return galleries
  359. else:
  360. logger.error('Unexpected gallery location format! \n{}'.format(pprint.pformat(galleries)))
  361. def process_gallery(generator, content, location):
  362. content.photo_gallery = []
  363. galleries = galleries_string_decompose(location)
  364. for gallery in galleries:
  365. if gallery['location'] in DEFAULT_CONFIG['created_galleries']:
  366. content.photo_gallery.append((gallery['location'], DEFAULT_CONFIG['created_galleries'][gallery]))
  367. continue
  368. if gallery['type'] == '{photo}':
  369. dir_gallery = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), gallery['location'])
  370. rel_gallery = gallery['location']
  371. elif gallery['type'] == '{filename}':
  372. base_path = os.path.join(generator.path, content.relative_dir)
  373. dir_gallery = os.path.join(base_path, gallery['location'])
  374. rel_gallery = os.path.join(content.relative_dir, gallery['location'])
  375. if os.path.isdir(dir_gallery):
  376. logger.info('photos: Gallery detected: {}'.format(rel_gallery))
  377. dir_photo = os.path.join('photos', rel_gallery.lower())
  378. dir_thumb = os.path.join('photos', rel_gallery.lower())
  379. exifs = read_notes(os.path.join(dir_gallery, 'exif.txt'),
  380. msg='photos: No EXIF for gallery')
  381. captions = read_notes(os.path.join(dir_gallery, 'captions.txt'), msg='photos: No captions for gallery')
  382. blacklist = read_notes(os.path.join(dir_gallery, 'blacklist.txt'), msg='photos: No blacklist for gallery')
  383. content_gallery = []
  384. title = gallery['title']
  385. for pic in sorted(os.listdir(dir_gallery)):
  386. if pic.startswith('.'):
  387. continue
  388. if pic.endswith('.txt'):
  389. continue
  390. if pic in blacklist:
  391. continue
  392. photo = os.path.splitext(pic)[0].lower() + '.jpg'
  393. thumb = os.path.splitext(pic)[0].lower() + 't.jpg'
  394. content_gallery.append((
  395. pic,
  396. os.path.join(dir_photo, photo),
  397. os.path.join(dir_thumb, thumb),
  398. exifs.get(pic, ''),
  399. captions.get(pic, '')))
  400. enqueue_resize(
  401. os.path.join(dir_gallery, pic),
  402. os.path.join(dir_photo, photo),
  403. generator.settings['PHOTO_GALLERY'])
  404. enqueue_resize(
  405. os.path.join(dir_gallery, pic),
  406. os.path.join(dir_thumb, thumb),
  407. generator.settings['PHOTO_THUMB'])
  408. content.photo_gallery.append((title, content_gallery))
  409. logger.debug('Gallery Data: '.format(pprint.pformat(content.photo_gallery)))
  410. DEFAULT_CONFIG['created_galleries']['gallery'] = content_gallery
  411. else:
  412. logger.error('photos: Gallery does not exist: {} at {}'.format(gallery['location'], dir_gallery))
  413. def detect_gallery(generator, content):
  414. if 'gallery' in content.metadata:
  415. gallery = content.metadata.get('gallery')
  416. if gallery.startswith('{photo}') or gallery.startswith('{filename}'):
  417. process_gallery(generator, content, gallery)
  418. elif gallery:
  419. logger.error('photos: Gallery tag not recognized: {}'.format(gallery))
  420. def image_clipper(x):
  421. return x[8:] if x[8] == '/' else x[7:]
  422. def file_clipper(x):
  423. return x[11:] if x[10] == '/' else x[10:]
  424. def process_image(generator, content, image):
  425. if image.startswith('{photo}'):
  426. path = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), image_clipper(image))
  427. image = image_clipper(image)
  428. elif image.startswith('{filename}'):
  429. path = os.path.join(content.relative_dir, file_clipper(image))
  430. image = file_clipper(image)
  431. if os.path.isfile(path):
  432. photo = os.path.splitext(image)[0].lower() + 'a.jpg'
  433. thumb = os.path.splitext(image)[0].lower() + 't.jpg'
  434. content.photo_image = (
  435. os.path.basename(image).lower(),
  436. os.path.join('photos', photo),
  437. os.path.join('photos', thumb))
  438. enqueue_resize(
  439. path,
  440. os.path.join('photos', photo),
  441. generator.settings['PHOTO_ARTICLE'])
  442. enqueue_resize(
  443. path,
  444. os.path.join('photos', thumb),
  445. generator.settings['PHOTO_THUMB'])
  446. else:
  447. logger.error('photo: No photo for {} at {}'.format(content.source_path, path))
  448. def detect_image(generator, content):
  449. image = content.metadata.get('image', None)
  450. if image:
  451. if image.startswith('{photo}') or image.startswith('{filename}'):
  452. process_image(generator, content, image)
  453. else:
  454. logger.error('photos: Image tag not recognized: {}'.format(image))
  455. def detect_images_and_galleries(generators):
  456. """Runs generator on both pages and articles."""
  457. for generator in generators:
  458. if isinstance(generator, ArticlesGenerator):
  459. for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
  460. detect_image(generator, article)
  461. detect_gallery(generator, article)
  462. elif isinstance(generator, PagesGenerator):
  463. for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):
  464. detect_image(generator, page)
  465. detect_gallery(generator, page)
  466. def register():
  467. """Uses the new style of registration based on GitHub Pelican issue #314."""
  468. signals.initialized.connect(initialized)
  469. try:
  470. signals.content_object_init.connect(detect_content)
  471. signals.all_generators_finalized.connect(detect_images_and_galleries)
  472. signals.article_writer_finalized.connect(resize_photos)
  473. except Exception as e:
  474. logger.exception('Plugin failed to execute: {}'.format(pprint.pformat(e)))