-
-
Notifications
You must be signed in to change notification settings - Fork 46
Add Parquet dataset upload endpoint #252
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Vivekgupta008
wants to merge
2
commits into
openml:main
Choose a base branch
from
Vivekgupta008:vivek/parquet-upload
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import hashlib | ||
| import io | ||
| from dataclasses import dataclass, field | ||
|
|
||
| import pyarrow as pa | ||
| import pyarrow.parquet as pq | ||
|
|
||
| from schemas.datasets.openml import FeatureType | ||
|
|
||
| __all__ = [ | ||
| "ColumnMeta", | ||
| "FeatureType", | ||
| "ParquetMeta", | ||
| "map_arrow_type", | ||
| "read_parquet_metadata", | ||
| ] | ||
|
|
||
|
|
||
| def map_arrow_type(arrow_type: pa.DataType) -> FeatureType: | ||
| """Map a PyArrow DataType to an OpenML FeatureType.""" | ||
| if ( | ||
| pa.types.is_floating(arrow_type) | ||
| or pa.types.is_integer(arrow_type) | ||
| or pa.types.is_decimal( | ||
| arrow_type, | ||
| ) | ||
| ): | ||
| return FeatureType.NUMERIC | ||
| if pa.types.is_boolean(arrow_type) or pa.types.is_dictionary(arrow_type): | ||
| return FeatureType.NOMINAL | ||
| return FeatureType.STRING | ||
|
|
||
|
|
||
| @dataclass | ||
| class ColumnMeta: | ||
| index: int | ||
| name: str | ||
| data_type: FeatureType | ||
| number_of_missing_values: int | ||
|
|
||
|
|
||
| @dataclass | ||
| class ParquetMeta: | ||
| num_rows: int | ||
| num_columns: int | ||
| md5_checksum: str | ||
| columns: list[ColumnMeta] = field(default_factory=list) | ||
|
|
||
|
|
||
| def read_parquet_metadata(file_bytes: bytes) -> ParquetMeta: | ||
| """Parse *file_bytes* as Parquet and extract schema / quality metadata. | ||
|
|
||
| Raises ``ValueError`` if the bytes are not a valid Parquet file. | ||
| """ | ||
| try: | ||
| buf = io.BytesIO(file_bytes) | ||
| pf = pq.ParquetFile(buf) | ||
| except Exception as exc: | ||
| msg = "File is not a valid Parquet file." | ||
| raise ValueError(msg) from exc | ||
|
|
||
| schema = pf.schema_arrow | ||
| num_rows = pf.metadata.num_rows | ||
| md5 = hashlib.md5(file_bytes, usedforsecurity=False).hexdigest() | ||
|
|
||
| # Read full table once to count per-column nulls | ||
| table = pf.read() | ||
|
|
||
| columns: list[ColumnMeta] = [] | ||
| for idx, col_name in enumerate(schema.names): | ||
| col = table.column(col_name) | ||
| null_count = col.null_count | ||
| columns.append( | ||
| ColumnMeta( | ||
| index=idx, | ||
| name=col_name, | ||
| data_type=map_arrow_type(schema.field(col_name).type), | ||
| number_of_missing_values=null_count, | ||
| ), | ||
| ) | ||
|
|
||
| return ParquetMeta( | ||
| num_rows=num_rows, | ||
| num_columns=len(columns), | ||
| md5_checksum=md5, | ||
| columns=columns, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| import logging | ||
| import os | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| import boto3 | ||
| from botocore.exceptions import BotoCoreError, ClientError | ||
|
|
||
| from config import _config_file, _load_configuration | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pathlib import Path | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| MINIO_ACCESS_KEY_ENV = "OPENML_MINIO_ACCESS_KEY" | ||
| MINIO_SECRET_KEY_ENV = "OPENML_MINIO_SECRET_KEY" # noqa: S105 | ||
|
|
||
|
|
||
| def _minio_config(file: Path = _config_file) -> dict[str, str]: | ||
| cfg = _load_configuration(file).get("minio", {}) | ||
| access_key = os.environ.get(MINIO_ACCESS_KEY_ENV) or cfg.get("access_key", "") | ||
| secret_key = os.environ.get(MINIO_SECRET_KEY_ENV) or cfg.get("secret_key", "") | ||
| if not access_key or not secret_key: | ||
| msg = ( | ||
| f"MinIO credentials not found. Set {MINIO_ACCESS_KEY_ENV} and " | ||
| f"{MINIO_SECRET_KEY_ENV} environment variables." | ||
| ) | ||
| raise RuntimeError(msg) | ||
| return { | ||
| "endpoint_url": cfg.get("endpoint_url", "http://minio:9000"), | ||
| "bucket": cfg.get("bucket", "datasets"), | ||
| "access_key": access_key, | ||
| "secret_key": secret_key, | ||
| } | ||
|
|
||
|
|
||
| def _object_key(dataset_id: int) -> str: | ||
| """Return the MinIO object key for a dataset, matching the existing URL pattern.""" | ||
| ten_thousands_prefix = f"{dataset_id // 10_000:04d}" | ||
| padded_id = f"{dataset_id:04d}" | ||
| return f"datasets/{ten_thousands_prefix}/{padded_id}/dataset_{dataset_id}.pq" | ||
|
|
||
|
|
||
| def upload_to_minio(file_bytes: bytes, dataset_id: int) -> str: | ||
| """Upload *file_bytes* to MinIO and return the object key. | ||
|
|
||
| Raises ``RuntimeError`` on upload failure so callers can convert to HTTP 500. | ||
| """ | ||
| cfg = _minio_config() | ||
| key = _object_key(dataset_id) | ||
| try: | ||
| client = boto3.client( | ||
| "s3", | ||
| endpoint_url=cfg["endpoint_url"], | ||
| aws_access_key_id=cfg["access_key"], | ||
| aws_secret_access_key=cfg["secret_key"], | ||
| ) | ||
| client.upload_fileobj(io.BytesIO(file_bytes), cfg["bucket"], key) | ||
| logger.info("Uploaded dataset %d to MinIO at key '%s'", dataset_id, key) | ||
| except (BotoCoreError, ClientError) as exc: | ||
| msg = f"Failed to upload dataset {dataset_id} to MinIO: {exc}" | ||
| logger.exception(msg) | ||
| raise RuntimeError(msg) from exc | ||
| return key |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.