您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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