Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

428 lines
18KB

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