0
# Format Conversion
1
2
This document covers converting between music notation formats including MEI, Humdrum, MIDI, and Plaine & Easie Code, as well as exporting and saving loaded documents.
3
4
## Capabilities
5
6
### MEI Export
7
8
Export the loaded document as MEI (Music Encoding Initiative) format.
9
10
```python { .api }
11
class toolkit:
12
def getMEI(self, options: dict | None = None) -> str:
13
"""
14
Get the loaded document as MEI string.
15
16
Args:
17
options: Dictionary with output options:
18
- pageNo: int (1-based), export specific page, or all if 0/None
19
- scoreBased: bool, true for score-based MEI (default: True)
20
- basic: bool, true for basic MEI (default: False)
21
- removeIds: bool, remove unused @xml:id attributes (default: False)
22
23
Returns:
24
MEI data as string
25
"""
26
27
def saveFile(self, filename: str, options: dict | None = None) -> bool:
28
"""
29
Save the loaded document as MEI to a file.
30
31
Args:
32
filename: Output file path
33
options: Dictionary with output options (same as getMEI)
34
35
Returns:
36
True if file was successfully written, False otherwise
37
"""
38
```
39
40
### Humdrum Conversion
41
42
Convert between MEI and Humdrum formats, and filter Humdrum data.
43
44
```python { .api }
45
class toolkit:
46
def convertMEIToHumdrum(self, meiData: str) -> str:
47
"""
48
Convert MEI data to Humdrum format.
49
50
Args:
51
meiData: MEI data as string
52
53
Returns:
54
Humdrum data as string
55
"""
56
57
def convertHumdrumToHumdrum(self, humdrumData: str) -> str:
58
"""
59
Filter and process Humdrum data.
60
61
Applies Humdrum filters to transform the data.
62
63
Args:
64
humdrumData: Humdrum data as string
65
66
Returns:
67
Filtered Humdrum data as string
68
"""
69
70
def convertHumdrumToMIDI(self, humdrumData: str) -> str:
71
"""
72
Convert Humdrum data to MIDI.
73
74
Args:
75
humdrumData: Humdrum data as string
76
77
Returns:
78
MIDI file as base64-encoded string
79
"""
80
81
def getHumdrumFile(self, filename: str) -> bool:
82
"""
83
Write the Humdrum buffer to a file.
84
85
Args:
86
filename: Output file path
87
88
Returns:
89
True if file was successfully written, False otherwise
90
"""
91
```
92
93
### Humdrum Buffer Management
94
95
Manage the internal Humdrum buffer for advanced workflows.
96
97
```python { .api }
98
class toolkit:
99
def setHumdrumBuffer(self, contents: str) -> None:
100
"""
101
Set the internal Humdrum buffer.
102
103
Args:
104
contents: Humdrum data as string
105
"""
106
107
def getHumdrumBuffer(self) -> str:
108
"""
109
Get the contents of the internal Humdrum buffer.
110
111
Returns:
112
Humdrum buffer as string, or "[empty]" if not allocated
113
"""
114
115
def clearHumdrumBuffer(self) -> None:
116
"""
117
Clear the internal Humdrum buffer.
118
"""
119
```
120
121
## Usage Examples
122
123
### MEI Export with Options
124
125
```python
126
import verovio
127
128
tk = verovio.toolkit()
129
tk.loadFile("score.mei")
130
131
# Export full MEI
132
mei_full = tk.getMEI()
133
134
# Export specific page
135
mei_page1 = tk.getMEI(options={'pageNo': 1})
136
137
# Export as basic MEI (simplified structure)
138
mei_basic = tk.getMEI(options={'basic': True})
139
140
# Export with unused IDs removed
141
mei_clean = tk.getMEI(options={'removeIds': True})
142
143
# Save to file
144
tk.saveFile("output.mei")
145
146
# Save with options
147
tk.saveFile("page1.mei", options={'pageNo': 1, 'removeIds': True})
148
```
149
150
### MEI to Humdrum Conversion
151
152
```python
153
import verovio
154
155
tk = verovio.toolkit()
156
157
# Load MEI file
158
with open("score.mei", "r") as f:
159
mei_data = f.read()
160
161
# Convert to Humdrum
162
humdrum_data = tk.convertMEIToHumdrum(mei_data)
163
164
# Save Humdrum output
165
with open("score.krn", "w") as f:
166
f.write(humdrum_data)
167
```
168
169
### Humdrum Filtering
170
171
```python
172
import verovio
173
174
tk = verovio.toolkit()
175
176
# Load and filter Humdrum data
177
with open("score.krn", "r") as f:
178
humdrum_input = f.read()
179
180
# Apply filters (e.g., transposition, extraction)
181
humdrum_filtered = tk.convertHumdrumToHumdrum(humdrum_input)
182
183
# Save filtered result
184
with open("score_filtered.krn", "w") as f:
185
f.write(humdrum_filtered)
186
187
# Load the filtered data into toolkit for rendering
188
tk.loadData(humdrum_filtered)
189
svg = tk.renderToSVG()
190
```
191
192
### Humdrum to MIDI
193
194
```python
195
import verovio
196
import base64
197
198
tk = verovio.toolkit()
199
200
# Read Humdrum file
201
with open("score.krn", "r") as f:
202
humdrum_data = f.read()
203
204
# Convert to MIDI
205
midi_base64 = tk.convertHumdrumToMIDI(humdrum_data)
206
207
# Decode and save
208
midi_bytes = base64.b64decode(midi_base64)
209
with open("output.mid", "wb") as f:
210
f.write(midi_bytes)
211
```
212
213
### Multi-Format Export Pipeline
214
215
```python
216
import verovio
217
218
def export_all_formats(input_file, base_output_name):
219
"""Export loaded notation to all available formats."""
220
tk = verovio.toolkit()
221
tk.loadFile(input_file)
222
223
# MEI
224
tk.saveFile(f"{base_output_name}.mei")
225
226
# SVG (all pages)
227
for page in range(1, tk.getPageCount() + 1):
228
tk.renderToSVGFile(f"{base_output_name}_page{page}.svg", pageNo=page)
229
230
# MIDI
231
tk.renderToMIDIFile(f"{base_output_name}.mid")
232
233
# PAE (Plaine & Easie)
234
tk.renderToPAEFile(f"{base_output_name}.pae")
235
236
# Timemap
237
tk.renderToTimemapFile(f"{base_output_name}_timemap.json")
238
239
# Humdrum
240
mei_data = tk.getMEI()
241
humdrum_data = tk.convertMEIToHumdrum(mei_data)
242
with open(f"{base_output_name}.krn", "w") as f:
243
f.write(humdrum_data)
244
245
print(f"Exported to all formats with base name: {base_output_name}")
246
247
# Usage
248
export_all_formats("input.mei", "output")
249
```
250
251
### Working with Humdrum Buffer
252
253
```python
254
import verovio
255
256
tk = verovio.toolkit()
257
258
# Load Humdrum data
259
with open("score.krn", "r") as f:
260
humdrum_str = f.read()
261
262
# Set buffer
263
tk.setHumdrumBuffer(humdrum_str)
264
265
# Retrieve buffer
266
buffer_content = tk.getHumdrumBuffer()
267
268
# Process buffer content
269
if buffer_content != "[empty]":
270
# Save to file
271
tk.getHumdrumFile("output.krn")
272
273
# Clear buffer when done
274
tk.clearHumdrumBuffer()
275
```
276
277
### Format Conversion Chain
278
279
```python
280
import verovio
281
282
def convert_chain(input_file, input_format):
283
"""Demonstrate conversion chain through multiple formats."""
284
tk = verovio.toolkit()
285
286
# Set input format
287
tk.setInputFrom(input_format)
288
289
# Load original file
290
tk.loadFile(input_file)
291
292
# Convert to MEI (internal representation)
293
mei_data = tk.getMEI()
294
print(f"Converted {input_format} to MEI")
295
296
# Convert MEI to Humdrum
297
humdrum_data = tk.convertMEIToHumdrum(mei_data)
298
with open("converted.krn", "w") as f:
299
f.write(humdrum_data)
300
print("Converted MEI to Humdrum")
301
302
# Convert Humdrum back to MIDI
303
midi_data = tk.convertHumdrumToMIDI(humdrum_data)
304
print("Converted Humdrum to MIDI")
305
306
# Render SVG from original MEI
307
tk.loadData(mei_data)
308
svg = tk.renderToSVG()
309
with open("converted.svg", "w") as f:
310
f.write(svg)
311
print("Rendered MEI to SVG")
312
313
return {
314
'mei': mei_data,
315
'humdrum': humdrum_data,
316
'midi': midi_data,
317
'svg': svg
318
}
319
320
# Convert MusicXML through the chain
321
results = convert_chain("score.musicxml", "musicxml")
322
```
323
324
### Batch Format Conversion
325
326
```python
327
import verovio
328
import os
329
from pathlib import Path
330
331
def batch_convert_to_mei(input_dir, output_dir, input_format='auto'):
332
"""Convert all files in directory to MEI format."""
333
tk = verovio.toolkit()
334
335
if input_format != 'auto':
336
tk.setInputFrom(input_format)
337
338
# Create output directory
339
Path(output_dir).mkdir(parents=True, exist_ok=True)
340
341
# Process all files
342
for filename in os.listdir(input_dir):
343
input_path = os.path.join(input_dir, filename)
344
345
if not os.path.isfile(input_path):
346
continue
347
348
try:
349
# Load file
350
if tk.loadFile(input_path):
351
# Generate output filename
352
base_name = os.path.splitext(filename)[0]
353
output_path = os.path.join(output_dir, f"{base_name}.mei")
354
355
# Save as MEI
356
tk.saveFile(output_path)
357
print(f"Converted: {filename} -> {base_name}.mei")
358
else:
359
print(f"Failed to load: {filename}")
360
print(f"Error: {tk.getLog()}")
361
362
except Exception as e:
363
print(f"Error processing {filename}: {e}")
364
365
# Convert all MusicXML files to MEI
366
batch_convert_to_mei("musicxml_files", "mei_output", input_format='musicxml')
367
```
368
369
### Preserving Metadata in Conversion
370
371
```python
372
import verovio
373
374
tk = verovio.toolkit()
375
tk.loadFile("score.musicxml")
376
377
# Get MEI with full metadata
378
mei_with_metadata = tk.getMEI(options={
379
'scoreBased': True,
380
'basic': False,
381
'removeIds': False
382
})
383
384
# Save with metadata preserved
385
with open("converted_with_metadata.mei", "w") as f:
386
f.write(mei_with_metadata)
387
388
# Get simplified version
389
mei_simple = tk.getMEI(options={
390
'basic': True,
391
'removeIds': True
392
})
393
394
# Save simplified version
395
with open("converted_simple.mei", "w") as f:
396
f.write(mei_simple)
397
```
398
399
### Round-Trip Conversion Testing
400
401
```python
402
import verovio
403
404
def test_round_trip(original_file):
405
"""Test round-trip conversion: Original -> MEI -> Humdrum -> MEI."""
406
tk = verovio.toolkit()
407
408
# Load original
409
tk.loadFile(original_file)
410
mei1 = tk.getMEI()
411
412
# Convert to Humdrum
413
humdrum = tk.convertMEIToHumdrum(mei1)
414
415
# Load Humdrum back
416
tk.loadData(humdrum)
417
418
# Get MEI again
419
mei2 = tk.getMEI()
420
421
# Compare (simplified comparison)
422
print(f"Original MEI length: {len(mei1)}")
423
print(f"Round-trip MEI length: {len(mei2)}")
424
425
# Save both for manual comparison
426
with open("mei_original.mei", "w") as f:
427
f.write(mei1)
428
with open("mei_roundtrip.mei", "w") as f:
429
f.write(mei2)
430
431
return mei1, mei2
432
433
# Test round-trip
434
test_round_trip("score.mei")
435
```
436