-
Notifications
You must be signed in to change notification settings - Fork 55
fix: update get_file_column_names to take a file reference #68
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
Merged
johnnygreco
merged 4 commits into
main
from
johnny/fix/bug-when-getting-column-names-from-datastore
Nov 24, 2025
+98
−52
Merged
Changes from all commits
Commits
Show all changes
4 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,47 +31,74 @@ class DatastoreSettings(BaseModel): | |
| token: Optional[str] = Field(default=None, description="If needed, token to use for authentication.") | ||
|
|
||
|
|
||
| def get_file_column_names(file_path: Union[str, Path], file_type: str) -> list[str]: | ||
| """Extract column names based on file type. Supports glob patterns like '../path/*.parquet'.""" | ||
| file_path = Path(file_path) | ||
| if "*" in str(file_path): | ||
| matching_files = sorted(file_path.parent.glob(file_path.name)) | ||
| if not matching_files: | ||
| raise InvalidFilePathError(f"🛑 No files found matching pattern: {str(file_path)!r}") | ||
| logger.debug(f"0️⃣ Using the first matching file in {str(file_path)!r} to determine column names in seed dataset") | ||
| file_path = matching_files[0] | ||
| def get_file_column_names(file_reference: Union[str, Path, HfFileSystem], file_type: str) -> list[str]: | ||
| """Get column names from a dataset file. | ||
|
|
||
| Args: | ||
| file_reference: Path to the dataset file, or an HfFileSystem object. | ||
| file_type: Type of the dataset file. Must be one of: 'parquet', 'json', 'jsonl', 'csv'. | ||
|
|
||
| Raises: | ||
| InvalidFilePathError: If the file type is not supported. | ||
|
|
||
| Returns: | ||
| List of column names. | ||
| """ | ||
| if file_type == "parquet": | ||
| try: | ||
| schema = pq.read_schema(file_path) | ||
| schema = pq.read_schema(file_reference) | ||
| if hasattr(schema, "names"): | ||
| return schema.names | ||
| else: | ||
| return [field.name for field in schema] | ||
| except Exception as e: | ||
| logger.warning(f"Failed to process parquet file {file_path}: {e}") | ||
| logger.warning(f"Failed to process parquet file {file_reference}: {e}") | ||
| return [] | ||
| elif file_type in ["json", "jsonl"]: | ||
| return pd.read_json(file_path, orient="records", lines=True, nrows=1).columns.tolist() | ||
| return pd.read_json(file_reference, orient="records", lines=True, nrows=1).columns.tolist() | ||
| elif file_type == "csv": | ||
| try: | ||
| df = pd.read_csv(file_path, nrows=1) | ||
| df = pd.read_csv(file_reference, nrows=1) | ||
| return df.columns.tolist() | ||
| except (pd.errors.EmptyDataError, pd.errors.ParserError) as e: | ||
| logger.warning(f"Failed to process CSV file {file_path}: {e}") | ||
| logger.warning(f"Failed to process CSV file {file_reference}: {e}") | ||
| return [] | ||
| else: | ||
| raise InvalidFilePathError(f"🛑 Unsupported file type: {file_type!r}") | ||
|
|
||
|
|
||
| def fetch_seed_dataset_column_names(seed_dataset_reference: SeedDatasetReference) -> list[str]: | ||
| if hasattr(seed_dataset_reference, "datastore_settings"): | ||
| return _fetch_seed_dataset_column_names_from_datastore( | ||
| return fetch_seed_dataset_column_names_from_datastore( | ||
| seed_dataset_reference.repo_id, | ||
| seed_dataset_reference.filename, | ||
| seed_dataset_reference.datastore_settings, | ||
| ) | ||
| return _fetch_seed_dataset_column_names_from_local_file(seed_dataset_reference.dataset) | ||
| return fetch_seed_dataset_column_names_from_local_file(seed_dataset_reference.dataset) | ||
|
|
||
|
|
||
| def fetch_seed_dataset_column_names_from_datastore( | ||
| repo_id: str, | ||
| filename: str, | ||
| datastore_settings: Optional[Union[DatastoreSettings, dict]] = None, | ||
| ) -> list[str]: | ||
| file_type = filename.split(".")[-1] | ||
| if f".{file_type}" not in VALID_DATASET_FILE_EXTENSIONS: | ||
| raise InvalidFileFormatError(f"🛑 Unsupported file type: {filename!r}") | ||
|
|
||
| datastore_settings = resolve_datastore_settings(datastore_settings) | ||
| fs = HfFileSystem(endpoint=datastore_settings.endpoint, token=datastore_settings.token, skip_instance_cache=True) | ||
|
|
||
| file_path = _extract_single_file_path_from_glob_pattern_if_present(f"datasets/{repo_id}/{filename}", fs=fs) | ||
|
|
||
| with fs.open(file_path) as f: | ||
| return get_file_column_names(f, file_type) | ||
|
|
||
|
|
||
| def fetch_seed_dataset_column_names_from_local_file(dataset_path: str | Path) -> list[str]: | ||
| dataset_path = _validate_dataset_path(dataset_path, allow_glob_pattern=True) | ||
| dataset_path = _extract_single_file_path_from_glob_pattern_if_present(dataset_path) | ||
| return get_file_column_names(dataset_path, str(dataset_path).split(".")[-1]) | ||
|
|
||
|
|
||
| def resolve_datastore_settings(datastore_settings: DatastoreSettings | dict | None) -> DatastoreSettings: | ||
|
|
@@ -114,25 +141,34 @@ def upload_to_hf_hub( | |
| return f"{repo_id}/{filename}" | ||
|
|
||
|
|
||
| def _fetch_seed_dataset_column_names_from_datastore( | ||
| repo_id: str, | ||
| filename: str, | ||
| datastore_settings: Optional[Union[DatastoreSettings, dict]] = None, | ||
| ) -> list[str]: | ||
| file_type = filename.split(".")[-1] | ||
| if f".{file_type}" not in VALID_DATASET_FILE_EXTENSIONS: | ||
| raise InvalidFileFormatError(f"🛑 Unsupported file type: {filename!r}") | ||
|
|
||
| datastore_settings = resolve_datastore_settings(datastore_settings) | ||
| fs = HfFileSystem(endpoint=datastore_settings.endpoint, token=datastore_settings.token, skip_instance_cache=True) | ||
|
|
||
| with fs.open(f"datasets/{repo_id}/{filename}") as f: | ||
| return get_file_column_names(f, file_type) | ||
|
|
||
| def _extract_single_file_path_from_glob_pattern_if_present( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This could be public too so we can more easily and directly test code paths? |
||
| file_path: str | Path, | ||
| fs: HfFileSystem | None = None, | ||
| ) -> Path: | ||
| file_path = Path(file_path) | ||
|
|
||
| def _fetch_seed_dataset_column_names_from_local_file(dataset_path: str | Path) -> list[str]: | ||
| dataset_path = _validate_dataset_path(dataset_path, allow_glob_pattern=True) | ||
| return get_file_column_names(dataset_path, str(dataset_path).split(".")[-1]) | ||
| # no glob pattern | ||
| if "*" not in str(file_path): | ||
| return file_path | ||
|
|
||
| # glob pattern with HfFileSystem | ||
| if fs is not None: | ||
| file_to_check = None | ||
| file_extension = file_path.name.split(".")[-1] | ||
| for file in fs.ls(str(file_path.parent)): | ||
| filename = file["name"] | ||
| if filename.endswith(f".{file_extension}"): | ||
| file_to_check = filename | ||
| if file_to_check is None: | ||
| raise InvalidFilePathError(f"🛑 No files found matching pattern: {str(file_path)!r}") | ||
| logger.debug(f"Using the first matching file in {str(file_path)!r} to determine column names in seed dataset") | ||
| return Path(file_to_check) | ||
|
|
||
| # glob pattern with local file system | ||
| if not (matching_files := sorted(file_path.parent.glob(file_path.name))): | ||
| raise InvalidFilePathError(f"🛑 No files found matching pattern: {str(file_path)!r}") | ||
| logger.debug(f"Using the first matching file in {str(file_path)!r} to determine column names in seed dataset") | ||
| return matching_files[0] | ||
|
|
||
|
|
||
| def _validate_dataset_path(dataset_path: Union[str, Path], allow_glob_pattern: bool = False) -> Path: | ||
|
|
||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
made these public because we should use them directly for testsing