forked from csound/manual
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csd2docbook2.py
326 lines (291 loc) · 10.9 KB
/
csd2docbook2.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#
# Copyright (C) 2007 Francois Pinot
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111, USA
# or connect to:
# http://www.fsf.org/licensing/licenses/lgpl.html
#
#import csnd
import getopt, sys, os, glob, re
from xml.dom import minidom
class OrchestraDict(dict):
def __init__(self):
self.initOpcodes()
self.initHeaderSymbols()
self.initBlockDelim()
self.initOperators()
self.initSeqCtrl()
self.initMacros()
self.labels = []
def initOpcodes(self):
'''Read the list of csound opcodes from csound 5 API.
Thus we're sure that the opcode list is up to date, however it will be
complete only if csound has been built with all the plugins.
It is needed to compile an orchestra and score before calling
CsoundOpcodeList() in order to get the opcode list. So we use a dummy
csd file for that purpose (tricky isn't it?)
'''
#csound = csnd.CppSound()
#dummy = '''<CsoundSynthesizer>
#<CsOptions>
#-dodac
#</CsOptions>
#<CsInstruments>
#instr 1
#print p3
#endin
#</CsInstruments>
#<CsScore>
#i1 0 1
#e
#</CsScore>
#</CsoundSynthesizer>'''
f = open("opcode_list.txt", 'r')
file = f.read()
f.close()
#csound.Compile("dummy.csd")
lo = file.split()
#n = lo.Count()
for i in xrange(len(lo)):
self[lo[i]] = 'opc'
#lo.Clear()
#csound.Reset()
#os.remove("dummy.csd")
def initHeaderSymbols(self):
self.update({
'sr':'ohdr', 'kr':'ohdr', 'ksmps':'ohdr', 'nchnls':'ohdr',
'0dbfs':'ohdr', 'ctrlinit':'ohdr', 'ftgen':'ohdr', 'massign':'ohdr',
'pgmassign':'ohdr', 'seed':'ohdr', 'strset':'ohdr'})
def initBlockDelim(self):
self.update({
'instr':'oblock', 'endin':'oblock',
'opcode':'oblock', 'endop':'oblock'})
def initOperators(self):
self.update({
'==':'op', '!=':'op', '?':'op', '>':'op', '>=':'op', 'LeSsThAn':'op',
'LeSsThAn=':'op', '=':'op', '+':'op', '-':'op', '*':'op', '/':'op',
'%':'op', '^':'op', 'AmPeRsAnDAmPeRsAnD':'op', '||':'op',
'AmPeRsAnD':'op', '|':'op', '~':'op', ':':'op'})
def initSeqCtrl(self):
self.update({
'cggoto':'octrl', 'cigoto':'octrl', 'ckgoto':'octrl', 'cngoto':'octrl',
'elseif':'octrl', 'else':'octrl', 'endif':'octrl', 'goto':'octrl',
'if':'octrl', 'igoto':'octrl', 'kgoto':'octrl', 'tigoto':'octrl',
'timout':'octrl', 'loop_ge':'octrl', 'loop_gt':'octrl',
'loop_le':'octrl', 'loop_lt':'octrl'})
def initMacros(self):
self.update({
'#define':'omacro', '#ifdef':'omacro', '#ifndef':'omacro', '#end':'omacro',
'#else':'omacro', '#include':'omacro', '#undef':'omacro'})
def addLabel(self, key):
self[key] = 'olabel'
self.labels.append(key)
def clearLabels(self):
for key in self.labels:
if self.has_key(key):
self.pop(key)
self.labels = []
def get(self, key, x=None):
if self.has_key(key):
return '<emphasis role="' + self[key] +'">' + key + '</emphasis>'
return key
class OrchestraTransform(object):
def __init__(self):
motif = '''(
\s+ | \( |
== | != | LeSsThAn= | LeSsThAn | >= | > | \? |
= | \+ | - | \* | / | % | ^ |
AmPeRsAnDAmPeRsAnD | \|\| |
AmPeRsAnD | \| | ~ | :
)'''
self.pattern = re.compile(motif, re.VERBOSE)
self.labelPattern = re.compile('[a-zA-Z]\w*:')
self.orcDict = OrchestraDict()
def detectLabels(self, lines):
for s in lines:
c = self.labelPattern.match(s)
if c:
self.orcDict.addLabel(s[:c.end()-1])
def comment(self, s):
return '<emphasis role="comment">' + s + '</emphasis>'
def orcLine(self, line):
inTokens = self.pattern.split(line)
outTokens = []
for t in inTokens:
if len(t) > 0:
outTokens.append(self.orcDict.get(t, line))
return ''.join(outTokens)
def transformLines(self, lines):
self.orcDict.clearLabels()
self.detectLabels(lines)
outLines = []
for s in lines:
i = s.find(';')
if i == 0:
outLines.append(self.comment(s))
elif i > 0:
outLines.append(self.orcLine(s[:i]) + self.comment(s[i:]))
else:
outLines.append(self.orcLine(s))
return outLines
def transform(self, filename):
f = open(filename, 'r')
s = f.read()
f.close()
s = s.replace('&', 'AmPeRsAnD')
s = s.replace('<', 'LeSsThAn')
s = s.replace('LeSsThAnCs', '<Cs')
s = s.replace('LeSsThAn/Cs', '</Cs')
olines = self.transformLines(s.split('\n'))
s = '\n'.join(olines).replace('AmPeRsAnD', '&')
s = s.replace('LeSsThAn', '<')
outfn = filename.replace('examples', 'examples-xml')
fout = open(outfn + '.xml', 'w')
fout.write('<programlisting>\n')
fout.write(s)
fout.write('</programlisting>')
fout.close()
print filename
class ScoreTransform(object):
def __init__(self):
self.pattern = re.compile('^\s*[abefimnqrstvx]')
def comment(self, s):
return '<emphasis role="comment">' + s + '</emphasis>'
def scoLine(self, line):
r = self.pattern.search(line)
if r:
s = line[r.end()-1]
return line.replace(s, '<emphasis role="stamnt">' + s + '</emphasis>')
return line
def transformLines(self, lines):
outLines = []
for s in lines:
i = s.find(';')
if i == 0:
outLines.append(self.comment(s))
elif i > 0:
outLines.append(self.scoLine(s[:i]) + self.comment(s[i:]))
else:
outLines.append(self.scoLine(s))
return outLines
class CsdTransform(object):
def __init__(self):
self.orc_t = OrchestraTransform()
self.sco_t = ScoreTransform()
def text(self, node):
s = node.childNodes[0].nodeValue
if s[0] == '\n':
start = 1
else:
start = 0
if s[-1] == '\n':
end = -1
else:
end = None
return s[start:end].split('\n')
def optTransform(self, lines):
comment = lambda s: '<emphasis role="comment">' + s + '</emphasis>'
outLines = []
for s in lines:
i = s.find(';')
if i == 0:
outLines.append(comment(s))
elif i > 0:
outLines.append(s[:i] + comment(s[i:]))
else:
outLines.append(s)
return outLines
def transform(self, filename):
tag = lambda s: '<emphasis role="csdtag"><' + s + '></emphasis>'
f = open(filename, 'r')
s = f.read()
f.close()
# We convert & and < in "pseudo" entities because we don't want that
# minidom resolves those entities
s = s.replace('&', 'AmPeRsAnD')
s = s.replace('<', 'LeSsThAn')
s = s.replace('LeSsThAnCs', '<Cs')
s = s.replace('LeSsThAn/Cs', '</Cs')
csddoc = minidom.parseString(s)
options_elem = csddoc.getElementsByTagName("CsOptions")
if len(options_elem) > 0:
options = options_elem[0]
orchestra = csddoc.getElementsByTagName("CsInstruments")[0]
score = csddoc.getElementsByTagName("CsScore")[0]
outLines = []
outLines.append('<programlisting>')
outLines.append(tag("CsoundSynthesizer"))
if len(options_elem) > 0:
outLines.append(tag("CsOptions"))
outLines.extend(self.optTransform(self.text(options)))
outLines.append(tag("/CsOptions"))
outLines.append(tag("CsInstruments"))
outLines.extend(self.orc_t.transformLines(self.text(orchestra)))
outLines.append(tag("/CsInstruments"))
outLines.append(tag("CsScore"))
outLines.extend(self.sco_t.transformLines(self.text(score)))
outLines.append(tag("/CsScore"))
outLines.append(tag("/CsoundSynthesizer"))
outLines.append('</programlisting>')
csddoc.unlink()
# We convert back our "pseudo" entities in actual entities
s = '\n'.join(outLines).replace('AmPeRsAnD', '&')
s = s.replace('LeSsThAn', '<')
outfn = filename.replace('examples', 'examples-xml')
fout = open(outfn + '.xml', 'w')
fout.write(s)
fout.close()
print filename
def main():
'''Usage: python csd2xml option [filename]
where option is one of the following:
-f filename or --file=filename
transform examples/filename to examples-xml/filename.xml
where filename is the name of a csd file or orc file
-a or --all
transform all the csd files of the example directory to
xml files in the examples-xml directory.'''
try:
opts, args = getopt.getopt(sys.argv[1:], "f:a", ["file=", "all"])
except getopt.GetoptError:
print main.__doc__
sys.exit(2)
for o, a in opts:
if o in ("-f", "--file") and a:
if a.find('examples') < 0:
a = 'examples' + os.sep + a
if os.path.exists(a):
suf = os.path.splitext(a)[1]
if suf == '.csd':
CsdTransform().transform(a)
elif suf == '.orc':
OrchestraTransform().transform(a)
else:
print a + ' is not a csd or orc filename'
sys.exit(0)
else:
print a + " doesn't exists!"
sys.exit(2)
if o in ("-a", "--all"):
ct = CsdTransform()
infiles = glob.glob('examples/*.csd')
for f in infiles:
ct.transform(f)
sys.exit(0)
print main.__doc__
sys.exit(2)
if __name__ == '__main__':
main()