photos.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. try:
  206. im, exif_copy = manipulate_exif(im, settings)
  207. except:
  208. logger.info('photos: no EXIF or EXIF error in {}'.format(orig))
  209. exif_copy = b''
  210. else:
  211. exif_copy = b''
  212. icc_profile = im.info.get("icc_profile", None)
  213. im.thumbnail((spec[0], spec[1]), Image.ANTIALIAS)
  214. directory = os.path.split(resized)[0]
  215. if isalpha(im):
  216. im = remove_alpha(im, settings['PHOTO_ALPHA_BACKGROUND_COLOR'])
  217. if not os.path.exists(directory):
  218. try:
  219. os.makedirs(directory)
  220. except Exception:
  221. logger.exception('Could not create {}'.format(directory))
  222. else:
  223. logger.debug('Directory already exists at {}'.format(os.path.split(resized)[0]))
  224. if settings['PHOTO_WATERMARK']:
  225. isthumb = True if spec == settings['PHOTO_THUMB'] else False
  226. if not isthumb or (isthumb and settings['PHOTO_WATERMARK_THUMB']):
  227. im = watermark_photo(im, settings)
  228. im.save(resized, 'JPEG', quality=spec[2], icc_profile=icc_profile, exif=exif_copy)
  229. def resize_photos(generator, writer):
  230. if generator.settings['PHOTO_RESIZE_JOBS'] == -1:
  231. debug = True
  232. generator.settings['PHOTO_RESIZE_JOBS'] = 1
  233. else:
  234. debug = False
  235. pool = multiprocessing.Pool(generator.settings['PHOTO_RESIZE_JOBS'])
  236. logger.debug('Debug Status: {}'.format(debug))
  237. for resized, what in DEFAULT_CONFIG['queue_resize'].items():
  238. resized = os.path.join(generator.output_path, resized)
  239. orig, spec = what
  240. if (not os.path.isfile(resized) or os.path.getmtime(orig) > os.path.getmtime(resized)):
  241. if debug:
  242. resize_worker(orig, resized, spec, generator.settings)
  243. else:
  244. pool.apply_async(resize_worker, (orig, resized, spec, generator.settings))
  245. pool.close()
  246. pool.join()
  247. def detect_content(content):
  248. hrefs = None
  249. def replacer(m):
  250. what = m.group('what')
  251. value = m.group('value')
  252. tag = m.group('tag')
  253. output = m.group(0)
  254. if what in ('photo', 'lightbox'):
  255. if value.startswith('/'):
  256. value = value[1:]
  257. path = os.path.join(
  258. os.path.expanduser(settings['PHOTO_LIBRARY']),
  259. value
  260. )
  261. if os.path.isfile(path):
  262. photo_prefix = os.path.splitext(value)[0].lower()
  263. if what == 'photo':
  264. photo_article = photo_prefix + 'a.jpg'
  265. enqueue_resize(
  266. path,
  267. os.path.join('photos', photo_article),
  268. settings['PHOTO_ARTICLE']
  269. )
  270. output = ''.join((
  271. '<',
  272. m.group('tag'),
  273. m.group('attrs_before'),
  274. m.group('src'),
  275. '=',
  276. m.group('quote'),
  277. os.path.join(settings['SITEURL'], 'photos', photo_article),
  278. m.group('quote'),
  279. m.group('attrs_after'),
  280. ))
  281. elif what == 'lightbox' and tag == 'img':
  282. photo_gallery = photo_prefix + '.jpg'
  283. enqueue_resize(
  284. path,
  285. os.path.join('photos', photo_gallery),
  286. settings['PHOTO_GALLERY']
  287. )
  288. photo_thumb = photo_prefix + 't.jpg'
  289. enqueue_resize(
  290. path,
  291. os.path.join('photos', photo_thumb),
  292. settings['PHOTO_THUMB']
  293. )
  294. lightbox_attr_list = ['']
  295. gallery_name = value.split('/')[0]
  296. lightbox_attr_list.append('{}="{}"'.format(
  297. settings['PHOTO_LIGHTBOX_GALLERY_ATTR'],
  298. gallery_name
  299. ))
  300. captions = read_notes(
  301. os.path.join(os.path.dirname(path), 'captions.txt'),
  302. msg = 'photos: No captions for gallery'
  303. )
  304. caption = captions.get(os.path.basename(path)) if captions else None
  305. if caption:
  306. lightbox_attr_list.append('{}="{}"'.format(
  307. settings['PHOTO_LIGHTBOX_CAPTION_ATTR'],
  308. caption
  309. ))
  310. lightbox_attrs = ' '.join(lightbox_attr_list)
  311. output = ''.join((
  312. '<a href=',
  313. m.group('quote'),
  314. os.path.join(settings['SITEURL'], 'photos', photo_gallery),
  315. m.group('quote'),
  316. lightbox_attrs,
  317. '><img',
  318. m.group('attrs_before'),
  319. 'src=',
  320. m.group('quote'),
  321. os.path.join(settings['SITEURL'], 'photos', photo_thumb),
  322. m.group('quote'),
  323. m.group('attrs_after'),
  324. '</a>'
  325. ))
  326. else:
  327. logger.error('photos: No photo %s', path)
  328. return output
  329. if hrefs is None:
  330. regex = r"""
  331. <\s*
  332. (?P<tag>[^\s\>]+) # detect the tag
  333. (?P<attrs_before>[^\>]*)
  334. (?P<src>href|src) # match tag with src and href attr
  335. \s*=
  336. (?P<quote>["\']) # require value to be quoted
  337. (?P<path>{0}(?P<value>.*?)) # the url value
  338. (?P=quote)
  339. (?P<attrs_after>[^\>]*>)
  340. """.format(
  341. content.settings['INTRASITE_LINK_REGEX']
  342. )
  343. hrefs = re.compile(regex, re.X)
  344. if content._content and ('{photo}' in content._content or '{lightbox}' in content._content):
  345. settings = content.settings
  346. content._content = hrefs.sub(replacer, content._content)
  347. def galleries_string_decompose(gallery_string):
  348. splitter_regex = re.compile(r'[\s,]*?({photo}|{filename})')
  349. title_regex = re.compile(r'{(.+)}')
  350. galleries = map(unicode.strip if sys.version_info.major == 2 else str.strip, filter(None, splitter_regex.split(gallery_string)))
  351. galleries = [gallery[1:] if gallery.startswith('/') else gallery for gallery in galleries]
  352. if len(galleries) % 2 == 0 and ' ' not in galleries:
  353. galleries = zip(zip(['type'] * len(galleries[0::2]), galleries[0::2]), zip(['location'] * len(galleries[0::2]), galleries[1::2]))
  354. galleries = [dict(gallery) for gallery in galleries]
  355. for gallery in galleries:
  356. title = re.search(title_regex, gallery['location'])
  357. if title:
  358. gallery['title'] = title.group(1)
  359. gallery['location'] = re.sub(title_regex, '', gallery['location']).strip()
  360. else:
  361. gallery['title'] = DEFAULT_CONFIG['PHOTO_GALLERY_TITLE']
  362. return galleries
  363. else:
  364. logger.error('Unexpected gallery location format! \n{}'.format(pprint.pformat(galleries)))
  365. def process_gallery(generator, content, location):
  366. content.photo_gallery = []
  367. galleries = galleries_string_decompose(location)
  368. for gallery in galleries:
  369. if gallery['location'] in DEFAULT_CONFIG['created_galleries']:
  370. content.photo_gallery.append((gallery['location'], DEFAULT_CONFIG['created_galleries'][gallery]))
  371. continue
  372. if gallery['type'] == '{photo}':
  373. dir_gallery = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), gallery['location'])
  374. rel_gallery = gallery['location']
  375. elif gallery['type'] == '{filename}':
  376. base_path = os.path.join(generator.path, content.relative_dir)
  377. dir_gallery = os.path.join(base_path, gallery['location'])
  378. rel_gallery = os.path.join(content.relative_dir, gallery['location'])
  379. if os.path.isdir(dir_gallery):
  380. logger.info('photos: Gallery detected: {}'.format(rel_gallery))
  381. dir_photo = os.path.join('photos', rel_gallery.lower())
  382. dir_thumb = os.path.join('photos', rel_gallery.lower())
  383. exifs = read_notes(os.path.join(dir_gallery, 'exif.txt'),
  384. msg='photos: No EXIF for gallery')
  385. captions = read_notes(os.path.join(dir_gallery, 'captions.txt'), msg='photos: No captions for gallery')
  386. blacklist = read_notes(os.path.join(dir_gallery, 'blacklist.txt'), msg='photos: No blacklist for gallery')
  387. content_gallery = []
  388. title = gallery['title']
  389. for pic in sorted(os.listdir(dir_gallery)):
  390. if pic.startswith('.'):
  391. continue
  392. if pic.endswith('.txt'):
  393. continue
  394. if pic in blacklist:
  395. continue
  396. photo = os.path.splitext(pic)[0].lower() + '.jpg'
  397. thumb = os.path.splitext(pic)[0].lower() + 't.jpg'
  398. content_gallery.append((
  399. pic,
  400. os.path.join(dir_photo, photo),
  401. os.path.join(dir_thumb, thumb),
  402. exifs.get(pic, ''),
  403. captions.get(pic, '')))
  404. enqueue_resize(
  405. os.path.join(dir_gallery, pic),
  406. os.path.join(dir_photo, photo),
  407. generator.settings['PHOTO_GALLERY'])
  408. enqueue_resize(
  409. os.path.join(dir_gallery, pic),
  410. os.path.join(dir_thumb, thumb),
  411. generator.settings['PHOTO_THUMB'])
  412. content.photo_gallery.append((title, content_gallery))
  413. logger.debug('Gallery Data: '.format(pprint.pformat(content.photo_gallery)))
  414. DEFAULT_CONFIG['created_galleries']['gallery'] = content_gallery
  415. else:
  416. logger.error('photos: Gallery does not exist: {} at {}'.format(gallery['location'], dir_gallery))
  417. def detect_gallery(generator, content):
  418. if 'gallery' in content.metadata:
  419. gallery = content.metadata.get('gallery')
  420. if gallery.startswith('{photo}') or gallery.startswith('{filename}'):
  421. process_gallery(generator, content, gallery)
  422. elif gallery:
  423. logger.error('photos: Gallery tag not recognized: {}'.format(gallery))
  424. def image_clipper(x):
  425. return x[8:] if x[8] == '/' else x[7:]
  426. def file_clipper(x):
  427. return x[11:] if x[10] == '/' else x[10:]
  428. def process_image(generator, content, image):
  429. if image.startswith('{photo}'):
  430. path = os.path.join(os.path.expanduser(generator.settings['PHOTO_LIBRARY']), image_clipper(image))
  431. image = image_clipper(image)
  432. elif image.startswith('{filename}'):
  433. path = os.path.join(content.relative_dir, file_clipper(image))
  434. image = file_clipper(image)
  435. if os.path.isfile(path):
  436. photo = os.path.splitext(image)[0].lower() + 'a.jpg'
  437. thumb = os.path.splitext(image)[0].lower() + 't.jpg'
  438. content.photo_image = (
  439. os.path.basename(image).lower(),
  440. os.path.join('photos', photo),
  441. os.path.join('photos', thumb))
  442. enqueue_resize(
  443. path,
  444. os.path.join('photos', photo),
  445. generator.settings['PHOTO_ARTICLE'])
  446. enqueue_resize(
  447. path,
  448. os.path.join('photos', thumb),
  449. generator.settings['PHOTO_THUMB'])
  450. else:
  451. logger.error('photo: No photo for {} at {}'.format(content.source_path, path))
  452. def detect_image(generator, content):
  453. image = content.metadata.get('image', None)
  454. if image:
  455. if image.startswith('{photo}') or image.startswith('{filename}'):
  456. process_image(generator, content, image)
  457. else:
  458. logger.error('photos: Image tag not recognized: {}'.format(image))
  459. def detect_images_and_galleries(generators):
  460. """Runs generator on both pages and articles."""
  461. for generator in generators:
  462. if isinstance(generator, ArticlesGenerator):
  463. for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
  464. detect_image(generator, article)
  465. detect_gallery(generator, article)
  466. elif isinstance(generator, PagesGenerator):
  467. for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):
  468. detect_image(generator, page)
  469. detect_gallery(generator, page)
  470. def register():
  471. """Uses the new style of registration based on GitHub Pelican issue #314."""
  472. signals.initialized.connect(initialized)
  473. try:
  474. signals.content_object_init.connect(detect_content)
  475. signals.all_generators_finalized.connect(detect_images_and_galleries)
  476. signals.article_writer_finalized.connect(resize_photos)
  477. except Exception as e:
  478. logger.exception('Plugin failed to execute: {}'.format(pprint.pformat(e)))