misc.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import itertools
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import string
  7. from typing import Any
  8. from schema import Optional, Or, Schema
  9. from tqdm import tqdm
  10. from embedchain.models.data_type import DataType
  11. def parse_content(content, type):
  12. implemented = ["html.parser", "lxml", "lxml-xml", "xml", "html5lib"]
  13. if type not in implemented:
  14. raise ValueError(f"Parser type {type} not implemented. Please choose one of {implemented}")
  15. from bs4 import BeautifulSoup
  16. soup = BeautifulSoup(content, type)
  17. original_size = len(str(soup.get_text()))
  18. tags_to_exclude = [
  19. "nav",
  20. "aside",
  21. "form",
  22. "header",
  23. "noscript",
  24. "svg",
  25. "canvas",
  26. "footer",
  27. "script",
  28. "style",
  29. ]
  30. for tag in soup(tags_to_exclude):
  31. tag.decompose()
  32. ids_to_exclude = ["sidebar", "main-navigation", "menu-main-menu"]
  33. for id in ids_to_exclude:
  34. tags = soup.find_all(id=id)
  35. for tag in tags:
  36. tag.decompose()
  37. classes_to_exclude = [
  38. "elementor-location-header",
  39. "navbar-header",
  40. "nav",
  41. "header-sidebar-wrapper",
  42. "blog-sidebar-wrapper",
  43. "related-posts",
  44. ]
  45. for class_name in classes_to_exclude:
  46. tags = soup.find_all(class_=class_name)
  47. for tag in tags:
  48. tag.decompose()
  49. content = soup.get_text()
  50. content = clean_string(content)
  51. cleaned_size = len(content)
  52. if original_size != 0:
  53. logging.info(
  54. f"Cleaned page size: {cleaned_size} characters, down from {original_size} (shrunk: {original_size-cleaned_size} chars, {round((1-(cleaned_size/original_size)) * 100, 2)}%)" # noqa:E501
  55. )
  56. return content
  57. def clean_string(text):
  58. """
  59. This function takes in a string and performs a series of text cleaning operations.
  60. Args:
  61. text (str): The text to be cleaned. This is expected to be a string.
  62. Returns:
  63. cleaned_text (str): The cleaned text after all the cleaning operations
  64. have been performed.
  65. """
  66. # Stripping and reducing multiple spaces to single:
  67. cleaned_text = re.sub(r"\s+", " ", text.strip())
  68. # Removing backslashes:
  69. cleaned_text = cleaned_text.replace("\\", "")
  70. # Replacing hash characters:
  71. cleaned_text = cleaned_text.replace("#", " ")
  72. # Eliminating consecutive non-alphanumeric characters:
  73. # This regex identifies consecutive non-alphanumeric characters (i.e., not
  74. # a word character [a-zA-Z0-9_] and not a whitespace) in the string
  75. # and replaces each group of such characters with a single occurrence of
  76. # that character.
  77. # For example, "!!! hello !!!" would become "! hello !".
  78. cleaned_text = re.sub(r"([^\w\s])\1*", r"\1", cleaned_text)
  79. return cleaned_text
  80. def is_readable(s):
  81. """
  82. Heuristic to determine if a string is "readable" (mostly contains printable characters and forms meaningful words)
  83. :param s: string
  84. :return: True if the string is more than 95% printable.
  85. """
  86. len_s = len(s)
  87. if len_s == 0:
  88. return False
  89. printable_chars = set(string.printable)
  90. printable_ratio = sum(c in printable_chars for c in s) / len_s
  91. return printable_ratio > 0.95 # 95% of characters are printable
  92. def use_pysqlite3():
  93. """
  94. Swap std-lib sqlite3 with pysqlite3.
  95. """
  96. import platform
  97. import sqlite3
  98. if platform.system() == "Linux" and sqlite3.sqlite_version_info < (3, 35, 0):
  99. try:
  100. # According to the Chroma team, this patch only works on Linux
  101. import datetime
  102. import subprocess
  103. import sys
  104. subprocess.check_call(
  105. [sys.executable, "-m", "pip", "install", "pysqlite3-binary", "--quiet", "--disable-pip-version-check"]
  106. )
  107. __import__("pysqlite3")
  108. sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
  109. # Let the user know what happened.
  110. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  111. print(
  112. f"{current_time} [embedchain] [INFO]",
  113. "Swapped std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  114. f"Your original version was {sqlite3.sqlite_version}.",
  115. )
  116. except Exception as e:
  117. # Escape all exceptions
  118. current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
  119. print(
  120. f"{current_time} [embedchain] [ERROR]",
  121. "Failed to swap std-lib sqlite3 with pysqlite3 for ChromaDb compatibility.",
  122. "Error:",
  123. e,
  124. )
  125. def format_source(source: str, limit: int = 20) -> str:
  126. """
  127. Format a string to only take the first x and last x letters.
  128. This makes it easier to display a URL, keeping familiarity while ensuring a consistent length.
  129. If the string is too short, it is not sliced.
  130. """
  131. if len(source) > 2 * limit:
  132. return source[:limit] + "..." + source[-limit:]
  133. return source
  134. def detect_datatype(source: Any) -> DataType:
  135. """
  136. Automatically detect the datatype of the given source.
  137. :param source: the source to base the detection on
  138. :return: data_type string
  139. """
  140. from urllib.parse import urlparse
  141. import requests
  142. import yaml
  143. def is_openapi_yaml(yaml_content):
  144. # currently the following two fields are required in openapi spec yaml config
  145. return "openapi" in yaml_content and "info" in yaml_content
  146. def is_google_drive_folder(url):
  147. # checks if url is a Google Drive folder url against a regex
  148. regex = r"^drive\.google\.com\/drive\/(?:u\/\d+\/)folders\/([a-zA-Z0-9_-]+)$"
  149. return re.match(regex, url)
  150. try:
  151. if not isinstance(source, str):
  152. raise ValueError("Source is not a string and thus cannot be a URL.")
  153. url = urlparse(source)
  154. # Check if both scheme and netloc are present. Local file system URIs are acceptable too.
  155. if not all([url.scheme, url.netloc]) and url.scheme != "file":
  156. raise ValueError("Not a valid URL.")
  157. except ValueError:
  158. url = False
  159. formatted_source = format_source(str(source), 30)
  160. if url:
  161. YOUTUBE_ALLOWED_NETLOCKS = {
  162. "www.youtube.com",
  163. "m.youtube.com",
  164. "youtu.be",
  165. "youtube.com",
  166. "vid.plus",
  167. "www.youtube-nocookie.com",
  168. }
  169. if url.netloc in YOUTUBE_ALLOWED_NETLOCKS:
  170. logging.debug(f"Source of `{formatted_source}` detected as `youtube_video`.")
  171. return DataType.YOUTUBE_VIDEO
  172. if url.netloc in {"notion.so", "notion.site"}:
  173. logging.debug(f"Source of `{formatted_source}` detected as `notion`.")
  174. return DataType.NOTION
  175. if url.path.endswith(".pdf"):
  176. logging.debug(f"Source of `{formatted_source}` detected as `pdf_file`.")
  177. return DataType.PDF_FILE
  178. if url.path.endswith(".xml"):
  179. logging.debug(f"Source of `{formatted_source}` detected as `sitemap`.")
  180. return DataType.SITEMAP
  181. if url.path.endswith(".csv"):
  182. logging.debug(f"Source of `{formatted_source}` detected as `csv`.")
  183. return DataType.CSV
  184. if url.path.endswith(".mdx") or url.path.endswith(".md"):
  185. logging.debug(f"Source of `{formatted_source}` detected as `mdx`.")
  186. return DataType.MDX
  187. if url.path.endswith(".docx"):
  188. logging.debug(f"Source of `{formatted_source}` detected as `docx`.")
  189. return DataType.DOCX
  190. if url.path.endswith(".yaml"):
  191. try:
  192. response = requests.get(source)
  193. response.raise_for_status()
  194. try:
  195. yaml_content = yaml.safe_load(response.text)
  196. except yaml.YAMLError as exc:
  197. logging.error(f"Error parsing YAML: {exc}")
  198. raise TypeError(f"Not a valid data type. Error loading YAML: {exc}")
  199. if is_openapi_yaml(yaml_content):
  200. logging.debug(f"Source of `{formatted_source}` detected as `openapi`.")
  201. return DataType.OPENAPI
  202. else:
  203. logging.error(
  204. f"Source of `{formatted_source}` does not contain all the required \
  205. fields of OpenAPI yaml. Check 'https://spec.openapis.org/oas/v3.1.0'"
  206. )
  207. raise TypeError(
  208. "Not a valid data type. Check 'https://spec.openapis.org/oas/v3.1.0', \
  209. make sure you have all the required fields in YAML config data"
  210. )
  211. except requests.exceptions.RequestException as e:
  212. logging.error(f"Error fetching URL {formatted_source}: {e}")
  213. if url.path.endswith(".json"):
  214. logging.debug(f"Source of `{formatted_source}` detected as `json_file`.")
  215. return DataType.JSON
  216. if "docs" in url.netloc or ("docs" in url.path and url.scheme != "file"):
  217. # `docs_site` detection via path is not accepted for local filesystem URIs,
  218. # because that would mean all paths that contain `docs` are now doc sites, which is too aggressive.
  219. logging.debug(f"Source of `{formatted_source}` detected as `docs_site`.")
  220. return DataType.DOCS_SITE
  221. if "github.com" in url.netloc:
  222. logging.debug(f"Source of `{formatted_source}` detected as `github`.")
  223. return DataType.GITHUB
  224. if is_google_drive_folder(url.netloc + url.path):
  225. logging.debug(f"Source of `{formatted_source}` detected as `google drive folder`.")
  226. return DataType.GOOGLE_DRIVE_FOLDER
  227. # If none of the above conditions are met, it's a general web page
  228. logging.debug(f"Source of `{formatted_source}` detected as `web_page`.")
  229. return DataType.WEB_PAGE
  230. elif not isinstance(source, str):
  231. # For datatypes where source is not a string.
  232. if isinstance(source, tuple) and len(source) == 2 and isinstance(source[0], str) and isinstance(source[1], str):
  233. logging.debug(f"Source of `{formatted_source}` detected as `qna_pair`.")
  234. return DataType.QNA_PAIR
  235. # Raise an error if it isn't a string and also not a valid non-string type (one of the previous).
  236. # We could stringify it, but it is better to raise an error and let the user decide how they want to do that.
  237. raise TypeError(
  238. "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
  239. )
  240. elif os.path.isfile(source):
  241. # For datatypes that support conventional file references.
  242. # Note: checking for string is not necessary anymore.
  243. if source.endswith(".docx"):
  244. logging.debug(f"Source of `{formatted_source}` detected as `docx`.")
  245. return DataType.DOCX
  246. if source.endswith(".csv"):
  247. logging.debug(f"Source of `{formatted_source}` detected as `csv`.")
  248. return DataType.CSV
  249. if source.endswith(".xml"):
  250. logging.debug(f"Source of `{formatted_source}` detected as `xml`.")
  251. return DataType.XML
  252. if source.endswith(".mdx") or source.endswith(".md"):
  253. logging.debug(f"Source of `{formatted_source}` detected as `mdx`.")
  254. return DataType.MDX
  255. if source.endswith(".txt"):
  256. logging.debug(f"Source of `{formatted_source}` detected as `text`.")
  257. return DataType.TEXT_FILE
  258. if source.endswith(".pdf"):
  259. logging.debug(f"Source of `{formatted_source}` detected as `pdf_file`.")
  260. return DataType.PDF_FILE
  261. if source.endswith(".yaml"):
  262. with open(source, "r") as file:
  263. yaml_content = yaml.safe_load(file)
  264. if is_openapi_yaml(yaml_content):
  265. logging.debug(f"Source of `{formatted_source}` detected as `openapi`.")
  266. return DataType.OPENAPI
  267. else:
  268. logging.error(
  269. f"Source of `{formatted_source}` does not contain all the required \
  270. fields of OpenAPI yaml. Check 'https://spec.openapis.org/oas/v3.1.0'"
  271. )
  272. raise ValueError(
  273. "Invalid YAML data. Check 'https://spec.openapis.org/oas/v3.1.0', \
  274. make sure to add all the required params"
  275. )
  276. if source.endswith(".json"):
  277. logging.debug(f"Source of `{formatted_source}` detected as `json`.")
  278. return DataType.JSON
  279. if os.path.exists(source) and is_readable(open(source).read()):
  280. logging.debug(f"Source of `{formatted_source}` detected as `text_file`.")
  281. return DataType.TEXT_FILE
  282. # If the source is a valid file, that's not detectable as a type, an error is raised.
  283. # It does not fall back to text.
  284. raise ValueError(
  285. "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
  286. )
  287. else:
  288. # Source is not a URL.
  289. # TODO: check if source is gmail query
  290. # check if the source is valid json string
  291. if is_valid_json_string(source):
  292. logging.debug(f"Source of `{formatted_source}` detected as `json`.")
  293. return DataType.JSON
  294. # Use text as final fallback.
  295. logging.debug(f"Source of `{formatted_source}` detected as `text`.")
  296. return DataType.TEXT
  297. # check if the source is valid json string
  298. def is_valid_json_string(source: str):
  299. try:
  300. _ = json.loads(source)
  301. return True
  302. except json.JSONDecodeError:
  303. return False
  304. def validate_config(config_data):
  305. schema = Schema(
  306. {
  307. Optional("app"): {
  308. Optional("config"): {
  309. Optional("id"): str,
  310. Optional("name"): str,
  311. Optional("log_level"): Or("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"),
  312. Optional("collect_metrics"): bool,
  313. Optional("collection_name"): str,
  314. }
  315. },
  316. Optional("llm"): {
  317. Optional("provider"): Or(
  318. "openai",
  319. "azure_openai",
  320. "anthropic",
  321. "huggingface",
  322. "cohere",
  323. "together",
  324. "gpt4all",
  325. "ollama",
  326. "jina",
  327. "llama2",
  328. "vertexai",
  329. "google",
  330. "aws_bedrock",
  331. "mistralai",
  332. "vllm",
  333. "groq",
  334. "nvidia",
  335. ),
  336. Optional("config"): {
  337. Optional("model"): str,
  338. Optional("model_name"): str,
  339. Optional("number_documents"): int,
  340. Optional("temperature"): float,
  341. Optional("max_tokens"): int,
  342. Optional("top_p"): Or(float, int),
  343. Optional("stream"): bool,
  344. Optional("template"): str,
  345. Optional("prompt"): str,
  346. Optional("system_prompt"): str,
  347. Optional("deployment_name"): str,
  348. Optional("where"): dict,
  349. Optional("query_type"): str,
  350. Optional("api_key"): str,
  351. Optional("endpoint"): str,
  352. Optional("model_kwargs"): dict,
  353. Optional("local"): bool,
  354. },
  355. },
  356. Optional("vectordb"): {
  357. Optional("provider"): Or(
  358. "chroma", "elasticsearch", "opensearch", "pinecone", "qdrant", "weaviate", "zilliz"
  359. ),
  360. Optional("config"): object, # TODO: add particular config schema for each provider
  361. },
  362. Optional("embedder"): {
  363. Optional("provider"): Or(
  364. "openai",
  365. "gpt4all",
  366. "huggingface",
  367. "vertexai",
  368. "azure_openai",
  369. "google",
  370. "mistralai",
  371. "nvidia",
  372. ),
  373. Optional("config"): {
  374. Optional("model"): Optional(str),
  375. Optional("deployment_name"): Optional(str),
  376. Optional("api_key"): str,
  377. Optional("title"): str,
  378. Optional("task_type"): str,
  379. Optional("vector_dimension"): int,
  380. },
  381. },
  382. Optional("embedding_model"): {
  383. Optional("provider"): Or(
  384. "openai",
  385. "gpt4all",
  386. "huggingface",
  387. "vertexai",
  388. "azure_openai",
  389. "google",
  390. "mistralai",
  391. "nvidia",
  392. ),
  393. Optional("config"): {
  394. Optional("model"): str,
  395. Optional("deployment_name"): str,
  396. Optional("api_key"): str,
  397. Optional("title"): str,
  398. Optional("task_type"): str,
  399. Optional("vector_dimension"): int,
  400. },
  401. },
  402. Optional("chunker"): {
  403. Optional("chunk_size"): int,
  404. Optional("chunk_overlap"): int,
  405. Optional("length_function"): str,
  406. Optional("min_chunk_size"): int,
  407. },
  408. Optional("cache"): {
  409. Optional("similarity_evaluation"): {
  410. Optional("strategy"): Or("distance", "exact"),
  411. Optional("max_distance"): float,
  412. Optional("positive"): bool,
  413. },
  414. Optional("config"): {
  415. Optional("similarity_threshold"): float,
  416. Optional("auto_flush"): int,
  417. },
  418. },
  419. }
  420. )
  421. return schema.validate(config_data)
  422. def chunks(iterable, batch_size=100, desc="Processing chunks"):
  423. """A helper function to break an iterable into chunks of size batch_size."""
  424. it = iter(iterable)
  425. total_size = len(iterable)
  426. with tqdm(total=total_size, desc=desc, unit="batch") as pbar:
  427. chunk = tuple(itertools.islice(it, batch_size))
  428. while chunk:
  429. yield chunk
  430. pbar.update(len(chunk))
  431. chunk = tuple(itertools.islice(it, batch_size))