Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

337 Zeilen
15KB

  1. import requests
  2. import json
  3. import plugins
  4. from bridge.reply import Reply, ReplyType
  5. from bridge.context import ContextType
  6. from channel.chat_message import ChatMessage
  7. from plugins import *
  8. from common.log import logger
  9. from common.expired_dict import ExpiredDict
  10. import os
  11. import base64
  12. from pathlib import Path
  13. from PIL import Image
  14. import oss2
  15. from lib import itchat
  16. from lib.itchat.content import *
  17. # C:\Users\vsoni\source\repos\chatgpt-on-wechat\channel\wechat\wechat_channel.py
  18. @plugins.register(
  19. name="coze4upload",
  20. desire_priority=-1,
  21. desc="A plugin for upload",
  22. version="0.0.01",
  23. author="",
  24. )
  25. class coze4upload(Plugin):
  26. def __init__(self):
  27. super().__init__()
  28. try:
  29. curdir = os.path.dirname(__file__)
  30. config_path = os.path.join(curdir, "config.json")
  31. if os.path.exists(config_path):
  32. with open(config_path, "r", encoding="utf-8") as f:
  33. self.config = json.load(f)
  34. else:
  35. # 使用父类的方法来加载配置
  36. self.config = super().load_config()
  37. if not self.config:
  38. raise Exception("config.json not found")
  39. # 设置事件处理函数
  40. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  41. self.params_cache = ExpiredDict(300)
  42. # 从配置中提取所需的设置
  43. self.keys = self.config.get("keys", {})
  44. self.url_sum = self.config.get("url_sum", {})
  45. self.search_sum = self.config.get("search_sum", {})
  46. self.file_sum = self.config.get("file_sum", {})
  47. self.image_sum = self.config.get("image_sum", {})
  48. self.note = self.config.get("note", {})
  49. self.sum4all_key = self.keys.get("sum4all_key", "")
  50. self.search1api_key = self.keys.get("search1api_key", "")
  51. self.gemini_key = self.keys.get("gemini_key", "")
  52. self.bibigpt_key = self.keys.get("bibigpt_key", "")
  53. self.outputLanguage = self.keys.get("outputLanguage", "zh-CN")
  54. self.opensum_key = self.keys.get("opensum_key", "")
  55. self.open_ai_api_key = self.keys.get("open_ai_api_key", "")
  56. self.model = self.keys.get("model", "gpt-3.5-turbo")
  57. self.open_ai_api_base = self.keys.get("open_ai_api_base", "https://api.openai.com/v1")
  58. self.xunfei_app_id = self.keys.get("xunfei_app_id", "")
  59. self.xunfei_api_key = self.keys.get("xunfei_api_key", "")
  60. self.xunfei_api_secret = self.keys.get("xunfei_api_secret", "")
  61. self.perplexity_key = self.keys.get("perplexity_key", "")
  62. self.flomo_key = self.keys.get("flomo_key", "")
  63. # 之前提示
  64. self.previous_prompt=''
  65. self.file_sum_enabled = self.file_sum.get("enabled", False)
  66. self.file_sum_service = self.file_sum.get("service", "")
  67. self.max_file_size = self.file_sum.get("max_file_size", 15000)
  68. self.file_sum_group = self.file_sum.get("group", True)
  69. self.file_sum_qa_prefix = self.file_sum.get("qa_prefix", "问")
  70. self.file_sum_prompt = self.file_sum.get("prompt", "")
  71. self.image_sum_enabled = self.image_sum.get("enabled", False)
  72. self.image_sum_service = self.image_sum.get("service", "")
  73. self.image_sum_group = self.image_sum.get("group", True)
  74. self.image_sum_qa_prefix = self.image_sum.get("qa_prefix", "问")
  75. self.image_sum_prompt = self.image_sum.get("prompt", "")
  76. # 初始化成功日志
  77. logger.info("[file4upload] inited.")
  78. except Exception as e:
  79. # 初始化失败日志
  80. logger.warn(f"file4upload init failed: {e}")
  81. # def on_handle_context(self, e_context: EventContext):
  82. # context = e_context["context"]
  83. # # logger.info(f'{e_context.__dict__}')
  84. # # logger.info('---------------------------------')
  85. # # logger.info(f'{ e_context["context"]}')
  86. # logger.info('---------------------------------')
  87. # logger.info(f'{e_context["context"]["msg"]}')
  88. # if context.type not in [ContextType.TEXT, ContextType.SHARING,ContextType.FILE,ContextType.IMAGE]:
  89. # return
  90. # msg: ChatMessage = e_context["context"]["msg"]
  91. # user_id = msg.from_user_id
  92. # content = context.content
  93. # isgroup = e_context["context"].get("isgroup", False)
  94. # print(msg.actual_user_nickname)
  95. # itchat.send(f'@{msg.actual_user_nickname}立刻为你服务', toUserName=user_id)
  96. def on_handle_context(self, e_context: EventContext):
  97. context = e_context["context"]
  98. # logger.info(f'{e_context.__dict__}')
  99. # logger.info('---------------------------------')
  100. # logger.info(f'{ e_context["context"]}')
  101. # logger.info('---------------------------------')
  102. # logger.info(f'{e_context["context"]["msg"]}')
  103. if context.type not in [ContextType.TEXT, ContextType.SHARING,ContextType.FILE,ContextType.IMAGE]:
  104. return
  105. msg: ChatMessage = e_context["context"]["msg"]
  106. user_id = msg.from_user_id
  107. content = context.content
  108. isgroup = e_context["context"].get("isgroup", False)
  109. # itchat.send(f'@{msg.actual_user_nickname}立刻为你服务', toUserName=msg.actual_user_nickname)
  110. if isgroup and not self.file_sum_group:
  111. # 群聊中忽略处理文件
  112. logger.info("群聊消息,文件处理功能已禁用")
  113. return
  114. logger.info("on_handle_context: 处理上下文开始")
  115. context.get("msg").prepare()
  116. api_key='sk-5z2L4zy9T1w90j6e3T90ANZdyN2zLWClRwFnBzWgzdrG4onx'
  117. logger.info(f'当前缓存:self.params_cache:{self.params_cache}')
  118. if user_id not in self.params_cache:
  119. self.params_cache[user_id] = {}
  120. logger.info(f'初始化缓存:{self.params_cache}')
  121. if context.type == ContextType.TEXT and user_id in self.params_cache:
  122. self.params_cache[user_id]['previous_prompt']=msg.content
  123. # print(f'{msg.__dict__}')
  124. if context.type == ContextType.IMAGE:
  125. logger.info('处理图片')
  126. file_path = context.content
  127. logger.info(f"on_handle_context: 获取到图片路径 {file_path},{user_id in self.params_cache}")
  128. if user_id in self.params_cache:
  129. if 'previous_prompt' not in self.params_cache[user_id]:
  130. reply = Reply()
  131. reply.type = ReplyType.TEXT
  132. # reply.content = f"{remove_markdown(reply_content)}\n\n💬5min内输入{self.file_sum_qa_prefix}+问题,可继续追问"
  133. reply.content = f"您刚刚上传了一张图片,请问我有什么可以帮您的呢?"
  134. e_context["reply"] = reply
  135. e_context.action = EventAction.BREAK
  136. # else:
  137. print(f'准备抽取文字')
  138. file_content=extract_content_by_llm(file_path,api_key)
  139. if file_content is None:
  140. logger.info('不能抽取文字,使用图片oss请求LLM')
  141. access_key_id = 'LTAI5tRTG6pLhTpKACJYoPR5'
  142. access_key_secret = 'E7dMzeeMxq4VQvLg7Tq7uKf3XWpYfN'
  143. # OSS区域对应的Endpoint
  144. endpoint = 'http://oss-cn-shanghai.aliyuncs.com' # 根据你的区域选择
  145. # Bucket名称
  146. bucket_name = 'cow-agent'
  147. local_file_path=file_path
  148. oss_file_name=f'cow/{os.path.basename(file_path)}'
  149. logger.info(f'oss_file_name:{oss_file_name}\n local_file_path :{local_file_path}')
  150. file_content = upload_oss(access_key_id, access_key_secret, endpoint, bucket_name, local_file_path, oss_file_name)
  151. logger.info(f'写入图片缓存oss 地址{file_content}')
  152. self.params_cache[user_id]['last_content']=file_content
  153. # else:
  154. # logger.warn(f'还没有建立会话')
  155. logger.info('删除图片')
  156. os.remove(file_path)
  157. if context.type == ContextType.FILE:
  158. logger.info('处理图片')
  159. file_path = context.content
  160. logger.info(f"on_handle_context: 获取到文件路径 {file_path}")
  161. if user_id in self.params_cache:
  162. if 'previous_prompt' not in self.params_cache[user_id]:
  163. reply = Reply()
  164. reply.type = ReplyType.TEXT
  165. # reply.content = f"{remove_markdown(reply_content)}\n\n💬5min内输入{self.file_sum_qa_prefix}+问题,可继续追问"
  166. reply.content = f"您刚刚上传了一份文件,请问我有什么可以帮您的呢?"
  167. e_context["reply"] = reply
  168. e_context.action = EventAction.BREAK
  169. # else:
  170. print(f'准备抽取文字')
  171. file_content=extract_content_by_llm(file_path,api_key)
  172. if file_content is None:
  173. reply = Reply()
  174. reply.type = ReplyType.TEXT
  175. # reply.content = f"{remove_markdown(reply_content)}\n\n💬5min内输入{self.file_sum_qa_prefix}+问题,可继续追问"
  176. reply.content = f"不能处理这份文件"
  177. e_context["reply"] = reply
  178. e_context.action = EventAction.BREAK
  179. return
  180. else:
  181. self.params_cache[user_id]['last_content']=file_content
  182. logger.info('删除图片')
  183. os.remove(file_path)
  184. # logger.info('previous_prompt' in self.params_cache[user_id])
  185. # logger.info('last_content' in self.params_cache[user_id])
  186. is_previous_prompt='previous_prompt' in self.params_cache[user_id]
  187. is_last_content='last_content' in self.params_cache[user_id]
  188. logger.info(f"存在提示词 previous_prompt:{is_previous_prompt}")
  189. logger.info(f'存在内容 last_content:{is_last_content}' )
  190. if 'previous_prompt' in self.params_cache[user_id] and 'last_content' in self.params_cache[user_id]:
  191. #先回应
  192. logger.info('先回应')
  193. # reply2 = Reply()
  194. # reply2.type = ReplyType.TEXT
  195. # reply2.content = f"已经收到,立刻为你服务"
  196. # msg:ChatMessage = e_context['context']['msg']
  197. # e_context['reply'] = reply2
  198. # e_context.action = EventAction.BREAK # 事件结束
  199. # reply = Reply()
  200. # reply.type = ReplyType.TEXT
  201. # reply.content = f"已经收到,立刻为你服务"
  202. # e_context["reply"] = reply
  203. # e_context.action = EventAction.BREAK
  204. receiver=user_id
  205. print(receiver)
  206. # itchat_content= '' if e_context['context']['isgroup'] else '[小蕴]'+"已经收到,立刻为你服务"
  207. # if e_context['context']['isgroup']:
  208. # itchat_content =f'@{msg.actual_user_nickname}已经收到,立刻为你服务'
  209. # else:
  210. # itchat_content = '[小蕴]'+"已经收到,立刻为你服务"
  211. itchat_content= f'@{msg.actual_user_nickname}' if e_context['context']['isgroup'] else '[小蕴]'
  212. itchat_content+="已经收到,立刻为您服务"
  213. itchat.send(itchat_content, toUserName=receiver)
  214. e_context.action = EventAction.BREAK
  215. if 'previous_prompt' in self.params_cache[user_id] and 'last_content' in self.params_cache[user_id] :
  216. e_context["context"].type = ContextType.TEXT
  217. e_context["context"].content = self.params_cache[user_id]['last_content']+'\n\t'+self.params_cache[user_id]['previous_prompt']
  218. logger.info(f'conze4upload 插件处理上传文件或图片')
  219. e_context.action = EventAction.CONTINUE
  220. # 清空清空缓存
  221. self.params_cache.clear()
  222. logger.info(f'清空缓存后:{self.params_cache}')
  223. ## e_context.action = EventAction.BREAK
  224. def remove_markdown(text):
  225. # 替换Markdown的粗体标记
  226. text = text.replace("**", "")
  227. # 替换Markdown的标题标记
  228. text = text.replace("### ", "").replace("## ", "").replace("# ", "")
  229. return text
  230. def extract_content_by_llm(file_path: str, api_key: str) -> str:
  231. logger.info(f'大模型开始抽取文字')
  232. try:
  233. headers = {
  234. 'Authorization': f'Bearer {api_key}'
  235. }
  236. data = {
  237. 'purpose': 'file-extract',
  238. }
  239. file_name=os.path.basename(file_path)
  240. files = {
  241. 'file': (file_name, open(Path(file_path), 'rb')),
  242. }
  243. # print(files)
  244. api_url='https://api.moonshot.cn/v1/files'
  245. response = requests.post(api_url, headers=headers, files=files, data=data)
  246. response_data = response.json()
  247. file_id = response_data.get('id')
  248. response=requests.get(url=f"https://api.moonshot.cn/v1/files/{file_id}/content", headers=headers)
  249. print(response.text)
  250. response_data = response.json()
  251. content = response_data.get('content')
  252. return content
  253. except requests.exceptions.RequestException as e:
  254. logger.error(f"Error calling LLM API: {e}")
  255. return None
  256. def upload_oss(access_key_id, access_key_secret, endpoint, bucket_name, local_file_path, oss_file_name, expiration_days=7):
  257. """
  258. 上传文件到阿里云OSS并设置生命周期规则,同时返回文件的公共访问地址。
  259. :param access_key_id: 阿里云AccessKey ID
  260. :param access_key_secret: 阿里云AccessKey Secret
  261. :param endpoint: OSS区域对应的Endpoint
  262. :param bucket_name: OSS中的Bucket名称
  263. :param local_file_path: 本地文件路径
  264. :param oss_file_name: OSS中的文件存储路径
  265. :param expiration_days: 文件保存天数,默认7天后删除
  266. :return: 文件的公共访问地址
  267. """
  268. # 创建Bucket实例
  269. auth = oss2.Auth(access_key_id, access_key_secret)
  270. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  271. ### 1. 设置生命周期规则 ###
  272. rule_id = f'delete_after_{expiration_days}_days' # 规则ID
  273. prefix = oss_file_name.split('/')[0] + '/' # 设置规则应用的前缀为文件所在目录
  274. # 定义生命周期规则
  275. rule = oss2.models.LifecycleRule(rule_id, prefix, status=oss2.models.LifecycleRule.ENABLED,
  276. expiration=oss2.models.LifecycleExpiration(days=expiration_days))
  277. # 设置Bucket的生命周期
  278. lifecycle = oss2.models.BucketLifecycle([rule])
  279. bucket.put_bucket_lifecycle(lifecycle)
  280. print(f"已设置生命周期规则:文件将在{expiration_days}天后自动删除")
  281. ### 2. 上传文件到OSS ###
  282. bucket.put_object_from_file(oss_file_name, local_file_path)
  283. ### 3. 构建公共访问URL ###
  284. file_url = f"http://{bucket_name}.{endpoint.replace('http://', '')}/{oss_file_name}"
  285. print(f"文件上传成功,公共访问地址:{file_url}")
  286. return file_url