So, let’s make our own dataset

Community Article
Published September 9, 2026

I've read so manyyyyy docs, tutorials, books and blogs over the years while tinkering, experimenting and building stuff.

And while it's been a mostly positive experience, I've spent plenty of nights and wasted hours going through bullshit, useless, nonpractical resources that left me more confused than when I started lol.

I try my best to share things I've learnt without all the jargon and dumb, over the top examples.

This writeup shows how we can build our own dataset from scratch. Hopefully it'll introduce you to the basics and some common things you'll run into when working with data :)

So, now that's out of the way... let's make a dataset!

There are datasets for everything: books, conversations, code, images, medical text, jokes, instructions, translations and some real weird niche stuff out here. Have a look for yourself.

We're going to:

  1. Use Python and the Hugging Face API.
  2. Collect information about datasets, including their names, downloads and tags.
  3. Save the original information in a RAWDATA folder.
  4. Process it into our own small dataset.
  5. Explore popular datasets, task categories and formats.
  6. Save everything with enough information for someone else to understand it.

The complete script is at the bottom. You can copy it, run it and follow along without changing anything.

Wait, a dataset about datasets?

Yep lol.

Each row in our dataset will describe one dataset repository on Hugging Face.

Think of the information you see when browsing the Hub: the repository name, its tags, download count, languages and so on. We're collecting that information into something we can sort, check and analyse ourselves.

That stuff is called metadata, which just means information describing other data.

We're starting with up to 1,000 repositories sorted by downloads over the last 30 days. That's enough to explore a wider range of metadata while keeping the files manageable. We'll inspect a few rows ourselves and use the reports to see patterns across the collection.

The actual books, images and conversations inside those repositories stay where they are. We're collecting their public metadata.

Get it running first

You'll need Python 3.10 or newer and an internet connection.

That's it. The script uses Python's built in tools, so there's nothing extra to install and no Hugging Face login to configure.

  1. Create a folder for the project.
  2. Save the complete script at the bottom as build_dataset.py.
  3. Open a terminal in that folder.
  4. Run:
python build_dataset.py

On macOS or Linux, your command might be:

python3 build_dataset.py

On Windows, you can also use:

py -3 build_dataset.py

You'll see four numbered steps as it collects, saves, checks and processes the information.

When it's finished, it'll print the folder containing your results. Each run looks like this:

dataset_output/
└── <unique run folder>/
    ├── RAWDATA/
    │   ├── response.json
    │   └── collection.json
    └── PROCESSED/
        ├── datasets.jsonl
        ├── task_categories_counts.csv
        ├── languages_counts.csv
        ├── formats_counts.csv
        ├── tags_counts.csv
        ├── owners.csv
        ├── insights.txt
        ├── summary.json
        ├── collection.json
        └── README.md

Start with PROCESSED/README.md for a map of the results, then open datasets.jsonl in your editor to see the records. We'll look at the raw response and reports below.

Now let's go through what it actually did.

First, ask Hugging Face for the information

An API lets our code ask a service for information directly.

Here, we're using the Hugging Face Hub API to request dataset metadata.

These entries come from the QUERY dictionary in the complete script. They are an excerpt, not a separate script to run:

"sort": "downloads",
"direction": -1,
"limit": LIMIT,

LIMIT is set to 1000 near the top of the script. That asks for up to 1,000 results ordered from highest to lowest downloads over the last 30 days.

These are HTTP query parameters sent directly to the API. Python's built-in HTTP tools let us run this example without installing anything and save the original response bytes.

We're requesting one page of up to 1,000 repositories. The script doesn't follow links to further pages. Collecting the whole Hub needs pagination, which means requesting successive pages of results; simply increasing LIMIT isn't enough.

For a bigger project, the official huggingface_hub SDK handles pagination and offers built in rate limit handling. Here we're keeping the collection to one page so we can see each step ourselves; temporary failures may cause that request to be retried.

Another entry in that dictionary asks for a few specific fields:

"expand": ["downloads", "likes", "tags", "citation", "sha"],

expand selects the metadata fields we want returned; it doesn't guarantee that every repository has a value for each one. citation is a documented option, but it may be absent in the response.

sha is the repository revision identifier. Keeping it gives us another reference point for the repository as it appeared during collection.

It doesn't freeze download counts or other changing metadata, though. That's why we also record the collection time.

If the request doesn't work

Temporary connection problems and some server errors trigger up to three attempts. Check your connection and try again if all three fail.

HTTP 429 means the Hub has rate limited the request. The script reads Retry-After and the API reset time in Hugging Face's RateLimit header. It respects the longer valid delay. If the requested wait exceeds 60 seconds, it stops and tells you how long to wait before running it again. Anonymous limits are shared by IP address, so other activity on the same network can affect you too.

If you see a certificate verification error, check your computer's clock and your Python installation's certificates. Keep HTTPS verification enabled.

A folder permission or disk space error means the script couldn't finish saving its output. When it prints an incomplete run's location, keep that folder if you want to inspect it. RAWDATA holds any saved response, and PROCESSING may contain unfinished outputs. The script names the finished output folder PROCESSED only after writing and checking it. Running again creates a separate folder.

Keep the raw stuff

Before changing anything, the script saves the response in RAWDATA/response.json.

(raw / "response.json").write_bytes(body)

Open that file in your editor and have a look.

It might be one enormous line. That's okay. Most code editors have a format document option that makes JSON easier to read. If you want to reformat it, work on a copy.

This is our source snapshot. Keeping it means we can check what Hugging Face actually returned if something looks wrong in our processed dataset.

We also save collection.json, which records the request, collection times and script version.

After a successful response, each run gets a separate folder inside dataset_output in your current working folder. You can run the script again without overwriting the previous collection.

This is a habit worth getting into early: keep what you collected separate from what you changed.

So what does processing actually mean?

In this project, it means taking the returned information and organising it into consistent fields.

For example, the Hub might return tags like:

language:en
task_categories:text-classification
format:parquet

We keep those original tags, but also extract the useful bits into separate lists. These fields are part of the processed record:

"languages": ["en"],
"task_categories": ["text-classification"],
"formats": ["parquet"],

Now we can count formats without repeatedly searching through every tag ourselves.

Tags can come from the repository's dataset-card metadata and information derived by the Hub. We're recording what the API reports, not independently checking the contents of every repository.

We're also keeping:

  • The dataset ID and original URL.
  • Reported downloads and likes.
  • Citation text when returned.
  • The repository revision.
  • When we collected the information.

Also, task categories and topics aren't quite the same thing. “Text classification” describes something you can do with a dataset. “Cybersecurity” describes a subject it might cover.

If we add our own topic labels later, they should have their own field.

Some things will be missing

This is where working with real data gets interesting.

Some records won't have format tags. Some won't return a citation. Other fields might be missing too.

In the 1,000-record run for this guide on 9 September 2026, 369 records had no format tags and 987 returned no citation text through this request. Your results will differ as the Hub changes.

That doesn't mean those repositories have no files or citation information. It means our particular response didn't include those details.

You'll see missing values represented as null in JSON:

{
  "downloads": null,
  "citation": null
}

A missing download count and a download count of zero are different things.

So the script keeps missing counts as missing. It doesn't quietly turn them into zero just to make the column look tidy.

For extracted lists such as formats, an empty list means no matching tags were returned. In the summary, missing_tags counts absent or null tag lists. An empty tag list is present but contains no tags, so it contributes to without_format_tags instead.

Legit learning to leave a gap visible instead of guessing something to fill it is a pretty useful dataset skill.

Check it before calling it finished

The script checks for things like:

  • Empty or unexpected responses.
  • Duplicate dataset IDs.
  • Invalid download and like counts.
  • Tags arriving in an unexpected format.
  • Problems saving and loading the finished file.

It also counts some of the missing information so we can see where the collection is incomplete.

These checks won't prove that every tag is accurate or every dataset is useful. They catch problems with the structure of the data we're handling.

Once saved, the script loads the dataset again and compares it with the records it intended to write.

if reloaded != rows:
    raise DatasetError(
        "The saved dataset did not pass its reload check."
    )

That's a simple check, but it means we're actually testing the file someone will use.

JSONL for the dataset, CSV for the reports

Our main dataset is saved as datasets.jsonl.

JSONL puts one JSON object on each line. It works nicely here because a record can contain several tags, languages or formats without squeezing those lists into a spreadsheet cell.

Here's one complete record from the 1,000 record run on 9 September 2026, expanded across lines so it's easier to read. In datasets.jsonl, the same record occupies one line:

{
  "dataset_id": "KakologArchives/KakologArchives",
  "url": "https://huggingface.co/datasets/KakologArchives/KakologArchives",
  "downloads": 2509960,
  "likes": 82,
  "tags": [
    "task_categories:text-classification",
    "language:ja",
    "license:mit",
    "region:us"
  ],
  "citation": null,
  "source_revision": "bd9c08ef37aa18ef09acf9d8f5948c70646d2465",
  "collected_at": "2026-09-09T03:58:17.727099+00:00",
  "task_categories": [
    "text-classification"
  ],
  "languages": [
    "ja"
  ],
  "formats": []
}

dataset_id identifies the repository, and url takes you back to its page. The original tags give us languages and task_categories. There is no format: tag, so formats is empty. The null citation means this response didn't provide citation text. Neither tells us what we would find by inspecting the repository itself.

I go through the formats in more detail in LLM Dataset Formats 101.

The reports are saved as CSV files:

File What it contains
task_categories_counts.csv How many repositories have each task category
languages_counts.csv How many repositories have each language tag
formats_counts.csv How many repositories have each format tag
tags_counts.csv How many repositories have each returned tag
owners.csv Repository counts and reported download totals by owner

Open one in your spreadsheet app and sort the counts or make a chart.

The script also creates a README.md explaining the fields and collection method, plus a summary.json with counts, missing information and collection statistics.

So when you come back to this folder later, you've got some context instead of just a file you vaguely remember making.

Let's see what's popular

The terminal prints a collection report with several sections:

  • Download and like statistics: total, mean, median, minimum and maximum, plus how many values were reported or missing.
  • Up to ten repositories with the highest reported downloads over the last 30 days, and up to ten with the most likes.
  • Up to ten dataset formats/types, task categories, languages and tags, with repository counts and percentages.
  • Up to ten repository owners by number of datasets in our collection, then by summed reported downloads.
  • Metadata coverage, including missing tags, formats and citation text.

Here, “dataset types” means the returned format tags, such as Parquet or imagefolder. Task categories describe uses such as text classification. Neither is an inspection of the files themselves.

“Owners” are the namespaces before the slash in repository IDs. They may be individual users or organizations; we aren't identifying the people downloading datasets. Owner rankings cover only their repositories in our collection. IDs without a namespace are counted separately.

The mean is the sum divided by the number of reported values. The median is the middle value after sorting (or the average of the two middle values). A few very popular repositories can pull the mean upwards, so looking at both is useful. Missing values are excluded from these statistics; zero still counts. Download totals are sums of repository counts, not unique downloaders.

The same report is saved as insights.txt. Its statistics and owner aggregates are also in summary.json, and owners.csv gives you the full owner table. A blank download total means no counts were reported for that owner's repositories. The reported_downloads column counts repositories with a reported value; total_downloads is their summed download count. Equal scores are ordered alphabetically for consistent reports.

The reports show which tags and categories appear most often. For example, formats_counts.csv from the 1,000-record run on 9 September 2026 contains:

"value","dataset_count"
"imagefolder","328"
"parquet","215"
"json","47"
"csv","11"
"text","10"
"webdataset","9"
"audiofolder","6"
"optimized-parquet","6"
"arrow","5"

We can say that 215 of the 1,000 repositories had a format:parquet tag in that response. That is 21.5% of our selected sample. The most common returned format tag was imagefolder, appearing in 328 repositories. We can't say that only 215 actually contain Parquet files: 369 repositories had no format tags at all, and we haven't inspected their files.

Try opening your own formats_counts.csv and writing one sentence about the most common returned format. Include the count, the number of repositories actually collected and the collection date. Use the rows value in summary.json as your denominator if the API returned fewer than 1,000 records.

A dataset can have several formats or task categories, so those counts can add up to more than the number of repositories collected, even more than 1,000 in a full run. That's expected.

Keep these limits in mind when reading the results.

The API's downloads field covers the last 30 days; it is not a lifetime total. Hugging Face documents that distinction in its DatasetInfo reference.

Downloads aren't a quality score. They aren't a count of unique people either. Hugging Face documents how it groups requests when calculating dataset downloads in its download statistics guide.

Our collection is a selected sample. We requested the top 1,000 by downloads over the last 30 days. We can describe common formats in that collection, but we haven't measured every dataset on Hugging Face.

That changes how we'd describe a finding.

“Parquet appeared in this many repositories in our sample” is something our data can support.

“Everyone uses Parquet now” needs a bit more work haha.

Where do we go from here?

You've already got enough to build a few things:

  • A small dataset finder that filters by task, language or format.
  • A dashboard showing the counts in your collection.
  • A report about which metadata fields were returned or missing.
  • A comparison with another snapshot collected later.

If you compare snapshots, match records using dataset_id. A repository dropping out of the top 1,000 doesn't mean it was deleted. Each download count covers a rolling 30 day window, so subtracting two snapshots won't tell you how many new downloads happened between runs.

Before sharing the collected metadata, check the relevant source terms and attribution requirements. The generated README keeps the source and limitations attached without inventing a licence for other people's material.

For now, open a few rows and compare them with the original dataset pages. Look at what's there, what's missing and what you'd want to add.

That's a proper little dataset project already: collect something, understand it, organise it, check it and use it :)

Optional next step: citations and DOIs

The script keeps citation text if the API returns it. It doesn't count research citations.

DOIs need a separate check. A DOI identifies a particular resource, which could be a dataset or an associated paper. Hugging Face supports assigning them to dataset repositories and versions. Here's its DOI guide.

This script doesn't extract or verify DOIs.

A useful next step would be to pick a few records, open their original pages and add verified DOI information in a separate file. Record what each DOI identifies and where you found it.

Then you can connect those additions to your existing records using dataset_id.

That's called enrichment. You're adding useful information to data you already have.

It's also a good reason to keep the raw response intact. You can tell what came from the API and what you added yourself.


The complete script

Save this as build_dataset.py and run it from your project folder.

You don't need to understand every line before running it. When you're ready to follow the code, start with these functions:

  • fetch_snapshot() asks the API for the raw response.
  • prepare_rows() checks the records and extracts fields from tags.
  • write_outputs() saves the dataset, reports and README, and checks the JSONL reload.
  • build_insights() computes statistics and owner aggregates.
  • render_insights() turns the results into the report saved to insights.txt and printed in the terminal.
  • main() connects those steps and prints your results.

The other helpers handle details such as retry delays and writing files. You can come back to those after you've followed one record through the main steps.

It uses verified HTTPS, limits response size, retries temporary request failures and handles rate limit responses. The collected files stay local. It doesn't download dataset contents or run code from dataset repositories.

"""Build a small Hugging Face metadata dataset using Python 3.10+ | [td] tegridydev"""

import csv
import json
import re
import ssl
import sys
import tempfile
import time
from collections import Counter
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from http.client import HTTPException
from pathlib import Path
from statistics import mean, median
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import HTTPRedirectHandler, Request, build_opener


SCRIPT_VERSION = "1.2.1"
LIMIT = 1000
MAX_BYTES = 5 * 1024 * 1024
QUERY = {
    "sort": "downloads",
    "direction": -1,
    "limit": LIMIT,
    "expand": ["downloads", "likes", "tags", "citation", "sha"],
}
API_URL = "https://huggingface.co/api/datasets?" + urlencode(QUERY, doseq=True)
GROUPS = {
    "task_categories": "task_categories:",
    "languages": "language:",
    "formats": "format:",
}


class DatasetError(Exception):
    """An error with a message suitable for the person running the script."""


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        # Keep this collector on its fixed HTTPS endpoint.
        return None


def utc_now():
    return datetime.now(timezone.utc).isoformat()


def retry_delay(value, fallback, rate_limit=None):
    delays = [fallback]
    if value:
        try:
            if re.fullmatch(r"[0-9]+", value.strip()):
                seconds = int(value)
            else:
                date = parsedate_to_datetime(value)
                seconds = (date - datetime.now(timezone.utc)).total_seconds()
            delays.append(seconds)
        except (ValueError, TypeError, OverflowError):
            pass

    # The Hub advertises its API reset as: '"api";r=0;t=120'.
    for bucket in (rate_limit or "").split(","):
        parts = bucket.strip().split(";")
        if parts[0].strip() != '"api"':
            continue
        for parameter in parts[1:]:
            match = re.fullmatch(r"\s*t\s*=\s*([0-9]+)\s*", parameter)
            if match:
                try:
                    delays.append(int(match[1]))
                except ValueError:
                    pass
    seconds = max(delays)
    if seconds > 60:
        raise DatasetError(
            f"The Hub asked us to wait {seconds:.0f} seconds. "
            "Please try again after that wait; this script waits at most 60 seconds per retry."
        )
    return seconds


def fetch_snapshot():
    request = Request(API_URL, headers={
        "User-Agent": f"tegridydev-dataset-guide/{SCRIPT_VERSION}",
        "Accept": "application/json",
        "Accept-Encoding": "identity",
    })
    opener = build_opener(NoRedirects())

    for attempt in range(3):
        delay = 2 ** (attempt + 1)
        try:
            with opener.open(request, timeout=30) as response:
                if response.headers.get_content_type() != "application/json":
                    raise DatasetError("The Hub returned something other than JSON.")
                body = response.read(MAX_BYTES + 1)
                if len(body) > MAX_BYTES:
                    raise DatasetError("The response exceeded our 5 MiB size limit.")
                return body
        except HTTPError as error:
            status = error.code
            retry_after = error.headers.get("Retry-After")
            rate_limit = error.headers.get("RateLimit") if status == 429 else None
            error.close()
            if status not in {429, 500, 502, 503, 504}:
                raise DatasetError(f"The Hub returned HTTP {status}.") from None
            delay = retry_delay(retry_after, delay, rate_limit)
        except (URLError, TimeoutError, HTTPException) as error:
            reason = getattr(error, "reason", error)
            if isinstance(reason, ssl.SSLCertVerificationError):
                raise DatasetError(
                    "HTTPS certificate verification failed. Check your computer's "
                    "clock and Python certificate installation. Keep TLS verification on."
                ) from None

        if attempt == 2:
            raise DatasetError(
                "Could not collect data after three attempts. "
                "Check your connection or try again later."
            )
        print(f"  Request interrupted. Retrying in {delay:.0f} seconds...")
        time.sleep(delay)


def tag_values(tags, prefix):
    return sorted({
        tag[len(prefix):]
        for tag in (tags or [])
        if tag.startswith(prefix) and tag[len(prefix):]
    })


def prepare_rows(records, collected_at):
    if not isinstance(records, list) or not 1 <= len(records) <= LIMIT:
        raise DatasetError(f"Expected between 1 and {LIMIT} dataset records.")

    rows, seen = [], set()
    for record in records:
        if not isinstance(record, dict):
            raise DatasetError("A returned record is not a JSON object.")
        dataset_id = record.get("id")
        # Match the official client's repository-ID rules.
        if (
            not isinstance(dataset_id, str)
            or not re.fullmatch(r"(\b[\w.-]+\b/)?\b[\w.-]{1,96}\b", dataset_id)
            or "--" in dataset_id
            or ".." in dataset_id
            or dataset_id.endswith(".git")
        ):
            raise DatasetError("A record has an invalid dataset ID.")
        if dataset_id in seen:
            raise DatasetError("Duplicate dataset IDs found in the response.")
        seen.add(dataset_id)

        tags = record.get("tags")
        if tags is not None and (
            not isinstance(tags, list)
            or any(not isinstance(tag, str) for tag in tags)
        ):
            raise DatasetError("A record has an unexpected tags value.")
        for field in ("downloads", "likes"):
            value = record.get(field)
            if value is not None and (type(value) is not int or value < 0):
                raise DatasetError(f"A record has an invalid {field} count.")
        for field in ("citation", "sha"):
            if record.get(field) is not None and not isinstance(record[field], str):
                raise DatasetError(f"A record has an unexpected {field} value.")

        row = {
            "dataset_id": dataset_id,
            "url": "https://huggingface.co/datasets/" + quote(dataset_id, safe="/"),
            "downloads": record.get("downloads"),
            "likes": record.get("likes"),
            "tags": tags,
            "citation": record.get("citation"),
            "source_revision": record.get("sha"),
            "collected_at": collected_at,
        }
        for field, prefix in GROUPS.items():
            row[field] = tag_values(tags, prefix)
        rows.append(row)
    return rows


def save_json(path, value):
    path.write_text(
        json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n",
        encoding="utf-8",
    )


def csv_cell(value):
    # Escape formula-like text in spreadsheet exports; JSON remains unchanged.
    text = "".join(c for c in str(value) if c.isprintable())
    if text.lstrip().startswith(("=", "+", "-", "@")):
        text = "'" + text
    return text


def build_insights(rows):
    statistics = {}
    rankings = {}
    for field in ("downloads", "likes"):
        ranked = sorted(
            (row for row in rows if row[field] is not None),
            key=lambda row: (-row[field], row["dataset_id"]),
        )
        values = [row[field] for row in ranked]
        statistics[field] = {
            "reported": len(values), "missing": len(rows) - len(values),
            "total": sum(values) if values else None,
            "mean": mean(values) if values else None,
            "median": median(values) if values else None,
            "minimum": min(values) if values else None,
            "maximum": max(values) if values else None,
        }
        rankings[field] = [
            {"dataset_id": row["dataset_id"], "value": row[field]}
            for row in ranked[:10]
        ]

    owners = {}
    without_owner = 0
    for row in rows:
        if "/" not in row["dataset_id"]:
            without_owner += 1
            continue
        owner = row["dataset_id"].split("/", 1)[0]
        item = owners.setdefault(owner, {
            "owner": owner, "dataset_count": 0,
            "reported_downloads": 0, "total_downloads": None,
        })
        item["dataset_count"] += 1
        if row["downloads"] is not None:
            item["reported_downloads"] += 1
            item["total_downloads"] = (item["total_downloads"] or 0) + row["downloads"]
    return {
        "statistics": statistics, "top_datasets": rankings,
        "owners": sorted(owners.values(), key=lambda item: (-item["dataset_count"], item["owner"])),
        "without_owner_namespace": without_owner,
    }


def render_insights(summary):
    lines = ["Collection insights", f"  Repositories collected: {summary['rows']:,}"]
    insights = summary["insights"]
    for field, label in (("downloads", "Downloads over the last 30 days"), ("likes", "Likes")):
        stats = insights["statistics"][field]
        lines.extend(["", f"{label}: statistics for reported values",
                      f"  Reported: {stats['reported']:,}; missing: {stats['missing']:,}"])
        for key in ("total", "mean", "median", "minimum", "maximum"):
            value = stats[key]
            if value is None:
                display = "not available"
            elif key in {"mean", "median"}:
                display = f"{value:,.2f}"
            else:
                display = f"{value:,}"
            metric_label = "Average (mean)" if key == "mean" else key.capitalize()
            lines.append(f"  {metric_label}: {display}")
        heading = "Highest reported downloads over the last 30 days in this collection" if field == "downloads" else "Most liked repositories in this collection"
        lines.extend(["", heading + ":"])
        for rank, item in enumerate(insights["top_datasets"][field], 1):
            lines.append(f"  {rank:2}. {item['dataset_id']}: {item['value']:,}")
        if not insights["top_datasets"][field]:
            lines.append("  No reported values.")

    for field, label in (("formats", "Top dataset formats/types (reported format tags)"),
                         ("task_categories", "Top task categories"),
                         ("languages", "Top language tags"), ("tags", "Top tags (all returned tags)")):
        lines.extend(["", label + ":"])
        for rank, (value, count) in enumerate(summary["reports"][field][:10], 1):
            # Prevent control characters in remote tags from affecting the terminal.
            label_value = "".join(c for c in value if c.isprintable())
            noun = "repository" if count == 1 else "repositories"
            lines.append(
                f"  {rank:2}. {label_value}: {count:,} {noun} "
                f"({count / summary['rows']:.1%})"
            )
        if not summary["reports"][field]:
            lines.append("  No matching tags returned.")

    owners = insights["owners"]
    lines.extend(["", "Top repository owners by datasets in this collection (users or organizations):"])
    for rank, item in enumerate(owners[:10], 1):
        noun = "repository" if item["dataset_count"] == 1 else "repositories"
        lines.append(f"  {rank:2}. {item['owner']}: {item['dataset_count']:,} {noun}")
    if not owners:
        lines.append("  No owner namespaces returned.")
    lines.extend(["", "Top repository owners by summed reported 30-day downloads in this collection:"])
    ranked_owners = sorted((item for item in owners if item["total_downloads"] is not None),
                           key=lambda item: (-item["total_downloads"], item["owner"]))
    for rank, item in enumerate(ranked_owners[:10], 1):
        lines.append(f"  {rank:2}. {item['owner']}: {item['total_downloads']:,} "
                     f"(counts reported for {item['reported_downloads']}/{item['dataset_count']} repositories)")
    if not ranked_owners:
        lines.append("  No reported downloads for owner namespaces.")
    lines.extend(["", "Metadata coverage:", f"  Distinct owner namespaces: {len(owners):,}"])
    for key, label in (("missing_tags", "Missing tag lists"),
                       ("without_format_tags", "Without format tags"),
                       ("without_returned_citation", "Without returned citation")):
        lines.append(f"  {label}: {summary[key]:,} / {summary['rows']:,}")
    lines.extend([f"  Without owner namespace: {insights['without_owner_namespace']:,}", "",
                  "All rankings describe this selected collection, not the whole Hub.",
                  "Tag percentages use all collected rows; categories overlap and missing tags remain missing.",
                  "Owners are repository namespaces, not downloaders; totals are not unique people.",
                  "Missing tag lists count null/absent values; empty lists also have no format tags."])
    return "\n".join(lines) + "\n"


def write_outputs(directory, rows, manifest):
    dataset_path = directory / "datasets.jsonl"
    with dataset_path.open("w", encoding="utf-8") as output:
        for row in rows:
            output.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n")

    with dataset_path.open(encoding="utf-8") as source:
        reloaded = [json.loads(line) for line in source]
    if reloaded != rows:
        raise DatasetError("The saved dataset did not pass its reload check.")

    reports = {}
    for field in (*GROUPS, "tags"):
        counts = Counter(value for row in rows for value in set(row[field] or []))
        ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
        reports[field] = ordered
        with (directory / f"{field}_counts.csv").open(
            "w", newline="", encoding="utf-8-sig"
        ) as output:
            writer = csv.writer(output, quoting=csv.QUOTE_ALL)
            writer.writerow(["value", "dataset_count"])
            writer.writerows((csv_cell(value), count) for value, count in ordered)

    summary = {
        "rows": len(rows),
        "missing_downloads": sum(row["downloads"] is None for row in rows),
        "missing_tags": sum(row["tags"] is None for row in rows),
        "without_format_tags": sum(not row["formats"] for row in rows),
        "without_returned_citation": sum(not row["citation"] for row in rows),
        "reports": reports,
    }
    summary["insights"] = build_insights(rows)
    (directory / "insights.txt").write_text(render_insights(summary), encoding="utf-8")
    with (directory / "owners.csv").open("w", newline="", encoding="utf-8-sig") as output:
        writer = csv.writer(output, quoting=csv.QUOTE_ALL)
        writer.writerow(["owner", "dataset_count", "reported_downloads", "total_downloads"])
        for item in summary["insights"]["owners"]:
            writer.writerow([csv_cell(item["owner"]), item["dataset_count"],
                             item["reported_downloads"], item["total_downloads"]])
    save_json(directory / "summary.json", summary)
    save_json(directory / "collection.json", manifest)
    (directory / "README.md").write_text(
        f"""# Hugging Face dataset metadata snapshot

One row describes one public dataset repository. This collection contains
{len(rows)} results from a request for the top {LIMIT} repositories by downloads over the last 30 days.
Collection finished at {manifest['collection_finished_at']} (UTC).

## Files

datasets.jsonl contains the processed records. The CSV files count repositories
with each reported tag, task category, language or format. summary.json includes
counts of missing information and insights with download/like statistics,
top repositories, and owner aggregates. insights.txt contains the terminal report.
owners.csv lists namespaces by repository count, with reported-download coverage
and summed downloads (blank if none are reported). collection.json records the exact request.
Means and medians exclude missing values, but include zero. Tag percentages use
all collected rows. Owners may be users or organizations; they are not downloaders.
Owner totals cover only repositories in this collection, not their entire account.
In owners.csv, owner is the namespace before the slash, dataset_count counts its
collected repositories, reported_downloads counts repositories with a nonmissing
download value, and total_downloads sums those values over the last 30 days.
Namespaces may be users or organizations. IDs without a namespace are excluded
from owner rankings and counted separately in the insights.
In summary.json, missing_tags counts absent/null tag lists, not empty lists.
without_format_tags includes both missing and empty lists, plus lists with no
matching format tag. All rankings break equal values alphabetically by ID or label.
The original response is stored in ../RAWDATA/response.json.

## Fields

* dataset_id: Repository identifier returned by Hugging Face.
* url: Link to the original dataset repository.
* downloads: Hub downloads over the last 30 days at collection time, not unique users.
* likes: Hub likes value at collection time.
* tags: Original returned tags, or null when missing.
* task_categories, languages, formats: Sorted unique values extracted from tags.
  An empty list means no matching tags were returned.
* citation: Citation text when returned, otherwise null. This is not a count.
* source_revision: Returned repository revision, otherwise null. It does not
  freeze download counts or other changing Hub metadata.
* collected_at: UTC collection completion time.

## Method and limitations

Only public API metadata was requested, using one page of up to {LIMIT} results.
Dataset contents were not downloaded. This collector does not follow pagination.
Selection favours heavily downloaded repositories and does not represent the
whole Hub. Categories can overlap. Format tags are not a file inspection.
No DOI extraction was performed. Missing metadata does not prove that the
information is absent elsewhere. Downloads and tags may change over time.
Download counts use a rolling 30-day window; differences between snapshots
are not counts of new downloads between collections.
Raw values were preserved; no missing counts were replaced with zero.
CSV exports remove control characters and escape formula prefixes for safer
spreadsheet viewing. JSONL retains the original text.

Review source terms and attribution before redistributing this collection.
No blanket licence is assigned to third party metadata by this script.

Source: https://huggingface.co/datasets
API: https://huggingface.co/docs/hub/api
Downloads: https://huggingface.co/docs/hub/datasets-download-stats
Rate limits: https://huggingface.co/docs/hub/rate-limits
""",
        encoding="utf-8",
    )
    return summary


def main():
    run_directory = None
    try:
        print("\nLet's make a dataset :)\n")
        print("[1/4] Collecting public metadata from Hugging Face...")
        started_at = utc_now()
        body = fetch_snapshot()
        manifest = {
            "collection_started_at": started_at,
            "collection_finished_at": utc_now(),
            "request_url": API_URL,
            "query": QUERY,
            "python_version": sys.version.split()[0],
            "script_version": SCRIPT_VERSION,
        }

        base = Path.cwd() / "dataset_output"
        base.mkdir(exist_ok=True)
        prefix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ_")
        run_directory = Path(tempfile.mkdtemp(prefix=prefix, dir=base))
        print(f"  Output folder: {run_directory}")
        print("[2/4] Saving the raw response...")
        raw = run_directory / "RAWDATA"
        raw.mkdir()
        (raw / "response.json").write_bytes(body)
        save_json(raw / "collection.json", manifest)

        print("[3/4] Preparing and checking the records...")
        records = json.loads((raw / "response.json").read_text(encoding="utf-8"))
        rows = prepare_rows(records, manifest["collection_finished_at"])
        if len(rows) < LIMIT:
            print(f"  The API returned {len(rows)} of the {LIMIT} requested records.")

        print("[4/4] Saving the dataset, reports and README...")
        staging = run_directory / "PROCESSING"
        staging.mkdir()
        summary = write_outputs(staging, rows, manifest)
        # Publish the completed folder only after writing and verification succeed.
        staging.rename(run_directory / "PROCESSED")

        print(f"\nDone. Saved and checked {len(rows)} dataset records.\n")
        print(render_insights(summary), end="")
        print(f"\nOpen this folder: {run_directory / 'PROCESSED'}")
        return 0
    except KeyboardInterrupt:
        print("\nStopped. This run may be incomplete.", file=sys.stderr)
    except DatasetError as error:
        print(f"\nStopped: {error}", file=sys.stderr)
    except (UnicodeError, ValueError, RecursionError):
        print("\nStopped: the response could not be processed as valid data.", file=sys.stderr)
    except OSError:
        print("\nStopped: check your connection, folder permissions and free disk space.", file=sys.stderr)
    if run_directory is not None:
        print(f"Incomplete run retained at: {run_directory}", file=sys.stderr)
    return 1


if __name__ == "__main__":
    if sys.version_info < (3, 10):
        print("Please use Python 3.10 or newer.", file=sys.stderr)
        sys.exit(1)
    sys.exit(main())

[td] tegridydev

Website · Hugging Face · GitHub

Community

•
This comment has been hidden

Sign up or log in to comment