sitemap.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import concurrent.futures
  2. import hashlib
  3. import logging
  4. from urllib.parse import urlparse
  5. import requests
  6. from tqdm import tqdm
  7. try:
  8. from bs4 import BeautifulSoup
  9. from bs4.builder import ParserRejectedMarkup
  10. except ImportError:
  11. raise ImportError(
  12. 'Sitemap requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
  13. ) from None
  14. from embedchain.helpers.json_serializable import register_deserializable
  15. from embedchain.loaders.base_loader import BaseLoader
  16. from embedchain.loaders.web_page import WebPageLoader
  17. @register_deserializable
  18. class SitemapLoader(BaseLoader):
  19. """
  20. This method takes a sitemap URL as input and retrieves
  21. all the URLs to use the WebPageLoader to load content
  22. of each page.
  23. """
  24. def load_data(self, sitemap_url):
  25. output = []
  26. web_page_loader = WebPageLoader()
  27. if urlparse(sitemap_url).scheme not in ["file", "http", "https"]:
  28. raise ValueError("Not a valid URL.")
  29. if urlparse(sitemap_url).scheme in ["http", "https"]:
  30. response = requests.get(sitemap_url)
  31. response.raise_for_status()
  32. soup = BeautifulSoup(response.text, "xml")
  33. else:
  34. with open(sitemap_url, "r") as file:
  35. soup = BeautifulSoup(file, "xml")
  36. links = [link.text for link in soup.find_all("loc") if link.parent.name == "url"]
  37. if len(links) == 0:
  38. links = [link.text for link in soup.find_all("loc")]
  39. doc_id = hashlib.sha256((" ".join(links) + sitemap_url).encode()).hexdigest()
  40. def load_web_page(link):
  41. try:
  42. loader_data = web_page_loader.load_data(link)
  43. return loader_data.get("data")
  44. except ParserRejectedMarkup as e:
  45. logging.error(f"Failed to parse {link}: {e}")
  46. return None
  47. with concurrent.futures.ThreadPoolExecutor() as executor:
  48. future_to_link = {executor.submit(load_web_page, link): link for link in links}
  49. for future in tqdm(concurrent.futures.as_completed(future_to_link), total=len(links), desc="Loading pages"):
  50. link = future_to_link[future]
  51. try:
  52. data = future.result()
  53. if data:
  54. output.extend(data)
  55. except Exception as e:
  56. logging.error(f"Error loading page {link}: {e}")
  57. return {"doc_id": doc_id, "data": output}