您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

txt_parser.py 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. from rag.nlp import find_codec,num_tokens_from_string
  14. class RAGFlowTxtParser:
  15. def __call__(self, fnm, binary=None, chunk_token_num=128):
  16. txt = ""
  17. if binary:
  18. encoding = find_codec(binary)
  19. txt = binary.decode(encoding, errors="ignore")
  20. else:
  21. with open(fnm, "r") as f:
  22. while True:
  23. l = f.readline()
  24. if not l:
  25. break
  26. txt += l
  27. return self.parser_txt(txt, chunk_token_num)
  28. @classmethod
  29. def parser_txt(cls, txt, chunk_token_num=128):
  30. if type(txt) != str:
  31. raise TypeError("txt type should be str!")
  32. sections = []
  33. for sec in txt.split("\n"):
  34. if num_tokens_from_string(sec) > 10 * int(chunk_token_num):
  35. sections.append((sec[: int(len(sec) / 2)], ""))
  36. sections.append((sec[int(len(sec) / 2) :], ""))
  37. else:
  38. sections.append((sec, ""))
  39. return sections