|
| 1 | +import os |
| 2 | +import re |
| 3 | +from os.path import dirname |
| 4 | +from threading import Event |
| 5 | + |
| 6 | +import ovos_core.intent_services |
| 7 | +from ovos_bus_client.message import Message |
| 8 | +from ovos_bus_client.session import SessionManager |
| 9 | +from ovos_config.config import Configuration |
| 10 | +from ovos_utils import flatten_list |
| 11 | +from ovos_utils.bracket_expansion import expand_options |
| 12 | +from ovos_utils.log import LOG |
| 13 | +from ovos_utils.parse import match_one |
| 14 | + |
| 15 | + |
| 16 | +class StopService: |
| 17 | + """Intent Service thats handles stopping skills.""" |
| 18 | + |
| 19 | + def __init__(self, bus): |
| 20 | + self.bus = bus |
| 21 | + self._voc_cache = {} |
| 22 | + self.load_resource_files() |
| 23 | + |
| 24 | + def load_resource_files(self): |
| 25 | + base = f"{dirname(dirname(__file__))}/locale" |
| 26 | + for lang in os.listdir(base): |
| 27 | + lang2 = lang.split("-")[0].lower() |
| 28 | + self._voc_cache[lang2] = {} |
| 29 | + for f in os.listdir(f"{base}/{lang}"): |
| 30 | + with open(f"{base}/{lang}/{f}") as fi: |
| 31 | + lines = [expand_options(l) for l in fi.read().split("\n") |
| 32 | + if l.strip() and not l.startswith("#")] |
| 33 | + n = f.split(".", 1)[0] |
| 34 | + self._voc_cache[lang2][n] = flatten_list(lines) |
| 35 | + |
| 36 | + @property |
| 37 | + def config(self): |
| 38 | + """ |
| 39 | + Returns: |
| 40 | + stop_config (dict): config for stop handling options |
| 41 | + """ |
| 42 | + return Configuration().get("skills", {}).get("stop") or {} |
| 43 | + |
| 44 | + def get_active_skills(self, message=None): |
| 45 | + """Active skill ids ordered by converse priority |
| 46 | + this represents the order in which stop will be called |
| 47 | +
|
| 48 | + Returns: |
| 49 | + active_skills (list): ordered list of skill_ids |
| 50 | + """ |
| 51 | + session = SessionManager.get(message) |
| 52 | + return [skill[0] for skill in session.active_skills] |
| 53 | + |
| 54 | + def _collect_stop_skills(self, message): |
| 55 | + """use the messagebus api to determine which skills can stop |
| 56 | + This includes all skills and external applications""" |
| 57 | + |
| 58 | + want_stop = [] |
| 59 | + skill_ids = [] |
| 60 | + |
| 61 | + active_skills = self.get_active_skills(message) |
| 62 | + |
| 63 | + if not active_skills: |
| 64 | + return want_stop |
| 65 | + |
| 66 | + event = Event() |
| 67 | + |
| 68 | + def handle_ack(msg): |
| 69 | + nonlocal event |
| 70 | + skill_id = msg.data["skill_id"] |
| 71 | + |
| 72 | + # validate the stop pong |
| 73 | + if all((skill_id not in want_stop, |
| 74 | + msg.data.get("can_handle", True), |
| 75 | + skill_id in active_skills)): |
| 76 | + want_stop.append(skill_id) |
| 77 | + |
| 78 | + if skill_id not in skill_ids: # track which answer we got |
| 79 | + skill_ids.append(skill_id) |
| 80 | + |
| 81 | + if all(s in skill_ids for s in active_skills): |
| 82 | + # all skills answered the ping! |
| 83 | + event.set() |
| 84 | + |
| 85 | + self.bus.on("skill.stop.pong", handle_ack) |
| 86 | + |
| 87 | + # ask skills if they can stop |
| 88 | + for skill_id in active_skills: |
| 89 | + self.bus.emit(message.forward(f"{skill_id}.stop.ping", |
| 90 | + {"skill_id": skill_id})) |
| 91 | + |
| 92 | + # wait for all skills to acknowledge they can stop |
| 93 | + event.wait(timeout=0.5) |
| 94 | + |
| 95 | + self.bus.remove("skill.stop.pong", handle_ack) |
| 96 | + return want_stop or active_skills |
| 97 | + |
| 98 | + def stop_skill(self, skill_id, message): |
| 99 | + """Tell a skill to stop anything it's doing, |
| 100 | + taking into account the message Session |
| 101 | +
|
| 102 | + Args: |
| 103 | + skill_id: skill to query. |
| 104 | + message (Message): message containing interaction info. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + handled (bool): True if handled otherwise False. |
| 108 | + """ |
| 109 | + stop_msg = message.reply(f"{skill_id}.stop") |
| 110 | + result = self.bus.wait_for_response(stop_msg, f"{skill_id}.stop.response") |
| 111 | + if result and 'error' in result.data: |
| 112 | + error_msg = result.data['error'] |
| 113 | + LOG.error(f"{skill_id}: {error_msg}") |
| 114 | + return False |
| 115 | + elif result is not None: |
| 116 | + return result.data.get('result', False) |
| 117 | + |
| 118 | + def match_stop_high(self, utterances, lang, message): |
| 119 | + """If utterance is an exact match for "stop" , run before intent stage |
| 120 | +
|
| 121 | + Args: |
| 122 | + utterances (list): list of utterances |
| 123 | + lang (string): 4 letter ISO language code |
| 124 | + message (Message): message to use to generate reply |
| 125 | +
|
| 126 | + Returns: |
| 127 | + IntentMatch if handled otherwise None. |
| 128 | + """ |
| 129 | + lang = lang.split("-")[0] |
| 130 | + if lang not in self._voc_cache: |
| 131 | + return None |
| 132 | + |
| 133 | + # we call flatten in case someone is sending the old style list of tuples |
| 134 | + utterance = flatten_list(utterances)[0] |
| 135 | + |
| 136 | + is_stop = self.voc_match(utterance, 'stop', exact=True, lang=lang) |
| 137 | + is_global_stop = self.voc_match(utterance, 'global_stop', exact=True, lang=lang) or \ |
| 138 | + (is_stop and not len(self.get_active_skills(message))) |
| 139 | + |
| 140 | + conf = 1.0 |
| 141 | + |
| 142 | + if is_global_stop: |
| 143 | + # emit a global stop, full stop anything OVOS is doing |
| 144 | + self.bus.emit(message.reply("mycroft.stop", {})) |
| 145 | + return ovos_core.intent_services.IntentMatch('Stop', None, {"conf": conf}, |
| 146 | + None, utterance) |
| 147 | + |
| 148 | + if is_stop: |
| 149 | + # check if any skill can stop |
| 150 | + for skill_id in self._collect_stop_skills(message): |
| 151 | + if self.stop_skill(skill_id, message): |
| 152 | + return ovos_core.intent_services.IntentMatch('Stop', None, {"conf": conf}, |
| 153 | + skill_id, utterance) |
| 154 | + return None |
| 155 | + |
| 156 | + def match_stop_medium(self, utterances, lang, message): |
| 157 | + """ if "stop" intent is in the utterance, |
| 158 | + but it contains additional words not in .intent files |
| 159 | +
|
| 160 | + Args: |
| 161 | + utterances (list): list of utterances |
| 162 | + lang (string): 4 letter ISO language code |
| 163 | + message (Message): message to use to generate reply |
| 164 | +
|
| 165 | + Returns: |
| 166 | + IntentMatch if handled otherwise None. |
| 167 | + """ |
| 168 | + lang = lang.split("-")[0] |
| 169 | + if lang not in self._voc_cache: |
| 170 | + return None |
| 171 | + |
| 172 | + # we call flatten in case someone is sending the old style list of tuples |
| 173 | + utterance = flatten_list(utterances)[0] |
| 174 | + |
| 175 | + is_stop = self.voc_match(utterance, 'stop', exact=False, lang=lang) |
| 176 | + if not is_stop: |
| 177 | + is_global_stop = self.voc_match(utterance, 'global_stop', exact=False, lang=lang) or \ |
| 178 | + (is_stop and not len(self.get_active_skills(message))) |
| 179 | + if not is_global_stop: |
| 180 | + return None |
| 181 | + |
| 182 | + return self.match_stop_low(utterances, lang, message) |
| 183 | + |
| 184 | + def match_stop_low(self, utterances, lang, message): |
| 185 | + """ before fallback_low , fuzzy match stop intent |
| 186 | +
|
| 187 | + Args: |
| 188 | + utterances (list): list of utterances |
| 189 | + lang (string): 4 letter ISO language code |
| 190 | + message (Message): message to use to generate reply |
| 191 | +
|
| 192 | + Returns: |
| 193 | + IntentMatch if handled otherwise None. |
| 194 | + """ |
| 195 | + lang = lang.split("-")[0] |
| 196 | + if lang not in self._voc_cache: |
| 197 | + return None |
| 198 | + |
| 199 | + # we call flatten in case someone is sending the old style list of tuples |
| 200 | + utterance = flatten_list(utterances)[0] |
| 201 | + |
| 202 | + conf = match_one(utterance, self._voc_cache[lang]['stop'])[1] |
| 203 | + if len(self.get_active_skills(message)) > 0: |
| 204 | + conf += 0.1 |
| 205 | + conf = round(min(conf, 1.0), 3) |
| 206 | + |
| 207 | + if conf < self.config.get("min_conf", 0.5): |
| 208 | + return None |
| 209 | + |
| 210 | + # check if any skill can stop |
| 211 | + for skill_id in self._collect_stop_skills(message): |
| 212 | + if self.stop_skill(skill_id, message): |
| 213 | + return ovos_core.intent_services.IntentMatch('Stop', None, {"conf": conf}, |
| 214 | + skill_id, utterance) |
| 215 | + |
| 216 | + # emit a global stop, full stop anything OVOS is doing |
| 217 | + self.bus.emit(message.reply("mycroft.stop", {})) |
| 218 | + return ovos_core.intent_services.IntentMatch('Stop', None, {"conf": conf}, |
| 219 | + None, utterance) |
| 220 | + |
| 221 | + def voc_match(self, utt: str, voc_filename: str, lang: str, |
| 222 | + exact: bool = False): |
| 223 | + """ |
| 224 | + Determine if the given utterance contains the vocabulary provided. |
| 225 | +
|
| 226 | + By default the method checks if the utterance contains the given vocab |
| 227 | + thereby allowing the user to say things like "yes, please" and still |
| 228 | + match against "Yes.voc" containing only "yes". An exact match can be |
| 229 | + requested. |
| 230 | +
|
| 231 | + The method first checks in the current Skill's .voc files and secondly |
| 232 | + in the "res/text" folder of mycroft-core. The result is cached to |
| 233 | + avoid hitting the disk each time the method is called. |
| 234 | +
|
| 235 | + Args: |
| 236 | + utt (str): Utterance to be tested |
| 237 | + voc_filename (str): Name of vocabulary file (e.g. 'yes' for |
| 238 | + 'res/text/en-us/yes.voc') |
| 239 | + lang (str): Language code, defaults to self.lang |
| 240 | + exact (bool): Whether the vocab must exactly match the utterance |
| 241 | +
|
| 242 | + Returns: |
| 243 | + bool: True if the utterance has the given vocabulary it |
| 244 | + """ |
| 245 | + lang = lang.split("-")[0].lower() |
| 246 | + if lang not in self._voc_cache: |
| 247 | + return False |
| 248 | + |
| 249 | + _vocs = self._voc_cache[lang].get(voc_filename) or [] |
| 250 | + |
| 251 | + if utt and _vocs: |
| 252 | + if exact: |
| 253 | + # Check for exact match |
| 254 | + return any(i.strip() == utt |
| 255 | + for i in _vocs) |
| 256 | + else: |
| 257 | + # Check for matches against complete words |
| 258 | + return any([re.match(r'.*\b' + i + r'\b.*', utt) |
| 259 | + for i in _vocs]) |
| 260 | + return False |
0 commit comments