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

txt_parser.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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, delimiter="\n!?;。;!?"):
  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, delimiter)
  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. cks = [""]
  34. tk_nums = [0]
  35. def add_chunk(t):
  36. nonlocal cks, tk_nums, delimiter
  37. tnum = num_tokens_from_string(t)
  38. if tnum < 8:
  39. pos = ""
  40. if tk_nums[-1] > chunk_token_num:
  41. cks.append(t)
  42. tk_nums.append(tnum)
  43. else:
  44. cks[-1] += t
  45. tk_nums[-1] += tnum
  46. s, e = 0, 1
  47. while e < len(txt):
  48. if txt[e] in delimiter:
  49. add_chunk(txt[s: e + 1])
  50. s = e + 1
  51. e = s + 1
  52. else:
  53. e += 1
  54. if s < e:
  55. add_chunk(txt[s: e + 1])
  56. return [[c,""] for c in cks]