-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathConfig.py
237 lines (174 loc) · 7.01 KB
/
Config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import json
import re,os
import sublime, sublime_plugin
class Config(sublime_plugin.TextCommand):
def is_array(self,var):
return isinstance(var, (list, tuple))
def run(self,edit):
dir = sublime.packages_path()
pyconf = os.path.join(dir,"preech\config\python.gram.json")
fobj = open(pyconf, "r")
jsonConfig = fobj.readlines()
jsonList = json.loads("".join(jsonConfig) )
aliases = self.getAliases(jsonList)
print '----------------------'
#write each alias from the list into the grammar file that's read by sphinx
self.createGrammarFile(aliases)
#generate the processing code that will be used to process the input
#received from sphinx
self.generateCode(jsonList)
fobj.close()
def getAliases(self, jsonList):
#we return a list of UNIQUE aliases
#by maintaining a dictionary structure and storing everything as keys,
#we avoid duplicates, which is desired
aliaslist = {}
for i in jsonList:
#skip the settings key
if (i == "settings"):
continue
#for each one if it's an array, loop over it
if (self.is_array(jsonList[i])):
for j in jsonList[i]:
aliaslist[ j['alias'] ] = None
#otherwise, just get insert and alias
else:
aliaslist[ jsonList[i]['alias'] ] = None
return aliaslist
def createGrammarFile(self,aliases):
dir = sublime.packages_path()
gramfile = os.path.join(dir,"preech/sphinx/edu/cmu/sphinx/demo/helloworld/core.gram")
sphinxfile = open(gramfile,"w")
sphinxfile.write("#JSGF V1.0;\n\n")
sphinxfile.write('/* Grammar generated by preech config */\n\n')
sphinxfile.write("grammar core;\n\n")
rules = "public <start> ="
for alias in aliases:
rules = rules + " | " + alias
rules = rules.replace('|','', 1) + ";"
sphinxfile.write(rules)
#close all the open files
sphinxfile.close()
#this function generates the python code
#That is going to be able to accept it's
#input is the parsed json config, output is
#written to the file 'InputProcessor.py'
def generateCode(self, grammarList):
dir = sublime.packages_path()
codegenfile = os.path.join(dir,"preech/inputProcessor.py")
inputfile = open(codegenfile,"w")
inputfile.write("#this file has been generated\n")
inputfile.write("#by PREECH config.py for processing\n")
inputfile.write("#The input received by sphinx\n")
inputfile.write("import sublime,sublime_plugin\n")
inputfile.write("import time\n")
inputfile.write("try:\n")
inputfile.write(" from Queue import Queue, Empty\n")
inputfile.write("except ImportError:\n")
inputfile.write(" from queue import Queue, Empty # python 3.x\n")
inputfile.write("\n\nclass inputProcessor():\n")
inputfile.write(" speechQue = None\n")
inputfile.write(" actionQue = None\n")
inputfile.write(" def __init__(self,speechQue,actionQue):\n")
inputfile.write(" self.speechQue = speechQue\n")
inputfile.write(" self.actionQue = actionQue\n")
inputfile.write(" def __next_word(self):\n")
inputfile.write(" while ( True ):\n")
inputfile.write(" word = self.getNextInput() \n")
inputfile.write(" if (word is False):\n")
inputfile.write(" time.sleep(1)\n")
inputfile.write(" else:\n")
inputfile.write(" break\n")
inputfile.write(" return word\n")
inputfile.write(" def getNextInput(self):\n")
inputfile.write(" try: line = self.speechQue.get_nowait()\n")
inputfile.write(" except Empty:\n")
inputfile.write(" return False\n")
inputfile.write(" else: # got line\n")
inputfile.write(" return line\n")
inputfile.write(" def " + "getSym" + "(self):\n")
inputfile.write(" value = self.__next_word()\n")
inputfile.write(" if (False):\n")
inputfile.write(" pass\n")
inputfile.write(" elif (value =='continue'):\n")
inputfile.write(" pass\n")
inputfile.write(" else:\n")
inputfile.write(" self.getSym()\n")
defaultStates = ""
if ("*" in grammarList):
inputfile.write(" def " + "acceptDefaultStates(self,value):\n")
inputfile.write(" if (False):\n")
inputfile.write(" pass\n")
for ds in grammarList["*"]:
toinsert = ds['insert']
toinsert = toinsert.replace("\n","\\n")
toinsert = toinsert.replace("\t","\\t")
inputfile.write(" elif (value == '" + ds['alias'] + "' ):\n")
inputfile.write(" act = action()\n")
inputfile.write(" act.setInsert('" + toinsert + "')\n")
inputfile.write(" act.setOffset(0)\n")
inputfile.write(" self.actionQue.put(act)\n")
inputfile.write(" return True\n")
inputfile.write(" return False\n")
for i in grammarList:
#skip the settings key\n")
if (i == 'settings' or i == '*'):
continue
print i
inputfile.write("\n\n def " + i + "(self):\n")
#inputfile.write(" value = recognizer.getNextWord():\n")
inputfile.write(" value = self.__next_word()\n")
inputfile.write(" if(self.acceptDefaultStates(value)):\n")
inputfile.write(" self." + i + "()\n")
inputfile.write(" if (False):\n")
inputfile.write(" pass\n")
#Keeping everything in one loop makes everything cleaner
#inside the loop we check if it's an array or no
for j in grammarList[i]:
if (self.is_array(grammarList[i])):
rule=j
else:
rule=grammarList[i]
nonterminals = r"\[\[[^\]]*\]\]"
toinsert = re.sub( nonterminals, "", rule['insert'] )
toinsert = toinsert.replace('\n','\\n') ## escape newlines
rule_nonewlines = rule['insert']
alias = rule['alias']
inputfile.write(" elif (value =='" + alias + "'):\n")
inputfile.write(" act = action()\n")
inputfile.write(" act.setInsert('" + toinsert + "')\n")
inputfile.write("# self.view.insert(edit, pos, '"+ toinsert + "' )\n")
regex = re.compile( nonterminals )
decrement = 0
for m in regex.finditer(rule_nonewlines):
nontermName = m.group()[3:-2]
nontermSize = len(m.group())
cursorGoto = m.start()
nontermChar = m.group()[2]
inputfile.write(" act.setOffset(" + str(cursorGoto - decrement) + ")\n")
inputfile.write(" self.actionQue.put(act)\n")
inputfile.write(" act = action()\n")
inputfile.write(" act.setInsert('')\n")
#move the cursor,
if (nontermChar == "$"):
inputfile.write(" self." + str(nontermName) + "()\n")
elif (nontermChar == "%"):
inputfile.write(" " + "#alright we need to wait for her to enter a symbol name \n")
inputfile.write(" " + "self.getSym()\n")
decrement = nontermSize + cursorGoto
else:
inputfile.write(" act.setOffset(0)\n")
inputfile.write(" self.actionQue.put(act)\n")
print 'elsing'
inputfile.write(" else:\n")
inputfile.write(" self." + i +"()\n")
inputfile.write("\n\n#specifies what text to insert and then where to move\n")
inputfile.write("class action():\n")
inputfile.write(" def __init__(self):\n")
inputfile.write(" pass\n")
inputfile.write(" def setInsert(self,toinsert):\n")
inputfile.write(" self.toinsert = toinsert\n")
inputfile.write(" def setOffset(self,offset):\n")
inputfile.write(" self.offset = offset\n")
##annnnnd close the file
inputfile.close()