meshagent-commoncrawl 0.39.3__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.
- meshagent_commoncrawl-0.39.3/LICENSE +201 -0
- meshagent_commoncrawl-0.39.3/MANIFEST.in +2 -0
- meshagent_commoncrawl-0.39.3/PKG-INFO +51 -0
- meshagent_commoncrawl-0.39.3/README.md +33 -0
- meshagent_commoncrawl-0.39.3/meshagent/commoncrawl/__init__.py +17 -0
- meshagent_commoncrawl-0.39.3/meshagent/commoncrawl/commoncrawl.py +595 -0
- meshagent_commoncrawl-0.39.3/meshagent/commoncrawl/py.typed +1 -0
- meshagent_commoncrawl-0.39.3/meshagent/commoncrawl/version.py +1 -0
- meshagent_commoncrawl-0.39.3/meshagent_commoncrawl.egg-info/PKG-INFO +51 -0
- meshagent_commoncrawl-0.39.3/meshagent_commoncrawl.egg-info/SOURCES.txt +14 -0
- meshagent_commoncrawl-0.39.3/meshagent_commoncrawl.egg-info/dependency_links.txt +1 -0
- meshagent_commoncrawl-0.39.3/meshagent_commoncrawl.egg-info/requires.txt +5 -0
- meshagent_commoncrawl-0.39.3/meshagent_commoncrawl.egg-info/top_level.txt +1 -0
- meshagent_commoncrawl-0.39.3/pyproject.toml +32 -0
- meshagent_commoncrawl-0.39.3/setup.cfg +4 -0
- meshagent_commoncrawl-0.39.3/tests/test_commoncrawl.py +301 -0
|
@@ -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,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-commoncrawl
|
|
3
|
+
Version: 0.39.3
|
|
4
|
+
Summary: Common Crawl import support for Meshagent datasets
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pytest~=8.4
|
|
13
|
+
Requires-Dist: pytest-asyncio~=0.26
|
|
14
|
+
Requires-Dist: meshagent-api==0.39.3
|
|
15
|
+
Requires-Dist: pyarrow~=21.0.0
|
|
16
|
+
Requires-Dist: warcio~=1.7
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# Meshagent Common Crawl
|
|
20
|
+
|
|
21
|
+
Import Common Crawl captures into a Meshagent room dataset.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from meshagent.commoncrawl import import_domain_from_commoncrawl
|
|
25
|
+
|
|
26
|
+
result = await import_domain_from_commoncrawl(
|
|
27
|
+
room,
|
|
28
|
+
index="CC-MAIN-2025-08",
|
|
29
|
+
domain="example.com",
|
|
30
|
+
table="pages",
|
|
31
|
+
url_filter=r"https?://(www\.)?example\.com/docs/.*",
|
|
32
|
+
)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
To test it through `meshagent room connect`:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
meshagent room connect --room=my-room --identity=commoncrawl -- \
|
|
39
|
+
python meshagent-sdk/meshagent-commoncrawl/examples/crawl.py \
|
|
40
|
+
http://www.meshagent.com --table=sample --namespace=crawls --limit=10
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The sample command writes progress to stderr while it imports. TTY output uses a
|
|
44
|
+
single updating line; redirected output uses plain log lines. Pass `--silent` to
|
|
45
|
+
suppress progress output.
|
|
46
|
+
|
|
47
|
+
By default, records are merged on `url` with the columns `url`, `date`,
|
|
48
|
+
`content_type`, and `text`. Pass an async `extract=` callback to derive custom
|
|
49
|
+
columns from the WARC record and decoded content bytes. Return `None` from the
|
|
50
|
+
callback to skip the record. Pass an async `progress=` callback to observe import
|
|
51
|
+
progress from library code.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Meshagent Common Crawl
|
|
2
|
+
|
|
3
|
+
Import Common Crawl captures into a Meshagent room dataset.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from meshagent.commoncrawl import import_domain_from_commoncrawl
|
|
7
|
+
|
|
8
|
+
result = await import_domain_from_commoncrawl(
|
|
9
|
+
room,
|
|
10
|
+
index="CC-MAIN-2025-08",
|
|
11
|
+
domain="example.com",
|
|
12
|
+
table="pages",
|
|
13
|
+
url_filter=r"https?://(www\.)?example\.com/docs/.*",
|
|
14
|
+
)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
To test it through `meshagent room connect`:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
meshagent room connect --room=my-room --identity=commoncrawl -- \
|
|
21
|
+
python meshagent-sdk/meshagent-commoncrawl/examples/crawl.py \
|
|
22
|
+
http://www.meshagent.com --table=sample --namespace=crawls --limit=10
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The sample command writes progress to stderr while it imports. TTY output uses a
|
|
26
|
+
single updating line; redirected output uses plain log lines. Pass `--silent` to
|
|
27
|
+
suppress progress output.
|
|
28
|
+
|
|
29
|
+
By default, records are merged on `url` with the columns `url`, `date`,
|
|
30
|
+
`content_type`, and `text`. Pass an async `extract=` callback to derive custom
|
|
31
|
+
columns from the WARC record and decoded content bytes. Return `None` from the
|
|
32
|
+
callback to skip the record. Pass an async `progress=` callback to observe import
|
|
33
|
+
progress from library code.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .commoncrawl import (
|
|
2
|
+
CommonCrawlImportProgress,
|
|
3
|
+
CommonCrawlImportResult,
|
|
4
|
+
ExtractCallback,
|
|
5
|
+
ProgressCallback,
|
|
6
|
+
import_domain_from_commoncrawl,
|
|
7
|
+
)
|
|
8
|
+
from .version import __version__
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"CommonCrawlImportResult",
|
|
12
|
+
"CommonCrawlImportProgress",
|
|
13
|
+
"ExtractCallback",
|
|
14
|
+
"ProgressCallback",
|
|
15
|
+
"__version__",
|
|
16
|
+
"import_domain_from_commoncrawl",
|
|
17
|
+
]
|
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from html.parser import HTMLParser
|
|
7
|
+
from io import BytesIO
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
from typing import TYPE_CHECKING, Any, TypeAlias
|
|
11
|
+
from urllib.parse import parse_qsl, urlencode, urlparse
|
|
12
|
+
|
|
13
|
+
import pyarrow as pa
|
|
14
|
+
|
|
15
|
+
from meshagent.api import RoomClient
|
|
16
|
+
from meshagent.api.http import new_client_session
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from aiohttp import ClientSession
|
|
20
|
+
from warcio.recordloader import ArcWarcRecord
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
COMMONCRAWL_INDEX_BASE_URL = "https://index.commoncrawl.org"
|
|
25
|
+
COMMONCRAWL_DATA_BASE_URL = "https://data.commoncrawl.org"
|
|
26
|
+
|
|
27
|
+
ExtractedRecord: TypeAlias = Mapping[str, Any]
|
|
28
|
+
ExtractCallback: TypeAlias = Callable[
|
|
29
|
+
["ArcWarcRecord", bytes],
|
|
30
|
+
Awaitable[ExtractedRecord | None],
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class CommonCrawlImportResult:
|
|
36
|
+
matched_records: int
|
|
37
|
+
imported_records: int
|
|
38
|
+
skipped_records: int
|
|
39
|
+
files_read: int
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class CommonCrawlImportProgress:
|
|
44
|
+
stage: str
|
|
45
|
+
matched_records: int
|
|
46
|
+
imported_records: int
|
|
47
|
+
skipped_records: int
|
|
48
|
+
files_read: int
|
|
49
|
+
pending_records: int
|
|
50
|
+
current_url: str | None = None
|
|
51
|
+
current_file: str | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
ProgressCallback: TypeAlias = Callable[
|
|
55
|
+
[CommonCrawlImportProgress],
|
|
56
|
+
Awaitable[None],
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class _CdxRecord:
|
|
62
|
+
url: str
|
|
63
|
+
timestamp: str
|
|
64
|
+
mime: str | None
|
|
65
|
+
filename: str
|
|
66
|
+
offset: int
|
|
67
|
+
length: int
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def from_json(value: Mapping[str, Any]) -> _CdxRecord:
|
|
71
|
+
url = value["url"]
|
|
72
|
+
timestamp = value["timestamp"]
|
|
73
|
+
filename = value["filename"]
|
|
74
|
+
offset = value["offset"]
|
|
75
|
+
length = value["length"]
|
|
76
|
+
if not isinstance(url, str):
|
|
77
|
+
raise ValueError("Common Crawl index record has non-string url")
|
|
78
|
+
if not isinstance(timestamp, str):
|
|
79
|
+
raise ValueError("Common Crawl index record has non-string timestamp")
|
|
80
|
+
if not isinstance(filename, str):
|
|
81
|
+
raise ValueError("Common Crawl index record has non-string filename")
|
|
82
|
+
|
|
83
|
+
mime_value = value.get("mime")
|
|
84
|
+
if mime_value is not None and not isinstance(mime_value, str):
|
|
85
|
+
mime_value = str(mime_value)
|
|
86
|
+
|
|
87
|
+
return _CdxRecord(
|
|
88
|
+
url=url,
|
|
89
|
+
timestamp=timestamp,
|
|
90
|
+
mime=mime_value,
|
|
91
|
+
filename=filename,
|
|
92
|
+
offset=int(offset),
|
|
93
|
+
length=int(length),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _TextExtractor(HTMLParser):
|
|
98
|
+
def __init__(self) -> None:
|
|
99
|
+
super().__init__(convert_charrefs=True)
|
|
100
|
+
self._parts: list[str] = []
|
|
101
|
+
self._hidden_depth = 0
|
|
102
|
+
|
|
103
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
104
|
+
del attrs
|
|
105
|
+
if tag.lower() in {"script", "style", "noscript"}:
|
|
106
|
+
self._hidden_depth += 1
|
|
107
|
+
|
|
108
|
+
def handle_endtag(self, tag: str) -> None:
|
|
109
|
+
if tag.lower() in {"script", "style", "noscript"} and self._hidden_depth > 0:
|
|
110
|
+
self._hidden_depth -= 1
|
|
111
|
+
|
|
112
|
+
def handle_data(self, data: str) -> None:
|
|
113
|
+
if self._hidden_depth == 0:
|
|
114
|
+
stripped = data.strip()
|
|
115
|
+
if stripped:
|
|
116
|
+
self._parts.append(stripped)
|
|
117
|
+
|
|
118
|
+
def text(self) -> str:
|
|
119
|
+
return " ".join(self._parts)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def import_domain_from_commoncrawl(
|
|
123
|
+
room: RoomClient,
|
|
124
|
+
*,
|
|
125
|
+
index: str,
|
|
126
|
+
domain: str,
|
|
127
|
+
table: str = "commoncrawl",
|
|
128
|
+
url_filter: str | Sequence[str] | None = None,
|
|
129
|
+
extract: ExtractCallback | None = None,
|
|
130
|
+
schema: pa.Schema | None = None,
|
|
131
|
+
primary_key: str = "url",
|
|
132
|
+
namespace: list[str] | None = None,
|
|
133
|
+
branch: str | None = None,
|
|
134
|
+
limit: int | None = None,
|
|
135
|
+
batch_size: int = 100,
|
|
136
|
+
session: "ClientSession | None" = None,
|
|
137
|
+
progress: ProgressCallback | None = None,
|
|
138
|
+
) -> CommonCrawlImportResult:
|
|
139
|
+
"""Import Common Crawl captures for a domain into a room dataset.
|
|
140
|
+
|
|
141
|
+
`url_filter` is passed to the Common Crawl CDX API as `filter=~url:<value>`.
|
|
142
|
+
Supply a sequence to pass multiple URL filters. The default extractor writes
|
|
143
|
+
`url`, `date`, `content_type`, and `text`, merging on `url`. Pass `schema`
|
|
144
|
+
when a custom extractor should create an empty table before the first row.
|
|
145
|
+
Pass `progress` to receive async progress updates during the import.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
if batch_size <= 0:
|
|
149
|
+
raise ValueError("batch_size must be greater than zero")
|
|
150
|
+
if primary_key == "":
|
|
151
|
+
raise ValueError("primary_key must be non-empty")
|
|
152
|
+
|
|
153
|
+
close_session = session is None
|
|
154
|
+
http_session = session or new_client_session()
|
|
155
|
+
try:
|
|
156
|
+
return await _import_with_session(
|
|
157
|
+
room=room,
|
|
158
|
+
session=http_session,
|
|
159
|
+
index=index,
|
|
160
|
+
domain=domain,
|
|
161
|
+
table=table,
|
|
162
|
+
url_filter=url_filter,
|
|
163
|
+
extract=extract,
|
|
164
|
+
schema=schema,
|
|
165
|
+
primary_key=primary_key,
|
|
166
|
+
namespace=namespace,
|
|
167
|
+
branch=branch,
|
|
168
|
+
limit=limit,
|
|
169
|
+
batch_size=batch_size,
|
|
170
|
+
progress=progress,
|
|
171
|
+
)
|
|
172
|
+
finally:
|
|
173
|
+
if close_session:
|
|
174
|
+
await http_session.close()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
async def _import_with_session(
|
|
178
|
+
*,
|
|
179
|
+
room: RoomClient,
|
|
180
|
+
session: "ClientSession",
|
|
181
|
+
index: str,
|
|
182
|
+
domain: str,
|
|
183
|
+
table: str,
|
|
184
|
+
url_filter: str | Sequence[str] | None,
|
|
185
|
+
extract: ExtractCallback | None,
|
|
186
|
+
schema: pa.Schema | None,
|
|
187
|
+
primary_key: str,
|
|
188
|
+
namespace: list[str] | None,
|
|
189
|
+
branch: str | None,
|
|
190
|
+
limit: int | None,
|
|
191
|
+
batch_size: int,
|
|
192
|
+
progress: ProgressCallback | None,
|
|
193
|
+
) -> CommonCrawlImportResult:
|
|
194
|
+
extractor = extract or _default_extract
|
|
195
|
+
schema = schema or (_default_schema() if extract is None else None)
|
|
196
|
+
if schema is not None:
|
|
197
|
+
await _ensure_table(
|
|
198
|
+
room=room,
|
|
199
|
+
table=table,
|
|
200
|
+
schema=schema,
|
|
201
|
+
namespace=namespace,
|
|
202
|
+
branch=branch,
|
|
203
|
+
)
|
|
204
|
+
matched_records = 0
|
|
205
|
+
imported_records = 0
|
|
206
|
+
skipped_records = 0
|
|
207
|
+
files_read = 0
|
|
208
|
+
batch: list[dict[str, Any]] = []
|
|
209
|
+
await _report_progress(
|
|
210
|
+
progress,
|
|
211
|
+
stage="started",
|
|
212
|
+
matched_records=matched_records,
|
|
213
|
+
imported_records=imported_records,
|
|
214
|
+
skipped_records=skipped_records,
|
|
215
|
+
files_read=files_read,
|
|
216
|
+
pending_records=len(batch),
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
async for index_record in _iter_index_records(
|
|
220
|
+
session=session,
|
|
221
|
+
index=index,
|
|
222
|
+
domain=domain,
|
|
223
|
+
url_filter=url_filter,
|
|
224
|
+
limit=limit,
|
|
225
|
+
):
|
|
226
|
+
matched_records += 1
|
|
227
|
+
files_read += 1
|
|
228
|
+
await _report_progress(
|
|
229
|
+
progress,
|
|
230
|
+
stage="record_matched",
|
|
231
|
+
matched_records=matched_records,
|
|
232
|
+
imported_records=imported_records,
|
|
233
|
+
skipped_records=skipped_records,
|
|
234
|
+
files_read=files_read,
|
|
235
|
+
pending_records=len(batch),
|
|
236
|
+
current_url=index_record.url,
|
|
237
|
+
current_file=index_record.filename,
|
|
238
|
+
)
|
|
239
|
+
try:
|
|
240
|
+
async for warc_record, content in _iter_warc_records(
|
|
241
|
+
session=session,
|
|
242
|
+
index_record=index_record,
|
|
243
|
+
):
|
|
244
|
+
extracted = await extractor(warc_record, content)
|
|
245
|
+
if extracted is None:
|
|
246
|
+
skipped_records += 1
|
|
247
|
+
await _report_progress(
|
|
248
|
+
progress,
|
|
249
|
+
stage="record_skipped",
|
|
250
|
+
matched_records=matched_records,
|
|
251
|
+
imported_records=imported_records,
|
|
252
|
+
skipped_records=skipped_records,
|
|
253
|
+
files_read=files_read,
|
|
254
|
+
pending_records=len(batch),
|
|
255
|
+
current_url=index_record.url,
|
|
256
|
+
current_file=index_record.filename,
|
|
257
|
+
)
|
|
258
|
+
continue
|
|
259
|
+
row = dict(extracted)
|
|
260
|
+
if primary_key not in row:
|
|
261
|
+
raise ValueError(
|
|
262
|
+
f"extract callback must return primary key column {primary_key!r}"
|
|
263
|
+
)
|
|
264
|
+
batch.append(row)
|
|
265
|
+
await _report_progress(
|
|
266
|
+
progress,
|
|
267
|
+
stage="record_extracted",
|
|
268
|
+
matched_records=matched_records,
|
|
269
|
+
imported_records=imported_records,
|
|
270
|
+
skipped_records=skipped_records,
|
|
271
|
+
files_read=files_read,
|
|
272
|
+
pending_records=len(batch),
|
|
273
|
+
current_url=index_record.url,
|
|
274
|
+
current_file=index_record.filename,
|
|
275
|
+
)
|
|
276
|
+
if len(batch) >= batch_size:
|
|
277
|
+
schema = await _merge_batch(
|
|
278
|
+
room=room,
|
|
279
|
+
table=table,
|
|
280
|
+
rows=batch,
|
|
281
|
+
schema=schema,
|
|
282
|
+
primary_key=primary_key,
|
|
283
|
+
namespace=namespace,
|
|
284
|
+
branch=branch,
|
|
285
|
+
)
|
|
286
|
+
imported_records += len(batch)
|
|
287
|
+
batch = []
|
|
288
|
+
await _report_progress(
|
|
289
|
+
progress,
|
|
290
|
+
stage="batch_merged",
|
|
291
|
+
matched_records=matched_records,
|
|
292
|
+
imported_records=imported_records,
|
|
293
|
+
skipped_records=skipped_records,
|
|
294
|
+
files_read=files_read,
|
|
295
|
+
pending_records=len(batch),
|
|
296
|
+
current_url=index_record.url,
|
|
297
|
+
current_file=index_record.filename,
|
|
298
|
+
)
|
|
299
|
+
except Exception:
|
|
300
|
+
logger.exception(
|
|
301
|
+
"failed to import Common Crawl record %s from %s",
|
|
302
|
+
index_record.url,
|
|
303
|
+
index_record.filename,
|
|
304
|
+
)
|
|
305
|
+
raise
|
|
306
|
+
|
|
307
|
+
if batch:
|
|
308
|
+
await _merge_batch(
|
|
309
|
+
room=room,
|
|
310
|
+
table=table,
|
|
311
|
+
rows=batch,
|
|
312
|
+
schema=schema,
|
|
313
|
+
primary_key=primary_key,
|
|
314
|
+
namespace=namespace,
|
|
315
|
+
branch=branch,
|
|
316
|
+
)
|
|
317
|
+
imported_records += len(batch)
|
|
318
|
+
batch = []
|
|
319
|
+
await _report_progress(
|
|
320
|
+
progress,
|
|
321
|
+
stage="batch_merged",
|
|
322
|
+
matched_records=matched_records,
|
|
323
|
+
imported_records=imported_records,
|
|
324
|
+
skipped_records=skipped_records,
|
|
325
|
+
files_read=files_read,
|
|
326
|
+
pending_records=len(batch),
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
result = CommonCrawlImportResult(
|
|
330
|
+
matched_records=matched_records,
|
|
331
|
+
imported_records=imported_records,
|
|
332
|
+
skipped_records=skipped_records,
|
|
333
|
+
files_read=files_read,
|
|
334
|
+
)
|
|
335
|
+
await _report_progress(
|
|
336
|
+
progress,
|
|
337
|
+
stage="completed",
|
|
338
|
+
matched_records=result.matched_records,
|
|
339
|
+
imported_records=result.imported_records,
|
|
340
|
+
skipped_records=result.skipped_records,
|
|
341
|
+
files_read=result.files_read,
|
|
342
|
+
pending_records=0,
|
|
343
|
+
)
|
|
344
|
+
return result
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
async def _report_progress(
|
|
348
|
+
progress: ProgressCallback | None,
|
|
349
|
+
*,
|
|
350
|
+
stage: str,
|
|
351
|
+
matched_records: int,
|
|
352
|
+
imported_records: int,
|
|
353
|
+
skipped_records: int,
|
|
354
|
+
files_read: int,
|
|
355
|
+
pending_records: int,
|
|
356
|
+
current_url: str | None = None,
|
|
357
|
+
current_file: str | None = None,
|
|
358
|
+
) -> None:
|
|
359
|
+
if progress is None:
|
|
360
|
+
return
|
|
361
|
+
await progress(
|
|
362
|
+
CommonCrawlImportProgress(
|
|
363
|
+
stage=stage,
|
|
364
|
+
matched_records=matched_records,
|
|
365
|
+
imported_records=imported_records,
|
|
366
|
+
skipped_records=skipped_records,
|
|
367
|
+
files_read=files_read,
|
|
368
|
+
pending_records=pending_records,
|
|
369
|
+
current_url=current_url,
|
|
370
|
+
current_file=current_file,
|
|
371
|
+
)
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
async def _merge_batch(
|
|
376
|
+
*,
|
|
377
|
+
room: RoomClient,
|
|
378
|
+
table: str,
|
|
379
|
+
rows: list[dict[str, Any]],
|
|
380
|
+
schema: pa.Schema | None,
|
|
381
|
+
primary_key: str,
|
|
382
|
+
namespace: list[str] | None,
|
|
383
|
+
branch: str | None,
|
|
384
|
+
) -> pa.Schema:
|
|
385
|
+
next_schema = _merge_schema(
|
|
386
|
+
base=schema,
|
|
387
|
+
rows=rows,
|
|
388
|
+
primary_key=primary_key,
|
|
389
|
+
)
|
|
390
|
+
await _ensure_table(
|
|
391
|
+
room=room,
|
|
392
|
+
table=table,
|
|
393
|
+
schema=next_schema,
|
|
394
|
+
namespace=namespace,
|
|
395
|
+
branch=branch,
|
|
396
|
+
)
|
|
397
|
+
await room.datasets.merge(
|
|
398
|
+
table=table,
|
|
399
|
+
on=primary_key,
|
|
400
|
+
records=pa.Table.from_pylist(rows, schema=next_schema),
|
|
401
|
+
namespace=namespace,
|
|
402
|
+
branch=branch,
|
|
403
|
+
)
|
|
404
|
+
return next_schema
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
async def _ensure_table(
|
|
408
|
+
*,
|
|
409
|
+
room: RoomClient,
|
|
410
|
+
table: str,
|
|
411
|
+
schema: pa.Schema,
|
|
412
|
+
namespace: list[str] | None,
|
|
413
|
+
branch: str | None,
|
|
414
|
+
) -> None:
|
|
415
|
+
await room.datasets.create_table_with_schema(
|
|
416
|
+
name=table,
|
|
417
|
+
schema=schema,
|
|
418
|
+
mode="create_if_not_exists",
|
|
419
|
+
namespace=namespace,
|
|
420
|
+
branch=branch,
|
|
421
|
+
)
|
|
422
|
+
existing_schema = await room.datasets.inspect(
|
|
423
|
+
table=table,
|
|
424
|
+
namespace=namespace,
|
|
425
|
+
branch=branch,
|
|
426
|
+
)
|
|
427
|
+
existing_names = set(existing_schema.names)
|
|
428
|
+
missing_fields = {
|
|
429
|
+
field.name: field for field in schema if field.name not in existing_names
|
|
430
|
+
}
|
|
431
|
+
if missing_fields:
|
|
432
|
+
await room.datasets.add_columns(
|
|
433
|
+
table=table,
|
|
434
|
+
new_columns=missing_fields,
|
|
435
|
+
namespace=namespace,
|
|
436
|
+
branch=branch,
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
async def _iter_index_records(
|
|
441
|
+
*,
|
|
442
|
+
session: "ClientSession",
|
|
443
|
+
index: str,
|
|
444
|
+
domain: str,
|
|
445
|
+
url_filter: str | Sequence[str] | None,
|
|
446
|
+
limit: int | None,
|
|
447
|
+
) -> AsyncIterator[_CdxRecord]:
|
|
448
|
+
params: list[tuple[str, str]] = [
|
|
449
|
+
("url", _domain_index_query(domain)),
|
|
450
|
+
("matchType", "domain"),
|
|
451
|
+
("output", "json"),
|
|
452
|
+
("fl", "url,timestamp,mime,filename,offset,length"),
|
|
453
|
+
("filter", "status:200"),
|
|
454
|
+
]
|
|
455
|
+
for filter_value in _url_filters(url_filter):
|
|
456
|
+
params.append(("filter", f"~url:{filter_value}"))
|
|
457
|
+
if limit is not None:
|
|
458
|
+
params.append(("limit", str(limit)))
|
|
459
|
+
|
|
460
|
+
url = f"{_index_base_url(index)}?{urlencode(params)}"
|
|
461
|
+
async with session.get(url) as response:
|
|
462
|
+
if response.status == 404:
|
|
463
|
+
return
|
|
464
|
+
response.raise_for_status()
|
|
465
|
+
async for raw_line in response.content:
|
|
466
|
+
line = raw_line.decode("utf-8").strip()
|
|
467
|
+
if line == "":
|
|
468
|
+
continue
|
|
469
|
+
yield _CdxRecord.from_json(json.loads(line))
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
async def _iter_warc_records(
|
|
473
|
+
*,
|
|
474
|
+
session: "ClientSession",
|
|
475
|
+
index_record: _CdxRecord,
|
|
476
|
+
) -> AsyncIterator[tuple["ArcWarcRecord", bytes]]:
|
|
477
|
+
from warcio.archiveiterator import ArchiveIterator
|
|
478
|
+
|
|
479
|
+
end = index_record.offset + index_record.length - 1
|
|
480
|
+
headers = {"Range": f"bytes={index_record.offset}-{end}"}
|
|
481
|
+
url = f"{COMMONCRAWL_DATA_BASE_URL}/{index_record.filename}"
|
|
482
|
+
|
|
483
|
+
async with session.get(url, headers=headers) as response:
|
|
484
|
+
response.raise_for_status()
|
|
485
|
+
data = await response.read()
|
|
486
|
+
|
|
487
|
+
for warc_record in ArchiveIterator(BytesIO(data)):
|
|
488
|
+
if warc_record.rec_type != "response":
|
|
489
|
+
continue
|
|
490
|
+
yield warc_record, warc_record.content_stream().read()
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
async def _default_extract(record: "ArcWarcRecord", content: bytes) -> dict[str, str]:
|
|
494
|
+
content_type = _content_type(record)
|
|
495
|
+
text = _content_text(content=content, content_type=content_type)
|
|
496
|
+
return {
|
|
497
|
+
"url": record.rec_headers.get_header("WARC-Target-URI") or "",
|
|
498
|
+
"date": _warc_date(record.rec_headers.get_header("WARC-Date")),
|
|
499
|
+
"content_type": content_type,
|
|
500
|
+
"text": text,
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _content_type(record: "ArcWarcRecord") -> str:
|
|
505
|
+
content_type = ""
|
|
506
|
+
if record.http_headers is not None:
|
|
507
|
+
content_type = record.http_headers.get_header("Content-Type") or ""
|
|
508
|
+
if content_type == "":
|
|
509
|
+
content_type = record.rec_headers.get_header("Content-Type") or ""
|
|
510
|
+
return content_type
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _warc_date(value: str | None) -> str:
|
|
514
|
+
if value is None or value == "":
|
|
515
|
+
return ""
|
|
516
|
+
try:
|
|
517
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
518
|
+
except ValueError:
|
|
519
|
+
return value
|
|
520
|
+
return parsed.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _content_text(*, content: bytes, content_type: str) -> str:
|
|
524
|
+
charset = _charset(content_type)
|
|
525
|
+
decoded = content.decode(charset, errors="replace")
|
|
526
|
+
normalized_content_type = content_type.lower()
|
|
527
|
+
if "html" not in normalized_content_type and "xml" not in normalized_content_type:
|
|
528
|
+
return decoded
|
|
529
|
+
|
|
530
|
+
parser = _TextExtractor()
|
|
531
|
+
parser.feed(decoded)
|
|
532
|
+
parser.close()
|
|
533
|
+
return parser.text()
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _charset(content_type: str) -> str:
|
|
537
|
+
for key, value in parse_qsl(content_type.replace(";", "&"), keep_blank_values=True):
|
|
538
|
+
if key.strip().lower() == "charset" and value.strip() != "":
|
|
539
|
+
return value.strip()
|
|
540
|
+
return "utf-8"
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _default_schema() -> pa.Schema:
|
|
544
|
+
return pa.schema(
|
|
545
|
+
[
|
|
546
|
+
pa.field("url", pa.string(), nullable=False),
|
|
547
|
+
pa.field("date", pa.string()),
|
|
548
|
+
pa.field("content_type", pa.string()),
|
|
549
|
+
pa.field("text", pa.string()),
|
|
550
|
+
]
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _merge_schema(
|
|
555
|
+
*,
|
|
556
|
+
base: pa.Schema | None,
|
|
557
|
+
rows: list[dict[str, Any]],
|
|
558
|
+
primary_key: str,
|
|
559
|
+
) -> pa.Schema:
|
|
560
|
+
inferred = pa.Table.from_pylist(rows).schema
|
|
561
|
+
fields_by_name = {field.name: field for field in base} if base is not None else {}
|
|
562
|
+
for field in inferred:
|
|
563
|
+
if pa.types.is_null(field.type):
|
|
564
|
+
field = pa.field(field.name, pa.string(), nullable=field.nullable)
|
|
565
|
+
if field.name == primary_key:
|
|
566
|
+
field = pa.field(field.name, field.type, nullable=False)
|
|
567
|
+
fields_by_name.setdefault(field.name, field)
|
|
568
|
+
|
|
569
|
+
if primary_key not in fields_by_name:
|
|
570
|
+
raise ValueError(f"rows must include primary key column {primary_key!r}")
|
|
571
|
+
return pa.schema(list(fields_by_name.values()))
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _domain_index_query(domain: str) -> str:
|
|
575
|
+
parsed = urlparse(domain)
|
|
576
|
+
host = parsed.netloc or parsed.path.split("/", maxsplit=1)[0]
|
|
577
|
+
normalized = host.strip().strip(".").lower()
|
|
578
|
+
if normalized == "":
|
|
579
|
+
raise ValueError("domain must be non-empty")
|
|
580
|
+
return normalized
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _url_filters(url_filter: str | Sequence[str] | None) -> list[str]:
|
|
584
|
+
if url_filter is None:
|
|
585
|
+
return []
|
|
586
|
+
if isinstance(url_filter, str):
|
|
587
|
+
return [url_filter]
|
|
588
|
+
return list(url_filter)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def _index_base_url(index: str) -> str:
|
|
592
|
+
if index.startswith("http://") or index.startswith("https://"):
|
|
593
|
+
return index
|
|
594
|
+
normalized = index if index.endswith("-index") else f"{index}-index"
|
|
595
|
+
return f"{COMMONCRAWL_INDEX_BASE_URL}/{normalized}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.39.3"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-commoncrawl
|
|
3
|
+
Version: 0.39.3
|
|
4
|
+
Summary: Common Crawl import support for Meshagent datasets
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pytest~=8.4
|
|
13
|
+
Requires-Dist: pytest-asyncio~=0.26
|
|
14
|
+
Requires-Dist: meshagent-api==0.39.3
|
|
15
|
+
Requires-Dist: pyarrow~=21.0.0
|
|
16
|
+
Requires-Dist: warcio~=1.7
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# Meshagent Common Crawl
|
|
20
|
+
|
|
21
|
+
Import Common Crawl captures into a Meshagent room dataset.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from meshagent.commoncrawl import import_domain_from_commoncrawl
|
|
25
|
+
|
|
26
|
+
result = await import_domain_from_commoncrawl(
|
|
27
|
+
room,
|
|
28
|
+
index="CC-MAIN-2025-08",
|
|
29
|
+
domain="example.com",
|
|
30
|
+
table="pages",
|
|
31
|
+
url_filter=r"https?://(www\.)?example\.com/docs/.*",
|
|
32
|
+
)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
To test it through `meshagent room connect`:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
meshagent room connect --room=my-room --identity=commoncrawl -- \
|
|
39
|
+
python meshagent-sdk/meshagent-commoncrawl/examples/crawl.py \
|
|
40
|
+
http://www.meshagent.com --table=sample --namespace=crawls --limit=10
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The sample command writes progress to stderr while it imports. TTY output uses a
|
|
44
|
+
single updating line; redirected output uses plain log lines. Pass `--silent` to
|
|
45
|
+
suppress progress output.
|
|
46
|
+
|
|
47
|
+
By default, records are merged on `url` with the columns `url`, `date`,
|
|
48
|
+
`content_type`, and `text`. Pass an async `extract=` callback to derive custom
|
|
49
|
+
columns from the WARC record and decoded content bytes. Return `None` from the
|
|
50
|
+
callback to skip the record. Pass an async `progress=` callback to observe import
|
|
51
|
+
progress from library code.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
meshagent/commoncrawl/__init__.py
|
|
6
|
+
meshagent/commoncrawl/commoncrawl.py
|
|
7
|
+
meshagent/commoncrawl/py.typed
|
|
8
|
+
meshagent/commoncrawl/version.py
|
|
9
|
+
meshagent_commoncrawl.egg-info/PKG-INFO
|
|
10
|
+
meshagent_commoncrawl.egg-info/SOURCES.txt
|
|
11
|
+
meshagent_commoncrawl.egg-info/dependency_links.txt
|
|
12
|
+
meshagent_commoncrawl.egg-info/requires.txt
|
|
13
|
+
meshagent_commoncrawl.egg-info/top_level.txt
|
|
14
|
+
tests/test_commoncrawl.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
meshagent
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "meshagent-commoncrawl"
|
|
7
|
+
description = "Common Crawl import support for Meshagent datasets"
|
|
8
|
+
dynamic = ["version", "readme"]
|
|
9
|
+
requires-python = ">=3.13"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"pytest~=8.4",
|
|
13
|
+
"pytest-asyncio~=0.26",
|
|
14
|
+
"meshagent-api==0.39.3",
|
|
15
|
+
"pyarrow~=21.0.0",
|
|
16
|
+
"warcio~=1.7",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Documentation = "https://docs.meshagent.com"
|
|
21
|
+
Website = "https://www.meshagent.com"
|
|
22
|
+
Source = "https://www.meshagent.com"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["meshagent.*"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
"meshagent.commoncrawl" = ["py.typed", "*.pyi", "**/*.pyi"]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.dynamic]
|
|
31
|
+
version = {attr = "meshagent.commoncrawl.version.__version__"}
|
|
32
|
+
readme = { file = "README.md", content-type = "text/markdown" }
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pyarrow as pa
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from meshagent.commoncrawl import commoncrawl
|
|
11
|
+
from meshagent.commoncrawl.commoncrawl import CommonCrawlImportProgress, _CdxRecord
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _Headers:
|
|
15
|
+
def __init__(self, values: dict[str, str]) -> None:
|
|
16
|
+
self._values = values
|
|
17
|
+
|
|
18
|
+
def get_header(self, name: str) -> str | None:
|
|
19
|
+
return self._values.get(name)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _WarcRecord:
|
|
23
|
+
rec_type = "response"
|
|
24
|
+
|
|
25
|
+
def __init__(self, *, url: str, date: str, content_type: str) -> None:
|
|
26
|
+
self.rec_headers = _Headers(
|
|
27
|
+
{
|
|
28
|
+
"WARC-Target-URI": url,
|
|
29
|
+
"WARC-Date": date,
|
|
30
|
+
"Content-Type": "application/http; msgtype=response",
|
|
31
|
+
}
|
|
32
|
+
)
|
|
33
|
+
self.http_headers = _Headers({"Content-Type": content_type})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _FakeDatasets:
|
|
37
|
+
def __init__(self) -> None:
|
|
38
|
+
self.schema: pa.Schema | None = None
|
|
39
|
+
self.create_calls: list[dict[str, Any]] = []
|
|
40
|
+
self.add_columns_calls: list[dict[str, Any]] = []
|
|
41
|
+
self.merge_calls: list[dict[str, Any]] = []
|
|
42
|
+
|
|
43
|
+
async def create_table_with_schema(
|
|
44
|
+
self,
|
|
45
|
+
*,
|
|
46
|
+
name: str,
|
|
47
|
+
schema: pa.Schema,
|
|
48
|
+
mode: str,
|
|
49
|
+
namespace: list[str] | None = None,
|
|
50
|
+
branch: str | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
self.create_calls.append(
|
|
53
|
+
{
|
|
54
|
+
"name": name,
|
|
55
|
+
"schema": schema,
|
|
56
|
+
"mode": mode,
|
|
57
|
+
"namespace": namespace,
|
|
58
|
+
"branch": branch,
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
if self.schema is None:
|
|
62
|
+
self.schema = schema
|
|
63
|
+
|
|
64
|
+
async def inspect(
|
|
65
|
+
self,
|
|
66
|
+
*,
|
|
67
|
+
table: str,
|
|
68
|
+
namespace: list[str] | None = None,
|
|
69
|
+
branch: str | None = None,
|
|
70
|
+
) -> pa.Schema:
|
|
71
|
+
del table, namespace, branch
|
|
72
|
+
return self.schema or pa.schema([])
|
|
73
|
+
|
|
74
|
+
async def add_columns(
|
|
75
|
+
self,
|
|
76
|
+
*,
|
|
77
|
+
table: str,
|
|
78
|
+
new_columns: dict[str, pa.Field],
|
|
79
|
+
namespace: list[str] | None = None,
|
|
80
|
+
branch: str | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.add_columns_calls.append(
|
|
83
|
+
{
|
|
84
|
+
"table": table,
|
|
85
|
+
"new_columns": new_columns,
|
|
86
|
+
"namespace": namespace,
|
|
87
|
+
"branch": branch,
|
|
88
|
+
}
|
|
89
|
+
)
|
|
90
|
+
assert self.schema is not None
|
|
91
|
+
self.schema = self.schema.append(next(iter(new_columns.values())))
|
|
92
|
+
|
|
93
|
+
async def merge(
|
|
94
|
+
self,
|
|
95
|
+
*,
|
|
96
|
+
table: str,
|
|
97
|
+
on: str,
|
|
98
|
+
records: pa.Table,
|
|
99
|
+
namespace: list[str] | None = None,
|
|
100
|
+
branch: str | None = None,
|
|
101
|
+
) -> None:
|
|
102
|
+
self.merge_calls.append(
|
|
103
|
+
{
|
|
104
|
+
"table": table,
|
|
105
|
+
"on": on,
|
|
106
|
+
"records": records,
|
|
107
|
+
"namespace": namespace,
|
|
108
|
+
"branch": branch,
|
|
109
|
+
}
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class _FakeRoom:
|
|
115
|
+
datasets: _FakeDatasets
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _FakeSession:
|
|
119
|
+
async def close(self) -> None:
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
async def _fake_index_records(**kwargs: Any) -> AsyncIterator[_CdxRecord]:
|
|
124
|
+
del kwargs
|
|
125
|
+
yield _CdxRecord(
|
|
126
|
+
url="https://example.com/a",
|
|
127
|
+
timestamp="20240101000000",
|
|
128
|
+
mime="text/html",
|
|
129
|
+
filename="crawl/a.warc.gz",
|
|
130
|
+
offset=0,
|
|
131
|
+
length=10,
|
|
132
|
+
)
|
|
133
|
+
yield _CdxRecord(
|
|
134
|
+
url="https://example.com/b",
|
|
135
|
+
timestamp="20240101000001",
|
|
136
|
+
mime="text/html",
|
|
137
|
+
filename="crawl/b.warc.gz",
|
|
138
|
+
offset=10,
|
|
139
|
+
length=10,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def _fake_warc_records(
|
|
144
|
+
*,
|
|
145
|
+
index_record: _CdxRecord,
|
|
146
|
+
**kwargs: Any,
|
|
147
|
+
) -> AsyncIterator[tuple[_WarcRecord, bytes]]:
|
|
148
|
+
del kwargs
|
|
149
|
+
yield (
|
|
150
|
+
_WarcRecord(
|
|
151
|
+
url=index_record.url,
|
|
152
|
+
date="2024-01-01T00:00:00Z",
|
|
153
|
+
content_type="text/html; charset=utf-8",
|
|
154
|
+
),
|
|
155
|
+
b"<html><head><style>.x{}</style></head><body>Hello <b>page</b></body></html>",
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@pytest.mark.asyncio
|
|
160
|
+
async def test_import_domain_uses_default_columns_and_merge(monkeypatch) -> None:
|
|
161
|
+
monkeypatch.setattr(commoncrawl, "_iter_index_records", _fake_index_records)
|
|
162
|
+
monkeypatch.setattr(commoncrawl, "_iter_warc_records", _fake_warc_records)
|
|
163
|
+
room = _FakeRoom(datasets=_FakeDatasets())
|
|
164
|
+
|
|
165
|
+
result = await commoncrawl.import_domain_from_commoncrawl(
|
|
166
|
+
room, # type: ignore[arg-type]
|
|
167
|
+
index="CC-MAIN-2025-08",
|
|
168
|
+
domain="example.com",
|
|
169
|
+
table="pages",
|
|
170
|
+
batch_size=1,
|
|
171
|
+
session=_FakeSession(), # type: ignore[arg-type]
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
assert result.matched_records == 2
|
|
175
|
+
assert result.imported_records == 2
|
|
176
|
+
assert result.skipped_records == 0
|
|
177
|
+
assert room.datasets.create_calls[0]["mode"] == "create_if_not_exists"
|
|
178
|
+
assert room.datasets.merge_calls[0]["on"] == "url"
|
|
179
|
+
assert room.datasets.merge_calls[0]["records"].to_pylist() == [
|
|
180
|
+
{
|
|
181
|
+
"url": "https://example.com/a",
|
|
182
|
+
"date": "2024-01-01T00:00:00Z",
|
|
183
|
+
"content_type": "text/html; charset=utf-8",
|
|
184
|
+
"text": "Hello page",
|
|
185
|
+
}
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@pytest.mark.asyncio
|
|
190
|
+
async def test_extract_callback_can_filter_records(monkeypatch) -> None:
|
|
191
|
+
monkeypatch.setattr(commoncrawl, "_iter_index_records", _fake_index_records)
|
|
192
|
+
monkeypatch.setattr(commoncrawl, "_iter_warc_records", _fake_warc_records)
|
|
193
|
+
room = _FakeRoom(datasets=_FakeDatasets())
|
|
194
|
+
|
|
195
|
+
async def extract(record: _WarcRecord, content: bytes) -> dict[str, str] | None:
|
|
196
|
+
del content
|
|
197
|
+
url = record.rec_headers.get_header("WARC-Target-URI") or ""
|
|
198
|
+
if url.endswith("/b"):
|
|
199
|
+
return None
|
|
200
|
+
return {"url": url, "title": "A"}
|
|
201
|
+
|
|
202
|
+
result = await commoncrawl.import_domain_from_commoncrawl(
|
|
203
|
+
room, # type: ignore[arg-type]
|
|
204
|
+
index="CC-MAIN-2025-08",
|
|
205
|
+
domain="example.com",
|
|
206
|
+
extract=extract, # type: ignore[arg-type]
|
|
207
|
+
session=_FakeSession(), # type: ignore[arg-type]
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
assert result.matched_records == 2
|
|
211
|
+
assert result.imported_records == 1
|
|
212
|
+
assert result.skipped_records == 1
|
|
213
|
+
assert room.datasets.merge_calls[0]["records"].to_pylist() == [
|
|
214
|
+
{"url": "https://example.com/a", "title": "A"}
|
|
215
|
+
]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@pytest.mark.asyncio
|
|
219
|
+
async def test_import_domain_reports_progress(monkeypatch) -> None:
|
|
220
|
+
monkeypatch.setattr(commoncrawl, "_iter_index_records", _fake_index_records)
|
|
221
|
+
monkeypatch.setattr(commoncrawl, "_iter_warc_records", _fake_warc_records)
|
|
222
|
+
room = _FakeRoom(datasets=_FakeDatasets())
|
|
223
|
+
updates: list[CommonCrawlImportProgress] = []
|
|
224
|
+
|
|
225
|
+
async def progress(update: CommonCrawlImportProgress) -> None:
|
|
226
|
+
updates.append(update)
|
|
227
|
+
|
|
228
|
+
result = await commoncrawl.import_domain_from_commoncrawl(
|
|
229
|
+
room, # type: ignore[arg-type]
|
|
230
|
+
index="CC-MAIN-2025-08",
|
|
231
|
+
domain="example.com",
|
|
232
|
+
batch_size=2,
|
|
233
|
+
session=_FakeSession(), # type: ignore[arg-type]
|
|
234
|
+
progress=progress,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
assert result.imported_records == 2
|
|
238
|
+
assert [update.stage for update in updates] == [
|
|
239
|
+
"started",
|
|
240
|
+
"record_matched",
|
|
241
|
+
"record_extracted",
|
|
242
|
+
"record_matched",
|
|
243
|
+
"record_extracted",
|
|
244
|
+
"batch_merged",
|
|
245
|
+
"completed",
|
|
246
|
+
]
|
|
247
|
+
assert updates[-1].matched_records == 2
|
|
248
|
+
assert updates[-1].imported_records == 2
|
|
249
|
+
assert updates[-1].pending_records == 0
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def test_commoncrawl_index_url_helpers() -> None:
|
|
253
|
+
assert commoncrawl._domain_index_query("https://Example.COM/docs") == "example.com"
|
|
254
|
+
assert commoncrawl._url_filters(["a", "b"]) == ["a", "b"]
|
|
255
|
+
assert commoncrawl._index_base_url("CC-MAIN-2025-08").endswith(
|
|
256
|
+
"/CC-MAIN-2025-08-index"
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@pytest.mark.asyncio
|
|
261
|
+
async def test_index_404_is_treated_as_no_matches() -> None:
|
|
262
|
+
class _Content:
|
|
263
|
+
def __aiter__(self) -> AsyncIterator[bytes]:
|
|
264
|
+
return self._iter()
|
|
265
|
+
|
|
266
|
+
async def _iter(self) -> AsyncIterator[bytes]:
|
|
267
|
+
if False:
|
|
268
|
+
yield b""
|
|
269
|
+
|
|
270
|
+
class _Response:
|
|
271
|
+
status = 404
|
|
272
|
+
content = _Content()
|
|
273
|
+
|
|
274
|
+
async def __aenter__(self) -> _Response:
|
|
275
|
+
return self
|
|
276
|
+
|
|
277
|
+
async def __aexit__(self, *args: object) -> None:
|
|
278
|
+
return None
|
|
279
|
+
|
|
280
|
+
def raise_for_status(self) -> None:
|
|
281
|
+
raise AssertionError("404 should not raise")
|
|
282
|
+
|
|
283
|
+
class _Session:
|
|
284
|
+
def get(self, url: str) -> _Response:
|
|
285
|
+
assert "matchType=domain" in url
|
|
286
|
+
assert "url=www.hersheyland.com" in url
|
|
287
|
+
assert "filter=~url%3A%5Ehttps%3F%3A%2F%2Fwww" in url
|
|
288
|
+
return _Response()
|
|
289
|
+
|
|
290
|
+
rows = [
|
|
291
|
+
row
|
|
292
|
+
async for row in commoncrawl._iter_index_records(
|
|
293
|
+
session=_Session(), # type: ignore[arg-type]
|
|
294
|
+
index="CC-MAIN-2025-08",
|
|
295
|
+
domain="www.hersheyland.com",
|
|
296
|
+
url_filter=r"^https?://www\.hersheyland\.com(/.*)?$",
|
|
297
|
+
limit=None,
|
|
298
|
+
)
|
|
299
|
+
]
|
|
300
|
+
|
|
301
|
+
assert rows == []
|