carbr 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
carbr/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ """carbr — imóveis do Cadastro Ambiental Rural (CAR) no Python.
2
+
3
+ Os imóveis rurais declarados no CAR, republicados do serviço público do Sicar
4
+ em GeoParquet. As consultas por UF, município, situação, porte, retângulo,
5
+ ponto ou código leem do arquivo remoto só os trechos de que precisam: não é
6
+ preciso baixar a base inteira.
7
+
8
+ Quick start
9
+ -----------
10
+ >>> import carbr
11
+ >>> carbr.car_catalog() # doctest: +SKIP
12
+ >>> carbr.car_summary(["state", "size_class"]) # doctest: +SKIP
13
+ >>> carbr.car_properties("PE", municipality="Petrolina") # doctest: +SKIP
14
+ >>> carbr.car_at(lon=-40.5, lat=-9.2) # doctest: +SKIP
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from ._client import (
20
+ CarError,
21
+ CarWarning,
22
+ ConfigError,
23
+ IntegrityError,
24
+ set_base_url,
25
+ set_timeout,
26
+ )
27
+ from ._client import cache_dir as car_cache_dir
28
+ from ._client import clear_cache as car_cache_clear
29
+ from ._msg import set_verbose
30
+ from .cite import car_cite
31
+ from .data import (
32
+ car_at,
33
+ car_catalog,
34
+ car_dictionary,
35
+ car_municipalities,
36
+ car_properties,
37
+ car_property,
38
+ car_summary,
39
+ car_tbl,
40
+ )
41
+
42
+ __version__ = "0.1.0"
43
+
44
+ __all__ = [
45
+ "CarError",
46
+ "CarWarning",
47
+ "ConfigError",
48
+ "IntegrityError",
49
+ "car_at",
50
+ "car_cache_clear",
51
+ "car_cache_dir",
52
+ "car_catalog",
53
+ "car_cite",
54
+ "car_dictionary",
55
+ "car_municipalities",
56
+ "car_properties",
57
+ "car_property",
58
+ "car_summary",
59
+ "car_tbl",
60
+ "set_base_url",
61
+ "set_timeout",
62
+ "set_verbose",
63
+ ]
carbr/_client.py ADDED
@@ -0,0 +1,246 @@
1
+ """Where the publication lives, how small files are fetched and cached."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import shutil
9
+ import time
10
+ import warnings
11
+ from pathlib import Path
12
+ from urllib.parse import quote
13
+
14
+ import duckdb
15
+ import platformdirs
16
+ import requests
17
+
18
+ from . import _msg
19
+
20
+ _TIMEOUT = 60.0
21
+ _MAX_TRIES = 3
22
+ _CATALOG_MAX_AGE = 6 * 3600
23
+ DEFAULT_URL = "https://car.castlab.org/current"
24
+ _BASE_URL: str | None = None
25
+ _CON: duckdb.DuckDBPyConnection | None = None
26
+ _HTTPFS = False
27
+
28
+
29
+ class CarError(Exception):
30
+ """Erro do carbr."""
31
+
32
+
33
+ class ConfigError(CarError):
34
+ """Extensão do DuckDB indisponível."""
35
+
36
+
37
+ class IntegrityError(CarError):
38
+ """Arquivo que não confere com o SHA-256 do catálogo."""
39
+
40
+
41
+ class CarWarning(UserWarning):
42
+ """A publicação não respondeu; a função devolve um resultado vazio."""
43
+
44
+
45
+ def set_base_url(url: str | os.PathLike | None) -> None:
46
+ """Define o endereço (URL ou pasta local) da publicação.
47
+
48
+ Sem isso, vale a variável de ambiente ``CAR_URL`` e, na falta dela, o
49
+ bucket público. ``None`` volta ao padrão.
50
+ """
51
+ global _BASE_URL
52
+ _BASE_URL = None if url is None else str(url)
53
+
54
+
55
+ def set_timeout(seconds: float) -> None:
56
+ """Tempo limite de cada requisição, em segundos (padrão 60)."""
57
+ global _TIMEOUT
58
+ _TIMEOUT = float(seconds)
59
+
60
+
61
+ def base_url() -> str:
62
+ base = _BASE_URL or os.environ.get("CAR_URL") or DEFAULT_URL
63
+ return base.rstrip("/") if is_remote(base) else str(Path(base).expanduser().resolve())
64
+
65
+
66
+ def is_remote(base: str) -> bool:
67
+ return base.startswith(("http://", "https://"))
68
+
69
+
70
+ def cache_dir() -> Path:
71
+ """Pasta de cache do carbr.
72
+
73
+ Guarda o catálogo e o resumo municipal, uma pasta por versão. Os imóveis
74
+ não são copiados: cada consulta lê do arquivo remoto só o que precisa.
75
+ """
76
+ return Path(os.environ.get("CAR_CACHE_DIR") or platformdirs.user_cache_dir("carbr"))
77
+
78
+
79
+ def clear_cache() -> Path:
80
+ """Apaga o cache e devolve o caminho da pasta."""
81
+ path = cache_dir()
82
+ if path.exists():
83
+ shutil.rmtree(path)
84
+ _msg.success(f"Cleared carbr cache at {path}.")
85
+ else:
86
+ _msg.step(f"No carbr cache found at {path}.")
87
+ return path
88
+
89
+
90
+ def _warn(reason: str) -> None:
91
+ warnings.warn(
92
+ f"The CAR publication could not be reached; returning an empty result. {reason}",
93
+ CarWarning,
94
+ stacklevel=4,
95
+ )
96
+
97
+
98
+ def fetch(path: str) -> bytes | None:
99
+ """A small file of the publication, or ``None`` (with a warning)."""
100
+ base = base_url()
101
+ if not is_remote(base):
102
+ file = Path(base) / path
103
+ if file.exists():
104
+ return file.read_bytes()
105
+ _warn(f"{file} does not exist.")
106
+ return None
107
+ url = f"{base}/{quote(path)}"
108
+ reason = ""
109
+ for attempt in range(1, _MAX_TRIES + 1):
110
+ try:
111
+ resp = requests.get(url, timeout=_TIMEOUT, headers={"User-Agent": "carbr Python package"})
112
+ if resp.status_code == 200:
113
+ return resp.content
114
+ reason = f"HTTP {resp.status_code}"
115
+ if resp.status_code not in (429, 500, 502, 503, 504):
116
+ break
117
+ except requests.RequestException as err:
118
+ reason = str(err)
119
+ if attempt < _MAX_TRIES:
120
+ time.sleep(2**attempt)
121
+ _warn(reason)
122
+ return None
123
+
124
+
125
+ def _parse_catalog(raw: bytes) -> dict:
126
+ cat = json.loads(raw)
127
+ if "version" not in cat or "files" not in cat:
128
+ raise CarError("Unexpected catalogue format (no version/files).")
129
+ return cat
130
+
131
+
132
+ def catalog_json(refresh: bool = False) -> dict | None:
133
+ """The published catalogue, from the disk cache when recent enough."""
134
+ base = base_url()
135
+ if not is_remote(base):
136
+ raw = fetch("catalog.json")
137
+ return None if raw is None else _parse_catalog(raw)
138
+ path = cache_dir() / "catalog.json"
139
+ age = time.time() - path.stat().st_mtime if path.exists() else float("inf")
140
+ if not refresh and age < _CATALOG_MAX_AGE:
141
+ return _parse_catalog(path.read_bytes())
142
+ raw = fetch("catalog.json")
143
+ if raw is None:
144
+ if path.exists():
145
+ _msg.step("Using the cached catalogue.")
146
+ return _parse_catalog(path.read_bytes())
147
+ return None
148
+ cat = _parse_catalog(raw)
149
+ path.parent.mkdir(parents=True, exist_ok=True)
150
+ path.write_bytes(raw)
151
+ return cat
152
+
153
+
154
+ def _sha256(path: Path) -> str:
155
+ h = hashlib.sha256()
156
+ with path.open("rb") as f:
157
+ for chunk in iter(lambda: f.read(1 << 20), b""):
158
+ h.update(chunk)
159
+ return h.hexdigest()
160
+
161
+
162
+ def cached_file(cat: dict, path: str) -> Path | None:
163
+ """Path to a verified local copy of a small catalogue file.
164
+
165
+ The publication is updated in place. When a file no longer matches the
166
+ SHA-256 of a catalogue read from the cache, the catalogue is read again
167
+ and the file is checked against the fresh one.
168
+ """
169
+
170
+ def sha_of(cat: dict) -> str:
171
+ entry = next((f for f in cat["files"] if f["path"] == path), None)
172
+ if entry is None:
173
+ raise CarError(f"{path} is not in the catalogue.")
174
+ return entry["sha256"]
175
+
176
+ sha256 = sha_of(cat)
177
+ base = base_url()
178
+ if not is_remote(base):
179
+ return Path(base) / path
180
+ dest = cache_dir() / cat["version"] / path
181
+ if dest.exists() and _sha256(dest) == sha256:
182
+ return dest
183
+ raw = fetch(path)
184
+ if raw is None:
185
+ return None
186
+ dest.parent.mkdir(parents=True, exist_ok=True)
187
+ tmp = dest.with_name(dest.name + ".tmp")
188
+ tmp.write_bytes(raw)
189
+ if _sha256(tmp) != sha256:
190
+ fresh = catalog_json(refresh=True)
191
+ if fresh is None or _sha256(tmp) != sha_of(fresh):
192
+ tmp.unlink()
193
+ raise IntegrityError(
194
+ f"{path} does not match the SHA-256 in the catalogue. The publication "
195
+ "may be in progress; try again in a few minutes."
196
+ )
197
+ cat = fresh
198
+ dest = cache_dir() / cat["version"] / path
199
+ dest.parent.mkdir(parents=True, exist_ok=True)
200
+ tmp.replace(dest)
201
+ # Files of other catalogue versions are superseded.
202
+ for other in cache_dir().iterdir():
203
+ if other.is_dir() and other.name != cat["version"]:
204
+ shutil.rmtree(other)
205
+ return dest
206
+
207
+
208
+ def con() -> duckdb.DuckDBPyConnection:
209
+ """The package's DuckDB connection (in memory, created on first use)."""
210
+ global _CON, _HTTPFS
211
+ if _CON is None:
212
+ _CON = duckdb.connect()
213
+ _HTTPFS = False
214
+ return _CON
215
+
216
+
217
+ def _need_httpfs() -> None:
218
+ global _HTTPFS
219
+ if _HTTPFS:
220
+ return
221
+ try:
222
+ try:
223
+ con().execute("LOAD httpfs")
224
+ except duckdb.Error:
225
+ con().execute("INSTALL httpfs")
226
+ con().execute("LOAD httpfs")
227
+ except duckdb.Error as err:
228
+ raise ConfigError(
229
+ "DuckDB's httpfs extension could not be loaded; it is downloaded once "
230
+ "from the DuckDB extension repository."
231
+ ) from err
232
+ _HTTPFS = True
233
+
234
+
235
+ def property_files(cat: dict, states: list[str]) -> list[str]:
236
+ """Addresses of the property files of the given states."""
237
+ base = base_url()
238
+ keep = [
239
+ f["path"]
240
+ for f in cat["files"]
241
+ if f["path"].startswith("properties/state=") and f["path"][17:19] in states
242
+ ]
243
+ if is_remote(base):
244
+ _need_httpfs()
245
+ return [f"{base}/{quote(p)}" for p in keep]
246
+ return [str(Path(base) / p) for p in keep]
carbr/_msg.py ADDED
@@ -0,0 +1,26 @@
1
+ """Lightweight console messages, mirroring the R package's cli alerts.
2
+
3
+ Messages go to stderr and can be silenced with :func:`set_verbose`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+
10
+ _VERBOSE = True
11
+
12
+
13
+ def set_verbose(verbose: bool) -> None:
14
+ """Liga ou desliga as mensagens informativas."""
15
+ global _VERBOSE
16
+ _VERBOSE = bool(verbose)
17
+
18
+
19
+ def success(message: str) -> None:
20
+ if _VERBOSE:
21
+ print(f"✔ {message}", file=sys.stderr)
22
+
23
+
24
+ def step(message: str) -> None:
25
+ if _VERBOSE:
26
+ print(f"ℹ {message}", file=sys.stderr)
carbr/cite.py ADDED
@@ -0,0 +1,26 @@
1
+ """How to cite the data."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def citation(version: str) -> str:
7
+ return (
8
+ "Serviço Florestal Brasileiro. Sistema Nacional de Cadastro Ambiental Rural "
9
+ "(Sicar): imóveis rurais. Dados organizados pelo CastLab/UFPE (pacote carbr), "
10
+ f"versão {version}."
11
+ )
12
+
13
+
14
+ def car_cite() -> str | None:
15
+ """Imprime e devolve a citação da versão publicada.
16
+
17
+ A origem dos dados é o Sicar, do Serviço Florestal Brasileiro.
18
+ """
19
+ from . import _client
20
+
21
+ cat = _client.catalog_json()
22
+ if cat is None:
23
+ return None
24
+ text = citation(cat["version"])
25
+ print(text)
26
+ return text
carbr/data.py ADDED
@@ -0,0 +1,361 @@
1
+ """The public functions: catalogue, municipalities and properties."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import unicodedata
8
+ import warnings
9
+ from typing import Iterable, Sequence
10
+
11
+ import duckdb
12
+ import pandas as pd
13
+
14
+ from . import _client, _msg
15
+ from .cite import citation
16
+
17
+ COLUMNS = [
18
+ "property_code", "status_code", "status", "condition", "property_type_code",
19
+ "property_type", "created_at", "area_ha", "fiscal_modules", "size_class", "state",
20
+ "municipality", "municipality_code", "registration_state", "lon", "lat",
21
+ "geometry_valid", "xmin", "ymin", "xmax", "ymax", "geometry",
22
+ ]
23
+ _STATUS = ("active", "pending", "suspended", "cancelled")
24
+ _SIZE = ("small", "medium", "large")
25
+ _TYPE = ("rural_property", "settlement", "traditional_community")
26
+ _CODE = re.compile(r"^[A-Z]{2}-[0-9]{7}-[0-9A-F]{32}$")
27
+ _CRS = "EPSG:4674"
28
+
29
+
30
+ def _as_list(x) -> list:
31
+ if x is None:
32
+ return []
33
+ return [x] if isinstance(x, (str, int)) else list(x)
34
+
35
+
36
+ def _choices(value, allowed: Sequence[str], arg: str) -> list[str]:
37
+ values = _as_list(value)
38
+ bad = [v for v in values if v not in allowed]
39
+ if bad:
40
+ raise ValueError(f"`{arg}` must be one of {', '.join(allowed)}; got {bad!r}.")
41
+ return values
42
+
43
+
44
+ def _fold(text: str) -> str:
45
+ """Lower case, no accents, single spaces: how municipality names are matched."""
46
+ text = unicodedata.normalize("NFKD", str(text)).encode("ascii", "ignore").decode()
47
+ return " ".join(re.sub(r"[^a-z0-9 ]", "", text.lower()).split())
48
+
49
+
50
+ def _states(state, cat: dict) -> list[str]:
51
+ available = list(cat["states"])
52
+ if state is None:
53
+ return available
54
+ states = [str(s).upper() for s in _as_list(state)]
55
+ missing = [s for s in states if s not in available]
56
+ if missing:
57
+ raise ValueError(
58
+ f"State(s) {missing!r} not in this publication. Available: {available!r}."
59
+ )
60
+ return states
61
+
62
+
63
+ def _relation(cat: dict, states: list[str]) -> duckdb.DuckDBPyRelation:
64
+ return _client.con().read_parquet(_client.property_files(cat, states))
65
+
66
+
67
+ def _collect(rel: duckdb.DuckDBPyRelation, where: list[str], params: list, geometry: bool):
68
+ cols = "*" if geometry else "* EXCLUDE (geometry)"
69
+ sql = f"SELECT {cols} FROM rel" + (" WHERE " + " AND ".join(where) if where else "")
70
+ try:
71
+ return _client.con().execute(sql, params).df()
72
+ except duckdb.Error as err:
73
+ warnings.warn(
74
+ f"The CAR publication could not be read; returning an empty result. {err}",
75
+ _client.CarWarning,
76
+ stacklevel=3,
77
+ )
78
+ return None
79
+
80
+
81
+ def _finish(out: pd.DataFrame | None, geometry: bool):
82
+ """DataFrame, or GeoDataFrame when geometry was asked for and geopandas is there."""
83
+ if out is None:
84
+ out = pd.DataFrame(columns=COLUMNS)
85
+ if not geometry:
86
+ return out.drop(columns="geometry", errors="ignore")
87
+ try:
88
+ import geopandas as gpd
89
+ except ImportError:
90
+ _msg.step("Install carbr[geo] to get a GeoDataFrame; returning WKB.")
91
+ return out
92
+ geom = gpd.GeoSeries.from_wkb(out["geometry"].map(lambda g: None if g is None else bytes(g)),
93
+ crs=_CRS)
94
+ return gpd.GeoDataFrame(out.drop(columns="geometry"), geometry=geom, crs=_CRS)
95
+
96
+
97
+ def car_catalog(refresh: bool = False) -> pd.DataFrame:
98
+ """O que está publicado: uma linha por UF.
99
+
100
+ A versão, a origem e a citação ficam em ``df.attrs`` (``version``,
101
+ ``source``, ``citation``). Zero linhas (com aviso) se a publicação não
102
+ responder.
103
+
104
+ Parameters
105
+ ----------
106
+ refresh
107
+ Se ``True``, ignora o catálogo em cache (válido por 6 horas).
108
+ """
109
+ columns = ["state", "properties", "municipalities", "invalid_geometries",
110
+ "null_geometries", "registered_in_other_state"]
111
+ cat = _client.catalog_json(refresh)
112
+ if cat is None:
113
+ return pd.DataFrame(columns=columns)
114
+ rows = [
115
+ {
116
+ "state": uf,
117
+ "properties": s.get("properties"),
118
+ "municipalities": s.get("municipalities"),
119
+ **{k: s.get("quality", {}).get(k) for k in columns[3:]},
120
+ }
121
+ for uf, s in cat["states"].items()
122
+ ]
123
+ out = pd.DataFrame(rows, columns=columns)
124
+ out.attrs.update(version=cat["version"], source=cat.get("source"),
125
+ citation=citation(cat["version"]))
126
+ return out
127
+
128
+
129
+ def car_dictionary() -> pd.DataFrame:
130
+ """Dicionário de dados: coluna publicada, nome no Sicar e descrição."""
131
+ columns = ["column", "sicar_name", "description"]
132
+ raw = _client.fetch("dictionary.json")
133
+ if raw is None:
134
+ return pd.DataFrame(columns=columns)
135
+ return pd.DataFrame(json.loads(raw), columns=columns)
136
+
137
+
138
+ def car_municipalities(state: str | Iterable[str] | None = None) -> pd.DataFrame:
139
+ """Resumo por município.
140
+
141
+ Imóveis, pequenos imóveis (até 4 módulos fiscais), área declarada,
142
+ contagem por situação, geometrias inválidas e retângulo envolvente.
143
+
144
+ Parameters
145
+ ----------
146
+ state
147
+ Sigla de uma ou mais UFs; ``None`` traz todas as publicadas.
148
+ """
149
+ columns = ["state", "municipality_code", "municipality", "properties", "small_properties",
150
+ "area_ha", "active", "pending", "suspended", "cancelled", "invalid_geometries",
151
+ "xmin", "ymin", "xmax", "ymax"]
152
+ cat = _client.catalog_json()
153
+ if cat is None:
154
+ return pd.DataFrame(columns=columns)
155
+ files = [_client.cached_file(cat, f"municipalities/state={s}.parquet")
156
+ for s in _states(state, cat)]
157
+ if any(f is None for f in files):
158
+ return pd.DataFrame(columns=columns)
159
+ rel = _client.con().read_parquet([str(f) for f in files]) # noqa: F841
160
+ return _client.con().execute("SELECT * FROM rel ORDER BY municipality_code").df()
161
+
162
+
163
+ _DIMS = ("state", "status", "size_class", "property_type", "condition", "created_year")
164
+
165
+
166
+ def car_summary(by: str | Iterable[str] | None = "state",
167
+ state: str | Iterable[str] | None = None) -> pd.DataFrame:
168
+ """Resumo pré-calculado.
169
+
170
+ Contagem de imóveis e área declarada por qualquer combinação de UF,
171
+ situação, porte, tipo, etapa da análise e ano de criação do cadastro. Lê
172
+ tabelas pequenas, calculadas na publicação e guardadas em cache: responde
173
+ em segundos mesmo para o país inteiro, sem ler os imóveis.
174
+
175
+ Parameters
176
+ ----------
177
+ by
178
+ Dimensões do resumo, uma ou mais de ``"state"``, ``"status"``,
179
+ ``"size_class"``, ``"property_type"``, ``"condition"`` e
180
+ ``"created_year"``. ``None`` devolve uma linha só, com o total.
181
+ state
182
+ Sigla de uma ou mais UFs; ``None`` traz todas as publicadas.
183
+
184
+ Returns
185
+ -------
186
+ pandas.DataFrame
187
+ As colunas de ``by``, ``properties`` (número de imóveis) e ``area_ha``
188
+ (área declarada, em hectares).
189
+ """
190
+ by = _choices(by, _DIMS, "by")
191
+ empty = pd.DataFrame(columns=[*by, "properties", "area_ha"])
192
+ cat = _client.catalog_json()
193
+ if cat is None:
194
+ return empty
195
+ paths = [f"summary/state={s}.parquet" for s in _states(state, cat)]
196
+ if not set(paths) <= {f["path"] for f in cat["files"]}:
197
+ # A catalogue cached before the summary was published.
198
+ cat = _client.catalog_json(refresh=True)
199
+ if cat is None:
200
+ return empty
201
+ files = [_client.cached_file(cat, p) for p in paths]
202
+ if any(f is None for f in files):
203
+ return empty
204
+ rel = _client.con().read_parquet([str(f) for f in files]) # noqa: F841
205
+ cols = ", ".join([*by, "sum(properties)::BIGINT AS properties", "sum(area_ha) AS area_ha"])
206
+ group = f" GROUP BY {', '.join(by)} ORDER BY {', '.join(by)}" if by else ""
207
+ return _client.con().execute(f"SELECT {cols} FROM rel{group}").df()
208
+
209
+
210
+ def _municipality_codes(municipality, states: list[str]) -> list[int]:
211
+ values = _as_list(municipality)
212
+ if all(isinstance(v, int) or re.fullmatch(r"[0-9]{7}", str(v)) for v in values):
213
+ return [int(v) for v in values]
214
+ known = car_municipalities(states)
215
+ folded = known["municipality"].map(_fold)
216
+ wanted = [_fold(v) for v in values]
217
+ unknown = [v for v, w in zip(values, wanted) if w not in set(folded)]
218
+ if unknown:
219
+ raise ValueError(
220
+ f"Municipalities not found in {', '.join(states)}: {unknown!r}. "
221
+ "See car_municipalities(), or pass the 7-digit IBGE code."
222
+ )
223
+ return [int(c) for c in known.loc[folded.isin(wanted), "municipality_code"]]
224
+
225
+
226
+ def car_tbl(state: str | Iterable[str] | None = None) -> duckdb.DuckDBPyRelation | None:
227
+ """Relação preguiçosa do DuckDB sobre os imóveis.
228
+
229
+ Para consultas que as outras funções não cobrem. Nada é lido até
230
+ ``.df()``; ``filter``, ``project`` e ``aggregate`` viram leitura parcial
231
+ do arquivo remoto. A geometria vem em WKB.
232
+ """
233
+ cat = _client.catalog_json()
234
+ if cat is None:
235
+ return None
236
+ return _relation(cat, _states(state, cat))
237
+
238
+
239
+ def car_properties(
240
+ state: str | Iterable[str],
241
+ municipality=None,
242
+ status=None,
243
+ size_class=None,
244
+ property_type=None,
245
+ bbox: Sequence[float] | None = None,
246
+ geometry: bool = True,
247
+ ):
248
+ """Imóveis rurais declarados no CAR.
249
+
250
+ Os filtros são aplicados antes da leitura: só os trechos do arquivo que
251
+ os atendem são transferidos.
252
+
253
+ Parameters
254
+ ----------
255
+ state
256
+ Sigla de uma ou mais UFs.
257
+ municipality
258
+ Nomes ou códigos IBGE (7 dígitos) de municípios.
259
+ status
260
+ ``"active"``, ``"pending"``, ``"suspended"``, ``"cancelled"``.
261
+ size_class
262
+ ``"small"`` (até 4 módulos fiscais), ``"medium"`` (acima de 4 até 15), ``"large"``.
263
+ property_type
264
+ ``"rural_property"``, ``"settlement"``, ``"traditional_community"``.
265
+ bbox
266
+ ``(xmin, ymin, xmax, ymax)`` em graus (SIRGAS 2000).
267
+ geometry
268
+ Se ``True``, devolve o perímetro: GeoDataFrame com ``carbr[geo]``
269
+ instalado, senão WKB. ``False`` não transfere a geometria.
270
+
271
+ Returns
272
+ -------
273
+ pandas.DataFrame ou geopandas.GeoDataFrame
274
+ Uma linha por imóvel; as colunas estão em :func:`car_dictionary`.
275
+ """
276
+ status = _choices(status, _STATUS, "status")
277
+ size_class = _choices(size_class, _SIZE, "size_class")
278
+ property_type = _choices(property_type, _TYPE, "property_type")
279
+ if bbox is not None and len(bbox) != 4:
280
+ raise ValueError("`bbox` must be (xmin, ymin, xmax, ymax).")
281
+ cat = _client.catalog_json()
282
+ if cat is None:
283
+ return _finish(None, geometry)
284
+ states = _states(state, cat)
285
+ where, params = [], []
286
+
287
+ def isin(column: str, values: list) -> None:
288
+ where.append(f"{column} IN ({', '.join('?' * len(values))})")
289
+ params.extend(values)
290
+
291
+ if municipality is not None:
292
+ isin("municipality_code", _municipality_codes(municipality, states))
293
+ if status:
294
+ isin("status", status)
295
+ if size_class:
296
+ isin("size_class", size_class)
297
+ if property_type:
298
+ isin("property_type", property_type)
299
+ if bbox is not None:
300
+ where.append("xmax >= ? AND ymax >= ? AND xmin <= ? AND ymin <= ?")
301
+ params.extend(float(v) for v in bbox)
302
+ rel = _relation(cat, states)
303
+ return _finish(_collect(rel, where, params, geometry), geometry)
304
+
305
+
306
+ def car_property(code: str | Iterable[str], geometry: bool = True):
307
+ """Um ou mais imóveis pelo código (``UF-0000000-identificador``)."""
308
+ codes = [str(c).strip().upper() for c in _as_list(code)]
309
+ bad = [c for c in codes if not _CODE.match(c)]
310
+ if bad:
311
+ raise ValueError(
312
+ f"Not CAR property codes: {bad!r}. Expected 'UF-0000000-' followed by "
313
+ "32 hexadecimal digits."
314
+ )
315
+ cat = _client.catalog_json()
316
+ if cat is None:
317
+ return _finish(None, geometry)
318
+ rel = _relation(cat, list(cat["states"]))
319
+ marks = ", ".join("?" * len(codes))
320
+ # The code carries the municipality: that filter reads a few row groups.
321
+ out = _collect(
322
+ rel,
323
+ [f"municipality_code IN ({marks})", f"property_code IN ({marks})"],
324
+ [int(c[3:10]) for c in codes] + codes,
325
+ geometry,
326
+ )
327
+ if out is None:
328
+ return _finish(None, geometry)
329
+ # A few properties sit in another municipality or state than the code says.
330
+ left = [c for c in codes if c not in set(out["property_code"])]
331
+ if left:
332
+ more = _collect(rel, [f"property_code IN ({', '.join('?' * len(left))})"], left, geometry)
333
+ if more is not None and len(more):
334
+ out = pd.concat([out, more], ignore_index=True)
335
+ return _finish(out, geometry)
336
+
337
+
338
+ def car_at(lon: float, lat: float, state=None, geometry: bool = True):
339
+ """Imóveis que contêm um ponto.
340
+
341
+ Responde "que imóveis estão declarados aqui?". O filtro pelo retângulo
342
+ envolvente é feito na leitura remota e o teste exato, com o shapely
343
+ (``carbr[geo]``). Sobreposições são comuns: pode vir mais de uma linha.
344
+ """
345
+ lon, lat = float(lon), float(lat)
346
+ try:
347
+ import geopandas # noqa: F401
348
+ from shapely.geometry import Point
349
+ except ImportError as err:
350
+ raise ImportError("car_at() needs geopandas: pip install 'carbr[geo]'.") from err
351
+ cat = _client.catalog_json()
352
+ if cat is None:
353
+ return _finish(None, geometry)
354
+ rel = _relation(cat, _states(state, cat))
355
+ out = _collect(rel, ["xmin <= ? AND xmax >= ? AND ymin <= ? AND ymax >= ?"],
356
+ [lon, lon, lat, lat], True)
357
+ out = _finish(out, True)
358
+ out = out[out.geometry.intersects(Point(lon, lat))].reset_index(drop=True)
359
+ if not geometry:
360
+ return pd.DataFrame(out.drop(columns="geometry"))
361
+ return out
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: carbr
3
+ Version: 0.1.0
4
+ Summary: Imóveis do Cadastro Ambiental Rural (CAR) no Python, sem baixar a base inteira
5
+ Project-URL: Homepage, https://strategicprojects.github.io/carbr-py/
6
+ Project-URL: Documentation, https://strategicprojects.github.io/carbr-py/
7
+ Project-URL: Repository, https://github.com/StrategicProjects/carbr-py
8
+ Project-URL: Issues, https://github.com/StrategicProjects/carbr-py/issues
9
+ Project-URL: Changelog, https://github.com/StrategicProjects/carbr-py/blob/main/NEWS.md
10
+ Author-email: André Leite <leite@castlab.org>, Marcos Wasiliew <marcos.wasiliew@gmail.com>, Hugo Vasconcelos <hugo.vasconcelos@ufpe.br>, Carlos Amorim <carlos.agaf@ufpe.br>, Diogo Bezerra <diogo.bezerra@ufpe.br>, Hortênsia Nunes Braz de Oliveira <hortensia.nunes@condepefidem.pe.gov.br>
11
+ License: MIT License
12
+
13
+ Copyright (c) 2026 carbr authors
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+ License-File: LICENSE
33
+ Keywords: Brazil,CAR,Sicar,environment,geoparquet,open-data,rural
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Intended Audience :: Science/Research
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Natural Language :: Portuguese (Brazilian)
38
+ Classifier: Operating System :: OS Independent
39
+ Classifier: Programming Language :: Python :: 3
40
+ Classifier: Topic :: Scientific/Engineering :: GIS
41
+ Requires-Python: >=3.10
42
+ Requires-Dist: duckdb>=1.1
43
+ Requires-Dist: pandas>=1.3
44
+ Requires-Dist: platformdirs>=3
45
+ Requires-Dist: requests>=2.25
46
+ Provides-Extra: dev
47
+ Requires-Dist: build>=1.0; extra == 'dev'
48
+ Requires-Dist: geopandas>=1.0; extra == 'dev'
49
+ Requires-Dist: pytest>=7; extra == 'dev'
50
+ Requires-Dist: ruff>=0.6; extra == 'dev'
51
+ Provides-Extra: docs
52
+ Requires-Dist: contextily>=1.5; extra == 'docs'
53
+ Requires-Dist: geopandas>=1.0; extra == 'docs'
54
+ Requires-Dist: matplotlib>=3.5; extra == 'docs'
55
+ Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
56
+ Requires-Dist: mkdocstrings[python]>=0.26; extra == 'docs'
57
+ Provides-Extra: geo
58
+ Requires-Dist: geopandas>=1.0; extra == 'geo'
59
+ Provides-Extra: test
60
+ Requires-Dist: geopandas>=1.0; extra == 'test'
61
+ Requires-Dist: pytest>=7; extra == 'test'
62
+ Description-Content-Type: text/markdown
63
+
64
+ # carbr <img src="https://raw.githubusercontent.com/StrategicProjects/carbr-py/main/docs/assets/logo.svg" align="right" height="139" alt="" />
65
+
66
+ [![CI](https://github.com/StrategicProjects/carbr-py/actions/workflows/ci.yml/badge.svg)](https://github.com/StrategicProjects/carbr-py/actions/workflows/ci.yml)
67
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
68
+
69
+ Os imóveis rurais declarados no **Cadastro Ambiental Rural (CAR)** no Python, sem
70
+ baixar a base inteira.
71
+
72
+ O `carbr` lê uma republicação dos dados públicos do Sicar em GeoParquet. Cada
73
+ consulta — por UF, município, situação, porte, retângulo, ponto ou código do
74
+ imóvel — transfere só os trechos do arquivo de que precisa, e não passa pelos
75
+ servidores do Sicar.
76
+
77
+ **Documentação:** <https://strategicprojects.github.io/carbr-py/>
78
+
79
+ ## Instalação
80
+
81
+ ```bash
82
+ pip install "carbr[geo]"
83
+ ```
84
+
85
+ Sem o extra `geo`, a geometria vem em WKB e `car_at()` não está disponível.
86
+
87
+ ## Uso
88
+
89
+ ```python
90
+ import carbr
91
+
92
+ carbr.car_catalog() # UFs publicadas, versão e qualidade da carga
93
+ carbr.car_summary(["state", "size_class"]) # totais do país, sem ler os imóveis
94
+ carbr.car_municipalities("PE") # resumo por município
95
+
96
+ # Imóveis grandes de Petrolina, como GeoDataFrame
97
+ carbr.car_properties("PE", municipality="Petrolina", size_class="large")
98
+
99
+ # Cadastros pendentes do estado, sem transferir a geometria
100
+ carbr.car_properties("PE", status="pending", geometry=False)
101
+
102
+ carbr.car_at(lon=-40.5, lat=-9.2) # que imóveis estão declarados neste ponto?
103
+ carbr.car_property("PE-2611101-588BC484570D440484F527F07DF5AFFA")
104
+
105
+ # Qualquer outra consulta, direto no arquivo remoto
106
+ carbr.car_tbl("PE").aggregate("status, size_class, count(*) AS n").df()
107
+ ```
108
+
109
+ ## Guias
110
+
111
+ - [Primeiros passos](https://strategicprojects.github.io/carbr-py/primeiros-passos/)
112
+ - [Inconsistências do cadastro](https://strategicprojects.github.io/carbr-py/inconsistencias/): sobreposições, imóveis fora do município, área declarada maior que o território.
113
+ - [Onde a análise está parada](https://strategicprojects.github.io/carbr-py/fila-da-analise/): as etapas da análise por UF e quem aguarda resposta à notificação.
114
+
115
+ ## Os dados
116
+
117
+ - **Origem:** serviço público do Sicar, do Serviço Florestal Brasileiro. O cadastro é
118
+ autodeclarado: há sobreposições entre imóveis, e a presença no CAR não comprova domínio.
119
+ - **Conteúdo:** o perímetro declarado e dez atributos de cada imóvel. Não há dado pessoal.
120
+ - **Cobertura:** as 27 UFs, cerca de 8,6 milhões de imóveis. `car_catalog()` mostra o que está
121
+ publicado e a data.
122
+ - **Endereço:** o padrão é um bucket público; `carbr.set_base_url()` ou a variável `CAR_URL`
123
+ apontam para um espelho compatível com S3 ou para uma pasta local.
124
+
125
+ As mesmas funções existem em R: [carbr-r](https://github.com/StrategicProjects/carbr-r).
126
+
127
+ ## Licença
128
+
129
+ Código sob licença MIT. Os dados são do Sicar; use `car_cite()` para citá-los.
@@ -0,0 +1,9 @@
1
+ carbr/__init__.py,sha256=2GO_bslHm46w3AL-275vqnkrp1fmSmZQoFZq6vhrUuc,1585
2
+ carbr/_client.py,sha256=JVuTVhNSkd1RcfoX0ERpl9-HTV3-AFXitbpCt9NJQz8,7425
3
+ carbr/_msg.py,sha256=iD2rj8cJMaj60B_S4h_UPzI6etpGPKq-Vfuaanxm530,556
4
+ carbr/cite.py,sha256=IjqZZsBcyvffb3z5uXBXURMOglu6zWd8x0qLqXhE75c,663
5
+ carbr/data.py,sha256=2eIhUxfqxvu03xWibWu7a6Dt8lamfuYT4qvUN58-VdU,13656
6
+ carbr-0.1.0.dist-info/METADATA,sha256=ANZ2ONiRbVnVuksM8KeraorysywCF-tIDz5OPFx9mUU,6289
7
+ carbr-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ carbr-0.1.0.dist-info/licenses/LICENSE,sha256=7lZp1mfu8TL3lkWM-gxhcyR2nRCtf4nnaRWpb-G-GK0,1070
9
+ carbr-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 carbr authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.