File size: 9,711 Bytes
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
1e8447a
 
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e8447a
b162b24
 
 
 
 
 
 
 
173eaab
afe69d1
b162b24
 
 
 
 
e5bdbf7
1e8447a
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa7e161
b162b24
fa7e161
b162b24
 
 
 
 
 
 
173eaab
 
 
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173eaab
b162b24
 
 
 
 
173eaab
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
ca868cb
8cf3257
 
 
 
 
b162b24
 
 
 
 
 
 
 
 
a7f8fd9
 
 
 
 
 
 
 
b162b24
a7f8fd9
afe69d1
 
b162b24
 
 
 
a7f8fd9
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
4ea2502
b162b24
 
 
 
 
4ea2502
b162b24
 
1e8447a
07f23b6
1e8447a
 
 
 
 
 
 
 
8cf3257
1e8447a
8cf3257
1e8447a
 
 
 
 
 
 
 
 
 
 
8cf3257
1e8447a
 
8cf3257
1e8447a
 
b162b24
 
 
96c69bb
b162b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d603624
b162b24
 
 
 
 
8bce18e
b162b24
 
 
 
 
 
 
 
 
 
 
 
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
"use client";
import Image from "next/image";
import {
  AutoTokenizer,
  MusicgenForConditionalGeneration,
  BaseStreamer,
} from "@xenova/transformers";

import { Prompt } from "@/components/prompt";
import { Length } from "@/components/length";
import { Styles } from "@/components/styles";
import { Moods } from "@/components/moods";
import { useGeneration } from "@/components/hooks/useGeneration";
import { useState, useRef, useEffect, useMemo } from "react";
import { encodeWAV, MODEL_ID, share } from "@/utils";
import classNames from "classnames";

class CallbackStreamer extends BaseStreamer {
  [x: string]: any;
  constructor(callback_fn: any) {
    super();

    this.callback_fn = callback_fn;
  }

  put(value: any) {
    return this.callback_fn(value);
  }

  end() {
    return this.callback_fn();
  }
}

export const Form = ({ children }: { children: React.ReactNode }) => {
  const [modelLoaded, setModelLoaded] = useState(false);
  const [progress, setProgress] = useState(0);
  const [statusText, setStatusText] = useState("Loading model (656MB)...");
  const [loadProgress, setLoadProgress] = useState({});
  const [track, setTrack] = useState("");
  const [shareLoading, setShareLoading] = useState(false);

  const {
    form,
    setForm,
    formattedPrompt,
    generate,
    results,
    loading,
    randomize,
    setResults,
  } = useGeneration();

  const modelPromise = useRef(null);
  const tokenizerPromise = useRef(null);

  const SHARING_ENABLED = true;

  useEffect(() => {
    modelPromise.current ??= MusicgenForConditionalGeneration.from_pretrained(
      MODEL_ID,
      {
        progress_callback: (data: any) => {
          if (data.status !== "progress") return;
          setLoadProgress((prev) => ({ ...prev, [data.file]: data }));
        },
        dtype: {
          text_encoder: "q8",
          decoder_model_merged: "q8",
          encodec_decode: "fp32",
        },
        device: "wasm",
      }
    );
    //@ts-ignore
    tokenizerPromise.current ??= AutoTokenizer.from_pretrained(MODEL_ID);
  }, []);

  useEffect(() => {
    const items = Object.values(loadProgress);
    if (items.length !== 5) return; // 5 files to load
    let loaded = 0;
    let total = 0;
    for (const data of Object.values(loadProgress)) {
      // @ts-ignore
      loaded += data.loaded;
      // @ts-ignore
      total += data.total;
    }
    const progress = loaded / total;
    setProgress(progress);
    setStatusText(
      progress === 1
        ? "Ready!"
        : `Loading In-Browser model (${(
            progress * 100
          ).toFixed()}% of 656MB)...`
    );
    if (progress === 1) {
      setTimeout(() => setModelLoaded(true), 1500);
    }
  }, [loadProgress]);

  const generateMusic = async () => {
    const tokenizer: any = await tokenizerPromise.current;
    const model: any = await modelPromise.current;

    if (!tokenizer || !model) return null;

    const max_length = Math.min(
      Math.max(Math.floor(form.length * 50), 1) + 4,
      model?.generation_config?.max_length ?? 1500
    );

    const streamer = new CallbackStreamer((value: string) => {
      const percent = value === undefined ? 1 : value[0].length / max_length;
      setStatusText(`Generating (${(percent * 100).toFixed()}%)...`);
      setProgress(percent);
    });

    const inputs = tokenizer(formattedPrompt);

    const audio_values = await model.generate({
      ...inputs,
      max_length,
      streamer,
    });

    setStatusText("Encoding audio...");

    const sampling_rate = model.config.audio_encoder.sampling_rate;
    const wav = encodeWAV(audio_values.data, sampling_rate);
    const blob = new Blob([wav], { type: "audio/wav" });
    setTrack(URL.createObjectURL(blob));
    setStatusText("Done!");
  };

  return (
    <main className="grid grid-cols-1 gap-20 lg:grid-cols-2 lg:gap-20 relative">
      <div className="grid grid-cols-1 gap-10">
        {children}
        <Prompt
          value={form.prompt}
          onChange={(value) => setForm({ ...form, prompt: value })}
          onRandomize={randomize}
        />
        <Length
          value={form.length}
          onChange={(value) => setForm({ ...form, length: value })}
        />
        <Styles
          value={form.style}
          onChange={(value) => setForm({ ...form, style: value })}
        />
        <Moods
          value={form.mood}
          onChange={(value) => setForm({ ...form, mood: value })}
        />
      </div>
      <div className="max-lg:pb-16">
        <div
          className={classNames("w-full", {
            "sticky top-0": !track,
          })}
        >
          <div className="border rounded-xl p-6 bg-stone-900/40 border-white/5">
            <p className="text-amber-200 font-semibold text-xs uppercase mb-3">
              Generated prompt
            </p>
            <p className="text-white text-xl font-semibold">
              &quot;{formattedPrompt}&quot;
            </p>
          </div>
          <button
            className={classNames(
              "rounded-xl bg-stone-900/90 border-white/5 border px-6 py-3 font-semibold text-base text-white mt-6 hover:brightness-125 transition-all duration-200",
              {
                "animate-pulse": loading,
                "opacity-50 !cursor-not-allowed": !modelLoaded,
              }
            )}
            disabled={loading || !modelLoaded}
            onClick={() => {
              if (loading || !modelLoaded) return;
              setResults({ cover: null, title: null });
              setTrack("");
              generate();
              generateMusic();
            }}
          >
            {!modelLoaded ? "Waiting for model loaded" : "Generate music"}
          </button>
          {(loading || results?.title || results?.cover) && (
            <div className="mt-6 space-y-6 flex flex-col">
              {results.cover ? (
                <Image
                  src={results.cover}
                  alt="Cover art"
                  className="w-[300px] h-[300px] object-contain bg-amber-950 rounded-xl mx-auto"
                  width={300}
                  height={300}
                />
              ) : (
                <div className="w-[300px] h-[300px] bg-stone-900 animate-pulse rounded-xl mx-auto"></div>
              )}
              {results.title ? (
                <p className="text-center text-white font-bold text-3xl">
                  {results.title}
                </p>
              ) : (
                <div className="w-[450px] h-8 bg-stone-900 animate-pulse rounded-xl mx-auto"></div>
              )}
              {modelLoaded &&
                (track !== "" ? (
                  <div className="mx-auto flex flex-col gap-5 justify-center">
                    <audio controls src={track} />
                    {SHARING_ENABLED && (
                      <button
                        className={classNames(
                          "rounded-xl bg-amber-500/10 border-amber-500 border px-6 py-3 font-semibold text-base text-amber-500 mt-6 hover:bg-amber-500 hover:text-white transition-all duration-200 relative",
                          {
                            "animate-pulse": shareLoading,
                          }
                        )}
                        onClick={async () => {
                          if (shareLoading) return;
                          setShareLoading(true);
                          await share(
                            track,
                            {
                              mood: form.mood,
                              style: form.style,
                              duration: form.length,
                              prompt: form.prompt,
                              formatted_prompt: formattedPrompt,
                            },
                            results
                          );
                          setShareLoading(false);
                        }}
                      >
                        {shareLoading ? "Sharing..." : "Share my song"}
                      </button>
                    )}
                  </div>
                ) : (
                  <div className="mx-auto w-full max-w-sm border rounded-xl p-6 bg-amber-900/10 border-white/10 overflow-hidden transition-all duration-200">
                    <p className="text-sm text-left mb-4 uppercase font-medium text-white">
                      {statusText}
                    </p>
                    <div className="bg-gray-200 h-2.5 w-full rounded-full overflow-hidden">
                      <div
                        className="from-amber-500 to-orange-500 bg-gradient-to-r h-full"
                        style={{ width: `${100 * progress}%` }}
                      ></div>
                    </div>
                  </div>
                ))}
            </div>
          )}
        </div>
      </div>
      <div
        className={classNames(
          "fixed lg:right-10 w-[calc(100%-24px)] max-lg:top-6 lg:bottom-10 max-lg:left-1/2 max-lg:-translate-x-1/2 z-20 lg:w-full max-w-sm border rounded-xl p-6 bg-stone-950 lg:bg-amber-900/10 border-white/10 overflow-hidden transition-all duration-200",
          {
            "opacity-0 pointer-events-none translate-y-full": modelLoaded,
          }
        )}
      >
        <p className="text-sm text-left mb-4 uppercase font-medium text-white">
          {statusText}
        </p>
        <div className="bg-gray-200 h-2.5 w-full rounded-full overflow-hidden">
          <div
            className="from-amber-500 to-orange-500 bg-gradient-to-r h-full"
            style={{ width: `${100 * progress}%` }}
          ></div>
        </div>
      </div>
    </main>
  );
};