2023-09-07 20:43:40 +00:00
|
|
|
import { InputFile, InputMediaBuilder, log, types } from "./deps.ts";
|
2023-09-06 00:53:34 +00:00
|
|
|
import { bot } from "./bot.ts";
|
|
|
|
import { getGlobalSession } from "./session.ts";
|
2023-09-04 16:55:48 +00:00
|
|
|
import { formatOrdinal } from "./intl.ts";
|
2023-09-07 20:43:40 +00:00
|
|
|
import { SdTxt2ImgRequest, SdTxt2ImgResponse, txt2img } from "./sd.ts";
|
2023-09-04 16:55:48 +00:00
|
|
|
import { extFromMimeType, mimeTypeFromBase64 } from "./mimeType.ts";
|
2023-09-07 20:43:40 +00:00
|
|
|
import { Model, Schema, Store } from "./store.ts";
|
|
|
|
|
|
|
|
const logger = () => log.getLogger();
|
2023-09-04 16:55:48 +00:00
|
|
|
|
|
|
|
interface Job {
|
2023-09-07 20:43:40 +00:00
|
|
|
params: Partial<SdTxt2ImgRequest>;
|
2023-09-06 17:51:52 +00:00
|
|
|
user: types.User;
|
|
|
|
chat: types.Chat.PrivateChat | types.Chat.GroupChat | types.Chat.SupergroupChat;
|
|
|
|
requestMessage: types.Message & types.Message.TextMessage;
|
|
|
|
statusMessage?: types.Message & types.Message.TextMessage;
|
2023-09-07 20:43:40 +00:00
|
|
|
status:
|
|
|
|
| { type: "idle" }
|
|
|
|
| { type: "processing"; progress: number; updatedDate: Date };
|
2023-09-06 17:51:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const db = await Deno.openKv("./app.db");
|
|
|
|
|
2023-09-07 20:43:40 +00:00
|
|
|
const jobStore = new Store(db, "job", {
|
|
|
|
schema: new Schema<Job>(),
|
|
|
|
indices: ["status.type", "user.id", "chat.id"],
|
|
|
|
});
|
|
|
|
|
|
|
|
jobStore.getBy("user.id", 123).then(() => {});
|
2023-09-06 17:51:52 +00:00
|
|
|
|
|
|
|
export async function pushJob(job: Job) {
|
|
|
|
await jobStore.create(job);
|
|
|
|
}
|
|
|
|
|
|
|
|
async function takeJob(): Promise<Model<Job> | null> {
|
2023-09-07 20:43:40 +00:00
|
|
|
const jobs = await jobStore.getAll();
|
2023-09-06 17:51:52 +00:00
|
|
|
const job = jobs.find((job) => job.value.status.type === "idle");
|
|
|
|
if (!job) return null;
|
|
|
|
await job.update({ status: { type: "processing", progress: 0, updatedDate: new Date() } });
|
|
|
|
return job;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function getAllJobs(): Promise<Array<Job>> {
|
2023-09-07 20:43:40 +00:00
|
|
|
return await jobStore.getAll().then((jobs) => jobs.map((job) => job.value));
|
2023-09-04 16:55:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function processQueue() {
|
|
|
|
while (true) {
|
2023-09-07 20:43:40 +00:00
|
|
|
const job = await takeJob().catch((err) =>
|
|
|
|
void logger().warning("failed getting job", err.message)
|
|
|
|
);
|
2023-09-04 16:55:48 +00:00
|
|
|
if (!job) {
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
|
|
continue;
|
|
|
|
}
|
2023-09-06 17:51:52 +00:00
|
|
|
let place = 0;
|
2023-09-07 20:43:40 +00:00
|
|
|
for (const job of await jobStore.getAll().catch(() => [])) {
|
2023-09-06 17:51:52 +00:00
|
|
|
if (job.value.status.type === "idle") place += 1;
|
|
|
|
if (place === 0) continue;
|
|
|
|
const statusMessageText = `You are ${formatOrdinal(place)} in queue.`;
|
|
|
|
if (!job.value.statusMessage) {
|
|
|
|
await bot.api.sendMessage(job.value.chat.id, statusMessageText, {
|
|
|
|
reply_to_message_id: job.value.requestMessage.message_id,
|
|
|
|
}).catch(() => undefined)
|
2023-09-07 20:43:40 +00:00
|
|
|
.then((message) => job.update({ statusMessage: message })).catch(() => undefined);
|
2023-09-06 17:51:52 +00:00
|
|
|
} else {
|
|
|
|
await bot.api.editMessageText(
|
|
|
|
job.value.chat.id,
|
|
|
|
job.value.statusMessage.message_id,
|
|
|
|
statusMessageText,
|
2023-09-04 16:55:48 +00:00
|
|
|
)
|
2023-09-06 17:51:52 +00:00
|
|
|
.catch(() => undefined);
|
|
|
|
}
|
2023-09-04 16:55:48 +00:00
|
|
|
}
|
|
|
|
try {
|
2023-09-06 17:51:52 +00:00
|
|
|
if (job.value.statusMessage) {
|
|
|
|
await bot.api
|
|
|
|
.deleteMessage(job.value.chat.id, job.value.statusMessage?.message_id)
|
|
|
|
.catch(() => undefined)
|
|
|
|
.then(() => job.update({ statusMessage: undefined }));
|
|
|
|
}
|
|
|
|
await bot.api.sendMessage(
|
|
|
|
job.value.chat.id,
|
2023-09-04 16:55:48 +00:00
|
|
|
"Generating your prompt now...",
|
2023-09-06 17:51:52 +00:00
|
|
|
{ reply_to_message_id: job.value.requestMessage.message_id },
|
|
|
|
).then((message) => job.update({ statusMessage: message }));
|
2023-09-05 18:26:15 +00:00
|
|
|
const config = await getGlobalSession();
|
2023-09-04 16:55:48 +00:00
|
|
|
const response = await txt2img(
|
|
|
|
config.sdApiUrl,
|
2023-09-06 17:51:52 +00:00
|
|
|
{ ...config.defaultParams, ...job.value.params },
|
|
|
|
(progress) => {
|
|
|
|
job.update({
|
|
|
|
status: { type: "processing", progress: progress.progress, updatedDate: new Date() },
|
|
|
|
});
|
|
|
|
if (job.value.statusMessage) {
|
|
|
|
bot.api
|
|
|
|
.editMessageText(
|
|
|
|
job.value.chat.id,
|
|
|
|
job.value.statusMessage.message_id,
|
|
|
|
`Generating your prompt now... ${
|
|
|
|
Math.round(
|
|
|
|
progress.progress * 100,
|
|
|
|
)
|
|
|
|
}%`,
|
|
|
|
)
|
|
|
|
.catch(() => undefined);
|
|
|
|
}
|
|
|
|
},
|
2023-09-04 16:55:48 +00:00
|
|
|
);
|
2023-09-07 20:43:40 +00:00
|
|
|
const jobCount = (await jobStore.getAll()).filter((job) =>
|
|
|
|
job.value.status.type !== "processing"
|
|
|
|
).length;
|
|
|
|
logger().info("Job finished", job.value.user.first_name, job.value.chat.type, { jobCount });
|
2023-09-06 17:51:52 +00:00
|
|
|
if (job.value.statusMessage) {
|
|
|
|
await bot.api.editMessageText(
|
|
|
|
job.value.chat.id,
|
|
|
|
job.value.statusMessage.message_id,
|
|
|
|
`Uploading your images...`,
|
|
|
|
).catch(() => undefined);
|
|
|
|
}
|
2023-09-04 16:55:48 +00:00
|
|
|
const inputFiles = await Promise.all(
|
|
|
|
response.images.map(async (imageBase64, idx) => {
|
|
|
|
const mimeType = mimeTypeFromBase64(imageBase64);
|
2023-09-06 17:51:52 +00:00
|
|
|
const imageBlob = await fetch(`data:${mimeType};base64,${imageBase64}`)
|
|
|
|
.then((resp) => resp.blob());
|
2023-09-04 16:55:48 +00:00
|
|
|
return InputMediaBuilder.photo(
|
2023-09-06 17:51:52 +00:00
|
|
|
new InputFile(imageBlob, `image_${idx}.${extFromMimeType(mimeType)}`),
|
2023-09-04 16:55:48 +00:00
|
|
|
);
|
|
|
|
}),
|
|
|
|
);
|
2023-09-06 17:51:52 +00:00
|
|
|
if (job.value.statusMessage) {
|
|
|
|
await bot.api
|
|
|
|
.deleteMessage(job.value.chat.id, job.value.statusMessage.message_id)
|
|
|
|
.catch(() => undefined).then(() => job.update({ statusMessage: undefined }));
|
|
|
|
}
|
|
|
|
await bot.api.sendMediaGroup(job.value.chat.id, inputFiles, {
|
|
|
|
reply_to_message_id: job.value.requestMessage.message_id,
|
2023-09-04 16:55:48 +00:00
|
|
|
});
|
2023-09-06 17:51:52 +00:00
|
|
|
await job.delete();
|
2023-09-04 16:55:48 +00:00
|
|
|
} catch (err) {
|
2023-09-07 20:43:40 +00:00
|
|
|
logger().error("Job failed", job.value.user.first_name, job.value.chat.type, err);
|
2023-09-06 17:51:52 +00:00
|
|
|
const errorMessage = await bot.api
|
|
|
|
.sendMessage(job.value.chat.id, err.toString(), {
|
|
|
|
reply_to_message_id: job.value.requestMessage.message_id,
|
2023-09-04 16:55:48 +00:00
|
|
|
})
|
2023-09-06 17:51:52 +00:00
|
|
|
.catch(() => undefined);
|
|
|
|
if (errorMessage) {
|
|
|
|
if (job.value.statusMessage) {
|
|
|
|
await bot.api
|
|
|
|
.deleteMessage(job.value.chat.id, job.value.statusMessage.message_id)
|
2023-09-07 20:43:40 +00:00
|
|
|
.then(() => job.update({ statusMessage: undefined }))
|
|
|
|
.catch(() => void logger().warning("failed deleting status message", err.message));
|
2023-09-06 17:51:52 +00:00
|
|
|
}
|
2023-09-07 20:43:40 +00:00
|
|
|
await job.update({ status: { type: "idle" } }).catch((err) =>
|
|
|
|
void logger().warning("failed returning job", err.message)
|
|
|
|
);
|
2023-09-06 17:51:52 +00:00
|
|
|
} else {
|
2023-09-07 20:43:40 +00:00
|
|
|
await job.delete().catch((err) =>
|
|
|
|
void logger().warning("failed deleting job", err.message)
|
|
|
|
);
|
2023-09-06 17:51:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function returnHangedJobs() {
|
|
|
|
while (true) {
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 5000));
|
2023-09-07 20:43:40 +00:00
|
|
|
const jobs = await jobStore.getAll().catch(() => []);
|
2023-09-06 17:51:52 +00:00
|
|
|
for (const job of jobs) {
|
2023-09-07 20:43:40 +00:00
|
|
|
if (job.value.status.type !== "processing") continue;
|
2023-09-06 17:51:52 +00:00
|
|
|
// if job wasn't updated for 1 minute, return it to the queue
|
|
|
|
if (job.value.status.updatedDate.getTime() < Date.now() - 60 * 1000) {
|
2023-09-07 20:43:40 +00:00
|
|
|
logger().warning("Hanged job returned", job.value.user.first_name, job.value.chat.type);
|
|
|
|
await job.update({ status: { type: "idle" } }).catch((err) =>
|
|
|
|
void logger().warning("failed returning job", err.message)
|
2023-09-06 17:51:52 +00:00
|
|
|
);
|
|
|
|
}
|
2023-09-04 16:55:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|