scrapeMM 0.1.0__py3-none-any.whl

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.
scrapemm/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .retrieval import retrieve
2
+ from .integrations import Telegram, X
scrapemm/common.py ADDED
@@ -0,0 +1,30 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ from scrapemm.util import get_domain
5
+ import logging
6
+
7
+ logger = logging.getLogger("Retriever")
8
+ logger.setLevel(logging.DEBUG)
9
+
10
+ # Only add handler if none exists (avoid duplicate logs on rerun)
11
+ if not logger.hasHandlers():
12
+ handler = logging.StreamHandler(sys.stdout)
13
+ formatter = logging.Formatter('[%(levelname)s]: %(message)s')
14
+ handler.setFormatter(formatter)
15
+ logger.addHandler(handler)
16
+
17
+
18
+ def is_unsupported_site(url: str) -> bool:
19
+ """Checks if the URL belongs to a known unsupported website."""
20
+ domain = get_domain(url)
21
+ return domain is None or domain.endswith(".gov") or domain in unsupported_domains
22
+
23
+
24
+ def read_urls_from_file(file_path):
25
+ with open(file_path, 'r') as f:
26
+ return f.read().splitlines()
27
+
28
+
29
+ unsupported_domains_file = Path(__file__).parent / "unsupported_domains.txt"
30
+ unsupported_domains = read_urls_from_file(unsupported_domains_file)
@@ -0,0 +1,20 @@
1
+ from typing import Optional
2
+
3
+ import aiohttp
4
+ from ezmm import MultimodalSequence
5
+
6
+ from scrapemm.util import get_domain
7
+ from .telegram import Telegram
8
+ from .x import X
9
+
10
+ RETRIEVAL_INTEGRATIONS = [X(), Telegram()]
11
+ DOMAIN_TO_INTEGRATION = {domain: integration
12
+ for integration in RETRIEVAL_INTEGRATIONS
13
+ for domain in integration.domains}
14
+
15
+
16
+ async def retrieve_via_integration(url: str, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
17
+ domain = get_domain(url)
18
+ if domain in DOMAIN_TO_INTEGRATION:
19
+ integration = DOMAIN_TO_INTEGRATION[domain]
20
+ return await integration.get(url, session)
@@ -0,0 +1,13 @@
1
+ import aiohttp
2
+ from ezmm import MultimodalSequence
3
+
4
+
5
+ class RetrievalIntegration:
6
+ """Any integration used to retrieve information via a proprietary API, i.e., where
7
+ direct URL scraping is not possible."""
8
+
9
+ domains: list[str] # The domains supported by this integration
10
+
11
+ async def get(self, url: str, session: aiohttp.ClientSession) -> MultimodalSequence:
12
+ """Retrieves the contents present at the given URL."""
13
+ raise NotImplementedError
@@ -0,0 +1,124 @@
1
+ import asyncio
2
+ import logging
3
+ from typing import Optional
4
+ from urllib.parse import urlparse
5
+
6
+ import aiohttp
7
+ from ezmm import MultimodalSequence, Image, Item, Video
8
+ from telethon import TelegramClient
9
+ from telethon.tl.types import Channel, User
10
+
11
+ from config import telegram_api_id, telegram_api_hash, telegram_bot_token
12
+ from scrapemm.integrations.base import RetrievalIntegration
13
+ from scrapemm.util import get_domain
14
+
15
+ logger = logging.getLogger("Retriever")
16
+
17
+
18
+ class Telegram(RetrievalIntegration):
19
+ """The Telegram integration for retrieving post contents from Telegram channels and groups."""
20
+
21
+ domains = ["t.me", "telegram.me"]
22
+ session_path = "temp/telegram"
23
+
24
+ def __init__(self):
25
+ self.api_id = telegram_api_id
26
+ self.api_hash = telegram_api_hash
27
+
28
+ self.client = TelegramClient(self.session_path, self.api_id, self.api_hash)
29
+ self.client.start(bot_token=telegram_bot_token)
30
+ logger.info("✅ Successfully connected to Telegram...")
31
+
32
+ async def get(self, url: str, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
33
+ """Retrieves content from a Telegram post URL."""
34
+ assert get_domain(url) in self.domains
35
+
36
+ # Parse the URL to get channel/group name and post ID
37
+ parsed = urlparse(url)
38
+ path_parts = parsed.path.strip("/").split("/")
39
+
40
+ if len(path_parts) < 2:
41
+ return None
42
+
43
+ channel_name = path_parts[0]
44
+ post_id = int(path_parts[1])
45
+
46
+ try:
47
+ # Get the message
48
+ channel = await self.client.get_entity(channel_name)
49
+ message = await self.client.get_messages(channel, ids=post_id)
50
+
51
+ if not message:
52
+ return None
53
+
54
+ # Handle media
55
+ media = await self._get_media_from_message(channel, message)
56
+
57
+ author = message.sender
58
+ author_type = type(author).__name__
59
+ if isinstance(author, Channel):
60
+ name = f'"{author.title}"'
61
+ if author.username:
62
+ name += f" (@{author.username})"
63
+ elif isinstance(author, User):
64
+ if author.bot:
65
+ author_type = "Bot"
66
+ name = f"{author.first_name} {author.last_name}" if author.last_name else author.first_name
67
+ if author.username:
68
+ name += f" (@{author.username})"
69
+ if author.phone:
70
+ name += f", Phone: {author.phone}"
71
+ if author.verified:
72
+ name += " (Verified)"
73
+ else:
74
+ name = "Unknown"
75
+
76
+ edit_text = "\nEdit date: " + message.edit_date.strftime("%B %d, %Y at %H:%M") if message.edit_date else ""
77
+ reactions_text = "\nReactions: " + message.reactions.stringify() if message.reactions else ""
78
+
79
+ text = f"""**Telegram Post**
80
+ Author: {author_type} {name}
81
+ Date: {message.date.strftime("%B %d, %Y at %H:%M")}{edit_text}
82
+ Views: {message.views}
83
+ Forwards: {message.forwards}{reactions_text}
84
+
85
+ {' '.join(m.reference for m in media)}
86
+ {message.text}"""
87
+
88
+ return MultimodalSequence(text)
89
+
90
+ except Exception as e:
91
+ print(f"Error retrieving Telegram content: {e}")
92
+ # raise
93
+ return None
94
+
95
+ async def _get_media_from_message(self, chat, original_post, max_amp=10) -> list[Item]:
96
+ """
97
+ Searches for Telegram posts that are part of the same group of uploads.
98
+ The search is conducted around the id of the original post with an amplitude
99
+ of `max_amp` both ways.
100
+ Returns a list of [post] where each post has media and is in the same grouped_id.
101
+ """
102
+ # Gather posts that may belong to the same group
103
+ if original_post.grouped_id is None:
104
+ posts = [original_post]
105
+ else:
106
+ search_ids = list(range(original_post.id - max_amp, original_post.id + max_amp + 1))
107
+ posts = await self.client.get_messages(chat, ids=search_ids)
108
+
109
+ # Download media of posts that belong to the same group
110
+ media = []
111
+ for post in posts:
112
+ if post is not None and post.grouped_id == original_post.grouped_id:
113
+ if medium := post.media:
114
+ post_url = f"https://t.me/{chat.username}/{post.id}"
115
+ medium_bytes = await self.client.download_media(post, file=bytes)
116
+ if hasattr(medium, "photo"):
117
+ item = Image(binary_data=medium_bytes, source_url=post_url)
118
+ elif hasattr(medium, "video"):
119
+ item = Video(binary_data=medium_bytes, source_url=post_url)
120
+ else:
121
+ raise ValueError(f"Unsupported medium: {medium.__dict__}")
122
+ media.append(item)
123
+
124
+ return media
@@ -0,0 +1,198 @@
1
+ import asyncio
2
+ import re
3
+ from typing import Optional
4
+ from urllib.parse import urlparse
5
+
6
+ import aiohttp
7
+ from ezmm import MultimodalSequence, download_video, download_image
8
+ from tweepy import Tweet
9
+ from tweepy.asynchronous import AsyncClient
10
+
11
+ from config import x_bearer_token
12
+ from scrapemm.integrations.base import RetrievalIntegration
13
+ from scrapemm.util import get_domain
14
+
15
+
16
+ class X(RetrievalIntegration):
17
+ """The X (Twitter) integration. Requires "Basic" API access to work. For more info, see
18
+ https://developer.x.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-level
19
+ "Free" API access does NOT include reading Tweets."""
20
+ domains = ["twitter.com", "x.com", "t.co"]
21
+
22
+ account_explanation = """X accounts having a "blue" verification fulfill a basic set of criteria,
23
+ such as having a confirmed phone number. At time of the verification, the account must be not
24
+ deceptive.
25
+
26
+ An account with "gold" verification belongs to an "official organization" verified through X,
27
+ costing about $1000 per month.
28
+
29
+ If an account is "protected", it means that it was set private by the user.
30
+
31
+ A "withheld" account is a user who got restricted by X.
32
+
33
+ A "parody" account is an explicit, user-provided indication of being a parody (of someone or something).
34
+
35
+ The "location" of a user profile is a user-provided string and is not guaranteed to be accurate."""
36
+
37
+ def __init__(self):
38
+ if not x_bearer_token: raise ValueError("No X bearer token provided. Add it to config/secrets.yaml")
39
+ self.client = AsyncClient(bearer_token=x_bearer_token)
40
+
41
+ async def get(self, url: str, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
42
+ assert get_domain(url) in self.domains
43
+ tweet_id = extract_tweet_id_from_url(url)
44
+ if tweet_id:
45
+ return await self._get_tweet(tweet_id, session)
46
+ else:
47
+ username = extract_username_from_url(url)
48
+ if username:
49
+ return await self._get_user(username, session)
50
+
51
+ async def _get_tweet(self, tweet_id: int, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
52
+ """Returns a MultimodalSequence containing the tweet's text and media
53
+ along with information like metrics, etc."""
54
+
55
+ response = await self.client.get_tweet(
56
+ id=tweet_id,
57
+ expansions=["author_id", "attachments.media_keys", "geo.place_id",
58
+ "edit_history_tweet_ids"],
59
+ media_fields=["url", "variants"],
60
+ tweet_fields=["created_at", "public_metrics"],
61
+ )
62
+ tweet: Tweet = response.data
63
+
64
+ if tweet:
65
+ media_raw = response.includes.get("media")
66
+ author = response.includes.get("users")[0]
67
+ metrics = tweet.public_metrics
68
+
69
+ # Post-process text
70
+ text = tweet.text
71
+ text = re.sub(r"https?://t\.co/\S+", "", text).strip()
72
+
73
+ # Download the media
74
+ media = []
75
+ for medium_raw in media_raw:
76
+ if medium_raw.type == "photo":
77
+ url = medium_raw.url
78
+ medium = await download_image(url, session=session)
79
+ elif medium_raw.type in ["video", "animated_gif"]:
80
+ # Get the variant with the highest bitrate
81
+ url = _get_best_quality_video_url(medium_raw.variants)
82
+ medium = await download_video(url, session=session)
83
+ else:
84
+ raise ValueError(f"Unsupported media type: {medium_raw.type}")
85
+ if medium:
86
+ media.append(medium)
87
+
88
+ tweet_str = f"""**Post on X**
89
+ Author: {author.name}, @{author.username}
90
+ Posted on: {tweet.created_at.strftime("%B %d, %Y at %H:%M")}
91
+ Likes: {metrics['like_count']} - Retweets: {metrics['retweet_count']} - Replies: {metrics['reply_count']} - Views: {metrics['impression_count']}
92
+
93
+ {text}""" # TODO: Add edit history
94
+ return MultimodalSequence([tweet_str, *media])
95
+
96
+ async def _get_user(self, username: str, session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
97
+ """Returns a MultimodalSequence containing the user's profile information
98
+ incl. profile image and profile banner."""
99
+
100
+ # The fields "parody" and "verified_followers_count" are fairly new. See
101
+ # https://x.com/Safety/status/1877581125608153389
102
+ # and https://x.com/XDevelopers/status/1865180409425715202
103
+ response = await self.client.get_user(username=username, user_fields=[
104
+ "created_at", "description", "location", "parody", "profile_banner_url", "profile_image_url",
105
+ "protected", "public_metrics", "url", "verified", "verified_followers_count", "verified_type", "withheld"
106
+ ])
107
+ user = response.data
108
+
109
+ if user:
110
+ # Turn all the data into a multimodal sequence
111
+
112
+ profile_image_url = user.profile_image_url.replace("_normal", "") # Use the original picture variant
113
+ profile_image = await download_image(profile_image_url, session)
114
+ profile_banner = await download_image(user.profile_banner_url, session)
115
+
116
+ verification_status_text = f"{'Verified' if user.verified else 'Not verified'}"
117
+ if user.verified:
118
+ verification_status_text += f" ({user.verified_type})"
119
+
120
+ metrics = [f" - {k.capitalize().replace('_', ' ')}: {v}"
121
+ for k, v in user.public_metrics.items()]
122
+ metrics_text = "\n".join(metrics)
123
+ if hasattr(user, "verified_followers_count"):
124
+ metrics_text += f"\n - Verified followers count: {user.verified_followers_count}"
125
+
126
+ properties_text = f"- {verification_status_text}"
127
+ if user.protected:
128
+ properties_text += "\n- Protected"
129
+ if user.withheld:
130
+ properties_text += "\n- Withheld"
131
+ if user.parody:
132
+ properties_text += "\n- Marked as parody"
133
+
134
+ text = f"""**Profile on X**
135
+ User: {user.name}, @{user.username}
136
+ Created on: {user.created_at.strftime("%B %d, %Y")}
137
+ Profile image: {profile_image.reference}
138
+ Profile banner: {profile_banner.reference}
139
+
140
+ URL: {user.url}
141
+ Location: {user.location}
142
+ Description: {user.description}
143
+
144
+ Metrics:
145
+ {metrics_text}
146
+
147
+ Account properties:
148
+ {properties_text}"""
149
+
150
+ return MultimodalSequence(text)
151
+
152
+
153
+ def extract_username_from_url(url: str) -> Optional[str]:
154
+ # TODO: Users may change their username, invalidating corresponding URLs. Handle this
155
+ # by retrieving the author's ID of the linked tweet.
156
+ parsed = urlparse(url)
157
+ try:
158
+ candidate = parsed.path.strip("/").split("/")[0]
159
+ if candidate and len(candidate) >= 3:
160
+ return candidate
161
+ except IndexError:
162
+ return None
163
+
164
+
165
+ def extract_tweet_id_from_url(url: str) -> Optional[int]:
166
+ parsed = urlparse(url)
167
+ id_candidate = parsed.path.strip("/").split("/")[-1] # Takes variants (like short links) into account
168
+ try:
169
+ return int(id_candidate)
170
+ except ValueError:
171
+ return None
172
+
173
+
174
+ def _get_best_quality_video_url(variants: list) -> Optional[str]:
175
+ """Returns the URL of the video variant that has the highest bitrate."""
176
+ bitrate = -1
177
+ best_url = None
178
+ for variant in variants:
179
+ if content_type := variant.get("content_type"):
180
+ if content_type.startswith("video/") and variant["bit_rate"] > bitrate:
181
+ bitrate = variant["bit_rate"]
182
+ best_url = variant["url"]
183
+ return best_url
184
+
185
+
186
+ if __name__ == "__main__":
187
+ urls = [
188
+ # "https://x.com/thinking_panda/status/1939348093155344491", # Image
189
+ # "https://x.com/PopBase/status/1938496291908030484", # Multiple images
190
+ # "https://x.com/AMAZlNGNATURE" # Profile
191
+ # "https://x.com/AMAZlNGNATURE/status/1917939518000210352", # Video
192
+ "https://x.com/GiFShitposting/status/1936904802082161085", # GIF
193
+ ]
194
+ x = X()
195
+ for url in urls:
196
+ task = x.get(url)
197
+ out = asyncio.run(task)
198
+ print(out)
scrapemm/retrieval.py ADDED
@@ -0,0 +1,65 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import aiohttp
5
+ from ezmm import MultimodalSequence
6
+
7
+ from scrapemm.common import is_unsupported_site
8
+ from scrapemm.integrations import retrieve_via_integration
9
+ from scrapemm.scraping.firecrawl import firecrawl
10
+ from scrapemm.util import run_with_semaphore
11
+
12
+ logger = logging.getLogger("Retriever")
13
+
14
+
15
+ async def retrieve(urls: str | list[str], remove_urls: bool = True) -> Optional[MultimodalSequence] | list[Optional[MultimodalSequence]]:
16
+ """Main function of this repository. Downloads the contents present at the given URL(s).
17
+ For each URL, returns a MultimodalSequence containing text, images, and videos.
18
+ Returns None if the corresponding URL is not supported or if retrieval failed.
19
+
20
+ :param urls: The URL(s) to retrieve.
21
+ :param remove_urls: Whether to remove URLs from hyperlinks contained in the
22
+ retrieved text (and only keep the hypertext).
23
+ """
24
+
25
+ async with aiohttp.ClientSession() as session:
26
+ if isinstance(urls, str):
27
+ return await _retrieve_single(urls, remove_urls, session)
28
+
29
+ elif isinstance(urls, list):
30
+ if len(urls) == 1:
31
+ return await _retrieve_single(urls[0], remove_urls, session)
32
+
33
+ # Remove duplicates
34
+ urls_unique = set(urls)
35
+
36
+ # Retrieve URLs concurrently
37
+ tasks = [_retrieve_single(url, remove_urls, session) for url in urls_unique]
38
+ results = await run_with_semaphore(tasks, limit=20, show_progress=True,
39
+ progress_description="Retrieving URLs...")
40
+
41
+ # Reconstruct output list
42
+ results = dict(zip(urls_unique, results))
43
+ return [results[url] for url in urls]
44
+
45
+ else:
46
+ raise ValueError("'urls' must be a string or a list of strings.")
47
+
48
+
49
+ async def _retrieve_single(url: str, remove_urls: bool,
50
+ session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
51
+ try:
52
+ # Ensure URL is a string
53
+ url = str(url)
54
+
55
+ # Skip URLs from domains that are not supported
56
+ if is_unsupported_site(url):
57
+ return None
58
+
59
+ # First, try to use a matching API, otherwise scrape directly
60
+ return ((await retrieve_via_integration(url, session)) or
61
+ (await firecrawl.scrape(url, remove_urls, session)))
62
+
63
+ except Exception as e:
64
+ logger.error(f"Error while retrieving URL '{url}'.\n"
65
+ f"{type(e).__name__}: {e}")
File without changes
@@ -0,0 +1,126 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ import aiohttp
5
+ import requests
6
+ from ezmm import MultimodalSequence
7
+
8
+ from config import firecrawl_url
9
+ from scrapemm.scraping.util import find_firecrawl, to_multimodal_sequence
10
+
11
+ logger = logging.getLogger("Retriever")
12
+
13
+ FIRECRAWL_URLS = [
14
+ firecrawl_url,
15
+ "http://localhost:3002",
16
+ "http://firecrawl:3002",
17
+ "http://0.0.0.0:3002",
18
+ ]
19
+
20
+
21
+ class Firecrawl:
22
+ """Takes any URL and tries to scrape its contents. If the URL belongs to a platform
23
+ requiring an API and the API integration is implemented (e.g. X, Reddit etc.), the
24
+ respective API will be used instead of direct HTTP requests."""
25
+
26
+ firecrawl_url: Optional[str]
27
+
28
+ def __init__(self):
29
+ self.locate_firecrawl()
30
+ self.n_scrapes = 0
31
+
32
+ def locate_firecrawl(self):
33
+ """Scans a list of URLs (included the user-specified one) to find a
34
+ running Firecrawl instance."""
35
+ self.firecrawl_url = find_firecrawl(FIRECRAWL_URLS)
36
+ if self.firecrawl_url:
37
+ logger.info(f"✅ Detected Firecrawl running at {self.firecrawl_url}.")
38
+ else:
39
+ logger.warning(f"❌ Unable to locate Firecrawl! It is not running at: {firecrawl_url}")
40
+
41
+ async def scrape(self, url: str,
42
+ remove_urls: bool,
43
+ session: aiohttp.ClientSession) -> Optional[MultimodalSequence]:
44
+ """Downloads the contents of the specified webpages dynamically or statically.
45
+ Resolves up to MAX_MEDIA_PER_PAGE image URLs and replaces them with their
46
+ respective reference."""
47
+ html = await self._call_firecrawl(url, session)
48
+ if html:
49
+ return await to_multimodal_sequence(html, remove_urls=remove_urls, session=session)
50
+
51
+ async def _call_firecrawl(self, url: str, session: aiohttp.ClientSession,
52
+ format: str = "html", timeout: int = 30_000) -> Optional[str]:
53
+ """Scrapes the given URL using Firecrawl. Returns a Markdown-formatted string
54
+ of the webpage's contents."""
55
+ assert self.firecrawl_url is not None
56
+
57
+ headers = {
58
+ 'Content-Type': 'application/json',
59
+ }
60
+ json_data = {
61
+ "url": url,
62
+ "formats": [format],
63
+ "onlyMainContent": False,
64
+ "removeBase64Images": False,
65
+ # "includeTags": [
66
+ # # Text
67
+ # "p", "h1", "h2", "h3", "h4", "h5", "h6", "span", "a", "div",
68
+ # "li", "blockquote", "figcaption", "article", "header", "section", "ul", "ol",
69
+ # "pre", "code", "table", "tbody", "tr", "td", "th", "thead",
70
+ # # Media
71
+ # "img", "picture", "video", "audio", "source", "iframe", "embed", "object",
72
+ # ],
73
+ "excludeTags": ["script", "style", "noscript", "footer", "aside"],
74
+ "timeout": timeout, # Max. duration in ms that the scraper will wait for the page to respond
75
+ }
76
+
77
+ try:
78
+ async with session.post(self.firecrawl_url + "/v1/scrape",
79
+ json=json_data,
80
+ headers=headers,
81
+ timeout=10 * 60) as response: # Firecrawl scrapes usually take 2 to 4s, but a 1700-page PDF takes 5 min
82
+
83
+ if response.status != 200:
84
+ logger.warning(
85
+ f"Failed to scrape {url}\nStatus code: {response.status} - Reason: {response.reason}")
86
+ match response.status:
87
+ case 402:
88
+ logger.debug(f"Error 402: Access denied.")
89
+ case 403:
90
+ logger.debug(f"Error 403: Forbidden.")
91
+ case 408:
92
+ logger.warning(f"Error 408: Timeout! Firecrawl overloaded or Webpage did not respond.")
93
+ case 409:
94
+ logger.debug(f"Error 409: Access denied.")
95
+ case 500:
96
+ logger.debug(f"Error 500: Server error.")
97
+ case _:
98
+ logger.debug(f"Error {response.status}: {response.reason}.")
99
+ logger.debug("Skipping that URL.")
100
+ return None
101
+
102
+ json = await response.json()
103
+ success = json["success"]
104
+ if success and "data" in json:
105
+ data = json["data"]
106
+ text = data.get(format)
107
+ return text
108
+ else:
109
+ logger.warning(f"Unable to read {url}. No usable data in response. Skipping it.")
110
+ logger.debug(str(json))
111
+ return None
112
+
113
+ except (requests.exceptions.RetryError, requests.exceptions.ConnectionError):
114
+ logger.error(f"Firecrawl is not running!")
115
+ return None
116
+ except requests.exceptions.Timeout:
117
+ error_message = "Firecrawl failed to respond in time! This can be due to server overload."
118
+ logger.warning(f"{error_message}\nSkipping the URL {url}.")
119
+ return None
120
+ except Exception as e:
121
+ error_message = f"Exception: {repr(e)}"
122
+ logger.warning(f"{error_message}\nUnable to scrape {url} with Firecrawl. Skipping...")
123
+ return None
124
+
125
+
126
+ firecrawl = Firecrawl()
@@ -0,0 +1,159 @@
1
+ from typing import Optional
2
+
3
+ import aiohttp
4
+ import requests
5
+ from ezmm import MultimodalSequence, download_item, Item, Image, Video
6
+ from markdownify import markdownify as md
7
+ import re
8
+ import base64
9
+
10
+ from scrapemm.util import run_with_semaphore
11
+
12
+ MAX_MEDIA_PER_PAGE = 32
13
+
14
+ URL_REGEX = r"https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)"
15
+ DATA_URI_REGEX = r"data:([\w/+.-]+/[\w.+-]+);base64,([A-Za-z0-9+/=]+)"
16
+ MD_HYPERLINK_REGEX = rf'(!?\[([^]^[]*)\]\((.*?)(?: "[^"]*")?\))'
17
+
18
+
19
+ def find_firecrawl(urls):
20
+ for url in urls:
21
+ if firecrawl_is_running(url):
22
+ return url
23
+ return None
24
+
25
+
26
+ def firecrawl_is_running(url):
27
+ """Returns True iff Firecrawl is running at the specified URL."""
28
+ try:
29
+ response = requests.get(url, timeout=0.1)
30
+ except (requests.exceptions.ConnectionError, requests.exceptions.RetryError):
31
+ return False
32
+ return response.status_code == 200
33
+
34
+
35
+ def postprocess_scraped(text: str) -> str:
36
+ # Remove any excess whitespaces
37
+ text = re.sub(r' {2,}', ' ', text)
38
+
39
+ # Remove any excess newlines
40
+ text = re.sub(r'(\n *){3,}', '\n\n', text)
41
+
42
+ return sanitize(text.strip())
43
+
44
+
45
+ async def resolve_media_hyperlinks(
46
+ text: str, session: aiohttp.ClientSession,
47
+ remove_urls: bool = False,
48
+ ) -> Optional[MultimodalSequence]:
49
+ """Identifies up to MAX_MEDIA_PER_PAGE image URLs, downloads images that
50
+ have substantial size (larger than 256 x 256) and replaces the
51
+ respective Markdown hyperlinks with their proper image reference."""
52
+
53
+ if text is None:
54
+ return None
55
+
56
+ # Extract URLs and base64-encoded data from the text
57
+ hyperlinks = get_markdown_hyperlinks(text)
58
+ urls = set()
59
+ data_uris = set()
60
+ for _, _, href in hyperlinks:
61
+ if is_url(href):
62
+ urls.add(href)
63
+ elif is_data_uri(href):
64
+ data_uris.add(href)
65
+
66
+ # Try to download media for each URL
67
+ tasks = [download_item(url, session=session) for url in urls]
68
+ media: list[Item | None] = await run_with_semaphore(tasks, limit=100, show_progress=False)
69
+
70
+ href_media = dict(zip(urls, media))
71
+
72
+ # Convert each base64-encoded data to the respective medium
73
+ for data_uri in data_uris:
74
+ mime_type, base64_encoding = decompose_data_uri(data_uri)
75
+ href_media[data_uri] = from_base64(base64_encoding, mime_type=mime_type)
76
+
77
+ # Replace hyperlinks with their respective media reference
78
+ media_count = 0
79
+ for full_match, hypertext, href in hyperlinks:
80
+ medium = href_media.get(href)
81
+ if medium:
82
+ # Ignore small images
83
+ to_ignore = isinstance(medium, Image) and (medium.width < 256 or medium.height < 256)
84
+ reference = "" if to_ignore else medium.reference
85
+ replacement = f"{hypertext} {reference}" if hypertext else reference
86
+ text = text.replace(full_match, replacement)
87
+ media_count += 1 if not to_ignore else 0
88
+ elif remove_urls:
89
+ text = text.replace(full_match, hypertext)
90
+
91
+ if media_count >= MAX_MEDIA_PER_PAGE:
92
+ break
93
+
94
+ return MultimodalSequence(text)
95
+
96
+
97
+ def is_url(href: str) -> bool:
98
+ """Returns True iff the given string is a valid URL."""
99
+ return re.match(URL_REGEX, href) is not None
100
+
101
+
102
+ def is_data_uri(href: str) -> bool:
103
+ """Returns True iff the given string is a valid data URI."""
104
+ return re.match(DATA_URI_REGEX, href) is not None
105
+
106
+
107
+ # def md(soup, **kwargs):
108
+ # """Converts a BeautifulSoup object into Markdown."""
109
+ # if soup is None:
110
+ # return None
111
+ # return MarkdownConverter(**kwargs).convert_soup(soup)
112
+
113
+
114
+ def get_markdown_hyperlinks(text: str) -> list[tuple[str, str, str]]:
115
+ """Extracts all web hyperlinks from the given markdown-formatted string. Returns
116
+ a list of fullmatch-hypertext-URL-triples."""
117
+ pattern = re.compile(MD_HYPERLINK_REGEX, re.DOTALL)
118
+ hyperlinks = re.findall(pattern, text)
119
+ return hyperlinks
120
+
121
+
122
+ def decompose_data_uri(href: str) -> Optional[tuple[str, str]]:
123
+ """Extracts the mime type and base64-encoded data from a data URI."""
124
+ match = re.match(DATA_URI_REGEX, href)
125
+ if match:
126
+ return match.group(1), match.group(2)
127
+ else:
128
+ return None
129
+
130
+
131
+ async def to_multimodal_sequence(
132
+ html: str | None,
133
+ **kwargs
134
+ ) -> Optional[MultimodalSequence]:
135
+ """Turns a scraped output into the corresponding MultimodalSequences
136
+ by converting the HTML into Markdown and resolving media hyperlinks."""
137
+ text = md(html, heading_style="ATX")
138
+ text = postprocess_scraped(text)
139
+ return await resolve_media_hyperlinks(text, **kwargs)
140
+
141
+
142
+ def sanitize(text: str) -> str:
143
+ """Post-processes scraped text, removing invalid characters."""
144
+ return text.replace("\u0000", "")
145
+
146
+
147
+ def from_base64(b64_data: str, mime_type: str = "image/jpeg") -> Optional[Item]:
148
+ """Converts a base64-encoded image to an Item object."""
149
+ try:
150
+ binary_data = base64.b64decode(b64_data)
151
+ if binary_data:
152
+ if mime_type.startswith("image/"):
153
+ return Image(binary_data=binary_data)
154
+ elif mime_type.startswith("video/"):
155
+ return Video(binary_data=binary_data)
156
+ else:
157
+ raise ValueError(f"Unsupported media type: {mime_type}")
158
+ except ValueError as e:
159
+ print(f"Error decoding base64 data: {e}")
scrapemm/util.py ADDED
@@ -0,0 +1,69 @@
1
+ import asyncio
2
+ import logging
3
+ import re
4
+ import sys
5
+ from typing import Optional, Awaitable, Iterable
6
+
7
+ import tqdm
8
+ from pydantic import HttpUrl
9
+
10
+ logger = logging.getLogger("Retriever")
11
+
12
+ HEADERS = {
13
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
14
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
15
+ "Chrome/123.0.0.0 Safari/537.36",
16
+ }
17
+
18
+ DOMAIN_REGEX = r"(?:https?:\/\/)?(?:www\.)?([-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6})/?"
19
+
20
+
21
+ def get_domain(url: str | HttpUrl, keep_subdomain: bool = False) -> Optional[str]:
22
+ """Uses regex to get out the domain from the given URL. The output will be
23
+ of the form 'example.com'. No 'www', no 'http'."""
24
+ url = str(url)
25
+ match = re.search(DOMAIN_REGEX, url)
26
+ if match:
27
+ domain = match.group(1)
28
+ if not keep_subdomain:
29
+ # Keep only second-level and top-level domain
30
+ domain = '.'.join(domain.split('.')[-2:])
31
+ return domain
32
+
33
+
34
+ async def run_with_semaphore(tasks: Iterable[Awaitable],
35
+ limit: int,
36
+ show_progress: bool = True,
37
+ progress_description: str = None) -> list:
38
+ """
39
+ Runs asynchronous tasks with a concurrency limit.
40
+
41
+ Args:
42
+ tasks: The tasks to execute concurrently.
43
+ limit: The maximum number of coroutines to run concurrently.
44
+ show_progress: Whether to show a progress bar while executing tasks.
45
+ progress_description: The message to display in the progress bar.
46
+
47
+ Returns:
48
+ list: A list of results returned by the tasks, order-preserved.
49
+ """
50
+ semaphore = asyncio.Semaphore(limit) # Limit concurrent executions
51
+
52
+ async def limited_coroutine(t: Awaitable):
53
+ async with semaphore:
54
+ return await t
55
+
56
+ print(progress_description, end="\r")
57
+
58
+ tasks = [asyncio.create_task(limited_coroutine(task)) for task in tasks]
59
+
60
+ # Report completion status of tasks (if more than one task)
61
+ if show_progress:
62
+ progress = tqdm.tqdm(total=len(tasks), desc=progress_description, file=sys.stdout)
63
+ while progress.n < len(tasks):
64
+ progress.n = sum(task.done() for task in tasks)
65
+ progress.refresh()
66
+ await asyncio.sleep(0.1)
67
+ progress.close()
68
+
69
+ return await asyncio.gather(*tasks)
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: scrapeMM
3
+ Version: 0.1.0
4
+ Summary: LLM-friendly scraper for media and text from social media and the open web.
5
+ Author-email: Mark Rothermel <mark.rothermel@tu-darmstadt.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/multimodal-ai-lab/scrapeMM
8
+ Project-URL: Bug Tracker, https://github.com/multimodal-ai-lab/scrapeMM
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: ezmm
13
+ Requires-Dist: telethon
14
+ Requires-Dist: tweepy
15
+ Requires-Dist: markdownify
16
+ Dynamic: license-file
17
+
18
+ # scrapeMM: Multimodal Web Retrieval
19
+ Simple web scraper to asynchronously retrieve webpages and access social media contents, fetching text along with media, i.e., images and videos.
20
+
21
+ This library aims to help developers and researchers to easily access multimodal data from the web and use it for LLM processing.
22
+
23
+ ## Usage
24
+ ```python
25
+ from scrapemm import retrieve
26
+
27
+ url = "https://example.com"
28
+ result = retrieve(url)
29
+ result.render()
30
+ ```
31
+
32
+ ## How it works
33
+ ```
34
+ Input: Output:
35
+ URL (string) --> retrieve() --> MultimodalSequence
36
+ ```
37
+ The `MultimodalSequence` is a sequence of Markdown-formatted text and media provided by the [ezMM](https://github.com/multimodal-ai-lab/ezmm) library.
38
+
39
+ Web scraping is done with [Firecrawl](https://github.com/mendableai/firecrawl).
40
+
41
+ ## Supported Proprietary APIs
42
+ - ✅ X/Twitter
43
+ - ✅ Telegram
44
+ - ⏳ Facebook
45
+ - ⏳ Instagram
46
+ - ⏳ Threads
47
+ - ⏳ TikTok
@@ -0,0 +1,16 @@
1
+ scrapemm/__init__.py,sha256=G1hiuY8OvUdmamcHJTc9Ov2yK7tY8SVXQO8q6UBJxT4,70
2
+ scrapemm/common.py,sha256=jwgvuVHg-7iAUEOQt-pLvod4QrhUZIrBqvhjac99e0M,954
3
+ scrapemm/retrieval.py,sha256=3J8gfVcIwhggomN4HkT8y6_Oz8k9Nk2ZlG9ihwHraOA,2578
4
+ scrapemm/util.py,sha256=iUBb9kqmoHOr71RqfaXIJLHINNqdMlNd1gj75WTuwFU,2406
5
+ scrapemm/integrations/__init__.py,sha256=xU58ouFwKUbr4rnLHOwQhgawttcZZoEJZtSC8pgCYXM,686
6
+ scrapemm/integrations/base.py,sha256=5gyf4zyMufcmvv0hVr4p5Q8bnIvrN8829nz1LNHmdrI,481
7
+ scrapemm/integrations/telegram.py,sha256=8qTN6UGoKjkkIVAE9YHetJ-2f38W0_5Ktf76yYb1C9s,4947
8
+ scrapemm/integrations/x.py,sha256=8x8_KyVl9RhKkocr9EjqHwPjhIvkfUyge2DPr5O9whU,8315
9
+ scrapemm/scraping/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ scrapemm/scraping/firecrawl.py,sha256=pT0Se11aq7ayalfZBKDMgEj1-V56aCKBDyx958ED_uk,5514
11
+ scrapemm/scraping/util.py,sha256=5kiNn9pDpiJTVVlk8AfOns2MzD4V1EfXQ2hmJzM7-EE,5538
12
+ scrapemm-0.1.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
13
+ scrapemm-0.1.0.dist-info/METADATA,sha256=Zs3E04B33rzNVcEBSBs1xrzVAz1Tekhiz7gvReDdygo,1539
14
+ scrapemm-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ scrapemm-0.1.0.dist-info/top_level.txt,sha256=ftpWMzYGpbXKbz6etSQCOFbSqoiTxQN3eLkHHlhBXJA,9
16
+ scrapemm-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ scrapemm