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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. import re
  14. from deepdoc.parser.utils import get_text
  15. from rag.nlp import num_tokens_from_string
  16. class RAGFlowTxtParser:
  17. def __call__(self, fnm, binary=None, chunk_token_num=128, delimiter="\n!?;。;!?"):
  18. txt = get_text(fnm, binary)
  19. return self.parser_txt(txt, chunk_token_num, delimiter)
  20. @classmethod
  21. def parser_txt(cls, txt, chunk_token_num=128, delimiter="\n!?;。;!?"):
  22. if not isinstance(txt, str):
  23. raise TypeError("txt type should be str!")
  24. cks = [""]
  25. tk_nums = [0]
  26. def add_chunk(t):
  27. nonlocal cks, tk_nums, delimiter
  28. tnum = num_tokens_from_string(t)
  29. if tk_nums[-1] > chunk_token_num:
  30. cks.append(t)
  31. tk_nums.append(tnum)
  32. else:
  33. cks[-1] += t
  34. tk_nums[-1] += tnum
  35. dels = []
  36. s = 0
  37. for m in re.finditer(r"`([^`]+)`", delimiter, re.I):
  38. f, t = m.span()
  39. dels.append(m.group(1))
  40. dels.extend(list(delimiter[s: f]))
  41. s = t
  42. if s < len(delimiter):
  43. dels.extend(list(delimiter[s:]))
  44. dels = [re.escape(d) for d in delimiter if d]
  45. dels = [d for d in dels if d]
  46. dels = "|".join(dels)
  47. secs = re.split(r"(%s)" % dels, txt)
  48. for sec in secs:
  49. add_chunk(sec)
  50. return [[c, ""] for c in cks]