Browse Source

[Refactor] move RecognitionOptions to Options

ThiBuff 7 years ago
parent
commit
54a85bb75f

+ 41 - 56
Docs/settings.md

@@ -12,9 +12,6 @@ This part of the documentation explains the main configuration of Kalliope place
   - [Speech to text configuration](#speech-to-text-configuration)
     - [default_speech_to_text](#defaultspeechtotext)
     - [speech_to_text](#speechtotext)
-    - [recognition_options](#recognitionoptions)
-      - [energy_threshold](#energythreshold)
-      - [adjust_for_ambient_noise_second](#adjustforambientnoisesecond)
   - [Text to speech configuration](#text-to-speech-configuration)
     - [default_text_to_speech](#defaulttexttospeech)
     - [text_to_speech](#texttospeech)
@@ -155,55 +152,6 @@ speech_to_text:
 
 Some arguments are required, some others are optional, please refer to the [STT documentation](stt.md) to know available parameters for each supported STT.
 
-### recognition_options
-
-Represents a collection of speech recognition settings and functionality.
-```yml
-recognition_options:
-  option_name: option_value
-  option_name2: option_value2
-```
-
-E.g
-```yml
-recognition_options:
-  energy_threshold: 3000
-```
-
-#### energy_threshold
-
-Represents the energy level threshold for sounds. By default set to **4000**.
-Values below this threshold are considered silence, and values above this threshold are considered speech.
-This is adjusted automatically if dynamic thresholds are enabled with `adjust_for_ambient_noise_second` parameter.
-
-This threshold is associated with the perceived loudness of the sound, but it is a nonlinear relationship.
-The actual energy threshold you will need depends on your microphone sensitivity or audio data.
-Typical values for a silent room are 0 to 100, and typical values for speaking are between 150 and 3500.
-Ambient (non-speaking) noise has a significant impact on what values will work best.
-
-If you're having trouble with the recognizer trying to recognize words even when you're not speaking, try tweaking this to a higher value.
-If you're having trouble with the recognizer not recognizing your words when you are speaking, try tweaking this to a lower value.
-For example, a sensitive microphone or microphones in louder rooms might have a ambient energy level of up to 4000.
-```yml
-recognition_options:
-  energy_threshold: 4000
-```
-
->**Note:** The default value is 4000 if not set
-
-#### adjust_for_ambient_noise_second
-
-If defined, will adjusts the energy threshold dynamically by capturing the current ambient noise of the room during the number of second set in the parameter.
-When set, the `energy_threshold` parameter is overridden by the returned value of the noise calibration.
-This value should be at least 0.5 in order to get a representative sample of the ambient noise.
-
-```yml
-recognition_options:
-  adjust_for_ambient_noise_second: 1
-```
-
->**Note:** The number of second here represents the time between kalliope's awakening and the moment when you can give her your order.
-
 ## Text to speech configuration
 
 ### default_text_to_speech
@@ -500,10 +448,47 @@ options:
 
 Available options:
 
-| Option | Description                                                                                   |
-| ------ | --------------------------------------------------------------------------------------------- |
-| muted  | When muted, the STT engine will not be used to make Kalliope talking during neurons execution |
-| deaf   | When deaf, the trigger engine is not started. Kalliope will not listen for a wake up word     |
+| Option                            | Description                                                                                   |
+| ----------------------------------| --------------------------------------------------------------------------------------------- |
+| muted                             | When muted, the STT engine will not be used to make Kalliope talking during neurons execution |
+| deaf                              | When deaf, the trigger engine is not started. Kalliope will not listen for a wake up word     |
+| energy_threshold                  | [energy_threshold](#energythreshold)                                                          |
+| adjust_for_ambient_noise_second   | [adjust_for_ambient_noise_second](#adjustforambientnoisesecond)                               |
 
 ## Next: configure the brain of Kalliope
 Now your settings are ok, you can start creating the [brain](brain.md) of your assistant.
+
+
+#### energy_threshold
+
+Represents the energy level threshold for sounds. By default set to **4000**.
+Values below this threshold are considered silence, and values above this threshold are considered speech.
+This is adjusted automatically if dynamic thresholds are enabled with `adjust_for_ambient_noise_second` parameter.
+
+This threshold is associated with the perceived loudness of the sound, but it is a nonlinear relationship.
+The actual energy threshold you will need depends on your microphone sensitivity or audio data.
+Typical values for a silent room are 0 to 100, and typical values for speaking are between 150 and 3500.
+Ambient (non-speaking) noise has a significant impact on what values will work best.
+
+If you're having trouble with the recognizer trying to recognize words even when you're not speaking, try tweaking this to a higher value.
+If you're having trouble with the recognizer not recognizing your words when you are speaking, try tweaking this to a lower value.
+For example, a sensitive microphone or microphones in louder rooms might have a ambient energy level of up to 4000.
+```yml
+options:
+  energy_threshold: 4000
+```
+
+>**Note:** The default value is 4000 if not set
+
+#### adjust_for_ambient_noise_second
+
+If defined, will adjusts the energy threshold dynamically by capturing the current ambient noise of the room during the number of second set in the parameter.
+When set, the `energy_threshold` parameter is overridden by the returned value of the noise calibration.
+This value should be at least 0.5 in order to get a representative sample of the ambient noise.
+
+```yml
+options:
+  adjust_for_ambient_noise_second: 1
+```
+
+>**Note:** The number of second here represents the time between kalliope's awakening and the moment when you can give her your order.

+ 1 - 0
Tests/settings/settings_test.yml

@@ -118,3 +118,4 @@ var_files:
 options:
   deaf: True
   mute: False
+  energy_threshold: 3000

+ 0 - 7
Tests/test_models.py

@@ -4,7 +4,6 @@ import mock
 
 from kalliope.core.Models.settings.Player import Player
 from kalliope.core.Models.Signal import Signal
-from kalliope.core.Models.settings.RecognitionOptions import RecognitionOptions
 from kalliope.core.Models.settings.Tts import Tts
 
 from kalliope.core.Models.settings.Trigger import Trigger
@@ -244,8 +243,6 @@ class TestModels(unittest.TestCase):
                                 active=True,
                                 port=5000, allowed_cors_origin="*")
 
-            recognition_options = RecognitionOptions()
-
             setting1 = Settings(default_tts_name="pico2wav",
                                 default_stt_name="google",
                                 default_trigger_name="swoyboy",
@@ -258,7 +255,6 @@ class TestModels(unittest.TestCase):
                                 cache_path="/tmp/kalliope",
                                 resources=None,
                                 variables={"key1": "val1"},
-                                recognition_options=recognition_options,
                                 options={'deaf': False, 'mute': False})
             setting1.kalliope_version = "0.4.5"
 
@@ -273,7 +269,6 @@ class TestModels(unittest.TestCase):
                                 cache_path="/tmp/kalliope_tmp",
                                 resources=None,
                                 variables={"key1": "val1"},
-                                recognition_options=recognition_options,
                                 options={'deaf': False, 'mute': False})
             setting2.kalliope_version = "0.4.5"
 
@@ -289,7 +284,6 @@ class TestModels(unittest.TestCase):
                                 cache_path="/tmp/kalliope",
                                 resources=None,
                                 variables={"key1": "val1"},
-                                recognition_options=recognition_options,
                                 options={'deaf': False, 'mute': False})
             setting3.kalliope_version = "0.4.5"
 
@@ -317,7 +311,6 @@ class TestModels(unittest.TestCase):
                 'resources': None,
                 'triggers': ['snowboy'],
                 'players': ['mplayer'],
-                'recognition_options': {'energy_threshold': 4000, 'adjust_for_ambient_noise_second': 0},
                 'options': {'deaf': False, 'mute': False}
             }
 

+ 3 - 5
Tests/test_settings_loader.py

@@ -12,7 +12,6 @@ from kalliope.core.Models.settings.Player import Player
 from kalliope.core.Models.settings.RestAPI import RestAPI
 from kalliope.core.Models.settings.Settings import Settings
 from kalliope.core.Models.settings.Stt import Stt
-from kalliope.core.Models.settings.RecognitionOptions import RecognitionOptions
 from kalliope.core.Models.settings.Trigger import Trigger
 from kalliope.core.Models.settings.Tts import Tts
 
@@ -52,7 +51,7 @@ class TestSettingLoader(unittest.TestCase):
                 {'voxygen': {'voice': 'Agnes', 'cache': True}}
                 ],
             'var_files': ["../Tests/settings/variables.yml"],
-            'options': {'deaf': True, 'mute': False},
+            'options': {'energy_threshold': 3000, 'deaf': True, 'mute': False},
             'hooks': {'on_waiting_for_trigger': 'test',
                       'on_stop_listening': None,
                       'on_start_listening': None,
@@ -126,9 +125,8 @@ class TestSettingLoader(unittest.TestCase):
             "test_number": 60,
             "test": "kalliope"
         }
-        settings_object.options = Options(deaf=True, mute=False)
+        settings_object.options = Options(energy_threshold=3000, deaf=True, mute=False)
         settings_object.machine = platform.machine()
-        settings_object.recognition_options = RecognitionOptions()
         settings_object.hooks = {'on_waiting_for_trigger': 'test',
                                  'on_stop_listening': None,
                                  'on_start_listening': None,
@@ -225,7 +223,7 @@ class TestSettingLoader(unittest.TestCase):
                          sl._get_variables(self.settings_dict))
 
     def test_get_options(self):
-        expected_result = Options(deaf=True, mute=False)
+        expected_result = Options(energy_threshold=3000, deaf=True, mute=False)
         sl = SettingLoader(file_path=self.settings_file_to_test)
         self.assertEqual(expected_result,
                          sl._get_options(self.settings_dict))

+ 13 - 33
kalliope/core/ConfigurationManager/SettingLoader.py

@@ -3,7 +3,6 @@ import os
 from six import with_metaclass
 
 from kalliope.core.Models.settings.Options import Options
-from kalliope.core.Models.settings.RecognitionOptions import RecognitionOptions
 from .YAMLLoader import YAMLLoader
 from kalliope.core.Models.settings.Resources import Resources
 from kalliope.core.Utils.Utils import Utils
@@ -112,7 +111,6 @@ class SettingLoader(with_metaclass(Singleton, object)):
         cache_path = self._get_cache_path(settings)
         resources = self._get_resources(settings)
         variables = self._get_variables(settings)
-        recognition_options = self._get_recognition_options(settings)
         options = self._get_options(settings)
         hooks = self._get_hooks(settings)
 
@@ -129,7 +127,6 @@ class SettingLoader(with_metaclass(Singleton, object)):
         setting_object.cache_path = cache_path
         setting_object.resources = resources
         setting_object.variables = variables
-        setting_object.recognition_options = recognition_options
         setting_object.options = options
         setting_object.hooks = hooks
 
@@ -605,33 +602,6 @@ class SettingLoader(with_metaclass(Singleton, object)):
             # User does not provide this settings
             return dict()
 
-    @staticmethod
-    def _get_recognition_options(settings):
-        """
-        return the value of stt_threshold
-        :param settings: The loaded YAML settings file
-        :return: integer or 1200 by default if not set
-        """
-        recognition_options = RecognitionOptions()
-
-        try:
-            recognition_options_dict = settings["recognition_options"]
-
-            if "energy_threshold" in recognition_options_dict:
-                recognition_options.energy_threshold = recognition_options_dict["energy_threshold"]
-                logger.debug("[SettingsLoader] energy_threshold set to %s" % recognition_options.energy_threshold)
-            if "adjust_for_ambient_noise_second" in recognition_options_dict:
-                recognition_options.adjust_for_ambient_noise_second = recognition_options_dict["adjust_for_ambient_noise_second"]
-                logger.debug("[SettingsLoader] adjust_for_ambient_noise_second set to %s"
-                             % recognition_options.adjust_for_ambient_noise_second)
-            return recognition_options
-
-        except KeyError:
-            logger.debug("[SettingsLoader] no recognition_options defined. Set to default")
-
-        logger.debug("[SettingsLoader] recognition_options: %s" % str(recognition_options))
-        return recognition_options
-
     @staticmethod
     def _get_options(settings):
         """
@@ -639,6 +609,8 @@ class SettingLoader(with_metaclass(Singleton, object)):
         if not set, default values are :
         deaf: False
         mute: False
+        energy_threshold = 4000
+        adjust_for_ambient_noise_second = 0
 
         :param settings: The YAML settings file
         :type settings: dict
@@ -648,6 +620,8 @@ class SettingLoader(with_metaclass(Singleton, object)):
 
         deaf = False
         mute = False
+        energy_threshold = 4000
+        adjust_for_ambient_noise_second = 0
 
         try:
             options = settings["options"]
@@ -655,12 +629,18 @@ class SettingLoader(with_metaclass(Singleton, object)):
                 deaf = options['deaf']
             if options['mute']:
                 mute = options['mute']
+            if options["energy_threshold"]:
+                energy_threshold = options["energy_threshold"]
+            if options["adjust_for_ambient_noise_second"]:
+                adjust_for_ambient_noise_second = options["adjust_for_ambient_noise_second"]
         except KeyError:
             pass
 
-        options = Options(deaf=deaf, mute=mute)
-
-        logger.debug("Options: %s" % options)
+        options = Options(energy_threshold=energy_threshold,
+                          adjust_for_ambient_noise_second=adjust_for_ambient_noise_second,
+                          deaf=deaf,
+                          mute=mute)
+        logger.debug("[SettingsLoader] Options: %s" % options)
         return options
 
     @staticmethod

+ 5 - 1
kalliope/core/Models/settings/Options.py

@@ -8,10 +8,12 @@ class Options(SettingsEntry):
     .. note:: must be defined in the settings.yml
     """
 
-    def __init__(self, deaf=None, mute=None):
+    def __init__(self, energy_threshold=4000, adjust_for_ambient_noise_second=0, deaf=None, mute=None):
         super(Options, self).__init__(name="Options")
         self.deaf = deaf
         self.mute = mute
+        self.energy_threshold = energy_threshold
+        self.adjust_for_ambient_noise_second = adjust_for_ambient_noise_second
 
     def __str__(self):
         return str(self.serialize())
@@ -19,6 +21,8 @@ class Options(SettingsEntry):
     def serialize(self):
         return {
             'name': self.name,
+            'energy_threshold': self.energy_threshold,
+            'adjust_for_ambient_noise_second': self.adjust_for_ambient_noise_second,
             'deaf': self.deaf,
             'mute': self.mute
         }

+ 0 - 31
kalliope/core/Models/settings/RecognitionOptions.py

@@ -1,31 +0,0 @@
-from kalliope.core.Models.settings.SettingsEntry import SettingsEntry
-
-
-class RecognitionOptions(SettingsEntry):
-    """
-    This Class is representing a Speech To Text (STT) Recognition elements with name and parameters
-
-    .. note:: must be defined in the settings.yml
-    """
-
-    def __init__(self, energy_threshold=4000, adjust_for_ambient_noise_second=0):
-        super(RecognitionOptions, self).__init__("RecognitionOptions")
-        self.energy_threshold = energy_threshold
-        self.adjust_for_ambient_noise_second = adjust_for_ambient_noise_second
-
-    def __str__(self):
-        return str(self.serialize())
-
-    def serialize(self):
-        return {
-            'energy_threshold': self.energy_threshold,
-            'adjust_for_ambient_noise_second': self.adjust_for_ambient_noise_second
-        }
-
-    def __eq__(self, other):
-        """
-        This is used to compare 2 objects
-        :param other:
-        :return:
-        """
-        return self.__dict__ == other.__dict__

+ 0 - 3
kalliope/core/Models/settings/Settings.py

@@ -21,7 +21,6 @@ class Settings(object):
                  cache_path=None,
                  resources=None,
                  variables=None,
-                 recognition_options=None,
                  options=None,
                  hooks=None):
 
@@ -39,7 +38,6 @@ class Settings(object):
         self.variables = variables
         self.machine = platform.machine()   # can be x86_64 or armv7l
         self.kalliope_version = current_kalliope_version
-        self.recognition_options = recognition_options
         self.options = options
         self.hooks = hooks
 
@@ -66,7 +64,6 @@ class Settings(object):
             'variables': self.variables,
             'machine': self.machine,
             'kalliope_version': self.kalliope_version,
-            'recognition_options': self.recognition_options.serialize() if self.recognition_options is not None else None,
             'options': self.options,
             'hooks': self.hooks
         }

+ 2 - 5
kalliope/settings.yml

@@ -25,11 +25,6 @@ triggers:
 # This is the STT that will be used by default
 default_speech_to_text: "google"
 
-# Speech to text options
-#recognition_options:
-#  energy_threshold: 4000
-#  adjust_for_ambient_noise_second: 1
-
 # Speech to Text engines configuration
 # Available engine are:
 # - google (via SpeechRecognition)
@@ -165,5 +160,7 @@ rest_api:
 # Options
 # -------------
 options:
+  energy_threshold: 4000                 # Speech to text option
+  adjust_for_ambient_noise_second: 1     # Speech to text option
   deaf: False
   mute: False

+ 6 - 6
kalliope/stt/Utils.py

@@ -31,21 +31,21 @@ class SpeechRecognition(Thread):
         if audio_file is None:
             # audio file not set, we need to capture a sample from the microphone
             with self.microphone as source:
-                if self.settings.recognition_options.adjust_for_ambient_noise_second > 0:
+                if self.settings.options.adjust_for_ambient_noise_second > 0:
                     # threshold is calculated from capturing ambient sound
                     logger.debug("[SpeechRecognition] threshold calculated by "
                                  "capturing ambient noise during %s seconds" %
-                                 self.settings.recognition_options.adjust_for_ambient_noise_second)
+                                 self.settings.options.adjust_for_ambient_noise_second)
                     Utils.print_info("[SpeechRecognition] capturing ambient sound during %s seconds" %
-                                     self.settings.recognition_options.adjust_for_ambient_noise_second)
+                                     self.settings.options.adjust_for_ambient_noise_second)
                     self.recognizer.adjust_for_ambient_noise(source,
                                                              duration=self.settings.
-                                                             recognition_options.adjust_for_ambient_noise_second)
+                                                             options.adjust_for_ambient_noise_second)
                 else:
                     # threshold is defined manually
                     logger.debug("[SpeechRecognition] threshold defined by settings: %s" %
-                                 self.settings.recognition_options.energy_threshold)
-                    self.recognizer.energy_threshold = self.settings.recognition_options.energy_threshold
+                                 self.settings.options.energy_threshold)
+                    self.recognizer.energy_threshold = self.settings.options.energy_threshold
 
                 Utils.print_info("Threshold set to: %s" % self.recognizer.energy_threshold)
         else: