You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

txt_parser.py 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 deepdoc.parser.utils import get_text
  14. from rag.nlp import num_tokens_from_string
  15. class RAGFlowTxtParser:
  16. def __call__(self, fnm, binary=None, chunk_token_num=128, delimiter="\n!?;。;!?"):
  17. txt = get_text(fnm, binary)
  18. return self.parser_txt(txt, chunk_token_num, delimiter)
  19. @classmethod
  20. def parser_txt(cls, txt, chunk_token_num=128, delimiter="\n!?;。;!?"):
  21. if not isinstance(txt, str):
  22. raise TypeError("txt type should be str!")
  23. cks = [""]
  24. tk_nums = [0]
  25. def add_chunk(t):
  26. nonlocal cks, tk_nums, delimiter
  27. tnum = num_tokens_from_string(t)
  28. if tnum < 8:
  29. pos = ""
  30. if tk_nums[-1] > chunk_token_num:
  31. cks.append(t)
  32. tk_nums.append(tnum)
  33. else:
  34. cks[-1] += t
  35. tk_nums[-1] += tnum
  36. s, e = 0, 1
  37. while e < len(txt):
  38. if txt[e] in delimiter:
  39. add_chunk(txt[s: e + 1])
  40. s = e + 1
  41. e = s + 1
  42. else:
  43. e += 1
  44. if s < e:
  45. add_chunk(txt[s: e + 1])
  46. return [[c,""] for c in cks]