Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
- TMIDIX.py+60-5
- midi_to_colab_audio.py+171-115
1460 unmodified lines1461146214631464146514662385 unmodified lines3852385338543855385638573858122 unmodified lines3981398239833984398539863987439 unmodified lines44274428442944304431443244334434443544364437443834 unmodified lines447344744475447644774478447927 unmodified lines4507450845094510451145121460 unmodified linesfrom itertools import zip_longestfrom itertools import groupbyfrom operator import itemgetter2385 unmodified lines[2, 5, 7, 9, 11], [1, 3, 5, 7, 10], [0, 2, 4, 7, 10], [1, 3, 5, 7, 9],[1, 3, 5, 9, 11], [1, 5, 7, 9, 11], [1, 3, 7, 9, 11], [3, 5, 7, 9, 11],[2, 4, 6, 8, 10], [0, 4, 6, 8, 10], [0, 2, 6, 8, 10], [1, 3, 5, 7, 11],[0, 2, 4, 8, 10], [0, 2, 4, 6, 8], [0, 2, 4, 6, 10]]def find_exact_match_variable_length(list_of_lists, target_list, uncertain_indices):# Infer possible values for each uncertain index122 unmodified lines###################################################################################ALL_CHORDS_GROUPED = [[[0, 2, 5, 7, 10], [0, 2, 4, 7, 9], [0, 2, 5, 7, 9], [1, 4, 6, 9, 11],[1, 3, 6, 8, 11], [1, 3, 6, 8, 10], [1, 4, 6, 8, 11], [1, 3, 5, 8, 10],[2, 4, 6, 9, 11], [2, 4, 7, 9, 11], [0, 3, 5, 7, 10], [0, 3, 5, 8, 10],439 unmodified linesdeterministic_matching = False):if not deterministic_matching:random.shuffle(texts)clean_texts = []for t in texts:text_words_list = [at.split(chr(32)) for at in t.split(chr(10))]clean_text_words_list = []34 unmodified linesif texts_match_ratios:max_text_match_ratio = max(texts_match_ratios)max_match_ratio_text = texts[texts_match_ratios.index(max_text_match_ratio)]max_text_words_match_indexes = words_match_indexes[texts_match_ratios.index(max_text_match_ratio)]return [max_match_ratio_text, max_text_match_ratio, max_text_words_match_indexes]27 unmodified lines#################################################################################### This is the end of the TMIDI X Python module###################################################################################1460 unmodified lines14611462146314641465146614672385 unmodified lines38533854385538563857385838593860122 unmodified lines3983398439853986398739883989439 unmodified lines44294430443144324433443444354436443744384439444044414442444334 unmodified lines447844794480448144824483448427 unmodified lines451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645671460 unmodified linesfrom itertools import zip_longestfrom itertools import groupbyfrom collections import Counterfrom operator import itemgetter2385 unmodified lines[2, 5, 7, 9, 11], [1, 3, 5, 7, 10], [0, 2, 4, 7, 10], [1, 3, 5, 7, 9],[1, 3, 5, 9, 11], [1, 5, 7, 9, 11], [1, 3, 7, 9, 11], [3, 5, 7, 9, 11],[2, 4, 6, 8, 10], [0, 4, 6, 8, 10], [0, 2, 6, 8, 10], [1, 3, 5, 7, 11],[0, 2, 4, 8, 10], [0, 2, 4, 6, 8], [0, 2, 4, 6, 10], [0, 2, 4, 6, 8, 10],[1, 3, 5, 7, 9, 11]]def find_exact_match_variable_length(list_of_lists, target_list, uncertain_indices):# Infer possible values for each uncertain index122 unmodified lines###################################################################################ALL_CHORDS_GROUPED = [[[1, 3, 5, 7, 9, 11], [0, 2, 4, 6, 8, 10]],[[0, 2, 5, 7, 10], [0, 2, 4, 7, 9], [0, 2, 5, 7, 9], [1, 4, 6, 9, 11],[1, 3, 6, 8, 11], [1, 3, 6, 8, 10], [1, 4, 6, 8, 11], [1, 3, 5, 8, 10],[2, 4, 6, 9, 11], [2, 4, 7, 9, 11], [0, 3, 5, 7, 10], [0, 3, 5, 8, 10],439 unmodified linesdeterministic_matching = False):texts_copy = textsif not deterministic_matching:texts_copy = copy.deepcopy(texts)random.shuffle(texts_copy)clean_texts = []for t in texts_copy:text_words_list = [at.split(chr(32)) for at in t.split(chr(10))]clean_text_words_list = []34 unmodified linesif texts_match_ratios:max_text_match_ratio = max(texts_match_ratios)max_match_ratio_text = texts_copy[texts_match_ratios.index(max_text_match_ratio)]max_text_words_match_indexes = words_match_indexes[texts_match_ratios.index(max_text_match_ratio)]return [max_match_ratio_text, max_text_match_ratio, max_text_words_match_indexes]27 unmodified lines###################################################################################def check_and_fix_tones_chord(tones_chord):lst = tones_chordif len(lst) == 2:if lst[1] - lst[0] == 1:return [lst[-1]]else:if 0 in lst and 11 in lst:lst.remove(0)return lstnon_consecutive = [lst[0]]if len(lst) > 2:for i in range(1, len(lst) - 1):if lst[i-1] + 1 != lst[i] and lst[i] + 1 != lst[i+1]:non_consecutive.append(lst[i])non_consecutive.append(lst[-1])if 0 in non_consecutive and 11 in non_consecutive:non_consecutive.remove(0)return non_consecutive###################################################################################def create_similarity_matrix(list_of_values, matrix_length=0):counts = Counter(list_of_values).items()if matrix_length > 0:sim_matrix = [0] * max(matrix_length, len(list_of_values))else:sim_matrix = [0] * len(counts)for c in counts:sim_matrix[c[0]] = c[1]similarity_matrix = [[0] * len(sim_matrix) for _ in range(len(sim_matrix))]for i in range(len(sim_matrix)):for j in range(len(sim_matrix)):if max(sim_matrix[i], sim_matrix[j]) != 0:similarity_matrix[i][j] = min(sim_matrix[i], sim_matrix[j]) / max(sim_matrix[i], sim_matrix[j])return similarity_matrix, sim_matrix#################################################################################### This is the end of the TMIDI X Python module###################################################################################
123442 unmodified lines474849505152532820 unmodified lines2874287528762877287828792880288128822883288428853 unmodified lines288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529568 unmodified lines296529662967296829692970297129721 unmodified line2974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034#===================================================================================================================## MIDI to Colab AUdio Python Module#42 unmodified lines# could break compatiblity, but there's not much else you can do to fix the bug# https://en.wikipedia.org/wiki/Shift_JISr'''This module offers functions: concatenate_scores(), grep(),merge_scores(), mix_scores(), midi2opus(), midi2score(), opus2midi(),opus2score(), play_score(), score2midi(), score2opus(), score2stats(),2820 unmodified lines#===============================================================================import numpy as npdef midi_opus_to_colab_audio(midi_opus,soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',sample_rate=16000, # 44100volume_scale=10,output_for_gradio=False):def normalize_volume(matrix, factor=10):3 unmodified linesfinal_matrix = np.clip(mult_matrix, -1.0, 1.0)return final_matrixticks_per_beat = midi_opus[0]event_list = []for track_idx, track in enumerate(midi_opus[1:]):abs_t = 0for event in track:abs_t += event[1]event_new = [*event]event_new[1] = abs_tevent_list.append(event_new)event_list = sorted(event_list, key=lambda e: e[1])tempo = int((60 / 120) * 10 ** 6) # default 120 bpmss = np.empty((0, 2), dtype=np.int16)fl = Synth(samplerate=float(sample_rate))sfid = fl.sfload(soundfont_path)last_t = 0for c in range(16):fl.program_select(c, sfid, 128 if c == 9 else 0, 0)for event in event_list:name = event[0]sample_len = int(((event[1] / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)sample_len -= int(((last_t / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)last_t = event[1]if sample_len > 0:sample = fl.get_samples(sample_len).reshape(sample_len, 2)ss = np.concatenate([ss, sample])if name == "set_tempo":tempo = event[2]elif name == "patch_change":c, p = event[2:4]fl.program_select(c, sfid, 128 if c == 9 else 0, p)elif name == "control_change":c, cc, v = event[2:5]fl.cc(c, cc, v)elif name == "note_on" and event[3] > 0:c, p, v = event[2:5]fl.noteon(c, p, v)elif name == "note_off" or (name == "note_on" and event[3] == 0):c, p = event[2:4]fl.noteoff(c, p)fl.delete()if ss.shape[0] > 0:max_val = np.abs(ss).max()if max_val != 0:ss = (ss / max_val) * np.iinfo(np.int16).maxss = ss.astype(np.int16)ss = ss.swapaxes(1, 0)raw_audio = normalize_volume(ss, volume_scale)if output_for_gradio:raw_audio = np.transpose(raw_audio)return raw_audiodef midi_to_colab_audio(midi_file,soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',sample_rate=16000, # 44100volume_scale=10,output_for_gradio=False):'''8 unmodified lines'''midi_opus = midi2opus(open(midi_file, 'rb').read())def normalize_volume(matrix, factor=10):norm = np.linalg.norm(matrix)matrix = matrix/norm # normalized matrix1 unmodified linefinal_matrix = np.clip(mult_matrix, -1.0, 1.0)return final_matrixticks_per_beat = midi_opus[0]event_list = []for track_idx, track in enumerate(midi_opus[1:]):abs_t = 0for event in track:abs_t += event[1]event_new = [*event]event_new[1] = abs_tevent_list.append(event_new)event_list = sorted(event_list, key=lambda e: e[1])tempo = int((60 / 120) * 10 ** 6) # default 120 bpmss = np.empty((0, 2), dtype=np.int16)fl = Synth(samplerate=float(sample_rate))sfid = fl.sfload(soundfont_path)last_t = 0for c in range(16):fl.program_select(c, sfid, 128 if c == 9 else 0, 0)for event in event_list:name = event[0]sample_len = int(((event[1] / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)sample_len -= int(((last_t / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)last_t = event[1]if sample_len > 0:sample = fl.get_samples(sample_len).reshape(sample_len, 2)ss = np.concatenate([ss, sample])if name == "set_tempo":tempo = event[2]elif name == "patch_change":c, p = event[2:4]fl.program_select(c, sfid, 128 if c == 9 else 0, p)elif name == "control_change":c, cc, v = event[2:5]fl.cc(c, cc, v)elif name == "note_on" and event[3] > 0:c, p, v = event[2:5]fl.noteon(c, p, v)elif name == "note_off" or (name == "note_on" and event[3] == 0):c, p = event[2:4]fl.noteoff(c, p)fl.delete()if ss.shape[0] > 0:max_val = np.abs(ss).max()if max_val != 0:ss = (ss / max_val) * np.iinfo(np.int16).maxss = ss.astype(np.int16)if output_for_gradio:return ssss = ss.swapaxes(1, 0)raw_audio = normalize_volume(ss, volume_scale)return raw_audio#===================================================================================================================123442 unmodified lines4748495051522820 unmodified lines28732874287528762877287828792880288128822883288428852886288728883 unmodified lines289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529868 unmodified lines2995299629972998299930001 unmodified line30023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090r'''#===================================================================================================================## MIDI to Colab AUdio Python Module#42 unmodified lines# could break compatiblity, but there's not much else you can do to fix the bug# https://en.wikipedia.org/wiki/Shift_JISThis module offers functions: concatenate_scores(), grep(),merge_scores(), mix_scores(), midi2opus(), midi2score(), opus2midi(),opus2score(), play_score(), score2midi(), score2opus(), score2stats(),2820 unmodified lines#===============================================================================import numpy as npimport wavedef midi_opus_to_colab_audio(midi_opus,soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',sample_rate=16000, # 44100volume_scale=10,trim_silence=True,silence_threshold=0.1,output_for_gradio=False,write_audio_to_WAV=''):def normalize_volume(matrix, factor=10):3 unmodified linesfinal_matrix = np.clip(mult_matrix, -1.0, 1.0)return final_matrixif midi_opus[1]:ticks_per_beat = midi_opus[0]event_list = []for track_idx, track in enumerate(midi_opus[1:]):abs_t = 0for event in track:abs_t += event[1]event_new = [*event]event_new[1] = abs_tevent_list.append(event_new)event_list = sorted(event_list, key=lambda e: e[1])tempo = int((60 / 120) * 10 ** 6) # default 120 bpmss = np.empty((0, 2), dtype=np.int16)fl = Synth(samplerate=float(sample_rate))sfid = fl.sfload(soundfont_path)last_t = 0for c in range(16):fl.program_select(c, sfid, 128 if c == 9 else 0, 0)for event in event_list:name = event[0]sample_len = int(((event[1] / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)sample_len -= int(((last_t / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)last_t = event[1]if sample_len > 0:sample = fl.get_samples(sample_len).reshape(sample_len, 2)ss = np.concatenate([ss, sample])if name == "set_tempo":tempo = event[2]elif name == "patch_change":c, p = event[2:4]fl.program_select(c, sfid, 128 if c == 9 else 0, p)elif name == "control_change":c, cc, v = event[2:5]fl.cc(c, cc, v)elif name == "note_on" and event[3] > 0:c, p, v = event[2:5]fl.noteon(c, p, v)elif name == "note_off" or (name == "note_on" and event[3] == 0):c, p = event[2:4]fl.noteoff(c, p)fl.delete()if ss.shape[0] > 0:max_val = np.abs(ss).max()if max_val != 0:ss = (ss / max_val) * np.iinfo(np.int16).maxss = ss.astype(np.int16)if trim_silence:threshold = np.std(np.abs(ss)) * silence_thresholdexceeded_thresh = np.abs(ss) > thresholdif np.any(exceeded_thresh):last_idx = np.where(exceeded_thresh)[0][-1]ss = ss[:last_idx+1]if output_for_gradio:return ssss = ss.swapaxes(1, 0)raw_audio = normalize_volume(ss, volume_scale)if write_audio_to_WAV != '':r_audio = raw_audio.Tr_audio = np.int16(r_audio / np.max(np.abs(r_audio)) * 32767)with wave.open(write_audio_to_WAV, 'w') as wf:wf.setframerate(sample_rate)wf.setsampwidth(2)wf.setnchannels(r_audio.shape[1])wf.writeframes(r_audio)return raw_audioelse:return Nonedef midi_to_colab_audio(midi_file,soundfont_path='/usr/share/sounds/sf2/FluidR3_GM.sf2',sample_rate=16000, # 44100volume_scale=10,trim_silence=True,silence_threshold=0.1,output_for_gradio=False,write_audio_to_WAV=False):'''8 unmodified lines'''def normalize_volume(matrix, factor=10):norm = np.linalg.norm(matrix)matrix = matrix/norm # normalized matrix1 unmodified linefinal_matrix = np.clip(mult_matrix, -1.0, 1.0)return final_matrixmidi_opus = midi2opus(open(midi_file, 'rb').read())if midi_opus[1]:ticks_per_beat = midi_opus[0]event_list = []for track_idx, track in enumerate(midi_opus[1:]):abs_t = 0for event in track:abs_t += event[1]event_new = [*event]event_new[1] = abs_tevent_list.append(event_new)event_list = sorted(event_list, key=lambda e: e[1])tempo = int((60 / 120) * 10 ** 6) # default 120 bpmss = np.empty((0, 2), dtype=np.int16)fl = Synth(samplerate=float(sample_rate))sfid = fl.sfload(soundfont_path)last_t = 0for c in range(16):fl.program_select(c, sfid, 128 if c == 9 else 0, 0)for event in event_list:name = event[0]sample_len = int(((event[1] / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)sample_len -= int(((last_t / ticks_per_beat) * tempo / (10 ** 6)) * sample_rate)last_t = event[1]if sample_len > 0:sample = fl.get_samples(sample_len).reshape(sample_len, 2)ss = np.concatenate([ss, sample])if name == "set_tempo":tempo = event[2]elif name == "patch_change":c, p = event[2:4]fl.program_select(c, sfid, 128 if c == 9 else 0, p)elif name == "control_change":c, cc, v = event[2:5]fl.cc(c, cc, v)elif name == "note_on" and event[3] > 0:c, p, v = event[2:5]fl.noteon(c, p, v)elif name == "note_off" or (name == "note_on" and event[3] == 0):c, p = event[2:4]fl.noteoff(c, p)fl.delete()if ss.shape[0] > 0:max_val = np.abs(ss).max()if max_val != 0:ss = (ss / max_val) * np.iinfo(np.int16).maxss = ss.astype(np.int16)if trim_silence:threshold = np.std(np.abs(ss)) * silence_thresholdexceeded_thresh = np.abs(ss) > thresholdif np.any(exceeded_thresh):last_idx = np.where(exceeded_thresh)[0][-1]ss = ss[:last_idx+1]if output_for_gradio:return ssss = ss.swapaxes(1, 0)raw_audio = normalize_volume(ss, volume_scale)if write_audio_to_WAV:filename = midi_file.split('.')[-2] + '.wav'r_audio = raw_audio.Tr_audio = np.int16(r_audio / np.max(np.abs(r_audio)) * 32767)with wave.open(filename, 'w') as wf:wf.setframerate(sample_rate)wf.setsampwidth(2)wf.setnchannels(r_audio.shape[1])wf.writeframes(r_audio)return raw_audioelse:return None#===================================================================================================================
TMIDIX.py+60-5
midi_to_colab_audio.py+171-115