UNPKG

@magenta/music

Version:

Make music with machine learning, in the browser.

1 lines 168 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@tensorflow/tfjs")):"function"==typeof define&&define.amd?define(["tf"],t):"object"==typeof exports?exports.music_vae=t(require("@tensorflow/tfjs")):e.music_vae=t(e.tf)}(self,(function(__WEBPACK_EXTERNAL_MODULE__2__){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=187)}({10:function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(35),o=r.tensorflow.magenta.NoteSequence},12:function(e,t,n){"use strict";n.r(t),n.d(t,"Level",(function(){return r})),n.d(t,"verbosity",(function(){return i})),n.d(t,"setVerbosity",(function(){return s})),n.d(t,"log",(function(){return a})),n.d(t,"logWithDuration",(function(){return u}));var r,o=n(15);!function(e){e[e.NONE=0]="NONE",e[e.WARN=5]="WARN",e[e.INFO=10]="INFO",e[e.DEBUG=20]="DEBUG"}(r||(r={}));let i=10;function s(e){e=e}function a(e,t="Magenta.js",n=10){if(0===n)throw Error("Logging level cannot be NONE.");if(i>=n){(5===n?console.warn:console.log)(`%c ${t} `,"background:magenta; color:white",e)}}function u(e,t,n="Magenta.js",r=10){a(`${e} in ${((o.d.now()-t)/1e3).toPrecision(3)}s`,n,r)}},13:function(e,t,n){"use strict";n.r(t),n.d(t,"MultipleTimeSignatureException",(function(){return i})),n.d(t,"BadTimeSignatureException",(function(){return s})),n.d(t,"NegativeTimeException",(function(){return a})),n.d(t,"MultipleTempoException",(function(){return u})),n.d(t,"QuantizationStatusException",(function(){return c})),n.d(t,"clone",(function(){return l})),n.d(t,"stepsPerQuarterToStepsPerSecond",(function(){return p})),n.d(t,"quantizeToStep",(function(){return m})),n.d(t,"quantizeNoteSequence",(function(){return f})),n.d(t,"isQuantizedSequence",(function(){return g})),n.d(t,"assertIsQuantizedSequence",(function(){return S})),n.d(t,"isRelativeQuantizedSequence",(function(){return y})),n.d(t,"assertIsRelativeQuantizedSequence",(function(){return P})),n.d(t,"isAbsoluteQuantizedSequence",(function(){return b})),n.d(t,"assertIsAbsoluteQuantizedSequence",(function(){return w})),n.d(t,"unquantizeSequence",(function(){return M})),n.d(t,"createQuantizedNoteSequence",(function(){return N})),n.d(t,"mergeInstruments",(function(){return q})),n.d(t,"replaceInstruments",(function(){return T})),n.d(t,"mergeConsecutiveNotes",(function(){return v})),n.d(t,"applySustainControlChanges",(function(){return A})),n.d(t,"concatenate",(function(){return O})),n.d(t,"trim",(function(){return _})),n.d(t,"split",(function(){return z}));var r=n(10),o=n(8);class i extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class s extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class a extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class u extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class c extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}function l(e){return r.a.decode(r.a.encode(e).finish())}function p(e,t){return e*t/60}function m(e,t,n=.5){const r=e*t;return Math.floor(r+(1-n))}function d(e){return e.controlChanges.concat(e.textAnnotations)}function h(e){if(e.tempos&&0!==e.tempos.length){if(e.tempos.sort((e,t)=>e.time-t.time),0!==e.tempos[0].time&&e.tempos[0].qpm!==o.DEFAULT_QUARTERS_PER_MINUTE)throw new u("NoteSequence has an implicit tempo change from initial "+o.DEFAULT_QUARTERS_PER_MINUTE+" qpm to "+`${e.tempos[0].qpm} qpm at ${e.tempos[0].time} seconds.`);for(let t=1;t<e.tempos.length;t++)if(e.tempos[t].qpm!==e.tempos[0].qpm)throw new u(`NoteSequence has at least one tempo change from ${e.tempos[0].qpm} qpm to ${e.tempos[t].qpm}qpm at ${e.tempos[t].time} seconds.`)}}function f(e,t){const n=l(e);if(n.quantizationInfo=r.a.QuantizationInfo.create({stepsPerQuarter:t}),n.timeSignatures.length>0){if(n.timeSignatures.sort((e,t)=>e.time-t.time),0!==n.timeSignatures[0].time&&(4!==n.timeSignatures[0].numerator||4!==n.timeSignatures[0].denominator))throw new i(`NoteSequence has an implicit change from initial 4/4 time signature to ${n.timeSignatures[0].numerator}/`+n.timeSignatures[0].denominator+" at "+n.timeSignatures[0].time+" seconds.");for(let e=1;e<n.timeSignatures.length;e++){const t=n.timeSignatures[e];if(t.numerator!==n.timeSignatures[0].numerator||t.denominator!==n.timeSignatures[0].denominator)throw new i("NoteSequence has at least one time signature change from "+n.timeSignatures[0].numerator+"/"+n.timeSignatures[0].denominator+" to "+`${t.numerator}/${t.denominator} `+`at ${t.time} seconds`)}n.timeSignatures[0].time=0,n.timeSignatures=[n.timeSignatures[0]]}else{const e=r.a.TimeSignature.create({numerator:4,denominator:4,time:0});n.timeSignatures.push(e)}const u=n.timeSignatures[0];if(!(c=u.denominator)||0!=(c&c-1))throw new s(`Denominator is not a power of 2. Time signature: ${u.numerator}/${u.denominator}`);var c;if(0===u.numerator)throw new s(`Numerator is 0. Time signature: ${u.numerator}/${u.denominator}`);if(n.tempos.length>0)h(n),n.tempos[0].time=0,n.tempos=[n.tempos[0]];else{const e=r.a.Tempo.create({qpm:o.DEFAULT_QUARTERS_PER_MINUTE,time:0});n.tempos.push(e)}const f=p(t,n.tempos[0].qpm);return n.totalQuantizedSteps=m(e.totalTime,f),function(e,t){for(const n of e.notes){if(n.quantizedStartStep=m(n.startTime,t),n.quantizedEndStep=m(n.endTime,t),n.quantizedEndStep===n.quantizedStartStep&&(n.quantizedEndStep+=1),n.quantizedStartStep<0||n.quantizedEndStep<0)throw new a("Got negative note time: start_step = "+n.quantizedStartStep+", end_step = "+n.quantizedEndStep);n.quantizedEndStep>e.totalQuantizedSteps&&(e.totalQuantizedSteps=n.quantizedEndStep)}d(e).forEach(e=>{if(e.quantizedStep=m(e.time,t),e.quantizedStep<0)throw new a("Got negative event time: step = "+e.quantizedStep)})}(n,f),n}function g(e){return e.quantizationInfo&&(e.quantizationInfo.stepsPerQuarter>0||e.quantizationInfo.stepsPerSecond>0)}function S(e){if(!g(e))throw new c(`NoteSequence ${e.id} is not quantized (missing quantizationInfo)`)}function y(e){return e.quantizationInfo&&e.quantizationInfo.stepsPerQuarter>0}function P(e){if(!y(e))throw new c(`NoteSequence ${e.id} is not quantized or is quantized based on absolute timing`)}function b(e){return e.quantizationInfo&&e.quantizationInfo.stepsPerSecond>0}function w(e){if(!b(e))throw new c(`NoteSequence ${e.id} is not quantized or is quantized based on relative timing`)}function M(e,t){P(e),h(e);const n=l(e);t?n.tempos&&n.tempos.length>0?n.tempos[0].qpm=t:n.tempos.push(r.a.Tempo.create({time:0,qpm:t})):t=e.tempos&&e.tempos.length>0?n.tempos[0].qpm:o.DEFAULT_QUARTERS_PER_MINUTE;const i=e=>e/n.quantizationInfo.stepsPerQuarter*(60/t);return n.totalTime=i(n.totalQuantizedSteps),n.notes.forEach(e=>{e.startTime=i(e.quantizedStartStep),e.endTime=i(e.quantizedEndStep),n.totalTime=Math.max(n.totalTime,e.endTime),delete e.quantizedStartStep,delete e.quantizedEndStep}),d(n).forEach(e=>{e.time=i(e.time)}),delete n.totalQuantizedSteps,delete n.quantizationInfo,n}function N(e=o.DEFAULT_STEPS_PER_QUARTER,t=o.DEFAULT_QUARTERS_PER_MINUTE){return r.a.create({quantizationInfo:{stepsPerQuarter:e},tempos:[{qpm:t}]})}function q(e){const t=l(e),n=t.notes.concat(t.pitchBends).concat(t.controlChanges),r=Array.from(new Set(n.filter(e=>!e.isDrum).map(e=>e.program)));return n.forEach(e=>{e.isDrum?(e.program=0,e.instrument=r.length):e.instrument=r.indexOf(e.program)}),t}function T(e,t){const n=new Set(e.notes.map(e=>e.instrument)),o=new Set(t.notes.map(e=>e.instrument)),i=[];e.notes.forEach(e=>{o.has(e.instrument)||i.push(r.a.Note.create(e))}),t.notes.forEach(e=>{n.has(e.instrument)&&i.push(r.a.Note.create(e))});const s=l(e);return s.notes=i.sort((e,t)=>{const n=e.instrument-t.instrument;return n||e.quantizedStartStep-t.quantizedStartStep}),s}function v(e){S(e);const t=l(e);t.notes=[];const n=e.notes.sort((e,t)=>{const n=e.instrument-t.instrument;return n||e.quantizedStartStep-t.quantizedStartStep}),o=new r.a.Note;o.pitch=n[0].pitch,o.instrument=n[0].instrument,o.quantizedStartStep=n[0].quantizedStartStep,o.quantizedEndStep=n[0].quantizedEndStep,t.notes.push(o);let i=0;for(let e=1;e<n.length;e++){const o=n[e],s=t.notes[i];if(s.instrument===o.instrument&&s.pitch===o.pitch&&o.quantizedStartStep===s.quantizedEndStep&&o.quantizedStartStep%16!=0)t.notes[i].quantizedEndStep+=o.quantizedEndStep-o.quantizedStartStep;else{const o=new r.a.Note;o.pitch=n[e].pitch,o.instrument=n[e].instrument,o.quantizedStartStep=n[e].quantizedStartStep,o.quantizedEndStep=n[e].quantizedEndStep,t.notes.push(o),i++}}return t}function A(e,t=64){let n;!function(e){e[e.SUSTAIN_ON=0]="SUSTAIN_ON",e[e.SUSTAIN_OFF=1]="SUSTAIN_OFF",e[e.NOTE_ON=2]="NOTE_ON",e[e.NOTE_OFF=3]="NOTE_OFF"}(n||(n={}));if(g(e))throw new Error("Can only apply sustain to unquantized NoteSequence.");const r=l(e),o=[];for(const e of r.notes)!1===e.isDrum&&(null!==e.startTime&&o.push({time:e.startTime,type:n.NOTE_ON,event:e}),null!==e.endTime&&o.push({time:e.endTime,type:n.NOTE_OFF,event:e}));for(const e of r.controlChanges)if(e.controlNumber===t){const t=e.controlValue;t>=64?o.push({time:e.time,type:n.SUSTAIN_ON,event:e}):t<64&&o.push({time:e.time,type:n.SUSTAIN_OFF,event:e})}o.sort((e,t)=>e.time-t.time);const i={},s={};let a=0;for(const e of o){a=e.time;const t=e.type,o=e.event;if(t===n.SUSTAIN_ON)s[o.instrument]=!0;else if(t===n.SUSTAIN_OFF){s[o.instrument]=!1;const e=[];o.instrument in i||(i[o.instrument]=[]);for(const t of i[o.instrument])t.endTime<a?(t.endTime=a,a>r.totalTime&&(r.totalTime=a)):e.push(t);i[o.instrument]=e}else if(t===n.NOTE_ON){if(!0===s[o.instrument]){const e=[];o.instrument in i||(i[o.instrument]=[]);for(const t of i[o.instrument])t.pitch===o.pitch?(t.endTime=a,t.startTime===t.endTime&&r.notes.push(t)):e.push(t);i[o.instrument]=e}o.instrument in i||(i[o.instrument]=[]),i[o.instrument].push(o)}else if(t===n.NOTE_OFF)if(!0===s[o.instrument]);else{const e=i[o.instrument].indexOf(o);e>-1&&i[o.instrument].splice(e,1)}}for(const e of Object.values(i))for(const t of e)t.endTime=a,r.totalTime=a;return r}function O(e,t){if(t&&t.length!==e.length)throw new Error("Number of sequences to concatenate and their individual\n durations does not match.");if(g(e[0])){for(let t=0;t<e.length;++t)if(S(e[t]),e[t].quantizationInfo.stepsPerQuarter!==e[0].quantizationInfo.stepsPerQuarter)throw new Error("Not all sequences have the same quantizationInfo");return E(e,"totalQuantizedSteps","quantizedStartStep","quantizedEndStep",t)}return E(e,"totalTime","startTime","endTime",t)}function _(e,t,n,r){return g(e)?I(e,t,n,"totalQuantizedSteps","quantizedStartStep","quantizedEndStep",r):I(e,t,n,"totalTime","startTime","endTime",r)}function E(e,t,n,o,i){let s,a=0;for(let u=0;u<e.length;++u){const c=i?i[u]:e[u][t];if(0===c)throw Error(`Sequence ${e[u].id} has no ${t}, and no individual duration was provided.`);0===u?s=l(e[0]):Array.prototype.push.apply(s.notes,e[u].notes.map(e=>{const t=r.a.Note.create(e);return t[n]+=a,t[o]+=a,t})),a+=c}return s[t]=a,s}function I(e,t,n,r,o,i,s){const a=l(e);a[r]=n,a.notes=a.notes.filter(e=>e[o]>=t&&e[o]<=n&&(s||e[i]<=n)),a[r]-=t;for(let e=0;e<a.notes.length;e++)a.notes[e][o]-=t,a.notes[e][i]-=t,s&&(a.notes[e][i]=Math.min(a.notes[e][i],a[r]));return a}function z(e,t){S(e);const n=l(e),o=n.notes.sort((e,t)=>e.quantizedStartStep-t.quantizedStartStep),i=[];let s=0,a=[];for(let e=0;e<o.length;e++){const u=o[e],c=u.quantizedStartStep,p=u.quantizedEndStep;if(u.quantizedStartStep-=s,u.quantizedEndStep-=s,!(u.quantizedStartStep<0))if(u.quantizedEndStep<=t)a.push(u);else{if(u.quantizedStartStep<t){const e=r.a.Note.create(u);e.quantizedEndStep=t,e.startTime=e.endTime=void 0,a.push(e),u.quantizedStartStep=s+t,u.quantizedEndStep=p}else u.quantizedStartStep=c,u.quantizedEndStep=p;if((u.quantizedEndStep>t||u.quantizedStartStep>t)&&(e-=1),0!==a.length){const e=l(n);e.notes=a,e.totalQuantizedSteps=t,i.push(e)}a=[],s+=t}}if(0!==a.length){const e=l(n);e.notes=a,e.totalQuantizedSteps=t,i.push(e)}return i}},15:function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return o})),n.d(t,"d",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"b",(function(){return u}));const r=function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==e)return e;throw new Error("cannot find the global object")}(),o=r.fetch.bind(r),i=r.performance,s=(r.navigator,!!r.webkitOfflineAudioContext),a=void 0!==r.WorkerGlobalScope;function u(e){if(e=s?44100:e,a)throw new Error("Cannot use offline audio context in a web worker.");const t=r.webkitOfflineAudioContext;return s?new t(1,e,e):new r.OfflineAudioContext(1,e,e)}}).call(this,n(21))},18:function(e,t,n){"use strict";(function(e){var r=t;function o(e,t,n){for(var r=Object.keys(t),o=0;o<r.length;++o)void 0!==e[r[o]]&&n||(e[r[o]]=t[r[o]]);return e}function i(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&o(this,n)}return(t.prototype=Object.create(Error.prototype)).constructor=t,Object.defineProperty(t.prototype,"name",{get:function(){return e}}),t.prototype.toString=function(){return this.name+": "+this.message},t}r.asPromise=n(51),r.base64=n(52),r.EventEmitter=n(53),r.float=n(54),r.inquire=n(55),r.utf8=n(56),r.pool=n(57),r.LongBits=n(58),r.isNode=Boolean(void 0!==e&&e&&e.process&&e.process.versions&&e.process.versions.node),r.global=r.isNode&&e||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},r.isString=function(e){return"string"==typeof e||e instanceof String},r.isObject=function(e){return e&&"object"==typeof e},r.isset=r.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=o,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=i,r.ProtocolError=i("ProtocolError"),r.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},r.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):r._Buffer_from=r._Buffer_allocUnsafe=null}}).call(this,n(21))},187:function(e,t,n){"use strict";n.r(t),n.d(t,"MidiMe",(function(){return a})),n.d(t,"Decoder",(function(){return y})),n.d(t,"Encoder",(function(){return d})),n.d(t,"MusicVAE",(function(){return A}));var r=n(2),o=n(12),i=n(15);class s extends r.layers.Layer{constructor(){super({})}computeOutputShape(e){return e[0]}call(e){return r.tidy(()=>{const[t,n]=e;return r.add(r.mul(r.randomNormal(n.shape),n),t)})}getClassName(){return"SamplingLayer"}}class a{constructor(e={}){this.trained=!1,this.initialized=!1,this.config={encoder_layers:e.encoder_layers||[1024,256,64],decoder_layers:e.decoder_layers||[64,256,1024],input_size:e.input_size||256,latent_size:e.latent_size||4,beta:e.beta||1,epochs:e.epochs||10}}dispose(){this.initialized&&(this.encoder.dispose(),this.decoder.dispose(),this.vae.dispose(),this.initialized=!1)}initialize(){this.dispose();const e=i.d.now(),t=r.input({shape:[this.config.input_size]});this.encoder=this.getEncoder(t);const[n,,]=this.encoder.apply(t);this.decoder=this.getDecoder(n.shape.slice(1));const s=this.decoder.apply(n);this.vae=r.model({inputs:t,outputs:s,name:"vae"}),this.initialized=!0,o.logWithDuration("Initialized model",e,"MidiMe")}async train(e,t){const n=i.d.now();this.trained=!1;let s=.001;!1===r.ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")&&!1===r.ENV.get("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&1===r.ENV.get("WEBGL_VERSION")&&(s=5e-5);const a=r.train.adam(s);for(let n=0;n<this.config.epochs;n++)await r.nextFrame(),await a.minimize(()=>r.tidy(()=>{const[,r,o]=this.encoder.predict(e),i=this.vae.predict(e),s=this.loss(r,o,i,e);return t&&t(n,{y:i,total:s.totalLoss.arraySync(),losses:[s.reconLoss.arraySync(),s.latentLoss.arraySync()]}),s.totalLoss})),await r.nextFrame();o.logWithDuration("Training finished",n,"MidiMe"),this.trained=!0,a.dispose()}async sample(e=1){return this.initialized||await this.initialize(),r.tidy(()=>{const t=r.randomNormal([e,this.config.latent_size]);return this.decoder.predict(t)})}async decode(e){return this.initialized||await this.initialize(),this.decoder.predict(e)}async encode(e){this.initialized||await this.initialize();const[t,,]=this.encoder.predict(e);return t}predict(e){return this.vae.predict(e)}getEncoder(e){let t=e;for(let e=0;e<this.config.encoder_layers.length;e++)t=r.layers.dense({units:this.config.encoder_layers[e],activation:"relu"}).apply(t);const n=this.getAffineLayers(t,this.config.latent_size,e,!1),o=this.getAffineLayers(t,this.config.latent_size,e,!0),i=(new s).apply([n,o]);return r.model({inputs:e,outputs:[i,n,o],name:"encoder"})}getDecoder(e){const t=r.input({shape:e});let n=t;for(let e=0;e<this.config.decoder_layers.length;e++)n=r.layers.dense({units:this.config.decoder_layers[e],activation:"relu"}).apply(n);const o=this.getAffineLayers(n,this.config.input_size,t,!1);return r.model({inputs:t,outputs:o,name:"decoder"})}loss(e,t,n,o){return r.tidy(()=>{const i=this.klLoss(e,t),s=this.reconstructionLoss(o,n);return{latentLoss:i,reconLoss:s,totalLoss:r.add(s,r.mul(i,this.config.beta))}})}reconstructionLoss(e,t){return r.tidy(()=>{const n=r.pow(r.sub(e,t),2),o=r.div(n,r.mul(2,r.pow(r.ones([1]),2)));return r.mean(r.sum(o,-1))})}klLoss(e,t){return r.tidy(()=>{const n=r.pow(e,2),o=r.pow(t,2),i=r.add(1,r.log(o)),s=r.add(n,o),a=r.sub(i,s),u=r.div(r.mean(r.sum(a,-1)),2);return r.mul(-1,u)})}getAffineLayers(e,t,n,o){const i=r.layers.dense({units:t}).apply(e);return o?r.layers.activation({activation:"softplus"}).apply(i):i}}var u=n(37),c=n(8),l=n(36);class p{constructor(e,t){if(void 0===e)throw Error("`kernel` is undefined.");if(void 0===t)throw Error("`bias` is undefined.");this.kernel=e,this.bias=t}}function m(e,t){return t.matMul(e.kernel).add(e.bias)}class d{}class h{constructor(e,t){this.lstmFwVars=e,this.lstmBwVars=t}process(e){return r.tidy(()=>[this.singleDirection(e,!0),this.singleDirection(e,!1)])}singleDirection(e,t){const n=e.shape[0],o=e.shape[1],i=t?this.lstmFwVars:this.lstmBwVars;let s=[r.zeros([n,i.bias.shape[0]/4]),r.zeros([n,i.bias.shape[0]/4])];const a=r.scalar(1),u=(e,t)=>r.basicLSTMCell(a,i.kernel,i.bias,e,t[0],t[1]),c=r.split(e.toFloat(),o,1),l=[];for(const e of t?c:c.reverse())s=u(e.squeeze([1]),s),l.push(s[1]);return t?l:l.reverse()}}class f extends d{constructor(e,t,n){super(),this.bidirectionalLstm=new h(e,t),this.muVars=n,this.zDims=n?this.muVars.bias.shape[0]:null}encode(e,t){if(t)throw new Error("Variable-length segments not supported in flat encoder");return r.tidy(()=>{const[t,n]=this.bidirectionalLstm.process(e),o=r.concat([t[t.length-1],n[0]],1);return this.muVars?m(this.muVars,o):o})}}class g extends d{constructor(e,t,n){super(),this.baseEncoders=e,this.numSteps=t,this.muVars=n,this.zDims=this.muVars.bias.shape[0]}encode(e,t){if(t){if(1!==e.shape[0])throw new Error("When using variable-length segments, batch size must be 1.");if(t.length!==this.numSteps[0])throw new Error("Must provide length for all variable-length segments.")}return r.tidy(()=>{let n=e;for(let e=0;e<this.baseEncoders.length;++e){const o=this.numSteps[e],i=r.split(n,o,1),s=[];for(let n=0;n<o;++n)s.push(this.baseEncoders[e].encode(0===e&&t?r.slice3d(i[n],[0,0,0],[1,t[n],-1]):i[n]));n=r.stack(s,1)}return m(this.muVars,n.squeeze([1]))})}}function S(e,t,n){const o=[],i=[],s=[],a=r.split(m(n,e).tanh(),2*t.length,1);for(let e=0;e<t.length;++e){const n=t[e],u=r.scalar(1);o.push((e,t,o)=>r.basicLSTMCell(u,n.kernel,n.bias,e,t,o)),i.push(a[2*e]),s.push(a[2*e+1])}return{cell:o,c:i,h:s}}class y{}class P extends y{constructor(e,t,n,r,o,i){super(),this.lstmCellVars=e,this.zToInitStateVars=t,this.outputProjectVars=n,this.zDims=this.zToInitStateVars.kernel.shape[0],this.outputDims=r||n.bias.shape[0],o&&i&&(this.controlBidirectionalLstm=new h(o,i))}decode(e,t,n,o,i){const s=e.shape[0];return r.tidy(()=>{const a=S(e,this.lstmCellVars,this.zToInitStateVars);let u=i?r.expandDims(i,0):void 0;const c=[];let l=n||r.zeros([s,this.outputDims]);if(this.controlBidirectionalLstm){const[e,t]=this.controlBidirectionalLstm.process(u);u=r.concat([r.stack(e,1),r.stack(t,1)],2)}const p=u?r.split(r.tile(u,[s,1,1]),i.shape[0],1):void 0;for(let n=0;n<t;++n){const t=p?[l,e,r.squeeze(p[n],[1])]:[l,e];[a.c,a.h]=r.multiRNNCell(a.cell,r.concat(t,1),a.c,a.h);const i=m(this.outputProjectVars,a.h[a.h.length-1]);l=this.sample(i,o),c.push(l)}return r.stack(c,1)})}}class b extends P{sample(e,t){const n=e;return(t?r.greaterEqual(r.sigmoid(n.div(r.scalar(t))),r.randomUniform(n.shape)):r.greaterEqual(n,0)).toFloat()}}class w extends P{sample(e,t){const n=e,o=t?r.multinomial(n.div(r.scalar(t)),1).as1D():n.argMax(1).as1D();return r.oneHot(o,this.outputDims).toFloat()}}class M extends P{constructor(e,t,n,r,o,i){super(e,t,n,r.numDims,o,i),this.nade=r}sample(e,t){const[n,o]=r.split(e,[this.nade.numHidden,this.nade.numDims],1);return this.nade.sample(n,o)}}class N extends P{sample(e,t){let[n,o,i]=r.split(e,3,1);if(o=r.sigmoid(o),i=r.tanh(i),t){n=r.sigmoid(n.div(r.scalar(t)));const e=r.randomUniform(n.shape,0,1);n=r.greater(n,e).toFloat()}else n=r.greater(r.sigmoid(n),.5).toFloat();return r.concat([n,o,i],1)}}class q extends y{constructor(e){super(),this.coreDecoders=e,this.numDecoders=this.coreDecoders.length,this.zDims=this.coreDecoders[0].zDims,this.outputDims=this.coreDecoders.reduce((e,t)=>e+t.outputDims,0)}decodeSeparately(e,t,n,r,o){const i=[];for(let s=0;s<this.coreDecoders.length;++s)i.push(this.coreDecoders[s].decode(e,t,n[s],r,o));return i}decode(e,t,n,o,i){return r.tidy(()=>{const s=this.decodeSeparately(e,t,this.coreDecoders.map(e=>n),o,i);return r.concat(s,-1)})}}class T extends y{constructor(e,t,n,r){super(),this.splitDecoder=new q(e),this.lstmCellVars=t,this.zToInitStateVars=n,this.numSteps=r,this.zDims=this.zToInitStateVars.kernel.shape[0],this.outputDims=this.splitDecoder.outputDims}decode(e,t,n,o,i){const s=e.shape[0];return r.tidy(()=>{const n=S(e,this.lstmCellVars,this.zToInitStateVars),a=[];let u=new Array(this.splitDecoder.numDecoders).fill(void 0);const c=r.zeros([s,1]),l=i?r.split(i,this.numSteps):void 0;for(let e=0;e<this.numSteps;++e){[n.c,n.h]=r.multiRNNCell(n.cell,c,n.c,n.h);const i=this.splitDecoder.decodeSeparately(n.h[n.h.length-1],t/this.numSteps,u,o,l?l[e]:void 0);a.push(r.concat(i,-1)),u=i.map(e=>e.slice([0,e.shape[1]-1,0],[s,1,e.shape[e.rank-1]]).squeeze([1]).toFloat())}return r.concat(a,1)})}}class v{constructor(e,t){this.numDims=e.shape[0],this.numHidden=e.shape[2],this.encWeights=e.as2D(this.numDims,this.numHidden),this.decWeightsT=t.as2D(this.numDims,this.numHidden)}sample(e,t){const n=e.shape[0];return r.tidy(()=>{const o=[];let i=e.clone();for(let e=0;e<this.numDims;e++){const s=r.sigmoid(i),a=this.encWeights.slice([e,0],[1,this.numHidden]).as1D(),u=this.decWeightsT.slice([e,0],[1,this.numHidden]),c=t.slice([0,e],[n,1]).add(r.matMul(s,u,!1,!0)).sigmoid().greaterEqual(r.scalar(.5)).toFloat().as1D();e<this.numDims-1&&(i=i.add(r.outerProduct(c.toFloat(),a))),o.push(c)}return r.stack(o,1)})}}class A{constructor(e,t){this.initialized=!1,this.checkpointURL=e,this.spec=t}instantiateFromSpec(){this.dataConverter=l.converterFromSpec(this.spec.dataConverter),this.chordEncoder=this.spec.chordEncoder?u.chordEncoderFromType(this.spec.chordEncoder):void 0}dispose(){void 0!==this.rawVars&&Object.keys(this.rawVars).forEach(e=>this.rawVars[e].dispose()),this.encoder=void 0,this.decoder=void 0,this.initialized=!1}getLstmLayers(e,t){const n=[];let r=0;for(;;){const o=e.replace("%d",r.toString());if(!(o+"kernel"in t))break;n.push(new p(t[o+"kernel"],t[o+"bias"])),++r}return n}async initialize(){this.dispose();const e=i.d.now();this.spec||await Object(i.a)(this.checkpointURL+"/config.json").then(e=>e.json()).then(e=>{if("MusicVAE"!==e.type)throw new Error("Attempted to instantiate MusicVAE model with incorrect type:\n "+e.type);this.spec=e}),this.instantiateFromSpec();const t="cell_%d/bidirectional_rnn/%s/multi_rnn_cell/cell_0/lstm_cell/",n="encoder/"+t,s="encoder/hierarchical_level_%d/"+t.replace("%d","0"),a="control_preprocessing/"+t,u=await Object(i.a)(this.checkpointURL+"/weights_manifest.json").then(e=>e.json()).then(e=>r.io.loadWeights(e,this.checkpointURL));this.rawVars=u;const c=new p(u["encoder/mu/kernel"],u["encoder/mu/bias"]);if(this.dataConverter.numSegments){const e=this.getLstmLayers(s.replace("%s","fw"),u),t=this.getLstmLayers(s.replace("%s","bw"),u);if(e.length!==t.length||2!==e.length)throw Error(`Only 2 hierarchical encoder levels are supported. Got ${e.length} forward and ${t.length} backward.`);const n=[0,1].map(n=>new f(e[n],t[n]));this.encoder=new g(n,[this.dataConverter.numSegments,1],c)}else{const e=this.getLstmLayers(n.replace("%s","fw"),u),t=this.getLstmLayers(n.replace("%s","bw"),u);if(e.length!==t.length||1!==e.length)throw Error(`Only single-layer bidirectional encoders are supported. Got ${e.length} forward and ${t.length} backward.`);this.encoder=new f(e[0],t[0],c)}const l=a.replace("%s","fw").replace("%d","0")+"kernel"in u,m=this.dataConverter.numSegments?"core_decoder/":"",d=[];if(this.dataConverter.NUM_SPLITS)for(let e=0;e<this.dataConverter.NUM_SPLITS;++e)d.push(`${m}core_decoder_${e}/decoder/`);else d.push(m+"decoder/");let h=[null],S=[null];if(l&&(h=this.getLstmLayers(a.replace("%s","fw"),u),S=this.getLstmLayers(a.replace("%s","bw"),u),h.length!==S.length||1!==h.length))throw Error(`Only single-layer bidirectional control preprocessing is supported. Got ${h.length} forward and ${S.length} backward.`);const y=d.map(e=>{const t=this.getLstmLayers(e+"multi_rnn_cell/cell_%d/lstm_cell/",u),n=new p(u[e+"z_to_initial_state/kernel"],u[e+"z_to_initial_state/bias"]),r=new p(u[e+"output_projection/kernel"],u[e+"output_projection/bias"]);return e+"nade/w_enc"in u?new M(t,n,r,new v(u[e+"nade/w_enc"],u[e+"nade/w_dec_t"]),h[0],S[0]):"GrooveConverter"===this.spec.dataConverter.type?new N(t,n,r,void 0,h[0],S[0]):this.spec.useBooleanDecoder?new b(t,n,r,void 0,h[0],S[0]):new w(t,n,r,void 0,h[0],S[0])});if(this.dataConverter.numSegments){const e=this.getLstmLayers("decoder/hierarchical_level_0/cell_%d/lstm_cell/",u),t=new p(u["decoder/hierarchical_level_0/initial_state/kernel"],u["decoder/hierarchical_level_0/initial_state/bias"]);this.decoder=new T(y,e,t,this.dataConverter.numSegments)}else 1===y.length?this.decoder=y[0]:this.decoder=new q(y);this.zDims=this.decoder.zDims,this.initialized=!0,o.logWithDuration("Initialized model",e,"MusicVAE")}isInitialized(){return this.initialized}checkControlArgs(e){const t=(e=e||{}).extraControls||{};if(this.chordEncoder&&!e.chordProgression)throw new Error("Chord progression expected but not provided.");if(!this.chordEncoder&&e.chordProgression)throw new Error("Unexpected chord progression provided.");if(this.chordEncoder&&this.dataConverter.endTensor&&e.chordProgression.length>1)throw new Error("Multiple chords not supported when using variable-length segments.");if(this.spec.conditionOnKey&&null==e.key)throw new Error("Key expected but not provided.");if(!this.spec.conditionOnKey&&null!=e.key)throw new Error("Unexpected key provided.");if(this.spec.extraControls)for(const e of this.spec.extraControls){if(!(e.name in t))throw new Error("Missing control signal: "+e.name);if(t[e.name].shape[1]!==e.depth)throw new Error(`Control signal ${e.name} has invalid depth: ${t[e.name].shape[1]} != ${e.depth}`)}const n=this.spec.extraControls?new Set(this.spec.extraControls.map(e=>e.name)):new Set;for(const e in t)n.has(e)||o.log("Unspecified control signal provided: "+e,"MusicVAE",5)}controlArgsToTensor(e){return e=e||{},r.tidy(()=>{const t=[];if(e.chordProgression){const n=this.encodeChordProgression(e.chordProgression);t.push(n)}if(null!=e.key){const n=r.oneHot(r.fill([this.dataConverter.numSteps],e.key,"int32"),12);t.push(n)}if(e.extraControls)for(const n of this.spec.extraControls)t.push(e.extraControls[n.name]);return t.length?r.concat2d(t,1):void 0})}async interpolateTensors(e,t,n,o){this.initialized||await this.initialize();const i=await this.encodeTensors(e,o),s=r.tidy(()=>this.getInterpolatedZs(i,t));i.dispose();const a=await this.decodeTensors(s,n,o);return s.dispose(),a}async interpolate(e,t,n,i){this.checkControlArgs(i),this.initialized||await this.initialize();const s=await this.encode(e,i),a=r.tidy(()=>this.getInterpolatedZs(s,t));s.dispose();const u=this.decode(a,n,i);return a.dispose(),u.then(()=>o.logWithDuration("Interpolation completed",0,"MusicVAE",20)),u}async getSegmentLengths(e){if(e.shape[0]>1)throw new Error("Variable-length segments not supported for batch size > 1.");const t=this.dataConverter.numSteps,n=this.dataConverter.numSegments,o=r.tidy(()=>r.min(r.equal(e.squeeze([0]),this.dataConverter.endTensor.expandDims(0)),1)),i=await o.data();o.dispose();const s=t/n,a=[];let u=0,c=i.indexOf(1);for(;-1!==c;)a.push(c-u+1),u+=s,c=i.indexOf(1,u);if(a.length!==n)throw new Error(`Incorrect number of segments: ${a.length} != ${n}`);return a}encodeChordProgression(e){const t=this.dataConverter.numSteps,n=this.dataConverter.numSegments,o=this.dataConverter.SEGMENTED_BY_TRACK?t/n:t,i=this.dataConverter.SEGMENTED_BY_TRACK?r.concat2d([this.chordEncoder.encode(c.NO_CHORD).expandDims(0),this.chordEncoder.encodeProgression(e,o-1)],0):this.chordEncoder.encodeProgression(e,o);return this.dataConverter.SEGMENTED_BY_TRACK?r.tile(i,[n,1]):i}async encodeTensors(e,t){this.checkControlArgs(t),this.initialized||await this.initialize();const n=this.dataConverter.endTensor?await this.getSegmentLengths(e):void 0;return r.tidy(()=>{const o=this.controlArgsToTensor(t),i=[e];if(o){const t=r.tile(r.expandDims(o,0),[e.shape[0],1,1]);i.push(t)}const s=r.concat3d(i,2);return this.encoder.encode(s,n)})}async encode(e,t){this.initialized||await this.initialize();const n=i.d.now(),s=r.tidy(()=>r.stack(e.map(e=>this.dataConverter.toTensor(e)))),a=await this.encodeTensors(s,t);return s.dispose(),o.logWithDuration("Encoding completed",n,"MusicVAE",20),a}async decodeTensors(e,t,n){return this.checkControlArgs(n),this.initialized||await this.initialize(),r.tidy(()=>{const r=this.controlArgsToTensor(n);return this.decoder.decode(e,this.dataConverter.numSteps,void 0,t,r)})}async decode(e,t,n,s=c.DEFAULT_STEPS_PER_QUARTER,a=c.DEFAULT_QUARTERS_PER_MINUTE){this.initialized||await this.initialize();const u=i.d.now(),l=await this.decodeTensors(e,t,n),p=r.tidy(()=>r.split(l,l.shape[0]).map(e=>e.squeeze([0]))),m=[];for(const e of p)m.push(await this.dataConverter.toNoteSequence(e,s,a)),e.dispose();return l.dispose(),o.logWithDuration("Decoding completed",u,"MusicVAE",20),m}getInterpolatedZs(e,t){if("number"==typeof t&&(t=[t]),2!==e.shape[0]&&4!==e.shape[0])throw new Error("Invalid number of input sequences. Requires length 2, or 4");if(1!==t.length&&2!==t.length)throw new Error("Invalid number of dimensions. Requires length 1, or 2.");const n=t[0],o=2===t.length?t[1]:n;return r.tidy(()=>{const t=r.linspace(0,1,n),i=e.slice([0,0],[1,e.shape[1]]).as1D(),s=e.slice([1,0],[1,e.shape[1]]).as1D();if(2===e.shape[0]){const e=s.sub(i);return r.outerProduct(t,e).add(i)}if(4===e.shape[0]){const a=r.linspace(0,1,o),u=e.slice([2,0],[1,e.shape[1]]).as1D(),c=e.slice([3,0],[1,e.shape[1]]).as1D(),l=r.scalar(1).sub(t),p=r.scalar(1).sub(a);let m=i.mul(r.outerProduct(p,l).as3D(o,n,1));return m=r.addStrict(m,s.mul(r.outerProduct(a,l).as3D(o,n,1))),m=r.addStrict(m,u.mul(r.outerProduct(p,t).as3D(o,n,1))),m=r.addStrict(m,c.mul(r.outerProduct(a,t).as3D(o,n,1))),m.as2D(n*o,e.shape[1])}throw new Error("Invalid number of note sequences. Requires length 2, or 4")})}async sampleTensors(e,t=.5,n){this.checkControlArgs(n),this.initialized||await this.initialize();const o=r.tidy(()=>r.randomNormal([e,this.decoder.zDims])),i=await this.decodeTensors(o,t,n);return o.dispose(),i}async sample(e,t=.5,n,s=c.DEFAULT_STEPS_PER_QUARTER,a=c.DEFAULT_QUARTERS_PER_MINUTE){this.checkControlArgs(n),this.initialized||await this.initialize();const u=i.d.now(),l=r.tidy(()=>r.randomNormal([e,this.decoder.zDims])),p=this.decode(l,t,n,s,a);return l.dispose(),p.then(()=>o.logWithDuration("Sampling completed",u,"MusicVAE",20)),p}async similarTensors(e,t,n,o,i){if(n<0||n>1)throw new Error("Similarity must be between 0 and 1.");this.initialized||await this.initialize();const s=r.expandDims(e,0),a=await this.encodeTensors(s,i);s.dispose();const u=r.tidy(()=>{const e=r.randomNormal([t,this.decoder.zDims]);return r.add(a.mul(n),e.mul(1-n))});a.dispose();const c=await this.decodeTensors(u,o,i);return u.dispose(),c}async similar(e,t,n,i,s){if(this.checkControlArgs(s),n<0||n>1)throw new Error("Similarity must be between 0 and 1.");this.initialized||await this.initialize();const a=await this.encode([e],s),u=r.tidy(()=>{const e=r.randomNormal([t,this.decoder.zDims]);return r.add(a.mul(n),e.mul(1-n))});a.dispose();const c=this.decode(u,i,s);return u.dispose(),c.then(()=>o.logWithDuration("Similar sequence generation completed",0,"MusicVAE",20)),c}}},2:function(e,t){e.exports=__WEBPACK_EXTERNAL_MODULE__2__},21:function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},23:function(e,t,n){"use strict";n.r(t),n.d(t,"NO_EVENT",(function(){return s})),n.d(t,"NOTE_OFF",(function(){return a})),n.d(t,"Melody",(function(){return u})),n.d(t,"MelodyRhythm",(function(){return c})),n.d(t,"MelodyShape",(function(){return l})),n.d(t,"MelodyRegister",(function(){return p}));var r=n(2),o=n(10),i=n(13);const s=0,a=1;class u{constructor(e,t,n){this.events=e,this.minPitch=t,this.maxPitch=n}static fromNoteSequence(e,t,n,r=!0,o){i.assertIsQuantizedSequence(e);const s=e.notes.sort((e,t)=>e.quantizedStartStep===t.quantizedStartStep?t.pitch-e.pitch:e.quantizedStartStep-t.quantizedStartStep),c=new Int32Array(o||e.totalQuantizedSteps);let l=-1;return s.forEach(e=>{if(e.quantizedStartStep===l){if(r)return;throw new Error("`NoteSequence` is not monophonic.")}if(e.pitch<t||e.pitch>n)throw Error("`NoteSequence` has a pitch outside of the valid range: "+e.pitch);c[e.quantizedStartStep]=e.pitch-t+2,c[e.quantizedEndStep]=a,l=e.quantizedStartStep}),new u(c,t,n)}toNoteSequence(e,t){const n=i.createQuantizedNoteSequence(e,t);let r=null;for(let e=0;e<this.events.length;++e){const t=this.events[e];switch(t){case s:break;case a:r&&(r.quantizedEndStep=e,n.notes.push(r),r=null);break;default:r&&(r.quantizedEndStep=e,n.notes.push(r)),r=o.a.Note.create({pitch:t-2+this.minPitch,quantizedStartStep:e})}}return r&&(r.quantizedEndStep=this.events.length,n.notes.push(r)),n.totalQuantizedSteps=this.events.length,n}}class c{constructor(){this.depth=1}extract(e){const t=e.events.length,n=r.buffer([t,1]);for(let r=0;r<t;++r)n.set(e.events[r]>=2?1:0,r,0);return n.toTensor().as2D(t,1)}}class l{constructor(){this.depth=3}extract(e){const t=e.events.length,n=r.buffer([t,3]);let o=null,i=null;for(let r=0;r<t;++r)if(e.events[r]>=2){if(null!==o){let t;0===n.get(o,0)&&0===n.get(o,1)&&0===n.get(o,2)&&(o=-1),t=e.events[r]<i?0:e.events[r]>i?2:1;for(let e=r;e>o;--e)n.set(1,e,t)}o=r,i=e.events[r]}if(o!==t-1)if(null===o||0===n.get(o,0)&&0===n.get(o,1)&&0===n.get(o,2))for(let e=0;e<t;++e)n.set(1,e,1);else for(let e=t-1;e>o;--e)for(let t=0;t<3;t++)n.set(n.get(o,t),e,t);return n.toTensor().as2D(t,3)}}class p{constructor(e){this.boundaryPitches=e,this.depth=e.length+1}meanMelodyPitch(e){let t=0,n=0,r=null;for(let o=0;o<e.events.length;++o)e.events[o]===a?r=null:e.events[o]>=2&&(r=e.minPitch+e.events[o]-2),null!==r&&(t+=r,n+=1);return n?t/n:null}extract(e){const t=e.events.length,n=this.meanMelodyPitch(e);if(null===n)return r.zeros([t,this.depth]);let o=0;for(;o<this.boundaryPitches.length&&n>=this.boundaryPitches[o];)o++;const i=r.buffer([t,this.depth]);for(let e=0;e<t;++e)i.set(1,e,o);return i.toTensor().as2D(t,this.depth)}}},29:function(e,t,n){"use strict";n.r(t),n.d(t,"Performance",(function(){return a}));var r=n(10),o=n(8),i=n(13),s=n(12);class a{constructor(e,t,n,r,o){this.events=e,this.maxShiftSteps=t,this.numVelocityBins=n,this.program=r,this.isDrum=o}static fromNoteSequence(e,t,n,r){i.assertIsQuantizedSequence(e);const s=e.notes.filter((e,t)=>void 0===r||e.instrument===r),u=s.sort((e,t)=>e.startTime===t.startTime?e.pitch-t.pitch:e.startTime-t.startTime),c=u.map((e,t)=>({step:e.quantizedStartStep,index:t,isOffset:0})),l=u.map((e,t)=>({step:e.quantizedEndStep,index:t,isOffset:1})),p=c.concat(l).sort((e,t)=>e.step===t.step?e.index===t.index?e.isOffset-t.isOffset:e.index-t.index:e.step-t.step),m=n?Math.ceil((o.MIDI_VELOCITIES-1)/n):void 0,d=[];let h=0,f=n;for(const e of p){if(e.step>h){for(;e.step>h+t;)d.push({type:"time-shift",steps:t}),h+=t;d.push({type:"time-shift",steps:e.step-h}),h=e.step}if(e.isOffset)d.push({type:"note-off",pitch:u[e.index].pitch});else{if(m){const t=Math.floor((u[e.index].velocity-o.MIN_MIDI_VELOCITY-1)/m)+1;t!==f&&(d.push({type:"velocity-change",velocityBin:t}),f=t)}d.push({type:"note-on",pitch:u[e.index].pitch})}}const g=!!s.some(e=>e.isDrum)&&(!s.some(e=>!e.isDrum)||void 0),S=Array.from(new Set(s.map(e=>e.program))),y=g||1!==S.length?void 0:S[0],P=new a(d,t,n,y,g);return P.setNumSteps(e.totalQuantizedSteps),P}getNumSteps(){return this.events.filter(e=>"time-shift"===e.type).map(e=>e.steps).reduce((e,t)=>e+t,0)}setNumSteps(e){let t=this.getNumSteps();if(t<e){if(this.events.length){const n=this.events[this.events.length-1];if("time-shift"===n.type){const r=Math.min(e-t,this.maxShiftSteps-n.steps);n.steps+=r,t+=r}}for(;t<e;)t+this.maxShiftSteps>e?(this.events.push({type:"time-shift",steps:e-t}),t=e):(this.events.push({type:"time-shift",steps:this.maxShiftSteps}),t+=this.maxShiftSteps)}else if(t>e)for(;this.events.length&&t>e;){const n=this.events[this.events.length-1];"time-shift"===n.type?t-n.steps<e?(n.steps-=t-e,t=e):(this.events.pop(),t-=n.steps):this.events.pop()}}toNoteSequence(e){const t=this.numVelocityBins?Math.ceil((o.MIDI_VELOCITIES-1)/this.numVelocityBins):void 0,n=r.a.create();let i=0,a=void 0;const u=new Map;for(let e=o.MIN_MIDI_PITCH;e<=o.MAX_MIDI_PITCH;++e)u.set(e,[]);for(const c of this.events)switch(c.type){case"note-on":u.get(c.pitch).push([i,a]);break;case"note-off":const l=u.get(c.pitch);if(l.length){const[t,o]=l.shift();i>t?n.notes.push(r.a.Note.create({pitch:c.pitch,velocity:o,instrument:e,quantizedStartStep:t,quantizedEndStep:i,program:this.program,isDrum:this.isDrum})):s.log(`Ignoring zero-length note: (pitch = ${c.pitch}, step = ${i})`,"Performance")}else s.log(`Ignoring note-off with no previous note-on:(pitch = ${c.pitch}, step = ${i})`,"Performance");break;case"time-shift":i+=c.steps;break;case"velocity-change":if(!t)throw new Error("Unexpected velocity change event: "+c);a=o.MIN_MIDI_VELOCITY+(c.velocityBin-1)*t+1;break;default:throw new Error("Unrecognized performance event: "+c)}return u.forEach((t,o)=>{for(const[a,u]of t)i>a?n.notes.push(r.a.Note.create({pitch:o,velocity:u,instrument:e,quantizedStartStep:a,quantizedEndStep:i,program:this.program,isDrum:this.isDrum})):s.log(`Ignoring zero-length note: (pitch = ${o}, step = ${i})`,"Performance")}),n.totalQuantizedSteps=i,n}}},33:function(e,t,n){"use strict";e.exports=p;var r,o=n(18),i=o.LongBits,s=o.base64,a=o.utf8;function u(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function c(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function p(){this.len=0,this.head=new u(c,0,0),this.tail=this.head,this.states=null}var m=function(){return o.Buffer?function(){return(p.create=function(){return new r})()}:function(){return new p}};function d(e,t,n){t[n]=255&e}function h(e,t){this.len=e,this.next=void 0,this.val=t}function f(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function g(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}p.create=m(),p.alloc=function(e){return new o.Array(e)},o.Array!==Array&&(p.alloc=o.pool(p.alloc,o.Array.prototype.subarray)),p.prototype._push=function(e,t,n){return this.tail=this.tail.next=new u(e,t,n),this.len+=t,this},h.prototype=Object.create(u.prototype),h.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},p.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new h((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},p.prototype.int32=function(e){return e<0?this._push(f,10,i.fromNumber(e)):this.uint32(e)},p.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},p.prototype.uint64=function(e){var t=i.from(e);return this._push(f,t.length(),t)},p.prototype.int64=p.prototype.uint64,p.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(f,t.length(),t)},p.prototype.bool=function(e){return this._push(d,1,e?1:0)},p.prototype.fixed32=function(e){return this._push(g,4,e>>>0)},p.prototype.sfixed32=p.prototype.fixed32,p.prototype.fixed64=function(e){var t=i.from(e);return this._push(g,4,t.lo)._push(g,4,t.hi)},p.prototype.sfixed64=p.prototype.fixed64,p.prototype.float=function(e){return this._push(o.float.writeFloatLE,4,e)},p.prototype.double=function(e){return this._push(o.float.writeDoubleLE,8,e)};var S=o.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var r=0;r<e.length;++r)t[n+r]=e[r]};p.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(d,1,0);if(o.isString(e)){var n=p.alloc(t=s.length(e));s.decode(e,n,0),e=n}return this.uint32(t)._push(S,t,e)},p.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(d,1,0)},p.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new u(c,0,0),this.len=0,this},p.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(c,0,0),this.len=0),this},p.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},p.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},p._configure=function(e){r=e,p.create=m(),r._configure()}},34:function(e,t,n){"use strict";e.exports=u;var r,o=n(18),i=o.LongBits,s=o.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function u(e){this.buf=e,this.pos=0,this.len=e.length}var c,l="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new u(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new u(e);throw Error("illegal buffer")},p=function(){return o.Buffer?function(e){return(u.create=function(e){return o.Buffer.isBuffer(e)?new r(e):l(e)})(e)}:l};function m(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function d(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw a(this,8);return new i(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}u.create=p(),u.prototype._slice=o.Array.prototype.subarray||o.Array.prototype.slice,u.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return c}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return d(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|d(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=o.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=o.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},u.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)},u.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},u.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},u._configure=function(e){r=e,u.create=p(),r._configure();var t=o.Long?"toLong":"toNumber";o.merge(u.prototype,{int64:function(){return m.call(this)[t](!1)},uint64:function(){return m.call(this)[t](!0)},sint64:function(){return m.call(this).zzDecode()[t](!1)},fixed64:function(){return h.call(this)[t](!0)},sfixed64:function(){return h.call(this)[t](!1)}})}},35:function(e,t,n){"use strict";var r,o,i=n(49),s=i.Reader,a=i.Writer,u=i.util,c=i.roots.default||(i.roots.default={});c.tensorflow=((o={}).magenta=((r={}).NoteSequence=function(){function e(e){if(this.timeSignatures=[],this.keySignatures=[],this.tempos=[],this.notes=[],this.pitchBends=[],this.controlChanges=[],this.partInfos=[],this.textAnnotations=[],this.sectionAnnotations=[],this.sectionGroups=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t,n;return e.prototype.id="",e.prototype.filename="",e.prototype.referenceNumber=u.Long?u.Long.fromBits(0,0,!1):0,e.prototype.collectionName="",e.prototype.ticksPerQuarter=0,e.prototype.timeSignatures=u.emptyArray,e.prototype.keySignatures=u.emptyArray,e.prototype.tempos=u.emptyArray,e.prototype.notes=u.emptyArray,e.prototype.totalTime=0,e.prototype.totalQuantizedSteps=u.Long?u.Long.fromBits(0,0,!1):0,e.prototype.pitchBends=u.emptyArray,e.prototype.controlChanges=u.emptyArray,e.prototype.partInfos=u.emptyArray,e.prototype.sourceInfo=null,e.prototype.textAnnotations=u.emptyArray,e.prototype.sectionAnnotations=u.emptyArray,e.prototype.sectionGroups=u.emptyArray,e.prototype.quantizationInfo=null,e.prototype.subsequenceInfo=null,e.prototype.sequenceMetadata=null,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=a.create()),null!=e.id&&e.hasOwnProperty("id")&&t.uint32(10).string(e.id),null!=e.filename&&e.hasOwnProperty("filename")&&t.uint32(18).string(e.filenam