kagglehub

repository·main·Indexed 18 days ago

https://github.com/kaggle/kagglehub

A Python library providing a simple interface to interact with Kaggle resources, including datasets, models, notebook outputs, and competition data. It supports downloading and uploading models and datasets, loading datasets directly into Python objects via Pandas, Polars, or Hugging Face adapters, and managing local resource caches.

Tokens
8.9K
Snippets
31
Records
36
Agent score
66%

What's inside kagglehub

  1. How kagglehub behaves in Kaggle notebooks vs local environments

    main

    The behavior of kagglehub depends on whether you are running code inside a Kaggle notebook or in a local environment:

    In a Kaggle notebook:

    • Resources are automatically attached to your notebook.
    • Resources appear under the "Input" panel in the Kaggle notebook editor.
    • Files are served from the shared Kaggle resources cache rather than the VM's disk.

    Outside a Kaggle notebook:

    • Resource files are downloaded to a local cache folder.
  2. Set up VS Code for kagglehub development

    main

    To use VS Code with the project's hatch managed environments, follow these steps:

    1. Configure hatch to create virtual environments within the project folder:
      hatch config set dirs.env.virtual .
    2. Create the necessary Python environments by running all tests:
      hatch test --all
    3. In VS Code, open the Command Palette (cmd + shift + p), select Python: Select Interpreter, and pick an environment from the ./.env folder.
    hatch config set dirs.env.virtual .
    hatch test --all
  3. Authenticate with kagglehub

    main

    Authentication is required to access public resources requiring user consent or private resources. kagglehub is authenticated by default when running in a Kaggle notebook.

    To authenticate manually, you can use one of the following methods:

    1. Interactive Login: Call kagglehub.login() to be prompted for your Kaggle API token.
    2. Environment Variable: Export KAGGLE_API_TOKEN with your token value.
    3. API Token File: Place your token in ~/.kaggle/access_token.
    4. Google Colab Secret: Store your token in a Colab secret named KAGGLE_API_TOKEN.
    5. Legacy API Credentials: Place a kaggle.json file at ~/.kaggle/kaggle.json.
    import kagglehub
    
    # Option 1: Interactive login
    kagglehub.login()
  4. Configure the kagglehub cache directory

    main

    By default, kagglehub downloads files to ~/.cache/kagglehub/. You can override this location by setting the KAGGLEHUB_CACHE environment variable.

    export KAGGLEHUB_CACHE=/path/to/your/custom/cache
  5. Override the default cache directory

    main

    By default, kagglehub uses a standard system cache folder. You can redirect all cache operations to a specific directory by passing the override_dir argument to the Cache constructor. This is useful for managing disk space or working in environments with restricted write permissions.

    When an override_dir is provided, get_path and get_archive_path will resolve paths relative to this directory instead of the default Kaggle cache location.

    from kagglehub.cache import Cache
    
    # All downloaded resources will be stored in this specific folder
    cache = Cache(override_dir="/mnt/data/kaggle_cache")
  6. Configure file-based logging for kagglehub

    main

    By default, kagglehub is configured for console logging. To enable file-based logging, set the KAGGLE_LOGGING_ENABLED environment variable to 1.

    Logs will be written to a directory resolved via os.path.expanduser. The default log paths are:

    • macOS: /user/$USERNAME/.kaggle/logs/kagglehub.log
    • Linux: ~/.kaggle/logs/kagglehub.log
    • Windows: C:\Users\%USERNAME%\.kaggle\logs\kagglehub.log

    You can override the root log directory by setting the KAGGLE_LOGGING_ROOT_DIR environment variable.

  7. Load Datasets with dataset_load() and KaggleDatasetAdapter

    main

    The kagglehub.dataset_load() function loads Kaggle dataset files directly into Python objects using specific adapters.

    Required Dependencies:

    • KaggleDatasetAdapter.PANDAS: pip install kagglehub[pandas-datasets]
    • KaggleDatasetAdapter.HUGGING_FACE: pip install kagglehub[hf-datasets]
    • KaggleDatasetAdapter.POLARS: pip install kagglehub[polars-datasets]

    Adapters Overview

    1. KaggleDatasetAdapter.PANDAS

    Maps file extensions to pandas.read_* methods (e.g., .csv $\rightarrow$ read_csv, .parquet $\rightarrow$ read_parquet). Supports pandas_kwargs for passing arguments directly to pandas.

    2. KaggleDatasetAdapter.HUGGING_FACE

    Returns a Hugging Face Dataset object. It uses Dataset.from_pandas internally. Supports pandas_kwargs and hf_kwargs (passed to from_pandas).

    3. KaggleDatasetAdapter.POLARS

    Returns a polars.LazyFrame by default (using scan_* methods) or a polars.DataFrame if polars_frame_type=PolarsFrameType.DATA_FRAME is specified. Supports polars_kwargs.

    import kagglehub
    from kagglehub import KaggleDatasetAdapter, PolarsFrameType
    
    # Load as Pandas DataFrame
    df = kagglehub.dataset_load(
        KaggleDatasetAdapter.PANDAS,
        "unsdsn/world-happiness/versions/1",
        "2016.csv",
        pandas_kwargs={"columns": ["year", "score"]}
    )
    
    # Load as Hugging Face Dataset
    hf_dataset = kagglehub.dataset_load(
        KaggleDatasetAdapter.HUGGING_FACE,
        "robikscube/textocr-text-extraction-from-images-dataset",
        "annot.parquet"
    )
    
    # Load as Polars LazyFrame
    lf = kagglehub.dataset_load(
        KaggleDatasetAdapter.POLARS,
        "unsdsn/world-happiness/versions/1",
        "2016.csv"
    )
    # To get a DataFrame instead of a LazyFrame:
    df_polars = kagglehub.dataset_load(
        KaggleDatasetAdapter.POLARS,
        "robikscube/textocr-text-extraction-from-images-dataset",
        "annot.parquet",
        polars_frame_type=PolarsFrameType.DATA_FRAME
    )
  8. Download Models with model_download()

    main

    Use kagglehub.model_download() to download Kaggle models. You can download the latest version, a specific version, a single file, or force a re-download even if the file is already cached.

    Key Parameters:

    • handle: The model handle (e.g., 'google/bert/tensorFlow2/answer-equivalence-bem').
    • path: (Optional) The specific file path within the model to download.
    • force_download: (Optional) Boolean to force download even if cached.
    • output_dir: (Optional) Custom local directory for the download.
    import kagglehub
    
    # Download the latest version
    kagglehub.model_download('google/bert/tensorFlow2/answer-equivalence-bem')
    
    # Download a specific version
    kagglehub.model_download('google/bert/tensorFlow2/answer-equivalence-bem/1')
    
    # Download a single file
    kagglehub.model_download('google/bert/tensorFlow2/answer-equivalence-bem', path='variables/variables.index')
    
    # Download to a custom local directory
    kagglehub.model_download('google/bert/tensorFlow2/answer-equivalence-bem', output_dir='./models')
    
    # Force download and overwrite existing directory
    kagglehub.model_download('google/bert/tensorFlow2/answer-equivalence-bem', output_dir='./models', force_download=True)
  9. Download Datasets with dataset_download()

    main

    Use kagglehub.dataset_download() to download Kaggle datasets. You can download entire datasets, specific versions, single files, or directories while preserving structure.

    Key Parameters:

    • handle: The dataset handle.
    • path: (Optional) Specific file or directory path within the dataset.
    • force_download: (Optional) Boolean to force re-download.
    • output_dir: (Optional) Custom local directory for the download.
    import kagglehub
    
    # Download latest version
    kagglehub.dataset_download('bricevergnou/spotify-recommendation')
    
    # Download specific version
    kagglehub.dataset_download('bricevergnou/spotify-recommendation/versions/1')
    
    # Download a single file to a custom directory
    kagglehub.dataset_download('bricevergnou/spotify-recommendation', path='data.csv', output_dir='./data')
  10. Upload Models with model_upload()

    main

    Use kagglehub.model_upload() to upload a new model variation or version.

    Parameters:

    • handle: The target handle in the format <KAGGLE_USERNAME>/<MODEL>/<FRAMEWORK>/<VARIATION>.
    • local_model_dir: The path to your local model directory.
    • version_notes: (Optional) String describing the version.
    • license_name: (Optional) The license for the model.
    • ignore_patterns: (Optional) A list of file/directory patterns to exclude (e.g., ["original/", "*.tmp"]).
    import kagglehub
    
    handle = '<KAGGLE_USERNAME>/<MODEL>/<FRAMEWORK>/<VARIATION>'
    local_model_dir = 'path/to/local/model/dir'
    
    # Basic upload
    kagglehub.model_upload(handle, local_model_dir)
    
    # Upload with metadata and ignore patterns
    kagglehub.model_upload(
        handle, 
        local_model_dir, 
        version_notes='improved accuracy',
        license_name='Apache 2.0',
        ignore_patterns=["original/", "*.tmp"]
    )
  11. Install Utility Scripts with utility_script_install()

    main

    You can install Kaggle utility scripts directly into your Python environment using kagglehub.utility_script_install(). This makes the code from the script available for import/use in your current session.

    import kagglehub
    
    # Install the latest version of a utility script
    kagglehub.utility_script_install('bjoernjostein/physionet-challenge-utility-script')