Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

340 linhas
14KB

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