Browse Source

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 8 years ago
parent
commit
87c0a1bfe9
3 changed files with 67 additions and 56 deletions
  1. 6
    49
      blather.py
  2. 56
    0
      config.py
  3. 5
    7
      recognizer.py

+ 6
- 49
blather.py View File

@@ -11,11 +11,11 @@ import signal
11 11
 import hashlib
12 12
 import os.path
13 13
 import subprocess
14
-from argparse import ArgumentParser
15 14
 from gi.repository import GObject, GLib
16 15
 import json
17 16
 
18 17
 from recognizer import Recognizer
18
+from config import Config
19 19
 
20 20
 # Where are the files?
21 21
 conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
@@ -24,7 +24,6 @@ lang_dir = os.path.join(conf_dir, "language")
24 24
 command_file = os.path.join(conf_dir, "commands.conf")
25 25
 strings_file = os.path.join(conf_dir, "sentences.corpus")
26 26
 history_file = os.path.join(conf_dir, "blather.history")
27
-opt_file = os.path.join(conf_dir, "options.json")
28 27
 hash_file = os.path.join(conf_dir, "hash.json")
29 28
 lang_file = os.path.join(lang_dir, 'lm')
30 29
 dic_file = os.path.join(lang_dir, 'dic')
@@ -34,7 +33,7 @@ if not os.path.exists(lang_dir):
34 33
 
35 34
 class Blather:
36 35
 
37
-    def __init__(self, opts):
36
+    def __init__(self):
38 37
         self.ui = None
39 38
         self.options = {}
40 39
         ui_continuous_listen = False
@@ -46,13 +45,8 @@ class Blather:
46 45
         self.read_commands()
47 46
 
48 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 51
         if self.options['interface'] != None:
58 52
             if self.options['interface'] == "g":
@@ -63,7 +57,7 @@ class Blather:
63 57
                 print("no GUI defined")
64 58
                 sys.exit()
65 59
 
66
-            self.ui = UI(args, self.options['continuous'])
60
+            self.ui = UI(self.options, self.options['continuous'])
67 61
             self.ui.connect("command", self.process_command)
68 62
             # Can we load the icon resource?
69 63
             icon = self.load_resource("icon.png")
@@ -110,13 +104,6 @@ class Blather:
110 104
         # Close the strings file
111 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 107
     def log_history(self, text):
121 108
         if self.options['history']:
122 109
             self.history.append(text)
@@ -228,38 +215,8 @@ class Blather:
228 215
 
229 216
 
230 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 218
     # Make our blather object
262
-    blather = Blather(args)
219
+    blather = Blather()
263 220
     # Init gobject threads
264 221
     GObject.threads_init()
265 222
     # We want a main loop

+ 56
- 0
config.py View File

@@ -0,0 +1,56 @@
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 View File

@@ -3,16 +3,14 @@
3 3
 # Copyright 2013 Jezra
4 4
 # Copyright 2015 Clayton G. Hobbs
5 5
 
6
+import os.path
7
+import sys
8
+
6 9
 import gi
7 10
 gi.require_version('Gst', '1.0')
8 11
 from gi.repository import GObject, Gst
9 12
 GObject.threads_init()
10 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 16
 class Recognizer(GObject.GObject):
@@ -20,7 +18,7 @@ class Recognizer(GObject.GObject):
20 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 22
         GObject.GObject.__init__(self)
25 23
         self.commands = {}
26 24
         if src:
@@ -41,7 +39,7 @@ class Recognizer(GObject.GObject):
41 39
         bus.add_signal_watch()
42 40
 
43 41
         # Get the Auto Speech Recognition piece
44
-        asr=self.pipeline.get_by_name('asr')
42
+        asr = self.pipeline.get_by_name('asr')
45 43
         bus.connect('message::element', self.result)
46 44
         asr.set_property('lm', language_file)
47 45
         asr.set_property('dict', dictionary_file)

Loading…
Cancel
Save