def _action_class(action_name): # type: (Text) -> Action """Tries to create an instance by importing and calling the class.""" try: cls = utils.class_from_module_path(action_name) return cls() except ImportError as e: if len(e.args) > 0: erx = re.compile("No module named '?(.*?)'?$") matched = erx.search(e.args[0]) if matched and matched.group(1) in action_name: # we only want to capture exceptions that are raised by the # class itself, not by other packages that fail to import raise ValueError( "Action '{}' doesn't correspond to a template / " "action. Remember to prefix actions that should " "utter a template with `utter_`. " "Error: {}".format(action_name, e)) # raises the original exception again raise except (AttributeError, KeyError) as e: raise ValueError( "Action '{}' doesn't correspond to a template / action. " "Module doesn't contain a class with this name. " "Remember to prefix actions that should utter a template " "with `utter_`. Error: {}".format(action_name, e))
def load(cls, path): # type: (Text) -> PolicyEnsemble """Loads policy and domain specification from storage""" metadata = cls.load_metadata(path) cls.ensure_model_compatibility(metadata) policies = [] for i, policy_name in enumerate(metadata["policy_names"]): policy_cls = utils.class_from_module_path(policy_name) dir_name = 'policy_{}_{}'.format(i, policy_cls.__name__) policy_path = os.path.join(path, dir_name) policy = policy_cls.load(policy_path) policies.append(policy) ensemble_cls = utils.class_from_module_path( metadata["ensemble_name"]) fingerprints = metadata.get("action_fingerprints", {}) ensemble = ensemble_cls(policies, fingerprints) return ensemble
def resolve_by_type(type_name): """Returns a slots class by its type name.""" for cls in utils.all_subclasses(Slot): if cls.type_name == type_name: return cls try: return utils.class_from_module_path(type_name) except Exception: raise ValueError( "Failed to find slot type. Neither a known type nor. If " "you are creating your own slot type, make sure its " "module path is correct: {}.".format(type_name))
def create_input_channel(channel, port, credentials_file): """Instantiate the chosen input channel.""" if channel in ['facebook', 'slack', 'telegram', 'mattermost', 'twilio']: return _create_external_channel(channel, port, credentials_file) elif channel == "cmdline": return ConsoleInputChannel() else: try: c = utils.class_from_module_path(channel) return c() except Exception: raise Exception("Unknown input channel for running main.")
def create_input_channel(channel, port, credentials_file): """Instantiate the chosen input channel.""" if channel in ['facebook', 'slack', 'telegram', 'mattermost', 'twilio']: return _create_external_channel(channel, port, credentials_file) elif channel == "cmdline": return ConsoleInputChannel() else: try: c = utils.class_from_module_path(channel) return c() except Exception: raise Exception("Unknown input channel for running main.")
def resolve_by_type(type_name): """Returns a slots class by its type name.""" for cls in utils.all_subclasses(Slot): if cls.type_name == type_name: return cls try: return utils.class_from_module_path(type_name) except Exception: raise ValueError( "Failed to find slot type. Neither a known type nor. If " "you are creating your own slot type, make sure its " "module path is correct: {}.".format(type_name))
def load_tracker_from_module_string(domain, store): custom_tracker = None try: custom_tracker = class_from_module_path(store.type) except (AttributeError, ImportError): logger.warning("Store type '{}' not found. " "Using InMemoryTrackerStore instead".format( store.type)) if custom_tracker: return custom_tracker(domain=domain, url=store.url, **store.kwargs) else: return InMemoryTrackerStore(domain)
def create_http_input_channels(channel, # type: Union[None, Text, RestInput] credentials_file # type: Optional[Text] ): # type: (...) -> List[InputChannel] """Instantiate the chosen input channel.""" if channel is None or channel in rasa_core.channels.BUILTIN_CHANNELS: return _create_external_channels(channel, credentials_file) else: try: c = utils.class_from_module_path(channel) return [c()] except Exception: raise Exception("Unknown input channel for running main.")
def _create_single_channel(channel, credentials): if channel in BUILTIN_CHANNELS: return BUILTIN_CHANNELS[channel].from_credentials(credentials) else: # try to load channel based on class name try: input_channel_class = utils.class_from_module_path(channel) return input_channel_class.from_credentials(credentials) except (AttributeError, ImportError): raise Exception( "Failed to find input channel class for '{}'. Unknown " "input channel. Check your credentials configuration to " "make sure the mentioned channel is not misspelled. " "If you are creating your own channel, make sure it " "is a proper name of a class in a module.".format(channel))
def create_http_input_channels(channel, # type: Union[None, Text, RestInput] credentials_file # type: Optional[Text] ): # type: (...) -> List[InputChannel] """Instantiate the chosen input channel.""" print(channel, credentials_file, "create_http son2") if channel is None or channel in rasa_core.channels.BUILTIN_CHANNELS: return _create_external_channels(channel, credentials_file) else: try: c = utils.class_from_module_path(channel) return [c()] except Exception: raise Exception("Unknown input channel for running main.")
def create_input_channel(channel, port, credentials_file): """Instantiate the chosen input channel.""" if channel == "facebook": return _create_facebook_channel(channel, port, credentials_file) elif channel == "cmdline": return ConsoleInputChannel() elif channel == "bot": return _create_bot_channel(port) else: try: c = utils.class_from_module_path(channel) return c() except Exception: raise Exception("Unknown input channel for running main.")
def load(cls, path: Text) -> 'PolicyEnsemble': """Loads policy and domain specification from storage""" metadata = cls.load_metadata(path) cls.ensure_model_compatibility(metadata) policies = [] for i, policy_name in enumerate(metadata["policy_names"]): policy_cls = registry.policy_from_module_path(policy_name) dir_name = 'policy_{}_{}'.format(i, policy_cls.__name__) policy_path = os.path.join(path, dir_name) policy = policy_cls.load(policy_path) cls._ensure_loaded_policy(policy, policy_cls, policy_name) policies.append(policy) ensemble_cls = utils.class_from_module_path(metadata["ensemble_name"]) fingerprints = metadata.get("action_fingerprints", {}) ensemble = ensemble_cls(policies, fingerprints) return ensemble
def from_dict(cls, dictionary: Dict[Text, Any]) -> List[Policy]: policies = dictionary.get('policies') or dictionary.get('policy') if policies is None: raise InvalidPolicyConfig( "You didn't define any policies. " "Please define them under 'policies:' in " "your policy configuration file.") if len(policies) == 0: raise InvalidPolicyConfig("The policy configuration file has to " "include at least one policy.") parsed_policies = [] for policy in policies: policy_name = policy.pop('name') if policy.get('featurizer'): featurizer_func, featurizer_config = \ cls.get_featurizer_from_dict(policy) if featurizer_config.get('state_featurizer'): state_featurizer_func, state_featurizer_config = \ cls.get_state_featurizer_from_dict( featurizer_config) # override featurizer's state_featurizer # with real state_featurizer class featurizer_config['state_featurizer'] = ( state_featurizer_func(**state_featurizer_config)) # override policy's featurizer with real featurizer class policy['featurizer'] = featurizer_func(**featurizer_config) constr_func = utils.class_from_module_path(policy_name) if constr_func: policy_object = constr_func(**policy) parsed_policies.append(policy_object) else: raise InvalidPolicyConfig( "Module for policy '{}' could not be " "loaded. Please make sure the name " "is a valid policy." "".format(policy_name)) return parsed_policies
def _action_class(action_name): # type: (Text) -> Action """Tries to create an instance by importing and calling the class.""" try: cls = utils.class_from_module_path(action_name) return cls() except ImportError as e: raise ValueError( "Action '{}' doesn't correspond to a template / action. " "Remember to prefix actions that should utter a template " "with `utter_`. Error: {}".format(action_name, e)) except (AttributeError, KeyError) as e: raise ValueError( "Action '{}' doesn't correspond to a template / action. " "Module doesn't contain a class with this name. " "Remember to prefix actions that should utter a template " "with `utter_`. Error: {}".format(action_name, e))
def from_dict(cls, dictionary): # type: Dict[Text, Any] -> List[Policy] policies = [] for policy in dictionary.get('policies', []): policy_name = policy.pop('name') if policy_name == 'KerasPolicy': policy_object = KerasPolicy(MaxHistoryTrackerFeaturizer( BinarySingleStateFeaturizer(), max_history=policy.get('max_history', 3))) constr_func = utils.class_from_module_path(policy_name) policy_object = constr_func(**policy) policies.append(policy_object) return policies