docs_site_loader.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import hashlib
  2. import logging
  3. from urllib.parse import urljoin, urlparse
  4. import requests
  5. try:
  6. from bs4 import BeautifulSoup
  7. except ImportError:
  8. raise ImportError(
  9. 'DocsSite requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
  10. ) from None
  11. from embedchain.helpers.json_serializable import register_deserializable
  12. from embedchain.loaders.base_loader import BaseLoader
  13. @register_deserializable
  14. class DocsSiteLoader(BaseLoader):
  15. def __init__(self):
  16. self.visited_links = set()
  17. def _get_child_links_recursive(self, url):
  18. parsed_url = urlparse(url)
  19. base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
  20. current_path = parsed_url.path
  21. response = requests.get(url)
  22. if response.status_code != 200:
  23. logging.info(f"Failed to fetch the website: {response.status_code}")
  24. return
  25. soup = BeautifulSoup(response.text, "html.parser")
  26. all_links = [link.get("href") for link in soup.find_all("a")]
  27. child_links = [link for link in all_links if link and link.startswith(current_path) and link != current_path]
  28. absolute_paths = [urljoin(base_url, link) for link in child_links]
  29. for link in absolute_paths:
  30. if link not in self.visited_links:
  31. self.visited_links.add(link)
  32. self._get_child_links_recursive(link)
  33. def _get_all_urls(self, url):
  34. self.visited_links = set()
  35. self._get_child_links_recursive(url)
  36. urls = [link for link in self.visited_links if urlparse(link).netloc == urlparse(url).netloc]
  37. return urls
  38. @staticmethod
  39. def _load_data_from_url(url: str) -> list:
  40. response = requests.get(url)
  41. if response.status_code != 200:
  42. logging.info(f"Failed to fetch the website: {response.status_code}")
  43. return []
  44. soup = BeautifulSoup(response.content, "html.parser")
  45. selectors = [
  46. "article.bd-article",
  47. 'article[role="main"]',
  48. "div.md-content",
  49. 'div[role="main"]',
  50. "div.container",
  51. "div.section",
  52. "article",
  53. "main",
  54. ]
  55. output = []
  56. for selector in selectors:
  57. element = soup.select_one(selector)
  58. if element:
  59. content = element.prettify()
  60. break
  61. else:
  62. content = soup.get_text()
  63. soup = BeautifulSoup(content, "html.parser")
  64. ignored_tags = [
  65. "nav",
  66. "aside",
  67. "form",
  68. "header",
  69. "noscript",
  70. "svg",
  71. "canvas",
  72. "footer",
  73. "script",
  74. "style",
  75. ]
  76. for tag in soup(ignored_tags):
  77. tag.decompose()
  78. content = " ".join(soup.stripped_strings)
  79. output.append(
  80. {
  81. "content": content,
  82. "meta_data": {"url": url},
  83. }
  84. )
  85. return output
  86. def load_data(self, url):
  87. all_urls = self._get_all_urls(url)
  88. output = []
  89. for u in all_urls:
  90. output.extend(self._load_data_from_url(u))
  91. doc_id = hashlib.sha256((" ".join(all_urls) + url).encode()).hexdigest()
  92. return {
  93. "doc_id": doc_id,
  94. "data": output,
  95. }