padatious_service.py
Go to the documentation of this file.
1 # Copyright 2017 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 from functools import lru_cache
16 from subprocess import call
17 from threading import Event
18 from time import time as get_time, sleep
19 
20 from os.path import expanduser, isfile
21 from pkg_resources import get_distribution
22 
23 from mycroft.configuration import Configuration
24 from mycroft.messagebus.message import Message
25 from mycroft.skills.core import FallbackSkill
26 from mycroft.util.log import LOG
27 
28 
30  instance = None
31 
32  fallback_tight_match = 5 # Fallback priority for the conf > 0.8 match
33  fallback_loose_match = 89 # Fallback priority for the conf > 0.5 match
34 
35  def __init__(self, bus, service):
36  FallbackSkill.__init__(self, use_settings=False)
37  if not PadatiousService.instance:
38  PadatiousService.instance = self
39 
40  self.padatious_config = Configuration.get()['padatious']
41  self.service = service
42  intent_cache = expanduser(self.padatious_config['intent_cache'])
43 
44  try:
45  from padatious import IntentContainer
46  except ImportError:
47  LOG.error('Padatious not installed. Please re-run dev_setup.sh')
48  try:
49  call(['notify-send', 'Padatious not installed',
50  'Please run build_host_setup and dev_setup again'])
51  except OSError:
52  pass
53  return
54 
55  self.container = IntentContainer(intent_cache)
56 
57  self._bus = bus
58  self.bus.on('padatious:register_intent', self.register_intent)
59  self.bus.on('padatious:register_entity', self.register_entity)
60  self.bus.on('detach_intent', self.handle_detach_intent)
61  self.bus.on('detach_skill', self.handle_detach_skill)
62  self.bus.on('mycroft.skills.initialized', self.train)
63 
64  # Call Padatious an an early fallback, looking for a high match intent
66  PadatiousService.fallback_tight_match)
67 
68  # Try loose Padatious intent match before going to fallback-unknown
70  PadatiousService.fallback_loose_match)
71 
72  self.finished_training_event = Event()
74 
75  self.train_delay = self.padatious_config['train_delay']
76  self.train_time = get_time() + self.train_delay
77 
79 
80  def train(self, message=None):
81  if message is None:
82  single_thread = False
83  else:
84  single_thread = message.data.get('single_thread', False)
85  self.finished_training_event.clear()
86 
87  LOG.info('Training... (single_thread={})'.format(single_thread))
88  self.container.train(single_thread=single_thread)
89  LOG.info('Training complete.')
90 
91  self.finished_training_event.set()
92  if not self.finished_initial_train:
93  LOG.info("Mycroft is all loaded and ready to roll!")
94  self.bus.emit(Message('mycroft.ready'))
95  self.finished_initial_train = True
96 
97  def wait_and_train(self):
98  if not self.finished_initial_train:
99  return
100  sleep(self.train_delay)
101  if self.train_time < 0.0:
102  return
103 
104  if self.train_time <= get_time() + 0.01:
105  self.train_time = -1.0
106  self.train()
107 
108  def __detach_intent(self, intent_name):
109  self.registered_intents.remove(intent_name)
110  self.container.remove_intent(intent_name)
111 
112  def handle_detach_intent(self, message):
113  self.__detach_intent(message.data.get('intent_name'))
114 
115  def handle_detach_skill(self, message):
116  skill_id = message.data['skill_id']
117  remove_list = [i for i in self.registered_intents if skill_id in i]
118  for i in remove_list:
119  self.__detach_intent(i)
120 
121  def _register_object(self, message, object_name, register_func):
122  file_name = message.data['file_name']
123  name = message.data['name']
124 
125  LOG.debug('Registering Padatious ' + object_name + ': ' + name)
126 
127  if not isfile(file_name):
128  LOG.warning('Could not find file ' + file_name)
129  return
130 
131  register_func(name, file_name)
132  self.train_time = get_time() + self.train_delay
133  self.wait_and_train()
134 
135  def register_intent(self, message):
136  self.registered_intents.append(message.data['name'])
137  self._register_object(message, 'intent', self.container.load_intent)
138 
139  def register_entity(self, message):
140  self._register_object(message, 'entity', self.container.load_entity)
141 
142  def handle_fallback(self, message, threshold=0.8):
143  if not self.finished_training_event.is_set():
144  LOG.debug('Waiting for Padatious training to finish...')
145  return False
146 
147  utt = message.data.get('utterance', '')
148  LOG.debug("Padatious fallback attempt: " + utt)
149  intent = self.calc_intent(utt)
150 
151  if not intent or intent.conf < threshold:
152  # Attempt to use normalized() version
153  norm = message.data.get('norm_utt', '')
154  if norm != utt:
155  LOG.debug(" alt attempt: " + norm)
156  intent = self.calc_intent(norm)
157  utt = norm
158  if not intent or intent.conf < threshold:
159  return False
160 
161  intent.matches['utterance'] = utt
162  self.service.add_active_skill(intent.name.split(':')[0])
163  self.bus.emit(message.reply(intent.name, data=intent.matches))
164  return True
165 
166  def handle_fallback_last_chance(self, message):
167  return self.handle_fallback(message, 0.5)
168 
169  # NOTE: This cache will keep a reference to this calss (PadatiousService),
170  # but we can live with that since it is used as a singleton.
171  @lru_cache(maxsize=2) # 2 catches both raw and normalized utts in cache
172  def calc_intent(self, utt):
173  return self.container.calc_intent(utt)
def _register_object(self, message, object_name, register_func)
def register_fallback(self, handler, priority)
Definition: core.py:1793
def handle_fallback(self, message, threshold=0.8)
def register_intent(self, intent_parser, handler)
Definition: core.py:1133


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40