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.

619 Zeilen
30KB

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