File size: 9,268 Bytes
3278fb4
 
7deef83
 
 
 
 
 
 
 
 
 
3278fb4
7deef83
054d418
3278fb4
 
054d418
3278fb4
 
 
7deef83
28d3dab
 
3dafaa1
da263cc
 
7deef83
28d3dab
bf27d36
28d3dab
 
7deef83
7fd9023
7deef83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb150c0
 
 
 
 
 
 
 
 
 
 
 
 
28d3dab
da7f3ce
7deef83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb150c0
7deef83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de900c7
7deef83
 
 
de900c7
7deef83
 
 
 
 
 
 
 
 
de900c7
7deef83
 
 
 
 
 
 
 
 
 
 
 
56df2d9
7deef83
 
 
 
 
 
56df2d9
7deef83
 
 
 
 
56df2d9
 
7deef83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c39daa
 
 
 
7deef83
0c39daa
 
 
 
 
 
 
 
7deef83
 
0c39daa
 
 
 
 
 
 
 
 
 
 
 
 
 
7deef83
0c39daa
7deef83
 
0c39daa
 
 
 
 
 
7deef83
0c39daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7deef83
45bbff4
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
from contextlib import nullcontext
from torch.nn import functional as F
from utils import TOKENIZER, Dataset
from pedalboard import Pedalboard, Reverb, Compressor, Gain, Limiter
from pedalboard.io import AudioFile
import pandas as pd
import subprocess
import pretty_midi
import gradio as gr
import time
import copy
import types
import torch
import random
import spaces
import os


torch.backends.cudnn.benchmark = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cuda.matmul.allow_tf32 = True

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

n_layer = 12
n_embd = 768
ctx_len = 2048

os.environ['RWKV_FLOAT_MODE'] = 'fp32'
os.environ['RWKV_RUN_DEVICE'] = 'cpu'
model_type = 'RWKV'

MODEL_NAME = 'model'
LENGTH_PER_TRIAL = round((2048) / 13) * 13
TEMPERATURE = 1.0

from model_run import RWKV_RNN
model = RWKV_RNN(MODEL_NAME, os.environ['RWKV_RUN_DEVICE'], model_type, n_layer, n_embd, ctx_len)
tokenizer = TOKENIZER()

temp_dir = 'temp'
if not os.path.exists(temp_dir):
    os.makedirs(temp_dir)

def clear_midi(dir):
    for file in os.listdir(dir):
        if file.endswith('.mid'):
            os.remove(os.path.join(dir, file))

clear_midi(temp_dir)


ctx_seed = "000000000000\n"
ctx = tokenizer.encode(ctx_seed)
src_len = len(ctx)
src_ctx = ctx.copy()


def humanize_notes(midi_events):
    def humanize(value):
        if value != 0:
            humanize_offset = random.choice([-0.20, 0.20])
            return max(0, int(value + humanize_offset))
        return value
    midi_events['start'] = midi_events['start'].apply(humanize)
    midi_events['end'] = midi_events['end'].apply(humanize)

    max_tick = 8 * 384
    midi_events['end'] = midi_events['end'].clip(upper=max_tick)
    return midi_events


@spaces.GPU(duration=60)
def generate_midi(LENGTH_PER_TRIAL, src_ctx, model, src_len, ctx_len, TEMPERATURE, top_k, tokenizer, ctx_seed, bpm):
    midi_seq = []
    
    for TRIAL in range(1):
        t_begin = time.time_ns()

        if TRIAL > 0:
            midi_seq.append("\n")

        ctx = src_ctx.copy()
        model.clear()
        midi_tokens = []

        if TRIAL == 0:
            init_state = types.SimpleNamespace()
            for i in range(src_len):
                x = ctx[:i+1]
                if i == src_len - 1:
                    init_state.out = model.run(x)
                else:
                    model.run(x)
            model.save(init_state)
        else:
            model.load(init_state)

        midi_seq.append(ctx_seed)
        
        for i in range(src_len, src_len + LENGTH_PER_TRIAL):
            x = ctx[:i+1]
            x = x[-ctx_len:]

            if i == src_len:
                out = copy.deepcopy(init_state.out)
            else:
                out = model.run(x)

            char = tokenizer.sample_logits(out, x, ctx_len, temperature=TEMPERATURE, top_k=top_k).item()
            midi_tokens.append(char)

            if len(midi_tokens) > 2:
                midi_tokens.pop(0)

            if midi_tokens == [11, 10]:  # stop token pattern
                break
            
            midi_seq.append(tokenizer.decode([int(char)]))
            
            if midi_tokens != [11, 10]:
                ctx += [char]
        
        t_end = time.time_ns()

    trim_seq = "".join(midi_seq)
    events = trim_seq.split("\n")
    
    midi_events = []
    sequence = []
    rndm_num = 895645

    for event in events:
        if event.strip() == "":
            midi_events.append(sequence)
            sequence = []
            rndm_num = random.randint(100000, 999999)
        try:
            pitch = int(event[0:2])
            velocity = int(event[2:4])
            start = int(event[4:8])
            end = int(event[8:12])
        except ValueError:
            pitch = 0
            velocity = 0
            start = 0
            end = 0

        sequence.append({'file_name': f'rwkv_{rndm_num}', 'pitch': pitch, 'velocity': velocity, 'start': start, 'end': end})

    if sequence:
        midi_events.append(sequence)

    midi_events = pd.DataFrame([pd.Series(event) for sequence in midi_events for event in sequence])
    midi_events = midi_events[['file_name', 'pitch', 'velocity', 'start', 'end']]
    midi_events = humanize_notes(midi_events)
    midi_events = midi_events.sort_values(by=['file_name', 'start']).reset_index(drop=True)
    midi_events = midi_events[(midi_events['start'] < 3072) & (midi_events['end'] <= 3072)]

    for file_name, events in midi_events.groupby('file_name'):
        midi_obj = pretty_midi.PrettyMIDI(initial_tempo=bpm, resolution=96)
        instrument = pretty_midi.Instrument(0)
        midi_obj.instruments.append(instrument)

        for _, event in events.iterrows():
            note = pretty_midi.Note(
                pitch=event['pitch'], 
                velocity=event['velocity'], 
                start=midi_obj.tick_to_time(event['start']), 
                end=midi_obj.tick_to_time(event['end'])
            )
            instrument.notes.append(note)

        midi_path = os.path.join(temp_dir, 'output.mid')
        midi_obj.write(midi_path)

    return midi_path


def render_wav(midi_file, uploaded_sf2=None, output_level='2.0'):
    sf2_dir = 'sf2'
    audio_format = 's16'
    sample_rate = '44100'
    gain = str(output_level)

    if uploaded_sf2:
        sf2_file = uploaded_sf2
    else:
        sf2_files = [f for f in os.listdir(os.path.join(sf2_dir)) if f.endswith('.sf2')]
        if not sf2_files:
            raise ValueError("No SoundFont (.sf2) file found in directory.")
        sf2_file = os.path.join(sf2_dir, random.choice(sf2_files))

    #print(f"Using SoundFont: {sf2_file}")
    output_wav = os.path.join(temp_dir, 'output.wav')

    with open(os.devnull, 'w') as devnull:
        command = [
            'fluidsynth', '-ni', sf2_file, midi_file, '-F', output_wav, '-r', str(sample_rate), 
            '-o', f'audio.file.format={audio_format}', '-g', str(gain)
        ]
        subprocess.call(command, stdout=devnull, stderr=devnull)

    return output_wav


def generate_and_return_files(bpm, temperature, top_k, uploaded_sf2=None, output_level='2.0'):
    midi_events = generate_midi(
        LENGTH_PER_TRIAL, src_ctx, model, src_len, ctx_len, temperature, top_k, 
        tokenizer, ctx_seed, bpm
    )  
    
    midi_file = 'temp/output.mid'
    wav_raw = render_wav(midi_file, uploaded_sf2, output_level)
    wav_fx = os.path.join(temp_dir, 'output_fx.wav')

    sfx_settings = [
        {
            'board': Pedalboard([
                Reverb(room_size=0.50, wet_level=0.30, dry_level=0.75, width=1.0),
                Compressor(threshold_db=-4.0, ratio=4.0, attack_ms=0.0, release_ms=300.0),
            ])
        }
    ]

    for setting in sfx_settings:
        board = setting['board']

        with AudioFile(wav_raw) as f:
            with AudioFile(wav_fx, 'w', f.samplerate, f.num_channels) as o:
                while f.tell() < f.frames:
                    chunk = f.read(int(f.samplerate))
                    effected = board(chunk, f.samplerate, reset=False)
                    o.write(effected)

    return midi_file, wav_fx


custom_css = """
#container {
  max-width: 1200px !important;
  margin: 0 auto !important;
}
#generate-btn {
  font-size: 18px;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background: linear-gradient(90deg, hsla(268, 90%, 70%, 1) 0%, hsla(260, 72%, 74%, 1) 50%, hsla(247, 73%, 65%, 1) 100%);
  transition: background 1s ease;
}
#generate-btn:hover {
  color: white;
  background: linear-gradient(90deg, hsla(268, 90%, 62%, 1) 0%, hsla(260, 70%, 70%, 1) 50%, hsla(247, 73%, 55%, 1) 100%);
}
#container .prose {
  text-align: center !important;
}
#container h1 {
  font-weight: bold;
  font-size: 40px;
  margin: 0px;
}
#container p {
  font-size: 18px;
  text-align: center;
}

"""

with gr.Blocks(
    css=custom_css,
    theme=gr.themes.Default(
        font=[gr.themes.GoogleFont("Roboto"), "sans-serif"],
        primary_hue="violet",
        secondary_hue="violet"
    )
) as iface:
    with gr.Column(elem_id="container"):
        gr.Markdown("<h1>Pop-K</h1>")
        gr.Markdown("<p>Pop-K is a small RWKV model that generates pop melodies in C major and A minor.</p>")

        bpm = gr.Slider(minimum=50, maximum=200, step=1, value=100, label="BPM")
        temperature = gr.Slider(minimum=0.1, maximum=2.0, step=0.1, value=1.0, label="Temperature")
        top_k = gr.Slider(minimum=4, maximum=32, step=1, value=20, label="Top-k")
        output_level = gr.Slider(minimum=0, maximum=3, step=0.10, value=2.0, label="Output Gain")
        generate_button = gr.Button("Generate", elem_id="generate-btn")
        midi_file = gr.File(label="MIDI Output")
        audio_file = gr.Audio(label="Audio Output", type="filepath")
        soundfont = gr.File(label="Optional: Upload SoundFont (preset=0, bank=0)")

        generate_button.click(
            fn=generate_and_return_files,
            inputs=[bpm, temperature, top_k, soundfont, output_level],
            outputs=[midi_file, audio_file]
        )

        gr.Markdown("<p style='font-size: 16px;'>Developed by <a href='https://www.patchbanks.com/' target='_blank'><strong>Patchbanks</strong></a></p>")

iface.launch(share=True)