Pārlūkot izejas kodu

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 gadus atpakaļ
vecāks
revīzija
25ebc8fe8b
4 mainītis faili ar 71 papildinājumiem un 51 dzēšanām
  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 Parādīt failu

17
 from recognizer import Recognizer
17
 from recognizer import Recognizer
18
 from config import Config
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
 class Blather:
21
 class Blather:
35
 
22
 
41
 
28
 
42
         self.commands = {}
29
         self.commands = {}
43
 
30
 
44
-        # Read the commands
45
-        self.read_commands()
46
-
47
-        # Load the options file
31
+        # Load configuration
48
         self.config = Config()
32
         self.config = Config()
49
         self.options = vars(self.config.options)
33
         self.options = vars(self.config.options)
50
 
34
 
35
+        # Read the commands
36
+        self.read_commands()
37
+
51
         if self.options['interface'] != None:
38
         if self.options['interface'] != None:
52
             if self.options['interface'] == "g":
39
             if self.options['interface'] == "g":
53
                 from gtkui import UI
40
                 from gtkui import UI
75
         self.update_language()
62
         self.update_language()
76
 
63
 
77
         # Create the recognizer
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
         self.recognizer.connect('finished', self.recognizer_finished)
66
         self.recognizer.connect('finished', self.recognizer_finished)
86
 
67
 
87
     def read_commands(self):
68
     def read_commands(self):
88
         # Read the commands file
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
         for line in file_lines:
72
         for line in file_lines:
92
             # Trim the white spaces
73
             # Trim the white spaces
93
             line = line.strip()
74
             line = line.strip()
94
             # If the line has length and the first char isn't a hash
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
                 # This is a parsible line
77
                 # This is a parsible line
97
                 (key, value) = line.split(":", 1)
78
                 (key, value) = line.split(":", 1)
98
                 self.commands[key.strip().lower()] = value.strip()
79
                 self.commands[key.strip().lower()] = value.strip()
108
                 self.history.pop(0)
89
                 self.history.pop(0)
109
 
90
 
110
             # Open and truncate the blather history file
91
             # Open and truncate the blather history file
111
-            hfile = open(history_file, "w")
92
+            hfile = open(self.config.history_file, "w")
112
             for line in self.history:
93
             for line in self.history:
113
                 hfile.write(line + "\n")
94
                 hfile.write(line + "\n")
114
             # Close the file
95
             # Close the file
118
         """Update the language if its hash has changed"""
99
         """Update the language if its hash has changed"""
119
         # Load the stored hash from the hash file
100
         # Load the stored hash from the hash file
120
         try:
101
         try:
121
-            with open(hash_file, 'r') as f:
102
+            with open(self.config.hash_file, 'r') as f:
122
                 hashes = json.load(f)
103
                 hashes = json.load(f)
123
             stored_hash = hashes['language']
104
             stored_hash = hashes['language']
124
         except (IOError, KeyError, TypeError):
105
         except (IOError, KeyError, TypeError):
127
 
108
 
128
         # Calculate the hash the language file has right now
109
         # Calculate the hash the language file has right now
129
         hasher = hashlib.sha256()
110
         hasher = hashlib.sha256()
130
-        with open(strings_file, 'rb') as sfile:
111
+        with open(self.config.strings_file, 'rb') as sfile:
131
             buf = sfile.read()
112
             buf = sfile.read()
132
             hasher.update(buf)
113
             hasher.update(buf)
133
         new_hash = hasher.hexdigest()
114
         new_hash = hasher.hexdigest()
139
             self.run_command('./language_updater.sh')
120
             self.run_command('./language_updater.sh')
140
             # Store the new hash
121
             # Store the new hash
141
             new_hashes = {'language': new_hash}
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
                 json.dump(new_hashes, f)
124
                 json.dump(new_hashes, f)
144
 
125
 
145
     def run_command(self, cmd):
126
     def run_command(self, cmd):

+ 46
- 10
config.py Parādīt failu

10
 from gi.repository import GLib
10
 from gi.repository import GLib
11
 
11
 
12
 class Config:
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
     opt_file = os.path.join(conf_dir, "options.json")
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
     def __init__(self):
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
         # Set up the argument parser
41
         # Set up the argument parser
19
         self.parser = ArgumentParser()
42
         self.parser = ArgumentParser()
20
         self.parser.add_argument("-i", "--interface", type=str,
43
         self.parser.add_argument("-i", "--interface", type=str,
24
 
47
 
25
         self.parser.add_argument("-c", "--continuous",
48
         self.parser.add_argument("-c", "--continuous",
26
                 action="store_true", dest="continuous", default=False,
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
         self.parser.add_argument("-p", "--pass-words",
52
         self.parser.add_argument("-p", "--pass-words",
30
                 action="store_true", dest="pass_words", default=False,
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
                 " command")
55
                 " command")
33
 
56
 
34
         self.parser.add_argument("-H", "--history", type=int,
57
         self.parser.add_argument("-H", "--history", type=int,
35
                 action="store", dest="history",
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
         self.parser.add_argument("-m", "--microphone", type=int,
61
         self.parser.add_argument("-m", "--microphone", type=int,
39
                 action="store", dest="microphone", default=None,
62
                 action="store", dest="microphone", default=None,
41
 
64
 
42
         self.parser.add_argument("--valid-sentence-command", type=str,
65
         self.parser.add_argument("--valid-sentence-command", type=str,
43
                 dest="valid_sentence_command", action='store',
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
         self.parser.add_argument("--invalid-sentence-command", type=str,
69
         self.parser.add_argument("--invalid-sentence-command", type=str,
47
                 dest="invalid_sentence_command", action='store',
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
         # Read the configuration file
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
         # Parse command-line arguments, overriding config file as appropriate
76
         # Parse command-line arguments, overriding config file as appropriate
56
         self.args = self.parser.parse_args(namespace=self.options)
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 Parādīt failu

1
 #!/bin/bash
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
 sourcefile=$blatherdir/commands.conf
7
 sourcefile=$blatherdir/commands.conf
6
-langdir=$blatherdir/language
7
-tempfile=$blatherdir/url.txt
8
+tempfile=$blathercachedir/url.txt
8
 lmtoolurl=http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
9
 lmtoolurl=http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
9
 
10
 
10
 cd $blatherdir
11
 cd $blatherdir
25
 curl -C - -O $(cat $tempfile).lm
26
 curl -C - -O $(cat $tempfile).lm
26
 
27
 
27
 # mv em to the right name/place
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
 rm $tempfile
32
 rm $tempfile

+ 6
- 4
recognizer.py Parādīt failu

18
         'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,))
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
         GObject.GObject.__init__(self)
22
         GObject.GObject.__init__(self)
23
         self.commands = {}
23
         self.commands = {}
24
+
25
+        src = config.options.microphone
24
         if src:
26
         if src:
25
-            audio_src = 'alsasrc device="hw:%d,0"' % (src)
27
+            audio_src = 'alsasrc device="hw:{0},0"'.format(src)
26
         else:
28
         else:
27
             audio_src = 'autoaudiosrc'
29
             audio_src = 'autoaudiosrc'
28
 
30
 
31
             audio_src +
33
             audio_src +
32
             ' ! audioconvert' +
34
             ' ! audioconvert' +
33
             ' ! audioresample' +
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
             ' ! appsink sync=false'
38
             ' ! appsink sync=false'
37
         )
39
         )
38
         try:
40
         try:

Notiek ielāde…
Atcelt
Saglabāt