utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import json
  2. import logging
  3. import os
  4. import re
  5. import string
  6. from typing import Any
  7. from schema import Optional, Or, Schema
  8. from embedchain.models.data_type import DataType
  9. def clean_string(text):
  10. """
  11. This function takes in a string and performs a series of text cleaning operations.
  12. Args:
  13. text (str): The text to be cleaned. This is expected to be a string.
  14. Returns:
  15. cleaned_text (str): The cleaned text after all the cleaning operations
  16. have been performed.
  17. """
  18. # Replacement of newline characters:
  19. text = text.replace("\n", " ")
  20. # Stripping and reducing multiple spaces to single:
  21. cleaned_text = re.sub(r"\s+", " ", text.strip())
  22. # Removing backslashes:
  23. cleaned_text = cleaned_text.replace("\\", "")
  24. # Replacing hash characters:
  25. cleaned_text = cleaned_text.replace("#", " ")
  26. # Eliminating consecutive non-alphanumeric characters:
  27. # This regex identifies consecutive non-alphanumeric characters (i.e., not
  28. # a word character [a-zA-Z0-9_] and not a whitespace) in the string
  29. # and replaces each group of such characters with a single occurrence of
  30. # that character.
  31. # For example, "!!! hello !!!" would become "! hello !".
  32. cleaned_text = re.sub(r"([^\w\s])\1*", r"\1", cleaned_text)
  33. return cleaned_text
  34. def is_readable(s):
  35. """
  36. Heuristic to determine if a string is "readable" (mostly contains printable characters and forms meaningful words)
  37. :param s: string
  38. :return: True if the string is more than 95% printable.
  39. """
  40. try:
  41. printable_ratio = sum(c in string.printable for c in s) / len(s)
  42. except ZeroDivisionError:
  43. logging.warning("Empty string processed as unreadable")
  44. printable_ratio = 0
  45. return printable_ratio > 0.95 # 95% of characters are printable
  46. def use_pysqlite3():
  47. """
  48. Swap std-lib sqlite3 with pysqlite3.
  49. """
  50. import platform
  51. import sqlite3
  52. if platform.system() == "Linux" and sqlite3.sqlite_version_info < (3, 35, 0):
  53. try:
  54. # According to the Chroma team, this patch only works on Linux
  55. import datetime
  56. import subprocess
  57. import sys
  58. subprocess.check_call(
  59. [sys.executable, "-m", "pip", "install", "pysqlite3-binary", "--quiet", "--disable-pip-version-check"]
  60. )
  61. __import__("pysqlite3")
  62. sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
  63. # Let the user know what happened.
  64. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  65. print(
  66. f"{current_time} [embedchain] [INFO]",
  67. "Swapped std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  68. f"Your original version was {sqlite3.sqlite_version}.",
  69. )
  70. except Exception as e:
  71. # Escape all exceptions
  72. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  73. print(
  74. f"{current_time} [embedchain] [ERROR]",
  75. "Failed to swap std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  76. "Error:",
  77. e,
  78. )
  79. def format_source(source: str, limit: int = 20) -> str:
  80. """
  81. Format a string to only take the first x and last x letters.
  82. This makes it easier to display a URL, keeping familiarity while ensuring a consistent length.
  83. If the string is too short, it is not sliced.
  84. """
  85. if len(source) > 2 * limit:
  86. return source[:limit] + "..." + source[-limit:]
  87. return source
  88. def detect_datatype(source: Any) -> DataType:
  89. """
  90. Automatically detect the datatype of the given source.
  91. :param source: the source to base the detection on
  92. :return: data_type string
  93. """
  94. from urllib.parse import urlparse
  95. import requests
  96. import yaml
  97. def is_openapi_yaml(yaml_content):
  98. # currently the following two fields are required in openapi spec yaml config
  99. return "openapi" in yaml_content and "info" in yaml_content
  100. try:
  101. if not isinstance(source, str):
  102. raise ValueError("Source is not a string and thus cannot be a URL.")
  103. url = urlparse(source)
  104. # Check if both scheme and netloc are present. Local file system URIs are acceptable too.
  105. if not all([url.scheme, url.netloc]) and url.scheme != "file":
  106. raise ValueError("Not a valid URL.")
  107. except ValueError:
  108. url = False
  109. formatted_source = format_source(str(source), 30)
  110. if url:
  111. from langchain.document_loaders.youtube import \
  112. ALLOWED_NETLOCK as YOUTUBE_ALLOWED_NETLOCS
  113. if url.netloc in YOUTUBE_ALLOWED_NETLOCS:
  114. logging.debug(f"Source of `{formatted_source}` detected as `youtube_video`.")
  115. return DataType.YOUTUBE_VIDEO
  116. if url.netloc in {"notion.so", "notion.site"}:
  117. logging.debug(f"Source of `{formatted_source}` detected as `notion`.")
  118. return DataType.NOTION
  119. if url.path.endswith(".pdf"):
  120. logging.debug(f"Source of `{formatted_source}` detected as `pdf_file`.")
  121. return DataType.PDF_FILE
  122. if url.path.endswith(".xml"):
  123. logging.debug(f"Source of `{formatted_source}` detected as `sitemap`.")
  124. return DataType.SITEMAP
  125. if url.path.endswith(".csv"):
  126. logging.debug(f"Source of `{formatted_source}` detected as `csv`.")
  127. return DataType.CSV
  128. if url.path.endswith(".docx"):
  129. logging.debug(f"Source of `{formatted_source}` detected as `docx`.")
  130. return DataType.DOCX
  131. if url.path.endswith(".yaml"):
  132. try:
  133. response = requests.get(source)
  134. response.raise_for_status()
  135. try:
  136. yaml_content = yaml.safe_load(response.text)
  137. except yaml.YAMLError as exc:
  138. logging.error(f"Error parsing YAML: {exc}")
  139. raise TypeError(f"Not a valid data type. Error loading YAML: {exc}")
  140. if is_openapi_yaml(yaml_content):
  141. logging.debug(f"Source of `{formatted_source}` detected as `openapi`.")
  142. return DataType.OPENAPI
  143. else:
  144. logging.error(
  145. f"Source of `{formatted_source}` does not contain all the required \
  146. fields of OpenAPI yaml. Check 'https://spec.openapis.org/oas/v3.1.0'"
  147. )
  148. raise TypeError(
  149. "Not a valid data type. Check 'https://spec.openapis.org/oas/v3.1.0', \
  150. make sure you have all the required fields in YAML config data"
  151. )
  152. except requests.exceptions.RequestException as e:
  153. logging.error(f"Error fetching URL {formatted_source}: {e}")
  154. if url.path.endswith(".json"):
  155. logging.debug(f"Source of `{formatted_source}` detected as `json_file`.")
  156. return DataType.JSON
  157. if "docs" in url.netloc or ("docs" in url.path and url.scheme != "file"):
  158. # `docs_site` detection via path is not accepted for local filesystem URIs,
  159. # because that would mean all paths that contain `docs` are now doc sites, which is too aggressive.
  160. logging.debug(f"Source of `{formatted_source}` detected as `docs_site`.")
  161. return DataType.DOCS_SITE
  162. # If none of the above conditions are met, it's a general web page
  163. logging.debug(f"Source of `{formatted_source}` detected as `web_page`.")
  164. return DataType.WEB_PAGE
  165. elif not isinstance(source, str):
  166. # For datatypes where source is not a string.
  167. if isinstance(source, tuple) and len(source) == 2 and isinstance(source[0], str) and isinstance(source[1], str):
  168. logging.debug(f"Source of `{formatted_source}` detected as `qna_pair`.")
  169. return DataType.QNA_PAIR
  170. # Raise an error if it isn't a string and also not a valid non-string type (one of the previous).
  171. # We could stringify it, but it is better to raise an error and let the user decide how they want to do that.
  172. raise TypeError(
  173. "Source is not a string and a valid non-string type could not be detected. If you want to embed it, please stringify it, for instance by using `str(source)` or `(', ').join(source)`." # noqa: E501
  174. )
  175. elif os.path.isfile(source):
  176. # For datatypes that support conventional file references.
  177. # Note: checking for string is not necessary anymore.
  178. if source.endswith(".docx"):
  179. logging.debug(f"Source of `{formatted_source}` detected as `docx`.")
  180. return DataType.DOCX
  181. if source.endswith(".csv"):
  182. logging.debug(f"Source of `{formatted_source}` detected as `csv`.")
  183. return DataType.CSV
  184. if source.endswith(".xml"):
  185. logging.debug(f"Source of `{formatted_source}` detected as `xml`.")
  186. return DataType.XML
  187. if source.endswith(".yaml"):
  188. with open(source, "r") as file:
  189. yaml_content = yaml.safe_load(file)
  190. if is_openapi_yaml(yaml_content):
  191. logging.debug(f"Source of `{formatted_source}` detected as `openapi`.")
  192. return DataType.OPENAPI
  193. else:
  194. logging.error(
  195. f"Source of `{formatted_source}` does not contain all the required \
  196. fields of OpenAPI yaml. Check 'https://spec.openapis.org/oas/v3.1.0'"
  197. )
  198. raise ValueError(
  199. "Invalid YAML data. Check 'https://spec.openapis.org/oas/v3.1.0', \
  200. make sure to add all the required params"
  201. )
  202. if source.endswith(".json"):
  203. logging.debug(f"Source of `{formatted_source}` detected as `json`.")
  204. return DataType.JSON
  205. # If the source is a valid file, that's not detectable as a type, an error is raised.
  206. # It does not fallback to text.
  207. raise ValueError(
  208. "Source points to a valid file, but based on the filename, no `data_type` can be detected. Please be aware, that not all data_types allow conventional file references, some require the use of the `file URI scheme`. Please refer to the embedchain documentation (https://docs.embedchain.ai/advanced/data_types#remote-data-types)." # noqa: E501
  209. )
  210. else:
  211. # Source is not a URL.
  212. # TODO: check if source is gmail query
  213. # check if the source is valid json string
  214. if is_valid_json_string(source):
  215. logging.debug(f"Source of `{formatted_source}` detected as `json`.")
  216. return DataType.JSON
  217. # Use text as final fallback.
  218. logging.debug(f"Source of `{formatted_source}` detected as `text`.")
  219. return DataType.TEXT
  220. # check if the source is valid json string
  221. def is_valid_json_string(source: str):
  222. try:
  223. _ = json.loads(source)
  224. return True
  225. except json.JSONDecodeError:
  226. logging.error(
  227. "Insert valid string format of JSON. \
  228. Check the docs to see the supported formats - `https://docs.embedchain.ai/data-sources/json`"
  229. )
  230. return False
  231. def validate_yaml_config(config_data):
  232. schema = Schema(
  233. {
  234. Optional("app"): {
  235. Optional("config"): {
  236. Optional("id"): str,
  237. Optional("name"): str,
  238. Optional("log_level"): Or("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
  239. Optional("collect_metrics"): bool,
  240. Optional("collection_name"): str,
  241. }
  242. },
  243. Optional("llm"): {
  244. Optional("provider"): Or(
  245. "openai",
  246. "azure_openai",
  247. "anthropic",
  248. "huggingface",
  249. "cohere",
  250. "gpt4all",
  251. "jina",
  252. "llama2",
  253. "vertex_ai",
  254. ),
  255. Optional("config"): {
  256. Optional("model"): str,
  257. Optional("number_documents"): int,
  258. Optional("temperature"): float,
  259. Optional("max_tokens"): int,
  260. Optional("top_p"): Or(float, int),
  261. Optional("stream"): bool,
  262. Optional("template"): str,
  263. Optional("system_prompt"): str,
  264. Optional("deployment_name"): str,
  265. Optional("where"): dict,
  266. Optional("query_type"): str,
  267. },
  268. },
  269. Optional("vectordb"): {
  270. Optional("provider"): Or(
  271. "chroma", "elasticsearch", "opensearch", "pinecone", "qdrant", "weaviate", "zilliz"
  272. ),
  273. Optional("config"): {
  274. Optional("collection_name"): str,
  275. Optional("dir"): str,
  276. Optional("allow_reset"): bool,
  277. Optional("host"): str,
  278. Optional("port"): str,
  279. },
  280. },
  281. Optional("embedder"): {
  282. Optional("provider"): Or("openai", "gpt4all", "huggingface", "vertexai"),
  283. Optional("config"): {
  284. Optional("model"): Optional(str),
  285. Optional("deployment_name"): Optional(str),
  286. },
  287. },
  288. Optional("embedding_model"): {
  289. Optional("provider"): Or("openai", "gpt4all", "huggingface", "vertexai"),
  290. Optional("config"): {
  291. Optional("model"): str,
  292. Optional("deployment_name"): str,
  293. },
  294. },
  295. Optional("chunker"): {
  296. Optional("chunk_size"): int,
  297. Optional("chunk_overlap"): int,
  298. Optional("length_function"): str,
  299. },
  300. }
  301. )
  302. return schema.validate(config_data)