tag_cloud.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 attrgetter, itemgetter
  9. import logging
  10. import math
  11. import random
  12. from pelican import signals, contents
  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. def init_default_config(pelican):
  19. from pelican.settings import DEFAULT_CONFIG
  20. set_default_settings(DEFAULT_CONFIG)
  21. if(pelican):
  22. set_default_settings(pelican.settings)
  23. def generate_tag_cloud(generator):
  24. tag_cloud = defaultdict(int)
  25. for article in generator.articles:
  26. for tag in getattr(article, 'tags', []):
  27. tag_cloud[tag] += 1
  28. tag_cloud = sorted(tag_cloud.items(), key=itemgetter(1), reverse=True)
  29. tag_cloud = tag_cloud[:generator.settings.get('TAG_CLOUD_MAX_ITEMS')]
  30. tags = list(map(itemgetter(1), tag_cloud))
  31. if tags:
  32. max_count = max(tags)
  33. steps = generator.settings.get('TAG_CLOUD_STEPS')
  34. # calculate word sizes
  35. tag_cloud = [
  36. (
  37. tag,
  38. int(math.floor(steps - (steps - 1) * math.log(count)
  39. / (math.log(max_count)or 1)))
  40. )
  41. for tag, count in tag_cloud
  42. ]
  43. sorting = generator.settings.get('TAG_CLOUD_SORTING')
  44. if sorting == 'alphabetically':
  45. tag_cloud.sort(key=lambda elem: elem[0].name)
  46. elif sorting == 'alphabetically-rev':
  47. tag_cloud.sort(key=lambda elem: elem[0].name, reverse=True)
  48. elif sorting == 'size':
  49. tag_cloud.sort(key=lambda elem: elem[1])
  50. elif sorting == 'size-rev':
  51. tag_cloud.sort(key=lambda elem: elem[1], reverse=True)
  52. elif sorting == 'random':
  53. random.shuffle(tag_cloud)
  54. else:
  55. logger.warning("setting for TAG_CLOUD_SORTING not recognized: %s, "
  56. "falling back to 'random'", sorting)
  57. random.shuffle(tag_cloud)
  58. #make available in context
  59. generator.tag_cloud = tag_cloud
  60. generator._update_context(['tag_cloud'])
  61. def register():
  62. signals.initialized.connect(init_default_config)
  63. signals.article_generator_finalized.connect(generate_tag_cloud)