sitemap.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import concurrent.futures
  2. import hashlib
  3. import logging
  4. import requests
  5. from tqdm import tqdm
  6. try:
  7. from bs4 import BeautifulSoup
  8. from bs4.builder import ParserRejectedMarkup
  9. except ImportError:
  10. raise ImportError(
  11. 'Sitemap requires extra dependencies. Install with `pip install --upgrade "embedchain[dataloaders]"`'
  12. ) from None
  13. from embedchain.helpers.json_serializable import register_deserializable
  14. from embedchain.loaders.base_loader import BaseLoader
  15. from embedchain.loaders.web_page import WebPageLoader
  16. from embedchain.utils import is_readable
  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. response = requests.get(sitemap_url)
  28. response.raise_for_status()
  29. soup = BeautifulSoup(response.text, "xml")
  30. links = [link.text for link in soup.find_all("loc") if link.parent.name == "url"]
  31. if len(links) == 0:
  32. links = [link.text for link in soup.find_all("loc")]
  33. doc_id = hashlib.sha256((" ".join(links) + sitemap_url).encode()).hexdigest()
  34. def load_link(link):
  35. try:
  36. each_load_data = web_page_loader.load_data(link)
  37. if is_readable(each_load_data.get("data")[0].get("content")):
  38. return each_load_data.get("data")
  39. else:
  40. logging.warning(f"Page is not readable (too many invalid characters): {link}")
  41. except ParserRejectedMarkup as e:
  42. logging.error(f"Failed to parse {link}: {e}")
  43. return None
  44. with concurrent.futures.ThreadPoolExecutor() as executor:
  45. future_to_link = {executor.submit(load_link, link): link for link in links}
  46. for future in tqdm(concurrent.futures.as_completed(future_to_link), total=len(links), desc="Loading pages"):
  47. link = future_to_link[future]
  48. try:
  49. data = future.result()
  50. if data:
  51. output.extend(data)
  52. except Exception as e:
  53. logging.error(f"Error loading page {link}: {e}")
  54. return {"doc_id": doc_id, "data": output}