Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

txt_parser.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. from deepdoc.parser.utils import get_text
  18. from rag.nlp import num_tokens_from_string
  19. class RAGFlowTxtParser:
  20. def __call__(self, fnm, binary=None, chunk_token_num=128, delimiter="\n!?;。;!?"):
  21. txt = get_text(fnm, binary)
  22. return self.parser_txt(txt, chunk_token_num, delimiter)
  23. @classmethod
  24. def parser_txt(cls, txt, chunk_token_num=128, delimiter="\n!?;。;!?"):
  25. if not isinstance(txt, str):
  26. raise TypeError("txt type should be str!")
  27. cks = [""]
  28. tk_nums = [0]
  29. def add_chunk(t):
  30. nonlocal cks, tk_nums, delimiter
  31. tnum = num_tokens_from_string(t)
  32. if tk_nums[-1] > chunk_token_num:
  33. cks.append(t)
  34. tk_nums.append(tnum)
  35. else:
  36. cks[-1] += t
  37. tk_nums[-1] += tnum
  38. dels = []
  39. s = 0
  40. for m in re.finditer(r"`([^`]+)`", delimiter, re.I):
  41. f, t = m.span()
  42. dels.append(m.group(1))
  43. dels.extend(list(delimiter[s: f]))
  44. s = t
  45. if s < len(delimiter):
  46. dels.extend(list(delimiter[s:]))
  47. dels = [re.escape(d) for d in delimiter if d]
  48. dels = [d for d in dels if d]
  49. dels = "|".join(dels)
  50. secs = re.split(r"(%s)" % dels, txt)
  51. for sec in secs:
  52. add_chunk(sec)
  53. return [[c, ""] for c in cks]