src/pyams_content/features/glossary/__init__.py
changeset 1195 9870e7467087
equal deleted inserted replaced
1194:d4ae54d8fe17 1195:9870e7467087
       
     1 #
       
     2 # Copyright (c) 2008-2018 Thierry Florac <tflorac AT ulthar.net>
       
     3 # All Rights Reserved.
       
     4 #
       
     5 # This software is subject to the provisions of the Zope Public License,
       
     6 # Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
       
     7 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
       
     8 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
       
     9 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
       
    10 # FOR A PARTICULAR PURPOSE.
       
    11 #
       
    12 
       
    13 __docformat__ = 'restructuredtext'
       
    14 
       
    15 import logging
       
    16 import pickle
       
    17 from ahocorasick import Automaton
       
    18 
       
    19 from pyams_cache.beaker import get_cache
       
    20 from pyams_content.component.theme import ITagsManager
       
    21 from pyams_thesaurus.interfaces.thesaurus import IThesaurus
       
    22 from pyams_utils.registry import query_utility
       
    23 
       
    24 
       
    25 logger = logging.getLogger("PyAMS (content)")
       
    26 
       
    27 GLOSSARY_CACHE_REGION = 'persistent'
       
    28 GLOSSARY_CACHE_NAME = 'PyAMS::glossary'
       
    29 GLOSSARY_CACHE_KEY = 'automaton'
       
    30 
       
    31 
       
    32 def get_glossary_automaton(root):
       
    33     """Generate and store glossary automaton"""
       
    34     # generate Automaton
       
    35     tags_manager = ITagsManager(root)
       
    36     if not tags_manager.enable_glossary:
       
    37         return
       
    38     thesaurus = query_utility(IThesaurus, name=tags_manager.glossary_thesaurus_name)
       
    39     if thesaurus is None:
       
    40         return
       
    41     logger.debug("Building glossary automaton...")
       
    42     automaton = Automaton()
       
    43     for term in thesaurus.terms.values():
       
    44         if term.status == 'published':
       
    45             automaton.add_word(term.label, term.label)
       
    46     automaton.make_automaton()
       
    47     logger.debug("Automaton built with {} terms".format(len(automaton)))
       
    48     # store automaton items
       
    49     glossary_cache = get_cache(GLOSSARY_CACHE_REGION, GLOSSARY_CACHE_NAME)
       
    50     glossary_cache.set_value(GLOSSARY_CACHE_KEY, pickle.dumps(automaton))
       
    51     return automaton
       
    52 
       
    53 
       
    54 def reset_glossary_automaton():
       
    55     """Re-initialize glossary automaton"""
       
    56     glossary_cache = get_cache(GLOSSARY_CACHE_REGION, GLOSSARY_CACHE_NAME)
       
    57     glossary_cache.clear()