|
| 1 | +import tempfile |
| 2 | +from functools import cached_property |
| 3 | +from typing import TYPE_CHECKING, Iterator |
| 4 | + |
| 5 | +from pyspark.sql.datasource import DataSource, DataSourceReader |
| 6 | +from pyspark.sql.pandas.types import from_arrow_schema |
| 7 | +from pyspark.sql.types import StructType |
| 8 | + |
| 9 | +if TYPE_CHECKING: |
| 10 | + import pyarrow as pa |
| 11 | + |
| 12 | + |
| 13 | +class KaggleDataSource(DataSource): |
| 14 | + """ |
| 15 | + A DataSource for reading Kaggle datasets in Spark. |
| 16 | +
|
| 17 | + This data source allows reading datasets from Kaggle directly into Spark DataFrames. |
| 18 | +
|
| 19 | + Name: `kaggle` |
| 20 | +
|
| 21 | + Options |
| 22 | + ------- |
| 23 | + - `handle`: The dataset handle on Kaggle, in the form of `{owner_slug}/{dataset_slug}` |
| 24 | + or `{owner_slug}/{dataset_slug}/versions/{version_number}` |
| 25 | + - `path`: The path to a file within the dataset. |
| 26 | + - `username`: The Kaggle username for authentication. |
| 27 | + - `key`: The Kaggle API key for authentication. |
| 28 | +
|
| 29 | + Notes: |
| 30 | + ----- |
| 31 | + - The `kagglehub` library is required to use this data source. Make sure it is installed. |
| 32 | + - To read private datasets or datasets that require user authentication, `username` and `key` must be provided. |
| 33 | + - Currently all data is read from a single partition. |
| 34 | +
|
| 35 | + Examples |
| 36 | + -------- |
| 37 | + Register the data source. |
| 38 | +
|
| 39 | + >>> from pyspark_datasources import KaggleDataSource |
| 40 | + >>> spark.dataSource.register(KaggleDataSource) |
| 41 | +
|
| 42 | + Load a public dataset from Kaggle. |
| 43 | +
|
| 44 | + >>> spark.read.format("kaggle").options(handle="yasserh/titanic-dataset").load("Titanic-Dataset.csv").select("Name").show() |
| 45 | + +--------------------+ |
| 46 | + | Name| |
| 47 | + +--------------------+ |
| 48 | + |Braund, Mr. Owen ...| |
| 49 | + |Cumings, Mrs. Joh...| |
| 50 | + |... | |
| 51 | + +--------------------+ |
| 52 | +
|
| 53 | + Load a private dataset with authentication. |
| 54 | +
|
| 55 | + >>> spark.read.format("kaggle").options( |
| 56 | + ... username="myaccount", |
| 57 | + ... key="<token>", |
| 58 | + ... handle="myaccount/my-private-dataset", |
| 59 | + ... ).load("file.csv").show() |
| 60 | + """ |
| 61 | + |
| 62 | + @classmethod |
| 63 | + def name(cls) -> str: |
| 64 | + return "kaggle" |
| 65 | + |
| 66 | + @cached_property |
| 67 | + def _data(self) -> "pa.Table": |
| 68 | + import ast |
| 69 | + import os |
| 70 | + |
| 71 | + import pyarrow as pa |
| 72 | + |
| 73 | + handle = self.options.pop("handle") |
| 74 | + path = self.options.pop("path") |
| 75 | + username = self.options.pop("username", None) |
| 76 | + key = self.options.pop("key", None) |
| 77 | + if username or key: |
| 78 | + if not (username and key): |
| 79 | + raise ValueError( |
| 80 | + "Both username and key must be provided to authenticate." |
| 81 | + ) |
| 82 | + os.environ["KAGGLE_USERNAME"] = username |
| 83 | + os.environ["KAGGLE_KEY"] = key |
| 84 | + |
| 85 | + kwargs = {k: ast.literal_eval(v) for k, v in self.options.items()} |
| 86 | + |
| 87 | + # Cache in a temporary directory to avoid writing to ~ which may be read-only |
| 88 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 89 | + os.environ["KAGGLEHUB_CACHE"] = tmpdir |
| 90 | + import kagglehub |
| 91 | + |
| 92 | + df = kagglehub.dataset_load( |
| 93 | + kagglehub.KaggleDatasetAdapter.PANDAS, |
| 94 | + handle, |
| 95 | + path, |
| 96 | + **kwargs, |
| 97 | + ) |
| 98 | + return pa.Table.from_pandas(df) |
| 99 | + |
| 100 | + def schema(self) -> StructType: |
| 101 | + return from_arrow_schema(self._data.schema) |
| 102 | + |
| 103 | + def reader(self, schema: StructType) -> "KaggleDataReader": |
| 104 | + return KaggleDataReader(self) |
| 105 | + |
| 106 | + |
| 107 | +class KaggleDataReader(DataSourceReader): |
| 108 | + def __init__(self, source: KaggleDataSource): |
| 109 | + self.source = source |
| 110 | + |
| 111 | + def read(self, partition) -> Iterator["pa.RecordBatch"]: |
| 112 | + yield from self.source._data.to_batches() |
0 commit comments