import_dataset.py

Created about 12 hours ago

attributes
source_pathreferences/data-discovery/dataset-import/code_templates/import_dataset.py
source_sha25653b49813991e596953cc4e2cf815d9b75f34df8352f2ccc541f286007948f4a8
source_urlhttps://github.com/aws/agent-toolkit-for-aws/blob/903433d67cc4eeab334355620373f33a0c162dd4/skills/core-skills/aws-ai-ml/references/data-discovery/dataset-import/code_templates/import_dataset.py
supporting_skill_id40202
upstream_revision903433d67cc4eeab334355620373f33a0c162dd4
# Cell 0 [markdown]: Import a file as a SageMaker dataset
# Imports one S3 file or local file as a DataSet (see ../overview.md). Valid in
# both Script Mode and Notebook Mode (../../../code_output_guide.md). Region and
# credentials come from the SDK's default session. Needs a sagemaker-train
# release whose DataSet.create accepts dataset_file_format (sdk-getting-started
# installs the SDK); no line here is notebook-only, so nothing is marked as such.

# Cell 1: Parameters
DATASET_NAME = "[DATASET_NAME]"                  # confirmed with the user
SOURCE = "[SOURCE]"                              # s3://bucket/key.jsonl, or a local .jsonl path
DATASET_FILE_FORMAT = "[DATASET_FILE_FORMAT]"    # "Custom" unless a format is known
PROJECT_ID = "[PROJECT_ID]"                      # the active project ID, or None
ROLE_ARN = "[ROLE_ARN]"                          # the execution role ARN, or None (../overview.md, Step 2)

# Cell 2: Import
# Telemetry attribution before the first SDK call.
from sagemaker.core import Attribution, set_attribution

set_attribution(Attribution.SAGEMAKER_AGENT_PLUGIN)

import os

from sagemaker.ai_registry.dataset import DataSet

for _name, _value in (("DATASET_NAME", DATASET_NAME), ("SOURCE", SOURCE),
                      ("DATASET_FILE_FORMAT", DATASET_FILE_FORMAT)):
    if not _value.strip() or "[" in _value:
        raise ValueError(f"Fill {_name} before running this template")
_from_s3 = SOURCE.startswith("s3://")
if not _from_s3 and not (os.path.isfile(SOURCE) and SOURCE.endswith(".jsonl")):
    raise ValueError("SOURCE must be an s3:// URI or an existing local .jsonl file")
if not _from_s3 and os.path.getsize(SOURCE) > 50 * 1024 * 1024:
    raise ValueError("Local files over 50 MB must be uploaded to S3 and imported from there")
if PROJECT_ID is not None and (not PROJECT_ID.strip() or "[" in PROJECT_ID or " " in PROJECT_ID):
    raise ValueError("Set PROJECT_ID to the active project ID, or to None")
if ROLE_ARN is not None and (not ROLE_ARN.startswith("arn:") or "[" in ROLE_ARN):
    raise ValueError("Set ROLE_ARN to the execution role ARN, or to None")

# Stop if the name exists (../overview.md, Step 2).
try:
    _existing = DataSet.get(name=DATASET_NAME)
except Exception as error:  # the SDK raises botocore's ClientError
    # A missing name is code "ResourceNotFound" (seen live). Only a ClientError
    # carries a response code; anything else is raised as is.
    if getattr(error, "response", {}).get("Error", {}).get("Code") != "ResourceNotFound":
        raise
else:
    raise RuntimeError(f"Dataset {DATASET_NAME} already exists: {_existing.arn}")

# Passing tags replaces the SDK's default "method" keyword, so it is restated
# with the SDK's own value for this source. The
# sagemaker:project-id tag goes on this call, and the bundled SDK applies each tag as an
# AWS resource tag. Lineage reads a dataset's project from its versionless hub content
# name, so the tag attributes the dataset rather than the one version this call creates.
tags = (
    [("method", "generated" if _from_s3 else "uploaded"), ("sagemaker:project-id", PROJECT_ID)]
    if PROJECT_ID is not None
    else None
)

# The import document carries no role, so no ValidationRoleArn is sent; role= only
# names the role the SDK checks before the import, which runs as the caller's credentials.
dataset = DataSet.create(
    name=DATASET_NAME,
    source=SOURCE,  # a local file is uploaded to the default SageMaker bucket
    role=ROLE_ARN,
    dataset_file_format=DATASET_FILE_FORMAT,
    tags=tags,
    wait=True,  # short registration, no compute job: waits inline (../overview.md, Step 2)
)
print(f"Imported dataset: {dataset.arn}")
if PROJECT_ID is not None:
    # The tag drives the association; this checks that lineage wrote it.
    print(
        f"Confirm the association for {PROJECT_ID}: aws sagemaker list-artifacts "
        f"--source-uri {dataset.arn}. One artifact of type Dataset means it is "
        "linked (../overview.md, Step 3)."
    )

Children

No children yet.

Like how this is organised?

Build your own Memory tree on knowen.md: notes, decisions and tasks in one connected markdown graph, shared with your team and your AI agents.