V 2.2.6 增加了MJ的api

This commit is contained in:
2024-06-01 15:08:22 +08:00
parent 941a86d07a
commit 8b011856c2
52 changed files with 3255 additions and 2376 deletions
+14
View File
@@ -0,0 +1,14 @@
import { ipcMain } from "electron";
import { DEFINE_STRING } from '../../define/define_string'
import { Image } from "../Public/Image";
let image = new Image(global);
function ImageIpc() {
// 一拆四
ipcMain.handle(DEFINE_STRING.IMG.ONE_SPLIT_FOUR, async (event, value) => await image.OneSplitFour(value));
}
export {
ImageIpc
}
+6
View File
@@ -57,6 +57,12 @@ function MjIpc() {
// 给图片链接,下载指定的图片并分割保存
ipcMain.handle(DEFINE_STRING.MJ.DOWNLOAD_IMAGE_URL_AND_SPLIT, async (event, value) => await mJOriginalImageGenerate.DownloadImageUrlAndSplit(value));
// 获取MJ图片的所有的分割尺寸
ipcMain.handle(DEFINE_STRING.MJ.GET_MJ_IMAGE_SCALE, async (event) => await mjSimple.GetMJImageScale());
// 获取所有的MJ生图模型
ipcMain.handle(DEFINE_STRING.MJ.GET_MJ_IMAGE_ROBOT_MODEL, async (event) => await mjSimple.GetMJImageRobotModel());
/**
* 监听DISCORD界面创建消息,并修改数据
*/
+262 -78
View File
@@ -9,7 +9,11 @@ import path from 'path'
import sharp from 'sharp'
import { define } from "../../define/define";
import { AwesomeRegx } from "awesome-js";
import { checkStringValueAddSuffix } from "../generalTools";
import { checkStringValueAddSuffix, errorMessage, successMessage } from "../generalTools";
import { ImageSetting } from "../../define/setting/imageSetting";
import { DiscordAPI } from "../../api/discordApi";
import { GPT } from "../Public/GPT";
const { v4: uuidv4 } = require('uuid');
/**
* MJ原创生图的类
@@ -20,6 +24,39 @@ export class MJOriginalImageGenerate {
this.pm = new PublicMethod(global);
this.discordWorker = new DiscordWorker();
this.tools = new Tools();
this.discordAPI = new DiscordAPI();
this.gpt = new GPT(global);
}
/**
* 返回指定的人物到前端
* @param {*} data
*/
sendChangeMessage(data) {
this.global.newWindow[0].win.webContents.send(DEFINE_STRING.DISCORD.MAIN_DISCORD_MESSAGE_CHANGE, data);
}
/**
* 初始化MJ设置
*/
async InitMjSetting() {
let mjSetting_res = await ImageSetting.GetDefineConfigJsonByProperty(JSON.stringify(['img_base', 'mj_config', false, null]));
if (mjSetting_res.code == 0 || !mjSetting_res.data) {
throw new Error("请先添加MJ配置")
}
let mjSetting = mjSetting_res.data;
return mjSetting;
}
/**
* 初始化MJ API的URL
*/
async InitMJAPIUrl(id) {
let mj_api = (await this.gpt.GetGPTBusinessOption("all", (value) => value.mj_url)).data;
let mj_api_url_index = mj_api.findIndex(item => item.value == id);
if (mj_api_url_index == -1) {
throw new Error("没有找到对应的MJ API的配置,请先检查配置")
}
return mj_api[mj_api_url_index];
}
/**
@@ -28,6 +65,7 @@ export class MJOriginalImageGenerate {
*/
async DownloadImageUrlAndSplit(value) {
try {
console.log(value)
value = JSON.parse(value);
let element = value[0];
let iamge_url = value[1];
@@ -77,52 +115,97 @@ export class MJOriginalImageGenerate {
async GetGeneratedMJImageAndSplit(value) {
try {
value = JSON.parse(value);
let param = [];
// 循环数据,直传需要的数据
for (let i = 0; i < value.length; i++) {
const element = value[i];
param.push({
id: element.id,
image_id: element.mj_message.image_id,
name: element.name,
});
let mjSetting = await this.InitMjSetting();
let request_model = mjSetting.request_model;
let result = [];
// 浏览器生图模式
if (request_model == "browser_mj") {
let param = [];
// 循环数据,直传需要的数据
for (let i = 0; i < value.length; i++) {
const element = value[i];
// 一般进度大于 50 会出现图片,
if (!element.mj_message) {
continue;
}
if (element.mj_message.progress && element.mj_message.progress == 100) {
// 判断 image_path 是不是存在。
if (item.mj_message.image_id && !element.mj_message.image_path) {
// 通过当前的image_id获取图片
param.push({
id: element.id,
image_id: element.mj_message.image_id,
name: element.name,
});
}
}
}
// 判断窗口是不是开启
let discordWin = await this.discordWorker.CheckDiscordWindowIsOpenAndLoad();
// 执行采集图片的脚本
// 开始写入
let discordSimple = new DiscordSimple(discordWin);
// 开始执行脚本
result = await discordSimple.ExecuteScript(define.discordScript, `GetGeneratedMJImageAndSplit(${JSON.stringify(param)})`);
} else if (request_model == "api_mj") {
let mj_api = await this.InitMJAPIUrl(mjSetting.mj_api_url);
let once_get_task = mj_api.mj_url.once_get_task;
// 请求
for (let i = 0; i < value.length; i++) {
const element = value[i];
if (element.mj_message.progress == 100) {
continue
}
if (element.mj_message.progress.status == "success") {
continue
}
let task_res = await this.discordAPI.GetMJAPITaskByID(element.mj_message.message_id, once_get_task, mjSetting.api_key);
if (task_res.code == 0) {
task_res["id"] = element.id;
task_res["mj_api_url"] = mjSetting.mj_api_url;
this.sendChangeMessage()
}
// 判断进度是不是百分百
if (task_res.progress != 100) {
continue
}
result.push({
id: element.id,
image_id: null,
result: task_res.image_click,
name: element.name
})
}
}
// 判断窗口是不是开启
let discordWin = await this.discordWorker.CheckDiscordWindowIsOpenAndLoad();
// 执行采集图片的脚本
// 开始写入
let discordSimple = new DiscordSimple(discordWin);
// 开始执行脚本
let result = await discordSimple.ExecuteScript(define.discordScript, `GetGeneratedMJImageAndSplit(${JSON.stringify(param)})`);
let res = [];
result = JSON.parse(result);
// 判断返回的数据是不是一个字符串
if (typeof result == "string") {
result = JSON.parse(result);
}
// 将返回的数据进行分割
for (let i = 0; i < result.length; i++) {
const element = result[i];
let image_path = path.join(global.config.project_path, `data\\MJOriginalImage\\${element.image_id}.png`);
let ds = this.DownloadImageUrlAndSplit(JSON.stringify[element, element.result, image_path]);
let image_path = path.join(global.config.project_path, `data\\MJOriginalImage\\${uuidv4()}.png`);
let ds = await this.DownloadImageUrlAndSplit(JSON.stringify([element, element.result, image_path]));
if (ds.code == 0) {
throw new Error(ds.message);
}
// 修改数据。
ds.data["progress"] = 100;
ds.data["status"] = "success";
res.push(ds.data);
}
// 全部分割完毕,返回
return {
code: 1,
data: res
}
return successMessage(res);
} catch (error) {
return {
code: 0,
message: "获取已经生图完成的数据,并获取图片错误,错误信息如下" + error.message
}
return errorMessage("获取已经生图完成的数据,并获取图片错误,错误信息如下" + error.message)
}
}
@@ -182,6 +265,114 @@ export class MJOriginalImageGenerate {
}
/**
* 调用API生图的方法
* @param {*} element
* @param {*} mjSetting
*/
async MJImagineRequest(element, mjSetting, prompt) {
try {
// 获取当前的API url
let apiUrl = await this.InitMJAPIUrl(mjSetting.mj_api_url);
let imagine_url = apiUrl.mj_url.imagine;
let once_get_task = apiUrl.mj_url.once_get_task;
let task_count = mjSetting.task_count ? mjSetting.task_count : 3;
let request_model = mjSetting.request_model ? mjSetting.request_model : "relaxed";
let res;
// 判断当前的API是哪个
if (imagine_url.includes("mjapi.deepwl.net")) {
// DrawAPI(MJ)
let data = {
prompt: prompt,
mode: request_model == "fast" ? "FAST" : "RELAX",
}
let headers = {
"Authorization": mjSetting.api_key
}
res = await this.discordAPI.mjApiImagine(imagine_url, data, headers);
} else if (imagine_url.includes("api.ephone.ai")) {
// ePhoneAPI
let headers = {
"Authorization": mjSetting.api_key
}
let data = {
prompt: prompt,
botType: "MID_JOURNEY",
accountFilter: {
modes: [
request_model == "fast" ? "FAST" : "RELAX"
]
}
}
res = await this.discordAPI.mjApiImagine(imagine_url, data, headers);
}
// 创建成功,开始下一个
this.sendChangeMessage({
code: 1,
type: "created",
category: "api_mj",
message_id: res.result,
image_click: null,
image_show: null,
id: element.id,
progress: 0,
mj_api_url: mjSetting.mj_api_url
});
this.global.mjGenerateQuene.setCurrentCreateItem(null);
// 开始监听当前ID是不是的生图任务完成
// 这边设置一个循环监听,每隔一段时间去请求一次
let timeoutId;
let startInterval = () => {
timeoutId = setTimeout(async () => {
// 执行你的操作
let task_res = await this.discordAPI.GetMJAPITaskByID(res.result, once_get_task, mjSetting.api_key)
console.log(task_res)
// 判断他的状态是不是成功
if (task_res.code == 0) {
// 将但钱任务删除
this.global.mjGenerateQuene.removeTaskProgress((taskProgress) => {
return taskProgress.filter(item => item?.id != element.id)
});
// 停止当前循环
clearTimeout(timeoutId);
} else {
if (task_res.progress == 100) {
// 将但钱任务删除
this.global.mjGenerateQuene.removeTaskProgress((taskProgress) => {
return taskProgress.filter(item => item?.id != element.id)
});
task_res.type = "finished";
// 下载对应的图片
let image_path = path.join(this.global.config.project_path, `data\\MJOriginalImage\\${task_res.message_id}.png`);
// 这边开始下载对应的图片
await this.tools.downloadFileUrl(task_res.image_click, image_path);
task_res["image_path"] = image_path;
// 开始下一个任务
this.global.mjGenerateQuene.startNextTask(task_count);
} else {
// 当获取的图片的进度小于100的时候,继续监听
startInterval();
}
}
task_res['id'] = element.id;
task_res["mj_api_url"] = mjSetting.mj_api_url;
this.sendChangeMessage(task_res);
}, 5000);
}
startInterval();
this.global.mjGenerateQuene.startNextTask(task_count);
} catch (error) {
this.sendChangeMessage({
code: 0,
status: "error",
message: error.message,
id: element.id
})
throw new Error("MJ API 出图错误,错误信息如下:" + error.message)
}
}
/**
* MJ 原创生图
* @param {*} value
@@ -206,6 +397,8 @@ export class MJOriginalImageGenerate {
let output_crop_00001 = path.join(this.global.config.project_path, `tmp\\output_crop_00001`);
await this.tools.checkFolderExistsOrCreate(output_crop_00001);
// 获取MJ配置
let mjSetting = await this.InitMjSetting();
// 检查this.global中是不是又mj队列,没有的话创建一个
if (!this.global.mjGenerateQuene) {
@@ -225,35 +418,41 @@ export class MJOriginalImageGenerate {
let old_prompt = element.prompt;
// 拼接提示词
// 图生图的链接
// 获取风格词
let prompt = " " + image_styles + old_prompt;
// 获取风格词 + 命令后缀
let prompt = " " + image_styles + old_prompt + (mjSetting.image_suffix ? mjSetting.image_suffix : "");
this.global.mjGenerateQuene.enqueue(async () => {
try {
this.global.mjGenerateQuene.setCurrentCreateItem(element)
// 开始进行mj生图
current_task = element.name;
// 判断窗口是不是开启
let discordW = await this.discordWorker.CheckDiscordWindowIsOpenAndLoad();
// 开始写入
let discordSimple = new DiscordSimple(discordW);
await discordSimple.WritePromptToInput(prompt);
// 发送命令完成(删除当前正在执行。开始下一个任务)
} catch (error) {
throw error;
}
}, tasK_id, batch);
// 判断当前生图模式
let request_model = mjSetting.request_model
switch (request_model) {
case "api_mj":
this.global.mjGenerateQuene.enqueue(async () => {
this.global.mjGenerateQuene.setCurrentCreateItem(element)
await this.MJImagineRequest(element, mjSetting, prompt)
}, tasK_id, batch)
break;
case "browser_mj":
this.global.mjGenerateQuene.enqueue(async () => {
try {
this.global.mjGenerateQuene.setCurrentCreateItem(element)
// 开始进行mj生图
current_task = element.name;
// 判断窗口是不是开启
let discordW = await this.discordWorker.CheckDiscordWindowIsOpenAndLoad();
// 开始写入
let discordSimple = new DiscordSimple(discordW, mjSetting);
await discordSimple.WritePromptToInput(prompt);
// 发送命令完成(删除当前正在执行。开始下一个任务)
} catch (error) {
throw error;
}
}, tasK_id, batch);
default:
break;
}
}
// 判断该当前正在执行的人物队列数(小于设置的数量,开始一个任务)
this.global.mjGenerateQuene.startNextTask();
this.global.mjGenerateQuene.startNextTask(mjSetting.task_count ? mjSetting.task_count : 3);
this.global.requestQuene.setBatchCompletionCallback(batch, (failedTasks) => {
if (failedTasks.length > 0) {
@@ -265,31 +464,16 @@ export class MJOriginalImageGenerate {
message += `${taskId}-, \n 错误信息: ${error}` + '\n';
});
this.global.newWindow[0].win.webContents.send(DEFINE_STRING.SHOW_MESSAGE_DIALOG, {
code: 0,
message: message
})
this.global.newWindow[0].win.webContents.send(DEFINE_STRING.SHOW_MESSAGE_DIALOG, errorMessage(message))
} else {
if (show_global_message) {
this.global.newWindow[0].win.webContents.send(DEFINE_STRING.SHOW_MESSAGE_DIALOG, {
code: 1,
message: "所有MJ生图任务完成"
})
this.global.newWindow[0].win.webContents.send(DEFINE_STRING.SHOW_MESSAGE_DIALOG, successMessage(null, '所有MJ生图任务完成'))
}
}
});
return {
code: 1,
}
return successMessage(null)
} catch (error) {
return {
code: 0,
message: "MJ生图错误,错误信息如下" + error.message
}
return errorMessage("MJ生图错误,错误信息如下" + error.message)
}
}
+3 -2
View File
@@ -214,7 +214,6 @@ export class OriginalImageGenerate {
}
}
/**
* 自动保存数据到json文件
* @param {*} value 自动保存数据到json文件
@@ -223,9 +222,11 @@ export class OriginalImageGenerate {
try {
// 目前自动保存的信息,中文提示词,英文提示词,前缀,后缀
value = JSON.parse(value);
let batch = DEFINE_STRING.QUEUE_BATCH.AUTO_SAVE_DATA_JSON;
for (let i = 0; i < value.length; i++) {
const element = value[i];
// 将修改文件的的方法添加到修改文件队列中
this.global.fileQueue.enqueue(async () => {
try {
if (element.prompt_json) {
@@ -244,7 +245,7 @@ export class OriginalImageGenerate {
} catch (error) {
throw new Error(error);
}
});
}, `${batch}_${element.id}`, batch);
// 判断是不是有图片。判断图片是不是符合格式(有些格式是file:// 开头的, 以时间结尾(都要删除))
// 判断是不是有图片
+26 -3
View File
@@ -4,6 +4,8 @@ import { DEFINE_STRING } from "../../define/define_string";
import { define } from "../../define/define";
let fspromises = require("fs").promises;
import { gptDefine } from "../../define/gptDefine";
import { apiUrl } from "../../define/api/apiUrlDefine";
import { successMessage } from "../generalTools";
export class GPT {
constructor(global) {
@@ -255,6 +257,18 @@ export class GPT {
gpt_key = this.global.config.gpt_key,
gpt_model = this.global.config.gpt_model) {
try {
// 还有自定义的
let all_options = (await this.GetGPTBusinessOption("all", (value) => value.gpt_url)).data;
// 判断gpt_business 是不是一个http开头的
if (!gpt_url.includes("http")) {
// 获取对应Id的gpt_url
let index = all_options.findIndex(item => item.value == gpt_url && item.gpt_url);
if (index < 0) {
throw new Error("获取GPT的服务商配置失败");
}
gpt_url = all_options[index].gpt_url;
}
let data = {
"model": gpt_model,
@@ -268,7 +282,8 @@ export class GPT {
url: gpt_url,
headers: {
'Authorization': `Bearer ${gpt_key}`,
'Content-Type': 'application/json'
'Content-Type': 'application/json',
"Accept": "application/json"
},
data: JSON.stringify(data)
};
@@ -317,8 +332,16 @@ export class GPT {
* 获取GPT的服务商配置,默认的和自定义的
* @returns
*/
async GetGPTBusinessOption(value) {
return await gptDefine.getGptDataByTypeAndProperty(value, "gpt_options", []);
async GetGPTBusinessOption(value, callback = null) {
let res = await gptDefine.getGptDataByTypeAndProperty(value, "gpt_options", []);
if (res.code == 0) {
return res;
} else {
if (callback) {
callback(res.data)
}
return successMessage(res.data)
}
}
/**
+48
View File
@@ -0,0 +1,48 @@
import { errorMessage, successMessage } from "../generalTools";
import path from "path";
import { Tools } from "../tools";
export class Image {
constructor(global) {
this.global = global;
this.tools = new Tools();
}
// 将指定的文件夹复制到四个文件夹中
async OneSplitFour(value) {
try {
value = JSON.parse(value);
let count = value[1];
let data = value[0];
// 先创建输出文件
if (count <= 1) {
throw new Error("可选择的图片的数量必须大于1");
}
for (let i = 1; i < count; i++) {
let out_folder = path.join(this.global.config.project_path, `tmp/output_crop_0000${i + 1}`);
// 判断当前的文件夹是不是存在,存在删除
let isH = await this.tools.checkExists(out_folder);
if (isH) {
await this.tools.deleteFileOrDirectory(out_folder);
}
await this.tools.checkFolderExistsOrCreate(out_folder)
}
for (let i = 0; i < data.length; i++) {
const element = data[i];
let subImagePath = element.subImagePath;
for (let j = 1; j < count; j++) {
let out_file = path.join(this.global.config.project_path, `tmp/output_crop_0000${j + 1}/${element.name}`);
if (subImagePath[j] && subImagePath[j].startsWith("file")) {
subImagePath[j] = subImagePath[j].replace("file://", "");
subImagePath[j] = subImagePath[j].replace(/\?time=.*$/, '');
}
await this.tools.copyFileOrDirectory(subImagePath[j], out_file);
}
}
return successMessage("拆分成功");
} catch (error) {
return errorMessage(error.message);
}
}
}
+1 -1
View File
@@ -365,7 +365,7 @@ export class VideoGenerate {
// let task_list = JSON.parse(await fspromises.readFile(path.join(this.global.config.project_path,'scripts/task_')));
let scriptPath = path.join(define.scripts_path, 'Lai.exe');
// 执行生成图片的脚本
let script = `cd "${define.scripts_path}" && "${scriptPath}" -c "${project_config_path.replaceAll('\\', '/')}"`;
let script = `cd "${define.scripts_path}" && "${scriptPath}" -c "${project_config_path.replaceAll('\\', '/')}" "${this.global.gpu.type}"`;
const output = await execAsync(script, { maxBuffer: 1024 * 1024 * 10, encoding: 'utf-8' });
if (output.stderr != '') {
obj.status = "video_error";
-482
View File
@@ -1,482 +0,0 @@
const axios = require('axios');
const fetch = require("node-fetch");
export class DiscordAPI {
constructor(mj_setting) {
// https://discord.com/api/v9/channels/1208362852482809939/messages?limit=20
this.apiClient = axios.create({
baseURL: 'https://discord.com'
});
this.DiscordBaseUrl = 'https://discord.com';
this.ServerId = mj_setting.serviceID;
this.ChannelId = mj_setting.channelID;
this.userToken = mj_setting.token;
this.botId = mj_setting.select_robot?.botId;
this.commandId = mj_setting.select_robot?.commandId;
this.versionId = mj_setting.select_robot?.versionId;
this.versionName = mj_setting.select_robot?.versionName;
this.botName = mj_setting.select_robot?.botName;
}
// 提交任务
async imagine(data) {
// let req_data = {
// "token": this.userToken,
// "method": "post",
// "api_url": "/mj/submit/imagine",
// "data":data
// }
// const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
// await this.interactions(data.prompt);
return await this.interactions(data.prompt)
// return {
// code:1,
// result:'taskid_'+new Date().getTime()
// }
// return response.data;
}
async channelList() {
axios.get(`https://discord.com/api/v9/channels/${this.ChannelId}/messages?limit=20`, {
method: 'get',
headers: {
"Authorization": this.userToken
}
})
.then(response => {
// 请求成功处理
console.log(typeof response.data);
let eList = []
let flg = false;
let job_id = '';
let type = '';
if (response && response.data) {
try {
response.data.forEach(element => {
flg = false;
type = '';
if (element.attachments && element.attachments.length) {
const arr = element.attachments[0].filename.split("_");
job_id = arr[arr.length - 1].replace(".png", '');
if (element.components) {
element.components.forEach(e2 => {
e2.components.forEach(e3 => {
if (e3.label == 'U1') {
flg = true;
type = 'U1'
} else if (e3.label && e3.label.indexOf('Upscale') > -1) {
flg = true;
type = 'Upscale'
}
})
});
}
let t = eList.find((e) => {
return e.filename == element.attachments[0].filename;
})
if (!t) {
eList.push(
{
flg: flg, job_id: job_id, filename: element.attachments[0].filename,
url: element.attachments[0].url,
proxy_url: element.attachments[0].proxy_url,
type: type,
timestamp: element.timestamp
})
}
// console.log({flg:flg,job_id:job_id,filename:element.attachments[0].filename})
} else {
console.log({ flg: flg })
}
});
} catch (error) {
console.log('异常2', error)
}
// console.log(eList)
// 8e7406df-bf0c-4e3d-8e49-b2bb8e2c263d
// 5abedc71-ba80-4756-8ddc-489c927d3acd
}
}).catch(error => {
// 请求失败处理
console.error(error);
});
}
// 混合
async blend(data) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": "/mj/submit/blend",
"data": data
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
// 反推
async describe(data) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": "/mj/submit/describe",
"data": data
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
// 获取任务
async getTaskId(task_id) {
let req_data = {
"token": this.userToken,
"method": "get",
"api_url": `/mj/task/${task_id}/fetch`,
"data": {}
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
//获取seed
async imageSeed(task_id) {
let req_data = {
"token": this.userToken,
"method": "get",
"api_url": `/mj/task/${task_id}/image-seed`,
"data": {}
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
//账号创建
async account_create(data) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": '/mj/account/create',
"data": data
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data, { timeout: 20000 });
return response.data;
}
//账号创建
async account_fetch(cid) {
let req_data = {
"token": this.userToken,
"method": "get",
"api_url": `/mj/account/${cid}/fetch`,
"data": {}
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
//账号同步信息
async account_asyn_info(cid) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": `/mj/account/${cid}/sync-info`,
"data": {}
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data, { timeout: 20000 });
return response.data;
}
//账号删除信息
async account_del_info(cid) {
let req_data = {
"token": this.userToken,
"method": "delete",
"api_url": `/mj/account/${cid}/delete`,
"data": {}
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
//执行动作
async action(data) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": '/mj/submit/action',
"data": data
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
// 确认弹窗
async modal(data) {
let req_data = {
"token": this.userToken,
"method": "post",
"api_url": '/mj/submit/modal',
"data": data
}
const response = await this.apiClient.post('/api/v3/req_mj_api', req_data);
return response.data;
}
async interactions(prompt) {
// 直接自己调用
prompt = prompt.trim();
// prompt = "4k,8k,best quality, masterpiece, woman, divorced, leaving fast-paced city life, serene expression, walking away from cityscape, bustling streets, entering tranquil countryside, peaceful surroundings, rejuvenating atmosphere, , --niji 5 --ar 4:3"
var payload = {};
if (this.botName == 'niji') {
payload = {
"type": 2,
"application_id": this.botId,
"guild_id": this.ServerId,
"channel_id": this.ChannelId,
"session_id": this.userToken,
"data": {
"version": this.versionId,
"id": this.commandId,
"name": "imagine",
"type": 1,
"options": [
{
"type": 3,
"name": "prompt",
"value": prompt
}
],
"application_command": {
"id": this.commandId,
"type": 1,
"application_id": this.botId,
"version": this.versionId,
"name": "imagine",
"description": "Create images with Midjourney",
"options": [
{
"type": 3,
"name": "prompt",
"description": "The prompt to imagine",
"required": true,
"description_localized": "The prompt to imagine",
"name_localized": "prompt"
}
],
"integration_types": [
0
],
"global_popularity_rank": 1,
"description_localized": "Create images with Midjourney",
"name_localized": "imagine"
},
"attachments": [
]
},
// "nonce": "1210857131343872000",
"analytics_location": "slash_ui"
}
} else {
payload = {
"type": 2,
// "application_id":"1022952195194359889",//niji
"application_id": this.botId,
"guild_id": this.ServerId,
"channel_id": this.ChannelId,
"session_id": this.userToken,
"data": {
"version": this.versionId,
"id": this.commandId,
"name": "imagine", "type": 1,
"options":
[{
"type": 3,
"name": "prompt",
"value": prompt
}],
"application_command": {
"id": this.commandId,
"type": 1,
"application_id": this.botId,
"version": this.versionId,
"name": "imagine",
"description": "Create images with Niji journey",
"options": [{ "type": 3, "name": "prompt", "description": "The prompt to imagine", "required": true, "description_localized": "The prompt to imagine", "name_localized": "prompt" }],
"integration_types": [0], "global_popularity_rank": 1, "description_localized": "Create images with Niji journey", "name_localized": "imagine"
},
"attachments": []
},
"analytics_location": "slash_ui"
}
}
let response = {
status: 200,
data: {}
};
try {
const headers = {
"Content-Type": "application/json",
Authorization: this.userToken,
};
await fetch(`${this.DiscordBaseUrl}/api/v9/interactions`, {
method: "POST",
body: JSON.stringify(payload),
headers: headers,
}).then(res => res.json()).then(res => {
response.data = res;
}).catch(e => {
console.error("请求失败了,详细信息:" + JSON.stringify(e));
response = {
status: 500,
data: JSON.stringify(e)
};
});
console.log('response结果')
console.log(response)
// if (response.status == 204) {
// //成功
// }
if (response.status >= 400) {
console.error("api.error.config", {
payload: JSON.stringify(payload)
});
}
return {
code: response.status,
response: response
};
}
catch (error) {
console.error(error);
return 500;
}
return;
const client = new Midjourney.Midjourney({
ServerId: this.ServerId,
ChannelId: this.ChannelId,
SalaiToken: this.userToken,
Debug: true,
fetch: fetch,
Ws: true, //enable ws is required for remix mode (and custom zoom)
});
await client.init();
console.log('mjmj_begin2', prompt);
// const prompt =
// "Christmas dinner with spaghetti with family in a cozy house, we see interior details , simple blue&white illustration";
//imagine
const Imagine = await client.Imagine(
prompt,
(uri, progress) => {
client.Close();
console.log("loading", uri, "progress", progress);
return
}
);
console.log(Imagine);
if (!Imagine) {
console.log("no message");
console.log('mjmj_end2')
return;
}
console.log('mjmj_end')
client.Close();
return
}
/**
* 获取频道内的机器人
* @returns 返回机器人列表
*/
async getBotList() {
try {
const headers = {
'Host': 'discord.com',
'Connection': 'keep-alive',
'authorization': this.userToken,
}
await fetch('https://discord.com/api/v9/guilds/1182523906855284826/application-command-index', {
method: 'GET',
headers: headers,
})
.then(response => {
response.json()
}
)
.then(data => {
console.log(data)
})
.catch(error => {
console.error('Error:', error)
})
} catch (error) {
throw new Error(error);
}
}
async getMjMsgList() {
// const headers = {
// "Content-Type": "application/json",
// Authorization:this.userToken,
// };
let response = {
status: 200,
data: {}
};
// // `https://discord.com/api/v9/channels/${mj_channelId}/messages?limit=10
// await fetch(`${this.DiscordBaseUrl}/api/v9/channels/${this.ChannelId}/messages?limit=50`, {
// method: "GET",
// headers: headers,
// }).then(res => res.json()).then(res => {
// response.data=res;
// }).catch(e => {
// console.error("请求失败了,详细信息:" + JSON.stringify(e));
// response ={
// status:500,
// data:JSON.stringify(e)
// };
// });
// console.log('getMjMsgList_response结果')
// // console.log(response)
// return response;
axios.get(`https://discord.com/api/v9/channels/${this.ChannelId}/messages?limit=20`, {
method: 'get',
headers: {
"Authorization": this.userToken
}
}).then(res => {
response.data = res;
}).catch(error => {
// 请求失败处理
console.error(error);
});
}
}
+8 -4
View File
@@ -10,10 +10,11 @@ import { DEFINE_STRING } from "../../define/define_string";
* 对DisCord窗口进行操作的方法
*/
export class DiscordSimple {
constructor(win) {
constructor(win, mjSetting) {
this.win = win;
this.tools = new Tools();
this.script = define.discordScript;
this.mjSetting = mjSetting;
}
@@ -103,7 +104,7 @@ export class DiscordSimple {
async GetInputPosition() {
try {
await this.InitData();
await this.tools.delay(10000)
await this.tools.delay(this.mjSetting.space_time ? this.mjSetting.space_time * 1000 : 10000)
let result = await this.ExecuteScript(this.script, 'GetMessageInputPosition()');
this.x = result.mouseX;
this.y = result.mouseY;
@@ -641,6 +642,7 @@ export class DiscordSimple {
let currentCreateItem = global.mjGenerateQuene.getCurrentCreateItem();
console.log("LAITOOL 创建数据: ", value);
value.type = "created"
value.category = "browser_mj"
// 判断是不是是不是错误数据
if (value.error) {
@@ -652,7 +654,7 @@ export class DiscordSimple {
// 在将当前任务设置为空
global.mjGenerateQuene.setCurrentCreateItem(null);
// 开始下一个任务
global.mjGenerateQuene.startNextTask();
global.mjGenerateQuene.startNextTask(this.mjSetting.task_count ? this.mjSetting.task_count : 3);
}
@@ -702,7 +704,7 @@ export class DiscordSimple {
global.mjGenerateQuene.setCurrentCreateItem(null);
}
global.mjGenerateQuene.startNextTask();
global.mjGenerateQuene.startNextTask(this.mjSetting.task_count ? this.mjSetting.task_count : 3);
} catch (error) {
this.sendChangeMessage({
@@ -722,6 +724,7 @@ export class DiscordSimple {
// 接收到discord的消息
console.log("LAITOOL 更新数据: ", value);
value.type = "updated";
value.category = "browser_mj"
// 更新的时候,修改数据(判断是不是有进度)
let regex = /\((\d+)%\)/;
@@ -760,6 +763,7 @@ export class DiscordSimple {
}
console.log("LAITOOL 删除数据: ", value)
value.type = "delete"
value.category = "browser_mj"
this.sendChangeMessage(value)
// 这边可能要做判断(判断是不是开启下一个)
+34 -8
View File
@@ -1,9 +1,10 @@
let path = require('path');
import { Tools } from "../tools";
import { DiscordAPI } from "./discordApi";
import { DiscordAPI } from "../../api/discordApi";
import { MjSetting } from "../../define/setting/mjSetting";
import { DynamicSetting } from "../../define/setting/dynamicSetting";
import { AwesomeHelp } from "awesome-js"
import { errorMessage, successMessage } from "../generalTools";
export class MjSimple {
constructor(global) {
@@ -58,8 +59,6 @@ export class MjSimple {
value = JSON.parse(value);
let discordAPI = new DiscordAPI(value);
let res = await discordAPI.getBotList();
} catch (error) {
return {
code: 0,
@@ -102,7 +101,10 @@ export class MjSimple {
}
}
// 获取MJ所有的敏感词
/**
* 获取MJ所有的敏感词
* @returns
*/
async GetMJBadPrompt() {
try {
let default_bad_prompt = this.mjSetting.GetMJBadPrompt().data;
@@ -119,6 +121,34 @@ export class MjSimple {
}
}
/**
* 获取所有的MJ的图片比例
*/
async GetMJImageScale() {
try {
let default_image_scale = this.mjSetting.GetMJImageScale().data;
let data = await this.dynamicSetting.getDataByTypeAndProperty("all", 'mj', 'image_scale', default_image_scale, []);
return successMessage(data.data)
} catch (error) {
return errorMessage("获取图片比例失败, 错误信息如下:" + error.toString());
}
}
/**
* 获取所有的生图机器人模型
*/
async GetMJImageRobotModel() {
try {
let default_image_robot_model = this.mjSetting.GetMJImageRobotModel().data;
let data = await this.dynamicSetting.getDataByTypeAndProperty("all", 'mj', 'image_robot_model', default_image_robot_model, []);
return successMessage(data.data)
} catch (error) {
return errorMessage("获取生图机器人模型失败, 错误信息如下:" + error.toString());
}
}
/**
* 检查当前出入数据所有的敏感词
* @param {*} data
@@ -175,10 +205,6 @@ export class MjSimple {
}
}
}
console.log(res);
}
console.log(bad_prompt_ids)
+5 -8
View File
@@ -144,7 +144,7 @@ async function ReGenerateImageOne(window, value) {
}
prompt += value[1].prompt;
let model = value[1].model;
// 判断当前是不是有开修脸修手
@@ -626,12 +626,12 @@ async function SaveSDConfig(value) {
try {
let sd_config = JSON.parse((await fspromises.readFile(define.sd_setting, "utf-8")).toString());
global.config.webui_api_url = value.webui_api_url || value.webui_api_url == '' ? value.webui_api_url : global.config.webui_api_url;
sd_config.setting.webui_api_url = value.webui_api_url || value.webui_api_url == "" ? value.webui_api_url : sd_config.setting.webui_api_url;
sd_config.setting.type = value.type ? value.type : sd_config.setting.type;
sd_config.setting.batch_size = value.batch_size ? value.batch_size : sd_config.setting.batch_size;
sd_config.setting.style_weight = value.style_weight ? value.style_weight : sd_config.setting.style_weight;
sd_config.webui.prompt = value.prompt || value.prompt == "" ? value.prompt : sd_config.webui.prompt;
sd_config.webui.negative_prompt = value.negative_prompt || value.negative_prompt == "" ? value.negative_prompt : sd_config.webui.negative_prompt;
sd_config.webui.denoising_strength = value.denoising_strength || value.denoising_strength == "" ? value.denoising_strength : sd_config.webui.denoising_strength;
@@ -970,10 +970,7 @@ async function DeleteBadPrompt() {
* 打开购买 GPT 的网址
*/
async function openGptBuyUrl(value) {
// console.log(value)
if (value == "https://api.openai-hk.com/v1/chat/completions") {
OpenUrl('https://openai-hk.com/?i=10196')
}
OpenUrl(value)
}
/**
@@ -1055,7 +1052,7 @@ async function StartStoryboarding(value) {
global.newWindow[0].win.webContents.send(DEFINE_STRING.GET_FRAME_RETUN, { code: 1, data: "正在调用进程。请勿关闭程序" })
let cc = `${path.join(define.scripts_path, 'Lai.exe')}`;
let child = spawn(cc, ["-a", value.video_path, frame_path, input_path, value.sensitivity], { encoding: 'utf-8' });
let child = spawn(cc, ["-a", value.video_path, frame_path, input_path, value.sensitivity, global.gpu.type], { encoding: 'utf-8' });
child.on('error', console.error)
child.stdout.on('data', (data) => {
console.log(data.toString());
-2
View File
@@ -66,7 +66,6 @@ function checkStringValueDeletePrefix(value, prefix) {
}
/**
* 返回成功的消息,包含codedatamessage
* @param {*} code
* @param {*} data
* @param {*} message
* @returns
@@ -81,7 +80,6 @@ function successMessage(data, message = null) {
/**
* 返回失败的消息,包含codemessage
* @param {*} code
* @param {*} message
* @returns
*/
+29 -1
View File
@@ -1,6 +1,7 @@
import fspromises from "fs/promises";
import { v4 as uuidv4 } from 'uuid';
import { version } from '../../package.json'
import { graphics } from "systeminformation"
import { app, shell, BrowserWindow, ipcMain, dialog, nativeTheme } from 'electron'
@@ -29,6 +30,8 @@ import { SdIpc } from './IPCEvent/sdIpc.js'
import { DiscordIpc, RemoveDiscordIpc } from './IPCEvent/discordIpc.js'
import { MainIpc } from './IPCEvent/mainIpc.js'
import { GlobalIpc } from "./IPCEvent/globalIpc.js";
import { ImageIpc } from "./IPCEvent/imageIpc.js";
import { system } from "systeminformation";
let tools = new Tools();
let imageGenerate = new ImageGenerate(global);
@@ -226,6 +229,7 @@ MjIpc();
MainIpc(createWindow);
OriginalImageGenerateIpc();
GlobalIpc();
ImageIpc();
ipcMain.handle('dark-mode:toggle', (event, value) => {
@@ -313,7 +317,31 @@ ipcMain.handle(DEFINE_STRING.ADD_DRAFT, async (event, value) => {
})
// 获取当前版本
ipcMain.handle(DEFINE_STRING.GET_VERSION, async (event) => version);
ipcMain.handle(DEFINE_STRING.GET_VERSION, async (event) => {
// 获取当前电脑的显卡信息
let da = await graphics();
for (let i = 0; i < da.controllers.length; i++) {
// 获取第一个英伟达或者是AMD的显卡信息
const element = da.controllers[i];
if (element.vendor.startsWith("NVIDIA")) {
global.gpu = element;
global.gpu.type = "NVIDIA";
break;
} else if (element.vendor.startsWith("AMD") || element.vendor.startsWith("Advanced")) {
global.gpu = element;
global.gpu.type = "AMD";
break;
} else {
global.gpu = {
name: "OTHER"
};
global.gpu.type = "OTHER";
}
}
return version + " " + (global.gpu?.name ? global.gpu.name : "");
});
// 监听保存SD配置
ipcMain.handle(DEFINE_STRING.SAVE_SD_CONFIG, async (event, value) => await func.SaveSDConfig(value))
+13 -5
View File
@@ -19,6 +19,14 @@ export class AsyncQueue {
}
async enqueue(task, taskId, batchId, subBatchId = 'default') {
if (batchId && batchId != DEFINE_STRING.QUEUE_BATCH.IMAGE_SAVE_TO_OTHER_FOLDER) {
// 判断当前的任务是否已经存在,存在则不添加
let index = this.tasks.findIndex(item => item.taskId === taskId && item.batchId === batchId && item.subBatchId === subBatchId);
if (index != -1) {
throw new Error(`Task ${taskId} in batch ${batchId} already exists.`);
}
}
if (!this.batchCompletion[batchId]) {
this.batchCompletion[batchId] = { remaining: 0, subBatches: {}, callback: null, failedTasks: [] };
}
@@ -50,7 +58,7 @@ export class AsyncQueue {
this.taskDeadline = deadline;
}
async process() {
async process(task_count = 0) {
// 判断是不是有机器码检测的标识
if (!this.global.CheckMachineId) {
@@ -68,7 +76,7 @@ export class AsyncQueue {
return;
}
while (this.tasks.length > 0 && this.currentConcurrency < this.concurrencyLimit) {
while (this.tasks.length > 0 && (this.manualMode ? this.taskProgress.length < task_count : this.currentConcurrency < this.concurrencyLimit)) {
const { task, taskId, batchId, subBatchId } = this.tasks.shift();
this.currentConcurrency++;
task().then(() => {
@@ -244,14 +252,14 @@ export class AsyncQueue {
}
// 手动开启下一个任务
async startNextTask() {
async startNextTask(taskCount = 3) {
// 判断当前是不是有任务正在执行
if (this.currentCreateItem) {
return;
}
console.log("调用开始下一个任务", this.taskProgress)
if (this.manualMode && this.tasks.length > 0 && this.currentConcurrency < this.concurrencyLimit && this.taskProgress.length < 3) {
this.process();
if (this.manualMode && this.tasks.length > 0 && this.taskProgress.length < taskCount) {
this.process(taskCount);
}
}
+7 -26
View File
@@ -6,7 +6,7 @@ const { spawn, exec } = require('child_process');
const execAsync = util.promisify(exec);
import { define } from "../define/define";
import { get, has, set } from "lodash";
import axios from "axios";
import { basicApi } from "../api/apiBasic";
export class Tools {
constructor() { }
@@ -311,31 +311,12 @@ export class Tools {
* @returns
*/
async downloadFileUrl(url, filePath) {
return new Promise((resolve, reject) => {
const request = net.request({
method: 'GET',
url: url
});
request.on('response', (response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', async () => {
try {
await fspromises.writeFile(filePath, Buffer.concat(chunks));
console.log('File downloaded successfully');
resolve();
} catch (err) {
reject(err);
}
});
});
request.on('error', (error) => {
reject(error);
});
request.end();
});
try {
let data = await basicApi.downloadFileByURL(url);
await fspromises.writeFile(filePath, data.data);
} catch (error) {
throw error;
}
}
/**