Okay, you're on the right track! You've correctly created a DatasetCard object using the huggingface_hub library. The next step is to include this card's content when you call push_to_hub.
As discussed in the previous answer, push_to_hub (for both Dataset and DatasetDict) allows you to upload additional files by specifying their local src_path and their desired file_name in the repository.
Here's how you integrate your DatasetCard object into the push_to_hub process:
- Get the full card content: The
DatasetCard object holds both the YAML data and the Markdown content. You can get the final string representation (which includes the --- separators and the correctly formatted YAML) using str(card) or card.text.
- Save the content to a local file: Write this string to a local file named
README.md.
- Use
src_path and file_name in push_to_hub: Point src_path to your local README.md file and set file_name to "README.md".
Let's complete your code snippet:
import os
from datasets import Dataset, DatasetDict
# Make sure you have huggingface_hub installed: pip install huggingface_hub
from huggingface_hub import DatasetCard
# --- Assume these variables are already defined from your processing ---
# subsample_ratio = 0.1
# total_bytes = 123456789
# num_languages = 50
# min_bytes = 10000
# max_bytes = 5000000
# markdown_table = "| Lang | Bytes |\n|---|---|\n| en | 100000 |..."
# texts_sampled = {'en': ['hello'], 'fr': ['bonjour']} # Example structure
# -----------------------------------------------------------------------
# --- 1. (Optional) Define your repository ID ---
# Replace with your desired namespace/repo_name (e.g., "username/my-processed-dataset")
repo_id = "your-username/my-processed-moscar-subsample" # <-- CHANGE THIS!
# --- 2. Create DatasetCard content and object ---
# Define the YAML data part (recommended structure)
card_data = {
"tags": ["language-modeling", "multilingual", "oscar"],
"license": "apache-2.0", # Replace with the actual license if different
"dataset_info": {
"description": "A subsample of the mOSCAR dataset processed for language modeling.",
"features": [
{"name": "lang", "dtype": "string"},
{"name": "text", "dtype": "string"}
],
"splits": [
{"name": "train", "num_rows": len([item for sublist in texts_sampled.values() for item in sublist])} # Calculate total rows
],
# You can add structured stats here if you prefer, or keep them in markdown
# "processing_stats": {
# "subsample_ratio": subsample_ratio,
# "total_bytes": total_bytes,
# ...
# }
}
}
# Define the Markdown body part
markdown_body = (
"### Processed Dataset Statistics\n\n"
"This dataset is a subsample of the [mOSCAR dataset](https://huggingface.co/datasets/oscar-corpus/mOSCAR).\n\n"
f"**Subsample Ratio:** {subsample_ratio}\n\n"
f"**Overall Size (Bytes):** {total_bytes}\n\n"
f"**Number of Languages:** {num_languages}\n\n"
f"**Minimum Bytes per Language:** {min_bytes}\n\n"
f"**Maximum Bytes per Language:** {max_bytes}\n\n"
f"{markdown_table}" # Your generated table
)
# Create the DatasetCard object
card = DatasetCard(data=card_data, content=markdown_body)
# --- 3. Prepare dataset for upload ---
hf_data = []
for lang, texts in texts_sampled.items():
for text in texts:
hf_data.append({'lang': lang, 'text': text})
dataset_dict = DatasetDict({"train": Dataset.from_dict(hf_data)})
# --- 4. Get the full card content string ---
# This includes the YAML front matter and the markdown body
card_content_string = str(card) # Or card.text
# --- 5. Save the content to a local file ---
card_path = "README.md" # Standard filename
try:
with open(card_path, "w", encoding="utf-8") as f:
f.write(card_content_string)
print(f"Created local DatasetCard file: {card_path}")
# --- 6. Push the dataset AND the card to the Hub ---
# Use file_name="README.md" and src_path=card_path
print(f"Pushing dataset and card to hub: {repo_id}")
dataset_dict.push_to_hub(
repo_id,
file_name="README.md", # The name it will have in the repo
src_path=card_path, # The path to your local file
split="train", # Specify split if not pushing all splits
private=False, # Set to True if you want a private repo
commit_message="Add processed dataset with DatasetCard"
)
print(f"Successfully pushed dataset and card to https://huggingface.co/datasets/{repo_id}")
except Exception as e:
print(f"An error occurred: {e}")
print("Make sure you have authenticated with `huggingface-cli login`")
print("And that the repo_id is valid and you have permissions.")
finally:
# --- 7. Clean up the local file (optional) ---
if os.path.exists(card_path):
os.remove(card_path)
print(f"Removed local card file: {card_path}")