Compare commits

...

15 Commits

Author SHA1 Message Date
josc146
19b97e985c release v1.5.6 2023-11-29 21:21:50 +08:00
josc146
93bf74a320 fix NoteOff 2023-11-29 21:21:42 +08:00
josc146
7daae23bbb update defaultConfigs 2023-11-29 21:21:29 +08:00
josc146
0d0a3f15cc chore 2023-11-29 21:21:14 +08:00
github-actions[bot]
04fbb38861 release v1.5.5 2023-11-29 11:32:40 +00:00
josc146
d666c6032b release v1.5.5 2023-11-29 19:31:56 +08:00
josc146
93e8660d69 add instruments i18n 2023-11-29 19:31:52 +08:00
josc146
e687cf02bb try to use local soundfont by default 2023-11-29 19:17:19 +08:00
josc146
e858f1477a update locales 2023-11-29 19:10:01 +08:00
josc146
a2062ae9cc feat: save MIDI tracks to generation area; playing tracks and audio preview are still under development 2023-11-29 19:04:41 +08:00
josc146
34112c79c7 fix autoPlayed midi cannot be stopped 2023-11-29 15:28:43 +08:00
josc146
b625b8a6d1 MIDI Recording and details improvement 2023-11-29 14:05:58 +08:00
josc146
14a13d5768 basic MIDI Input Audio Tracks 2023-11-28 15:34:06 +08:00
josc146
7ce464ecda improve details 2023-11-26 22:54:59 +08:00
github-actions[bot]
2c1f89383f release v1.5.4 2023-11-24 11:22:42 +00:00
26 changed files with 1116 additions and 44 deletions

View File

@@ -1,17 +1,17 @@
## Changes
## Changes (v1.5.6 is a patch for v1.5.5)
- upgrade to rwkv 0.8.22 (rwkv6 support)
- allow reading attachments even if the model is offline
- improve launch flow of webgpu mode
- allow safetensors converter on macOS
- fix fs watcher of macOS
- update defaultConfigs
- update manifest
- chores
- MIDI Input Audio Tracks (Experimental, playing tracks is not supported yet, please save to generation area to preview)
- fix autoPlayed midi cannot be stopped
- try to use local soundfont by default
- improve details
## Install
- Windows: https://github.com/josStorer/RWKV-Runner/blob/master/build/windows/Readme_Install.txt
- MacOS: https://github.com/josStorer/RWKV-Runner/blob/master/build/darwin/Readme_Install.txt
- Linux: https://github.com/josStorer/RWKV-Runner/blob/master/build/linux/Readme_Install.txt
- Server-Deploy-Examples: https://github.com/josStorer/RWKV-Runner/tree/master/deploy-examples
- Server-Deploy-Examples: https://github.com/josStorer/RWKV-Runner/tree/master/deploy-examples
#### MIDI Input Audio Tracks
![image](https://github.com/josStorer/RWKV-Runner/assets/13366013/e35e23a4-1942-4649-995d-eabf386722f7)

View File

@@ -55,6 +55,7 @@ func (a *App) OnStartup(ctx context.Context) {
}
a.downloadLoop()
a.midiLoop()
a.watchFs()
a.monitorHardware()
}

View File

@@ -33,9 +33,9 @@ type DownloadStatus struct {
var downloadList []*DownloadStatus
func existsInDownloadList(url string) bool {
func existsInDownloadList(path string, url string) bool {
for _, ds := range downloadList {
if ds.Url == url {
if ds.Path == path || ds.Url == url {
return true
}
}
@@ -88,7 +88,7 @@ func (a *App) ContinueDownload(url string) {
}
func (a *App) AddToDownloadList(path string, url string) {
if !existsInDownloadList(url) {
if !existsInDownloadList(a.exDir+path, url) {
downloadList = append(downloadList, &DownloadStatus{
resp: nil,
Name: filepath.Base(path),

164
backend-golang/midi.go Normal file
View File

@@ -0,0 +1,164 @@
package backend_golang
import (
"errors"
"fmt"
"time"
"github.com/mattrtaylor/go-rtmidi"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
type Port struct {
Name string `json:"name"`
}
type MIDIMessage struct {
MessageType string `json:"messageType"`
Channel int `json:"channel"`
Note int `json:"note"`
Velocity int `json:"velocity"`
Control int `json:"control"`
Value int `json:"value"`
}
var ports []Port
var input rtmidi.MIDIIn
var out rtmidi.MIDIOut
var activeIndex int = -1
var lastNoteTime time.Time
func (a *App) midiLoop() {
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
return
}
out, err = rtmidi.NewMIDIOutDefault()
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
}
err = out.OpenPort(0, "")
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
}
ticker := time.NewTicker(500 * time.Millisecond)
go func() {
for {
<-ticker.C
count, err := input.PortCount()
if err != nil {
continue
}
ports = make([]Port, count)
for i := 0; i < count; i++ {
name, err := input.PortName(i)
if err == nil {
ports[i].Name = name
}
}
runtime.EventsEmit(a.ctx, "midiPorts", &ports)
}
}()
}
func (a *App) OpenMidiPort(index int) error {
if input == nil {
return errors.New("failed to initialize MIDI input")
}
if activeIndex == index {
return nil
}
input.Destroy()
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
return err
}
err = input.SetCallback(func(msg rtmidi.MIDIIn, bytes []byte, t float64) {
// https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message
// https://www.rfc-editor.org/rfc/rfc6295.html
//
// msgType channel
// 1001 0000
//
msgType := bytes[0] >> 4
channel := bytes[0] & 0x0f
switch msgType {
case 0x8:
note := bytes[1]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "NoteOff",
Channel: int(channel),
Note: int(note),
})
case 0x9:
elapsed := time.Since(lastNoteTime)
lastNoteTime = time.Now()
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "ElapsedTime",
Value: int(elapsed.Milliseconds()),
})
note := bytes[1]
velocity := bytes[2]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "NoteOn",
Channel: int(channel),
Note: int(note),
Velocity: int(velocity),
})
case 0xb:
// control 12 => K1 knob, control 13 => K2 knob
control := bytes[1]
value := bytes[2]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "ControlChange",
Channel: int(channel),
Control: int(control),
Value: int(value),
})
default:
fmt.Printf("Unknown midi message: %v\n", bytes)
}
})
if err != nil {
return err
}
err = input.OpenPort(index, "")
if err != nil {
return err
}
activeIndex = index
lastNoteTime = time.Now()
return nil
}
func (a *App) CloseMidiPort() error {
if input == nil {
return errors.New("failed to initialize MIDI input")
}
if activeIndex == -1 {
return nil
}
activeIndex = -1
input.Destroy()
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
return err
}
return nil
}
func (a *App) PlayNote(msg MIDIMessage) error {
if out == nil {
return errors.New("failed to initialize MIDI output")
}
channelByte := byte(msg.Channel)
if msg.MessageType == "NoteOn" {
out.SendMessage([]byte{0x90 | channelByte, byte(msg.Note), byte(msg.Velocity)})
} else if msg.MessageType == "NoteOff" {
out.SendMessage([]byte{0x80 | channelByte, byte(msg.Note), byte(msg.Velocity)})
}
return nil
}

View File

@@ -25,6 +25,7 @@
"react-beautiful-dnd": "^13.1.1",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.6",
"react-i18next": "^12.2.2",
"react-markdown": "^8.0.7",
"react-router": "^6.11.1",
@@ -5410,6 +5411,19 @@
"loose-envify": "^1.1.0"
}
},
"node_modules/react-draggable": {
"version": "4.4.6",
"resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-4.4.6.tgz",
"integrity": "sha512-LtY5Xw1zTPqHkVmtM3X8MUOxNDOUhv/khTgBgrUvwaS064bwVvxT+q5El0uUFNx5IEPKXuRejr7UqLwBIg5pdw==",
"dependencies": {
"clsx": "^1.1.1",
"prop-types": "^15.8.1"
},
"peerDependencies": {
"react": ">= 16.3.0",
"react-dom": ">= 16.3.0"
}
},
"node_modules/react-i18next": {
"version": "12.2.2",
"resolved": "https://registry.npmmirror.com/react-i18next/-/react-i18next-12.2.2.tgz",

View File

@@ -26,6 +26,7 @@
"react-beautiful-dnd": "^13.1.1",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.6",
"react-i18next": "^12.2.2",
"react-markdown": "^8.0.7",
"react-router": "^6.11.1",

View File

@@ -272,5 +272,33 @@
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "モデルの読み込みに失敗しました、仮想メモリ (WSL Swap) を増やすか小さなベースモデルを使用してみてください。",
"Save Conversation": "会話を保存",
"Use Hugging Face Mirror": "Hugging Faceミラーを使用",
"File is empty": "ファイルが空です"
"File is empty": "ファイルが空です",
"Open MIDI Input Audio Tracks": "MIDI入力オーディオトラックを開く",
"Track": "トラック",
"Play All": "すべて再生",
"Clear All": "すべてクリア",
"Scale View": "スケールビュー",
"Record": "録音",
"Play": "再生",
"New Track": "新規トラック",
"Select a track to preview the content": "トラックを選択して内容をプレビュー",
"Save to generation area": "生成エリアに保存",
"Piano": "ピアノ",
"Percussion": "パーカッション",
"Drum": "ドラム",
"Tuba": "チューバ",
"Marimba": "マリンバ",
"Bass": "ベース",
"Guitar": "ギター",
"Violin": "バイオリン",
"Trumpet": "トランペット",
"Sax": "サックス",
"Flute": "フルート",
"Lead": "リード",
"Pad": "パッド",
"MIDI Input": "MIDI入力",
"Select the MIDI input device to be used.": "使用するMIDI入力デバイスを選択します。",
"Start Time": "開始時間",
"Content Duration": "内容の長さ",
"Please select a MIDI device first": "まずMIDIデバイスを選択してください"
}

View File

@@ -272,5 +272,33 @@
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "模型载入失败,尝试增加虚拟内存(WSL Swap),或使用一个更小规模的基底模型",
"Save Conversation": "保存对话",
"Use Hugging Face Mirror": "使用Hugging Face镜像源",
"File is empty": "文件为空"
"File is empty": "文件为空",
"Open MIDI Input Audio Tracks": "打开MIDI输入音轨",
"Track": "音轨",
"Play All": "播放全部",
"Clear All": "清空",
"Scale View": "缩放视图",
"Record": "录制",
"Play": "播放",
"New Track": "新建音轨",
"Select a track to preview the content": "选择一个音轨以预览内容",
"Save to generation area": "保存到生成区",
"Piano": "钢琴",
"Percussion": "打击乐",
"Drum": "鼓",
"Tuba": "大号",
"Marimba": "马林巴",
"Bass": "贝斯",
"Guitar": "吉他",
"Violin": "小提琴",
"Trumpet": "小号",
"Sax": "萨克斯",
"Flute": "长笛",
"Lead": "主音",
"Pad": "和音",
"MIDI Input": "MIDI输入",
"Select the MIDI input device to be used.": "选择要使用的MIDI输入设备",
"Start Time": "开始时间",
"Content Duration": "内容时长",
"Please select a MIDI device first": "请先选择一个MIDI设备"
}

View File

@@ -84,6 +84,10 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
showDownloadPrompt(t('Model file not found'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else if (!currentModelSource?.isComplete) {
showDownloadPrompt(t('Model file download is not complete'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else {
toastWithButton(t('Please convert model to safe tensors format first'), t('Convert'), () => {
convertToSt(navigate, modelConfig);
@@ -112,7 +116,9 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
showDownloadPrompt(t('Model file not found'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else if (!currentModelSource?.isComplete) {
} else // If the user selects the .pth model with WebGPU mode, modelPath will be set to the .st model.
// However, if the .pth model is deleted, modelPath will exist and isComplete will be false.
if (!currentModelSource?.isComplete && modelPath.endsWith('.pth')) {
showDownloadPrompt(t('Model file download is not complete'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
@@ -145,6 +151,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
toast(t('Error') + ' - ' + errMsg, { type: 'error' });
});
setTimeout(WindowShow, 1000);
setTimeout(WindowShow, 2000);
setTimeout(WindowShow, 3000);
let timeoutCount = 6;
let loading = false;
@@ -161,7 +169,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
});
}
commonStore.setStatus({ status: ModelStatus.Loading });
toast(t('Loading Model'), { type: 'info' });
const loadingId = toast(t('Loading Model'), { type: 'info' });
if (!webgpu) {
updateConfig({
max_tokens: modelConfig.apiParameters.maxResponseToken,
@@ -247,6 +255,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
}).catch((e) => {
commonStore.setStatus({ status: ModelStatus.Offline });
toast(t('Failed to switch model') + ' - ' + (e.message || e), { type: 'error' });
}).finally(() => {
toast.dismiss(loadingId);
});
}
}).catch(() => {

View File

@@ -0,0 +1,40 @@
import React, { FC, lazy } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Dialog, DialogBody, DialogContent, DialogSurface, DialogTrigger } from '@fluentui/react-components';
import { CustomToastContainer } from '../../components/CustomToastContainer';
import { LazyImportComponent } from '../../components/LazyImportComponent';
import { flushMidiRecordingContent } from '../../utils';
import commonStore from '../../stores/commonStore';
const AudiotrackEditor = lazy(() => import('./AudiotrackEditor'));
export const AudiotrackButton: FC<{
size?: 'small' | 'medium' | 'large',
shape?: 'rounded' | 'circular' | 'square';
appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent';
setPrompt: (prompt: string) => void;
}> = ({ size, shape, appearance, setPrompt }) => {
const { t } = useTranslation();
return <Dialog onOpenChange={(e, data) => {
if (!data.open) {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
commonStore.setPlayingTrackId('');
}
}}>
<DialogTrigger disableButtonEnhancement>
<Button size={size} shape={shape} appearance={appearance}>
{t('Open MIDI Input Audio Tracks')}
</Button>
</DialogTrigger>
<DialogSurface style={{ paddingTop: 0, maxWidth: '90vw', width: 'fit-content' }}>
<DialogBody>
<DialogContent className="overflow-hidden">
<CustomToastContainer />
<LazyImportComponent lazyChildren={AudiotrackEditor} lazyProps={{ setPrompt }} />
</DialogContent>
</DialogBody>
</DialogSurface>
</Dialog>;
};

View File

@@ -0,0 +1,499 @@
import React, { FC, useEffect, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useTranslation } from 'react-i18next';
import Draggable from 'react-draggable';
import { ToolTipButton } from '../../components/ToolTipButton';
import { v4 as uuid } from 'uuid';
import {
Add16Regular,
ArrowAutofitWidth20Regular,
Delete16Regular,
MusicNote220Regular,
Pause16Regular,
Play16Filled,
Play16Regular,
Record16Regular,
Stop16Filled
} from '@fluentui/react-icons';
import { Button, Card, DialogTrigger, Slider, Text, Tooltip } from '@fluentui/react-components';
import { useWindowSize } from 'usehooks-ts';
import commonStore from '../../stores/commonStore';
import classnames from 'classnames';
import {
InstrumentTypeNameMap,
InstrumentTypeTokenMap,
MidiMessage,
tracksMinimalTotalTime
} from '../../types/composition';
import { toast } from 'react-toastify';
import { ToastOptions } from 'react-toastify/dist/types';
import { flushMidiRecordingContent, refreshTracksTotalTime } from '../../utils';
import { PlayNote } from '../../../wailsjs/go/backend_golang/App';
import { t } from 'i18next';
const snapValue = 25;
const minimalMoveTime = 8; // 1000/125=8ms wait_events=125
const scaleMin = 0.05;
const scaleMax = 3;
const baseMoveTime = Math.round(minimalMoveTime / scaleMin);
const velocityEvents = 128;
const velocityBins = 12;
const velocityExp = 0.5;
const minimalTrackWidth = 80;
const trackInitOffsetPx = 10;
const pixelFix = 0.5;
const topToArrowIcon = 19;
const arrowIconToTracks = 23;
type TrackProps = {
id: string;
right: number;
scale: number;
isSelected: boolean;
onSelect: (id: string) => void;
};
const displayCurrentInstrumentType = () => {
const displayPanelId = 'instrument_panel_id';
const content: React.ReactNode =
<div className="flex gap-2 items-center">
{InstrumentTypeNameMap.map((name, i) =>
<Text key={name} style={{ whiteSpace: 'nowrap' }}
className={commonStore.instrumentType === i ? 'text-blue-600' : ''}
weight={commonStore.instrumentType === i ? 'bold' : 'regular'}
size={commonStore.instrumentType === i ? 300 : 100}
>{t(name)}</Text>)}
</div>;
const options: ToastOptions = {
type: 'default',
autoClose: 2000,
toastId: displayPanelId,
position: 'top-left',
style: {
width: 'fit-content'
}
};
if (toast.isActive(displayPanelId))
toast.update(displayPanelId, {
render: content,
...options
});
else
toast(content, options);
};
const velocityToBin = (velocity: number) => {
velocity = Math.max(0, Math.min(velocity, velocityEvents - 1));
const binsize = velocityEvents / (velocityBins - 1);
return Math.ceil((velocityEvents * ((Math.pow(velocityExp, (velocity / velocityEvents)) - 1.0) / (velocityExp - 1.0))) / binsize);
};
const midiMessageToToken = (msg: MidiMessage) => {
if (msg.messageType === 'NoteOn' || msg.messageType === 'NoteOff') {
const instrument = InstrumentTypeTokenMap[commonStore.instrumentType];
const note = msg.note.toString(16);
const velocity = velocityToBin(msg.velocity).toString(16);
return `${instrument}:${note}:${velocity} `;
} else if (msg.messageType === 'ElapsedTime') {
let time = Math.round(msg.value / minimalMoveTime);
const num = Math.floor(time / 125); // wait_events=125
time -= num * 125;
let ret = '';
for (let i = 0; i < num; i++) {
ret += 't125 ';
}
if (time > 0)
ret += `t${time} `;
return ret;
} else
return '';
};
let dropRecordingTime = false;
export const midiMessageHandler = async (data: MidiMessage) => {
if (data.messageType === 'ControlChange') {
commonStore.setInstrumentType(Math.round(data.value / 127 * (InstrumentTypeNameMap.length - 1)));
displayCurrentInstrumentType();
return;
}
if (commonStore.recordingTrackId) {
if (dropRecordingTime && data.messageType === 'ElapsedTime') {
dropRecordingTime = false;
return;
}
data = {
...data,
instrument: commonStore.instrumentType
};
commonStore.setRecordingRawContent([...commonStore.recordingRawContent, data]);
commonStore.setRecordingContent(commonStore.recordingContent + midiMessageToToken(data));
//TODO data.channel = data.instrument;
PlayNote(data);
}
};
const Track: React.FC<TrackProps> = observer(({
id,
right,
scale,
isSelected,
onSelect
}) => {
const { t } = useTranslation();
const trackIndex = commonStore.tracks.findIndex(t => t.id === id)!;
const track = commonStore.tracks[trackIndex];
const trackClass = isSelected ? 'bg-blue-600' : 'bg-gray-700';
const controlX = useRef(0);
return (
<Draggable
axis="x"
bounds={{ left: 0, right }}
grid={[snapValue, snapValue]}
position={{
x: (track.offsetTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue,
y: 0
}}
onStart={(e, data) => {
controlX.current = data.lastX;
}}
onStop={(e, data) => {
const delta = data.lastX - controlX.current;
let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime;
offsetTime = Math.min(Math.max(
offsetTime,
-track.offsetTime), commonStore.trackTotalTime - track.offsetTime);
const tracks = commonStore.tracks.slice();
tracks[trackIndex].offsetTime += offsetTime;
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}}
>
<div
className={`p-1 cursor-move rounded whitespace-nowrap overflow-hidden ${trackClass}`}
style={{
width: `${Math.max(minimalTrackWidth,
track.contentTime / (baseMoveTime * scale) * snapValue
)}px`
}}
onClick={() => onSelect(id)}
>
<span className="text-white">{t('Track') + ' ' + (track.content || id)}</span>
</div>
</Draggable>
);
});
const AudiotrackEditor: FC<{ setPrompt: (prompt: string) => void }> = observer(({ setPrompt }) => {
const { t } = useTranslation();
const viewControlsContainerRef = useRef<HTMLDivElement>(null);
const currentTimeControlRef = useRef<HTMLDivElement>(null);
const playStartTimeControlRef = useRef<HTMLDivElement>(null);
const tracksEndLineRef = useRef<HTMLDivElement>(null);
const tracksRef = useRef<HTMLDivElement>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
const toolbarButtonRef = useRef<HTMLDivElement>(null);
const toolbarSliderRef = useRef<HTMLInputElement>(null);
const contentPreviewRef = useRef<HTMLDivElement>(null);
const [refreshRef, setRefreshRef] = useState(false);
const windowSize = useWindowSize();
const scale = (scaleMin + scaleMax) - commonStore.trackScale;
const [selectedTrackId, setSelectedTrackId] = useState<string>('');
const playStartTimeControlX = useRef(0);
const selectedTrack = selectedTrackId ? commonStore.tracks.find(t => t.id === selectedTrackId) : undefined;
useEffect(() => {
if (toolbarSliderRef.current && toolbarSliderRef.current.parentElement)
toolbarSliderRef.current.parentElement.style.removeProperty('--fui-Slider--steps-percent');
}, []);
const scrollContentToBottom = () => {
if (contentPreviewRef.current)
contentPreviewRef.current.scrollTop = contentPreviewRef.current.scrollHeight;
};
useEffect(() => {
scrollContentToBottom();
}, [commonStore.recordingContent]);
useEffect(() => {
setRefreshRef(!refreshRef);
}, [windowSize, commonStore.tracks]);
const viewControlsContainerWidth = (toolbarRef.current && toolbarButtonRef.current && toolbarSliderRef.current) ?
toolbarRef.current.clientWidth - toolbarButtonRef.current.clientWidth - toolbarSliderRef.current.clientWidth - 16 // 16 = ml-2 mr-2
: 0;
const tracksWidth = viewControlsContainerWidth;
const timeOfTracksWidth = Math.floor(tracksWidth / snapValue) // number of moves
* baseMoveTime * scale;
const currentTimeControlWidth = (timeOfTracksWidth < commonStore.trackTotalTime)
? timeOfTracksWidth / commonStore.trackTotalTime * viewControlsContainerWidth
: 0;
const playStartTimeControlPosition = (commonStore.trackPlayStartTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue;
const tracksEndPosition = (commonStore.trackTotalTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue;
const moveableTracksWidth = (tracksEndLineRef.current && viewControlsContainerRef.current &&
((tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx)) > 0))
? tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx)
: Infinity;
return (
<div className="flex flex-col gap-2 overflow-hidden" style={{ width: '80vw', height: '80vh' }}>
<div className="mx-auto">
<Text size={100}>{`${commonStore.trackPlayStartTime} ms / ${commonStore.trackTotalTime} ms`}</Text>
</div>
<div className="flex pb-2 border-b" ref={toolbarRef}>
<div className="flex gap-2" ref={toolbarButtonRef}>
<ToolTipButton disabled desc={t('Play All') + ' (Unavailable)'} icon={<Play16Regular />} />
<ToolTipButton desc={t('Clear All')} icon={<Delete16Regular />} onClick={() => {
commonStore.setTracks([]);
commonStore.setTrackScale(1);
commonStore.setTrackTotalTime(tracksMinimalTotalTime);
commonStore.setTrackCurrentTime(0);
commonStore.setTrackPlayStartTime(0);
}} />
</div>
<div className="grow">
<div className="flex flex-col ml-2 mr-2" ref={viewControlsContainerRef}>
<div className="relative">
<Tooltip content={`${commonStore.trackTotalTime} ms`} showDelay={0} hideDelay={0}
relationship="description">
<div className="border-l absolute"
ref={tracksEndLineRef}
style={{
height: (tracksRef.current && commonStore.tracks.length > 0)
? tracksRef.current.clientHeight - arrowIconToTracks
: 0,
top: `${topToArrowIcon + arrowIconToTracks}px`,
left: `${tracksEndPosition + trackInitOffsetPx - pixelFix}px`
}} />
</Tooltip>
</div>
<Draggable axis="x" bounds={{
left: 0,
right: viewControlsContainerWidth - currentTimeControlWidth
}}
position={{
x: commonStore.trackCurrentTime / commonStore.trackTotalTime * viewControlsContainerWidth,
y: 0
}}
onDrag={(e, data) => {
setTimeout(() => {
let offset = 0;
if (currentTimeControlRef.current) {
const match = currentTimeControlRef.current.style.transform.match(/translate\((.+)px,/);
if (match)
offset = parseFloat(match[1]);
}
const offsetTime = commonStore.trackTotalTime / viewControlsContainerWidth * offset;
commonStore.setTrackCurrentTime(offsetTime);
}, 1);
}}
>
<div ref={currentTimeControlRef} className="h-2 bg-gray-700 cursor-move rounded"
style={{ width: currentTimeControlWidth }} />
</Draggable>
<div className={classnames(
'flex',
(playStartTimeControlPosition < 0 || playStartTimeControlPosition > viewControlsContainerWidth)
&& 'hidden'
)}>
<Draggable axis="x" bounds={{
left: 0,
right: (playStartTimeControlRef.current)
? Math.min(viewControlsContainerWidth - playStartTimeControlRef.current.clientWidth, moveableTracksWidth)
: 0
}}
grid={[snapValue, snapValue]}
position={{ x: playStartTimeControlPosition, y: 0 }}
onStart={(e, data) => {
playStartTimeControlX.current = data.lastX;
}}
onStop={(e, data) => {
const delta = data.lastX - playStartTimeControlX.current;
let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime;
offsetTime = Math.min(Math.max(
offsetTime,
-commonStore.trackPlayStartTime), commonStore.trackTotalTime - commonStore.trackPlayStartTime);
commonStore.setTrackPlayStartTime(commonStore.trackPlayStartTime + offsetTime);
}}
>
<div className="relative cursor-move"
ref={playStartTimeControlRef}>
<ArrowAutofitWidth20Regular />
<div className="border-l absolute border-gray-700"
style={{
height: (tracksRef.current && commonStore.tracks.length > 0)
? tracksRef.current.clientHeight
: 0,
top: '50%',
left: `calc(50% - ${pixelFix}px)`
}} />
</div>
</Draggable>
</div>
</div>
</div>
<Tooltip content={t('Scale View')! + ': ' + commonStore.trackScale} showDelay={0} hideDelay={0}
relationship="description">
<Slider ref={toolbarSliderRef} value={commonStore.trackScale} step={scaleMin} max={scaleMax} min={scaleMin}
onChange={(e, data) => {
commonStore.setTrackScale(data.value);
}}
/>
</Tooltip>
</div>
<div className="flex flex-col overflow-y-auto gap-1" ref={tracksRef}>
{commonStore.tracks.map(track =>
<div key={track.id} className="flex gap-2 pb-1 border-b">
<div className="flex gap-1 border-r h-7">
<ToolTipButton desc={commonStore.recordingTrackId === track.id ? t('Stop') : t('Record')}
icon={commonStore.recordingTrackId === track.id ? <Stop16Filled /> : <Record16Regular />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
flushMidiRecordingContent();
commonStore.setPlayingTrackId('');
if (commonStore.recordingTrackId === track.id) {
commonStore.setRecordingTrackId('');
} else {
if (commonStore.activeMidiDeviceIndex === -1) {
toast(t('Please select a MIDI device first'), { type: 'warning' });
return;
}
dropRecordingTime = true;
setSelectedTrackId(track.id);
commonStore.setRecordingTrackId(track.id);
commonStore.setRecordingContent(track.content);
commonStore.setRecordingRawContent(track.rawContent.slice());
}
}} />
<ToolTipButton disabled
desc={commonStore.playingTrackId === track.id ? t('Stop') : t('Play') + ' (Unavailable)'}
icon={commonStore.playingTrackId === track.id ? <Pause16Regular /> : <Play16Filled />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
if (commonStore.playingTrackId === track.id) {
commonStore.setPlayingTrackId('');
} else {
setSelectedTrackId(track.id);
commonStore.setPlayingTrackId(track.id);
}
}} />
<ToolTipButton desc={t('Delete')} icon={<Delete16Regular />} size="small" shape="circular"
appearance="subtle" onClick={() => {
const tracks = commonStore.tracks.slice().filter(t => t.id !== track.id);
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}} />
</div>
<div className="relative grow overflow-hidden">
<div className="absolute" style={{ left: -0 }}>
<Track
id={track.id}
scale={scale}
right={Math.min(tracksWidth, moveableTracksWidth)}
isSelected={selectedTrackId === track.id}
onSelect={setSelectedTrackId}
/>
</div>
</div>
</div>)}
<div className="flex justify-between items-center">
<Button icon={<Add16Regular />} size="small" shape="circular"
appearance="subtle"
onClick={() => {
commonStore.setTracks([...commonStore.tracks, {
id: uuid(),
content: '',
rawContent: [],
offsetTime: 0,
contentTime: 0
}]);
}}>
{t('New Track')}
</Button>
<Text size={100}>
{t('Select a track to preview the content')}
</Text>
</div>
</div>
<div className="grow"></div>
{selectedTrack &&
<Card size="small" appearance="outline" style={{ minHeight: '150px', maxHeight: '200px' }}>
<div className="flex flex-col gap-1 overflow-hidden">
<Text size={100}>{`${t('Start Time')}: ${selectedTrack.offsetTime} ms`}</Text>
<Text size={100}>{`${t('Content Duration')}: ${selectedTrack.contentTime} ms`}</Text>
<div className="overflow-y-auto overflow-x-hidden" ref={contentPreviewRef}>
{selectedTrackId === commonStore.recordingTrackId
? commonStore.recordingContent
: selectedTrack.content}
</div>
</div>
</Card>
}
<DialogTrigger disableButtonEnhancement>
<Button icon={<MusicNote220Regular />} style={{ minHeight: '32px' }} onClick={() => {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
commonStore.setPlayingTrackId('');
const timestamp = [];
const sortedTracks = commonStore.tracks.slice().sort((a, b) => a.offsetTime - b.offsetTime);
for (const track of sortedTracks) {
timestamp.push(track.offsetTime);
let accContentTime = 0;
for (const msg of track.rawContent) {
if (msg.messageType === 'ElapsedTime') {
accContentTime += msg.value;
timestamp.push(track.offsetTime + accContentTime);
}
}
}
const sortedTimestamp = timestamp.slice().sort((a, b) => a - b);
const globalMessages: MidiMessage[] = sortedTimestamp.reduce((messages, current, i) =>
[...messages, {
messageType: 'ElapsedTime',
value: current - (i === 0 ? 0 : sortedTimestamp[i - 1])
} as MidiMessage]
, [] as MidiMessage[]);
for (const track of sortedTracks) {
let currentTime = track.offsetTime;
let accContentTime = 0;
for (const msg of track.rawContent) {
if (msg.messageType === 'ElapsedTime') {
accContentTime += msg.value;
currentTime = track.offsetTime + accContentTime;
} else if (msg.messageType === 'NoteOn' || msg.messageType === 'NoteOff') {
const insertIndex = sortedTimestamp.findIndex(t => t >= currentTime);
globalMessages.splice(insertIndex + 1, 0, msg);
sortedTimestamp.splice(insertIndex + 1, 0, 0); // placeholder
}
}
}
const result = globalMessages.map(m => midiMessageToToken(m)).join('');
commonStore.setCompositionSubmittedPrompt(result);
setPrompt(result);
}}>
{t('Save to generation area')}
</Button>
</DialogTrigger>
</div>
);
});
export default AudiotrackEditor;

View File

@@ -567,7 +567,7 @@ const ChatPanel: FC = observer(() => {
const filterPattern = '*.txt;*.pdf';
const setUploading = () => commonStore.setAttachmentUploading(true);
// actually, status of web platform is always Offline
if (commonStore.platform === 'web' || commonStore.status.status === ModelStatus.Offline) {
if (commonStore.platform === 'web' || commonStore.status.status === ModelStatus.Offline || currentConfig.modelParameters.device === 'WebGPU') {
webOpenOpenFileDialog({ filterPattern, fnStartLoading: setUploading }).then(webReturn => {
if (webReturn.content)
commonStore.setCurrentTempAttachment(

View File

@@ -2,7 +2,7 @@ import 'html-midi-player';
import React, { FC, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { WorkHeader } from '../components/WorkHeader';
import { Button, Checkbox, Textarea } from '@fluentui/react-components';
import { Button, Checkbox, Dropdown, Option, Textarea } from '@fluentui/react-components';
import { Labeled } from '../components/Labeled';
import { ValuedSlider } from '../components/ValuedSlider';
import { useTranslation } from 'react-i18next';
@@ -16,10 +16,17 @@ import { PlayerElement, VisualizerElement } from 'html-midi-player';
import * as mm from '@magenta/music/esm/core.js';
import { NoteSequence } from '@magenta/music/esm/protobuf.js';
import { defaultCompositionPrompt } from './defaultConfigs';
import { FileExists, OpenFileFolder, OpenSaveFileDialogBytes } from '../../wailsjs/go/backend_golang/App';
import { getServerRoot, toastWithButton } from '../utils';
import {
CloseMidiPort,
FileExists,
OpenFileFolder,
OpenMidiPort,
OpenSaveFileDialogBytes
} from '../../wailsjs/go/backend_golang/App';
import { getServerRoot, getSoundFont, toastWithButton } from '../utils';
import { CompositionParams } from '../types/composition';
import { useMediaQuery } from 'usehooks-ts';
import { AudiotrackButton } from './AudiotrackManager/AudiotrackButton';
let compositionSseController: AbortController | null = null;
@@ -64,20 +71,8 @@ const CompositionPanel: FC = observer(() => {
};
const setSoundFont = async () => {
let soundUrl: string;
if (commonStore.compositionParams.useLocalSoundFont)
soundUrl = 'assets/sound-font';
else
soundUrl = !commonStore.settings.giteeUpdatesSource ?
`https://raw.githubusercontent.com/josStorer/sgm_plus/master` :
`https://gitee.com/josc146/sgm_plus/raw/master`;
const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus';
await fetch(soundUrl + '/soundfont.json').then(r => {
if (!r.ok)
soundUrl = fallbackUrl;
}).catch(() => soundUrl = fallbackUrl);
if (playerRef.current) {
playerRef.current.soundFont = soundUrl;
playerRef.current.soundFont = await getSoundFont();
}
};
@@ -121,7 +116,9 @@ const CompositionPanel: FC = observer(() => {
});
updateNs(ns);
if (autoPlay) {
playerRef.current?.start();
setTimeout(() => {
playerRef.current?.start();
});
}
});
});
@@ -267,6 +264,36 @@ const CompositionPanel: FC = observer(() => {
autoPlay: data.checked as boolean
});
}} />
{commonStore.platform !== 'web' &&
<Labeled flex breakline label={t('MIDI Input')}
desc={t('Select the MIDI input device to be used.')}
content={
<div className="flex flex-col gap-1">
<Dropdown style={{ minWidth: 0 }}
value={commonStore.activeMidiDeviceIndex === -1 ? t('None')! : commonStore.midiPorts[commonStore.activeMidiDeviceIndex].name}
selectedOptions={[commonStore.activeMidiDeviceIndex.toString()]}
onOptionSelect={(_, data) => {
if (data.optionValue) {
const index = Number(data.optionValue);
let action = (index === -1)
? () => CloseMidiPort()
: () => OpenMidiPort(index);
action().then(() => {
commonStore.setActiveMidiDeviceIndex(index);
}).catch((e) => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}
}}>
<Option value={'-1'}>{t('None')!}</Option>
{commonStore.midiPorts.map((p, i) =>
<Option key={i} value={i.toString()}>{p.name}</Option>)
}
</Dropdown>
<AudiotrackButton setPrompt={setPrompt} />
</div>
} />
}
</div>
<div className="flex justify-between gap-2">
<ToolTipButton desc={t('Regenerate')} icon={<ArrowSync20Regular />} onClick={() => {

View File

@@ -211,7 +211,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
@@ -229,7 +229,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
@@ -687,7 +687,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
@@ -705,7 +705,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,

View File

@@ -1,5 +1,5 @@
import commonStore, { MonitorData, Platform } from './stores/commonStore';
import { GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App';
import { FileExists, GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App';
import { Cache, checkUpdate, downloadProgramFiles, LocalConfig, refreshLocalModels, refreshModels } from './utils';
import { getStatus } from './apis';
import { EventsOn, WindowSetTitle } from '../wailsjs/runtime';
@@ -7,6 +7,8 @@ import manifest from '../../manifest.json';
import { defaultModelConfigs, defaultModelConfigsMac } from './pages/defaultConfigs';
import { t } from 'i18next';
import { Preset } from './types/presets';
import { toast } from 'react-toastify';
import { MidiMessage, MidiPort } from './types/composition';
export async function startup() {
initPresets();
@@ -26,6 +28,7 @@ export async function startup() {
initLocalModelsNotify();
initLoraModels();
initHardwareMonitor();
initMidi();
}
await initConfig();
@@ -134,3 +137,21 @@ async function initHardwareMonitor() {
}
});
}
async function initMidi() {
EventsOn('midiError', (data: string) => {
toast('MIDI Error: ' + data, { type: 'error' });
});
EventsOn('midiPorts', (data: MidiPort[]) => {
commonStore.setMidiPorts(data);
});
EventsOn('midiMessage', async (data: MidiMessage) => {
await (await import('./pages/AudiotrackManager/AudiotrackEditor')).midiMessageHandler(data);
});
if (await FileExists('assets/sound-font/accordion/instrument.json')) {
commonStore.setCompositionParams({
...commonStore.compositionParams,
useLocalSoundFont: true
});
}
}

View File

@@ -9,7 +9,14 @@ import { Preset } from '../types/presets';
import { AboutContent } from '../types/about';
import { Attachment, ChatParams, Conversation } from '../types/chat';
import { CompletionPreset } from '../types/completion';
import { CompositionParams } from '../types/composition';
import {
CompositionParams,
InstrumentType,
MidiMessage,
MidiPort,
Track,
tracksMinimalTotalTime
} from '../types/composition';
import { ModelConfig } from '../types/configs';
import { DownloadStatus } from '../types/downloads';
import { IntroductionContent } from '../types/home';
@@ -90,6 +97,20 @@ class CommonStore {
};
compositionGenerating: boolean = false;
compositionSubmittedPrompt: string = defaultCompositionPrompt;
// composition midi device
midiPorts: MidiPort[] = [];
activeMidiDeviceIndex: number = -1;
instrumentType: InstrumentType = InstrumentType.Piano;
// composition tracks
tracks: Track[] = [];
trackScale: number = 1;
trackTotalTime: number = tracksMinimalTotalTime;
trackCurrentTime: number = 0;
trackPlayStartTime: number = 0;
playingTrackId: string = '';
recordingTrackId: string = '';
recordingContent: string = ''; // used to improve performance of midiMessageHandler, and I'm too lazy to maintain an ID dictionary for this (although that would be better for realtime effects)
recordingRawContent: MidiMessage[] = [];
// configs
currentModelConfigIndex: number = 0;
modelConfigs: ModelConfig[] = [];
@@ -380,6 +401,54 @@ class CommonStore {
setSidePanelCollapsed(value: boolean | 'auto') {
this.sidePanelCollapsed = value;
}
setTracks(value: Track[]) {
this.tracks = value;
}
setTrackScale(value: number) {
this.trackScale = value;
}
setTrackTotalTime(value: number) {
this.trackTotalTime = value;
}
setTrackCurrentTime(value: number) {
this.trackCurrentTime = value;
}
setTrackPlayStartTime(value: number) {
this.trackPlayStartTime = value;
}
setMidiPorts(value: MidiPort[]) {
this.midiPorts = value;
}
setInstrumentType(value: InstrumentType) {
this.instrumentType = value;
}
setRecordingTrackId(value: string) {
this.recordingTrackId = value;
}
setActiveMidiDeviceIndex(value: number) {
this.activeMidiDeviceIndex = value;
}
setRecordingContent(value: string) {
this.recordingContent = value;
}
setRecordingRawContent(value: MidiMessage[]) {
this.recordingRawContent = value;
}
setPlayingTrackId(value: string) {
this.playingTrackId = value;
}
}
export default new CommonStore();

View File

@@ -1,5 +1,7 @@
import { NoteSequence } from '@magenta/music/esm/protobuf';
export const tracksMinimalTotalTime = 5000;
export type CompositionParams = {
prompt: string,
maxResponseToken: number,
@@ -9,4 +11,74 @@ export type CompositionParams = {
useLocalSoundFont: boolean,
midi: ArrayBuffer | null,
ns: NoteSequence | null
}
}
export type Track = {
id: string;
content: string;
rawContent: MidiMessage[];
offsetTime: number;
contentTime: number;
};
export type MidiPort = {
name: string;
}
export type MessageType = 'NoteOff' | 'NoteOn' | 'ElapsedTime' | 'ControlChange';
export type MidiMessage = {
messageType: MessageType;
channel: number;
note: number;
velocity: number;
control: number;
value: number;
instrument: InstrumentType;
}
export enum InstrumentType {
Piano,
Percussion,
Drum,
Tuba,
Marimba,
Bass,
Guitar,
Violin,
Trumpet,
Sax,
Flute,
Lead,
Pad,
}
export const InstrumentTypeNameMap = [
'Piano',
'Percussion',
'Drum',
'Tuba',
'Marimba',
'Bass',
'Guitar',
'Violin',
'Trumpet',
'Sax',
'Flute',
'Lead',
'Pad'
];
export const InstrumentTypeTokenMap = [
'pi',
'p',
'd',
't',
'm',
'b',
'g',
'v',
'tr',
's',
'f',
'l',
'pa'
];

View File

@@ -23,7 +23,8 @@ export const convertToSt = async (navigate: NavigateFunction, selectedConfig: Mo
const newModelPath = modelPath.replace(/\.pth$/, '.st');
ConvertSafetensors(commonStore.settings.customPythonPath, modelPath, newModelPath).then(async () => {
if (!await FileExists(newModelPath)) {
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
if (commonStore.platform === 'windows')
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
} else {
toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' });
}

View File

@@ -22,6 +22,7 @@ import { DownloadStatus } from '../types/downloads';
import { ModelSourceItem } from '../types/models';
import { Language, Languages, SettingsType } from '../types/settings';
import { DataProcessParameters, LoraFinetuneParameters } from '../types/train';
import { tracksMinimalTotalTime } from '../types/composition';
export type Cache = {
version: string
@@ -480,6 +481,58 @@ export function getHfDownloadUrl(url: string) {
return url;
}
export function refreshTracksTotalTime() {
if (commonStore.tracks.length === 0) {
commonStore.setTrackTotalTime(tracksMinimalTotalTime);
commonStore.setTrackCurrentTime(0);
commonStore.setTrackPlayStartTime(0);
return;
}
const endTimes = commonStore.tracks.map(t => t.offsetTime + t.contentTime);
const totalTime = Math.max(...endTimes) + tracksMinimalTotalTime;
if (commonStore.trackPlayStartTime > totalTime)
commonStore.setTrackPlayStartTime(totalTime);
commonStore.setTrackTotalTime(totalTime);
}
export function flushMidiRecordingContent() {
const recordingTrackIndex = commonStore.tracks.findIndex(t => t.id === commonStore.recordingTrackId);
if (recordingTrackIndex >= 0) {
const recordingTrack = commonStore.tracks[recordingTrackIndex];
const tracks = commonStore.tracks.slice();
const contentTime = commonStore.recordingRawContent
.reduce((sum, current) =>
sum + (current.messageType === 'ElapsedTime' ? current.value : 0)
, 0);
tracks[recordingTrackIndex] = {
...recordingTrack,
content: commonStore.recordingContent,
rawContent: commonStore.recordingRawContent,
contentTime: contentTime
};
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}
commonStore.setRecordingContent('');
commonStore.setRecordingRawContent([]);
}
export async function getSoundFont() {
let soundUrl: string;
if (commonStore.compositionParams.useLocalSoundFont)
soundUrl = 'assets/sound-font';
else
soundUrl = !commonStore.settings.giteeUpdatesSource ?
`https://raw.githubusercontent.com/josStorer/sgm_plus/master` :
`https://gitee.com/josc146/sgm_plus/raw/master`;
const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus';
await fetch(soundUrl + '/soundfont.json').then(r => {
if (!r.ok)
soundUrl = fallbackUrl;
}).catch(() => soundUrl = fallbackUrl);
return soundUrl;
}
export function getSupportedCustomCudaFile(isBeta: boolean) {
if ([' 10', ' 16', ' 20', ' 30', 'MX', 'Tesla P', 'Quadro P', 'NVIDIA P', 'TITAN X', 'TITAN RTX', 'RTX A',
'Quadro RTX 4000', 'Quadro RTX 5000', 'Tesla T4', 'NVIDIA A10', 'NVIDIA A40'].some(v => commonStore.status.device_name.includes(v)))

View File

@@ -21,6 +21,7 @@ const embedded = [
// dependencies that exist in single component
'react-beautiful-dnd',
'react-draggable',
'@magenta/music', 'html-midi-player',
'react-markdown', 'rehype-highlight', 'rehype-raw', 'remark-breaks', 'remark-gfm'
];

View File

@@ -4,6 +4,8 @@ import {backend_golang} from '../models';
export function AddToDownloadList(arg1:string,arg2:string):Promise<void>;
export function CloseMidiPort():Promise<void>;
export function ContinueDownload(arg1:string):Promise<void>;
export function ConvertData(arg1:string,arg2:string,arg3:string,arg4:string):Promise<string>;
@@ -36,6 +38,8 @@ export function MergeLora(arg1:string,arg2:boolean,arg3:number,arg4:string,arg5:
export function OpenFileFolder(arg1:string,arg2:boolean):Promise<void>;
export function OpenMidiPort(arg1:number):Promise<void>;
export function OpenOpenFileDialog(arg1:string):Promise<string>;
export function OpenSaveFileDialog(arg1:string,arg2:string,arg3:string):Promise<string>;
@@ -44,6 +48,8 @@ export function OpenSaveFileDialogBytes(arg1:string,arg2:string,arg3:Array<numbe
export function PauseDownload(arg1:string):Promise<void>;
export function PlayNote(arg1:backend_golang.MIDIMessage):Promise<void>;
export function ReadFileInfo(arg1:string):Promise<backend_golang.FileInfo>;
export function ReadJson(arg1:string):Promise<any>;

View File

@@ -6,6 +6,10 @@ export function AddToDownloadList(arg1, arg2) {
return window['go']['backend_golang']['App']['AddToDownloadList'](arg1, arg2);
}
export function CloseMidiPort() {
return window['go']['backend_golang']['App']['CloseMidiPort']();
}
export function ContinueDownload(arg1) {
return window['go']['backend_golang']['App']['ContinueDownload'](arg1);
}
@@ -70,6 +74,10 @@ export function OpenFileFolder(arg1, arg2) {
return window['go']['backend_golang']['App']['OpenFileFolder'](arg1, arg2);
}
export function OpenMidiPort(arg1) {
return window['go']['backend_golang']['App']['OpenMidiPort'](arg1);
}
export function OpenOpenFileDialog(arg1) {
return window['go']['backend_golang']['App']['OpenOpenFileDialog'](arg1);
}
@@ -86,6 +94,10 @@ export function PauseDownload(arg1) {
return window['go']['backend_golang']['App']['PauseDownload'](arg1);
}
export function PlayNote(arg1) {
return window['go']['backend_golang']['App']['PlayNote'](arg1);
}
export function ReadFileInfo(arg1) {
return window['go']['backend_golang']['App']['ReadFileInfo'](arg1);
}

View File

@@ -18,6 +18,28 @@ export namespace backend_golang {
this.modTime = source["modTime"];
}
}
export class MIDIMessage {
messageType: string;
channel: number;
note: number;
velocity: number;
control: number;
value: number;
static createFrom(source: any = {}) {
return new MIDIMessage(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.messageType = source["messageType"];
this.channel = source["channel"];
this.note = source["note"];
this.velocity = source["velocity"];
this.control = source["control"];
this.value = source["value"];
}
}
}

1
go.mod
View File

@@ -5,6 +5,7 @@ go 1.20
require (
github.com/cavaliergopher/grab/v3 v3.0.1
github.com/fsnotify/fsnotify v1.6.0
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79
github.com/minio/selfupdate v0.6.0
github.com/nyaosorg/go-windows-su v0.2.1
github.com/ubuntu/gowsl v0.0.0-20230615094051-94945650cc1e

2
go.sum
View File

@@ -38,6 +38,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79 h1:CA1UHN3RuY70DlC0RlvgtB1e8h3kYzmvK7s8CFe+Ohw=
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79/go.mod h1:oBuZjmjlKSj9CZKrNhcx/adNhHiiE0hZknECjIP8Z0Q=
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM=
github.com/nyaosorg/go-windows-su v0.2.1 h1:5V0XavLyjOqPUp7psxxCvBISaneU4XmFPSMlejSl5sc=

View File

@@ -1,5 +1,5 @@
{
"version": "1.5.3",
"version": "1.5.5",
"introduction": {
"en": "RWKV is an open-source, commercially usable large language model with high flexibility and great potential for development.\n### About This Tool\nThis tool aims to lower the barrier of entry for using large language models, making it accessible to everyone. It provides fully automated dependency and model management. You simply need to click and run, following the instructions, to deploy a local large language model. The tool itself is very compact and only requires a single executable file for one-click deployment.\nAdditionally, this tool offers an interface that is fully compatible with the OpenAI API. This means you can use any ChatGPT client as a client for RWKV, enabling capability expansion beyond just chat functionality.\n### Preset Configuration Rules at the Bottom\nThis tool comes with a series of preset configurations to reduce complexity. The naming rules for each configuration represent the following in order: device - required VRAM/memory - model size - model language.\nFor example, \"GPU-8G-3B-EN\" indicates that this configuration is for a graphics card with 8GB of VRAM, a model size of 3 billion parameters, and it uses an English language model.\nLarger model sizes have higher performance and VRAM requirements. Among configurations with the same model size, those with higher VRAM usage will have faster runtime.\nFor example, if you have 12GB of VRAM but running the \"GPU-12G-7B-EN\" configuration is slow, you can downgrade to \"GPU-8G-3B-EN\" for a significant speed improvement.\n### About RWKV\nRWKV is an RNN with Transformer-level LLM performance, which can also be directly trained like a GPT transformer (parallelizable). And it's 100% attention-free. You only need the hidden state at position t to compute the state at position t+1. You can use the \"GPT\" mode to quickly compute the hidden state for the \"RNN\" mode.<br/>So it's combining the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, \"infinite\" ctx_len, and free sentence embedding (using the final hidden state).",
"zh": "RWKV是一个开源且允许商用的大语言模型灵活性很高且极具发展潜力。\n### 关于本工具\n本工具旨在降低大语言模型的使用门槛做到人人可用本工具提供了全自动化的依赖和模型管理你只需要直接点击运行跟随引导即可完成本地大语言模型的部署工具本身体积极小只需要一个exe即可完成一键部署。\n此外本工具提供了与OpenAI API完全兼容的接口这意味着你可以把任意ChatGPT客户端用作RWKV的客户端实现能力拓展而不局限于聊天。\n### 底部的预设配置规则\n本工具内置了一系列预设配置以降低使用难度每个配置名的规则依次代表着设备-所需显存/内存-模型规模-模型语言。\n例如GPU-8G-3B-CN表示该配置用于显卡需要8G显存模型规模为30亿参数使用的是中文模型。\n模型规模越大性能要求越高显存要求也越高而同样模型规模的配置中显存占用越高的运行速度越快。\n例如当你有12G显存但运行GPU-12G-7B-CN配置速度比较慢可降级成GPU-8G-3B-CN将会大幅提速。\n### 关于RWKV\nRWKV是具有Transformer级别LLM性能的RNN也可以像GPT Transformer一样直接进行训练可并行化。而且它是100% attention-free的。你只需在位置t处获得隐藏状态即可计算位置t + 1处的状态。你可以使用“GPT”模式快速计算用于“RNN”模式的隐藏状态。\n因此它将RNN和Transformer的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"