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.

пре 3 месеци
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import requests
  2. import json
  3. import re
  4. import plugins
  5. from bridge.reply import Reply, ReplyType
  6. from bridge.context import ContextType
  7. from channel.chat_message import ChatMessage
  8. from plugins import *
  9. from common.log import logger
  10. from common.expired_dict import ExpiredDict
  11. import os
  12. from docx import Document
  13. import markdown
  14. import fitz
  15. from openpyxl import load_workbook
  16. import csv
  17. from bs4 import BeautifulSoup
  18. from pptx import Presentation
  19. from PIL import Image
  20. import base64
  21. import html
  22. EXTENSION_TO_TYPE = {
  23. 'pdf': 'pdf',
  24. 'doc': 'docx', 'docx': 'docx',
  25. 'md': 'md',
  26. 'txt': 'txt',
  27. 'xls': 'excel', 'xlsx': 'excel',
  28. 'csv': 'csv',
  29. 'html': 'html', 'htm': 'html',
  30. 'ppt': 'ppt', 'pptx': 'ppt'
  31. }
  32. @plugins.register(
  33. name="file4upload",
  34. desire_priority=-1,
  35. desc="A plugin for upload",
  36. version="0.0.01",
  37. author="",
  38. )
  39. class file4upload(Plugin):
  40. def __init__(self):
  41. super().__init__()
  42. try:
  43. curdir = os.path.dirname(__file__)
  44. config_path = os.path.join(curdir, "config.json")
  45. if os.path.exists(config_path):
  46. with open(config_path, "r", encoding="utf-8") as f:
  47. self.config = json.load(f)
  48. else:
  49. # 使用父类的方法来加载配置
  50. self.config = super().load_config()
  51. if not self.config:
  52. raise Exception("config.json not found")
  53. # 设置事件处理函数
  54. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  55. self.params_cache = ExpiredDict(300)
  56. # 从配置中提取所需的设置
  57. self.keys = self.config.get("keys", {})
  58. self.url_sum = self.config.get("url_sum", {})
  59. self.search_sum = self.config.get("search_sum", {})
  60. self.file_sum = self.config.get("file_sum", {})
  61. self.image_sum = self.config.get("image_sum", {})
  62. self.note = self.config.get("note", {})
  63. self.sum4all_key = self.keys.get("sum4all_key", "")
  64. self.search1api_key = self.keys.get("search1api_key", "")
  65. self.gemini_key = self.keys.get("gemini_key", "")
  66. self.bibigpt_key = self.keys.get("bibigpt_key", "")
  67. self.outputLanguage = self.keys.get("outputLanguage", "zh-CN")
  68. self.opensum_key = self.keys.get("opensum_key", "")
  69. self.open_ai_api_key = self.keys.get("open_ai_api_key", "")
  70. self.model = self.keys.get("model", "gpt-3.5-turbo")
  71. self.open_ai_api_base = self.keys.get("open_ai_api_base", "https://api.openai.com/v1")
  72. self.xunfei_app_id = self.keys.get("xunfei_app_id", "")
  73. self.xunfei_api_key = self.keys.get("xunfei_api_key", "")
  74. self.xunfei_api_secret = self.keys.get("xunfei_api_secret", "")
  75. self.perplexity_key = self.keys.get("perplexity_key", "")
  76. self.flomo_key = self.keys.get("flomo_key", "")
  77. # 之前提示
  78. self.previous_prompt=''
  79. self.file_sum_enabled = self.file_sum.get("enabled", False)
  80. self.file_sum_service = self.file_sum.get("service", "")
  81. self.max_file_size = self.file_sum.get("max_file_size", 15000)
  82. self.file_sum_group = self.file_sum.get("group", True)
  83. self.file_sum_qa_prefix = self.file_sum.get("qa_prefix", "问")
  84. self.file_sum_prompt = self.file_sum.get("prompt", "")
  85. self.image_sum_enabled = self.image_sum.get("enabled", False)
  86. self.image_sum_service = self.image_sum.get("service", "")
  87. self.image_sum_group = self.image_sum.get("group", True)
  88. self.image_sum_qa_prefix = self.image_sum.get("qa_prefix", "问")
  89. self.image_sum_prompt = self.image_sum.get("prompt", "")
  90. # 初始化成功日志
  91. logger.info("[file4upload] inited.")
  92. except Exception as e:
  93. # 初始化失败日志
  94. logger.warn(f"file4upload init failed: {e}")
  95. def on_handle_context(self, e_context: EventContext):
  96. context = e_context["context"]
  97. if context.type not in [ContextType.TEXT, ContextType.SHARING,ContextType.FILE,ContextType.IMAGE]:
  98. return
  99. msg: ChatMessage = e_context["context"]["msg"]
  100. user_id = msg.from_user_id
  101. content = context.content
  102. isgroup = e_context["context"].get("isgroup", False)
  103. logger.info(f"user_id:{user_id},content:{content},isgroup:{isgroup}")
  104. logger.info(f'上下文参数缓存键字典:{self.params_cache.keys}')
  105. logger.info(f'user_id in self.params_cache: {user_id in self.params_cache}')
  106. # logger.info(f'last_file_content in self.params_cache[user_id] :{'last_file_content' in self.params_cache[user_id]}')
  107. # 上次提示
  108. if context.type == ContextType.TEXT:
  109. self.previous_prompt=msg.content
  110. if context.type == ContextType.FILE:
  111. logger.info('开始首次处理文件')
  112. # logger.info(f'{self.params_cache}')
  113. # # content = "The World"
  114. # logger.info(f'file4upload 插件作画')
  115. # e_context.action = EventAction.CONTINUE # 事件继续,交付给下个插件或默认逻辑
  116. # e_context["context"].type = ContextType.TEXT
  117. # e_context["context"].content = "The World"
  118. # logger.info(f'file4upload 插件处理')
  119. # e_context.action = EventAction.CONTINUE # 事件继续,交付给下个插件或默认逻辑
  120. if isgroup and not self.file_sum_group:
  121. # 群聊中忽略处理文件
  122. logger.info("群聊消息,文件处理功能已禁用")
  123. return
  124. logger.info("on_handle_context: 处理上下文开始")
  125. context.get("msg").prepare()
  126. file_path = context.content
  127. logger.info(f"on_handle_context: 获取到文件路径 {file_path}")
  128. # 检查是否应该进行文件总结
  129. if self.file_sum_enabled:
  130. # 更新params_cache中的last_file_content
  131. self.params_cache[user_id] = {}
  132. file_content = self.extract_content(file_path)
  133. if file_content is None:
  134. logger.info("文件内容无法提取,跳过处理")
  135. else:
  136. file_content=f'Use the following context as your learned knowledge, inside <context></context> XML tags.\n\t<context>{file_content}</context>\n\t\n\tWhen answer to user:\n\t- If you don\'t know, just say that you don\'t know.\n\t- If you don\'t know when you are not sure, ask for clarification.\n\tAvoid mentioning that you obtained the information from the context.\n\tAnd answer according to the language of the user\'s question.\n\t\t\t\n\tGiven the context information, answer the query.\n\tQuery:'
  137. self.params_cache[user_id]['last_file_content'] = file_content
  138. logger.info(f'写入文件内容缓存')
  139. # logger.info('Updated last_file_content in params_cache for user.')
  140. # # self.handle_file(file_content, e_context)
  141. # e_context["context"].type = ContextType.TEXT
  142. # e_context["context"].content = file_content+'\n\t请总结分析这份数据文件。文件内容是HRV分析报告,请分析这个用户的心梗、脑梗的风险等级(如无风险、低风险、中风险、高风险),并提供健康建议'
  143. # logger.info(f'file4upload 插件处理上传文件')
  144. e_context.action = EventAction.CONTINUE # 事件继续,交付给下个插件或默认逻辑
  145. else:
  146. logger.info("文件总结功能已禁用,不对文件内容进行处理")
  147. elif context.type == ContextType.IMAGE:
  148. logger.info('开始首次处理图片')
  149. if user_id in self.params_cache and ('last_file_content' in self.params_cache[user_id] or 'last_image_base64' in self.params_cache[user_id] ):
  150. # logger.info('上传过文件或图片')
  151. if 'last_file_content' in self.params_cache[user_id]:
  152. logger.info('上次文件内容开始')
  153. e_context["context"].type = ContextType.TEXT
  154. e_context["context"].content = self.params_cache[user_id]['last_file_content']+f'\n\t{self.previous_prompt}'
  155. logger.info(f'file4upload 插件处理上传文件')
  156. self.previous_prompt=''
  157. e_context.action = EventAction.CONTINUE # 事件继续,交付给下个插件或默认逻辑
  158. elif 'last_image_base64' in self.params_cache[user_id]:
  159. logger.info('上次图片开始')
  160. def handle_file(self, content, e_context):
  161. logger.info("handle_file: 向LLM发送内容总结请求")
  162. # 根据sum_service的值选择API密钥和基础URL
  163. if self.file_sum_service == "openai":
  164. api_key = self.open_ai_api_key
  165. api_base = self.open_ai_api_base
  166. model = self.model
  167. elif self.file_sum_service == "sum4all":
  168. api_key = self.sum4all_key
  169. api_base = "https://pro.sum4all.site/v1"
  170. model = "sum4all"
  171. elif self.file_sum_service == "gemini":
  172. api_key = self.gemini_key
  173. model = "gemini"
  174. api_base = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
  175. else:
  176. logger.error(f"未知的sum_service配置: {self.file_sum_service}")
  177. return
  178. msg: ChatMessage = e_context["context"]["msg"]
  179. user_id = msg.from_user_id
  180. user_params = self.params_cache.get(user_id, {})
  181. prompt = user_params.get('prompt', self.file_sum_prompt)
  182. if model == "gemini":
  183. headers = {
  184. 'Content-Type': 'application/json',
  185. 'x-goog-api-key': api_key
  186. }
  187. data = {
  188. "contents": [
  189. {"role": "user", "parts": [{"text": prompt}]},
  190. {"role": "model", "parts": [{"text": "okay"}]},
  191. {"role": "user", "parts": [{"text": content}]}
  192. ],
  193. "generationConfig": {
  194. "maxOutputTokens": 800
  195. }
  196. }
  197. api_url = api_base
  198. else:
  199. headers = {
  200. 'Content-Type': 'application/json',
  201. 'Authorization': f'Bearer {api_key}'
  202. }
  203. # content=f'Use the following context as your learned knowledge, inside <context></context> XML tags.\n\t<context>{content}</context>\n\t\n\tWhen answer to user:\n\t- If you don\'t know, just say that you don\'t know.\n\t- If you don\'t know when you are not sure, ask for clarification.\n\tAvoid mentioning that you obtained the information from the context.\n\tAnd answer according to the language of the user\'s question.\n\t\t\t\n\tGiven the context information, answer the query'
  204. if self.previous_prompt!='':
  205. prompt=self.previous_prompt
  206. logger.info(f"改变提示,使用上次提示")
  207. data = {
  208. "model": model,
  209. "messages": [
  210. {"role": "system", "content": prompt},
  211. {"role": "user", "content": content}
  212. ]
  213. }
  214. api_url = f"{api_base}/chat/completions"
  215. try:
  216. logger.info(f'handle_file: 请求文件内容{json.dumps(data, ensure_ascii=False)}')
  217. response = requests.post(api_url, headers=headers, data=json.dumps(data))
  218. response.raise_for_status()
  219. response_data = response.json()
  220. # 解析 JSON 并获取 content
  221. if model == "gemini":
  222. if "candidates" in response_data and len(response_data["candidates"]) > 0:
  223. first_candidate = response_data["candidates"][0]
  224. if "content" in first_candidate:
  225. if "parts" in first_candidate["content"] and len(first_candidate["content"]["parts"]) > 0:
  226. response_content = first_candidate["content"]["parts"][0]["text"].strip() # 获取响应内容
  227. logger.info(f"Gemini API response content: {response_content}") # 记录响应内容
  228. reply_content = response_content.replace("\\n", "\n") # 替换 \\n 为 \n
  229. else:
  230. logger.error("Parts not found in the Gemini API response content")
  231. reply_content = "Parts not found in the Gemini API response content"
  232. else:
  233. logger.error("Content not found in the Gemini API response candidate")
  234. reply_content = "Content not found in the Gemini API response candidate"
  235. else:
  236. logger.error("No candidates available in the Gemini API response")
  237. reply_content = "No candidates available in the Gemini API response"
  238. else:
  239. if "choices" in response_data and len(response_data["choices"]) > 0:
  240. first_choice = response_data["choices"][0]
  241. if "message" in first_choice and "content" in first_choice["message"]:
  242. response_content = first_choice["message"]["content"].strip() # 获取响应内容
  243. logger.info(f"LLM API response content") # 记录响应内容
  244. reply_content = response_content.replace("\\n", "\n") # 替换 \\n 为 \n
  245. if msg.ctype == ContextType.FILE and self.previous_prompt =='':
  246. reply_content="您刚刚上传了一个文件,请问我有什么可以帮您的呢?"
  247. self.previous_prompt=''
  248. # 已上传过,重置 previous_prompt
  249. elif self.previous_prompt !='' and 'last_file_content' in self.params_cache[user_id]:
  250. logger.info(f'last_file_content 已经回答最后的提示,清空previous_prompt')
  251. self.previous_prompt =''
  252. else:
  253. logger.error("Content not found in the response")
  254. reply_content = "Content not found in the LLM API response"
  255. else:
  256. logger.error("No choices available in the response")
  257. reply_content = "No choices available in the LLM API response"
  258. except requests.exceptions.RequestException as e:
  259. logger.error(f"Error calling LLM API: {e}")
  260. reply_content = f"An error occurred while calling LLM API"
  261. reply = Reply()
  262. reply.type = ReplyType.TEXT
  263. # reply.content = f"{remove_markdown(reply_content)}\n\n💬5min内输入{self.file_sum_qa_prefix}+问题,可继续追问"
  264. reply.content = f"{remove_markdown(reply_content)}"
  265. e_context["reply"] = reply
  266. e_context.action = EventAction.BREAK_PASS
  267. def handle_image(self, base64_image, e_context):
  268. logger.info("handle_image: 解析图像处理API的响应")
  269. msg: ChatMessage = e_context["context"]["msg"]
  270. user_id = msg.from_user_id
  271. user_params = self.params_cache.get(user_id, {})
  272. prompt = user_params.get('prompt', self.image_sum_prompt)
  273. if self.image_sum_service == "openai":
  274. api_key = self.open_ai_api_key
  275. api_base = f"{self.open_ai_api_base}/chat/completions"
  276. model = "gpt-4o-mini"
  277. elif self.image_sum_service == "xunfei":
  278. api_key = self.xunfei_api_key
  279. api_base = "https://spark.sum4all.site/v1/chat/completions"
  280. model = "spark-chat-vision"
  281. elif self.image_sum_service == "sum4all":
  282. api_key = self.sum4all_key
  283. api_base = "https://pro.sum4all.site/v1/chat/completions"
  284. model = "sum4all-vision"
  285. elif self.image_sum_service == "gemini":
  286. api_key = self.gemini_key
  287. api_base = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"
  288. payload = {
  289. "contents": [
  290. {
  291. "parts": [
  292. {"text": prompt},
  293. {
  294. "inline_data": {
  295. "mime_type":"image/png",
  296. "data": base64_image
  297. }
  298. }
  299. ]
  300. }
  301. ]
  302. }
  303. headers = {
  304. "Content-Type": "application/json",
  305. "x-goog-api-key": api_key
  306. }
  307. logger.info(f"准备发送请求. Payload大小: {len(json.dumps(payload))} 字节")
  308. else:
  309. logger.error(f"未知的image_sum_service配置: {self.image_sum_service}")
  310. return
  311. if self.previous_prompt!='':
  312. prompt=self.previous_prompt
  313. logger.info(f"改变提示,使用上次提示")
  314. if self.image_sum_service != "gemini":
  315. payload = {
  316. "model": model,
  317. "messages": [
  318. {
  319. "role": "user",
  320. "content": [
  321. {
  322. "type": "text",
  323. "text": prompt
  324. },
  325. {
  326. "type": "image_url",
  327. "image_url": {
  328. "url": f"data:image/jpeg;base64,{base64_image}"
  329. }
  330. }
  331. ]
  332. }
  333. ],
  334. "max_tokens": 3000
  335. }
  336. headers = {
  337. "Content-Type": "application/json",
  338. "Authorization": f"Bearer {api_key}"
  339. }
  340. try:
  341. logger.info(f'handle_image: 请求图片内容{json.dumps(payload, ensure_ascii=False)}')
  342. response = requests.post(api_base, headers=headers, json=payload)
  343. logger.info(f"API请求已发送. 状态码: {response.status_code}")
  344. response.raise_for_status()
  345. logger.info("API响应状态码正常,开始解析JSON")
  346. response_json = response.json()
  347. logger.info("JSON解析完成")
  348. if self.image_sum_service == "gemini":
  349. reply_content = response_json.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', 'No text found in the response')
  350. logger.info(f"成功解析Gemini响应. 回复内容长度: {len(reply_content)}")
  351. else:
  352. if "choices" in response_json and len(response_json["choices"]) > 0:
  353. first_choice = response_json["choices"][0]
  354. if "message" in first_choice and "content" in first_choice["message"]:
  355. response_content = first_choice["message"]["content"].strip()
  356. logger.info("LLM API response content")
  357. reply_content = response_content
  358. if msg.ctype == ContextType.IMAGE and self.previous_prompt =='':
  359. reply_content="您刚刚上传了一张图片,请问我有什么可以帮您的呢?"
  360. self.previous_prompt=''
  361. elif self.previous_prompt !='' and 'last_image_base64' in self.params_cache[user_id]:
  362. self.previous_prompt =''
  363. logger.info(f'last_image_base64 已经回答最后的提示,清空previous_prompt')
  364. else:
  365. logger.error("Content not found in the response")
  366. reply_content = "Content not found in the LLM API response"
  367. else:
  368. logger.error("No choices available in the response")
  369. reply_content = "No choices available in the LLM API response"
  370. except Exception as e:
  371. logger.error(f"Error processing LLM API response: {e}")
  372. reply_content = f"An error occurred while processing LLM API response"
  373. reply = Reply()
  374. reply.type = ReplyType.TEXT
  375. # reply.content = f"{remove_markdown(reply_content)}\n\n💬5min内输入{self.image_sum_qa_prefix}+问题,可继续追问"
  376. reply.content = f"{remove_markdown(reply_content)}"
  377. e_context["reply"] = reply
  378. e_context.action = EventAction.BREAK_PASS
  379. def read_pdf(self, file_path):
  380. logger.info(f"开始读取PDF文件:{file_path}")
  381. doc = fitz.open(file_path)
  382. content = ' '.join([page.get_text() for page in doc])
  383. logger.info(f"PDF文件读取完成:{file_path}")
  384. return content
  385. def read_word(self, file_path):
  386. doc = Document(file_path)
  387. return ' '.join([p.text for p in doc.paragraphs])
  388. def read_markdown(self, file_path):
  389. with open(file_path, 'r', encoding='utf-8') as file:
  390. md_content = file.read()
  391. return markdown.markdown(md_content)
  392. def read_excel(self, file_path):
  393. workbook = load_workbook(file_path)
  394. content = ''
  395. for sheet in workbook:
  396. for row in sheet.iter_rows():
  397. content += ' '.join([str(cell.value) for cell in row])
  398. content += '\n'
  399. return content
  400. def read_txt(self, file_path):
  401. logger.debug(f"开始读取TXT文件: {file_path}")
  402. try:
  403. with open(file_path, 'r', encoding='utf-8') as file:
  404. content = file.read()
  405. logger.debug(f"TXT文件读取完成: {file_path}")
  406. logger.debug("TXT文件内容的前50个字符:")
  407. logger.debug(content[:50]) # 打印文件内容的前50个字符
  408. return content
  409. except Exception as e:
  410. logger.error(f"读取TXT文件时出错: {file_path},错误信息: {str(e)}")
  411. return ""
  412. def read_csv(self, file_path):
  413. content = ''
  414. with open(file_path, 'r', encoding='utf-8') as csvfile:
  415. reader = csv.reader(csvfile)
  416. for row in reader:
  417. content += ' '.join(row) + '\n'
  418. return content
  419. def read_html(self, file_path):
  420. with open(file_path, 'r', encoding='utf-8') as file:
  421. soup = BeautifulSoup(file, 'html.parser')
  422. return soup.get_text()
  423. def read_ppt(self, file_path):
  424. presentation = Presentation(file_path)
  425. content = ''
  426. for slide in presentation.slides:
  427. for shape in slide.shapes:
  428. if hasattr(shape, "text"):
  429. content += shape.text + '\n'
  430. return content
  431. def extract_content(self, file_path):
  432. logger.info(f"extract_content: 提取文件内容,文件路径: {file_path}")
  433. file_size = os.path.getsize(file_path) // 1000 # 将文件大小转换为KB
  434. if file_size > int(self.max_file_size):
  435. logger.warning(f"文件大小超过限制({self.max_file_size}KB),不进行处理。文件大小: {file_size}KB")
  436. return None
  437. file_extension = os.path.splitext(file_path)[1][1:].lower()
  438. logger.info(f"extract_content: 文件类型为 {file_extension}")
  439. file_type = EXTENSION_TO_TYPE.get(file_extension)
  440. if not file_type:
  441. logger.error(f"不支持的文件扩展名: {file_extension}")
  442. return None
  443. read_func = {
  444. 'pdf': self.read_pdf,
  445. 'docx': self.read_word,
  446. 'md': self.read_markdown,
  447. 'txt': self.read_txt,
  448. 'excel': self.read_excel,
  449. 'csv': self.read_csv,
  450. 'html': self.read_html,
  451. 'ppt': self.read_ppt
  452. }.get(file_type)
  453. if not read_func:
  454. logger.error(f"不支持的文件类型: {file_type}")
  455. return None
  456. logger.info("extract_content: 文件内容提取完成")
  457. return read_func(file_path)
  458. def encode_image_to_base64(self, image_path):
  459. logger.info(f"开始处理图片: {image_path}")
  460. try:
  461. with Image.open(image_path) as img:
  462. logger.info(f"成功打开图片. 原始大小: {img.size}")
  463. if img.width > 1024:
  464. new_size = (1024, int(img.height*1024/img.width))
  465. img = img.resize(new_size)
  466. img.save(image_path) # 保存调整大小后的图片
  467. logger.info(f"调整图片大小至: {new_size}")
  468. with open(image_path, "rb") as image_file:
  469. img_byte_arr = image_file.read()
  470. logger.info(f"读取图片完成. 大小: {len(img_byte_arr)} 字节")
  471. encoded = base64.b64encode(img_byte_arr).decode('ascii')
  472. logger.info(f"Base64编码完成. 编码后长度: {len(encoded)}")
  473. return encoded
  474. except Exception as e:
  475. logger.error(f"图片编码过程中发生错误: {str(e)}", exc_info=True)
  476. raise
  477. def remove_markdown(text):
  478. # 替换Markdown的粗体标记
  479. text = text.replace("**", "")
  480. # 替换Markdown的标题标记
  481. text = text.replace("### ", "").replace("## ", "").replace("# ", "")
  482. return text