better_figures_and_images.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """
  2. Better Figures & Images
  3. ------------------------
  4. This plugin:
  5. - Adds a style="width: ???px; height: auto;" to each image in the content
  6. - Also adds the width of the contained image to any parent div.figures.
  7. - If RESPONSIVE_IMAGES == True, also adds style="max-width: 100%;"
  8. - Corrects alt text: if alt == image filename, set alt = ''
  9. TODO: Need to add a test.py for this plugin.
  10. """
  11. from __future__ import unicode_literals
  12. from os import path, access, R_OK
  13. import os
  14. from pelican import signals
  15. from bs4 import BeautifulSoup
  16. from PIL import Image
  17. import pysvg.parser
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. def content_object_init(instance):
  21. if instance._content is not None:
  22. content = instance._content
  23. soup = BeautifulSoup(content, 'html.parser')
  24. for img in soup(['img', 'object']):
  25. logger.debug('Better Fig. PATH: %s', instance.settings['PATH'])
  26. if img.name == 'img':
  27. logger.debug('Better Fig. img.src: %s', img['src'])
  28. img_path, img_filename = path.split(img['src'])
  29. else:
  30. logger.debug('Better Fig. img.data: %s', img['data'])
  31. img_path, img_filename = path.split(img['data'])
  32. logger.debug('Better Fig. img_path: %s', img_path)
  33. logger.debug('Better Fig. img_fname: %s', img_filename)
  34. # Strip off {filename}, |filename| or /static
  35. if img_path.startswith(('{filename}', '|filename|')):
  36. img_path = img_path[10:]
  37. elif img_path.startswith('/static'):
  38. img_path = img_path[7:]
  39. elif img_path.startswith('data:image'):
  40. # Image is encoded in-line (not a file).
  41. continue
  42. else:
  43. logger.warning('Better Fig. Error: img_path should start with either {filename}, |filename| or /static')
  44. # search src path list
  45. # 1. Build the source image filename from PATH
  46. # 2. Build the source image filename from STATIC_PATHS
  47. # if img_path start with '/', remove it.
  48. img_path = os.path.sep.join([el for el in img_path.split("/") if len(el) > 0])
  49. # style: {filename}/static/foo/bar.png
  50. src = os.path.join(instance.settings['PATH'], img_path, img_filename)
  51. src_candidates = [src]
  52. # style: {filename}../static/foo/bar.png
  53. src_candidates += [os.path.join(instance.settings['PATH'], static_path, img_path, img_filename) for static_path in instance.settings['STATIC_PATHS']]
  54. src_candidates = [f for f in src_candidates if path.isfile(f) and access(f, R_OK)]
  55. if not src_candidates:
  56. logger.error('Better Fig. Error: image not found: %s', src)
  57. logger.debug('Better Fig. Skip src: %s', img_path + '/' + img_filename)
  58. continue
  59. src = src_candidates[0]
  60. logger.debug('Better Fig. src: %s', src)
  61. # Open the source image and query dimensions; build style string
  62. try:
  63. if img.name == 'img':
  64. im = Image.open(src)
  65. extra_style = 'width: {}px; height: auto;'.format(im.size[0])
  66. else:
  67. svg = pysvg.parser.parse(src)
  68. extra_style = 'width: {}px; height: auto;'.format(svg.get_width())
  69. except IOError as e:
  70. logger.debug('Better Fig. Failed to open: %s', src)
  71. extra_style = 'width: 100%; height: auto;'
  72. if 'RESPONSIVE_IMAGES' in instance.settings and instance.settings['RESPONSIVE_IMAGES']:
  73. extra_style += ' max-width: 100%;'
  74. if img.get('style'):
  75. img['style'] += extra_style
  76. else:
  77. img['style'] = extra_style
  78. if img.name == 'img':
  79. if img['alt'] == img['src']:
  80. img['alt'] = ''
  81. fig = img.find_parent('div', 'figure')
  82. if fig:
  83. if fig.get('style'):
  84. fig['style'] += extra_style
  85. else:
  86. fig['style'] = extra_style
  87. instance._content = soup.decode()
  88. def register():
  89. signals.content_object_init.connect(content_object_init)