Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

341 rinda
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.value:
  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. logger.debug(res)
  158. if res.status_code == 200:
  159. res = res.json()
  160. if res.get("code") == 200:
  161. task_id = res.get("data").get("taskId")
  162. logger.info(f"[MJ] image upscale processing, task_id={task_id}")
  163. content = f"🔎图片正在放大中,请耐心等待"
  164. reply = Reply(ReplyType.INFO, content)
  165. task = MJTask(id=task_id, status=Status.PENDING, user_id=user_id, task_type=TaskType.UPSCALE)
  166. # put to memory dict
  167. self.tasks[task.id] = task
  168. key = f"{TaskType.UPSCALE.name}_{img_id}_{index}"
  169. self.temp_dict[key] = True
  170. asyncio.run_coroutine_threadsafe(self.check_task(task, e_context), self.event_loop)
  171. return reply
  172. else:
  173. error_msg = ""
  174. if res.status_code == 461:
  175. error_msg = "请输入正确的图片ID"
  176. res_json = res.json()
  177. logger.error(f"[MJ] upscale error, msg={res_json.get('message')}, status_code={res.status_code}")
  178. reply = Reply(ReplyType.ERROR, error_msg or "图片生成失败,请稍后再试")
  179. return reply
  180. async def check_task(self, task: MJTask, e_context: EventContext):
  181. max_retry_times = 90
  182. while max_retry_times > 0:
  183. await asyncio.sleep(10)
  184. async with aiohttp.ClientSession() as session:
  185. url = f"{self.base_url}/tasks/{task.id}"
  186. try:
  187. async with session.get(url, headers=self.headers) as res:
  188. if res.status == 200:
  189. res_json = await res.json()
  190. logger.debug(f"[MJ] task check res, task_id={task.id}, status={res.status}, "
  191. f"data={res_json.get('data')}, thread={threading.current_thread().name}")
  192. if res_json.get("data") and res_json.get("data").get("status") == Status.FINISHED.name:
  193. # process success res
  194. if self.tasks.get(task.id):
  195. self.tasks[task.id].status = Status.FINISHED
  196. self._process_success_task(task, res_json.get("data"), e_context)
  197. return
  198. else:
  199. res_json = await res.json()
  200. logger.warn(f"[MJ] image check error, status_code={res.status}, res={res_json}")
  201. max_retry_times -= 20
  202. except Exception as e:
  203. max_retry_times -= 20
  204. logger.warn(e)
  205. max_retry_times -= 1
  206. logger.warn("[MJ] end from poll")
  207. if self.tasks.get(task.id):
  208. self.tasks[task.id].status = Status.EXPIRED
  209. def _process_success_task(self, task: MJTask, res: dict, e_context: EventContext):
  210. """
  211. 处理任务成功的结果
  212. :param task: MJ任务
  213. :param res: 请求结果
  214. :param e_context: 对话上下文
  215. """
  216. # channel send img
  217. task.status = Status.FINISHED
  218. task.img_id = res.get("imgId")
  219. task.img_url = res.get("imgUrl")
  220. logger.info(f"[MJ] task success, task_id={task.id}, img_id={task.img_id}, img_url={task.img_url}")
  221. # send img
  222. reply = Reply(ReplyType.IMAGE_URL, task.img_url)
  223. channel = e_context["channel"]
  224. channel._send(reply, e_context["context"])
  225. # send info
  226. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  227. text = ""
  228. if task.task_type == TaskType.GENERATE:
  229. text = f"🎨绘画完成!\nprompt: {task.raw_prompt}\n- - - - - - - - -\n图片ID: {task.img_id}"
  230. text += f"\n\n🔎可使用 {trigger_prefix}mju 命令放大指定图片\n"
  231. text += f"例如:\n{trigger_prefix}mju {task.img_id} 1"
  232. reply = Reply(ReplyType.INFO, text)
  233. channel._send(reply, e_context["context"])
  234. self._print_tasks()
  235. return
  236. def _check_rate_limit(self, user_id: str, e_context: EventContext) -> bool:
  237. """
  238. midjourney任务限流控制
  239. :param user_id: 用户id
  240. :param e_context: 对话上下文
  241. :return: 任务是否能够生成, True:可以生成, False: 被限流
  242. """
  243. tasks = self.find_tasks_by_user_id(user_id)
  244. task_count = len([t for t in tasks if t.status == Status.PENDING])
  245. if task_count >= self.config.get("max_tasks_per_user"):
  246. reply = Reply(ReplyType.INFO, "您的Midjourney作图任务数已达上限,请稍后再试")
  247. e_context["reply"] = reply
  248. e_context.action = EventAction.BREAK_PASS
  249. return False
  250. task_count = len([t for t in self.tasks.values() if t.status == Status.PENDING])
  251. if task_count >= self.config.get("max_tasks"):
  252. reply = Reply(ReplyType.INFO, "Midjourney作图任务数已达上限,请稍后再试")
  253. e_context["reply"] = reply
  254. e_context.action = EventAction.BREAK_PASS
  255. return False
  256. return True
  257. def _fetch_mode(self, prompt) -> str:
  258. mode = self.config.get("mode")
  259. if "--relax" in prompt or mode == TaskMode.RELAX.value:
  260. return TaskMode.RELAX.value
  261. return mode or TaskMode.RELAX.value
  262. def _run_loop(self, loop: asyncio.BaseEventLoop):
  263. """
  264. 运行事件循环,用于轮询任务的线程
  265. :param loop: 事件循环
  266. """
  267. loop.run_forever()
  268. loop.stop()
  269. def _print_tasks(self):
  270. for id in self.tasks:
  271. logger.debug(f"[MJ] current task: {self.tasks[id]}")
  272. def _set_reply_text(self, content: str, e_context: EventContext, level: ReplyType=ReplyType.ERROR):
  273. """
  274. 设置回复文本
  275. :param content: 回复内容
  276. :param e_context: 对话上下文
  277. :param level: 回复等级
  278. """
  279. reply = Reply(level, content)
  280. e_context["reply"] = reply
  281. e_context.action = EventAction.BREAK_PASS
  282. def get_help_text(self, verbose=False, **kwargs):
  283. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  284. help_text = "🎨利用Midjourney进行画图\n\n"
  285. if not verbose:
  286. return help_text
  287. 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\""
  288. return help_text
  289. def find_tasks_by_user_id(self, user_id) -> list[MJTask]:
  290. result = []
  291. with self.tasks_lock:
  292. now = time.time()
  293. for task in self.tasks.values():
  294. if task.status == Status.PENDING and now > task.expiry_time:
  295. task.status = Status.EXPIRED
  296. logger.info(f"[MJ] {task} expired")
  297. if task.user_id == user_id:
  298. result.append(task)
  299. return result
  300. def check_prefix(content, prefix_list):
  301. if not prefix_list:
  302. return None
  303. for prefix in prefix_list:
  304. if content.startswith(prefix):
  305. return prefix
  306. return None