Browse Source

add a dedicated logger

nico 8 years ago
parent
commit
4544a1e728

+ 6 - 3
core/AudioPlayer.py

@@ -3,6 +3,9 @@ import pygame
 
 from core.FileManager import FileManager
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class AudioPlayer:
     PLAYER_MP3 = "MP3"
@@ -32,10 +35,10 @@ class AudioPlayer:
     def play_audio(self, music_file):
         try:
             self._init_player_audio(music_file)
-            logging.debug("Music file %s loaded!", music_file)
+            logger.debug("Music file %s loaded!", music_file)
         except pygame.error:
             FileManager.remove_file(music_file)
-            logging.error("File %s not found! (%s)", music_file, pygame.get_error())
+            logger.error("File %s not found! (%s)", music_file, pygame.get_error())
             return
 
         self._start_player_audio()
@@ -46,7 +49,7 @@ class AudioPlayer:
 
     @staticmethod
     def _start_player_audio():
-        logging.info("Starting pygame audio player")
+        logger.info("Starting pygame audio player")
         pygame.mixer.music.play()
         clock = pygame.time.Clock()
         while pygame.mixer.music.get_busy():

+ 3 - 1
core/Cache.py

@@ -10,6 +10,8 @@ DEFAULT_CACHE_EXTENSION = "tts"
 DEFAULT_LANGUAGE = "default"
 DEFAULT_VOICE = "default"
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
 
 class Cache:
 
@@ -27,7 +29,7 @@ class Cache:
         cache_directory = os.path.join(self._cache_path, self._module_name, language)
         file_path = os.path.join(cache_directory, filename)
         FileManager.create_directory(cache_directory)
-        logging.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
+        logger.debug("Cache directory %s exists and File path for audio is: %s", cache_directory, file_path)
         return file_path
 
     @staticmethod

+ 6 - 4
core/ConfigurationManager/BrainLoader.py

@@ -10,6 +10,9 @@ from core.Models.Neuron import Neuron
 from core.Models.Order import Order
 from core.Models.Synapse import Synapse
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class BrainLoader(YAMLLoader):
 
@@ -36,9 +39,9 @@ class BrainLoader(YAMLLoader):
         # create list of Synapse
         synapses = list()
         for synapes_dict in dict_brain:
-            # print synapes_dict
+            # print synapses_dict
             if ConfigurationChecker().check_synape_dict(synapes_dict):
-                # print "synapes_dict ok"
+                # print "synapses_dict ok"
                 name = synapes_dict["name"]
                 neurons = self._get_neurons(synapes_dict["neurons"])
                 signals = self._get_signals(synapes_dict["signals"])
@@ -114,8 +117,7 @@ class BrainLoader(YAMLLoader):
         # get parent dir. Now we are in /an/unknown/path/jarvis
         parent_dir = os.path.normpath(cur_script_directory + os.sep + os.pardir + os.sep + os.pardir)
         brain_path = parent_dir + os.sep + "brain.yml"
-        print brain_path
-        logging.debug("Real brain.yml path: %s" % brain_path)
+        logger.debug("Real brain.yml path: %s" % brain_path)
         if os.path.isfile(brain_path):
             return brain_path
         raise IOError("Default brain.yml file not found")

+ 9 - 6
core/ConfigurationManager/ConfigurationManager.py

@@ -2,6 +2,9 @@ from BrainLoader import BrainLoader
 from SettingLoader import SettingLoader
 import logging
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class DefaultSpeechToTextNotFound(Exception):
     pass
@@ -40,7 +43,7 @@ class ConfigurationManager:
             default_speech_to_text = settings["default_speech_to_text"]
             if default_speech_to_text is None:
                 raise DefaultSpeechNull("Attribute default_speech_to_text is null")
-            logging.info("Default STT: %s" % default_speech_to_text)
+            logger.info("Default STT: %s" % default_speech_to_text)
             return default_speech_to_text
         except KeyError:
             raise DefaultSpeechToTextNotFound("Attribute default_speech_to_text not found in settings")
@@ -53,7 +56,7 @@ class ConfigurationManager:
             default_text_to_speech = settings["default_text_to_speech"]
             if default_text_to_speech is None:
                 raise DefaultSpeechNull("Attribute default_text_to_speech is null")
-            logging.info("Default TTS: %s" % default_text_to_speech)
+            logger.info("Default TTS: %s" % default_text_to_speech)
             return default_text_to_speech
         except KeyError:
             raise DefaultSpeechToTextNotFound("Attribute default_text_to_speech not found in settings")
@@ -89,11 +92,11 @@ class ConfigurationManager:
         except KeyError:
             raise NoSpeechToTextConfiguration("No speech_to_text in settings")
 
-        logging.debug("Settings file content: %s" % speechs_to_text)
+        logger.debug("Settings file content: %s" % speechs_to_text)
         # get args
         args = find(speechs_to_text, default_stt_plugin_name)
 
-        logging.debug("Args for %s STT: %s" % (default_stt_plugin_name, args))
+        logger.debug("Args for %s STT: %s" % (default_stt_plugin_name, args))
 
         return args
 
@@ -128,10 +131,10 @@ class ConfigurationManager:
         except KeyError:
             raise NoSpeechToTextConfiguration("No text_to_speech in settings")
 
-        logging.debug("Settings file content: %s" % texts_to_speech)
+        logger.debug("Settings file content: %s" % texts_to_speech)
         # get args
         args = find(texts_to_speech, tts_name)
-        logging.debug("Args for %s TTS: %s" % (tts_name, args))
+        logger.debug("Args for %s TTS: %s" % (tts_name, args))
         # print args
         return args
 

+ 9 - 6
core/ConfigurationManager/SettingLoader.py

@@ -3,6 +3,9 @@ import logging
 
 FILE_NAME = "settings.yml"
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class DefaultSpeechToTextNotFound(Exception):
     pass
@@ -35,7 +38,7 @@ class SettingLoader(YAMLLoader):
             default_speech_to_text = settings["default_speech_to_text"]
             if default_speech_to_text is None:
                 raise DefaultSpeechNull("Attribute default_speech_to_text is null")
-            logging.info("Default STT: %s" % default_speech_to_text)
+            logger.info("Default STT: %s" % default_speech_to_text)
             return default_speech_to_text
         except KeyError:
             raise DefaultSpeechToTextNotFound("Attribute default_speech_to_text not found in settings")
@@ -47,7 +50,7 @@ class SettingLoader(YAMLLoader):
             default_text_to_speech = settings["default_text_to_speech"]
             if default_text_to_speech is None:
                 raise DefaultSpeechNull("Attribute default_text_to_speech is null")
-            logging.info("Default TTS: %s" % default_text_to_speech)
+            logger.info("Default TTS: %s" % default_text_to_speech)
             return default_text_to_speech
         except KeyError:
             raise DefaultSpeechToTextNotFound("Attribute default_text_to_speech not found in settings")
@@ -82,11 +85,11 @@ class SettingLoader(YAMLLoader):
         except KeyError:
             raise NoSpeechToTextConfiguration("No speech_to_text in settings")
 
-        logging.debug("Settings file content: %s" % speechs_to_text)
+        logger.debug("Settings file content: %s" % speechs_to_text)
         # get args
         args = find(speechs_to_text, default_stt_plugin_name)
 
-        logging.debug("Args for %s STT: %s" % (default_stt_plugin_name, args))
+        logger.debug("Args for %s STT: %s" % (default_stt_plugin_name, args))
 
         return args
 
@@ -120,9 +123,9 @@ class SettingLoader(YAMLLoader):
         except KeyError:
             raise NoSpeechToTextConfiguration("No text_to_speech in settings")
 
-        logging.debug("Settings file content: %s" % texts_to_speech)
+        logger.debug("Settings file content: %s" % texts_to_speech)
         # get args
         args = find(texts_to_speech, tts_name)
-        logging.debug("Args for %s TTS: %s" % (tts_name, args))
+        logger.debug("Args for %s TTS: %s" % (tts_name, args))
         # print args
         return args

+ 5 - 2
core/CrontabManager.py

@@ -6,6 +6,9 @@ from core.ConfigurationManager.BrainLoader import BrainLoader
 from core.Models import Event
 import logging
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class InvalidCrontabPeriod(Exception):
     pass
@@ -60,7 +63,7 @@ class CrontabManager:
         """
         iter = self.my_user_cron.find_comment(CRONTAB_COMMENT)
         for job in iter:
-            logging.debug("remove job %s from crontab" % job)
+            logger.debug("remove job %s from crontab" % job)
             self.my_user_cron.remove(job)
         # write the file
         self.my_user_cron.write()
@@ -87,7 +90,7 @@ class CrontabManager:
         # we add the jarvis.py file name
         real_jarvis_entry_point_path = parent_dir + os.sep + JARVIS_ENTRY_POINT_SCRIPT
         # We test that the file exist before return it
-        logging.debug("Real jarvis.py path: %s" % real_jarvis_entry_point_path)
+        logger.debug("Real jarvis.py path: %s" % real_jarvis_entry_point_path)
         if os.path.isfile(real_jarvis_entry_point_path):
             crontab_cmd = "python %s start --brain-file %s --run-synapse " % (real_jarvis_entry_point_path,
                                                                               self.brain.brain_file)

+ 6 - 3
core/NeuronModule.py

@@ -6,6 +6,9 @@ from jinja2 import Template
 
 from core.ConfigurationManager import SettingLoader
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class NoTemplateException(Exception):
     pass
@@ -36,7 +39,7 @@ class NeuronModule(object):
         """
         # get the child who called the class
         child_name = self.__class__.__name__
-        logging.debug("NeuronModule called from class %s with parameters: %s" % (child_name, kwargs))
+        logger.debug("NeuronModule called from class %s with parameters: %s" % (child_name, kwargs))
 
         # check if the user has overrider the TTS
         tts = kwargs.get('tts', None)
@@ -65,7 +68,7 @@ class NeuronModule(object):
         :param message: Can be a String or a dict
         :return:
         """
-        logging.debug("NeuronModule Say() called with message: %s" % message)
+        logger.debug("NeuronModule Say() called with message: %s" % message)
 
         tts_message = None
 
@@ -137,7 +140,7 @@ class NeuronModule(object):
     def _get_tts_instance(tts_name):
         # capitalise for loading module name
         tts = tts_name.capitalize()
-        logging.info("Import TTS module named %s " % tts)
+        logger.debug("Import TTS module named %s " % tts)
         mod = __import__('tts', fromlist=[str(tts)])
         try:
             klass = getattr(mod, tts)

+ 5 - 2
core/OrderAnalyser.py

@@ -6,6 +6,9 @@ from core.Models import Order
 from core.NeuroneLauncher import NeuroneLauncher
 import logging
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class OrderAnalyser:
     def __init__(self, order, main_controller=None, brain_file=None):
@@ -21,14 +24,14 @@ class OrderAnalyser:
             self.brain = BrainLoader().get_brain()
         else:
             self.brain = BrainLoader(brain_file).get_brain()
-        logging.info("Receiver order: %s" % self.order)
+            logger.info("Receiver order: %s" % self.order)
 
     def start(self):
         for synapse in self.brain.synapes:
             for signal in synapse.signals:
                 if type(signal) == Order:
                     if self._spelt_order_match_brain_order(signal.sentence):
-                        print "Order found! Run neurons: %s" % synapse.neurons
+                        logger.debug("Order found! Run neurons: %s" % synapse.neurons)
                         for neuron in synapse.neurons:
                             NeuroneLauncher.start_neurone(neuron)
 

+ 5 - 2
core/OrderListener.py

@@ -1,6 +1,9 @@
 import logging
 from core import ConfigurationManager
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class OrderListener:
 
@@ -31,11 +34,11 @@ class OrderListener:
     def _run_stt_plugin(self, stt_plugin, parameters=None):
         """
         Dynamic loading of a STT module
-        :param plugin: Module name to load
+        :param stt_plugin: Module name to load
         :param parameters: Parameter of the module
         :return:
         """
-        logging.debug("Running STT %s with parameter %s" % (stt_plugin, parameters))
+        logger.debug("Running STT %s with parameter %s" % (stt_plugin, parameters))
         mod = __import__('stt', fromlist=[stt_plugin])
 
         klass = getattr(mod, stt_plugin)

+ 35 - 1
jarvis.py

@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+# -*- coding: utf-8 -*-
 import argparse
 import logging
 
@@ -11,6 +12,9 @@ import sys
 
 from core.SynapseLauncher import SynapseLauncher
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 def signal_handler(signal, frame):
         print "\n"
@@ -29,14 +33,20 @@ def main():
     parser.add_argument("action", help="[start|gui|load-events]")
     parser.add_argument("--run-synapse", help="Name of a synapse to load surrounded by quote")
     parser.add_argument("--brain-file", help="Full path of a brain file")
+    parser.add_argument("--debug", action='store_true', help="Show debug output")
 
     # parse arguments from script parameters
     args = parser.parse_args()
-    logging.debug("jarvis args: %s" % args)
+
     if len(sys.argv[1:]) == 0:
         parser.print_usage()
         sys.exit(1)
 
+    # check if we want debug
+    configure_logging(debug=args.debug)
+
+    logger.debug("jarvis args: %s" % args)
+
     # by default, no brain file is set. Use the default one: brain.yml in the root path
     brain_file = None
 
@@ -71,5 +81,29 @@ def main():
         crontab_manager.load_events_in_crontab()
         Utils.print_success("Events loaded in crontab")
 
+
+def configure_logging(debug=None):
+    """
+    Prepare log folder in current home directory
+    :param debug: If true, set the lof level to debug
+    :return:
+    """
+    logger = logging.getLogger("jarvis")
+    logger.propagate = False
+    ch = logging.StreamHandler()
+    ch.setLevel(logging.DEBUG)
+    formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
+    ch.setFormatter(formatter)
+
+    # add the handlers to logger
+    logger.addHandler(ch)
+
+    if debug:
+        logger.setLevel(logging.DEBUG)
+    else:
+        logger.setLevel(logging.INFO)
+
+    logger.debug("Logger ready")
+
 if __name__ == '__main__':
     main()

+ 2 - 2
test.py

@@ -5,8 +5,8 @@ from core.CrontabManager import CrontabManager
 from core.OrderAnalyser import OrderAnalyser
 
 import logging
-logger = logging.getLogger()
-logger.setLevel(logging.DEBUG)
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
 
 
 # oa = OrderAnalyser("wake up", brain_file="/home/nico/Documents/jarvis/test.yml")

+ 13 - 8
tts/acapela/acapela.py

@@ -1,11 +1,14 @@
 import sha
 import os
 import shutil
-
+import sys
 import pygame
 import requests
 import logging
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 VOXYGEN_LANGUAGES = {
     "fr" : {"electra":"Electra","emma":"Emma","becool":"Becool","agnes":"Agnes","loic":"Loic","fabienne":"Fabienne","helene":"Helene","marion":"Marion","matteo":"Matteo","melodine":"Melodine","mendoo":"Mendoo","michel":"Michel","moussa":"Moussa","philippe":"Philippe","sorciere":"Sorciere"},
     "ar" : {"adel":"Adel"},
@@ -18,6 +21,7 @@ VOXYGEN_LANGUAGES = {
 
 CACHE_PATH = "/tmp/jarvis/tts/acapela/"
 
+
 def say(words=None, voice=None, language=None, cache=None):
 
     if not os.path.exists(CACHE_PATH):
@@ -34,6 +38,7 @@ def say(words=None, voice=None, language=None, cache=None):
     if not cache:
         os.remove(tempfile)
 
+
 def get_audio(voice, text, filepath,cache):
     if not cache or not os.path.exists(filepath):
         payload ={
@@ -43,39 +48,39 @@ def get_audio(voice, text, filepath,cache):
         }
 
         r = requests.get("http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2_fr.php", params=payload, stream=True)
-        logging.debug("Trying to get url: %s response code: %s",r.url,r.status_code)
+        logger.debug("Trying to get url: %s response code: %s",r.url,r.status_code)
 
         if r.status_code==200:
             with open(os.path.abspath(filepath), "wb") as sound_file:
                 sound_file.write(r.content)
 
+
 def play_audio(music_file, volume=0.8):
     pygame.mixer.init(16000, -16, 1, 2048)
     pygame.mixer.music.set_volume(volume)
     clock = pygame.time.Clock()
     try:
         pygame.mixer.music.load(music_file)
-        logging.debug("Music file {} loaded!".format(music_file))
+        logger.debug("Music file {} loaded!".format(music_file))
     except pygame.error:
         os.remove(music_file)
-        logging.debug("File {} not found! ({})".format(music_file, pygame.get_error()))
+        logger.debug("File {} not found! ({})".format(music_file, pygame.get_error()))
         return
     pygame.mixer.music.play()
     while pygame.mixer.music.get_busy():
         clock.tick(10)
 
+
 def get_voice(voice=None, language=None):
     if language in VOXYGEN_LANGUAGES:
         if voice in VOXYGEN_LANGUAGES[language]:
             return VOXYGEN_LANGUAGES[language][voice]
 
-    logging.debug("Cannot find language maching language: %s voice: %s",language,voice)
+    logger.debug("Cannot find language maching language: %s voice: %s",language,voice)
     return ""
 
+
 def wipe_cache():
     shutil.rmtree(CACHE_PATH)
 
 
-import sys
-logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
-say("Bonjour monsieur",get_voice("loic","fr"),None,True)

+ 6 - 4
tts/pico2wave/pico2wave.py

@@ -1,6 +1,10 @@
 import subprocess
 from tts import TTS
-import logging, sys
+import logging
+import sys
+
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
 
 
 class Pico2wave(TTS):
@@ -27,12 +31,10 @@ class Pico2wave(TTS):
         if language in self.PICO2WAVE_LANGUAGES:
             return self.PICO2WAVE_LANGUAGES[language]
 
-        logging.warn("Cannot find language matching language:  %s replace by default voice: %s", language, self.PICO2WAVE_LANGUAGES_DEFAULT)
+        logger.warn("Cannot find language matching language:  %s replace by default voice: %s", language, self.PICO2WAVE_LANGUAGES_DEFAULT)
         return self.PICO2WAVE_LANGUAGES_DEFAULT
 
     @staticmethod
     def get_audio(words, language, file_path):
         subprocess.check_output(["/usr/bin/pico2wave", "-l=%s" % language, "-w=%s" % file_path, words], stderr=sys.stderr)
 
-
-# logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

+ 8 - 5
tts/voxygen/voxygen.py

@@ -8,6 +8,9 @@ from core import AudioPlayer
 from core import FileManager
 from tts import TTS
 
+logging.basicConfig()
+logger = logging.getLogger("jarvis")
+
 
 class Voxygen(TTS):
     VOXYGEN_LANGUAGES = dict(
@@ -43,7 +46,7 @@ class Voxygen(TTS):
         if language in self.VOXYGEN_LANGUAGES and voice in self.VOXYGEN_LANGUAGES[language]:
             return self.VOXYGEN_LANGUAGES[language][voice]
 
-        logging.warn("Cannot find language matching language: %s voice: %s replace by default voice: %s", language, voice, self.VOXYGEN_VOICE_DEFAULT)
+        logger.warn("Cannot find language matching language: %s voice: %s replace by default voice: %s", language, voice, self.VOXYGEN_VOICE_DEFAULT)
         return self.VOXYGEN_VOICE_DEFAULT
 
     def get_audio(self, voice, words, file_path, cache):
@@ -57,7 +60,7 @@ class Voxygen(TTS):
             r = requests.get(self.VOXYGEN_URL, params=payload, stream=True, timeout=self.VOXYGEN_TIMEOUT_SEC)
 
             content_type = r.headers['Content-Type']
-            logging.debug("Trying to get url: %s response code: %s and content-type: %s", r.url, r.status_code, content_type)
+            logger.debug("Trying to get url: %s response code: %s and content-type: %s", r.url, r.status_code, content_type)
 
             try:
                 if r.status_code == requests.codes.ok and content_type == self.VOXYGEN_CONTENT_TYPE:
@@ -65,10 +68,10 @@ class Voxygen(TTS):
                 else:
                     return False
             except IOError as e:
-                logging.error("I/O error(%s): %s", e.errno, e.strerror)
+                logger.error("I/O error(%s): %s", e.errno, e.strerror)
             except ValueError:
-                logging.error("Could not convert data to an integer.")
+                logger.error("Could not convert data to an integer.")
             except:
-                logging.error("Unexpected error: %s", sys.exc_info()[0])
+                logger.error("Unexpected error: %s", sys.exc_info()[0])
         else:
             return True