Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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