You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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