Skip to content

Commit

Permalink
fix/get_response some more
Browse files Browse the repository at this point in the history
  • Loading branch information
JarbasAl committed Oct 2, 2023
1 parent 88d09bb commit 9401f49
Showing 1 changed file with 75 additions and 58 deletions.
133 changes: 75 additions & 58 deletions ovos_workshop/skills/ovos.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ def __init__(self, name: Optional[str] = None,
self.public_api: Dict[str, dict] = {}

self._original_converse = self.converse # for get_response

self.__responses = {}
self._threads = [] # for killable events decorator

# yay, following python best practices again!
Expand Down Expand Up @@ -935,6 +937,8 @@ def _register_system_event_handlers(self):
self.add_event('mycroft.skills.settings.changed',
self.handle_settings_change, speak_errors=False)

self.add_event("skill.converse.get_response", self.__handle_get_response, speak_errors=False)

def _send_public_api(self, message: Message):
"""
Respond with the skill's public api.
Expand Down Expand Up @@ -1543,6 +1547,24 @@ def converse(utterances, lang=None):
{"skill_id": self.skill_id}))
return converse.response

def __handle_get_response(self, message):

skill_id = message.data["skill_id"]
if skill_id != self.skill_id:
return # not for us!

# validate session_id to ensure this isnt another
# user querying the skill at same time
sess2 = SessionManager.get(message)
if sess2.session_id not in self.__responses:
LOG.debug(f"ignoring get_response answer for session: {sess2.session_id}")
return # not for us!

utterances = message.data["utterances"]
print(f"GET RESPONSE GOT: {utterances}")
# received get_response
self.__responses[sess2.session_id] = utterances

@backwards_compat(classic_core=__get_response_v1, pre_008=__get_response_v1)
def __get_response(self, session: Session):
"""Helper to get a response from the user
Expand All @@ -1565,48 +1587,30 @@ def __get_response(self, session: Session):

self.bus.emit(srcm.forward("skill.converse.get_response.enable",
{"skill_id": self.skill_id}))
utterances = []

LOG.debug(f"get_response session: {session.session_id}")

def _handle_get_response(message):
nonlocal utterances

skill_id = message.data["skill_id"]
if skill_id != self.skill_id:
return # not for us!

# validate session_id to ensure this isnt another
# user querying the skill at same time
sess2 = SessionManager.get(message)
if session.session_id != sess2.session_id:
LOG.debug(f"ignoring get_response answer for session: {sess2.session_id}")
return # not for us!

utterances = message.data["utterances"]
# received get_response

self.bus.on("skill.converse.get_response", _handle_get_response)
ans = []

# NOTE: a threading.Event is not used otherwise we can't raise the
# AbortEvent exception to kill the thread
# this is for compat with killable_intents decorators
start = time.time()
while time.time() - start <= 15 and not len(utterances):
while time.time() - start <= 15 and not ans:
ans = self.__responses[session.session_id]
time.sleep(0.1)
if self.__response is not False:
if self.__response is None:
# aborted externally (if None)
self.log.debug("get_response aborted")
else:
utterances = [self.__response] # external override
print(f"CURRENT GET RESPONSE: {ans}")
if ans is None:
# aborted externally (if None)
self.log.debug("get_response aborted")
break

self.bus.remove("skill.converse.get_response", _handle_get_response)
self.bus.emit(srcm.forward("skill.converse.get_response.disable",
{"skill_id": self.skill_id}))

if utterances:
return utterances[0]
if ans:
print(f"GET RESPONSE RETURN: {ans}")
return ans
print(f"GET RESPONSE RETURN: None")
return None

def get_response(self, dialog: str = '', data: Optional[dict] = None,
Expand Down Expand Up @@ -1678,25 +1682,52 @@ def _wait_response(self, is_cancel: callable, validator: callable,
@param num_retries: Number of times to retry getting a response
@returns: User response if validated, else None
"""
self.__response = False
session = SessionManager.get(message)

self.__responses[session.session_id] = []
# self.__responses.get(session.session_id) <- set in a killable thread
self._real_wait_response(is_cancel, validator, on_fail, num_retries, message)
while self.__response is False:

# wait for answer from killable thread
ans = []
while not ans:
# TODO: Refactor to Event
time.sleep(0.1)
return self.__response or None
ans = self.__responses.get(session.session_id)
if ans or ans is None: # canceled response
break

self.__responses.pop(session.session_id)

if isinstance(ans, list):
ans = ans[0] # TODO handle multiple transcriptions

# catch user saying 'cancel'
if is_cancel(ans):
return None

# returns the validated value or the response
# (backwards compat)
validated = validator(ans)
ans = ans if validated is True else validated

return ans

def _handle_killed_wait_response(self):
"""
Handle "stop" request when getting a response.
"""
self.__response = None
self.__responses = {k: None for k in self.__responses}
self.converse = self._original_converse

@killable_event("mycroft.skills.abort_question", exc=AbortQuestion,
callback=_handle_killed_wait_response, react_to_stop=True)
def _real_wait_response(self, is_cancel, validator, on_fail, num_retries,
message: Message):
"""
runs in a thread, result retrieved via self.__responses[sess.session_id]
Loop until a valid response is received from the user or the retry
limit is reached.
Expand All @@ -1707,46 +1738,32 @@ def _real_wait_response(self, is_cancel, validator, on_fail, num_retries,
"""
sess = SessionManager.get(message)
msg = message.reply('mycroft.mic.listen')

num_fails = 0
while True:
if self.__response is not False:
# usually None when aborted externally
# also allows overriding returned result from other events
return self.__response

response = self.__get_response(sess)

if response is None:
break # killed externally

if not response: # empty list
# if nothing said, prompt one more time
num_none_fails = 1 if num_retries < 0 else num_retries
if num_fails >= num_none_fails:
self.__response = None
return
else:
# catch user saying 'cancel'
if is_cancel(response):
self.__response = None
if num_fails >= num_retries:
self.__responses[sess.session_id] = None # stop trying
return

validated = validator(response)
# returns the validated value or the response
# (backwards compat)
if validated is not False and validated is not None:
self.__response = response if validated is True else validated
return
num_fails += 1

num_fails += 1
if 0 < num_retries < num_fails or self.__response is not False:
self.__response = None
return
if self.__responses.get(sess.session_id) is None:
return # dont prompt

# re-prompt user
line = on_fail(response)
if line:
self.speak(line, expect_response=True)
else:
self.bus.emit(msg)
self.bus.emit(message.reply('mycroft.mic.listen'))

@staticmethod
def __acknowledge_classic():
Expand Down

0 comments on commit 9401f49

Please sign in to comment.