To fetch complete data (including files) from a Hugging Face repository and upload it to an Amazon S3 bucket, you can follow these steps:
-
Set Up Environment:
- Install necessary Python libraries.
- Configure AWS credentials.
- (Optional) Authenticate with Hugging Face if accessing private repositories.
-
Download Data from Hugging Face:
- Use the
huggingface_hub library to clone or download the repository contents.
-
Upload Data to Amazon S3:
- Use the
boto3 library to interact with Amazon S3 and upload the downloaded files.
Below is a detailed guide with code snippets to accomplish this.
Step 1: Set Up Your Environment
1.1 Install Required Libraries
Ensure you have Python installed. Then, install the necessary libraries using pip:
pip install huggingface_hub boto3
1.2 Configure AWS Credentials
To interact with Amazon S3, you need to configure your AWS credentials. You can do this by setting environment variables or using the AWS credentials file.
Using Environment Variables:
export AWS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'
export AWS_SECRET_ACCESS_KEY='YOUR_SECRET_ACCESS_KEY'
export AWS_DEFAULT_REGION='YOUR_AWS_REGION' # e.g., us-west-2
Using AWS Credentials File:
Create a file at ~/.aws/credentials and add:
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
Ensure your IAM user has the necessary permissions to access the target S3 bucket.
1.3 (Optional) Authenticate with Hugging Face
If you're accessing a private repository or need higher rate limits, authenticate with Hugging Face:
from huggingface_hub import login
# Run this in your terminal or include in your script
login(token="YOUR_HUGGING_FACE_TOKEN")
Replace "YOUR_HUGGING_FACE_TOKEN" with your actual Hugging Face token, which you can obtain from your Hugging Face account settings.
Step 2: Download Data from Hugging Face
We'll use the huggingface_hub library to clone the repository containing the data you want. Depending on whether it's a dataset or a model, adjust the repository type accordingly.
Example: Downloading a Dataset Repository
Suppose you want to download the entire contents of a dataset repository named username/dataset-repo.
from huggingface_hub import snapshot_download
import os
# Define the repository ID
repo_id = "username/dataset-repo"
# Specify the local directory to download the repository
local_dir = "./hf_dataset_repo"
# Download the repository snapshot
snapshot_download(repo_id=repo_id, local_dir=local_dir, ignore_patterns=None)
This will download all files from the specified repository into the ./hf_dataset_repo directory.
Notes:
-
snapshot_download Parameters:
repo_id: The repository identifier in the format username/repo-name.
local_dir: The local directory where the repository will be downloaded.
ignore_patterns: Patterns to ignore during download (set to None to download everything).
-
For large repositories, consider checking available disk space and download time.
Step 3: Upload Data to Amazon S3
With the data downloaded locally, use boto3 to upload it to your S3 bucket.
3.1 Initialize the S3 Client
import boto3
from botocore.exceptions import NoCredentialsError
# Initialize the S3 client
s3_client = boto3.client('s3')
3.2 Define the Upload Function
Here's a function to recursively upload all files from a local directory to a specified S3 bucket:
import os
def upload_directory_to_s3(local_directory, bucket_name, s3_prefix=''):
"""
Uploads the contents of a local directory to an S3 bucket.
:param local_directory: Path to the local directory.
:param bucket_name: Name of the target S3 bucket.
:param s3_prefix: (Optional) Prefix for the S3 objects.
"""
for root, dirs, files in os.walk(local_directory):
for file in files:
# Construct the full local path
local_path = os.path.join(root, file)
# Construct the relative S3 path
relative_path = os.path.relpath(local_path, local_directory)
if s3_prefix:
s3_path = os.path.join(s3_prefix, relative_path)
else:
s3_path = relative_path
try:
print(f'Uploading {local_path} to s3://{bucket_name}/{s3_path}')
s3_client.upload_file(local_path, bucket_name, s3_path)
except FileNotFoundError:
print(f"The file {local_path} was not found.")
except NoCredentialsError:
print("AWS credentials not available.")
3.3 Execute the Upload
# Define your S3 bucket name
bucket_name = 'your-s3-bucket-name'
# (Optional) Define a prefix within the bucket
s3_prefix = 'path/in/bucket' # e.g., 'huggingface-data'
# Upload the directory
upload_directory_to_s3(local_dir, bucket_name, s3_prefix)
Explanation:
3.4 Verify the Upload
You can list objects in the bucket to confirm the upload:
response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=s3_prefix)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['Key'])
else:
print("No objects found in the bucket with the specified prefix.")
Complete Script Example
Here's a complete Python script combining all the steps:
import os
from huggingface_hub import snapshot_download
import boto3
from botocore.exceptions import NoCredentialsError
def download_huggingface_repo(repo_id, local_dir):
snapshot_download(repo_id=repo_id, local_dir=local_dir, ignore_patterns=None)
print(f"Repository {repo_id} downloaded to {local_dir}")
def upload_directory_to_s3(local_directory, bucket_name, s3_prefix='', aws_region='us-west-2'):
s3_client = boto3.client('s3', region_name=aws_region)
for root, dirs, files in os.walk(local_directory):
for file in files:
local_path = os.path.join(root, file)
relative_path = os.path.relpath(local_path, local_directory)
s3_path = os.path.join(s3_prefix, relative_path) if s3_prefix else relative_path
try:
print(f'Uploading {local_path} to s3://{bucket_name}/{s3_path}')
s3_client.upload_file(local_path, bucket_name, s3_path)
except FileNotFoundError:
print(f"The file {local_path} was not found.")
except NoCredentialsError:
print("AWS credentials not available.")
def main():
# Configuration
repo_id = "username/dataset-repo" # Replace with your repository
local_dir = "./hf_dataset_repo"
bucket_name = "your-s3-bucket-name"
s3_prefix = "huggingface-data" # Optional
aws_region = "us-west-2" # Replace with your AWS region
# Step 1: Download repository from Hugging Face
download_huggingface_repo(repo_id, local_dir)
# Step 2: Upload to Amazon S3
upload_directory_to_s3(local_dir, bucket_name, s3_prefix, aws_region)
print("Upload completed successfully.")
if __name__ == "__main__":
main()
Instructions:
-
Replace Configuration Placeholders:
repo_id: The Hugging Face repository ID you want to download.
bucket_name: Your target Amazon S3 bucket name.
s3_prefix: (Optional) S3 folder path where the data will be uploaded.
aws_region: Your AWS region (e.g., us-west-2).
-
Run the Script:
python script_name.py
Replace script_name.py with the name you saved the script as.
Additional Considerations
-
Data Size:
- Ensure that your local machine has sufficient storage to download the Hugging Face repository.
- Be aware of S3 upload limits and consider multipart uploads for very large files.
-
Private Repositories:
- If the Hugging Face repository is private, ensure you have the necessary access tokens and authenticate using the
huggingface_hub library.
-
Security:
- Never hard-code AWS credentials or Hugging Face tokens in your scripts. Use environment variables or secure storage solutions.
-
Efficiency:
- For very large datasets or frequent transfers, consider using AWS services like AWS DataSync or leveraging parallel uploads with
boto3's TransferConfig.
-
Cleanup:
- Optionally, remove the locally downloaded repository after uploading to free up space:
import shutil
shutil.rmtree(local_dir)
print(f"Removed local directory {local_dir}")
- Error Handling Enhancements:
- Implement retries for transient network errors.
- Log errors to a file for later inspection.
Conclusion
By following the steps above, you can efficiently fetch complete data from a Hugging Face repository and upload it to an Amazon S3 bucket. This approach leverages powerful Python libraries to handle interactions with both Hugging Face and AWS, enabling seamless data transfer workflows.
If you encounter any issues or have specific requirements (e.g., handling specific file types, optimizing upload speeds), consider consulting the documentation for huggingface_hub and boto3 for advanced configurations and features.
References: