Quellcode durchsuchen

Improved config/argument behaviour

The configuration file is now properly overridden by argument parsing.
This was accomplished by loading the config file, then treating the
specified options as a namespace for the ArgumentParser.  This makes
things from the config file get overridden iff they were specified on
the command line (not simply from defaults set in the ArgumentParser).
Clara Hobbs vor 8 Jahren
Ursprung
Commit
87c0a1bfe9
3 geänderte Dateien mit 67 neuen und 56 gelöschten Zeilen
  1. 6
    49
      blather.py
  2. 56
    0
      config.py
  3. 5
    7
      recognizer.py

+ 6
- 49
blather.py Datei anzeigen

11
 import hashlib
11
 import hashlib
12
 import os.path
12
 import os.path
13
 import subprocess
13
 import subprocess
14
-from argparse import ArgumentParser
15
 from gi.repository import GObject, GLib
14
 from gi.repository import GObject, GLib
16
 import json
15
 import json
17
 
16
 
18
 from recognizer import Recognizer
17
 from recognizer import Recognizer
18
+from config import Config
19
 
19
 
20
 # Where are the files?
20
 # Where are the files?
21
 conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
21
 conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
24
 command_file = os.path.join(conf_dir, "commands.conf")
24
 command_file = os.path.join(conf_dir, "commands.conf")
25
 strings_file = os.path.join(conf_dir, "sentences.corpus")
25
 strings_file = os.path.join(conf_dir, "sentences.corpus")
26
 history_file = os.path.join(conf_dir, "blather.history")
26
 history_file = os.path.join(conf_dir, "blather.history")
27
-opt_file = os.path.join(conf_dir, "options.json")
28
 hash_file = os.path.join(conf_dir, "hash.json")
27
 hash_file = os.path.join(conf_dir, "hash.json")
29
 lang_file = os.path.join(lang_dir, 'lm')
28
 lang_file = os.path.join(lang_dir, 'lm')
30
 dic_file = os.path.join(lang_dir, 'dic')
29
 dic_file = os.path.join(lang_dir, 'dic')
34
 
33
 
35
 class Blather:
34
 class Blather:
36
 
35
 
37
-    def __init__(self, opts):
36
+    def __init__(self):
38
         self.ui = None
37
         self.ui = None
39
         self.options = {}
38
         self.options = {}
40
         ui_continuous_listen = False
39
         ui_continuous_listen = False
46
         self.read_commands()
45
         self.read_commands()
47
 
46
 
48
         # Load the options file
47
         # Load the options file
49
-        self.load_options()
50
-
51
-        print(opts)
52
-        # Merge the options with the ones provided by command-line arguments
53
-        for k, v in vars(opts).items():
54
-            if v is not None:
55
-                self.options[k] = v
48
+        self.config = Config()
49
+        self.options = vars(self.config.options)
56
 
50
 
57
         if self.options['interface'] != None:
51
         if self.options['interface'] != None:
58
             if self.options['interface'] == "g":
52
             if self.options['interface'] == "g":
63
                 print("no GUI defined")
57
                 print("no GUI defined")
64
                 sys.exit()
58
                 sys.exit()
65
 
59
 
66
-            self.ui = UI(args, self.options['continuous'])
60
+            self.ui = UI(self.options, self.options['continuous'])
67
             self.ui.connect("command", self.process_command)
61
             self.ui.connect("command", self.process_command)
68
             # Can we load the icon resource?
62
             # Can we load the icon resource?
69
             icon = self.load_resource("icon.png")
63
             icon = self.load_resource("icon.png")
110
         # Close the strings file
104
         # Close the strings file
111
         strings.close()
105
         strings.close()
112
 
106
 
113
-    def load_options(self):
114
-        """Load options from the options.json file"""
115
-        # Is there an opt file?
116
-        with open(opt_file, 'r') as f:
117
-            self.options = json.load(f)
118
-            print(self.options)
119
-
120
     def log_history(self, text):
107
     def log_history(self, text):
121
         if self.options['history']:
108
         if self.options['history']:
122
             self.history.append(text)
109
             self.history.append(text)
228
 
215
 
229
 
216
 
230
 if __name__ == "__main__":
217
 if __name__ == "__main__":
231
-    parser = ArgumentParser()
232
-    parser.add_argument("-i", "--interface",  type=str, dest="interface",
233
-            action='store',
234
-            help="Interface to use (if any). 'g' for GTK or 'gt' for GTK system tray icon")
235
-
236
-    parser.add_argument("-c", "--continuous",
237
-            action="store_true", dest="continuous", default=False,
238
-            help="starts interface with 'continuous' listen enabled")
239
-
240
-    parser.add_argument("-p", "--pass-words",
241
-            action="store_true", dest="pass_words", default=False,
242
-            help="passes the recognized words as arguments to the shell command")
243
-
244
-    parser.add_argument("-H", "--history", type=int,
245
-            action="store", dest="history",
246
-            help="number of commands to store in history file")
247
-
248
-    parser.add_argument("-m", "--microphone", type=int,
249
-            action="store", dest="microphone", default=None,
250
-            help="Audio input card to use (if other than system default)")
251
-
252
-    parser.add_argument("--valid-sentence-command",  type=str, dest="valid_sentence_command",
253
-            action='store',
254
-            help="command to run when a valid sentence is detected")
255
-
256
-    parser.add_argument("--invalid-sentence-command",  type=str, dest="invalid_sentence_command",
257
-            action='store',
258
-            help="command to run when an invalid sentence is detected")
259
-
260
-    args = parser.parse_args()
261
     # Make our blather object
218
     # Make our blather object
262
-    blather = Blather(args)
219
+    blather = Blather()
263
     # Init gobject threads
220
     # Init gobject threads
264
     GObject.threads_init()
221
     GObject.threads_init()
265
     # We want a main loop
222
     # We want a main loop

+ 56
- 0
config.py Datei anzeigen

1
+# This is part of Kaylee
2
+# -- this code is licensed GPLv3
3
+# Copyright 2013 Jezra
4
+# Copyright 2015 Clayton G. Hobbs
5
+
6
+import json
7
+import os
8
+from argparse import ArgumentParser, Namespace
9
+
10
+from gi.repository import GLib
11
+
12
+class Config:
13
+    conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
14
+                                               "blather"))
15
+    opt_file = os.path.join(conf_dir, "options.json")
16
+
17
+    def __init__(self):
18
+        # Set up the argument parser
19
+        self.parser = ArgumentParser()
20
+        self.parser.add_argument("-i", "--interface", type=str,
21
+                dest="interface", action='store',
22
+                help="Interface to use (if any). 'g' for GTK or 'gt' for GTK" +
23
+                " system tray icon")
24
+
25
+        self.parser.add_argument("-c", "--continuous",
26
+                action="store_true", dest="continuous", default=False,
27
+                help="starts interface with 'continuous' listen enabled")
28
+
29
+        self.parser.add_argument("-p", "--pass-words",
30
+                action="store_true", dest="pass_words", default=False,
31
+                help="passes the recognized words as arguments to the shell" +
32
+                " command")
33
+
34
+        self.parser.add_argument("-H", "--history", type=int,
35
+                action="store", dest="history",
36
+                help="number of commands to store in history file")
37
+
38
+        self.parser.add_argument("-m", "--microphone", type=int,
39
+                action="store", dest="microphone", default=None,
40
+                help="Audio input card to use (if other than system default)")
41
+
42
+        self.parser.add_argument("--valid-sentence-command", type=str,
43
+                dest="valid_sentence_command", action='store',
44
+                help="command to run when a valid sentence is detected")
45
+
46
+        self.parser.add_argument("--invalid-sentence-command", type=str,
47
+                dest="invalid_sentence_command", action='store',
48
+                help="command to run when an invalid sentence is detected")
49
+
50
+        # Read the configuration file
51
+        with open(self.opt_file, 'r') as f:
52
+            self.options = json.load(f)
53
+            self.options = Namespace(**self.options)
54
+
55
+        # Parse command-line arguments, overriding config file as appropriate
56
+        self.args = self.parser.parse_args(namespace=self.options)

+ 5
- 7
recognizer.py Datei anzeigen

3
 # Copyright 2013 Jezra
3
 # Copyright 2013 Jezra
4
 # Copyright 2015 Clayton G. Hobbs
4
 # Copyright 2015 Clayton G. Hobbs
5
 
5
 
6
+import os.path
7
+import sys
8
+
6
 import gi
9
 import gi
7
 gi.require_version('Gst', '1.0')
10
 gi.require_version('Gst', '1.0')
8
 from gi.repository import GObject, Gst
11
 from gi.repository import GObject, Gst
9
 GObject.threads_init()
12
 GObject.threads_init()
10
 Gst.init(None)
13
 Gst.init(None)
11
-import os.path
12
-import sys
13
-
14
-# Define some global variables
15
-this_dir = os.path.dirname(os.path.abspath(__file__))
16
 
14
 
17
 
15
 
18
 class Recognizer(GObject.GObject):
16
 class Recognizer(GObject.GObject):
20
         'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
18
         'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
21
     }
19
     }
22
 
20
 
23
-    def __init__(self, language_file, dictionary_file, src = None):
21
+    def __init__(self, language_file, dictionary_file, src=None):
24
         GObject.GObject.__init__(self)
22
         GObject.GObject.__init__(self)
25
         self.commands = {}
23
         self.commands = {}
26
         if src:
24
         if src:
41
         bus.add_signal_watch()
39
         bus.add_signal_watch()
42
 
40
 
43
         # Get the Auto Speech Recognition piece
41
         # Get the Auto Speech Recognition piece
44
-        asr=self.pipeline.get_by_name('asr')
42
+        asr = self.pipeline.get_by_name('asr')
45
         bus.connect('message::element', self.result)
43
         bus.connect('message::element', self.result)
46
         asr.set_property('lm', language_file)
44
         asr.set_property('lm', language_file)
47
         asr.set_property('dict', dictionary_file)
45
         asr.set_property('dict', dictionary_file)

Laden…
Abbrechen
Speichern