david-ar commited on
Commit
743c8c5
·
verified ·
1 Parent(s): 2f27906

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. README.md +40 -0
  2. cc_digests_to_hex.py +46 -0
  3. cc_extract_job.py +156 -0
  4. dcso_bloom_build.py +97 -0
README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc0-1.0
3
+ pretty_name: Common Crawl document-digest bloom filter
4
+ tags:
5
+ - bloom-filter
6
+ - file-hashes
7
+ ---
8
+
9
+ # Common Crawl document-digest bloom filter
10
+
11
+ Membership filter over payload sha1 digests of **document-type
12
+ captures** (PDF ~74%, DOC/XLS/PPT/EPUB and similar) from one Common
13
+ Crawl crawl's URL index — the ~1% of CC that isn't HTML. CC digests
14
+ are SHA-1 of the (possibly truncated pre-2025) WARC payload; for
15
+ static documents this equals the file's raw sha1.
16
+
17
+ - **30,951,194 sha1 keys** (UPPERCASE hex), p = 1e-4, 71 MiB
18
+ - Source: CC-MAIN index `content_digest` column, filtered by MIME
19
+ (crawl data © Common Crawl, generously public; this digest
20
+ compilation CC0)
21
+ - One crawl only — a document must have been live and crawled that
22
+ month to appear; more crawls widen coverage
23
+
24
+ ## Rebuild
25
+
26
+ `cc_extract_job.py` in this repo streams one crawl's CDXJ index
27
+ (~1 h locally, $0), `cc_digests_to_hex.py` converts the base32
28
+ digests to hex, `./dcso_bloom_build.py cc.sha1.bloom sha1` builds
29
+ the filter.
30
+
31
+ ## Format
32
+
33
+ DCSO bloom filter format (`github.com/DCSO/bloom`), the same format
34
+ CIRCL publishes hashlookup in: 48-byte little-endian u64 header
35
+ (version, n, p, k, m, N) followed by the bit array. Keys are hex
36
+ digest strings — **UPPERCASE for sha1, lowercase for sha256** (the
37
+ hashlookup convention). Any DCSO-compatible reader works.
38
+
39
+ Membership answers are probabilistic: p = 1e-4 false-positive rate,
40
+ no false negatives. Confirm anything important against the source.
cc_digests_to_hex.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.11"
4
+ # dependencies = ["duckdb>=1.0"]
5
+ # ///
6
+ """Convert a digests.parquet (base32 sha1, Common Crawl convention) to
7
+ uppercase-hex lines on stdout, ready for `hdx filters build cc sha1`.
8
+
9
+ uv run tools/cc_digests_to_hex.py cc-out/CC-MAIN-2026-30/digests.parquet \
10
+ > ~/.cache/hashdex/extracts/cc.sha1.hex
11
+ """
12
+
13
+ import base64
14
+ import sys
15
+
16
+ import duckdb
17
+
18
+
19
+ def main():
20
+ if len(sys.argv) != 2:
21
+ sys.exit(__doc__)
22
+ con = duckdb.connect()
23
+ cur = con.execute(
24
+ "SELECT digest_b32 FROM read_parquet(?)", [sys.argv[1]]
25
+ )
26
+ out = sys.stdout
27
+ bad = 0
28
+ while batch := cur.fetchmany(100_000):
29
+ lines = []
30
+ for (b32,) in batch:
31
+ try:
32
+ raw = base64.b32decode(b32)
33
+ except Exception:
34
+ bad += 1
35
+ continue
36
+ if len(raw) != 20:
37
+ bad += 1
38
+ continue
39
+ lines.append(raw.hex().upper())
40
+ out.write("\n".join(lines) + "\n")
41
+ if bad:
42
+ print(f"skipped {bad} undecodable digests", file=sys.stderr)
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
cc_extract_job.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = ["duckdb>=1.0", "huggingface_hub>=0.30"]
4
+ # ///
5
+ """Extract non-HTML content digests + inverted index from one Common Crawl
6
+ columnar index, and (optionally) upload the result to a Hugging Face dataset.
7
+
8
+ Designed to run on HF Jobs (in-AWS, fat pipe to data.commoncrawl.org):
9
+
10
+ hf jobs uv run --flavor cpu-upgrade --timeout 4h -s HF_TOKEN \
11
+ tools/cc_extract_job.py -- --crawl CC-MAIN-2026-30 --repo <user>/hashdex-cc
12
+
13
+ or locally for a smoke test (a couple of ~600 MB index files):
14
+
15
+ uv run tools/cc_extract_job.py --crawl CC-MAIN-2026-30 --limit 2 --no-upload
16
+
17
+ Outputs, per crawl:
18
+ index-*.parquet digest_b32-sorted (digest, url, fetch_time, mime,
19
+ warc_filename/offset/length) for every kept capture
20
+ digests.parquet distinct digest_b32 (sha1 of payload, base32)
21
+
22
+ Kept = fetch_status 200, mime_detected not HTML/XHTML, not truncated.
23
+ The digest is CC's WARC-Payload-Digest: sha1 over the transfer payload.
24
+ For identity-served binaries (PDF and friends) that equals sha1 of the
25
+ file bytes; gzip-content-encoded responses do NOT match local files.
26
+ """
27
+
28
+ import argparse
29
+ import gzip
30
+ import io
31
+ import json
32
+ import os
33
+ import sys
34
+ import time
35
+ import urllib.request
36
+
37
+ USER_AGENT = "hashdex-cc/0.1 (hash index research)"
38
+ CC_BASE = "https://data.commoncrawl.org"
39
+
40
+
41
+ def fetch_warc_index_paths(crawl: str) -> list[str]:
42
+ url = f"{CC_BASE}/crawl-data/{crawl}/cc-index-table.paths.gz"
43
+ req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
44
+ with urllib.request.urlopen(req, timeout=120) as resp:
45
+ paths = gzip.decompress(resp.read()).decode().splitlines()
46
+ warc = [p for p in paths if "/subset=warc/" in p]
47
+ if not warc:
48
+ sys.exit(f"no subset=warc files listed for {crawl}")
49
+ return warc
50
+
51
+
52
+ def run_extract(con, files: list[str], out_dir: str) -> dict:
53
+ file_list = ", ".join(f"'{CC_BASE}/{p}'" for p in files)
54
+ os.makedirs(out_dir, exist_ok=True)
55
+ t0 = time.time()
56
+ con.execute(f"""
57
+ COPY (
58
+ SELECT content_digest AS digest_b32,
59
+ url,
60
+ fetch_time,
61
+ content_mime_detected AS mime,
62
+ warc_filename,
63
+ warc_record_offset,
64
+ warc_record_length
65
+ FROM read_parquet([{file_list}])
66
+ WHERE fetch_status = 200
67
+ AND content_digest IS NOT NULL
68
+ AND content_truncated IS NULL
69
+ AND content_mime_detected IS NOT NULL
70
+ AND content_mime_detected NOT LIKE 'text/html%'
71
+ AND content_mime_detected NOT LIKE 'application/xhtml%'
72
+ ORDER BY digest_b32
73
+ ) TO '{out_dir}/index.parquet'
74
+ (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 262144,
75
+ FILE_SIZE_BYTES '1900MB', FILENAME_PATTERN 'index-{{i}}',
76
+ OVERWRITE_OR_IGNORE)
77
+ """)
78
+ scan_s = time.time() - t0
79
+ con.execute(f"""
80
+ COPY (
81
+ SELECT DISTINCT digest_b32
82
+ FROM '{out_dir}/index.parquet/*.parquet'
83
+ ORDER BY digest_b32
84
+ ) TO '{out_dir}/digests.parquet'
85
+ (FORMAT PARQUET, COMPRESSION ZSTD)
86
+ """)
87
+ rows, distinct = con.execute(f"""
88
+ SELECT (SELECT count(*) FROM '{out_dir}/index.parquet/*.parquet'),
89
+ (SELECT count(*) FROM '{out_dir}/digests.parquet')
90
+ """).fetchone()
91
+ return {"rows_kept": rows, "distinct_digests": distinct,
92
+ "scan_seconds": round(scan_s, 1), "files_scanned": len(files)}
93
+
94
+
95
+ def upload(repo: str, crawl: str, out_dir: str, stats: dict):
96
+ from huggingface_hub import HfApi
97
+
98
+ api = HfApi()
99
+ api.create_repo(repo, repo_type="dataset", exist_ok=True)
100
+ with open(os.path.join(out_dir, "stats.json"), "w") as f:
101
+ json.dump(stats, f, indent=2)
102
+ api.upload_folder(
103
+ repo_id=repo,
104
+ repo_type="dataset",
105
+ folder_path=out_dir,
106
+ path_in_repo=f"crawls/{crawl}",
107
+ commit_message=f"{crawl}: {stats['distinct_digests']} distinct digests",
108
+ )
109
+ print(f"uploaded to https://huggingface.co/datasets/{repo}/tree/main/crawls/{crawl}")
110
+
111
+
112
+ def main():
113
+ ap = argparse.ArgumentParser()
114
+ ap.add_argument("--crawl", required=True, help="e.g. CC-MAIN-2026-30")
115
+ ap.add_argument("--repo", help="HF dataset repo to upload to, e.g. user/hashdex-cc")
116
+ ap.add_argument("--limit", type=int, help="only scan first N index files (smoke test)")
117
+ ap.add_argument("--out", default="cc-out", help="local output directory")
118
+ ap.add_argument("--no-upload", action="store_true")
119
+ ap.add_argument("--threads", type=int, default=0, help="duckdb threads (0 = auto)")
120
+ ap.add_argument("--memory", default="8GB",
121
+ help="duckdb memory_limit; spill goes to <out>/.duckdb-tmp")
122
+ args = ap.parse_args()
123
+
124
+ import duckdb
125
+
126
+ files = fetch_warc_index_paths(args.crawl)
127
+ print(f"{args.crawl}: {len(files)} subset=warc index files", flush=True)
128
+ if args.limit:
129
+ files = files[: args.limit]
130
+ print(f"limited to {len(files)} files", flush=True)
131
+
132
+ con = duckdb.connect(config={"custom_user_agent": USER_AGENT})
133
+ con.execute("INSTALL httpfs; LOAD httpfs")
134
+ con.execute("SET http_keep_alive=true")
135
+ con.execute("SET http_retries=6")
136
+ con.execute("SET preserve_insertion_order=false")
137
+ con.execute(f"SET memory_limit='{args.memory}'")
138
+ tmp = os.path.join(args.out, ".duckdb-tmp")
139
+ os.makedirs(tmp, exist_ok=True)
140
+ con.execute(f"SET temp_directory='{tmp}'")
141
+ if args.threads:
142
+ con.execute(f"SET threads={args.threads}")
143
+
144
+ out_dir = os.path.join(args.out, args.crawl)
145
+ stats = run_extract(con, files, out_dir)
146
+ print(json.dumps(stats, indent=2), flush=True)
147
+
148
+ if args.no_upload:
149
+ return
150
+ if not args.repo:
151
+ sys.exit("--repo required unless --no-upload")
152
+ upload(args.repo, args.crawl, out_dir, stats)
153
+
154
+
155
+ if __name__ == "__main__":
156
+ main()
dcso_bloom_build.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a DCSO-format bloom filter from files of hex digest lines.
3
+
4
+ Standalone, zero dependencies — everything needed to reproduce the
5
+ .bloom files in this dataset from the digest lists / harvest scripts
6
+ alongside it.
7
+
8
+ Format (github.com/DCSO/bloom, the format CIRCL hashlookup uses):
9
+ 48-byte header of little-endian u64s (version=1, n capacity, p as f64
10
+ bits, k, m, N inserted) followed by ceil(m/64) u64 words of bit array.
11
+ Keys are hex digest STRINGS: UPPERCASE for sha1 (the hashlookup
12
+ convention), lowercase for everything else.
13
+
14
+ Membership hashing (Go semantics preserved from the reference
15
+ implementation): h = FNV-1 64(key) mod M with M = 2^64 - 87, then k
16
+ rounds of h = (h * g mod 2^64) mod M with g = 18446744073709550147,
17
+ setting bit h mod m each round.
18
+
19
+ Usage:
20
+ dcso_bloom_build.py OUT.bloom SCHEME HEXFILE... [--fpp 0.0001]
21
+ (SCHEME in md5|sha1|sha256 — sets required line length + key case)
22
+ """
23
+ import math
24
+ import struct
25
+ import sys
26
+
27
+ MOD = 2**64 - 87
28
+ G = 18446744073709550147
29
+ MASK = 2**64 - 1
30
+
31
+ HEX_LEN = {"md5": 32, "sha1": 40, "sha256": 64}
32
+
33
+
34
+ def fnv1_64(data: bytes) -> int:
35
+ h = 0xCBF29CE484222325
36
+ for b in data:
37
+ h = (h * 0x100000001B3) & MASK
38
+ h ^= b
39
+ return h
40
+
41
+
42
+ def main() -> None:
43
+ args = [a for a in sys.argv[1:] if not a.startswith("--")]
44
+ fpp = 0.0001
45
+ for a in sys.argv[1:]:
46
+ if a.startswith("--fpp"):
47
+ fpp = float(a.split("=", 1)[1] if "=" in a else sys.argv[sys.argv.index(a) + 1])
48
+ if len(args) < 3 or args[1] not in HEX_LEN:
49
+ sys.exit(__doc__)
50
+ out, scheme, inputs = args[0], args[1], args[2:]
51
+ hex_len = HEX_LEN[scheme]
52
+ upper = scheme == "sha1"
53
+
54
+ n = 0
55
+ for path in inputs:
56
+ with open(path) as f:
57
+ for line in f:
58
+ t = line.strip()
59
+ if not t:
60
+ continue
61
+ if len(t) != hex_len or not all(c in "0123456789abcdefABCDEF" for c in t):
62
+ sys.exit(f"{path}: line {t!r} is not a {hex_len}-char hex digest")
63
+ n += 1
64
+ if n == 0:
65
+ sys.exit("no digests found in input")
66
+
67
+ ln2 = math.log(2)
68
+ m = math.ceil(n * -math.log(fpp) / (ln2 * ln2))
69
+ k = max(1, round((m / n) * ln2))
70
+ words = bytearray((m + 63) // 64 * 8)
71
+ print(f"building {out}: {n} keys, p={fpp}, {len(words) >> 20} MiB", file=sys.stderr)
72
+
73
+ done = 0
74
+ for path in inputs:
75
+ with open(path) as f:
76
+ for line in f:
77
+ t = line.strip()
78
+ if not t:
79
+ continue
80
+ key = (t.upper() if upper else t.lower()).encode()
81
+ h = fnv1_64(key) % MOD
82
+ for _ in range(k):
83
+ h = (h * G & MASK) % MOD
84
+ bit = h % m
85
+ words[bit >> 6 << 3 | (bit >> 3) & 7] |= 1 << (bit & 7)
86
+ done += 1
87
+ if done % 50_000_000 == 0:
88
+ print(f" … {done}/{n}", file=sys.stderr)
89
+
90
+ with open(out, "wb") as f:
91
+ f.write(struct.pack("<6Q", 1, n, struct.unpack("<Q", struct.pack("<d", fpp))[0], k, m, n))
92
+ f.write(words)
93
+ print(f"wrote {out}", file=sys.stderr)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ main()