File size: 2,224 Bytes
b58cfff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c861dc2
b58cfff
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# /// script
# requires-python = ">=3.8"
# dependencies = [
#   "warcio",
#   "requests",
# ]
# ///
"""Fetch a page's content from a NFS-mounted Common Crawl Hugging Face Bucket."""

import argparse
import io
import json
from pathlib import Path
from urllib.parse import quote_plus

import requests
from warcio.archiveiterator import ArchiveIterator

SERVER = "http://index.commoncrawl.org/"
INDEX_NAME = "CC-MAIN-2026-17"
USER_AGENT = "cc-hf-jobs/1.0 (Buckets Example)"

def search_cc_index(url):
    encoded_url = quote_plus(url)
    index_url = f"{SERVER}{INDEX_NAME}-index?url={encoded_url}&output=json"
    response = requests.get(index_url, headers={"user-agent": USER_AGENT})
    response.raise_for_status()
    return [json.loads(line) for line in response.text.strip().split("\n")]

def fetch_page_from_bucket(records, bucket_root):
    for record in records:
        offset = int(record["offset"])
        length = int(record["length"])
        warc_path = bucket_root / record["filename"]

        if not warc_path.exists():
            print(f"Not in bucket: {warc_path}")
            continue

        with warc_path.open("rb") as f:
            f.seek(offset)
            chunk = f.read(length)

        # The byte range covers exactly one gzipped WARC record, so we can
        # hand it to ArchiveIterator as an in-memory stream.
        for warc_record in ArchiveIterator(io.BytesIO(chunk)):
            if warc_record.rec_type == "response":
                return warc_record.content_stream().read()

    print("No response record found")
    return None

def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("url", help="URL to look up in the CC index (e.g. huggingface.co/blog)")
    parser.add_argument("bucket_path", type=Path, help="Path to the mounted Common Crawl bucket")
    args = parser.parse_args()

    records = search_cc_index(args.url)
    print(f"Found {len(records)} record(s) for {args.url}")

    content = fetch_page_from_bucket(records, args.bucket_path)
    if content is not None:
        print(f"Fetched {len(content)} bytes")
        print(content.decode("utf-8", errors="replace"))

if __name__ == "__main__":
    main()