File size: 7,493 Bytes
3888ab7
 
 
 
 
 
2278710
3888ab7
 
 
 
 
 
29090fa
 
6df655f
 
 
 
 
06d58f4
 
6df655f
 
3888ab7
 
6df655f
 
cf7d19c
6df655f
 
 
 
 
 
cf7d19c
 
6df655f
cf7d19c
6df655f
cf7d19c
 
6df655f
cf7d19c
6df655f
4301ec8
 
6df655f
cf7d19c
4301ec8
6df655f
cf7d19c
 
6df655f
 
 
cf7d19c
 
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
 
cf7d19c
6df655f
cf7d19c
 
6df655f
cf7d19c
 
 
 
 
6df655f
cf7d19c
6df655f
cf7d19c
 
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
cf7d19c
 
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
cf7d19c
 
 
 
 
 
6df655f
cf7d19c
 
 
 
6df655f
cf7d19c
 
6df655f
cf7d19c
6df655f
cf7d19c
6df655f
497670e
33f8e9f
6df655f
 
 
 
 
 
 
 
 
86dfaf8
6df655f
 
 
 
 
 
5c6968d
6df655f
 
 
5c6968d
 
91d5e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c43bea
91d5e8a
 
8c43bea
6df655f
 
 
3888ab7
 
 
 
 
eec4853
3888ab7
eec4853
1aa6fb6
29090fa
3888ab7
e469266
 
29090fa
e469266
 
3888ab7
 
29090fa
8c43bea
e30e402
8c43bea
 
 
3888ab7
8c43bea
 
3888ab7
86dfaf8
8c43bea
 
86dfaf8
3adc64e
fbae75f
c12a6f7
fbae75f
 
 
 
c04453c
86dfaf8
c12a6f7
d85cb0d
7dd6e93
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import argparse
import glob
import os.path

import gradio as gr

import pickle
import tqdm
import json

import MIDI
from midi_synthesizer import synthesis

from fuzzywuzzy import process

import copy
from collections import Counter
import random
import statistics

import matplotlib.pyplot as plt

#==========================================================================================================

in_space = os.getenv("SYSTEM") == "spaces"

#==========================================================================================================

def find_midi(title, artist):
  
    print('=' * 70)
    print('Loading MIDI file...')
    
    #==================================================
    
    print('Searching titles...Please wait...')
    random.shuffle(AUX_DATA)
    
    titles_index = []
    
    for A in AUX_DATA:
      titles_index.append(A[0])
    
    search_string = ''
    
    if title != '' and artist != '':
      search_string = title + ' --- ' + artist
    
    else:
      search_string = title + artist
    
    search_match = process.extract(query=search_string, choices=titles_index, limit=1)
    search_index = titles_index.index(search_match[0][0])
    
    print('Done!')
    print('=' * 70)
    print('Selected title:', AUX_DATA[search_index][0])
    print('=' * 70)

    outy = AUX_DATA[search_index][1]

    print('Sample INTs', outy[:12])
    print('=' * 70)
    
    if len(outy) != 0:
    
      song = outy
      song_f = []
    
      time = 0
      dur = 0
      vel = 90
      pitch = 0
      channel = 0
    
      patches = [-1] * 16
    
      channels = [0] * 16
      channels[9] = 1
    
      for ss in song:
    
          if 0 <= ss < 256:
    
              time += ss * 16
    
          if 256 <= ss < 2304:
    
              dur = ((ss-256) // 8) * 16
              vel = (((ss-256) % 8)+1) * 15
    
          if 2304 <= ss < 18945:
    
              patch = (ss-2304) // 129
    
              if patch < 128:
    
                  if patch not in patches:
                    if 0 in channels:
                        cha = channels.index(0)
                        channels[cha] = 1
                    else:
                        cha = 15
    
                    patches[cha] = patch
                    channel = patches.index(patch)
                  else:
                    channel = patches.index(patch)
    
              if patch == 128:
                  channel = 9
    
              pitch = (ss-2304) % 129
    
              song_f.append(['note', time, dur, channel, pitch, vel, patch ])
    

    
    x = []
    y = []
    c = []
    
    colors = ['red', 'yellow', 'green', 'cyan',
            'blue', 'pink', 'orange', 'purple',
            'gray', 'white', 'gold', 'silver',
            'lightgreen', 'indigo', 'maroon', 'turquoise']
    
    for s in [m for m in song_f if m[0] == 'note']:
        x.append(s[1])
        y.append(s[4])
        c.append(colors[s[3]])

    plt.close()
    plt.figure(figsize=(14,5))
    ax=plt.axes(title='MIDI Match Plot')
    ax.set_facecolor('black')
    
    plt.scatter(x,y, c=c)
    plt.xlabel("Time in MIDI ticks")
    plt.ylabel("MIDI Pitch")

    output_signature = AUX_DATA[search_index][0]
    track_name = 'Project Los Angeles'
    text_encoding = 'ISO-8859-1'

    list_of_MIDI_patches=[0, 24, 32, 40, 42, 46, 56, 71, 73, 0, 53, 19, 0, 0, 0, 0]

    output_header = [1000,
                    [['set_tempo', 0, 1000000],
                     ['time_signature', 0, 4, 2, 24, 8],
                     ['track_name', 0, bytes(output_signature, text_encoding)]]]

    patch_list = [['patch_change', 0, 0, list_of_MIDI_patches[0]], 
                    ['patch_change', 0, 1, list_of_MIDI_patches[1]],
                    ['patch_change', 0, 2, list_of_MIDI_patches[2]],
                    ['patch_change', 0, 3, list_of_MIDI_patches[3]],
                    ['patch_change', 0, 4, list_of_MIDI_patches[4]],
                    ['patch_change', 0, 5, list_of_MIDI_patches[5]],
                    ['patch_change', 0, 6, list_of_MIDI_patches[6]],
                    ['patch_change', 0, 7, list_of_MIDI_patches[7]],
                    ['patch_change', 0, 8, list_of_MIDI_patches[8]],
                    ['patch_change', 0, 9, list_of_MIDI_patches[9]],
                    ['patch_change', 0, 10, list_of_MIDI_patches[10]],
                    ['patch_change', 0, 11, list_of_MIDI_patches[11]],
                    ['patch_change', 0, 12, list_of_MIDI_patches[12]],
                    ['patch_change', 0, 13, list_of_MIDI_patches[13]],
                    ['patch_change', 0, 14, list_of_MIDI_patches[14]],
                    ['patch_change', 0, 15, list_of_MIDI_patches[15]],
                    ['track_name', 0, bytes(track_name, text_encoding)]]

    output = output_header + [patch_list + song_f]

    with open(f"MIDI-Search-Sample.mid", 'wb') as f:
        f.write(MIDI.score2midi(output)
    audio = synthesis(MIDI.score2opus(output), soundfont_path)
    yield AUX_DATA[search_index][0], "MIDI-Search-Sample.mid", (44100, audio), plt

#==========================================================================================================

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--share", action="store_true", default=False, help="share gradio app")
    parser.add_argument("--port", type=int, default=7860, help="gradio server port")
    parser.add_argument("--max-gen", type=int, default=1024, help="max")
    
    opt = parser.parse_args()
    
    soundfont_path = "SGM-v2.01-YamahaGrand-Guit-Bass-v2.7.sf2"
    meta_data_path = "Giant_Music_Transformer_Aux_Data.pickle"

    print('Loading meta-data...')
    with open(meta_data_path, 'rb') as f:
        AUX_DATA = pickle.load(f)
    print('Done!')
    
    app = gr.Blocks()
    with app:
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>MIDI Search</h1>")
        gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Search and explore 160k+ MIDI titles</h1>")
        
        gr.Markdown("![Visitors](https://api.visitorbadge.io/api/visitors?path=asigalov61.MIDI-Search&style=flat)\n\n"
                    "Giant Music Transformer Aux Data Demo\n\n"
                    "Please see [Giant Music Transformer](https://github.com/asigalov61/Giant-Music-Transformer) for more information and features\n\n"
                    "[Open In Colab]"
                    "(https://colab.research.google.com/github/asigalov61/Giant-Music-Transformer/blob/main/Giant_Music_Transformer_TTM.ipynb)"
                    " for all features"
                    )
        
        title = gr.Textbox(label="Desired Song Title", value="Family Guy")
        artist = gr.Textbox(label="Desired Song Artist", value="TV Themes")
        submit = gr.Button()

        gr.Markdown("# Search results")

        output_midi_seq = gr.Textbox(label="Output MIDI search metadata")
        output_audio = gr.Audio(label="Output MIDI search sample audio", format="mp3", elem_id="midi_audio")
        output_plot = gr.Plot(label="Output MIDI search sample plot")
        output_midi = gr.File(label="Output MIDI search sample MIDI", file_types=[".mid"])
        
        run_event = submit.click(find_midi, [title, artist],
                                                  [output_midi_seq, output_midi, output_audio, output_plot])
        
    app.queue(1).launch(server_port=opt.port, share=opt.share, inbrowser=True)