misc.py 19 KB

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