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

txt_parser.py 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. import re
  15. class RAGFlowTxtParser:
  16. def __call__(self, fnm, binary=None, chunk_token_num=128):
  17. txt = ""
  18. if binary:
  19. encoding = find_codec(binary)
  20. txt = binary.decode(encoding, errors="ignore")
  21. else:
  22. with open(fnm, "r") as f:
  23. while True:
  24. l = f.readline()
  25. if not l:
  26. break
  27. txt += l
  28. return self.parser_txt(txt, chunk_token_num)
  29. @classmethod
  30. def parser_txt(cls, txt, chunk_token_num=128, delimiter="\n!?;。;!?"):
  31. if type(txt) != str:
  32. raise TypeError("txt type should be str!")
  33. sections = []
  34. for sec in re.split(r"[%s]+"%delimiter, txt):
  35. if sections and sec in delimiter:
  36. sections[-1][0] += sec
  37. continue
  38. if num_tokens_from_string(sec) > 10 * int(chunk_token_num):
  39. sections.append([sec[: int(len(sec) / 2)], ""])
  40. sections.append([sec[int(len(sec) / 2) :], ""])
  41. else:
  42. sections.append([sec, ""])
  43. return sections