Browse Source

Moved paths to Config class

Paths of important files and directories are part of the program's
configuration, no?

We're making better use of XDG paths now.  Only configuration-y things
go in $XDG_CONFIG_HOME now, with cache-y and data-y things going in the
appropriate places instead of just being crammed in with configuration.
Clara Hobbs 8 years ago
parent
commit
25ebc8fe8b
4 changed files with 71 additions and 51 deletions
  1. 12
    31
      blather.py
  2. 46
    10
      config.py
  3. 7
    6
      language_updater.sh
  4. 6
    4
      recognizer.py

+ 12
- 31
blather.py View File

@@ -17,19 +17,6 @@ import json
17 17
 from recognizer import Recognizer
18 18
 from config import Config
19 19
 
20
-# Where are the files?
21
-conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
22
-                                           "blather"))
23
-lang_dir = os.path.join(conf_dir, "language")
24
-command_file = os.path.join(conf_dir, "commands.conf")
25
-strings_file = os.path.join(conf_dir, "sentences.corpus")
26
-history_file = os.path.join(conf_dir, "blather.history")
27
-hash_file = os.path.join(conf_dir, "hash.json")
28
-lang_file = os.path.join(lang_dir, 'lm')
29
-dic_file = os.path.join(lang_dir, 'dic')
30
-# Make the lang_dir if it doesn't exist
31
-if not os.path.exists(lang_dir):
32
-    os.makedirs(lang_dir)
33 20
 
34 21
 class Blather:
35 22
 
@@ -41,13 +28,13 @@ class Blather:
41 28
 
42 29
         self.commands = {}
43 30
 
44
-        # Read the commands
45
-        self.read_commands()
46
-
47
-        # Load the options file
31
+        # Load configuration
48 32
         self.config = Config()
49 33
         self.options = vars(self.config.options)
50 34
 
35
+        # Read the commands
36
+        self.read_commands()
37
+
51 38
         if self.options['interface'] != None:
52 39
             if self.options['interface'] == "g":
53 40
                 from gtkui import UI
@@ -75,24 +62,18 @@ class Blather:
75 62
         self.update_language()
76 63
 
77 64
         # Create the recognizer
78
-        try:
79
-            self.recognizer = Recognizer(lang_file, dic_file, self.options['microphone'])
80
-        except Exception as e:
81
-            # No recognizer? bummer
82
-            print('error making recognizer')
83
-            sys.exit()
84
-
65
+        self.recognizer = Recognizer(self.config)
85 66
         self.recognizer.connect('finished', self.recognizer_finished)
86 67
 
87 68
     def read_commands(self):
88 69
         # Read the commands file
89
-        file_lines = open(command_file)
90
-        strings = open(strings_file, "w")
70
+        file_lines = open(self.config.command_file)
71
+        strings = open(self.config.strings_file, "w")
91 72
         for line in file_lines:
92 73
             # Trim the white spaces
93 74
             line = line.strip()
94 75
             # If the line has length and the first char isn't a hash
95
-            if len(line) and line[0]!="#":
76
+            if len(line) and line[0] != "#":
96 77
                 # This is a parsible line
97 78
                 (key, value) = line.split(":", 1)
98 79
                 self.commands[key.strip().lower()] = value.strip()
@@ -108,7 +89,7 @@ class Blather:
108 89
                 self.history.pop(0)
109 90
 
110 91
             # Open and truncate the blather history file
111
-            hfile = open(history_file, "w")
92
+            hfile = open(self.config.history_file, "w")
112 93
             for line in self.history:
113 94
                 hfile.write(line + "\n")
114 95
             # Close the file
@@ -118,7 +99,7 @@ class Blather:
118 99
         """Update the language if its hash has changed"""
119 100
         # Load the stored hash from the hash file
120 101
         try:
121
-            with open(hash_file, 'r') as f:
102
+            with open(self.config.hash_file, 'r') as f:
122 103
                 hashes = json.load(f)
123 104
             stored_hash = hashes['language']
124 105
         except (IOError, KeyError, TypeError):
@@ -127,7 +108,7 @@ class Blather:
127 108
 
128 109
         # Calculate the hash the language file has right now
129 110
         hasher = hashlib.sha256()
130
-        with open(strings_file, 'rb') as sfile:
111
+        with open(self.config.strings_file, 'rb') as sfile:
131 112
             buf = sfile.read()
132 113
             hasher.update(buf)
133 114
         new_hash = hasher.hexdigest()
@@ -139,7 +120,7 @@ class Blather:
139 120
             self.run_command('./language_updater.sh')
140 121
             # Store the new hash
141 122
             new_hashes = {'language': new_hash}
142
-            with open(hash_file, 'w') as f:
123
+            with open(self.config.hash_file, 'w') as f:
143 124
                 json.dump(new_hashes, f)
144 125
 
145 126
     def run_command(self, cmd):

+ 46
- 10
config.py View File

@@ -10,11 +10,34 @@ from argparse import ArgumentParser, Namespace
10 10
 from gi.repository import GLib
11 11
 
12 12
 class Config:
13
-    conf_dir = os.path.expanduser(os.path.join(GLib.get_user_config_dir(),
14
-                                               "blather"))
13
+    """Keep track of the configuration of Kaylee"""
14
+    # Name of the program, for later use
15
+    program_name = "kaylee"
16
+
17
+    # Directories
18
+    conf_dir = os.path.join(GLib.get_user_config_dir(), program_name)
19
+    cache_dir = os.path.join(GLib.get_user_cache_dir(), program_name)
20
+    data_dir = os.path.join(GLib.get_user_data_dir(), program_name)
21
+
22
+    # Configuration files
23
+    command_file = os.path.join(conf_dir, "commands.conf")
15 24
     opt_file = os.path.join(conf_dir, "options.json")
16 25
 
26
+    # Cache files
27
+    history_file = os.path.join(cache_dir, program_name + "history")
28
+    hash_file = os.path.join(cache_dir, "hash.json")
29
+
30
+    # Data files
31
+    strings_file = os.path.join(data_dir, "sentences.corpus")
32
+    lang_file = os.path.join(data_dir, 'lm')
33
+    dic_file = os.path.join(data_dir, 'dic')
34
+
17 35
     def __init__(self):
36
+        # Ensure necessary directories exist
37
+        self._make_dir(self.conf_dir)
38
+        self._make_dir(self.cache_dir)
39
+        self._make_dir(self.data_dir)
40
+
18 41
         # Set up the argument parser
19 42
         self.parser = ArgumentParser()
20 43
         self.parser.add_argument("-i", "--interface", type=str,
@@ -24,16 +47,16 @@ class Config:
24 47
 
25 48
         self.parser.add_argument("-c", "--continuous",
26 49
                 action="store_true", dest="continuous", default=False,
27
-                help="starts interface with 'continuous' listen enabled")
50
+                help="Start interface with 'continuous' listen enabled")
28 51
 
29 52
         self.parser.add_argument("-p", "--pass-words",
30 53
                 action="store_true", dest="pass_words", default=False,
31
-                help="passes the recognized words as arguments to the shell" +
54
+                help="Pass the recognized words as arguments to the shell" +
32 55
                 " command")
33 56
 
34 57
         self.parser.add_argument("-H", "--history", type=int,
35 58
                 action="store", dest="history",
36
-                help="number of commands to store in history file")
59
+                help="Number of commands to store in history file")
37 60
 
38 61
         self.parser.add_argument("-m", "--microphone", type=int,
39 62
                 action="store", dest="microphone", default=None,
@@ -41,16 +64,29 @@ class Config:
41 64
 
42 65
         self.parser.add_argument("--valid-sentence-command", type=str,
43 66
                 dest="valid_sentence_command", action='store',
44
-                help="command to run when a valid sentence is detected")
67
+                help="Command to run when a valid sentence is detected")
45 68
 
46 69
         self.parser.add_argument("--invalid-sentence-command", type=str,
47 70
                 dest="invalid_sentence_command", action='store',
48
-                help="command to run when an invalid sentence is detected")
71
+                help="Command to run when an invalid sentence is detected")
49 72
 
50 73
         # 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)
74
+        self._read_options_file()
54 75
 
55 76
         # Parse command-line arguments, overriding config file as appropriate
56 77
         self.args = self.parser.parse_args(namespace=self.options)
78
+        print(self.args)
79
+        print(self.options)
80
+
81
+    def _make_dir(self, directory):
82
+        if not os.path.exists(directory):
83
+            os.makedirs(directory)
84
+
85
+    def _read_options_file(self):
86
+        try:
87
+            with open(self.opt_file, 'r') as f:
88
+                self.options = json.load(f)
89
+                self.options = Namespace(**self.options)
90
+        except FileNotFoundError:
91
+            # Make an empty options namespace
92
+            self.options = Namespace()

+ 7
- 6
language_updater.sh View File

@@ -1,10 +1,11 @@
1 1
 #!/bin/bash
2 2
 
3
-blatherdir=~/.config/blather
4
-sentences=$blatherdir/sentences.corpus
3
+blatherdir=~/.config/kaylee
4
+blatherdatadir=~/.local/share/kaylee
5
+blathercachedir=~/.cache/kaylee
6
+sentences=$blatherdatadir/sentences.corpus
5 7
 sourcefile=$blatherdir/commands.conf
6
-langdir=$blatherdir/language
7
-tempfile=$blatherdir/url.txt
8
+tempfile=$blathercachedir/url.txt
8 9
 lmtoolurl=http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
9 10
 
10 11
 cd $blatherdir
@@ -25,7 +26,7 @@ curl -C - -O $(cat $tempfile).dic
25 26
 curl -C - -O $(cat $tempfile).lm
26 27
 
27 28
 # mv em to the right name/place
28
-mv *.dic $langdir/dic
29
-mv *.lm $langdir/lm
29
+mv *.dic $blatherdatadir/dic
30
+mv *.lm $blatherdatadir/lm
30 31
 
31 32
 rm $tempfile

+ 6
- 4
recognizer.py View File

@@ -18,11 +18,13 @@ class Recognizer(GObject.GObject):
18 18
         'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
19 19
     }
20 20
 
21
-    def __init__(self, language_file, dictionary_file, src=None):
21
+    def __init__(self, config):
22 22
         GObject.GObject.__init__(self)
23 23
         self.commands = {}
24
+
25
+        src = config.options.microphone
24 26
         if src:
25
-            audio_src = 'alsasrc device="hw:%d,0"' % (src)
27
+            audio_src = 'alsasrc device="hw:{0},0"'.format(src)
26 28
         else:
27 29
             audio_src = 'autoaudiosrc'
28 30
 
@@ -31,8 +33,8 @@ class Recognizer(GObject.GObject):
31 33
             audio_src +
32 34
             ' ! audioconvert' +
33 35
             ' ! audioresample' +
34
-            ' ! pocketsphinx lm=' + language_file + ' dict=' +
35
-            dictionary_file + ' configured=true' +
36
+            ' ! pocketsphinx lm=' + config.lang_file + ' dict=' +
37
+            config.dic_file + ' configured=true' +
36 38
             ' ! appsink sync=false'
37 39
         )
38 40
         try:

Loading…
Cancel
Save