sitemap.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 --upgrade "embedchain[dataloaders]"`'
  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. @register_deserializable
  19. class SitemapLoader(BaseLoader):
  20. """
  21. This method takes a sitemap URL or local file path as input and retrieves
  22. all the URLs to use the WebPageLoader to load content
  23. of each page.
  24. """
  25. def load_data(self, sitemap_source):
  26. output = []
  27. web_page_loader = WebPageLoader()
  28. headers = {
  29. "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
  30. }
  31. if urlparse(sitemap_source).scheme in ("http", "https"):
  32. try:
  33. response = requests.get(sitemap_source, headers=headers)
  34. response.raise_for_status()
  35. soup = BeautifulSoup(response.text, "xml")
  36. except requests.RequestException as e:
  37. logging.error(f"Error fetching sitemap from URL: {e}")
  38. return
  39. elif os.path.isfile(sitemap_source):
  40. with open(sitemap_source, "r") as file:
  41. soup = BeautifulSoup(file, "xml")
  42. else:
  43. raise ValueError("Invalid sitemap source. Please provide a valid URL or local file path.")
  44. links = [link.text for link in soup.find_all("loc") if link.parent.name == "url"]
  45. if len(links) == 0:
  46. links = [link.text for link in soup.find_all("loc")]
  47. doc_id = hashlib.sha256((" ".join(links) + sitemap_source).encode()).hexdigest()
  48. def load_web_page(link):
  49. try:
  50. loader_data = web_page_loader.load_data(link)
  51. return loader_data.get("data")
  52. except ParserRejectedMarkup as e:
  53. logging.error(f"Failed to parse {link}: {e}")
  54. return None
  55. with concurrent.futures.ThreadPoolExecutor() as executor:
  56. future_to_link = {executor.submit(load_web_page, link): link for link in links}
  57. for future in tqdm(concurrent.futures.as_completed(future_to_link), total=len(links), desc="Loading pages"):
  58. link = future_to_link[future]
  59. try:
  60. data = future.result()
  61. if data:
  62. output.extend(data)
  63. except Exception as e:
  64. logging.error(f"Error loading page {link}: {e}")
  65. return {"doc_id": doc_id, "data": output}