from midiutil import MIDIFile

import xml.dom.minidom
import sys
from pathlib import PurePath

KEYS = {'n': 'noteNum', 'v': 'velocity', 'dur': 'durTick', 't':'posTick'}

def getNoteData(note, key):
	try: 
		return int(note.getElementsByTagName(key)[0].firstChild.data)
	except:
		return int(note.getElementsByTagName(KEYS[key])[0].firstChild.data)

def findPhoneme(note):
	for x in note.childNodes:
		if x.nodeName == 'phnms' or x.nodeName == 'p':
			return str(x.firstChild.data)

path = PurePath(sys.argv[1])

vsqx = xml.dom.minidom.parse(str(path))

TEMPO = int(vsqx.getElementsByTagName('tempo')[0].getElementsByTagName('v').item(0).childNodes[0].data)/100

mf = MIDIFile(len(vsqx.getElementsByTagName('vsTrack')), removeDuplicates=False)

time = 0

for trackNo, track in enumerate(vsqx.getElementsByTagName('vsTrack')):
	mf.addTrackName(trackNo, time, "Track {}".format(str(trackNo)))
	for note in track.getElementsByTagName('note'):
		print(getNoteData(note, 't'))
		mf.addSysEx(trackNo, getNoteData(note, 't')/480, 0x43, bytes((0x43, 0x79, 0x09, 0x00, 0x50, 0x10)) + findPhoneme(note).encode('utf-8') + bytes((0x00,)))
		mf.addNote(trackNo, 0, getNoteData(note, 'n'), getNoteData(note, 't') / 480, getNoteData(note, 'dur') / 480, getNoteData(note, 'v'))
	mf.addTempo(trackNo, time, TEMPO)

with open(str(path.parents[0]) +'\\'+ path.stem + ".mid", 'wb') as outf:
	mf.writeFile(outf)
