utils.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import logging
  2. import re
  3. import string
  4. def clean_string(text):
  5. """
  6. This function takes in a string and performs a series of text cleaning operations.
  7. Args:
  8. text (str): The text to be cleaned. This is expected to be a string.
  9. Returns:
  10. cleaned_text (str): The cleaned text after all the cleaning operations
  11. have been performed.
  12. """
  13. # Replacement of newline characters:
  14. text = text.replace("\n", " ")
  15. # Stripping and reducing multiple spaces to single:
  16. cleaned_text = re.sub(r"\s+", " ", text.strip())
  17. # Removing backslashes:
  18. cleaned_text = cleaned_text.replace("\\", "")
  19. # Replacing hash characters:
  20. cleaned_text = cleaned_text.replace("#", " ")
  21. # Eliminating consecutive non-alphanumeric characters:
  22. # This regex identifies consecutive non-alphanumeric characters (i.e., not
  23. # a word character [a-zA-Z0-9_] and not a whitespace) in the string
  24. # and replaces each group of such characters with a single occurrence of
  25. # that character.
  26. # For example, "!!! hello !!!" would become "! hello !".
  27. cleaned_text = re.sub(r"([^\w\s])\1*", r"\1", cleaned_text)
  28. return cleaned_text
  29. def is_readable(s):
  30. """
  31. Heuristic to determine if a string is "readable" (mostly contains printable characters and forms meaningful words)
  32. :param s: string
  33. :return: True if the string is more than 95% printable.
  34. """
  35. try:
  36. printable_ratio = sum(c in string.printable for c in s) / len(s)
  37. except ZeroDivisionError:
  38. logging.warning("Empty string processed as unreadable")
  39. printable_ratio = 0
  40. return printable_ratio > 0.95 # 95% of characters are printable
  41. def use_pysqlite3():
  42. """
  43. Swap std-lib sqlite3 with pysqlite3.
  44. """
  45. import platform
  46. import sqlite3
  47. if platform.system() == "Linux" and sqlite3.sqlite_version_info < (3, 35, 0):
  48. try:
  49. # According to the Chroma team, this patch only works on Linux
  50. import datetime
  51. import subprocess
  52. import sys
  53. subprocess.check_call(
  54. [sys.executable, "-m", "pip", "install", "pysqlite3-binary", "--quiet", "--disable-pip-version-check"]
  55. )
  56. __import__("pysqlite3")
  57. sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
  58. # Let the user know what happened.
  59. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  60. print(
  61. f"{current_time} [embedchain] [INFO]",
  62. "Swapped std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  63. f"Your original version was {sqlite3.sqlite_version}.",
  64. )
  65. except Exception as e:
  66. # Escape all exceptions
  67. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  68. print(
  69. f"{current_time} [embedchain] [ERROR]",
  70. "Failed to swap std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  71. "Error:",
  72. e,
  73. )