-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
342 lines (317 loc) · 13 KB
/
Copy pathmain.cpp
File metadata and controls
342 lines (317 loc) · 13 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "backend.h"
#include "events.h"
#include "midi_io.h"
#include "mt3.h"
#include "pipeline.h"
#include "resample.h"
#include "wav_io.h"
namespace {
void usage(const char* argv0) {
std::fprintf(stderr,
R"(muscriptor — audio-to-MIDI transcription (ggml)
Usage:
%s [options] <audio>
%s list-instruments
Model:
-m, --model PATH|SIZE GGUF path, or size keyword: small|medium|large
(default: medium → models/muscriptor-medium-F16.gguf)
-d, --device DEVICE auto|cpu|cuda|metal|gpu (default: auto)
Output:
-o, --output PATH Output path, or '-' for stdout (default: <audio>.mid/json/jsonl)
-f, --format FMT midi|json|jsonl (default: midi)
--notes Also print decoded events to stderr
Decoding (same knobs as Python muscriptor):
--sampling Temperature sampling instead of greedy
-t, --temperature T Sampling temperature (with --sampling; default: 1)
--cfg-coef C Classifier-free guidance (default: 1; keep 1 for released models)
-b, --batch-size N Chunks per step (default: 1; >1 needs --no-prelude-forcing)
--beam-size N Beam width (1 = greedy/sampling; default: 1)
--strict-eos Error if a chunk misses EOS (default: warn)
--prelude-forcing / --no-prelude-forcing
Teacher-force tie prologue across chunks (default: on)
--instruments LIST Comma-separated instrument groups (abbrev ok)
--max-gen-len N Max tokens per chunk (default: 2000)
Other:
--smoke-test Hermetic tiny-model smoke (no weights)
-h, --help
Weights are CC BY-NC 4.0 (MuScriptor). This binary's code is MIT.
)",
argv0, argv0);
}
std::vector<std::string> split_csv(const std::string& s) {
std::vector<std::string> out;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, ',')) {
if (!item.empty()) out.push_back(item);
}
return out;
}
std::string resolve_model_path(const std::string& model_arg) {
if (model_arg.empty() || model_arg == "medium") {
return "models/muscriptor-medium-F16.gguf";
}
if (model_arg == "small") return "models/muscriptor-small-F16.gguf";
if (model_arg == "large") return "models/muscriptor-large-F16.gguf";
return model_arg;
}
void apply_device(const std::string& device) {
if (device.empty() || device == "auto") return;
std::string d = device;
for (char& c : d) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (d == "cpu") {
setenv("GGML_BACKEND", "CPU", 1);
} else if (d == "cuda" || d.rfind("cuda:", 0) == 0 || d == "gpu") {
setenv("GGML_BACKEND", "CUDA", 1);
} else if (d == "metal" || d == "mps") {
setenv("GGML_BACKEND", "Metal", 1);
} else {
setenv("GGML_BACKEND", device.c_str(), 1);
}
}
void write_json_events(const std::vector<muscriptor::DecodedEvent>& events, FILE* f,
bool jsonl, bool include_progress) {
bool first = true;
if (!jsonl) std::fputc('[', f);
for (const auto& ev : events) {
if (std::holds_alternative<muscriptor::ProgressEvent>(ev)) {
if (!include_progress) continue;
const auto& p = std::get<muscriptor::ProgressEvent>(ev);
if (jsonl) {
std::fprintf(f, "{\"type\":\"Progress\",\"completed\":%d,\"total\":%d}\n",
p.completed, p.total);
} else {
if (!first) std::fputc(',', f);
std::fprintf(f, "\n {\"type\":\"Progress\",\"completed\":%d,\"total\":%d}",
p.completed, p.total);
first = false;
}
continue;
}
if (std::holds_alternative<muscriptor::NoteStartEvent>(ev)) {
const auto& s = std::get<muscriptor::NoteStartEvent>(ev);
if (jsonl) {
std::fprintf(f,
"{\"type\":\"start\",\"pitch\":%d,\"start_time\":%.6f,"
"\"index\":%d,\"instrument\":\"%s\"}\n",
s.pitch, s.start_time, s.index, s.instrument.c_str());
} else {
if (!first) std::fputc(',', f);
std::fprintf(f,
"\n {\"type\":\"start\",\"pitch\":%d,\"start_time\":%.6f,"
"\"index\":%d,\"instrument\":\"%s\"}",
s.pitch, s.start_time, s.index, s.instrument.c_str());
first = false;
}
} else if (std::holds_alternative<muscriptor::NoteEndEvent>(ev)) {
const auto& e = std::get<muscriptor::NoteEndEvent>(ev);
if (jsonl) {
std::fprintf(f,
"{\"type\":\"end\",\"end_time\":%.6f,\"start_event_index\":%d}\n",
e.end_time, e.start_event_index());
} else {
if (!first) std::fputc(',', f);
std::fprintf(f,
"\n {\"type\":\"end\",\"end_time\":%.6f,\"start_event_index\":%d}",
e.end_time, e.start_event_index());
first = false;
}
}
}
if (!jsonl) std::fputs("\n]\n", f);
}
void print_notes_stderr(const std::vector<muscriptor::DecodedEvent>& events) {
for (const auto& ev : events) {
if (std::holds_alternative<muscriptor::NoteStartEvent>(ev)) {
const auto& s = std::get<muscriptor::NoteStartEvent>(ev);
std::fprintf(stderr, "NoteStart pitch=%d t=%.3f %s\n", s.pitch, s.start_time,
s.instrument.c_str());
} else if (std::holds_alternative<muscriptor::NoteEndEvent>(ev)) {
const auto& e = std::get<muscriptor::NoteEndEvent>(ev);
std::fprintf(stderr, "NoteEnd t=%.3f start_index=%d\n", e.end_time,
e.start_event_index());
}
}
}
} // namespace
int main(int argc, char** argv) {
std::string model_arg = "medium";
std::string audio_path;
std::string output_path;
std::string format = "midi";
std::string device = "auto";
bool notes = false;
bool strict_eos = false;
muscriptor::TranscribeOptions opts;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
auto need = [&](const char* name) -> std::string {
if (i + 1 >= argc) {
std::fprintf(stderr, "missing value for %s\n", name);
std::exit(1);
}
return argv[++i];
};
if (a == "list-instruments") {
for (const auto& name : muscriptor::list_instrument_group_names()) {
std::printf("%s\n", name.c_str());
}
return 0;
} else if (a == "-m" || a == "--model") {
model_arg = need("--model");
} else if (a == "-d" || a == "--device") {
device = need("--device");
} else if (a == "--audio") {
audio_path = need("--audio");
} else if (a == "-o" || a == "--output") {
output_path = need("-o");
} else if (a == "-f" || a == "--format") {
format = need("--format");
} else if (a == "--notes") {
notes = true;
} else if (a == "--instruments") {
try {
opts.instruments =
muscriptor::resolve_instrument_names(split_csv(need("--instruments")));
std::fprintf(stderr, "Instruments: ");
for (size_t k = 0; k < opts.instruments.size(); ++k) {
if (k) std::fprintf(stderr, ", ");
std::fprintf(stderr, "%s", opts.instruments[k].c_str());
}
std::fprintf(stderr, "\n");
} catch (const std::exception& e) {
std::fprintf(stderr,
"Error: %s. Run '%s list-instruments' for available names.\n",
e.what(), argv[0]);
return 1;
}
} else if (a == "--beam-size") {
opts.beam_size = std::stoi(need("--beam-size"));
} else if (a == "--max-gen-len") {
opts.max_gen_len = std::stoi(need("--max-gen-len"));
} else if (a == "--sampling") {
opts.use_sampling = true;
} else if (a == "-t" || a == "--temperature") {
opts.temperature = std::stof(need("-t"));
} else if (a == "--cfg-coef") {
opts.cfg_coef = std::stof(need("--cfg-coef"));
} else if (a == "--prelude-forcing") {
opts.prelude_forcing = true;
} else if (a == "--no-prelude-forcing") {
opts.prelude_forcing = false;
} else if (a == "-b" || a == "--batch-size") {
opts.batch_size = std::stoi(need("--batch-size"));
} else if (a == "--strict-eos") {
strict_eos = true;
opts.no_eos_is_ok = false;
} else if (a == "-h" || a == "--help") {
usage(argv[0]);
return 0;
} else if (a == "--smoke-test") {
apply_device(device);
muscriptor::backend_init("muscriptor");
auto vocab = muscriptor::build_event_vocab(1001);
if (vocab.size() != 1393) {
std::fprintf(stderr, "vocab size %zu != 1393\n", vocab.size());
return 1;
}
muscriptor::LMConfig cfg;
cfg.card = 1393;
cfg.dim = 32;
cfg.num_heads = 4;
cfg.num_layers = 1;
auto lm = muscriptor::LMModel::create_random(cfg, 42);
muscriptor::GenerateConfig g;
g.max_gen_len = 8;
g.early_stop_on_token = 1;
auto toks = lm.generate({}, g);
std::fprintf(stderr, "[smoke] vocab=%zu generated=%zu tokens\n", vocab.size(),
toks.size());
return 0;
} else if (!a.empty() && a[0] != '-') {
if (!audio_path.empty()) {
std::fprintf(stderr, "unexpected argument: %s\n", a.c_str());
usage(argv[0]);
return 1;
}
audio_path = a;
} else {
std::fprintf(stderr, "unknown arg: %s\n", a.c_str());
usage(argv[0]);
return 1;
}
}
if (audio_path.empty()) {
usage(argv[0]);
return 1;
}
if (opts.prelude_forcing && opts.batch_size > 1) {
std::fprintf(stderr,
"Error: --batch-size %d requires --no-prelude-forcing\n",
opts.batch_size);
return 1;
}
if (output_path.empty()) {
std::string ext = ".mid";
if (format == "json") ext = ".json";
else if (format == "jsonl") ext = ".jsonl";
output_path = audio_path + ext;
// Replace extension if audio has one
auto dot = audio_path.find_last_of('.');
auto slash = audio_path.find_last_of("/\\");
if (dot != std::string::npos && (slash == std::string::npos || dot > slash)) {
output_path = audio_path.substr(0, dot) + ext;
}
}
apply_device(device);
muscriptor::backend_init("muscriptor");
const std::string model_path = resolve_model_path(model_arg);
std::fprintf(stderr, "Loading model %s …\n", model_path.c_str());
auto model = muscriptor::TranscriptionModel::load_gguf(model_path);
std::fprintf(stderr, "Transcribing %s …\n", audio_path.c_str());
(void)strict_eos;
int sr = 0;
auto wav = muscriptor::read_wav_f32_mono(audio_path, &sr);
if (sr != 16000) wav = muscriptor::resample_frac(wav, sr, 16000);
if (format == "midi") {
auto midi = model.transcribe_to_midi(wav, opts);
if (output_path == "-") {
fwrite(midi.data(), 1, midi.size(), stdout);
} else {
std::ofstream f(output_path, std::ios::binary);
f.write(reinterpret_cast<const char*>(midi.data()),
static_cast<std::streamsize>(midi.size()));
std::fprintf(stderr, "Saved MIDI to %s (%zu bytes)\n", output_path.c_str(),
midi.size());
}
if (notes) {
std::fprintf(stderr, "Re-run with --format json to inspect the event stream.\n");
}
} else if (format == "jsonl" || format == "json") {
auto events = model.transcribe(wav, opts);
FILE* f = (output_path == "-") ? stdout : std::fopen(output_path.c_str(), "w");
if (!f) {
std::perror("fopen");
return 1;
}
write_json_events(events, f, format == "jsonl", /*include_progress=*/false);
if (f != stdout) {
std::fclose(f);
std::fprintf(stderr, "Saved %s to %s\n", format.c_str(), output_path.c_str());
}
if (notes) print_notes_stderr(events);
} else {
std::fprintf(stderr, "unknown format: %s\n", format.c_str());
return 1;
}
return 0;
}