Skip to content

Commit

Permalink
add:替换规则
Browse files Browse the repository at this point in the history
  • Loading branch information
l1veIn committed Sep 20, 2024
1 parent b3d68dc commit ed6fe58
Show file tree
Hide file tree
Showing 10 changed files with 136 additions and 33 deletions.
1 change: 1 addition & 0 deletions child_process/asr_process/asr_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ function createRecognizer(message) {
logger.info('开始创建识别器', { message });
const config = get_config(message);
logger.debug('识别器配置', { config });
console.log({config})
const recognizer = new sherpa_onnx.OfflineRecognizer(config);
logger.info('识别器创建完成');
return recognizer;
Expand Down
32 changes: 25 additions & 7 deletions child_process/asr_process/get_config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@

const { join } = require('path');
let modelConfigMap = {
"sherpa-onnx-whisper-tiny": "tiny",
"sherpa-onnx-whisper-base": "base",
"sherpa-onnx-whisper-small": "small",
"sherpa-onnx-whisper-large-v3": "large-v3"
};
function get_config(message) {
switch (message.model) {
case "sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17":
Expand All @@ -22,14 +28,8 @@ function get_config(message) {
case "sherpa-onnx-whisper-tiny":
case "sherpa-onnx-whisper-base":
case "sherpa-onnx-whisper-small":
case "sherpa-onnx-whisper-large-v3":
let modelConfigMap = {
"sherpa-onnx-whisper-tiny": "tiny",
"sherpa-onnx-whisper-base": "base",
"sherpa-onnx-whisper-small": "small",
"sherpa-onnx-whisper-large_v3": "large-v3"
};
modelSize = modelConfigMap[message.model];
console.log(modelSize)
return {
'featConfig': {
'sampleRate': 16000,
Expand All @@ -46,6 +46,24 @@ function get_config(message) {
'debug': 1,
}
};
case "sherpa-onnx-whisper-large-v3":
modelSize = modelConfigMap[message.model];
return {
'featConfig': {
'sampleRate': 16000,
'featureDim': 80,
},
'modelConfig': {
'whisper': {
'encoder': join(message.modelDir, message.model, `${modelSize}-encoder.int8.onnx`),
'decoder': join(message.modelDir, message.model, `${modelSize}-decoder.int8.onnx`),
},
'tokens': join(message.modelDir, message.model, `${modelSize}-tokens.txt`),
'numThreads': 2,
'provider': 'cpu',
'debug': 1,
}
};

case "sherpa-onnx-zipformer-multi-zh-hans-2023-9-2":
return {
Expand Down
1 change: 1 addition & 0 deletions child_process/nut/handle_nut.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ async function register(message) {
runner: runner,
isRunning: false,
listener: async (keypress, down) => {
// console.log('keypress', keypress.name);
if (!getCondition(keypress, message, down)) {
return
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lol_wom_helper",
"version": "1.0.1",
"version": "1.0.2",
"description": "LOL互动助手",
"main": "./out/main/index.js",
"author": "kaihei.online",
Expand Down
34 changes: 30 additions & 4 deletions src/ipc/asr.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,25 @@ const portAudio = require('naudiodon2');
import icon from '../../resources/icon.png?asset'
import logger from '../utils/logger';
import { app } from 'electron';
import fs from 'fs/promises';

let replacementRules = {};
export function setupASR(win) {
logger.info('开始设置 ASR');
let lyricsWindow
let asrProcess = new ChildProcessManager(path.join(__dirname, '../../child_process/asr_process/asr_process.js'))


asrProcess.on('message', (message) => {
logger.debug('收到 ASR 进程消息', { message });
clipboard.writeText(message);
win.webContents.send('asr-message', message);

// 应用替换规则
let processedMessage = applyReplacementRules(message);

clipboard.writeText(processedMessage);
win.webContents.send('asr-message', processedMessage);
if (lyricsWindow) {
lyricsWindow.webContents.send('asr-message', message);
lyricsWindow.webContents.send('asr-message', processedMessage);
}
});

Expand All @@ -28,9 +35,20 @@ export function setupASR(win) {
logger.info('ASR 进程退出');
});

ipcMain.handle('start-asr', (_, data) => {
ipcMain.handle('start-asr', async (_, data) => {
logger.info('收到启动 ASR 请求', { data });
if (!asrProcess.exist()) {
// 读取替换规则文件
if (data.modelDir) {
try {
const ruleContent = await fs.readFile(path.join(data.modelDir, 'rules.json'), 'utf-8');
replacementRules = JSON.parse(ruleContent);
logger.debug('成功读取替换规则', { rules: replacementRules });
} catch (error) {
logger.error('读取替换规则文件失败', { error });
}
}

asrProcess.start()
asrProcess.send({...data, logPath: join(app.getPath('userData'), 'logs')});
logger.debug('ASR 进程已启动并发送数据');
Expand Down Expand Up @@ -129,4 +147,12 @@ export function setupASR(win) {
});

logger.info('ASR 设置完成');
}

function applyReplacementRules(message) {
let processedMessage = message;
for (const [key, value] of Object.entries(replacementRules)) {
processedMessage = processedMessage.replace(new RegExp(key, 'g'), value);
}
return processedMessage;
}
39 changes: 38 additions & 1 deletion src/ipc/asr_model_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const fs = require('fs');
const path = require('path');
const tar = require('tar');
const bzip2 = require('unbzip2-stream');
const { ipcMain, dialog } = require('electron');
const { ipcMain, dialog, shell } = require('electron');

export function setupASRModelManager(win) {
logger.info('开始设置 ASR 模型管理器');
Expand All @@ -19,6 +19,21 @@ export function setupASRModelManager(win) {
logger.info('用户选择的目录', { path: result.filePaths[0] });
return result.filePaths[0];
});
ipcMain.handle('select-file', async () => {
logger.debug('收到选择文件请求');
// 只能选择json文件
const result = await dialog.showOpenDialog({
properties: ['openFile'],
filters: [{ name: 'JSON', extensions: ['json'] }]
});
logger.info('用户选择的文件', { path: result.filePaths[0] });
return result.filePaths[0];
});

ipcMain.handle('open-model-dir', (event, modelDir) => {
logger.debug('打开模型目录', { modelDir });
shell.openPath(modelDir);
});

ipcMain.handle('check-model-existence', (event, { modelDir, modelName }) => {
logger.debug('检查模型是否存在', { modelDir, modelName });
Expand All @@ -27,7 +42,29 @@ export function setupASRModelManager(win) {
logger.info('模型存在性检查结果', { dirExists, tarExists });
return { dir: dirExists, tar: tarExists };
});
ipcMain.handle('check-rule-file', (event, modelDir) => {
logger.debug('检查规则文件是否存在', { modelDir });
const rulePath = path.join(modelDir, 'rules.json');
const fileExists = fs.existsSync(rulePath);

if (!fileExists) {
logger.info('规则文件不存在,正在创建默认文件');
try {
fs.writeFileSync(rulePath, JSON.stringify({
"我操": "我超",
"牛逼": "NB"
}, null, 2));
logger.info('默认规则文件创建成功');
return true;
} catch (error) {
logger.error('创建默认规则文件失败', { error });
return false;
}
}

logger.info('规则文件存在性检查结果', { fileExists });
return fileExists;
});
ipcMain.handle('start-download', async (event, { url, destination, modelName, modelDir }) => {
logger.info('开始下载模型', { url, destination, modelName });
try {
Expand Down
11 changes: 11 additions & 0 deletions src/ipc/shortcut.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,33 @@ const { ipcMain, clipboard } = require('electron');
const { fork } = require('child_process');
const path = require('path');

import logger from '../utils/logger';

// import Store from 'electron-store';
// 创建一个新的 Store 实例
// const store = new Store();

export function setupShortcut(win, sender) {
// 存储当前注册的快捷键状态
// let currentStatus = store.get('currentStatus', {});
logger.info('开始设置快捷键');
let currentStatus = {}
let shortcutProcess = new ChildProcessManager(path.join(__dirname, '../../child_process/nut/handle_nut.js'))
shortcutProcess.start()
logger.info('快捷键子进程已启动');

// 注册默认的快捷键
currentStatus['PAGE UP'] = '';
currentStatus['PAGE DOWN'] = '';
// 打印当前快捷键状态并注册
Object.entries(currentStatus).forEach(([key, value]) => {
console.log(key + ': ' + value);
logger.debug(`注册快捷键: ${key} - ${value}`);
shortcutProcess.send({ key, script: value });
});

shortcutProcess.on('message', (message) => {
logger.debug('收到子进程消息:', message);
if (message.sendClipboard2Game) {
sender.send({ ...message, data: clipboard.readText() })
} else if (message.onPageUp) {
Expand All @@ -37,29 +43,34 @@ export function setupShortcut(win, sender) {
})
// 处理获取快捷键状态的请求
ipcMain.handle('get-shortcut-status', (event, shortcut) => {
logger.debug(`获取快捷键状态: ${shortcut}`);
return shortcut in currentStatus;
});
// 处理注册快捷键的请求
ipcMain.handle('register-shortcut', (event, shortcut, script) => {
try {
logger.info(`注册快捷键: ${shortcut}`);
shortcutProcess.send({ key: shortcut, script: script });
currentStatus[shortcut] = script || '';
// store.set('currentStatus', currentStatus);
} catch (error) {
console.error(`Error registering shortcut: ${shortcut}`, error);
logger.error(`注册快捷键失败: ${shortcut}`, error);
return false;
}
});

// 处理注销快捷键的请求
ipcMain.handle('unregister-shortcut', (event, shortcut) => {
try {
logger.info(`注销快捷键: ${shortcut}`);
shortcutProcess.send({ key: shortcut, remove: true });
delete currentStatus[shortcut];
// store.set('currentStatus', currentStatus);
return true;
} catch (error) {
console.error(`Error unregistering shortcut: ${shortcut}`, error);
logger.error(`注销快捷键失败: ${shortcut}`, error);
return false;
}
});
Expand Down
3 changes: 3 additions & 0 deletions src/main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { electronApp, optimizer } from '@electron-toolkit/utils'
import logger from '../utils/logger.js';

import { createWindow } from './window';
// app.commandLine.appendSwitch("--in-process-gpu");



// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
Expand Down
11 changes: 8 additions & 3 deletions src/main/ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export function setupIPC(win, store) {
ipcMain.handle('send-msg-to-game', (event, message) => {
sender.send({ sendClipboard2Game: true, data: message })
})
ipcMain.handle('send-msg-to-game-all', (event, message) => {
sender.send({ sendClipboard2GameAll: true, data: message })
})
ipcMain.handle('init_lcu', () => init_lcu(win));
ipcMain.handle('current-summoner', getCurrentSummoner);
ipcMain.handle('get-client-url', getClientUrl);
Expand All @@ -58,15 +61,17 @@ export function setupIPC(win, store) {
});
newWindow.loadURL(tool.url);
});
ipcMain.handle('exec-cmd', (event, cmd) => {
exec(cmd, (error, stdout, stderr) => {
ipcMain.handle('shutdown-computer', () => {
// 关电脑
// 赢一把就睡觉功能,不管输赢检测到打完一把游戏直接关机!
exec('shutdown -s -t 0', (error, stdout, stderr) => {
if (error) {
console.error(`执行命令时发生错误: ${error.message}`);
return;
}
console.log(`命令输出: ${stdout}`);
});
});
})
setupASR(win)
setupASRModelManager(win)
setupShortcut(win, sender)
Expand Down
35 changes: 18 additions & 17 deletions src/main/window.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,25 @@ export function createWindow() {
mainWindow.loadURL("https://kaihei.online/lol-wom-helper")
} else {
const defaultUrl = "https://kaihei.online/lol-wom-helper";
const checkUrlAvailability = async (url) => {
try {
const response = await fetch(url, { method: 'HEAD' });
return response.ok;
} catch (error) {
return false;
}
};
mainWindow.loadURL(defaultUrl);
// const checkUrlAvailability = async (url) => {
// try {
// const response = await fetch(url, { method: 'HEAD' });
// return response.ok;
// } catch (error) {
// return false;
// }
// };

const loadUrlOrDefault = async () => {
const isAvailable = await checkUrlAvailability(defaultUrl);
if (isAvailable) {
mainWindow.loadURL(defaultUrl);
} else {
mainWindow.loadFile(defaultPage);
}
};
loadUrlOrDefault();
// const loadUrlOrDefault = async () => {
// const isAvailable = await checkUrlAvailability(defaultUrl);
// if (isAvailable) {
// mainWindow.loadURL(defaultUrl);
// } else {
// mainWindow.loadFile(defaultPage);
// }
// };
// loadUrlOrDefault();
}
// let lastPosition = { x: 0, y: 0 }

Expand Down

0 comments on commit ed6fe58

Please sign in to comment.