Spaces:
Runtime error
Runtime error
Upload TMIDIX.py
Browse files55 unmodified lines565758596061783 unmodified lines8458468478488498508518528538542 unmodified lines8578588598608618628638648658668678688696 unmodified lines87687787887988088188288388488588688788888989089189289389489589689789889990090190214 unmodified lines91791891992092192292392492513 unmodified lines9399409419429439449459469479489499509519529539549559569579589599609619627 unmodified lines9709719729739749759769779789799809819829839849859864 unmodified lines991992993994995996997998999100010016 unmodified lines10081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110010 unmodified lines111111121113111411151116111717 unmodified lines113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511668 unmodified lines1175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205613 unmodified lines1819182018211822182318242770 unmodified lines4595459645974598459946004601460246034604460546066 unmodified lines46134614461546164617461846194620462146224623462439 unmodified lines46644665466646674668466946703186 unmodified lines78577858785978607861786278637864786578667867786878697870787178727873787478751169 unmodified lines904590469047904890499050905155 unmodified lines_previous_warning = '' # 5.4_previous_times = 0 # 5.4#------------------------------- Encoding stuff --------------------------def opus2midi(opus=[], text_encoding='ISO-8859-1'):783 unmodified linesr'''Given a bytearray, returns a tuple of (the ber-integer at thestart, and the remainder of the bytearray).'''if not len(ba): # 6.7_warn('_unshift_ber_int: no integer found')return ((0, b""))byte = ba.pop(0)integer = 0while True:integer += (byte & 0x7F)2 unmodified linesif not len(ba):_warn('_unshift_ber_int: no end-of-integer found')return ((0, ba))byte = ba.pop(0)integer <<= 7def _clean_up_warnings(): # 5.4# Call this before returning from any publicly callable function# whenever there's a possibility that a warning might have been printed# by the function, or by any private functions it might have called.global _previous_timesglobal _previous_warningif _previous_times > 1:6 unmodified lines_previous_times = 0_previous_warning = ''def _warn(s=''):global _previous_timesglobal _previous_warningif s == _previous_warning: # 5.4_previous_times = _previous_times + 1else:_clean_up_warnings()sys.stderr.write(str(s)+"\n")_previous_warning = sdef _some_text_event(which_kind=0x01, text=b'some_text', text_encoding='ISO-8859-1'):if str(type(text)).find("'str'") >= 0: # 6.4 test for back-compatibilitydata = bytes(text, encoding=text_encoding)else:data = bytes(text)return b'\xFF'+bytes((which_kind,))+_ber_compressed_int(len(data))+datadef _consistentise_ticks(scores): # 3.6# used by mix_scores, merge_scores, concatenate_scoresif len(scores) == 1:return copy.deepcopy(scores)are_consistent = Trueticks = scores[0][0]iscore = 114 unmodified lines###########################################################################def _decode(trackdata=b'', exclude=None, include=None,event_callback=None, exclusive_event_callback=None, no_eot_magic=False):r'''Decodes MIDI track data into an opus-style list of events.The options:'exclude' is a list of event types which will be ignored SHOULD BE A SET13 unmodified linesexclude = set(exclude)# Pointer = 0; not used here; we eat through the bytearray instead.event_code = -1; # used for running statusevent_count = 0;events = []while(len(trackdata)):# loop while there's anything to analyze ...eot = False # When True, the event registrar aborts this loopevent_count += 1E = []# E for events - we'll feed it to the event registrar at the end.# Slice off the delta time code, and analyze it[time, remainder] = _unshift_ber_int(trackdata)# Now let's see what we can make of the commandfirst_byte = trackdata.pop(0) & 0xFFif (first_byte < 0xF0): # It's a MIDI eventif (first_byte & 0x80):event_code = first_byte7 unmodified linescommand = event_code & 0xF0channel = event_code & 0x0Fif (command == 0xF6): # 0-byte argumentpasselif (command == 0xC0 or command == 0xD0): # 1-byte argumentparameter = trackdata.pop(0) # could be Belse: # 2-byte argument could be BB or 14-bitparameter = (trackdata.pop(0), trackdata.pop(0))################################################################## MIDI eventsif (command == 0x80):if 'note_off' in exclude:continueE = ['note_off', time, channel, parameter[0], parameter[1]]4 unmodified lineselif (command == 0xA0):if 'key_after_touch' in exclude:continueE = ['key_after_touch',time,channel,parameter[0],parameter[1]]elif (command == 0xB0):if 'control_change' in exclude:continueE = ['control_change',time,channel,parameter[0],parameter[1]]elif (command == 0xC0):if 'patch_change' in exclude:continue6 unmodified linesif 'pitch_wheel_change' in exclude:continueE = ['pitch_wheel_change', time, channel,_read_14_bit(parameter)-0x2000]else:_warn("Shouldn't get here; command="+hex(command))elif (first_byte == 0xFF): # It's a Meta-Event! ###################[command, length, remainder] =# unpack("xCwa*", substr(trackdata, $Pointer, 6));#Pointer += 6 - len(remainder);# # Move past JUST the length-encoded.command = trackdata.pop(0) & 0xFF[length, trackdata] = _unshift_ber_int(trackdata)if (command == 0x00):if (length == 2):E = ['set_sequence_number',time,_twobytes2int(trackdata)]else:_warn('set_sequence_number: length must be 2, not '+str(length))E = ['set_sequence_number', time, 0]elif command >= 0x01 and command <= 0x0f: # Text events# 6.2 take it in bytes; let the user get the right encoding.# text_str = trackdata[0:length].decode('ascii','ignore')# text_str = trackdata[0:length].decode('ISO-8859-1')# 6.4 take it in bytes; let the user get the right encoding.text_data = bytes(trackdata[0:length]) # 6.4# Defined text eventsif (command == 0x01):E = ['text_event', time, text_data]elif (command == 0x02):E = ['copyright_text_event', time, text_data]elif (command == 0x03):E = ['track_name', time, text_data]elif (command == 0x04):E = ['instrument_name', time, text_data]elif (command == 0x05):E = ['lyric', time, text_data]elif (command == 0x06):E = ['marker', time, text_data]elif (command == 0x07):E = ['cue_point', time, text_data]# Reserved but apparently unassigned text eventselif (command == 0x08):E = ['text_event_08', time, text_data]elif (command == 0x09):E = ['text_event_09', time, text_data]elif (command == 0x0a):E = ['text_event_0a', time, text_data]elif (command == 0x0b):E = ['text_event_0b', time, text_data]elif (command == 0x0c):E = ['text_event_0c', time, text_data]elif (command == 0x0d):E = ['text_event_0d', time, text_data]elif (command == 0x0e):E = ['text_event_0e', time, text_data]elif (command == 0x0f):E = ['text_event_0f', time, text_data]# Now the sticky events -------------------------------------elif (command == 0x2F):E = ['end_track', time]# The code for handling this, oddly, comes LATER,# in the event registrar.elif (command == 0x51): # DTime, Microseconds/Crochetif length != 3:_warn('set_tempo event, but length='+str(length))E = ['set_tempo', time,struct.unpack(">I", b'\x00'+trackdata[0:3])[0]]elif (command == 0x54):if length != 5: # DTime, HR, MN, SE, FR, FF_warn('smpte_offset event, but length='+str(length))E = ['smpte_offset',time] + list(struct.unpack(">BBBBB",trackdata[0:5]))elif (command == 0x58):if length != 4: # DTime, NN, DD, CC, BB_warn('time_signature event, but length='+str(length))E = ['time_signature', time]+list(trackdata[0:4])elif (command == 0x59):if length != 2: # DTime, SF(signed), MI_warn('key_signature event, but length='+str(length))E = ['key_signature',time] + list(struct.unpack(">bB",trackdata[0:2]))elif (command == 0x7F): # 6.4E = ['sequencer_specific',time, bytes(trackdata[0:length])]else:E = ['raw_meta_event', time, command,bytes(trackdata[0:length])] # 6.0#"[uninterpretable meta-event command of length length]"# DTime, Command, Binary Data# It's uninterpretable; record it as raw_data.# Pointer += length; # Now move Pointertrackdata = trackdata[length:]10 unmodified lines# is omitted if this is a non-final block in a multiblock sysex;# but the F7 (if there) is counted in the message's declared# length, so we don't have to think about it anyway.)#command = trackdata.pop(0)[length, trackdata] = _unshift_ber_int(trackdata)if first_byte == 0xF0:# 20091008 added ISO-8859-1 to get an 8-bit str17 unmodified lines# from the MIDI file spec. So, I'm going to assume that# they CAN, in practice, occur. I don't know whether it's# proper for you to actually emit these into a MIDI file.elif (first_byte == 0xF2): # DTime, Beats# <song position msg> ::= F2 <data pair>E = ['song_position', time, _read_14_bit(trackdata[:2])]trackdata = trackdata[2:]elif (first_byte == 0xF3): # <song select msg> ::= F3 <data singlet># E = ['song_select', time, struct.unpack('>B',trackdata.pop(0))[0]]E = ['song_select', time, trackdata[0]]trackdata = trackdata[1:]# DTime, Thing (what?! song number? whatever ...)elif (first_byte == 0xF6): # DTimeE = ['tune_request', time]# What would a tune request be doing in a MIDI /file/?########################################################## ADD MORE META-EVENTS HERE. TODO:# f1 -- MTC Quarter Frame Message. One data byte follows# the Status; it's the time code value, from 0 to 127.# f8 -- MIDI clock. no data.# fa -- MIDI start. no data.# fb -- MIDI continue. no data.# fc -- MIDI stop. no data.# fe -- Active sense. no data.# f4 f5 f9 fd -- unallocatedr'''elif (first_byte > 0xF0) { # Some unknown kinda F-series event ####8 unmodified lineselif first_byte > 0xF0: # Some unknown F-series event# Here we only produce a one-byte piece of raw data.# E = ['raw_data', time, bytest(trackdata[0])] # 6.4E = ['raw_data', time, trackdata[0]] # 6.4 6.7trackdata = trackdata[1:]else: # Fallthru._warn("Aborting track. Command-byte first_byte="+hex(first_byte))break# End of the big if-group####################################################################### THE EVENT REGISTRAR...if E and (E[0] == 'end_track'):# This is the code for exceptional handling of the EOT event.eot = Trueif not no_eot_magic:if E[1] > 0: # a null text-event to carry the delta-timeE = ['text_event', E[1], '']else:E = [] # EOT with a delta-time of 0; ignore it.if E and not (E[0] in exclude):#if ( $exclusive_event_callback ):# &{ $exclusive_event_callback }( @E );#else:# &{ $event_callback }( @E ) if $event_callback;events.append(E)if eot:break613 unmodified linesplt.close()if return_plt:return figplt.show()2770 unmodified lines###################################################################################def check_and_fix_tones_chord(tones_chord):tones_chord_combs = [list(comb) for i in range(len(tones_chord), 0, -1) for comb in combinations(tones_chord, i)]for c in tones_chord_combs:if c in ALL_CHORDS_FULL:checked_tones_chord = cbreak6 unmodified lines###################################################################################def advanced_check_and_fix_tones_chord(tones_chord, high_pitch=0):tones_chord_combs = [list(comb) for i in range(len(tones_chord), 0, -1) for comb in combinations(tones_chord, i)]for c in tones_chord_combs:if c in ALL_CHORDS_FULL:tchord = cif 0 < high_pitch < 128 and len(tchord) == 1:39 unmodified linespitch_shift=0,ceil_timings=False,round_timings=False,legacy_timings=False):esn = copy.deepcopy(enhanced_score_notes)3186 unmodified lineschord = []for cc in c:if cc[pitches_index] not in seen:if cc[channels_index] != 9:cc[channels_index] = 0cc[patches_index] = 0chord.append(cc)seen.append(cc[pitches_index])else:if keep_drums:chord.append(cc)seen.append(cc[pitches_index])sp_escore_notes.append(chord)1169 unmodified lineselse:return None##################################################################################### This is the end of the TMIDI X Python module#55 unmodified lines5657585960616263783 unmodified lines8478488498508518528538548558568572 unmodified lines8608618628638648658668678688698708718728738748758766 unmodified lines88388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391414 unmodified lines92993093193293393493593613 unmodified lines9509519529539549559569579589599609619629639649659669679689699709719729737 unmodified lines9819829839849859869879889899909919929939949959969979989994 unmodified lines100410051006100710081009101010111012101310146 unmodified lines102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111410 unmodified lines112511261127112811291130113117 unmodified lines114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911808 unmodified lines118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218613 unmodified lines18321833183418351836183718382770 unmodified lines4609461046114612461346144615461646174618461946204621462246234624462546266 unmodified lines46334634463546364637463846394640464146424643464446454646464746484649465039 unmodified lines46904691469246934694469546963186 unmodified lines7883788478857886788778887889789078917892789378947895789678977898789979007901790279031169 unmodified lines907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926255 unmodified lines_previous_warning = '' # 5.4_previous_times = 0 # 5.4_no_warning = False#------------------------------- Encoding stuff --------------------------def opus2midi(opus=[], text_encoding='ISO-8859-1'):783 unmodified linesr'''Given a bytearray, returns a tuple of (the ber-integer at thestart, and the remainder of the bytearray).'''if not len(ba): # 6.7_warn('_unshift_ber_int: no integer found')return ((0, b""))byte = ba[0]ba = ba[1:]integer = 0while True:integer += (byte & 0x7F)2 unmodified linesif not len(ba):_warn('_unshift_ber_int: no end-of-integer found')return ((0, ba))byte = ba[0]ba = ba[1:]integer <<= 7def _clean_up_warnings(): # 5.4# Call this before returning from any publicly callable function# whenever there's a possibility that a warning might have been printed# by the function, or by any private functions it might have called.if _no_warning:returnglobal _previous_timesglobal _previous_warningif _previous_times > 1:6 unmodified lines_previous_times = 0_previous_warning = ''def _warn(s=''):if _no_warning:returnglobal _previous_timesglobal _previous_warningif s == _previous_warning: # 5.4_previous_times = _previous_times + 1else:_clean_up_warnings()sys.stderr.write(str(s) + "\n")_previous_warning = sdef _some_text_event(which_kind=0x01, text=b'some_text', text_encoding='ISO-8859-1'):if str(type(text)).find("'str'") >= 0: # 6.4 test for back-compatibilitydata = bytes(text, encoding=text_encoding)else:data = bytes(text)return b'\xFF' + bytes((which_kind,)) + _ber_compressed_int(len(data)) + datadef _consistentise_ticks(scores): # 3.6# used by mix_scores, merge_scores, concatenate_scoresif len(scores) == 1:return copy.deepcopy(scores)are_consistent = Trueticks = scores[0][0]iscore = 114 unmodified lines###########################################################################def _decode(trackdata=b'', exclude=None, include=None,event_callback=None, exclusive_event_callback=None, no_eot_magic=False):r'''Decodes MIDI track data into an opus-style list of events.The options:'exclude' is a list of event types which will be ignored SHOULD BE A SET13 unmodified linesexclude = set(exclude)# Pointer = 0; not used here; we eat through the bytearray instead.event_code = -1; # used for running statusevent_count = 0;events = []while (len(trackdata)):# loop while there's anything to analyze ...eot = False # When True, the event registrar aborts this loopevent_count += 1E = []# E for events - we'll feed it to the event registrar at the end.# Slice off the delta time code, and analyze it[time, trackdata] = _unshift_ber_int(trackdata)# Now let's see what we can make of the commandfirst_byte = trackdata[0] & 0xFFtrackdata = trackdata[1:]if (first_byte < 0xF0): # It's a MIDI eventif (first_byte & 0x80):event_code = first_byte7 unmodified linescommand = event_code & 0xF0channel = event_code & 0x0Fif (command == 0xF6): # 0-byte argumentpasselif (command == 0xC0 or command == 0xD0): # 1-byte argumentparameter = trackdata[0] # could be Btrackdata = trackdata[1:]else: # 2-byte argument could be BB or 14-bitparameter = (trackdata[0], trackdata[1])trackdata = trackdata[2:]################################################################## MIDI eventsif (command == 0x80):if 'note_off' in exclude:continueE = ['note_off', time, channel, parameter[0], parameter[1]]4 unmodified lineselif (command == 0xA0):if 'key_after_touch' in exclude:continueE = ['key_after_touch', time, channel, parameter[0], parameter[1]]elif (command == 0xB0):if 'control_change' in exclude:continueE = ['control_change', time, channel, parameter[0], parameter[1]]elif (command == 0xC0):if 'patch_change' in exclude:continue6 unmodified linesif 'pitch_wheel_change' in exclude:continueE = ['pitch_wheel_change', time, channel,_read_14_bit(parameter) - 0x2000]else:_warn("Shouldn't get here; command=" + hex(command))elif (first_byte == 0xFF): # It's a Meta-Event! ################### [command, length, remainder] =# unpack("xCwa*", substr(trackdata, $Pointer, 6));# Pointer += 6 - len(remainder);# # Move past JUST the length-encoded.command = trackdata[0] & 0xFFtrackdata = trackdata[1:][length, trackdata] = _unshift_ber_int(trackdata)if (command == 0x00):if (length == 2):E = ['set_sequence_number', time, _twobytes2int(trackdata)]else:_warn('set_sequence_number: length must be 2, not ' + str(length))E = ['set_sequence_number', time, 0]elif command >= 0x01 and command <= 0x0f: # Text events# 6.2 take it in bytes; let the user get the right encoding.# text_str = trackdata[0:length].decode('ascii','ignore')# text_str = trackdata[0:length].decode('ISO-8859-1')# 6.4 take it in bytes; let the user get the right encoding.text_data = bytes(trackdata[0:length]) # 6.4# Defined text eventsif (command == 0x01):E = ['text_event', time, text_data]elif (command == 0x02):E = ['copyright_text_event', time, text_data]elif (command == 0x03):E = ['track_name', time, text_data]elif (command == 0x04):E = ['instrument_name', time, text_data]elif (command == 0x05):E = ['lyric', time, text_data]elif (command == 0x06):E = ['marker', time, text_data]elif (command == 0x07):E = ['cue_point', time, text_data]# Reserved but apparently unassigned text eventselif (command == 0x08):E = ['text_event_08', time, text_data]elif (command == 0x09):E = ['text_event_09', time, text_data]elif (command == 0x0a):E = ['text_event_0a', time, text_data]elif (command == 0x0b):E = ['text_event_0b', time, text_data]elif (command == 0x0c):E = ['text_event_0c', time, text_data]elif (command == 0x0d):E = ['text_event_0d', time, text_data]elif (command == 0x0e):E = ['text_event_0e', time, text_data]elif (command == 0x0f):E = ['text_event_0f', time, text_data]# Now the sticky events -------------------------------------elif (command == 0x2F):E = ['end_track', time]# The code for handling this, oddly, comes LATER,# in the event registrar.elif (command == 0x51): # DTime, Microseconds/Crochetif length != 3:_warn('set_tempo event, but length=' + str(length))E = ['set_tempo', time,struct.unpack(">I", b'\x00' + trackdata[0:3])[0]]elif (command == 0x54):if length != 5: # DTime, HR, MN, SE, FR, FF_warn('smpte_offset event, but length=' + str(length))E = ['smpte_offset', time] + list(struct.unpack(">BBBBB", trackdata[0:5]))elif (command == 0x58):if length != 4: # DTime, NN, DD, CC, BB_warn('time_signature event, but length=' + str(length))E = ['time_signature', time] + list(trackdata[0:4])elif (command == 0x59):if length != 2: # DTime, SF(signed), MI_warn('key_signature event, but length=' + str(length))E = ['key_signature', time] + list(struct.unpack(">bB", trackdata[0:2]))elif (command == 0x7F): # 6.4E = ['sequencer_specific', time, bytes(trackdata[0:length])]else:E = ['raw_meta_event', time, command,bytes(trackdata[0:length])] # 6.0# "[uninterpretable meta-event command of length length]"# DTime, Command, Binary Data# It's uninterpretable; record it as raw_data.# Pointer += length; # Now move Pointertrackdata = trackdata[length:]10 unmodified lines# is omitted if this is a non-final block in a multiblock sysex;# but the F7 (if there) is counted in the message's declared# length, so we don't have to think about it anyway.)# command = trackdata.pop(0)[length, trackdata] = _unshift_ber_int(trackdata)if first_byte == 0xF0:# 20091008 added ISO-8859-1 to get an 8-bit str17 unmodified lines# from the MIDI file spec. So, I'm going to assume that# they CAN, in practice, occur. I don't know whether it's# proper for you to actually emit these into a MIDI file.elif (first_byte == 0xF2): # DTime, Beats# <song position msg> ::= F2 <data pair>E = ['song_position', time, _read_14_bit(trackdata[:2])]trackdata = trackdata[2:]elif (first_byte == 0xF3): # <song select msg> ::= F3 <data singlet># E = ['song_select', time, struct.unpack('>B',trackdata.pop(0))[0]]E = ['song_select', time, trackdata[0]]trackdata = trackdata[1:]# DTime, Thing (what?! song number? whatever ...)elif (first_byte == 0xF6): # DTimeE = ['tune_request', time]# What would a tune request be doing in a MIDI /file/?########################################################## ADD MORE META-EVENTS HERE. TODO:# f1 -- MTC Quarter Frame Message. One data byte follows# the Status; it's the time code value, from 0 to 127.# f8 -- MIDI clock. no data.# fa -- MIDI start. no data.# fb -- MIDI continue. no data.# fc -- MIDI stop. no data.# fe -- Active sense. no data.# f4 f5 f9 fd -- unallocatedr'''elif (first_byte > 0xF0) { # Some unknown kinda F-series event ####8 unmodified lineselif first_byte > 0xF0: # Some unknown F-series event# Here we only produce a one-byte piece of raw data.# E = ['raw_data', time, bytest(trackdata[0])] # 6.4E = ['raw_data', time, trackdata[0]] # 6.4 6.7trackdata = trackdata[1:]else: # Fallthru._warn("Aborting track. Command-byte first_byte=" + hex(first_byte))break# End of the big if-group####################################################################### THE EVENT REGISTRAR...if E and (E[0] == 'end_track'):# This is the code for exceptional handling of the EOT event.eot = Trueif not no_eot_magic:if E[1] > 0: # a null text-event to carry the delta-timeE = ['text_event', E[1], '']else:E = [] # EOT with a delta-time of 0; ignore it.if E and not (E[0] in exclude):# if ( $exclusive_event_callback ):# &{ $exclusive_event_callback }( @E );# else:# &{ $event_callback }( @E ) if $event_callback;events.append(E)if eot:break613 unmodified linesplt.close()if return_plt:plt.close(fig)return figplt.show()2770 unmodified lines###################################################################################def check_and_fix_tones_chord(tones_chord, use_full_chords=True):tones_chord_combs = [list(comb) for i in range(len(tones_chord), 0, -1) for comb in combinations(tones_chord, i)]if use_full_chords:CHORDS = ALL_CHORDS_FULLelse:CHORDS = ALL_CHORDS_SORTEDfor c in tones_chord_combs:if c in CHORDS:checked_tones_chord = cbreak6 unmodified lines###################################################################################def advanced_check_and_fix_tones_chord(tones_chord, high_pitch=0, use_full_chords=True):tones_chord_combs = [list(comb) for i in range(len(tones_chord), 0, -1) for comb in combinations(tones_chord, i)]if use_full_chords:CHORDS = ALL_CHORDS_FULLelse:CHORDS = ALL_CHORDS_SORTEDfor c in tones_chord_combs:if c in CHORDS:tchord = cif 0 < high_pitch < 128 and len(tchord) == 1:39 unmodified linespitch_shift=0,ceil_timings=False,round_timings=False,legacy_timings=True):esn = copy.deepcopy(enhanced_score_notes)3186 unmodified lineschord = []for cc in c:if cc[channels_index] != 9:if cc[pitches_index] not in seen:cc[channels_index] = 0cc[patches_index] = 0chord.append(cc)seen.append(cc[pitches_index])else:if keep_drums:if cc[pitches_index]+128 not in seen:chord.append(cc)seen.append(cc[pitches_index]+128)sp_escore_notes.append(chord)1169 unmodified lineselse:return None###################################################################################def escore_notes_durations_counter(escore_notes,min_duration=0,durations_index=2,channels_index=3):escore = [e for e in escore_notes if e[channels_index] != 9]durs = [e[durations_index] for e in escore if e[durations_index] >= min_duration]zero_durs = sum([1 for e in escore if e[durations_index] == 0])return [len(durs), len(escore), zero_durs, Counter(durs).most_common()]###################################################################################def count_bad_chords_in_chordified_score(chordified_score,pitches_index=4,patches_index=6,max_patch=127,use_full_chords=False):if use_full_chords:CHORDS = ALL_CHORDS_FULLelse:CHORDS = ALL_CHORDS_SORTEDbad_chords_count = 0for c in chordified_score:cpitches = [e[pitches_index] for e in c if e[patches_index] <= max_patch]tones_chord = sorted(set([p % 12 for p in cpitches]))if tones_chord:if tones_chord not in CHORDS:bad_chords_count += 1return [bad_chords_count, len(chordified_score)]###################################################################################def needleman_wunsch_aligner(seq1,seq2,align_idx,gap_penalty=-1,match_score=2,mismatch_penalty=-1):n = len(seq1)m = len(seq2)score_matrix = [[0] * (m + 1) for _ in range(n + 1)]for i in range(1, n + 1):score_matrix[i][0] = gap_penalty * ifor j in range(1, m + 1):score_matrix[0][j] = gap_penalty * jfor i in range(1, n + 1):for j in range(1, m + 1):match = score_matrix[i-1][j-1] + (match_score if seq1[i-1][align_idx] == seq2[j-1][align_idx] else mismatch_penalty)delete = score_matrix[i-1][j] + gap_penaltyinsert = score_matrix[i][j-1] + gap_penaltyscore_matrix[i][j] = max(match, delete, insert)align1, align2 = [], []i, j = n, mwhile i > 0 and j > 0:score = score_matrix[i][j]score_diag = score_matrix[i-1][j-1]score_up = score_matrix[i-1][j]score_left = score_matrix[i][j-1]if score == score_diag + (match_score if seq1[i-1][align_idx] == seq2[j-1][align_idx] else mismatch_penalty):align1.append(seq1[i-1])align2.append(seq2[j-1])i -= 1j -= 1elif score == score_up + gap_penalty:align1.append(seq1[i-1])align2.append([None] * 6)i -= 1elif score == score_left + gap_penalty:align1.append([None] * 6)align2.append(seq2[j-1])j -= 1while i > 0:align1.append(seq1[i-1])align2.append([None] * 6)i -= 1while j > 0:align1.append([None] * 6)align2.append(seq2[j-1])j -= 1align1.reverse()align2.reverse()return align1, align2###################################################################################def align_escore_notes_to_escore_notes(src_escore_notes,trg_escore_notes,recalculate_scores_timings=True,pitches_idx=4):if recalculate_scores_timings:src_escore_notes = recalculate_score_timings(src_escore_notes)trg_escore_notes = recalculate_score_timings(trg_escore_notes)src_align1, trg_align2 = needleman_wunsch_aligner(src_escore_notes, trg_escore_notes, pitches_idx)aligned_scores = [[al[0], al[1]] for al in zip(src_align1, trg_align2) if al[0][0] is not None and al[1][0] is not None]return aligned_scores###################################################################################def t_to_n(arr, si, t):ct = 0ci = siwhile ct + arr[ci][1] < t and ci < len(arr)-1:ct += arr[ci][1]ci += 1return ci+1###################################################################################def max_sum_chunk_idxs(arr, t=255):n = t_to_n(arr, 0, t)if n > len(arr):return [0, n]max_sum = 0max_sum_start_index = 0max_sum_start_idxs = [0, len(arr), sum([a[0] for a in arr])]for i in range(len(arr)):n = t_to_n(arr, i, t)current_sum = sum([a[0] for a in arr[i:n]])current_time = sum([a[1] for a in arr[i:n]])if current_sum > max_sum and current_time <= t:max_sum = current_summax_sum_start_idxs = [i, n, max_sum]return max_sum_start_idxs###################################################################################def find_highest_density_escore_notes_chunk(escore_notes, max_chunk_time=512):dscore = delta_score_notes(escore_notes)cscore = chordify_score([d[1:] for d in dscore])notes_counts = [[len(c), c[0][0]] for c in cscore]msc_idxs = max_sum_chunk_idxs(notes_counts, max_chunk_time)chunk_dscore = [['note'] + c for c in flatten(cscore[msc_idxs[0]:msc_idxs[1]])]chunk_escore = recalculate_score_timings(delta_score_to_abs_score(chunk_dscore))return chunk_escore##################################################################################### This is the end of the TMIDI X Python module#
TMIDIX.py+324-113