Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. delimiter = delimiter.encode('utf-8').decode('unicode_escape').encode('latin1').decode('utf-8')
  30. def add_chunk(t):
  31. nonlocal cks, tk_nums, delimiter
  32. tnum = num_tokens_from_string(t)
  33. if tk_nums[-1] > chunk_token_num:
  34. cks.append(t)
  35. tk_nums.append(tnum)
  36. else:
  37. cks[-1] += t
  38. tk_nums[-1] += tnum
  39. dels = []
  40. s = 0
  41. for m in re.finditer(r"`([^`]+)`", delimiter, re.I):
  42. f, t = m.span()
  43. dels.append(m.group(1))
  44. dels.extend(list(delimiter[s: f]))
  45. s = t
  46. if s < len(delimiter):
  47. dels.extend(list(delimiter[s:]))
  48. dels = [re.escape(d) for d in dels if d]
  49. dels = [d for d in dels if d]
  50. dels = "|".join(dels)
  51. secs = re.split(r"(%s)" % dels, txt)
  52. for sec in secs:
  53. if re.match(f"^{dels}$", sec):
  54. continue
  55. add_chunk(sec)
  56. return [[c, ""] for c in cks]