files.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import json
  2. import fitz
  3. import io
  4. from docx import Document
  5. from dashscope import get_tokenizer # dashscope版本 >= 1.14.0
  6. from app.models import ComplexChatSessionDao
  7. from app.service.auth import decode_access_token
  8. async def get_str_token(input_str):
  9. # 获取tokenizer对象,目前只支持通义千问系列模型
  10. tokenizer = get_tokenizer('qwen-turbo')
  11. # 将字符串切分成token并转换为token id
  12. tokens = tokenizer.encode(input_str)
  13. # print(f"经过切分后的token id为:{tokens}。")
  14. # # 经过切分后的token id为: [31935, 64559, 99320, 56007, 100629, 104795, 99788, 1773]
  15. # print(f"经过切分后共有{len(tokens)}个token")
  16. # # 经过切分后共有8个token
  17. #
  18. # # 将token id转化为字符串并打印出来
  19. # for i in range(len(tokens)):
  20. # print(f"token id为{tokens[i]}对应的字符串为:{tokenizer.decode(tokens[i])}")
  21. return len(tokens)
  22. async def read_pdf(pdf_stream):
  23. text = ""
  24. with fitz.open(stream=pdf_stream, filetype="pdf") as pdf_document:
  25. for page in pdf_document:
  26. text += page.get_text()
  27. return text
  28. async def read_word(word_stream):
  29. # 使用 python-docx 打开 Word 文件流
  30. doc = Document(io.BytesIO(word_stream))
  31. # 提取每个段落的文本
  32. text = ""
  33. for para in doc.paragraphs:
  34. text += para.text
  35. return text
  36. async def read_file(file, filename, content_type):
  37. text = ""
  38. if content_type == "application/pdf" or filename.endswith('.pdf'):
  39. # 提取 PDF 内容
  40. text = await read_pdf(file)
  41. elif content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" or filename.endswith(
  42. '.docx'):
  43. text = await read_word(file)
  44. return await get_str_token(text)
  45. async def service_chat_message(db, message_id: str):
  46. message = await ComplexChatSessionDao(db).get_session_by_id(message_id)
  47. content = ""
  48. title = ""
  49. if message:
  50. content = message.content
  51. title= json.loads(message.query).get("query")
  52. return title, content
  53. async def generate_word_document(title, content):
  54. doc = Document()
  55. # 添加标题
  56. doc.add_heading(title, level=1)
  57. # 将内容按段落分割并写入文档
  58. for paragraph in content.split('\n'):
  59. # print("--------------:", paragraph)
  60. doc.add_paragraph(paragraph)
  61. return doc