scrapeMM 0.3.2__tar.gz → 0.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {scrapemm-0.3.2 → scrapemm-0.3.4}/.gitignore +4 -1
  2. {scrapemm-0.3.2/scrapeMM.egg-info → scrapemm-0.3.4}/PKG-INFO +3 -3
  3. {scrapemm-0.3.2 → scrapemm-0.3.4}/README.md +2 -2
  4. {scrapemm-0.3.2 → scrapemm-0.3.4}/pyproject.toml +1 -1
  5. {scrapemm-0.3.2 → scrapemm-0.3.4/scrapeMM.egg-info}/PKG-INFO +3 -3
  6. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/fb.py +28 -39
  7. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/instagram.py +16 -22
  8. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/tiktok.py +4 -15
  9. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/youtube.py +5 -11
  10. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/retrieval.py +2 -2
  11. scrapemm-0.3.4/scrapemm/scraping/decodo.py +216 -0
  12. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/scraping/firecrawl.py +5 -2
  13. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/scraping/util.py +22 -5
  14. scrapemm-0.3.4/scrapemm/scraping/ytdlp.py +114 -0
  15. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/secrets.py +2 -2
  16. {scrapemm-0.3.2 → scrapemm-0.3.4}/scripts/example.py +1 -1
  17. {scrapemm-0.3.2 → scrapemm-0.3.4}/testing/test_retrieval.py +41 -15
  18. scrapemm-0.3.2/scrapemm/scraping/decodo.py +0 -191
  19. scrapemm-0.3.2/scrapemm/scraping/ytdlp.py +0 -203
  20. {scrapemm-0.3.2 → scrapemm-0.3.4}/LICENSE +0 -0
  21. {scrapemm-0.3.2 → scrapemm-0.3.4}/requirements.txt +0 -0
  22. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapeMM.egg-info/SOURCES.txt +0 -0
  23. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapeMM.egg-info/dependency_links.txt +0 -0
  24. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapeMM.egg-info/requires.txt +0 -0
  25. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapeMM.egg-info/top_level.txt +0 -0
  26. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/__init__.py +0 -0
  27. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/common.py +0 -0
  28. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/__init__.py +0 -0
  29. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/base.py +0 -0
  30. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/bluesky.py +0 -0
  31. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/telegram.py +0 -0
  32. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/integrations/x.py +0 -0
  33. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/scraping/__init__.py +0 -0
  34. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/scraping/no_bot_domains.txt +0 -0
  35. {scrapemm-0.3.2 → scrapemm-0.3.4}/scrapemm/util.py +0 -0
  36. {scrapemm-0.3.2 → scrapemm-0.3.4}/setup.cfg +0 -0
  37. {scrapemm-0.3.2 → scrapemm-0.3.4}/testing/test_utils.py +0 -0
@@ -4,4 +4,7 @@
4
4
  /dist/
5
5
  /config.yaml
6
6
  __pycache__/
7
- .DS_Store
7
+ .DS_Store
8
+ build/
9
+ .pytest_cache/
10
+ .claude/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapeMM
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: LLM-friendly scraper for media and text from social media and the open web.
5
5
  Author-email: Mark Rothermel <mark.rothermel@tu-darmstadt.de>
6
6
  License-Expression: Apache-2.0
@@ -54,8 +54,8 @@ Web scraping is done with [Firecrawl](https://github.com/mendableai/firecrawl) a
54
54
  - ✅ Telegram
55
55
  - ✅ Bluesky
56
56
  - ✅ TikTok
57
- - ⚠️ Facebook (working only sometimes and only with yt-dlp and Decodo)
57
+ - YouTube (working sometimes)
58
+ - ⚠️ Facebook (done for videos but not for images yet)
58
59
  - ⚠️ Instagram (done for videos but not for images yet)
59
- - ⚠️ YouTube (working sometimes)
60
60
  - ⏳ Threads
61
61
  - ⏳ Reddit
@@ -30,8 +30,8 @@ Web scraping is done with [Firecrawl](https://github.com/mendableai/firecrawl) a
30
30
  - ✅ Telegram
31
31
  - ✅ Bluesky
32
32
  - ✅ TikTok
33
- - ⚠️ Facebook (working only sometimes and only with yt-dlp and Decodo)
33
+ - YouTube (working sometimes)
34
+ - ⚠️ Facebook (done for videos but not for images yet)
34
35
  - ⚠️ Instagram (done for videos but not for images yet)
35
- - ⚠️ YouTube (working sometimes)
36
36
  - ⏳ Threads
37
37
  - ⏳ Reddit
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "scrapeMM"
3
- version = "0.3.2"
3
+ version = "0.3.4"
4
4
  description = "LLM-friendly scraper for media and text from social media and the open web."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapeMM
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: LLM-friendly scraper for media and text from social media and the open web.
5
5
  Author-email: Mark Rothermel <mark.rothermel@tu-darmstadt.de>
6
6
  License-Expression: Apache-2.0
@@ -54,8 +54,8 @@ Web scraping is done with [Firecrawl](https://github.com/mendableai/firecrawl) a
54
54
  - ✅ Telegram
55
55
  - ✅ Bluesky
56
56
  - ✅ TikTok
57
- - ⚠️ Facebook (working only sometimes and only with yt-dlp and Decodo)
57
+ - YouTube (working sometimes)
58
+ - ⚠️ Facebook (done for videos but not for images yet)
58
59
  - ⚠️ Instagram (done for videos but not for images yet)
59
- - ⚠️ YouTube (working sometimes)
60
60
  - ⏳ Threads
61
61
  - ⏳ Reddit
@@ -1,55 +1,52 @@
1
1
  import logging
2
+ import re
2
3
  from urllib.parse import urlparse
4
+
3
5
  import aiohttp
4
- from ezmm import MultimodalSequence, download_image
6
+ from ezmm import MultimodalSequence
5
7
 
6
- from scrapemm.scraping.ytdlp import check_ytdlp_available, get_video_with_ytdlp
7
8
  from scrapemm.integrations.base import RetrievalIntegration
9
+ from scrapemm.scraping.ytdlp import get_content_with_ytdlp
8
10
  from scrapemm.util import get_domain
9
11
 
10
12
  logger = logging.getLogger("scrapeMM")
11
13
 
14
+ VIDEO_URL_REGEX = r"facebook\.com/\d+/videos/\d+/?"
15
+
12
16
 
13
17
  class Facebook(RetrievalIntegration):
14
18
  name = "Facebook"
15
19
  domains = ["facebook.com", "www.facebook.com"]
16
20
 
17
21
  async def _connect(self):
18
- # Check if yt-dlp is available
19
- self.ytdlp_available = check_ytdlp_available()
20
-
21
- if self.ytdlp_available:
22
- self.connected = True
23
- mode = "yt-dlp only"
24
- logger.info(f"✅ Facebook integration ready ({mode} mode).")
25
- else:
26
- self.connected = False
27
- logger.warning("❌ Facebook integration not available: Neither API credentials nor yt-dlp found.")
22
+ self.api_available = False # TODO
23
+ logger.info(f"✅ Facebook integration ready (yt-dlp only mode).")
24
+ self.connected = True
28
25
 
29
26
  async def _get(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
30
27
  """Retrieves content from a Facebook post URL."""
31
28
  if get_domain(url) not in self.domains:
32
29
  logger.error(f"❌ Invalid domain for Facebook: {get_domain(url)}")
33
30
  return None
34
-
35
- # Determine if this is a video or profile URL
31
+
32
+ # Determine if this is a video or photo URL, act accordingly
36
33
  if self._is_video_url(url):
37
34
  return await self._get_video(url, session)
38
35
  elif self._is_photo_url(url):
39
36
  return await self._get_photo(url, session)
40
- else:
41
- return await self._get_user_profile(url, session)
42
-
43
- async def _get_video(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
44
- """Retrieves content from a TikTok video URL."""
45
37
 
46
- # Fallback to yt-dlp mode
47
- if self.ytdlp_available:
48
- return await get_video_with_ytdlp(url, session, platform="Facebook")
38
+ # The URL is not indicative, so try all methods
39
+ return (await self._get_video(url, session) or
40
+ await self._get_photo(url, session) or
41
+ await self._get_user_profile(url, session))
42
+
43
+ async def _get_video(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
44
+ """Retrieves content from a Facebook video URL."""
45
+ if self.api_available:
46
+ raise NotImplementedError
47
+ else:
48
+ return await get_content_with_ytdlp(url, session, platform="Facebook")
49
49
 
50
- logger.error("❌ No available method to retrieve Facebook video.")
51
- return None
52
-
53
50
  async def _get_photo(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
54
51
  """Retrieves content from a Facebook photo URL."""
55
52
  logger.error("❌ No available method to retrieve Facebook photo.")
@@ -57,23 +54,15 @@ class Facebook(RetrievalIntegration):
57
54
 
58
55
  async def _get_user_profile(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
59
56
  """Retrieves content from a Facebook user profile URL."""
60
- username = self._extract_username(url)
61
- if username:
62
- text = f"""**Facebook Profile**
63
- Username: @{username}
64
- URL: {url}
65
-
66
- Note: Profile details require Facebook API access.
67
- Configure API credentials for full profile information."""
68
- return MultimodalSequence([text])
69
-
57
+ logger.error("❌ No available method to retrieve Facebook profiles.")
70
58
  return None
71
59
 
72
60
  def _is_video_url(self, url: str) -> bool:
73
61
  """Checks if the URL is a Facebook video URL."""
74
62
  # video URLS are in the format: https://www.facebook.com/watch?v=VIDEO_ID
75
- return "facebook.com/watch" in url
76
-
63
+ # or Reels: https://www.facebook.com/reel/REEL_ID
64
+ return "facebook.com/watch" in url or "facebook.com/reel" in url or bool(re.search(VIDEO_URL_REGEX, url))
65
+
77
66
  def _extract_video_id(self, url: str) -> str:
78
67
  """Extracts the video ID from a Facebook video URL."""
79
68
  parsed_url = urlparse(url)
@@ -82,11 +71,11 @@ Configure API credentials for full profile information."""
82
71
  if param.startswith('v='):
83
72
  return param.split('=')[1]
84
73
  return ""
85
-
74
+
86
75
  def _is_photo_url(self, url: str) -> bool:
87
76
  """Checks if the URL is a Facebook photo URL."""
88
77
  return "facebook.com/photo" in url or "facebook.com/photos" in url
89
-
78
+
90
79
  def _extract_username(self, url: str) -> str:
91
80
  """Extracts the username from a Facebook profile URL."""
92
81
  # url format: https://www.facebook.com/username<?...>
@@ -1,10 +1,11 @@
1
1
  import logging
2
2
  from urllib.parse import urlparse
3
+
3
4
  import aiohttp
4
- from ezmm import MultimodalSequence, download_image
5
+ from ezmm import MultimodalSequence
5
6
 
6
- from scrapemm.scraping.ytdlp import check_ytdlp_available, get_video_with_ytdlp
7
7
  from scrapemm.integrations.base import RetrievalIntegration
8
+ from scrapemm.scraping.ytdlp import get_content_with_ytdlp
8
9
  from scrapemm.util import get_domain
9
10
 
10
11
  logger = logging.getLogger("scrapeMM")
@@ -15,44 +16,37 @@ class Instagram(RetrievalIntegration):
15
16
  domains = ["instagram.com", "www.instagram.com"]
16
17
 
17
18
  async def _connect(self):
18
- # Check if yt-dlp is available
19
- self.ytdlp_available = check_ytdlp_available()
20
-
21
- if self.ytdlp_available:
22
- self.connected = True
23
- mode = "yt-dlp only"
24
- logger.info(f"✅ Instagram integration ready ({mode} mode).")
25
- else:
26
- self.connected = False
27
- logger.warning("❌ Instagram integration not available: Neither API credentials nor yt-dlp found.")
19
+ self.api_available = False
20
+ logger.info(f"✅ Instagram integration ready (yt-dlp only mode).")
21
+ self.connected = True
28
22
 
29
23
  async def _get(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
30
24
  """Retrieves content from an Instagram post URL."""
31
25
  if get_domain(url) not in self.domains:
32
26
  logger.error(f"❌ Invalid domain for Instagram: {get_domain(url)}")
33
27
  return None
34
-
28
+
35
29
  # Determine if this is a video or profile URL
36
30
  if self._is_video_url(url):
37
31
  return await self._get_video(url, session)
38
32
  elif self._is_photo_url(url):
39
- return await self._get_photo(url, session)
33
+ # /p/ URLs can also be reels, so try both
34
+ return await self._get_video(url, session) or await self._get_photo(url, session)
40
35
  else:
41
36
  return await self._get_user_profile(url, session)
42
-
37
+
43
38
  async def _get_video(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
44
39
  """Retrieves content from an Instagram video URL."""
45
- if self.ytdlp_available:
46
- return await get_video_with_ytdlp(url, session, platform="Instagram")
40
+ if self.api_available:
41
+ raise NotImplementedError
42
+ else:
43
+ return await get_content_with_ytdlp(url, session, platform="Instagram")
47
44
 
48
- logger.error("❌ No available method to retrieve Instagram video.")
49
- return None
50
-
51
45
  async def _get_photo(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
52
- """Retrieves content from an Instagram photo URL."""
46
+ """Retrieves content from an Instagram photo URL (can also be a reel)."""
53
47
  logger.error("❌ No available method to retrieve Instagram photo.")
54
48
  return None
55
-
49
+
56
50
  async def _get_user_profile(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
57
51
  """Retrieves content from an Instagram user profile URL."""
58
52
  username = self._extract_username(url)
@@ -15,7 +15,6 @@ from ezmm.common.items import Video, Image
15
15
  from tiktok_research_api import TikTokResearchAPI, QueryVideoRequest, QueryUserInfoRequest, Criteria, Query
16
16
 
17
17
  from scrapemm.integrations.base import RetrievalIntegration
18
- from scrapemm.scraping.ytdlp import check_ytdlp_available
19
18
  from scrapemm.secrets import get_secret
20
19
 
21
20
  logger = logging.getLogger("scrapeMM")
@@ -57,16 +56,9 @@ class TikTok(RetrievalIntegration):
57
56
  except Exception as e:
58
57
  logger.info(f"⚠️ TikTok Research API connection failed: {e}. Using fallback mode.")
59
58
 
60
- # Check if yt-dlp is available
61
- self.ytdlp_available = check_ytdlp_available()
62
-
63
- if self.api_available or self.ytdlp_available:
64
- self.connected = True
65
- mode = "API + yt-dlp" if self.api_available else "yt-dlp only"
66
- logger.info(f"✅ TikTok integration ready ({mode} mode).")
67
- else:
68
- self.connected = False
69
- logger.warning("❌ TikTok integration not available: Neither API credentials nor yt-dlp found.")
59
+ mode = "API" if self.api_available else "yt-dlp only"
60
+ logger.info(f"✅ TikTok integration ready ({mode} mode).")
61
+ self.connected = True
70
62
 
71
63
  async def _get(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
72
64
  # Determine if this is a video or profile URL
@@ -86,12 +78,9 @@ class TikTok(RetrievalIntegration):
86
78
  logger.warning("API method failed, falling back to yt-dlp...")
87
79
 
88
80
  # Fallback to yt-dlp mode
89
- if self.ytdlp_available:
81
+ else:
90
82
  return await self._get_video_with_ytdlp(url, session)
91
83
 
92
- logger.error("❌ No available method to retrieve TikTok video.")
93
- return None
94
-
95
84
  async def _get_video_with_api(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence | None:
96
85
  """Retrieves video using TikTok Research API."""
97
86
  video_id = self._extract_video_id(url)
@@ -4,7 +4,7 @@ from typing import Optional
4
4
  import aiohttp
5
5
  from ezmm import MultimodalSequence
6
6
 
7
- from scrapemm.scraping.ytdlp import get_video_with_ytdlp, check_ytdlp_available
7
+ from scrapemm.scraping.ytdlp import get_content_with_ytdlp
8
8
  from .base import RetrievalIntegration
9
9
 
10
10
  logger = logging.getLogger("scrapeMM")
@@ -15,20 +15,14 @@ class YouTube(RetrievalIntegration):
15
15
 
16
16
  name = "YouTube"
17
17
  domains = [
18
- "youtube.com",
19
- "www.youtube.com",
20
- "youtu.be",
21
- "m.youtube.com"
18
+ "youtube.com",
19
+ "youtu.be",
22
20
  ]
23
21
 
24
22
  async def _connect(self):
25
- self.connected = check_ytdlp_available()
26
- if not self.connected:
27
- logger.warning("❌ YouTube integration disabled: yt-dlp not available")
28
- else:
29
- logger.info("✅ YouTube integration enabled")
23
+ self.connected = True
30
24
 
31
25
  async def _get(self, url: str, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
32
26
  """Downloads YouTube video or short using yt-dlp."""
33
27
  logger.debug(f"📺 Downloading YouTube content: {url}")
34
- return await get_video_with_ytdlp(url, session, "YouTube")
28
+ return await get_content_with_ytdlp(url, session, "YouTube")
@@ -1,5 +1,5 @@
1
1
  import logging
2
- from typing import Optional
2
+ from typing import Optional, Collection
3
3
  from traceback import format_exc
4
4
 
5
5
  import aiohttp
@@ -14,7 +14,7 @@ METHODS = ["integrations", "firecrawl", "decodo"]
14
14
 
15
15
 
16
16
  async def retrieve(
17
- urls: str | list[str],
17
+ urls: str | Collection[str],
18
18
  remove_urls: bool = False,
19
19
  show_progress: bool = True,
20
20
  actions: list[dict] = None,
@@ -0,0 +1,216 @@
1
+ import asyncio
2
+ import logging
3
+ from typing import Optional
4
+
5
+ import aiohttp
6
+ from ezmm import MultimodalSequence
7
+
8
+ from scrapemm.secrets import get_secret
9
+ from scrapemm.scraping.util import to_multimodal_sequence, get_domain_root
10
+
11
+ logger = logging.getLogger("scrapeMM")
12
+
13
+
14
+ class Decodo:
15
+ """Scrapes web content using Decodo's Web Scraping API with proxy support
16
+ and JavaScript rendering capabilities."""
17
+
18
+ DECODO_API_URL = "https://scraper-api.decodo.com/v2/scrape"
19
+
20
+ def __init__(self):
21
+ self.username = None
22
+ self.password = None
23
+ self.n_scrapes = 0
24
+
25
+ def _load_credentials(self):
26
+ """Loads Decodo credentials from the secrets manager."""
27
+ self.username = get_secret("decodo_username")
28
+ self.password = get_secret("decodo_password")
29
+
30
+ if self.username and self.password:
31
+ logger.info("✅ Decodo credentials loaded successfully.")
32
+ else:
33
+ logger.warning("⚠️ Decodo credentials not found. Please configure them in secrets.")
34
+
35
+ def _has_credentials(self) -> bool:
36
+ """Checks if Decodo credentials are available."""
37
+ return bool(self.username and self.password)
38
+
39
+ async def scrape(
40
+ self, url: str,
41
+ remove_urls: bool,
42
+ session: aiohttp.ClientSession,
43
+ format: str,
44
+ enable_js: bool = True,
45
+ timeout: int = 30,
46
+ ) -> Optional[MultimodalSequence | str]:
47
+ """Downloads the contents of the specified webpage using Decodo's API.
48
+
49
+ Args:
50
+ url: The URL to scrape
51
+ remove_urls: Whether to remove URLs from hyperlinks in the result
52
+ session: The aiohttp ClientSession to use
53
+ enable_js: Whether to enable JavaScript rendering (default: True)
54
+ timeout: Request timeout in seconds (default: 30)
55
+
56
+ Returns:
57
+ MultimodalSequence containing the scraped content, or None if scraping failed
58
+ """
59
+ if not self._has_credentials():
60
+ self._load_credentials()
61
+
62
+ if not self._has_credentials():
63
+ logger.warning("Cannot scrape with Decodo: credentials not configured.")
64
+ return None
65
+
66
+ # Try with JS rendering first if enabled
67
+ html = await self._call_decodo(url, session, enable_js, timeout)
68
+
69
+ # If it failed with JS and we got a 400 error, try without JS
70
+ # (400 might mean the plan doesn't support headless rendering)
71
+ if html is None and enable_js:
72
+ logger.debug("Retrying without JavaScript rendering...")
73
+ html = await self._call_decodo(url, session, enable_js=False, timeout=timeout)
74
+
75
+ if html:
76
+ if format == "html":
77
+ return html
78
+ else:
79
+ domain_root = get_domain_root(url)
80
+ return await to_multimodal_sequence(html, remove_urls=remove_urls, session=session, domain_root=domain_root)
81
+ return None
82
+
83
+ async def _call_decodo(
84
+ self, url: str,
85
+ session: aiohttp.ClientSession,
86
+ enable_js: bool = True,
87
+ timeout: int = 30,
88
+ max_retries: int = 5
89
+ ) -> Optional[str]:
90
+ """Calls the Decodo API to scrape the given URL with exponential backoff retry logic.
91
+
92
+ Args:
93
+ url: The URL to scrape
94
+ session: The aiohttp ClientSession to use
95
+ enable_js: Whether to enable JavaScript rendering
96
+ timeout: Request timeout in seconds
97
+ max_retries: Maximum number of retry attempts for rate limits (default: 5)
98
+
99
+ Returns:
100
+ HTML content as a string, or None if scraping failed
101
+ """
102
+ headers = {
103
+ 'Content-Type': 'application/json',
104
+ }
105
+
106
+ # Build request payload
107
+ # Note: For simple URL scraping, we just provide the URL
108
+ # The "target" parameter is only used for specific templates like "google_search"
109
+ payload = {
110
+ "url": url,
111
+ }
112
+
113
+ # Enable JavaScript rendering if requested
114
+ # Note: This requires an Advanced plan subscription
115
+ if enable_js:
116
+ payload["headless"] = "html"
117
+
118
+ # Create basic auth
119
+ auth = aiohttp.BasicAuth(self.username, self.password)
120
+
121
+ # Retry loop with exponential backoff
122
+ for attempt in range(max_retries + 1):
123
+ try:
124
+ async with session.post(
125
+ self.DECODO_API_URL,
126
+ json=payload,
127
+ headers=headers,
128
+ auth=auth,
129
+ timeout=aiohttp.ClientTimeout(total=timeout)
130
+ ) as response:
131
+ # Validate response health
132
+ if response.status != 200:
133
+ logger.debug("Communication with Decodo API failed.")
134
+
135
+ # Handle rate limiting and 613 errors with retry
136
+ if response.status in (429, 613):
137
+ if attempt < max_retries:
138
+ # Exponential backoff: 2^attempt seconds (1s, 2s, 4s, 8s, 16s)
139
+ wait_time = 2 ** attempt
140
+ error_msg = "Rate limit exceeded" if response.status == 429 else "Error 613"
141
+ logger.warning(f"Error {response.status}: {error_msg}. Retrying in {wait_time}s (attempt {attempt + 1}/{max_retries})...")
142
+ await asyncio.sleep(wait_time)
143
+ continue
144
+ else:
145
+ logger.warning(f"Error {response.status}: Maximum retries reached.")
146
+ return None
147
+
148
+ # Log other errors
149
+ match response.status:
150
+ case 400:
151
+ logger.debug("Error 400: Bad request. If you use JavaScript, make sure you have the "
152
+ "Advanced plan subscription.")
153
+ case 401:
154
+ logger.error("Error 401: Unauthorized. Check your Decodo credentials.")
155
+ case 402:
156
+ logger.error("Error 402: Payment required. Check your Decodo subscription.")
157
+ case 403:
158
+ logger.debug("Error 403: Forbidden.")
159
+ case 408:
160
+ logger.warning("Error 408: Timeout! Website did not respond in time.")
161
+ case 500:
162
+ logger.debug("Error 500: Server error.")
163
+ case _:
164
+ logger.debug(f"Error {response.status}: {response.reason}.")
165
+
166
+ return None
167
+
168
+ # Parse response
169
+ json_response = await response.json()
170
+
171
+ # Validate if scrape was successful
172
+ if json_response.get("status") == "failed":
173
+ status_code = json_response.get("status_code")
174
+ message = json_response.get("message")
175
+ logger.info(f"Decodo failed to scrape. Error {status_code}: {message}")
176
+ return None
177
+
178
+ # Extract HTML content from results
179
+ if "results" in json_response and len(json_response["results"]) > 0:
180
+ result = json_response["results"][0]
181
+
182
+ # Check status code from the actual request
183
+ status_code = result.get("status_code")
184
+ if status_code and status_code >= 400:
185
+ logger.warning(f"Target website returned status {status_code} for {url}")
186
+ return None
187
+
188
+ html_content = result.get("content")
189
+ if html_content:
190
+ self.n_scrapes += 1
191
+ logger.debug(f"Successfully scraped {url} with Decodo (scrape #{self.n_scrapes})")
192
+ return html_content
193
+ else:
194
+ logger.warning(f"No content in Decodo response for {url}")
195
+ return None
196
+ else:
197
+ logger.warning(f"No results in Decodo response for {url}")
198
+ logger.debug(f"Response: {json_response}")
199
+ return None
200
+
201
+ except aiohttp.ClientError as e:
202
+ logger.error(f"Network error while scraping {url} with Decodo: {repr(e)}")
203
+ return None
204
+ except asyncio.TimeoutError:
205
+ logger.warning(f"Timeout while scraping {url} with Decodo. Skipping...")
206
+ return None
207
+ except Exception as e:
208
+ logger.error(f"Unexpected error while scraping {url} with Decodo: {repr(e)}")
209
+ return None
210
+
211
+ # Should not reach here, but return None as fallback
212
+ return None
213
+
214
+
215
+ # Create a singleton instance
216
+ decodo = Decodo()
@@ -7,7 +7,7 @@ from ezmm import MultimodalSequence
7
7
 
8
8
  from scrapemm.common import get_config_var, update_config
9
9
  from scrapemm.util import read_urls_from_file, get_domain
10
- from scrapemm.scraping.util import find_firecrawl, to_multimodal_sequence, firecrawl_is_running
10
+ from scrapemm.scraping.util import find_firecrawl, to_multimodal_sequence, firecrawl_is_running, get_domain_root
11
11
 
12
12
  logger = logging.getLogger("scrapeMM")
13
13
 
@@ -58,6 +58,7 @@ class Firecrawl:
58
58
 
59
59
  def connect(self):
60
60
  from firecrawl import AsyncFirecrawl
61
+ logging.getLogger("firecrawl").setLevel(logging.WARNING)
61
62
  self.firecrawl_url = locate_firecrawl()
62
63
  self._firecrawl = AsyncFirecrawl(api_url=self.firecrawl_url)
63
64
 
@@ -88,7 +89,9 @@ class Firecrawl:
88
89
  if format == "html":
89
90
  return html
90
91
  else:
91
- return await to_multimodal_sequence(html, remove_urls=remove_urls, session=session)
92
+ domain_root = get_domain_root(url)
93
+ return await to_multimodal_sequence(html, remove_urls=remove_urls, session=session, domain_root=domain_root)
94
+ return None
92
95
 
93
96
 
94
97
  fire = Firecrawl()
@@ -54,6 +54,7 @@ def postprocess_scraped(text: str) -> str:
54
54
 
55
55
  async def resolve_media_hyperlinks(
56
56
  text: str, session: aiohttp.ClientSession,
57
+ domain_root: str = None,
57
58
  remove_urls: bool = False,
58
59
  ) -> Optional[MultimodalSequence]:
59
60
  """Downloads all media that are hyperlinked in the provided Markdown text.
@@ -65,19 +66,21 @@ async def resolve_media_hyperlinks(
65
66
 
66
67
  # Extract URLs and base64-encoded data from the text
67
68
  hyperlinks = get_markdown_hyperlinks(text)
68
- urls = set()
69
+ hrefs_urls = dict()
69
70
  data_uris = set()
70
71
  for _, _, href in hyperlinks:
71
72
  if is_url(href):
72
- urls.add(href)
73
+ hrefs_urls[href] = href
74
+ elif domain_root and is_root_relative_url(href):
75
+ hrefs_urls[href] = f"{domain_root}{href}"
73
76
  elif is_data_uri(href):
74
77
  data_uris.add(href)
75
78
 
76
79
  # Try to download media for each URL
77
- tasks = [download_item(url, session=session) for url in urls]
80
+ tasks = [download_item(url, session=session) for url in hrefs_urls.values()]
78
81
  media: list[Item | None] = await run_with_semaphore(tasks, limit=100, show_progress=False)
79
82
 
80
- href_media = dict(zip(urls, media))
83
+ href_media = dict(zip(hrefs_urls.keys(), media))
81
84
 
82
85
  # Convert each base64-encoded data to the respective medium
83
86
  for data_uri in data_uris:
@@ -102,15 +105,29 @@ async def resolve_media_hyperlinks(
102
105
 
103
106
 
104
107
  def is_url(href: str) -> bool:
105
- """Returns True iff the given string is a valid URL."""
108
+ """Returns True iff the given string is an absolute HTTP URL."""
106
109
  return re.match(URL_REGEX, href) is not None
107
110
 
108
111
 
112
+ def is_root_relative_url(href: str) -> bool:
113
+ """Returns True iff the given string is a root-relative URL."""
114
+ return href.startswith("/")
115
+
116
+
109
117
  def is_data_uri(href: str) -> bool:
110
118
  """Returns True iff the given string is a valid data URI."""
111
119
  return re.match(DATA_URI_REGEX, href) is not None
112
120
 
113
121
 
122
+ def get_domain_root(url: str) -> Optional[str]:
123
+ """Extracts the domain root from the given URL. Allows for missing http(s) prefix."""
124
+ match = re.match(r"(:?https?://)?([^/]+)", url)
125
+ if match:
126
+ return match.group(0)
127
+ else:
128
+ return None
129
+
130
+
114
131
  def get_markdown_hyperlinks(text: str) -> list[tuple[str, str, str]]:
115
132
  """Extracts all web hyperlinks from the given markdown-formatted string. Returns
116
133
  a list of fullmatch-hypertext-URL-triples."""