sitemap.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import concurrent.futures
  2. import hashlib
  3. import logging
  4. import os
  5. from urllib.parse import urlparse
  6. import requests
  7. from tqdm import tqdm
  8. try:
  9. from bs4 import BeautifulSoup
  10. from bs4.builder import ParserRejectedMarkup
  11. except ImportError:
  12. raise ImportError(
  13. "Sitemap requires extra dependencies. Install with `pip install beautifulsoup4==4.12.3`"
  14. ) from None
  15. from embedchain.helpers.json_serializable import register_deserializable
  16. from embedchain.loaders.base_loader import BaseLoader
  17. from embedchain.loaders.web_page import WebPageLoader
  18. logger = logging.getLogger(__name__)
  19. @register_deserializable
  20. class SitemapLoader(BaseLoader):
  21. """
  22. This method takes a sitemap URL or local file path as input and retrieves
  23. all the URLs to use the WebPageLoader to load content
  24. of each page.
  25. """
  26. def load_data(self, sitemap_source):
  27. output = []
  28. web_page_loader = WebPageLoader()
  29. headers = {
  30. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36", # noqa:E501
  31. }
  32. if urlparse(sitemap_source).scheme in ("http", "https"):
  33. try:
  34. response = requests.get(sitemap_source, headers=headers)
  35. response.raise_for_status()
  36. soup = BeautifulSoup(response.text, "xml")
  37. except requests.RequestException as e:
  38. logger.error(f"Error fetching sitemap from URL: {e}")
  39. return
  40. elif os.path.isfile(sitemap_source):
  41. with open(sitemap_source, "r") as file:
  42. soup = BeautifulSoup(file, "xml")
  43. else:
  44. raise ValueError("Invalid sitemap source. Please provide a valid URL or local file path.")
  45. links = [link.text for link in soup.find_all("loc") if link.parent.name == "url"]
  46. if len(links) == 0:
  47. links = [link.text for link in soup.find_all("loc")]
  48. doc_id = hashlib.sha256((" ".join(links) + sitemap_source).encode()).hexdigest()
  49. def load_web_page(link):
  50. try:
  51. loader_data = web_page_loader.load_data(link)
  52. return loader_data.get("data")
  53. except ParserRejectedMarkup as e:
  54. logger.error(f"Failed to parse {link}: {e}")
  55. return None
  56. with concurrent.futures.ThreadPoolExecutor() as executor:
  57. future_to_link = {executor.submit(load_web_page, link): link for link in links}
  58. for future in tqdm(concurrent.futures.as_completed(future_to_link), total=len(links), desc="Loading pages"):
  59. link = future_to_link[future]
  60. try:
  61. data = future.result()
  62. if data:
  63. output.extend(data)
  64. except Exception as e:
  65. logger.error(f"Error loading page {link}: {e}")
  66. return {"doc_id": doc_id, "data": output}