-
Notifications
You must be signed in to change notification settings - Fork 0
/
MusicXmlParser.py
188 lines (142 loc) · 7.29 KB
/
MusicXmlParser.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
# -*- coding: utf-8 -*-
'''
Created on Jun 14, 2015
@author: joro
'''
from music21 import *
from SyllableJingju import SyllableJingju
from cjklib.reading import ReadingFactory
from cjklib.characterlookup import CharacterLookup
import logging
from Lyrics import Lyrics
from Word import Word
from lyricsParser import stripPunctuationSings, syllables2Lyrics
from Phonetizer import Phonetizer
import sys
import os.path
# 64th of note
MIN_DUR_UNIT = 64
class MusicXMLParser(object):
'''
infer duration of lyrics from score.
loops though all notes and rests sequentially
a new syllable start, whenever a text is attached to a note (a pause after a note is considered a syllable with no text)
if no text, add note values to current syllable
'''
def __init__(self, MusicXmlURI, lyricsTextGrid):
'''
Constructor
'''
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self._loadSyllables( MusicXmlURI, lyricsTextGrid)
# lyrics for each sentence/line
self.listSentences = []
self.divideIntoSections()
# list of section names and their lyrics.
self.sectionLyrics = []
def _loadSyllables(self, MusicXmlURI, lyricsTextGrid):
'''
top=most method
'''
self.listSyllables = []
if not os.path.isfile(MusicXmlURI):
sys.exit("file {} does not exist, please name it so".format(MusicXmlURI))
score = converter.parse(MusicXmlURI)
notesAndRests = score.flat.notesAndRests
currSyllable = None
currSyllTotalDuration = None
for noteOrRest in notesAndRests:
currSyllable, currSyllTotalDuration = self.parseCurrTxtToken(currSyllable, currSyllTotalDuration, noteOrRest)
# last syllable
currSyllable.setDurationInMinUnit(currSyllTotalDuration)
self.listSyllables.append(currSyllable)
##### here workaround when not able to convert lyrics from score into pinyin
# syllablesAllPinyin = createSyllables(lyricsTextGrid, -1, -1 )
#
# counter = 0
# for syl in self.listSyllables:
# if syl.text == 'REST':
# pass
# else:
# if counter == len(syllablesAllPinyin): # reached last syllable
# sys.exit(" syllable {} is last available from syllablesPinyin".format(syllablesAllPinyin[counter-1].text))
# print "mandarin:{} and pinyin: {} ".format(syl.text, syllablesAllPinyin[counter].text)
# syl.text = syllablesAllPinyin[counter].text
# counter +=1
# print "len syllables in muicXML= {} and len syllables in TextGrid = {}".format(counter, len(syllablesAllPinyin))
# end of workaround
def divideIntoSections(self):
'''
same as lyricsParser.divideIntoSections just class variable name self.listSyllable is different
converts mandarin to pinyin
divides into sections
'''
currSectionLyrics = []
for syl in self.listSyllables:
isEndOfSentence, syl.text = stripPunctuationSings(syl.text)
### convert from mandarin to pinyin
if not syl.text == 'REST':
cjk = CharacterLookup('C')
textPinYinList = cjk.getReadingForCharacter(syl.text, 'Pinyin', toneMarkType='none')
if len(textPinYinList) > 1:
self.logger.warn("converted syllable {} has {} parts".format(textPinYinList, len(textPinYinList)))
syl.text = textPinYinList[0] # take only first variant of pinyin interpretations
### finish up sentence when punctuation present
if isEndOfSentence:
currSectionLyrics.append(syl)
self.listSentences.append(currSectionLyrics)
currSectionLyrics = []
else:
currSectionLyrics.append(syl)
def parseCurrTxtToken(self, currSyllable, syllTotalDuration, noteOrRest):
'''
discriminate between cases with or without lyrics and rest and no rest
'''
currNoteDuration = noteOrRest.duration.quarterLength * MIN_DUR_UNIT / 4
# self.logger.debug("currNoteDuration: {}".format(currNoteDuration))
# print "currNoteDuration: {}".format(currNoteDuration)
if noteOrRest.isRest:
if not (currSyllable is None) and not (syllTotalDuration is None):
if currSyllable.text == 'REST':
if not (currSyllable is None) and not (syllTotalDuration is None):
syllTotalDuration = syllTotalDuration + currNoteDuration
else:
textPinYin = 'REST'
currSyllable, syllTotalDuration = self.finishCurrentAndCreateNewSyllable(textPinYin, currSyllable, syllTotalDuration, currNoteDuration)
# '' (no lyrics at note) so still at same syllable
elif noteOrRest.isNote:
if (not noteOrRest.hasLyrics()) or (noteOrRest.hasLyrics() and noteOrRest.lyrics[0].text.strip().startswith('(') or noteOrRest.lyrics[0].text.strip()==''): # has no lyrics token. '(' is ignored
if not (currSyllable is None) and not (syllTotalDuration is None):
syllTotalDuration = syllTotalDuration + currNoteDuration
else: # has lyrics => has end of curr syllable
lyrics = noteOrRest.lyrics
if len(lyrics) > 1: # sanity check
self.logger.warn("syllable {} has {} characters".format(lyrics, len(lyrics)))
# convert to pinyin: maybe use this instead: https://pypi.python.org/pypi/pinyin/0.2.5
if len(lyrics) != 0: # skip lyrics of len 0
mandarinText = lyrics[0].text
currSyllable, syllTotalDuration = self.finishCurrentAndCreateNewSyllable(mandarinText, currSyllable, syllTotalDuration, currNoteDuration)
return currSyllable, syllTotalDuration
def finishCurrentAndCreateNewSyllable(self, textSyllable, currSyllable, syllTotalDuration, noteValue):
if not (currSyllable is None) and not (syllTotalDuration is None): # save last syllable and duration
currSyllable.setDurationInMinUnit(syllTotalDuration)
self.listSyllables.append(currSyllable)
# init next syllable and its duration
dummyNote = -1
currSyllable = SyllableJingju(textSyllable, dummyNote)
syllTotalDuration = noteValue
return currSyllable, syllTotalDuration
def getLyricsForSection(self, whichSection):
syllables = self.listSentences[whichSection]
return syllables2Lyrics(syllables)
def createWord(syllablesInCurrWord, currSyllable):
'''
create a new word ending in currect syllable
'''
currSyllable.text = currSyllable.text.rstrip()
currSyllable.setHasShortPauseAtEnd(True)
syllablesInCurrWord.append(currSyllable)
# create new word
word = Word(syllablesInCurrWord)
return word, syllablesInCurrWord