tag_cloud.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. '''
  2. tag_cloud
  3. ===================================
  4. This plugin generates a tag cloud from available tags
  5. '''
  6. from __future__ import unicode_literals
  7. from collections import defaultdict
  8. from operator import itemgetter
  9. import logging
  10. import math
  11. import random
  12. from pelican import signals
  13. logger = logging.getLogger(__name__)
  14. def set_default_settings(settings):
  15. settings.setdefault('TAG_CLOUD_STEPS', 4)
  16. settings.setdefault('TAG_CLOUD_MAX_ITEMS', 100)
  17. settings.setdefault('TAG_CLOUD_SORTING', 'random')
  18. settings.setdefault('TAG_CLOUD_BADGE', False)
  19. def init_default_config(pelican):
  20. from pelican.settings import DEFAULT_CONFIG
  21. set_default_settings(DEFAULT_CONFIG)
  22. if(pelican):
  23. set_default_settings(pelican.settings)
  24. def generate_tag_cloud(generator):
  25. tag_cloud = defaultdict(int)
  26. for article in generator.articles:
  27. for tag in getattr(article, 'tags', []):
  28. tag_cloud[tag] += 1
  29. tag_cloud = sorted(tag_cloud.items(), key=itemgetter(1), reverse=True)
  30. tag_cloud = tag_cloud[:generator.settings.get('TAG_CLOUD_MAX_ITEMS')]
  31. tags = list(map(itemgetter(1), tag_cloud))
  32. if tags:
  33. max_count = max(tags)
  34. steps = generator.settings.get('TAG_CLOUD_STEPS')
  35. # calculate word sizes
  36. def generate_tag(tag, count):
  37. tag = (
  38. tag,
  39. int(math.floor(steps - (steps - 1) * math.log(count)
  40. / (math.log(max_count)or 1)))
  41. )
  42. if generator.settings.get('TAG_CLOUD_BADGE'):
  43. tag += (count,)
  44. return tag
  45. tag_cloud = [
  46. generate_tag(tag, count)
  47. for tag, count in tag_cloud
  48. ]
  49. sorting = generator.settings.get('TAG_CLOUD_SORTING')
  50. if sorting == 'alphabetically':
  51. tag_cloud.sort(key=lambda elem: elem[0].name)
  52. elif sorting == 'alphabetically-rev':
  53. tag_cloud.sort(key=lambda elem: elem[0].name, reverse=True)
  54. elif sorting == 'size':
  55. tag_cloud.sort(key=lambda elem: elem[1])
  56. elif sorting == 'size-rev':
  57. tag_cloud.sort(key=lambda elem: elem[1], reverse=True)
  58. elif sorting == 'random':
  59. random.shuffle(tag_cloud)
  60. else:
  61. logger.warning("setting for TAG_CLOUD_SORTING not recognized: %s, "
  62. "falling back to 'random'", sorting)
  63. random.shuffle(tag_cloud)
  64. # make available in context
  65. generator.tag_cloud = tag_cloud
  66. generator._update_context(['tag_cloud'])
  67. def register():
  68. signals.initialized.connect(init_default_config)
  69. signals.article_generator_finalized.connect(generate_tag_cloud)