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.

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