crawlee 0.0.1__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.
crawlee/__init__.py ADDED
File without changes
@@ -0,0 +1,2 @@
1
+ from .snapshotter import Snapshotter
2
+ from .system_status import SystemStatus
File without changes
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from logging import getLogger
5
+ from typing import TYPE_CHECKING, Sequence, Union
6
+
7
+ if TYPE_CHECKING:
8
+ from datetime import datetime
9
+
10
+ logger = getLogger(__name__)
11
+
12
+
13
+ @dataclass
14
+ class MemorySnapshot:
15
+ """A snapshot of memory usage."""
16
+
17
+ created_at: datetime
18
+ is_overloaded: bool
19
+ used_bytes: int | None
20
+
21
+
22
+ @dataclass
23
+ class CpuSnapshot:
24
+ """A snapshot of CPU usage."""
25
+
26
+ created_at: datetime
27
+ is_overloaded: bool
28
+ used_ratio: float
29
+ ticks: dict | None = None
30
+
31
+
32
+ @dataclass
33
+ class EventLoopSnapshot:
34
+ """A snapshot of event loop usage."""
35
+
36
+ created_at: datetime
37
+ is_overloaded: bool
38
+ exceeded_millis: float
39
+
40
+
41
+ @dataclass
42
+ class ClientSnapshot:
43
+ """A snapshot of client usage."""
44
+
45
+ created_at: datetime
46
+ is_overloaded: bool
47
+ rate_limit_error_count: int
48
+
49
+
50
+ Snapshot = Union[MemorySnapshot, CpuSnapshot, EventLoopSnapshot, ClientSnapshot]
51
+
52
+
53
+ class Snapshotter:
54
+ """Creates snapshots of system resources at given intervals.
55
+
56
+ Creates snapshots of system resources at given intervals and marks the resource as either overloaded or not during
57
+ the last interval. Keeps a history of the snapshots. It tracks the following resources: Memory, EventLoop, API
58
+ and CPU. The class is used by the `AutoscaledPool` class.
59
+
60
+ When running on the Apify platform, the CPU and memory statistics are provided by the platform, as collected from
61
+ the running Docker container. When running locally, `Snapshotter` makes its own statistics by querying the OS.
62
+
63
+ CPU becomes overloaded locally when its current use exceeds the `maxUsedCpuRatio` option or when Apify platform
64
+ marks it as overloaded.
65
+
66
+ Memory becomes overloaded if its current use exceeds the `max_used_memory_ratio` option. It's computed using
67
+ the total memory available to the container when running on the Apify platform and a quarter of total system
68
+ memory when running locally. Max total memory when running locally may be overridden by using
69
+ the `CRAWLEE_MEMORY_MBYTES` environment variable.
70
+
71
+ Event loop becomes overloaded if it slows down by more than the `max_blocked_millis` option.
72
+
73
+ Client becomes overloaded when rate limit errors (429 - Too Many Requests) exceeds the `max_client_errors` option,
74
+ typically received from the request queue, exceed the set limit within the set interval.
75
+ """
76
+
77
+ def get_memory_sample(
78
+ self: Snapshotter,
79
+ sample_duration_millis: float | None = None,
80
+ ) -> Sequence[MemorySnapshot]:
81
+ """Returns a sample of the latest memory snapshots.
82
+
83
+ Args:
84
+ sample_duration_millis: The size of the sample in milliseconds. Defaults to None.
85
+ If omitted, it returns a full snapshot history.
86
+
87
+ Returns:
88
+ A sample of memory snapshots.
89
+ """
90
+
91
+ def get_event_loop_sample(
92
+ self: Snapshotter,
93
+ sample_duration_millis: float | None = None,
94
+ ) -> Sequence[EventLoopSnapshot]:
95
+ """Returns a sample of the latest event loop snapshots.
96
+
97
+ Args:
98
+ sample_duration_millis: The size of the sample in milliseconds. Defaults to None.
99
+ If omitted, it returns a full snapshot history.
100
+
101
+ Returns:
102
+ A sample of event loop snapshots.
103
+ """
104
+
105
+ def get_cpu_sample(
106
+ self: Snapshotter,
107
+ sample_duration_millis: float | None = None,
108
+ ) -> Sequence[CpuSnapshot]:
109
+ """Returns a sample of the latest CPU snapshots.
110
+
111
+ Args:
112
+ sample_duration_millis: The size of the sample in milliseconds. Defaults to None.
113
+ If omitted, it returns a full snapshot history.
114
+
115
+ Returns:
116
+ A sample of CPU snapshots.
117
+ """
118
+
119
+ def get_client_sample(
120
+ self: Snapshotter,
121
+ sample_duration_millis: float | None = None,
122
+ ) -> Sequence[ClientSnapshot]:
123
+ """Returns a sample of the latest client snapshots.
124
+
125
+ Args:
126
+ sample_duration_millis: The size of the sample in milliseconds. Defaults to None.
127
+ If omitted, it returns a full snapshot history.
128
+
129
+ Returns:
130
+ A sample of client snapshots.
131
+ """
@@ -0,0 +1,237 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from logging import getLogger
5
+ from typing import TYPE_CHECKING, Sequence
6
+
7
+ from more_itertools import pairwise
8
+
9
+ from crawlee.utils import weighted_avg
10
+
11
+ if TYPE_CHECKING:
12
+ from datetime import datetime
13
+
14
+ from crawlee.autoscaling.snapshotter import Snapshot, Snapshotter
15
+
16
+ logger = getLogger(__name__)
17
+
18
+
19
+ @dataclass
20
+ class LoadRatioInfo:
21
+ """Represents the load ratio of a resource."""
22
+
23
+ is_overloaded: bool
24
+ limit_ratio: float
25
+ actual_ratio: float
26
+
27
+
28
+ @dataclass
29
+ class SystemInfo:
30
+ """Represents the current status of the system."""
31
+
32
+ is_system_idle: bool # Indicates whether the system is currently idle or overloaded
33
+ mem_info: LoadRatioInfo
34
+ event_loop_info: LoadRatioInfo
35
+ cpu_info: LoadRatioInfo
36
+ client_info: LoadRatioInfo
37
+ mem_current_bytes: int | None = None # Platform only property
38
+ cpu_current_usage: int | None = None # Platform only property
39
+ is_cpu_overloaded: bool | None = None # Platform only property
40
+ created_at: datetime | None = None
41
+
42
+
43
+ @dataclass
44
+ class FinalStatistics:
45
+ """Represents final statistics."""
46
+
47
+ requests_finished: int
48
+ requests_failed: int
49
+ retry_histogram: list[int]
50
+ request_avg_failed_duration_millis: float
51
+ request_avg_finished_duration_millis: float
52
+ requests_finished_per_minute: float
53
+ requests_failed_per_minute: float
54
+ request_total_duration_millis: float
55
+ requests_total: int
56
+ crawler_runtime_millis: float
57
+
58
+
59
+ class SystemStatus:
60
+ """Provides a simple interface to reading system status from a `Snapshotter` instance.
61
+
62
+ It only exposes two functions `SystemStatus.get_current_status` and `SystemStatus.get_historical_status`.
63
+ The system status is calculated using a weighted average of overloaded messages in the snapshots, with the weights
64
+ being the time intervals between the snapshots. Each resource is calculated separately, and the system
65
+ is overloaded whenever at least one resource is overloaded. The class is used by the `AutoscaledPool` class.
66
+
67
+ `SystemStatus.get_current_status` returns a boolean that represents the current status of the system. The length
68
+ of the current timeframe in seconds is configurable by the `currentHistorySecs` option and represents the max age
69
+ of snapshots to be considered for the calculation.
70
+
71
+ `SystemStatus.get_historical_status` returns a boolean that represents the long-term status of the system. It
72
+ considers the full snapshot history available in the `Snapshotter` instance.
73
+
74
+ Attributes:
75
+ snapshotter: The `Snapshotter` instance to be queried for `SystemStatus`.
76
+
77
+ current_history_secs: Defines max age of snapshots used in the `SystemStatus.get_current_status` measurement.
78
+
79
+ max_memory_overloaded_ratio: Sets the maximum ratio of overloaded snapshots in a memory sample.
80
+ If the sample exceeds this ratio, the system will be overloaded.
81
+
82
+ max_event_loop_overloaded_ratio: Sets the maximum ratio of overloaded snapshots in an event loop sample.
83
+ If the sample exceeds this ratio, the system will be overloaded.
84
+
85
+ max_cpu_overloaded_ratio: Sets the maximum ratio of overloaded snapshots in a CPU sample. If the sample
86
+ exceeds this ratio, the system will be overloaded.
87
+
88
+ max_client_overloaded_ratio: Sets the maximum ratio of overloaded snapshots in a Client sample.
89
+ If the sample exceeds this ratio, the system will be overloaded.
90
+ """
91
+
92
+ def __init__(
93
+ self: SystemStatus,
94
+ snapshotter: Snapshotter,
95
+ current_history_secs: int = 5,
96
+ max_memory_overloaded_ratio: float = 0.2,
97
+ max_event_loop_overloaded_ratio: float = 0.6,
98
+ max_cpu_overloaded_ratio: float = 0.4,
99
+ max_client_overloaded_ratio: float = 0.3,
100
+ ) -> None:
101
+ self.snapshotter = snapshotter
102
+ self.current_history_secs = current_history_secs
103
+ self.max_memory_overloaded_ratio = max_memory_overloaded_ratio
104
+ self.max_event_loop_overloaded_ratio = max_event_loop_overloaded_ratio
105
+ self.max_cpu_overloaded_ratio = max_cpu_overloaded_ratio
106
+ self.max_client_overloaded_ratio = max_client_overloaded_ratio
107
+
108
+ def get_current_status(self: SystemStatus) -> SystemInfo:
109
+ """Get the current system status.
110
+
111
+ Returns a `SystemInfo` object where the `is_system_idle` property is `False` if the system has been overloaded
112
+ in the last `current_history_secs` seconds, and `True` otherwise.
113
+
114
+ Returns:
115
+ An object representing the current system status.
116
+ """
117
+ return self._is_system_idle(self.current_history_secs)
118
+
119
+ def get_historical_status(self: SystemStatus) -> SystemInfo:
120
+ """Get the historical system status.
121
+
122
+ Returns a `SystemInfo` where the `is_system_idle` property is set to `False` if the system has been overloaded
123
+ in the full history of the `Snapshotter` (which is configurable in the `Snapshotter`, and `True` otherwise.
124
+
125
+ Returns:
126
+ An object representing the historical system status.
127
+ """
128
+ return self._is_system_idle()
129
+
130
+ def _is_system_idle(self: SystemStatus, sample_duration_millis: int | None = None) -> SystemInfo:
131
+ """Determine if the system is currently idle or overloaded.
132
+
133
+ Args:
134
+ sample_duration_millis: The duration (in milliseconds) within which to analyze system status.
135
+
136
+ Returns:
137
+ An object representing the system status with an `is_system_idle` property set to `True` if the system
138
+ has not been overloaded within the specified time duration, and `False` otherwise.
139
+ """
140
+ mem_info = self._is_memory_overloaded(sample_duration_millis)
141
+ event_loop_info = self._is_event_loop_overloaded(sample_duration_millis)
142
+ cpu_info = self._is_cpu_overloaded(sample_duration_millis)
143
+ client_info = self._is_client_overloaded(sample_duration_millis)
144
+
145
+ return SystemInfo(
146
+ is_system_idle=(
147
+ not mem_info.is_overloaded
148
+ and not event_loop_info.is_overloaded
149
+ and not cpu_info.is_overloaded
150
+ and not client_info.is_overloaded
151
+ ),
152
+ mem_info=mem_info,
153
+ event_loop_info=event_loop_info,
154
+ cpu_info=cpu_info,
155
+ client_info=client_info,
156
+ )
157
+
158
+ def _is_memory_overloaded(self: SystemStatus, sample_duration_millis: int | None = None) -> LoadRatioInfo:
159
+ """Determine if memory has been overloaded within a specified time duration.
160
+
161
+ Args:
162
+ sample_duration_millis: The duration (in milliseconds) within which to analyze memory snapshots.
163
+
164
+ Returns:
165
+ An object with an `is_overloaded` property set to `True` if memory has been overloaded within the specified
166
+ time duration. Otherwise, `is_overloaded` is set to `False`.
167
+ """
168
+ sample = self.snapshotter.get_memory_sample(sample_duration_millis)
169
+ return self._is_sample_overloaded(sample, self.max_memory_overloaded_ratio)
170
+
171
+ def _is_event_loop_overloaded(self: SystemStatus, sample_duration_millis: int | None = None) -> LoadRatioInfo:
172
+ """Determine if the event loop has been overloaded within a specified time duration.
173
+
174
+ Args:
175
+ sample_duration_millis: The duration (in milliseconds) within which to analyze event loop snapshots.
176
+
177
+ Returns:
178
+ An object with an `is_overloaded` property set to `True` if the event loop has been overloaded within
179
+ the specified time duration. Otherwise, `is_overloaded` is set to `False`.
180
+ """
181
+ sample = self.snapshotter.get_event_loop_sample(sample_duration_millis)
182
+ return self._is_sample_overloaded(sample, self.max_event_loop_overloaded_ratio)
183
+
184
+ def _is_cpu_overloaded(self: SystemStatus, sample_duration_millis: int | None = None) -> LoadRatioInfo:
185
+ """Determine if the CPU has been overloaded within a specified time duration.
186
+
187
+ Args:
188
+ sample_duration_millis: The duration (in milliseconds) within which to analyze CPU snapshots.
189
+
190
+ Returns:
191
+ An object with an `is_overloaded` property set to `True` if the CPU has been overloaded within
192
+ the specified time duration. Otherwise, `is_overloaded` is set to `False`.
193
+ """
194
+ sample = self.snapshotter.get_cpu_sample(sample_duration_millis)
195
+ return self._is_sample_overloaded(sample, self.max_cpu_overloaded_ratio)
196
+
197
+ def _is_client_overloaded(self: SystemStatus, sample_duration_millis: int | None = None) -> LoadRatioInfo:
198
+ """Determine if the client has been overloaded within a specified time duration.
199
+
200
+ Args:
201
+ sample_duration_millis: The duration (in milliseconds) within which to analyze client snapshots.
202
+
203
+ Returns:
204
+ An object with an `is_overloaded` property set to `True` if the client has been overloaded within
205
+ the specified time duration. Otherwise, `is_overloaded` is set to `False`.
206
+ """
207
+ sample = self.snapshotter.get_client_sample(sample_duration_millis)
208
+ return self._is_sample_overloaded(sample, self.max_client_overloaded_ratio)
209
+
210
+ def _is_sample_overloaded(self: SystemStatus, sample: Sequence[Snapshot], ratio: float) -> LoadRatioInfo:
211
+ """Determine if a sample of snapshot data is overloaded based on a specified ratio.
212
+
213
+ Args:
214
+ sample: A sequence of snapshot data to analyze.
215
+ ratio: The ratio threshold to consider the sample as overloaded.
216
+
217
+ Returns:
218
+ An object with an `is_overloaded` property set to `True` if the sample is considered overloaded based
219
+ on the specified ratio. Otherwise, `is_overloaded` is set to `False`.
220
+ """
221
+ if not sample:
222
+ return LoadRatioInfo(is_overloaded=False, limit_ratio=ratio, actual_ratio=0)
223
+
224
+ weights, values = [], []
225
+
226
+ for previous, current in pairwise(sample):
227
+ weight = (current.created_at - previous.created_at).total_seconds() or 0.001 # Avoid zero
228
+ weights.append(weight)
229
+ values.append(float(current.is_overloaded))
230
+
231
+ w_avg = values[0] if len(sample) == 1 else weighted_avg(values, weights)
232
+
233
+ return LoadRatioInfo(
234
+ is_overloaded=w_avg > ratio,
235
+ limit_ratio=ratio,
236
+ actual_ratio=round(w_avg, 3),
237
+ )
@@ -0,0 +1 @@
1
+ from .event_manager import EventManager
@@ -0,0 +1,157 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections import defaultdict
5
+ from contextlib import suppress
6
+ from functools import wraps
7
+ from inspect import iscoroutinefunction
8
+ from logging import getLogger
9
+ from typing import TYPE_CHECKING
10
+
11
+ from pyee.asyncio import AsyncIOEventEmitter
12
+
13
+ if TYPE_CHECKING:
14
+ from datetime import timedelta
15
+
16
+ from crawlee.events.types import Event, EventData, Listener, WrappedListener
17
+
18
+ logger = getLogger(__name__)
19
+
20
+
21
+ class EventManager:
22
+ """Event manager for registering, emitting, and managing event listeners.
23
+
24
+ Event manager allows you to register event listeners, emit events, and wait for event listeners to complete
25
+ their execution. It is built on top of the `pyee.asyncio.AsyncIOEventEmitter` class.
26
+
27
+ Attributes:
28
+ _event_emitter: The event emitter which is used to emit events and call the event listeners.
29
+
30
+ _listener_tasks: The set of asyncio tasks which are currently executing the event listeners.
31
+
32
+ _listeners_to_wrappers: The mapping between events and listeners, and the wrapped listeners which are
33
+ registered with the event emitter.
34
+ """
35
+
36
+ def __init__(self: EventManager) -> None:
37
+ logger.debug('Calling LocalEventManager.__init__()...')
38
+ self._event_emitter = AsyncIOEventEmitter()
39
+
40
+ # Listeners are wrapped in a asyncio.Task, store their references here so that we can wait for them to finish
41
+ self._listener_tasks: set[asyncio.Task] = set()
42
+
43
+ # Store the mapping between events and listeners like this:
44
+ # event -> listener -> [wrapped_listener_1, wrapped_listener_2, ...]
45
+ self._listeners_to_wrappers: dict[Event, dict[Listener, list[WrappedListener]]] = defaultdict(
46
+ lambda: defaultdict(list),
47
+ )
48
+
49
+ async def close(self: EventManager, *, timeout: timedelta | None = None) -> None:
50
+ """Close the event manager.
51
+
52
+ This will stop listening for the events, and it will wait for all the event listeners to finish.
53
+
54
+ Args:
55
+ timeout: Optional timeout after which the pending event listeners are canceled.
56
+ """
57
+ logger.debug('Calling LocalEventManager.close()...')
58
+ await self.wait_for_all_listeners_to_complete(timeout=timeout)
59
+ self._event_emitter.remove_all_listeners()
60
+
61
+ def on(self: EventManager, *, event: Event, listener: Listener) -> None:
62
+ """Add an event listener to the event manager.
63
+
64
+ Args:
65
+ event: The Actor event for which to listen to.
66
+ listener: The function (sync or async) which is to be called when the event is emitted.
67
+ """
68
+ logger.debug('Calling LocalEventManager.on()...')
69
+
70
+ @wraps(listener)
71
+ async def listener_wrapper(event_data: EventData) -> None:
72
+ logger.debug('Calling LocalEventManager.on.listener_wrapper()...')
73
+
74
+ # If the listener is a coroutine function, just call it, otherwise, run it in a separate thread
75
+ # to avoid blocking the event loop
76
+ coroutine = (
77
+ listener(event_data) if iscoroutinefunction(listener) else asyncio.to_thread(listener, event_data)
78
+ )
79
+
80
+ listener_task = asyncio.create_task(coroutine, name=f'Task-{event.value}-{listener.__name__}')
81
+ self._listener_tasks.add(listener_task)
82
+
83
+ try:
84
+ await listener_task
85
+ except Exception:
86
+ # We need to swallow the exception and just log it here, otherwise it could break the event emitter
87
+ logger.exception(
88
+ 'Exception in the event listener',
89
+ extra={'event_name': event.value, 'listener_name': listener.__name__},
90
+ )
91
+ finally:
92
+ logger.debug('LocalEventManager.on.listener_wrapper(): Removing listener task from the set...')
93
+ self._listener_tasks.remove(listener_task)
94
+
95
+ self._listeners_to_wrappers[event][listener].append(listener_wrapper)
96
+ self._event_emitter.add_listener(event.value, listener_wrapper)
97
+
98
+ def off(self: EventManager, *, event: Event, listener: Listener | None = None) -> None:
99
+ """Remove a listener, or all listeners, from an Actor event.
100
+
101
+ Args:
102
+ event: The Actor event for which to remove listeners.
103
+ listener: The listener which is supposed to be removed. If not passed, all listeners of this event
104
+ are removed.
105
+ """
106
+ logger.debug('Calling LocalEventManager.off()...')
107
+
108
+ if listener:
109
+ for listener_wrapper in self._listeners_to_wrappers[event][listener]:
110
+ self._event_emitter.remove_listener(event.value, listener_wrapper)
111
+ self._listeners_to_wrappers[event][listener] = []
112
+ else:
113
+ self._listeners_to_wrappers[event] = defaultdict(list)
114
+ self._event_emitter.remove_all_listeners(event.value)
115
+
116
+ def emit(self: EventManager, *, event: Event, event_data: EventData) -> None:
117
+ """Emit an event.
118
+
119
+ Args:
120
+ event: The event which will be emitted.
121
+ event_data: The data which will be passed to the event listeners.
122
+ """
123
+ logger.debug('Calling LocalEventManager.emit()...')
124
+ self._event_emitter.emit(event.value, event_data)
125
+
126
+ async def wait_for_all_listeners_to_complete(self: EventManager, *, timeout: timedelta | None = None) -> None:
127
+ """Wait for all currently executing event listeners to complete.
128
+
129
+ Args:
130
+ timeout: The maximum time to wait for the event listeners to finish. If they do not complete within
131
+ the specified timeout, they will be canceled.
132
+ """
133
+ logger.debug('Calling LocalEventManager.wait_for_all_listeners_to_complete()...')
134
+
135
+ async def wait_for_listeners() -> None:
136
+ """Gathers all listener tasks and awaits their completion, logging any exceptions encountered."""
137
+ results = await asyncio.gather(*self._listener_tasks, return_exceptions=True)
138
+ for result in results:
139
+ if isinstance(result, Exception):
140
+ logger.exception('Event listener raised an exception.', exc_info=result)
141
+
142
+ tasks = [asyncio.create_task(wait_for_listeners(), name=f'Task-{wait_for_listeners.__name__}')]
143
+ timeout_secs = timeout.total_seconds() if timeout else None
144
+
145
+ try:
146
+ _, pending = await asyncio.wait(tasks, timeout=timeout_secs)
147
+ if pending:
148
+ logger.warning('Waiting timeout reached; canceling unfinished event listeners.')
149
+ except asyncio.CancelledError:
150
+ logger.warning('Asyncio wait was cancelled; canceling unfinished event listeners.')
151
+ raise
152
+ finally:
153
+ for task in tasks:
154
+ if not task.done():
155
+ task.cancel()
156
+ with suppress(asyncio.CancelledError):
157
+ await task
File without changes
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Coroutine
4
+ from dataclasses import dataclass
5
+ from enum import Enum
6
+ from typing import TYPE_CHECKING, Any, Union
7
+
8
+ if TYPE_CHECKING:
9
+ from crawlee.autoscaling.system_status import SystemInfo
10
+
11
+
12
+ class Event(Enum):
13
+ """Enum of all possible events that can be emitted."""
14
+
15
+ PERSIST_STATE = 'persistState'
16
+ SYSTEM_INFO = 'systemInfo'
17
+ MIGRATING = 'migrating'
18
+ ABORTING = 'aborting'
19
+ EXIT = 'exit'
20
+
21
+
22
+ @dataclass
23
+ class EventPersistStateData:
24
+ """Data for the persist state event."""
25
+
26
+ is_migrating: bool
27
+
28
+
29
+ @dataclass
30
+ class EventSystemInfoData:
31
+ """Data for the system info event."""
32
+
33
+ system_info: SystemInfo
34
+
35
+
36
+ @dataclass
37
+ class EventMigratingData:
38
+ """Data for the migrating event."""
39
+
40
+
41
+ @dataclass
42
+ class EventAbortingData:
43
+ """Data for the aborting event."""
44
+
45
+
46
+ @dataclass
47
+ class EventExitData:
48
+ """Data for the exit event."""
49
+
50
+
51
+ EventData = Union[EventPersistStateData, EventSystemInfoData, EventMigratingData, EventAbortingData, EventExitData]
52
+ SyncListener = Callable[..., None]
53
+ AsyncListener = Callable[..., Coroutine[Any, Any, None]]
54
+ Listener = Union[SyncListener, AsyncListener]
55
+ WrappedListener = Callable[..., Coroutine[Any, Any, None]]
crawlee/log_config.py ADDED
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import textwrap
6
+ import traceback
7
+ from typing import Any
8
+
9
+ from colorama import Fore, Style, just_fix_windows_console
10
+
11
+ just_fix_windows_console()
12
+
13
+ _LOG_NAME_COLOR = Fore.LIGHTBLACK_EX
14
+
15
+ _LOG_LEVEL_COLOR = {
16
+ logging.DEBUG: Fore.BLUE,
17
+ logging.INFO: Fore.GREEN,
18
+ logging.WARNING: Fore.YELLOW,
19
+ logging.ERROR: Fore.RED,
20
+ logging.CRITICAL: Fore.RED,
21
+ }
22
+
23
+ _LOG_LEVEL_SHORT_ALIAS = {
24
+ logging.DEBUG: 'DEBUG',
25
+ logging.INFO: 'INFO ',
26
+ logging.WARNING: 'WARN ',
27
+ logging.ERROR: 'ERROR',
28
+ }
29
+
30
+ # So that all the log messages have the same alignment
31
+ _LOG_MESSAGE_INDENT = ' ' * 6
32
+
33
+
34
+ class CrawleeLogFormatter(logging.Formatter):
35
+ """Log formatter that prints out the log message nicely formatted, with colored level and stringified extra fields.
36
+
37
+ It formats the log records so that they:
38
+ - start with the level (colorized, and padded to 5 chars so that it is nicely aligned)
39
+ - then have the actual log message, if it's multiline then it's nicely indented
40
+ - then have the stringified extra log fields
41
+ - then, if an exception is a part of the log record, prints the formatted exception.
42
+ """
43
+
44
+ # The fields that are added to the log record with `logger.log(..., extra={...})` are just merged in the log record
45
+ # with the other log record properties, and you can't get them in some nice, isolated way. So, to get the extra
46
+ # fields, we just compare all the properties present in the log record with properties present in an empty log
47
+ # record, and extract all the extra ones not present in the empty log record.
48
+ empty_record = logging.LogRecord('dummy', 0, 'dummy', 0, 'dummy', None, None)
49
+
50
+ def __init__(
51
+ self: CrawleeLogFormatter,
52
+ include_logger_name: bool = False, # noqa: FBT001, FBT002
53
+ *args: Any,
54
+ **kwargs: Any,
55
+ ) -> None:
56
+ """Create a new instance.
57
+
58
+ Args:
59
+ include_logger_name: Include logger name at the beginning of the log line. Defaults to False.
60
+ args: Arguments passed to the parent class.
61
+ kwargs: Keyword arguments passed to the parent class.
62
+ """
63
+ super().__init__(*args, **kwargs)
64
+ self.include_logger_name = include_logger_name
65
+
66
+ def _get_extra_fields(self: CrawleeLogFormatter, record: logging.LogRecord) -> dict[str, Any]:
67
+ extra_fields: dict[str, Any] = {}
68
+ for key, value in record.__dict__.items():
69
+ if key not in self.empty_record.__dict__:
70
+ extra_fields[key] = value
71
+
72
+ return extra_fields
73
+
74
+ def format(self: CrawleeLogFormatter, record: logging.LogRecord) -> str:
75
+ """Format the log record nicely.
76
+
77
+ This formats the log record so that it:
78
+ - starts with the level (colorized, and padded to 5 chars so that it is nicely aligned)
79
+ - then has the actual log message, if it's multiline then it's nicely indented
80
+ - then has the stringified extra log fields
81
+ - then, if an exception is a part of the log record, prints the formatted exception.
82
+ """
83
+ logger_name_string = f'{_LOG_NAME_COLOR}[{record.name}]{Style.RESET_ALL} '
84
+
85
+ # Colorize the log level, and shorten it to 6 chars tops
86
+ level_color_code = _LOG_LEVEL_COLOR.get(record.levelno, '')
87
+ level_short_alias = _LOG_LEVEL_SHORT_ALIAS.get(record.levelno, record.levelname)
88
+ level_string = f'{level_color_code}{level_short_alias}{Style.RESET_ALL} '
89
+
90
+ # Format the exception, if there is some
91
+ # Basically just print the traceback and indent it a bit
92
+ exception_string = ''
93
+ if record.exc_info:
94
+ exc_info = record.exc_info
95
+ record.exc_info = None
96
+ exception_string = ''.join(traceback.format_exception(*exc_info)).rstrip()
97
+ exception_string = '\n' + textwrap.indent(exception_string, _LOG_MESSAGE_INDENT)
98
+
99
+ # Format the extra log record fields, if there were some
100
+ # Just stringify them to JSON and color them gray
101
+ extra_string = ''
102
+ extra = self._get_extra_fields(record)
103
+ if extra:
104
+ extra_string = (
105
+ f' {Fore.LIGHTBLACK_EX}({json.dumps(extra, ensure_ascii=False, default=str)}){Style.RESET_ALL}'
106
+ )
107
+
108
+ # Format the actual log message, and indent everything but the first line
109
+ log_string = super().format(record)
110
+ log_string = textwrap.indent(log_string, _LOG_MESSAGE_INDENT).lstrip()
111
+
112
+ if self.include_logger_name:
113
+ # Include logger name at the beginning of the log line
114
+ return f'{logger_name_string}{level_string}{log_string}{extra_string}{exception_string}'
115
+
116
+ return f'{level_string}{log_string}{extra_string}{exception_string}'
crawlee/py.typed ADDED
File without changes
crawlee/utils.py ADDED
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ def weighted_avg(values: list[float], weights: list[float]) -> float:
5
+ """Computes a weighted average of an array of numbers, complemented by an array of weights.
6
+
7
+ Args:
8
+ values: List of values.
9
+ weights: List of weights.
10
+
11
+ Raises:
12
+ ValueError: If total weight is zero.
13
+
14
+ Returns:
15
+ float: Weighted average.
16
+ """
17
+ result = sum(value * weight for value, weight in zip(values, weights, strict=True))
18
+ total_weight = sum(weights)
19
+
20
+ if total_weight == 0:
21
+ raise ValueError('Total weight cannot be zero')
22
+
23
+ return result / total_weight
@@ -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 2023 Apify Technologies s.r.o.
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,34 @@
1
+ Metadata-Version: 2.1
2
+ Name: crawlee
3
+ Version: 0.0.1
4
+ Summary: Crawlee for Python
5
+ Home-page: https://todo.com/
6
+ License: Apache-2.0
7
+ Keywords: apify,automation,chrome,crawlee,crawler,headless,scraper,scraping
8
+ Author: Apify Technologies s.r.o.
9
+ Author-email: support@apify.com
10
+ Requires-Python: >=3.9,<4.0
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Requires-Dist: colorama (>=0.4.6,<0.5.0)
22
+ Requires-Dist: more_itertools (>=10.2.0,<11.0.0)
23
+ Requires-Dist: pyee (>=11.1.0,<12.0.0)
24
+ Requires-Dist: typing-extensions (>=4.1.0,<5.0.0)
25
+ Project-URL: Apify Homepage, https://apify.com
26
+ Project-URL: Changelog, https://github.com/apify/crawlee-py/blob/master/CHANGELOG.md
27
+ Project-URL: Documentation, https://todo.com/
28
+ Project-URL: Issue tracker, https://github.com/apify/crawlee-py/issues
29
+ Project-URL: Repository, https://github.com/apify/crawlee-py
30
+ Project-URL: Source, https://github.com/apify/crawlee-py
31
+ Description-Content-Type: text/markdown
32
+
33
+ # Crawlee Python
34
+
@@ -0,0 +1,16 @@
1
+ crawlee/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ crawlee/autoscaling/__init__.py,sha256=Tr9wCzbdF085Mp1MEpHQnfIdG0lEjM6SWLBy75GDt-Y,77
3
+ crawlee/autoscaling/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ crawlee/autoscaling/snapshotter.py,sha256=0U6258QEpetWXggBsTSqZADLAroTjEmJfkAUQeIWOkw,4198
5
+ crawlee/autoscaling/system_status.py,sha256=tdJL7RBhVD83qtvuQuOMl3QBKxJwPS6CwnP7TuAHy1s,10458
6
+ crawlee/events/__init__.py,sha256=7vxm0MJnDgy-64w__M6VcTqpX05Op-IP5LR0Y25NV0I,40
7
+ crawlee/events/event_manager.py,sha256=IIaFcbvhFtVKwZP64lf2PYXndI_0s4WmKQaUUOJ5KLA,6967
8
+ crawlee/events/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ crawlee/events/types.py,sha256=Rp2kTRE_2Y6sNLTQkZGsE58zmydDaqK3OV1RHUrrkBA,1245
10
+ crawlee/log_config.py,sha256=tpI18_2AMjOaEx1McCiQxpmAsPJPN97PafgjxWDuj_g,4802
11
+ crawlee/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ crawlee/utils.py,sha256=_vK2gt8Nz5ic7WnIVZKpnIKFEhHtxXJJD6n_BQMES00,630
13
+ crawlee-0.0.1.dist-info/LICENSE,sha256=AsFjHssKjj4LGd2ZCqXn6FBzMqcWdjQre1byPPSypVw,11355
14
+ crawlee-0.0.1.dist-info/METADATA,sha256=gTvMxx8jEcGTg0ZJuO0OLIjrscBBWfWkzW0r9IVFCAE,1411
15
+ crawlee-0.0.1.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
16
+ crawlee-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.8.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any