選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

380 行
16KB

  1. from enum import Enum
  2. from config import conf
  3. from common.log import logger
  4. import requests
  5. import threading
  6. import time
  7. from bridge.reply import Reply, ReplyType
  8. import aiohttp
  9. import asyncio
  10. from bridge.context import ContextType
  11. from plugins import EventContext, EventAction
  12. class TaskType(Enum):
  13. GENERATE = "generate"
  14. UPSCALE = "upscale"
  15. VARIATION = "variation"
  16. RESET = "reset"
  17. class Status(Enum):
  18. PENDING = "pending"
  19. FINISHED = "finished"
  20. EXPIRED = "expired"
  21. ABORTED = "aborted"
  22. def __str__(self):
  23. return self.name
  24. class TaskMode(Enum):
  25. FAST = "fast"
  26. RELAX = "relax"
  27. class MJTask:
  28. def __init__(self, id, user_id: str, task_type: TaskType, raw_prompt=None, expires: int=60*30, status=Status.PENDING):
  29. self.id = id
  30. self.user_id = user_id
  31. self.task_type = task_type
  32. self.raw_prompt = raw_prompt
  33. self.send_func = None # send_func(img_url)
  34. self.expiry_time = time.time() + expires
  35. self.status = status
  36. self.img_url = None # url
  37. self.img_id = None
  38. def __str__(self):
  39. return f"id={self.id}, user_id={self.user_id}, task_type={self.task_type}, status={self.status}, img_id={self.img_id}"
  40. # midjourney bot
  41. class MJBot:
  42. def __init__(self, config):
  43. self.base_url = "https://api.link-ai.chat/v1/img/midjourney"
  44. self.headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  45. self.config = config
  46. self.tasks = {}
  47. self.temp_dict = {}
  48. self.tasks_lock = threading.Lock()
  49. self.event_loop = asyncio.new_event_loop()
  50. # threading.Thread(name="mj-check-thread", target=self._run_loop, args=(self.event_loop,)).start()
  51. def judge_mj_task_type(self, e_context: EventContext):
  52. """
  53. 判断MJ任务的类型
  54. :param e_context: 上下文
  55. :return: 任务类型枚举
  56. """
  57. if not self.config or not self.config.get("enabled"):
  58. return None
  59. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  60. context = e_context['context']
  61. if context.type == ContextType.TEXT:
  62. cmd_list = context.content.split(maxsplit=1)
  63. if cmd_list[0].lower() == f"{trigger_prefix}mj":
  64. return TaskType.GENERATE
  65. elif cmd_list[0].lower() == f"{trigger_prefix}mju":
  66. return TaskType.UPSCALE
  67. elif context.type == ContextType.IMAGE_CREATE and self.config.get("use_image_create_prefix"):
  68. return TaskType.GENERATE
  69. def process_mj_task(self, mj_type: TaskType, e_context: EventContext):
  70. """
  71. 处理mj任务
  72. :param mj_type: mj任务类型
  73. :param e_context: 对话上下文
  74. """
  75. context = e_context['context']
  76. session_id = context["session_id"]
  77. cmd = context.content.split(maxsplit=1)
  78. if len(cmd) == 1 and context.type == ContextType.TEXT:
  79. self._set_reply_text(self.get_help_text(verbose=True), e_context, level=ReplyType.INFO)
  80. return
  81. if not self._check_rate_limit(session_id, e_context):
  82. logger.warn("[MJ] midjourney task exceed rate limit")
  83. return
  84. if mj_type == TaskType.GENERATE:
  85. if context.type == ContextType.IMAGE_CREATE:
  86. raw_prompt = context.content
  87. else:
  88. # 图片生成
  89. raw_prompt = cmd[1]
  90. reply = self.generate(raw_prompt, session_id, e_context)
  91. e_context['reply'] = reply
  92. e_context.action = EventAction.BREAK_PASS
  93. return
  94. elif mj_type == TaskType.UPSCALE:
  95. # 图片放大
  96. clist = cmd[1].split()
  97. if len(clist) < 2:
  98. self._set_reply_text(f"{cmd[0]} 命令缺少参数", e_context)
  99. return
  100. img_id = clist[0]
  101. index = int(clist[1])
  102. if index < 1 or index > 4:
  103. self._set_reply_text(f"图片序号 {index} 错误,应在 1 至 4 之间", e_context)
  104. return
  105. key = f"{TaskType.UPSCALE.name}_{img_id}_{index}"
  106. if self.temp_dict.get(key):
  107. self._set_reply_text(f"第 {index} 张图片已经放大过了", e_context)
  108. return
  109. # 图片放大操作
  110. reply = self.upscale(session_id, img_id, index, e_context)
  111. e_context['reply'] = reply
  112. e_context.action = EventAction.BREAK_PASS
  113. return
  114. else:
  115. self._set_reply_text(f"暂不支持该命令", e_context)
  116. def generate(self, prompt: str, user_id: str, e_context: EventContext) -> Reply:
  117. """
  118. 图片生成
  119. :param prompt: 提示词
  120. :param user_id: 用户id
  121. :param e_context: 对话上下文
  122. :return: 任务ID
  123. """
  124. logger.info(f"[MJ] image generate, prompt={prompt}")
  125. mode = self._fetch_mode(prompt)
  126. body = {"prompt": prompt, "mode": mode, "auto_translate": self.config.get("auto_translate")}
  127. res = requests.post(url=self.base_url + "/generate", json=body, headers=self.headers, timeout=(5,15))
  128. if res.status_code == 200:
  129. res = res.json()
  130. logger.debug(f"[MJ] image generate, res={res}")
  131. if res.get("code") == 200:
  132. task_id = res.get("data").get("taskId")
  133. real_prompt = res.get("data").get("realPrompt")
  134. if mode == TaskMode.RELAX.value:
  135. time_str = "1~10分钟"
  136. else:
  137. time_str = "1分钟"
  138. content = f"🚀您的作品将在{time_str}左右完成,请耐心等待\n- - - - - - - - -\n"
  139. if real_prompt:
  140. content += f"初始prompt: {prompt}\n转换后prompt: {real_prompt}"
  141. else:
  142. content += f"prompt: {prompt}"
  143. reply = Reply(ReplyType.INFO, content)
  144. task = MJTask(id=task_id, status=Status.PENDING, raw_prompt=prompt, user_id=user_id, task_type=TaskType.GENERATE)
  145. # put to memory dict
  146. self.tasks[task.id] = task
  147. # asyncio.run_coroutine_threadsafe(self.check_task(task, e_context), self.event_loop)
  148. self._do_check_task(task, e_context)
  149. return reply
  150. else:
  151. res_json = res.json()
  152. logger.error(f"[MJ] generate error, msg={res_json.get('message')}, status_code={res.status_code}")
  153. reply = Reply(ReplyType.ERROR, "图片生成失败,请稍后再试")
  154. return reply
  155. def upscale(self, user_id: str, img_id: str, index: int, e_context: EventContext) -> Reply:
  156. logger.info(f"[MJ] image upscale, img_id={img_id}, index={index}")
  157. body = {"type": TaskType.UPSCALE.name, "imgId": img_id, "index": index}
  158. res = requests.post(url=self.base_url + "/operate", json=body, headers=self.headers, timeout=(5,15))
  159. logger.debug(res)
  160. if res.status_code == 200:
  161. res = res.json()
  162. if res.get("code") == 200:
  163. task_id = res.get("data").get("taskId")
  164. logger.info(f"[MJ] image upscale processing, task_id={task_id}")
  165. content = f"🔎图片正在放大中,请耐心等待"
  166. reply = Reply(ReplyType.INFO, content)
  167. task = MJTask(id=task_id, status=Status.PENDING, user_id=user_id, task_type=TaskType.UPSCALE)
  168. # put to memory dict
  169. self.tasks[task.id] = task
  170. key = f"{TaskType.UPSCALE.name}_{img_id}_{index}"
  171. self.temp_dict[key] = True
  172. # asyncio.run_coroutine_threadsafe(self.check_task(task, e_context), self.event_loop)
  173. self._do_check_task(task, e_context)
  174. return reply
  175. else:
  176. error_msg = ""
  177. if res.status_code == 461:
  178. error_msg = "请输入正确的图片ID"
  179. res_json = res.json()
  180. logger.error(f"[MJ] upscale error, msg={res_json.get('message')}, status_code={res.status_code}")
  181. reply = Reply(ReplyType.ERROR, error_msg or "图片生成失败,请稍后再试")
  182. return reply
  183. def check_task_sync(self, task: MJTask, e_context: EventContext):
  184. logger.debug(f"[MJ] start check task status, {task}")
  185. max_retry_times = 90
  186. while max_retry_times > 0:
  187. time.sleep(10)
  188. url = f"{self.base_url}/tasks/{task.id}"
  189. try:
  190. res = requests.get(url, headers=self.headers, timeout=5)
  191. if res.status_code == 200:
  192. res_json = res.json()
  193. logger.debug(f"[MJ] task check res sync, task_id={task.id}, status={res.status_code}, "
  194. f"data={res_json.get('data')}, thread={threading.current_thread().name}")
  195. if res_json.get("data") and res_json.get("data").get("status") == Status.FINISHED.name:
  196. # process success res
  197. if self.tasks.get(task.id):
  198. self.tasks[task.id].status = Status.FINISHED
  199. self._process_success_task(task, res_json.get("data"), e_context)
  200. return
  201. else:
  202. res_json = res.json()
  203. logger.warn(f"[MJ] image check error, status_code={res.status_code}, res={res_json}")
  204. max_retry_times -= 20
  205. except Exception as e:
  206. max_retry_times -= 20
  207. logger.warn(e)
  208. logger.warn("[MJ] end from poll")
  209. if self.tasks.get(task.id):
  210. self.tasks[task.id].status = Status.EXPIRED
  211. async def check_task_async(self, task: MJTask, e_context: EventContext):
  212. try:
  213. logger.debug(f"[MJ] start check task status, {task}")
  214. max_retry_times = 90
  215. while max_retry_times > 0:
  216. await asyncio.sleep(10)
  217. async with aiohttp.ClientSession() as session:
  218. url = f"{self.base_url}/tasks/{task.id}"
  219. try:
  220. async with session.get(url, headers=self.headers) as res:
  221. if res.status == 200:
  222. res_json = await res.json()
  223. logger.debug(f"[MJ] task check res, task_id={task.id}, status={res.status}, "
  224. f"data={res_json.get('data')}, thread={threading.current_thread().name}")
  225. if res_json.get("data") and res_json.get("data").get("status") == Status.FINISHED.name:
  226. # process success res
  227. if self.tasks.get(task.id):
  228. self.tasks[task.id].status = Status.FINISHED
  229. self._process_success_task(task, res_json.get("data"), e_context)
  230. return
  231. else:
  232. res_json = await res.json()
  233. logger.warn(f"[MJ] image check error, status_code={res.status}, res={res_json}")
  234. max_retry_times -= 20
  235. except Exception as e:
  236. max_retry_times -= 20
  237. logger.warn(e)
  238. max_retry_times -= 1
  239. logger.warn("[MJ] end from poll")
  240. if self.tasks.get(task.id):
  241. self.tasks[task.id].status = Status.EXPIRED
  242. except Exception as e:
  243. logger.error(e)
  244. def _do_check_task(self, task: MJTask, e_context: EventContext):
  245. threading.Thread(target=self.check_task_sync, args=(task, e_context)).start()
  246. def _process_success_task(self, task: MJTask, res: dict, e_context: EventContext):
  247. """
  248. 处理任务成功的结果
  249. :param task: MJ任务
  250. :param res: 请求结果
  251. :param e_context: 对话上下文
  252. """
  253. # channel send img
  254. task.status = Status.FINISHED
  255. task.img_id = res.get("imgId")
  256. task.img_url = res.get("imgUrl")
  257. logger.info(f"[MJ] task success, task_id={task.id}, img_id={task.img_id}, img_url={task.img_url}")
  258. # send img
  259. reply = Reply(ReplyType.IMAGE_URL, task.img_url)
  260. channel = e_context["channel"]
  261. channel._send(reply, e_context["context"])
  262. # send info
  263. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  264. text = ""
  265. if task.task_type == TaskType.GENERATE:
  266. text = f"🎨绘画完成!\nprompt: {task.raw_prompt}\n- - - - - - - - -\n图片ID: {task.img_id}"
  267. text += f"\n\n🔎可使用 {trigger_prefix}mju 命令放大指定图片\n"
  268. text += f"例如:\n{trigger_prefix}mju {task.img_id} 1"
  269. reply = Reply(ReplyType.INFO, text)
  270. channel._send(reply, e_context["context"])
  271. self._print_tasks()
  272. return
  273. def _check_rate_limit(self, user_id: str, e_context: EventContext) -> bool:
  274. """
  275. midjourney任务限流控制
  276. :param user_id: 用户id
  277. :param e_context: 对话上下文
  278. :return: 任务是否能够生成, True:可以生成, False: 被限流
  279. """
  280. tasks = self.find_tasks_by_user_id(user_id)
  281. task_count = len([t for t in tasks if t.status == Status.PENDING])
  282. if task_count >= self.config.get("max_tasks_per_user"):
  283. reply = Reply(ReplyType.INFO, "您的Midjourney作图任务数已达上限,请稍后再试")
  284. e_context["reply"] = reply
  285. e_context.action = EventAction.BREAK_PASS
  286. return False
  287. task_count = len([t for t in self.tasks.values() if t.status == Status.PENDING])
  288. if task_count >= self.config.get("max_tasks"):
  289. reply = Reply(ReplyType.INFO, "Midjourney作图任务数已达上限,请稍后再试")
  290. e_context["reply"] = reply
  291. e_context.action = EventAction.BREAK_PASS
  292. return False
  293. return True
  294. def _fetch_mode(self, prompt) -> str:
  295. mode = self.config.get("mode")
  296. if "--relax" in prompt or mode == TaskMode.RELAX.value:
  297. return TaskMode.RELAX.value
  298. return mode or TaskMode.RELAX.value
  299. def _run_loop(self, loop: asyncio.BaseEventLoop):
  300. """
  301. 运行事件循环,用于轮询任务的线程
  302. :param loop: 事件循环
  303. """
  304. loop.run_forever()
  305. loop.stop()
  306. def _print_tasks(self):
  307. for id in self.tasks:
  308. logger.debug(f"[MJ] current task: {self.tasks[id]}")
  309. def _set_reply_text(self, content: str, e_context: EventContext, level: ReplyType=ReplyType.ERROR):
  310. """
  311. 设置回复文本
  312. :param content: 回复内容
  313. :param e_context: 对话上下文
  314. :param level: 回复等级
  315. """
  316. reply = Reply(level, content)
  317. e_context["reply"] = reply
  318. e_context.action = EventAction.BREAK_PASS
  319. def get_help_text(self, verbose=False, **kwargs):
  320. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  321. help_text = "🎨利用Midjourney进行画图\n\n"
  322. if not verbose:
  323. return help_text
  324. help_text += f" - 生成: {trigger_prefix}mj 描述词1, 描述词2.. \n - 放大: {trigger_prefix}mju 图片ID 图片序号\n\n例如:\n\"{trigger_prefix}mj a little cat, white --ar 9:16\"\n\"{trigger_prefix}mju 1105592717188272288 2\""
  325. return help_text
  326. def find_tasks_by_user_id(self, user_id) -> list[MJTask]:
  327. result = []
  328. with self.tasks_lock:
  329. now = time.time()
  330. for task in self.tasks.values():
  331. if task.status == Status.PENDING and now > task.expiry_time:
  332. task.status = Status.EXPIRED
  333. logger.info(f"[MJ] {task} expired")
  334. if task.user_id == user_id:
  335. result.append(task)
  336. return result
  337. def check_prefix(content, prefix_list):
  338. if not prefix_list:
  339. return None
  340. for prefix in prefix_list:
  341. if content.startswith(prefix):
  342. return prefix
  343. return None