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.

__init__.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #
  2. # Copyright 2024 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 os
  17. import re
  18. import tiktoken
  19. def singleton(cls, *args, **kw):
  20. instances = {}
  21. def _singleton():
  22. key = str(cls) + str(os.getpid())
  23. if key not in instances:
  24. instances[key] = cls(*args, **kw)
  25. return instances[key]
  26. return _singleton
  27. def rmSpace(txt):
  28. txt = re.sub(r"([^a-z0-9.,\)>]) +([^ ])", r"\1\2", txt, flags=re.IGNORECASE)
  29. return re.sub(r"([^ ]) +([^a-z0-9.,\(<])", r"\1\2", txt, flags=re.IGNORECASE)
  30. def findMaxDt(fnm):
  31. m = "1970-01-01 00:00:00"
  32. try:
  33. with open(fnm, "r") as f:
  34. while True:
  35. l = f.readline()
  36. if not l:
  37. break
  38. l = l.strip("\n")
  39. if l == 'nan':
  40. continue
  41. if l > m:
  42. m = l
  43. except Exception as e:
  44. pass
  45. return m
  46. def findMaxTm(fnm):
  47. m = 0
  48. try:
  49. with open(fnm, "r") as f:
  50. while True:
  51. l = f.readline()
  52. if not l:
  53. break
  54. l = l.strip("\n")
  55. if l == 'nan':
  56. continue
  57. if int(l) > m:
  58. m = int(l)
  59. except Exception as e:
  60. pass
  61. return m
  62. encoder = tiktoken.encoding_for_model("gpt-3.5-turbo")
  63. def num_tokens_from_string(string: str) -> int:
  64. """Returns the number of tokens in a text string."""
  65. try:
  66. return len(encoder.encode(string))
  67. except Exception:
  68. return 0
  69. def truncate(string: str, max_len: int) -> str:
  70. """Returns truncated text if the length of text exceed max_len."""
  71. return encoder.decode(encoder.encode(string)[:max_len])