-
Notifications
You must be signed in to change notification settings - Fork 125
Add v2 parquet pipeline foundation for Python geobr #418
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
JoaoCarabetta
wants to merge
3
commits into
ipeaGIT:master
Choose a base branch
from
JoaoCarabetta:python-v2-pipeline
base: master
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
3 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| # AppVeyor: Windows R CMD check for r-package only. | ||
| # Python CI runs in GitHub Actions (.github/workflows/Python-CMD-check.yaml). | ||
| # R also runs on Windows via GitHub Actions (.github/workflows/R-CMD-check.yaml). | ||
|
|
||
| only_commits: | ||
| files: | ||
| - r-package/** | ||
|
|
||
| skip_commits: | ||
| files: | ||
| - python-package/** | ||
| - .github/** | ||
| - mcp-server/** | ||
|
|
||
| environment: | ||
| global: | ||
| R_REMOTES_STANDALONE: true | ||
| PKGDIR: r-package | ||
| matrix: | ||
| - R_VERSION: release | ||
| R_ARCH: x64 | ||
|
|
||
| init: | ||
| ps: | | ||
| $ErrorActionPreference = "Stop" | ||
| Get-Date | ||
|
|
||
| install: | ||
| ps: | | ||
| $ErrorActionPreference = "Stop" | ||
| if (-not (Test-Path r-appveyor-scripts)) { | ||
| New-Item -ItemType Directory -Force -Path r-appveyor-scripts | Out-Null | ||
| } | ||
| if (-not (Test-Path r-appveyor-scripts/appveyor-tool.ps1)) { | ||
| Invoke-WebRequest -UseBasicParsing ` | ||
| -Uri "https://raw.githubusercontent.com/krlmlr/r-appveyor/master/scripts/appveyor-tool.ps1" ` | ||
| -OutFile "r-appveyor-scripts/appveyor-tool.ps1" | ||
| } | ||
| Import-Module .\r-appveyor-scripts\appveyor-tool.ps1 | ||
| Bootstrap | ||
|
|
||
| build_script: | ||
| ps: | | ||
| $ErrorActionPreference = "Stop" | ||
| Push-Location $env:PKGDIR | ||
| try { | ||
| travis-tool.sh install_deps | ||
| } finally { | ||
| Pop-Location | ||
| } | ||
|
|
||
| test_script: | ||
| ps: | | ||
| $ErrorActionPreference = "Stop" | ||
| Push-Location $env:PKGDIR | ||
| try { | ||
| travis-tool.sh run_tests | ||
| } finally { | ||
| Pop-Location | ||
| } | ||
|
|
||
| on_failure: | ||
| - 7z a failure.zip *.Rcheck\* | ||
| - appveyor PushArtifact failure.zip | ||
|
|
||
| artifacts: | ||
| - path: r-package\*.Rcheck\**\*.log | ||
| name: Logs | ||
| - path: r-package\*.Rcheck\**\*.out | ||
| name: Logs | ||
| - path: r-package\*.Rcheck\**\*.fail | ||
| name: Logs | ||
| - path: r-package\*.Rcheck\**\*.Rout | ||
| name: Logs | ||
| - path: r-package\*_*.zip | ||
| name: Bits |
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,33 @@ | ||
| """Disk-backed cache helpers for geobr parquet downloads.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def cache_dir() -> Path: | ||
| """Return the geobr cache directory (~/.cache/geobr or temp fallback).""" | ||
| base = os.environ.get("XDG_CACHE_HOME") | ||
| if base: | ||
| path = Path(base) / "geobr" | ||
| else: | ||
| path = Path.home() / ".cache" / "geobr" | ||
| try: | ||
| path.mkdir(parents=True, exist_ok=True) | ||
| except OSError: | ||
| import tempfile | ||
|
|
||
| path = Path(tempfile.gettempdir()) / "geobr" | ||
| path.mkdir(parents=True, exist_ok=True) | ||
| return path | ||
|
|
||
|
|
||
| def cached_path(filename: str) -> Path: | ||
| """Full path for a cached parquet file.""" | ||
| return cache_dir() / filename | ||
|
|
||
|
|
||
| def is_cached(filename: str) -> bool: | ||
| path = cached_path(filename) | ||
| return path.exists() and path.stat().st_size > 0 |
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,90 @@ | ||
| """Optional DuckDB backend for lazy parquet reads.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pathlib import Path | ||
| from typing import Any, Optional, Union | ||
|
|
||
| _CONN: Optional[Any] = None | ||
|
|
||
|
|
||
| def _require_duckdb(): | ||
| try: | ||
| import duckdb | ||
| except ImportError as e: | ||
| raise ImportError( | ||
| "Optional dependency 'duckdb' is required for output='duckdb'. " | ||
| "Install with: pip install geobr[duckdb]" | ||
| ) from e | ||
| return duckdb | ||
|
|
||
|
|
||
| def _setup_connection(conn) -> None: | ||
| for stmt in ("INSTALL spatial", "LOAD spatial", "INSTALL httpfs", "LOAD httpfs"): | ||
| try: | ||
| conn.execute(stmt) | ||
| except Exception: | ||
| pass | ||
|
|
||
|
|
||
| def duckdb_connection(): | ||
| """Return the shared DuckDB connection.""" | ||
| global _CONN | ||
| if _CONN is None: | ||
| duckdb = _require_duckdb() | ||
| _CONN = duckdb.connect() | ||
| _setup_connection(_CONN) | ||
| return _CONN | ||
|
|
||
|
|
||
| def register_dataset( | ||
| name: str, | ||
| parquet_path: Union[str, Path], | ||
| *, | ||
| connection: Optional[Any] = None, | ||
| ) -> Any: | ||
| """Register a parquet file as a DuckDB view.""" | ||
| conn = connection or duckdb_connection() | ||
| path_str = str(Path(parquet_path).resolve()).replace("'", "''") | ||
| safe_name = name.replace('"', '""') | ||
| conn.execute( | ||
| f'CREATE OR REPLACE VIEW "{safe_name}" AS ' | ||
| f"SELECT * FROM read_parquet('{path_str}')" | ||
| ) | ||
| return conn.sql(f'SELECT * FROM "{safe_name}"') | ||
|
|
||
|
|
||
| def read_parquet_relation( | ||
| path: Union[str, Path], | ||
| filter_code: Any = "all", | ||
| *, | ||
| connection: Optional[Any] = None, | ||
| view_name: Optional[str] = None, | ||
| ) -> Any: | ||
| """Return a DuckDB relation over a parquet file.""" | ||
| conn = connection or duckdb_connection() | ||
| if view_name: | ||
| register_dataset(view_name, path, connection=conn) | ||
| source = f'"{view_name.replace(chr(34), chr(34) * 2)}"' | ||
| else: | ||
| path_str = str(Path(path).resolve()).replace("'", "''") | ||
| source = f"read_parquet('{path_str}')" | ||
|
|
||
| if filter_code == "all" or filter_code is None: | ||
| return conn.sql(f"SELECT * FROM {source}") | ||
|
|
||
| codes = filter_code if isinstance(filter_code, (list, tuple)) else [filter_code] | ||
| code = codes[0] if len(codes) == 1 else filter_code | ||
|
|
||
| if isinstance(code, str) and len(code) == 2 and code.isalpha(): | ||
| return conn.sql(f"SELECT * FROM {source} WHERE abbrev_state = '{code}'") | ||
| if str(code).isdigit() and len(str(code)) == 7: | ||
| return conn.sql( | ||
| f"SELECT * FROM {source} WHERE CAST(code_muni AS BIGINT) = {int(code)}" | ||
| ) | ||
| if str(code).isdigit() and len(str(code)) <= 2: | ||
| return conn.sql( | ||
| f"SELECT * FROM {source} WHERE CAST(code_state AS INTEGER) = {int(code)}" | ||
| ) | ||
|
|
||
| return conn.sql(f"SELECT * FROM {source}") | ||
Oops, something went wrong.
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.
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.
Following the suggestion in https://github.com/ipeaGIT/geobr/pull/418/changes#r3283548653, this function can change to something like below. The filters would be done in a previous step in the arrow table.
I also included the
ST_GeomFromWKBfunction to correctly convert the geometry column into a duckdb spatial column (thx for the heads up regarding this @rafapereirabr !)