84 lines
3.8 KiB
TypeScript
84 lines
3.8 KiB
TypeScript
import { RequestHandler, Txt2ImgRequest } from "../type/request";
|
|
import { txt2imgAPIformatJSON, txt2imgAPIformatExtraData } from "../comfyJson/txt2img";
|
|
import axios from "axios";
|
|
import { selectNodeFromApiJSONbyID } from "../utils/editComfyJson";
|
|
import WebSocket from "ws";
|
|
import { readJSONFile, saveJSONFile } from "../utils/jsonReader";
|
|
const baseUrl = "http://47.108.92.176:20000";
|
|
const baseWsUrl = "ws://47.108.92.176:20000";
|
|
// const baseUrl = "http://localhost:8188";
|
|
// const baseWsUrl = "ws://localhost:8188";
|
|
axios.defaults.baseURL = baseUrl;
|
|
const Txt2ImgHandler: RequestHandler<Txt2ImgRequest, any> = async (ctx, next) => {
|
|
console.log(ctx.method);
|
|
ctx.set('Access-Control-Allow-Origin', '*')
|
|
ctx.set('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With')
|
|
ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
|
|
if (ctx.method == 'OPTIONS') {
|
|
ctx.body = 200;
|
|
return;
|
|
}
|
|
const requestBody = ctx.request.body;
|
|
const { prompt, loraDetail, loraModel } = requestBody;
|
|
const inputNode = selectNodeFromApiJSONbyID(txt2imgAPIformatJSON, "33");
|
|
let temp = "";
|
|
let preViewBlobs: any = [];
|
|
inputNode.inputs.string = prompt;
|
|
try {
|
|
ctx.body = {
|
|
data: await new Promise((resolve, reject) => {
|
|
const taskID = Math.random().toFixed(10);
|
|
const ws = new WebSocket(`${baseWsUrl}/ws?clientId=${taskID}`);
|
|
ws.onopen = () => {
|
|
try {
|
|
axios.post("/prompt", {
|
|
client_id: taskID,
|
|
prompt: txt2imgAPIformatJSON,
|
|
// extra_data: txt2imgAPIformatExtraData
|
|
});
|
|
console.log(`ok`);
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
|
|
ws.onmessage = (event) => {
|
|
if (typeof event.data === "string") {
|
|
const { type, data } = JSON.parse(event.data);
|
|
// if (type === "executed") {
|
|
// if (data.node === '94') {
|
|
// resolve(data.output.images[0].filename)
|
|
// }
|
|
// }
|
|
if (type === "executed") {
|
|
if (data.node === '21') {
|
|
temp = data.output.text[0];
|
|
}
|
|
if (data.node === '94') {
|
|
console.log(data.output);
|
|
const filePath = './data.json';
|
|
|
|
readJSONFile(filePath)
|
|
.then((data1: any) => {
|
|
console.log('读取的JSON数据:', data1);
|
|
// 修改对象
|
|
data1.push({ prompt: prompt, url: baseUrl + '/view?filename=' + data.output.images[0].filename, like: 0, index: data1.length+1 })
|
|
// 保存回JSON文件
|
|
saveJSONFile(filePath, data1);
|
|
})
|
|
resolve({ prompt: temp, url: baseUrl + '/view?filename=' + data.output.images[0].filename });
|
|
}
|
|
} else if (type === "executing") {
|
|
}
|
|
} else if (event.data instanceof Buffer) {
|
|
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
|
|
}
|
|
export default Txt2ImgHandler; |