<commit_before># -*- coding: utf-8 -*-
"""
This module handles the API for the system, registering backends and using them.
"""

from __future__ import absolute_import

import types
import sys
import warnings
import logging

from . import registry
from .utils.helpers import _Setting

__all__ = ['install', 'use', 'teardown', 'use_strict_xml', 'STRICT_KTL_XML', 'APISetting']

log = logging.getLogger("Cauldron.api")

CAULDRON_SETUP = _Setting("CAULDRON_SETUP", False)

class APISetting(_Setting):
    """A setting which locks with the API use() calls."""
    def __init__(self, name, value):
        super(APISetting, self).__init__(name=name, value=value, lock=CAULDRON_SETUP)

BASENAME = ".".join(__name__.split(".")[:-1])

KTL_DEFAULT_NAMES = set(['ktl', 'DFW'])

STRICT_KTL_XML = _Setting("STRICT_KTL_XML", False)

def use_strict_xml():
    """Use strict XML settings. Strict XML enforces all of the KTL XML rules to the letter, and requires that all keywords be pre-defined in XML files which are loaded when connecting a service from either the client or dispatcher side.
    
    If strict XML is not used, Cauldron will provide warnings when XML rules are violated, but will continue to operate."""
    STRICT_KTL_XML.on()

def use(name):
    """Activae a KTL backend in Cauldron.
    
    :param str name: The name of the KTL backend to use.
    
    You should only call this function once per interpreter session. It will raise a :exc:`RuntimeError` if it is called when Cauldron has been already set up. After this call, it is safe to make imports from Cauldron KTL API modules::
        
        import Cauldron
        Cauldron.use("local")
        from Cauldron import ktl
        
    
    """
    # We do some hacks here to install the module 'Cauldron.ktl' and 'Cauldron.DFW' only once this API function has been called.
    if CAULDRON_SETUP:
        raise RuntimeError("You may only call Cauldron.use() once! It is an error to activate again.")
    
    # Allow imports of backend modules now.
    CAULDRON_SETUP.on()
    
    # Set up the LROOT KTL installation differently
    if name in KTL_DEFAULT_NAMES: # pragma: no cover
        return setup_ktl_backend()
        
    if name not in registry.keys():
        raise ValueError("The Cauldron backend '{0}' is not registered. Available backends are {1!r}".format(
            name, list(registry.keys())))
    
    log.info("Cauldron initialized using backend '{0}'".format(name))
    registry.client.use(name)
    registry.dispatcher.use(name)
    
    Cauldron = sys.modules[BASENAME]
    # Install the client side libraries.
    from . import _ktl
    from ._ktl.Service import Service
    from ._ktl import Keyword
    _ktl.Service = Service
    _ktl.Keyword = Keyword
    Cauldron.ktl = sys.modules[BASENAME + ".ktl"] = _ktl
    
    # Install the dispatcher side libraries.
    from . import _DFW
    from ._DFW.Service import Service
    from ._DFW import Keyword
    _DFW.Service = Service
    _DFW.Keyword = Keyword
    Cauldron.DFW = sys.modules[BASENAME + ".DFW"] = _DFW
    
def setup_ktl_backend(): # pragma: no cover
    """Set up the KTL backend."""
    Cauldron = sys.modules[BASENAME]<commit_msg>Fixing some subtleties in module reloading.<commit_after># -*- coding: utf-8 -*-
"""
This module handles the API for the system, registering backends and using them.
"""

from __future__ import absolute_import

import types
import sys
import warnings
import logging

from . import registry
from .utils.helpers import _Setting

__all__ = ['install', 'use', 'teardown', 'use_strict_xml', 'STRICT_KTL_XML', 'APISetting']

log = logging.getLogger("Cauldron.api")

CAULDRON_SETUP = _Setting("CAULDRON_SETUP", False)

class APISetting(_Setting):
    """A setting which locks with the API use() calls."""
    def __init__(self, name, value):
        super(APISetting, self).__init__(name=name, value=value, lock=CAULDRON_SETUP)

BASENAME = ".".join(__name__.split(".")[:-1])

KTL_DEFAULT_NAMES = set(['ktl', 'DFW'])

STRICT_KTL_XML = _Setting("STRICT_KTL_XML", False)

def use_strict_xml():
    """Use strict XML settings. Strict XML enforces all of the KTL XML rules to the letter, and requires that all keywords be pre-defined in XML files which are loaded when connecting a service from either the client or dispatcher side.
    
    If strict XML is not used, Cauldron will provide warnings when XML rules are violated, but will continue to operate."""
    STRICT_KTL_XML.on()

def use(name):
    """Activae a KTL backend in Cauldron.
    
    :param str name: The name of the KTL backend to use.
    
    You should only call this function once per interpreter session. It will raise a :exc:`RuntimeError` if it is called when Cauldron has been already set up. After this call, it is safe to make imports from Cauldron KTL API modules::
        
        import Cauldron
        Cauldron.use("local")
        from Cauldron import ktl
        
    
    """
    # We do some hacks here to install the module 'Cauldron.ktl' and 'Cauldron.DFW' only once this API function has been called.
    if CAULDRON_SETUP:
        raise RuntimeError("You may only call Cauldron.use() once! It is an error to activate again.")
    
    # Allow imports of backend modules now.
    CAULDRON_SETUP.on()
    
    # Set up the LROOT KTL installation differently
    if name in KTL_DEFAULT_NAMES: # pragma: no cover
        return setup_ktl_backend()
        
    if name not in registry.keys():
        raise ValueError("The Cauldron backend '{0}' is not registered. Available backends are {1!r}".format(
            name, list(registry.keys())))
    
    log.info("Cauldron initialized using backend '{0}'".format(name))
    registry.client.use(name)
    registry.dispatcher.use(name)
    
    Cauldron = sys.modules[BASENAME]
    # Install the client side libraries.
    from Cauldron import _ktl
    sys.modules.setdefault('Cauldron._ktl', _ktl)
    reload(_ktl)
    
    from Cauldron._ktl.Service import Service
    from Cauldron._ktl import Keyword
    _ktl.Service = Service
    _ktl.Keyword = Keyword
    Cauldron.ktl = sys.modules[BASENAME + ".ktl"] = _ktl
    
    # Install the dispatcher side libraries.
    from Cauldron import _DFW
    sys.modules.setdefault('Cauldron._DFW', _DFW)
    reload(_DFW)
    from Cauldron._DFW.Service import Service
    from Cauldron._DFW import Keyword
    _DFW.Service = Service
    _DFW.Keyword = Keyword
    Cauldron.DFW = sys.modules[BASENAME + ".DFW"] = _DFW
    
def setup_ktl_backend(): # pragma: no cover
    """Set up the KTL backend."""
    Cauldron = sys.modules[BASENAME]
{'fraction_non_alphanumeric': 0.09300561371567288, 'fraction_numerical': 0.0015172204521316948, 'mean_word_length': 3.2805194805194806, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '602932', 'n_tokens_mistral': 2084, 'n_tokens_neox': 2022, 'n_words': 712}