Beispiel #1
0
 def detect_language_from_text(self, text):
     """
     Detects _language from text.
     :param str text: text to be analyzed
     :rtype ActionResult
     :return: ActionResult with _language name as payload
     """
     assert(isinstance(text, str))
     lang_code = self._detect_language(text).lang
     return ActionResult(self._convert_lang_code_to_language(lang_code), SUCCESS)
Beispiel #2
0
 def recognize_from_microphone(self):
     """
     Returns action result with recognized text from the speech. Input speech is read from microphone. Raises RequestError or
     UnknownValueError.
     :rtype: ActionResult
     :return: ActionResult with recognized text from the speech
     """
     audio = self._get_audio_from_microphone()
     speech = self._recognition_method(audio, language=self._language)
     result = ActionResult(speech, SUCCESS)
     return result
Beispiel #3
0
 def get_complete_page(self, query):
     """
     Returns wiki page that satisfy input query (complete page content)
     :param query: searching term (str)
     :return:
     """
     try:
         page = wikipedia.page(query)
         return ActionResult(page.content, SUCCESS)
     except Exception as e:
         #return ActionResult(e, DEFAULT_EXCEPTION)
         pass
    def _commit(self, service, method):
        """
        Executes service method with arguments from [service_command_methods] dict. If some error occurs, calls exception
        handler. If service is None, returns ActionResult with fatal status.
        :param str service: service name
        :param str method: method name
        :rtype: ActionResult
        :return: ActionResult with SUCCESS - result of execution as payload, FAIL - customized exception message as
        payload or FATAL - blank message result.
        """
        logger.info("-------- begin commit --------")
        service_inst = self._service_pool.get(service, None)
        command_result = None
        if service_inst is not None:
            if hasattr(service_inst, method):
                executor = getattr(service_inst, method)
                try:
                    result = executor(
                        **self._service_command_methods[service][method])
                    logger.debug("Output = {}".format(result))
                    command_result = result

                    # TODO:handle fatal exception
                except Exception as e:
                    message = ExceptionHandler.get_exception_message(
                        e, self._language)
                    command_result = ActionResult(message, FAIL,
                                                  self._language)
                finally:
                    logger.info("-------- end commit --------")
                    #self._clear_all_params(service, method)
                    return command_result
        else:
            logger.error("Fatal, service cannot be found.")
            message = ExceptionHandler.get_exception_message(
                VoiceAssistantException, self._language)
            #self._clear_all_params(service, method)
            return ActionResult(message, FATAL)
 def open_social_network_page(self, nickname=None, social_network_url=FACEBOOK_BASE_URL):
     """
     Opens social network page
     :param str nickname: user nickname
     :param str social_network_url: base url of wanted social network (FB, IG, TW, IN)
     :rtype ActionResult
     :return: Empty ActionResult with SUCCESS status
     """
     assert (isinstance(nickname, str) and isinstance(social_network_url, str))
     logger.debug("Calling open_social_network_page with params: [nickname = {}, social_network_url = {}].".
                  format(nickname, social_network_url))
     url = social_network_url + nickname + "/"
     self._browser_open(url)
     return ActionResult("", SUCCESS)
    def listen_and_execute(self):
        """
        Listen speech and convert it to text (if possible). Based on stt result, execute wanted command or returns the
        error message (through speak).
        :rtype: None
        :return: void method
        """
        try:
            text_result = self._recognizer.recognize_from_microphone()
        except Exception as e:
            message = ExceptionHandler.get_exception_message(e, self._language)
            text_result = ActionResult(message, FAIL)
            self._reset_speaking_language_()
        self._reset_recognizer_language()

        if text_result is None or text_result.get_result() is None or text_result.get_status() == FAIL:
            output = self._get_output_speech(text_result)
        else:
            logger.debug("Speech recognition result = {}".format(text_result))
            try:
                output = self._execute(text_result.get_result())
            except Exception as e:
                output = (ExceptionHandler.get_exception_message(e, self._language), '')
        self._speak_out(message_prefix=output[0], output_message=output[1])
Beispiel #7
0
 def brief_search(self, query, sentences=3):
     """
     Get summary section of page that satisfy query.
     :param query: searching term  (str)
     :param sentences: number of sentences that wikipedia summary should have (int)
     :return: ActionResult with the result from wikipedia page (or appropriate error message)
     """
     logger.debug(
         "Calling wikipedia brief_search with [query = {}]".format(query))
     if sentences > 10:
         raise ValueError(
             "Number of summary sentences can not be greater than 10.")
     summary = wikipedia.summary(query, sentences=sentences)
     logger.debug("Wikipedia summary = {}".format(summary))
     return ActionResult(summary, SUCCESS)
 def open_found_url_in_browser(self, query, tpe=""):
     """
     Opens the found url in browser.
     :param str query: google search query string. Must not be URL-encoded
     :param str tpe: type_ of search, default=`all`
     :rtype ActionResult
     :return: Empty ActionResult with SUCCESS status
     """
     assert (isinstance(query, str) and isinstance(tpe, str))
     logger.debug("Calling open_found_url_in_browser with params: [query = {}, tpe = {}].".format(query, tpe))
     url = self._get_first_search_result(query, tpe=tpe)
     #url = google_result.get_result()
     if url is not None:
         logger.debug("Found url = {}.".format(url))
         self._browser_open(url=url)
         return ActionResult("", SUCCESS)
     else:
         raise GoogleSearchException
Beispiel #9
0
 def translate_text(self,  text=None, src_language="en", dest_language="en"):
     """
     Translates text from src_language to dest_language.If text is `Mary had a little lamb`, src_language `en`, and
     dest_language is `sr`, resulting text has value: `Мери је имала мало јагње`
     :param str text: text for translation
     :param str src_language: _language code of text's _language
     :param str dest_language: target translation _language
     :rtype ActionResult
     :return: ActionResult with translated text as payload
     """
     assert(isinstance(text, str) and isinstance(src_language, str) and isinstance(dest_language, str))
     logger.debug("Calling translate_text with params: [text = {}, src_language = {}, dest_language = {}]".
                  format(text, src_language, dest_language))
     dest_language = self._get_appropriate_lang_code(dest_language)
     logger.debug("Language code = {}.".format(dest_language))
     translated_text = self._translate(text, src_lang=src_language, dest_lang=dest_language)
     logger.debug("Raw translation object = {}".format(translated_text))
     logger.debug("Translated text = {}".format(translated_text.text))
     return ActionResult(translated_text.text, SUCCESS, language=dest_language)
 def _execute_controller_method(self, method, command):
     """
     Handle execution of command's method that is defined in controller.
     :param str method: method name
     :param dict command: command dictionary
     :rtype: ActionResult
     :return: command result
     """
     executor = getattr(self, method)
     try:
         if command["has_args"]:
             command_result = eval('executor(' + command["arg_name"] + "=" + "'" + str(command["arg"]) + "')")
         else:
             command_result = executor()
     except Exception as e:
         language = self._language if self._language is not None else "en"
         message = ExceptionHandler.get_exception_message(e, language)
         command_result = ActionResult(message, FAIL, language)
     return command_result
 def get_forecast_result(self, location, param="all", unit="celsius"):
     """
     Returns weather forecast for location.
     :param location: location (str) - location which forecast we seek
     :param param: param (str); default = all - which weather parameter we want
     :param unit: unit(str); default = celsius - unit for temperature measurement, expected values are celsius,
     fahrenheit and kelvin
     :return: weather forecast in string format weather_param:value
     covered params:clouds, pressure, wind speed (mph), humidity, minimum temperature, maximum temperature,temperature
     detailed status
     """
     logger.debug(
         "Calling get_forecast_result with params: [location = {}, param = {}, unit = {}]".format(str(location), \
                                                                                                  str(param),
                                                                                                  str(unit)))
     weather_data = self._get_weather_at_location(location)
     logger.debug("Weather data results were fetched....")
     logger.debug("Raw forecast results = {}".format(str(weather_data)))
     forecast_output = self._get_forecast_in_readable_form(
         weather_data, param, **{"unit": unit})
     logger.debug("Forecast in readable form:\n{}".format(forecast_output))
     return ActionResult(forecast_output, SUCCESS)
 def get_movie_details(self, title):
     """
     Get movie details (full form) for movie with title [title].
     :param title: Movie title (str)
     :return: Movie details (str) wrapped in ActionResult.
     """
     assert (isinstance(title, str))
     logger.debug("Get movie details. Params: [title = {}].".format(title))
     movie = self._get_first_movie(title)
     if movie is not None:
         movie_id = self._get_movie_id(movie)
         logger.debug("Movie id = {}".format(movie_id))
         movie_details = self._get_movie_by_id(movie_id)
         if movie_details != {}:
             movie_info = self._get_detailed_movie_info(movie_details)
             movie_info_rdbl_form = self._movie_info_to_str(movie_info)
             logger.debug("Complete movie info:\n{}".format(movie_info))
         else:
             movie_info_rdbl_form = "Movie that you asked for cannot be found."
             logger.debug("Movie cannot be found....")
         return ActionResult(movie_info_rdbl_form, SUCCESS, language="en")
     else:
         return None
 def get_top_movies(self, num=1):
     """
     Returns brief movie info details about best movies by imdb. Number of movies is determined by [num] arg. This
     argument cannot be greater than 250.
     :param num: Number of top movies we seek. (int); in range [1,250]
     :return: movies info string wrapped in ActionResult; default speaking _language is english
     """
     assert (isinstance(num, int)), "Value must be integer by type_."
     assert (num in range(1, 251)), "Value must be in range 1 to 250"
     # TODO:handle num when spoken in Serbian, it uses words, in english it uses numbers
     num = int(num)
     logger.debug(
         "Seeking for best movies by imdb. Params: [num = {}].".format(num))
     top_movies = self._imdb.get_top250_movies()[:num]
     complete_info = ""
     for movie in top_movies:
         movie_id = self._get_movie_id(movie)
         logger.debug("Movie id = {}".format(movie_id))
         movie_details = self._get_movie_by_id(movie_id)
         movie_info = self._get_brief_movie_info(movie_details)
         complete_info += self._movie_info_to_str(movie_info) + "\n"
     logger.debug("Complete movies info:\n{}".format(complete_info))
     #NOTE:action result _language is set to english because imdb API results are in english
     return ActionResult(complete_info, SUCCESS, language="en")