quantilica-cli 0.19.0__tar.gz → 0.20.0__tar.gz
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.
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/CHANGELOG.md +20 -1
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/PKG-INFO +2 -1
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/pyproject.toml +3 -2
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/catalog.py +278 -44
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/cli.py +9 -2
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/sources.py +126 -45
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/conftest.py +12 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_catalog_cli.py +113 -1
- quantilica_cli-0.20.0/tests/test_catalog_registro.py +221 -0
- quantilica_cli-0.20.0/tests/test_catalog_sigla.py +38 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_registry_cli.py +1 -1
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sources.py +96 -1
- quantilica_cli-0.20.0/tests/test_sources_registro.py +72 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.githooks/pre-commit +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.githooks/pre-push +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.github/workflows/public-hygiene.yml +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.github/workflows/publish.yml +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.github/workflows/test.yml +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/.gitignore +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/LICENSE +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/README.md +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/__init__.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/docs.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/health.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/lake.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/manifests.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/registry.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/sdk.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/cli/ui.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/src/quantilica/py.typed +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/__init__.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/lake_build_fakes.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/lake_fixtures.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_cli_apelidos.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_docs_cli.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_health.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_lake_cli.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_manifests.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_package_hygiene.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk_backfill.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk_force_probe.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk_mes_string.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk_onda_a2.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_sdk_sync_exit.py +0 -0
- {quantilica_cli-0.19.0 → quantilica_cli-0.20.0}/tests/test_ui.py +0 -0
|
@@ -7,6 +7,25 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|
|
7
7
|
|
|
8
8
|
## [Não lançado]
|
|
9
9
|
|
|
10
|
+
## [0.20.0] - 2026-11-12
|
|
11
|
+
|
|
12
|
+
### Alterado
|
|
13
|
+
|
|
14
|
+
- `quantilica catalog sync` resolve o `source_id` do lake pelo registro de fetchers (apelido vira id canônico, e o id do dataset acompanha) e preenche a fonte com `nome`, `orgao`, `licenca`, `homepage`, `dominio` e `cadencia` do `FetcherInfo`; fonte fora do registro fica fora do envio, e com o registro vazio nada é enviado (sem registro não há como saber se a fonte pode ser redistribuída). Deixou de inventar `Geral`/`Open Data`/`mensal`/`nacional`. Cada dataset leva `fetcher_id` e `total_linhas` (soma de `num_rows` dos Parquets). Fonte de redistribuição restrita não entra no payload. Novo `--registry` aponta um `registry.json` no lugar dos fetchers instalados; o resumo do `--dry-run` mostra o que ficou de fora e o que é desconhecido.
|
|
15
|
+
- `quantilica sources install` consulta o índice da Quantilica antes do PyPI (uv: `--default-index` PyPI + `--index` Quantilica + `first-index`), e recusa instalar o que esse índice não publica, fechando o risco de dependency confusion; o erro de instalação informa quando o nome digitado foi lido como `<nome>-fetcher`.
|
|
16
|
+
- `quantilica sources install/uninstall` deixou de depender de uma lista de
|
|
17
|
+
fetchers escrita à mão: o nome curto vira `<id>-fetcher` (regra do registro),
|
|
18
|
+
então uma fonte nova é aceita sem editar o código. A tabela `SOURCES_REGISTRY`
|
|
19
|
+
guarda só o que foge da regra (`sql` e apelidos antigos como `bcb`, `rfb`,
|
|
20
|
+
`td`). Os nomes aceitos antes continuam levando à mesma distribuição.
|
|
21
|
+
- `quantilica catalog sync`: as amostras continuam com até 20 linhas por padrão (`--sample-size`), como estão no lake; com `--sample-size 0` a amostra não é enviada, e a já gravada no portal fica.
|
|
22
|
+
- `quantilica catalog sync` preenche a `sigla` da fonte com o primeiro trecho entre parênteses do órgão do registro (`... (ANAC)` vira `ANAC`; sem parênteses a sigla não é enviada, e a já gravada no portal fica).
|
|
23
|
+
- `quantilica catalog sync` recusa rodar sem `pyarrow` (antes saía com código 0, sem colunas, sem amostras e com zero linhas); o extra `lake` declara `pyarrow`.
|
|
24
|
+
|
|
25
|
+
### Corrigido
|
|
26
|
+
|
|
27
|
+
- `lake_path` do `catalog sync` sai com `/` também no Windows (antes, `anac\aero-caracteristicas`).
|
|
28
|
+
|
|
10
29
|
## [0.19.0] - 2026-11-11
|
|
11
30
|
|
|
12
31
|
### Adicionado
|
|
@@ -28,7 +47,7 @@ e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|
|
28
47
|
quando algum arquivo falha. Se ao menos um arquivo foi baixado e outros
|
|
29
48
|
falharam, sai com o código `3` (`EXIT_SYNC_PARTIAL`, "download parcial": o que
|
|
30
49
|
baixou está íntegro em disco); se nada foi baixado, sai com `1`. Antes saía
|
|
31
|
-
com `0` listando os erros, e quem automatiza a coleta (
|
|
50
|
+
com `0` listando os erros, e quem automatiza a coleta (agendador, integração contínua) considerava a
|
|
32
51
|
execução bem-sucedida. **Mudança de contrato:** scripts que tratam
|
|
33
52
|
qualquer código diferente de 0 como falha total devem tratar o `3` como
|
|
34
53
|
parcial. O `pipeline` converte o que baixou mesmo com download parcial e
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: quantilica-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.20.0
|
|
4
4
|
Summary: Unified CLI for Quantilica open data fetchers
|
|
5
5
|
Author-email: "Komesu, D.K." <daniel@dkko.me>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -22,6 +22,7 @@ Requires-Dist: typer>=0.15.0
|
|
|
22
22
|
Provides-Extra: docs
|
|
23
23
|
Requires-Dist: quantilica-core[docs]>=0.18.0; extra == 'docs'
|
|
24
24
|
Provides-Extra: lake
|
|
25
|
+
Requires-Dist: pyarrow>=15.0.0; extra == 'lake'
|
|
25
26
|
Requires-Dist: quantilica-analytics>=0.11.0; extra == 'lake'
|
|
26
27
|
Description-Content-Type: text/markdown
|
|
27
28
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "quantilica-cli"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.20.0"
|
|
4
4
|
description = "Unified CLI for Quantilica open data fetchers"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
authors = [{ name = "Komesu, D.K.", email = "daniel@dkko.me" }]
|
|
@@ -27,7 +27,7 @@ dependencies = [
|
|
|
27
27
|
|
|
28
28
|
[project.optional-dependencies]
|
|
29
29
|
# Motor de `quantilica lake build` e `quantilica lake audit`.
|
|
30
|
-
lake = ["quantilica-analytics>=0.11.0"]
|
|
30
|
+
lake = ["quantilica-analytics>=0.11.0", "pyarrow>=15.0.0"]
|
|
31
31
|
# `quantilica docs`: verificação da documentação dos dados dos fetchers.
|
|
32
32
|
docs = ["quantilica-core[docs]>=0.18.0"]
|
|
33
33
|
|
|
@@ -60,6 +60,7 @@ build-backend = "hatchling.build"
|
|
|
60
60
|
[tool.pytest.ini_options]
|
|
61
61
|
testpaths = ["tests"]
|
|
62
62
|
addopts = ["-p", "no:cacheprovider"]
|
|
63
|
+
markers = ["indice_real: o teste usa a consulta real de publicação no índice"]
|
|
63
64
|
|
|
64
65
|
[tool.ruff]
|
|
65
66
|
line-length = 88
|
|
@@ -13,12 +13,17 @@ import decimal
|
|
|
13
13
|
import json
|
|
14
14
|
import logging
|
|
15
15
|
import os
|
|
16
|
+
import re
|
|
16
17
|
import urllib.error
|
|
17
18
|
import urllib.request
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from dataclasses import dataclass, field
|
|
18
22
|
from pathlib import Path
|
|
19
23
|
from typing import Annotated, Any
|
|
20
24
|
|
|
21
25
|
import typer
|
|
26
|
+
from quantilica.core.registry import FetcherInfo, RegistryError
|
|
22
27
|
from rich.console import Console
|
|
23
28
|
from rich.table import Table
|
|
24
29
|
|
|
@@ -75,10 +80,143 @@ def _default_lake_dir() -> Path:
|
|
|
75
80
|
return Path("~/data/lake").expanduser().resolve()
|
|
76
81
|
|
|
77
82
|
|
|
83
|
+
#: Registro: id canônico, apelido (e id de lake) -> ``FetcherInfo``.
|
|
84
|
+
Registry = Mapping[str, FetcherInfo]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _registry_from_infos(
|
|
88
|
+
infos: list[tuple[FetcherInfo, tuple[str, ...]]],
|
|
89
|
+
) -> dict[str, FetcherInfo]:
|
|
90
|
+
"""Indexa os fetchers por id canônico, apelidos e ids extras (lake).
|
|
91
|
+
|
|
92
|
+
Id canônico e apelidos têm prioridade sobre os ids extras; entre dois
|
|
93
|
+
fetchers que disputam o mesmo nome, vale o primeiro.
|
|
94
|
+
"""
|
|
95
|
+
index: dict[str, FetcherInfo] = {}
|
|
96
|
+
for info, _extra in infos:
|
|
97
|
+
for name in info.names:
|
|
98
|
+
index.setdefault(name, info)
|
|
99
|
+
for info, extra in infos:
|
|
100
|
+
for name in extra:
|
|
101
|
+
index.setdefault(name, info)
|
|
102
|
+
return index
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_registry_file(path: Path) -> dict[str, FetcherInfo]:
|
|
106
|
+
"""Lê um ``registry.json`` (de ``registry export --json`` ou do índice)."""
|
|
107
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
108
|
+
entries = data.get("fetchers") if isinstance(data, dict) else None
|
|
109
|
+
if not isinstance(entries, list):
|
|
110
|
+
raise RegistryError(f"{path}: registro sem a lista 'fetchers'")
|
|
111
|
+
known = set(FetcherInfo.__dataclass_fields__)
|
|
112
|
+
infos: list[tuple[FetcherInfo, tuple[str, ...]]] = []
|
|
113
|
+
for entry in entries:
|
|
114
|
+
if entry.get("info_declared") is False:
|
|
115
|
+
continue
|
|
116
|
+
info = FetcherInfo.from_dict({k: v for k, v in entry.items() if k in known})
|
|
117
|
+
extra = tuple(
|
|
118
|
+
n for n in (entry.get("lake_source_id"), entry.get("source_id")) if n
|
|
119
|
+
)
|
|
120
|
+
infos.append((info, extra))
|
|
121
|
+
return _registry_from_infos(infos)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def load_registry(registry_file: Path | None = None) -> dict[str, FetcherInfo]:
|
|
125
|
+
"""Registro de fetchers: do arquivo dado ou dos entry points instalados.
|
|
126
|
+
|
|
127
|
+
Só entram fetchers que declaram ``info`` (o resto é desconhecido). Falha ao
|
|
128
|
+
carregar vira registro vazio com aviso: todas as fontes ficam sem metadados.
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
if registry_file is not None:
|
|
132
|
+
return load_registry_file(registry_file)
|
|
133
|
+
from quantilica.cli.registry import discover_fetchers
|
|
134
|
+
|
|
135
|
+
return _registry_from_infos(
|
|
136
|
+
[
|
|
137
|
+
(
|
|
138
|
+
d.info,
|
|
139
|
+
tuple(n for n in (d.lake_source_id, d.source_id) if n),
|
|
140
|
+
)
|
|
141
|
+
for d in discover_fetchers()
|
|
142
|
+
if d.info_declared
|
|
143
|
+
]
|
|
144
|
+
)
|
|
145
|
+
except Exception as exc:
|
|
146
|
+
logger.warning("Não foi possível carregar o registro de fetchers: %s", exc)
|
|
147
|
+
return {}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _count_rows(parquet_files: list[Path]) -> int:
|
|
151
|
+
"""Soma ``num_rows`` do rodapé de cada Parquet, sem ler os dados."""
|
|
152
|
+
if not parquet_files:
|
|
153
|
+
return 0
|
|
154
|
+
try:
|
|
155
|
+
import pyarrow.parquet as pq
|
|
156
|
+
except ImportError:
|
|
157
|
+
return 0
|
|
158
|
+
total = 0
|
|
159
|
+
for path in parquet_files:
|
|
160
|
+
try:
|
|
161
|
+
total += pq.ParquetFile(path).metadata.num_rows
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
logger.warning("Não foi possível contar linhas de %s: %s", path, exc)
|
|
164
|
+
return total
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass
|
|
168
|
+
class CatalogBuild:
|
|
169
|
+
"""Resultado da varredura: o payload e o que ficou de fora ou sem registro."""
|
|
170
|
+
|
|
171
|
+
payload: dict[str, Any]
|
|
172
|
+
#: Datasets omitidos por redistribuição restrita, por id canônico da fonte.
|
|
173
|
+
restricted: Counter[str] = field(default_factory=Counter)
|
|
174
|
+
#: ``source_id`` do lake que o registro não conhece (ficam fora do payload).
|
|
175
|
+
unknown: set[str] = field(default_factory=set)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _sigla(orgao: str | None) -> str | None:
|
|
179
|
+
"""Sigla do primeiro trecho entre parênteses do órgão (``... (ANAC)``)."""
|
|
180
|
+
m = re.search(r"\(([^()]+)\)", orgao or "")
|
|
181
|
+
return m.group(1).strip() or None if m else None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _source_object(
|
|
185
|
+
source_id: str, info: FetcherInfo | None, total_bytes: int
|
|
186
|
+
) -> dict[str, Any]:
|
|
187
|
+
"""Metadados da fonte: só o que o registro declara; o resto vai ``None``."""
|
|
188
|
+
return {
|
|
189
|
+
"id": source_id,
|
|
190
|
+
"nome": info.nome if info else None,
|
|
191
|
+
"sigla": _sigla(info.orgao) if info else None,
|
|
192
|
+
"orgao_emissor": info.orgao if info else None,
|
|
193
|
+
"dominio_tematico": info.dominio if info else None,
|
|
194
|
+
"licenca": info.licenca if info else None,
|
|
195
|
+
"homepage_url": info.homepage if info else None,
|
|
196
|
+
"cadencia": info.cadencia if info else None,
|
|
197
|
+
"redistribuicao": info.redistribuicao if info else None,
|
|
198
|
+
"tier_default": 2 if total_bytes > 0 else 1,
|
|
199
|
+
"ativo": True,
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _declared_text(desc_data: Mapping[str, Any], key: str) -> str | None:
|
|
204
|
+
value = desc_data.get(key)
|
|
205
|
+
return value.strip() if isinstance(value, str) and value.strip() else None
|
|
206
|
+
|
|
207
|
+
|
|
78
208
|
def _extract_dataset_metadata(
|
|
79
|
-
descriptor_path: Path,
|
|
209
|
+
descriptor_path: Path,
|
|
210
|
+
sample_size: int = 20,
|
|
211
|
+
lake_root: Path | None = None,
|
|
212
|
+
registry: Registry | None = None,
|
|
80
213
|
) -> dict[str, Any] | None:
|
|
81
|
-
"""Extrai metadados, colunas e amostras de um _dataset.json e seus Parquets.
|
|
214
|
+
"""Extrai metadados, colunas e amostras de um _dataset.json e seus Parquets.
|
|
215
|
+
|
|
216
|
+
O ``source_id`` do descritor é resolvido contra ``registry`` (apelido vira
|
|
217
|
+
id canônico). O resultado traz ``restrita`` (fonte de redistribuição
|
|
218
|
+
restrita) e ``conhecida`` (``source_id`` presente no registro).
|
|
219
|
+
"""
|
|
82
220
|
try:
|
|
83
221
|
desc_text = descriptor_path.read_text(encoding="utf-8")
|
|
84
222
|
desc_data = json.loads(desc_text)
|
|
@@ -86,15 +224,20 @@ def _extract_dataset_metadata(
|
|
|
86
224
|
logger.warning("Falha ao ler descritor %s: %s", descriptor_path, exc)
|
|
87
225
|
return None
|
|
88
226
|
|
|
89
|
-
|
|
227
|
+
raw_source_id = desc_data.get("source_id")
|
|
90
228
|
dataset_id = desc_data.get("dataset_id")
|
|
91
|
-
if not
|
|
229
|
+
if not raw_source_id or not dataset_id:
|
|
92
230
|
return None
|
|
93
231
|
|
|
232
|
+
info = (registry or {}).get(raw_source_id)
|
|
233
|
+
source_id = info.id if info else raw_source_id
|
|
234
|
+
restricted = info is not None and info.redistribuicao == "restrita"
|
|
235
|
+
|
|
94
236
|
dataset_dir = descriptor_path.parent
|
|
95
237
|
parquet_files = list(dataset_dir.rglob("*.parquet"))
|
|
96
238
|
total_arquivos = len(parquet_files)
|
|
97
239
|
total_bytes = sum(f.stat().st_size for f in parquet_files)
|
|
240
|
+
total_rows = _count_rows(parquet_files)
|
|
98
241
|
|
|
99
242
|
ultima_materializacao: str | None = None
|
|
100
243
|
if parquet_files:
|
|
@@ -172,42 +315,31 @@ def _extract_dataset_metadata(
|
|
|
172
315
|
exc,
|
|
173
316
|
)
|
|
174
317
|
|
|
175
|
-
source_obj =
|
|
176
|
-
"id": source_id,
|
|
177
|
-
"nome": source_id.upper(),
|
|
178
|
-
"sigla": source_id.upper()[:32],
|
|
179
|
-
"orgao_emissor": source_id.upper(),
|
|
180
|
-
"dominio_tematico": "Geral",
|
|
181
|
-
"licenca": "Open Data",
|
|
182
|
-
"homepage_url": None,
|
|
183
|
-
"tier_default": 2 if total_bytes > 0 else 1,
|
|
184
|
-
"ativo": True,
|
|
185
|
-
}
|
|
318
|
+
source_obj = _source_object(source_id, info, total_bytes)
|
|
186
319
|
|
|
187
320
|
if lake_root:
|
|
188
321
|
try:
|
|
189
|
-
lake_path =
|
|
322
|
+
lake_path = dataset_dir.relative_to(lake_root).as_posix()
|
|
190
323
|
except ValueError:
|
|
191
|
-
lake_path = f"{
|
|
324
|
+
lake_path = f"{raw_source_id}/{dataset_id}"
|
|
192
325
|
else:
|
|
193
326
|
try:
|
|
194
|
-
lake_path =
|
|
327
|
+
lake_path = dataset_dir.relative_to(dataset_dir.parent.parent).as_posix()
|
|
195
328
|
except ValueError:
|
|
196
|
-
lake_path = f"{
|
|
329
|
+
lake_path = f"{raw_source_id}/{dataset_id}"
|
|
197
330
|
|
|
198
331
|
dataset_obj = {
|
|
199
332
|
"id": full_id,
|
|
200
333
|
"source_id": source_id,
|
|
334
|
+
"fetcher_id": info.id if info else None,
|
|
201
335
|
"nome": alias.replace("-", " ").replace("_", " ").title(),
|
|
202
|
-
"descricao": (
|
|
203
|
-
|
|
204
|
-
),
|
|
205
|
-
"frequencia_temporal": "mensal",
|
|
206
|
-
"granularidade_espacial": "nacional",
|
|
336
|
+
"descricao": _declared_text(desc_data, "descricao"),
|
|
337
|
+
"frequencia_temporal": _declared_text(desc_data, "frequencia_temporal"),
|
|
338
|
+
"granularidade_espacial": _declared_text(desc_data, "granularidade_espacial"),
|
|
207
339
|
"lake_path": lake_path,
|
|
208
340
|
"manifest_sha256": None,
|
|
209
341
|
"ultima_materializacao_em": ultima_materializacao,
|
|
210
|
-
"total_linhas":
|
|
342
|
+
"total_linhas": total_rows,
|
|
211
343
|
"total_bytes": total_bytes,
|
|
212
344
|
"total_arquivos": total_arquivos,
|
|
213
345
|
"em_destaque": False,
|
|
@@ -224,54 +356,108 @@ def _extract_dataset_metadata(
|
|
|
224
356
|
"dataset": dataset_obj,
|
|
225
357
|
"columns": columns,
|
|
226
358
|
"sample": sample_obj,
|
|
359
|
+
"restrita": restricted,
|
|
360
|
+
"conhecida": info is not None,
|
|
227
361
|
}
|
|
228
362
|
|
|
229
363
|
|
|
230
|
-
def
|
|
364
|
+
def build_catalog(
|
|
231
365
|
lake_dir: Path,
|
|
232
366
|
source_filter: str | None = None,
|
|
233
367
|
sample_size: int = 20,
|
|
234
|
-
|
|
235
|
-
|
|
368
|
+
registry: Registry | None = None,
|
|
369
|
+
) -> CatalogBuild:
|
|
370
|
+
"""Varre o Lake e monta o payload, o que ficou de fora e o que é desconhecido.
|
|
371
|
+
|
|
372
|
+
``registry`` ausente carrega os fetchers instalados. Fontes de
|
|
373
|
+
redistribuição restrita não entram no payload.
|
|
374
|
+
"""
|
|
375
|
+
if registry is None:
|
|
376
|
+
registry = load_registry()
|
|
236
377
|
sources_dict: dict[str, dict[str, Any]] = {}
|
|
237
378
|
datasets_list: list[dict[str, Any]] = []
|
|
238
379
|
columns_list: list[dict[str, Any]] = []
|
|
239
380
|
samples_list: list[dict[str, Any]] = []
|
|
381
|
+
build = CatalogBuild(payload={})
|
|
240
382
|
|
|
241
383
|
if not lake_dir.is_dir():
|
|
242
384
|
logger.warning("Diretório do Lake %s não existe.", lake_dir)
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
385
|
+
build.payload = {"sources": [], "datasets": [], "columns": [], "samples": []}
|
|
386
|
+
return build
|
|
387
|
+
|
|
388
|
+
wanted = None
|
|
389
|
+
if source_filter:
|
|
390
|
+
found = registry.get(source_filter)
|
|
391
|
+
wanted = found.id if found else source_filter
|
|
249
392
|
|
|
393
|
+
seen_ids: set[str] = set()
|
|
250
394
|
# Busca todos os descritores _dataset.json
|
|
251
|
-
|
|
252
|
-
for desc_path in descriptor_paths:
|
|
395
|
+
for desc_path in sorted(lake_dir.rglob("_dataset.json")):
|
|
253
396
|
meta = _extract_dataset_metadata(
|
|
254
|
-
desc_path, sample_size=sample_size, lake_root=lake_dir
|
|
397
|
+
desc_path, sample_size=sample_size, lake_root=lake_dir, registry=registry
|
|
255
398
|
)
|
|
256
399
|
if not meta:
|
|
257
400
|
continue
|
|
258
401
|
|
|
259
402
|
src = meta["source"]
|
|
260
|
-
if
|
|
403
|
+
if wanted and src["id"] != wanted:
|
|
404
|
+
continue
|
|
405
|
+
if meta["restrita"]:
|
|
406
|
+
build.restricted[src["id"]] += 1
|
|
407
|
+
continue
|
|
408
|
+
if not meta["conhecida"]:
|
|
409
|
+
# Sem registro não há como saber se a fonte pode ser redistribuída
|
|
410
|
+
# (um fetcher restrito não instalado aqui cairia neste caso).
|
|
411
|
+
build.unknown.add(src["id"])
|
|
412
|
+
continue
|
|
413
|
+
if meta["dataset"]["id"] in seen_ids:
|
|
414
|
+
logger.warning(
|
|
415
|
+
"Dataset %s aparece mais de uma vez no Lake (%s); mantido o primeiro.",
|
|
416
|
+
meta["dataset"]["id"],
|
|
417
|
+
desc_path,
|
|
418
|
+
)
|
|
261
419
|
continue
|
|
420
|
+
seen_ids.add(meta["dataset"]["id"])
|
|
262
421
|
|
|
263
|
-
sources_dict
|
|
422
|
+
sources_dict.setdefault(src["id"], src)
|
|
264
423
|
datasets_list.append(meta["dataset"])
|
|
265
424
|
columns_list.extend(meta["columns"])
|
|
266
|
-
|
|
425
|
+
# Com --sample-size 0 a amostra não vai: enviar linhas vazias apagaria
|
|
426
|
+
# no portal a amostra de um envio anterior.
|
|
427
|
+
if sample_size > 0 and (
|
|
428
|
+
meta["sample"]["linhas_amostra"] or meta["sample"]["schema_arrow_json"]
|
|
429
|
+
):
|
|
267
430
|
samples_list.append(meta["sample"])
|
|
268
431
|
|
|
269
|
-
|
|
432
|
+
for source_id in sorted(build.unknown):
|
|
433
|
+
logger.warning(
|
|
434
|
+
"Fonte %r desconhecida do registro de fetchers: ficou de fora do envio.",
|
|
435
|
+
source_id,
|
|
436
|
+
)
|
|
437
|
+
if build.restricted:
|
|
438
|
+
logger.info(
|
|
439
|
+
"%d dataset(s) de fonte(s) de redistribuição restrita ficaram de fora: %s",
|
|
440
|
+
sum(build.restricted.values()),
|
|
441
|
+
", ".join(f"{k} ({v})" for k, v in sorted(build.restricted.items())),
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
build.payload = {
|
|
270
445
|
"sources": list(sources_dict.values()),
|
|
271
446
|
"datasets": datasets_list,
|
|
272
447
|
"columns": columns_list,
|
|
273
448
|
"samples": samples_list,
|
|
274
449
|
}
|
|
450
|
+
return build
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def extract_catalog_payload(
|
|
454
|
+
lake_dir: Path,
|
|
455
|
+
source_filter: str | None = None,
|
|
456
|
+
sample_size: int = 20,
|
|
457
|
+
registry: Registry | None = None,
|
|
458
|
+
) -> dict[str, Any]:
|
|
459
|
+
"""Varre o diretório do Lake e extrai o payload consolidado de metadados."""
|
|
460
|
+
return build_catalog(lake_dir, source_filter, sample_size, registry).payload
|
|
275
461
|
|
|
276
462
|
|
|
277
463
|
def send_catalog_payload(
|
|
@@ -336,11 +522,21 @@ def cmd_catalog_sync(
|
|
|
336
522
|
help="Filtrar por ID de fonte específica (ex: cvm, anp, b3).",
|
|
337
523
|
),
|
|
338
524
|
] = None,
|
|
525
|
+
registry_file: Annotated[
|
|
526
|
+
Path | None,
|
|
527
|
+
typer.Option(
|
|
528
|
+
"--registry",
|
|
529
|
+
help="registry.json a usar no lugar dos fetchers instalados "
|
|
530
|
+
"(saída de 'quantilica registry export --json').",
|
|
531
|
+
envvar="QUANTILICA_REGISTRY_FILE",
|
|
532
|
+
),
|
|
533
|
+
] = None,
|
|
339
534
|
sample_size: Annotated[
|
|
340
535
|
int,
|
|
341
536
|
typer.Option(
|
|
342
537
|
"--sample-size",
|
|
343
|
-
help="Número de linhas de amostra a extrair (máx 20)."
|
|
538
|
+
help="Número de linhas de amostra a extrair (máx 20). Com 0 a amostra "
|
|
539
|
+
"não é enviada e a do portal fica como está.",
|
|
344
540
|
),
|
|
345
541
|
] = 20,
|
|
346
542
|
dry_run: Annotated[
|
|
@@ -357,10 +553,33 @@ def cmd_catalog_sync(
|
|
|
357
553
|
f"[cyan]Varrendo Universal Hive Parquet Lake em:[/cyan] {target_lake}"
|
|
358
554
|
)
|
|
359
555
|
|
|
556
|
+
try:
|
|
557
|
+
import pyarrow.parquet # noqa: F401
|
|
558
|
+
except ImportError:
|
|
559
|
+
# Sem pyarrow o payload sai sem colunas, sem amostras e com zero
|
|
560
|
+
# linhas, e o envio apagaria esses dados no portal.
|
|
561
|
+
console.print(
|
|
562
|
+
"[red]pyarrow não está instalado: nada foi lido.[/red] "
|
|
563
|
+
"Instale o extra 'lake' (quantilica-cli[lake])."
|
|
564
|
+
)
|
|
565
|
+
raise typer.Exit(1) from None
|
|
566
|
+
|
|
360
567
|
safe_sample_size = max(0, min(sample_size, 20))
|
|
361
|
-
|
|
362
|
-
target_lake,
|
|
568
|
+
build = build_catalog(
|
|
569
|
+
target_lake,
|
|
570
|
+
source_filter=source,
|
|
571
|
+
sample_size=safe_sample_size,
|
|
572
|
+
registry=(registry := load_registry(registry_file)),
|
|
363
573
|
)
|
|
574
|
+
payload = build.payload
|
|
575
|
+
if not registry and not dry_run:
|
|
576
|
+
# Sem registro não dá para saber quais fontes são de redistribuição
|
|
577
|
+
# restrita: enviar assim poderia publicar o que não pode ser publicado.
|
|
578
|
+
console.print(
|
|
579
|
+
"[red]Registro de fetchers vazio: nada foi enviado.[/red] Instale os "
|
|
580
|
+
"fetchers nesta máquina ou informe --registry com um registry.json."
|
|
581
|
+
)
|
|
582
|
+
raise typer.Exit(1)
|
|
364
583
|
|
|
365
584
|
sources_count = len(payload.get("sources", []))
|
|
366
585
|
datasets_count = len(payload.get("datasets", []))
|
|
@@ -374,7 +593,22 @@ def cmd_catalog_sync(
|
|
|
374
593
|
table.add_row("Datasets Parquet", str(datasets_count))
|
|
375
594
|
table.add_row("Colunas e Chaves", str(columns_count))
|
|
376
595
|
table.add_row("Amostras de Dados", str(samples_count))
|
|
596
|
+
table.add_row(
|
|
597
|
+
"Deixados de fora (redistribuição restrita)",
|
|
598
|
+
str(sum(build.restricted.values())),
|
|
599
|
+
)
|
|
600
|
+
table.add_row("Fontes desconhecidas do registro", str(len(build.unknown)))
|
|
377
601
|
console.print(table)
|
|
602
|
+
if build.restricted:
|
|
603
|
+
console.print(
|
|
604
|
+
"[yellow]Fora do payload (restrita):[/yellow] "
|
|
605
|
+
+ ", ".join(f"{k} ({v})" for k, v in sorted(build.restricted.items()))
|
|
606
|
+
)
|
|
607
|
+
if build.unknown:
|
|
608
|
+
console.print(
|
|
609
|
+
"[yellow]Fora do payload (sem registro):[/yellow] "
|
|
610
|
+
+ ", ".join(sorted(build.unknown))
|
|
611
|
+
)
|
|
378
612
|
|
|
379
613
|
if dry_run:
|
|
380
614
|
console.print(
|
|
@@ -27,7 +27,8 @@ from quantilica.cli.sources import (
|
|
|
27
27
|
cmd_doctor,
|
|
28
28
|
cmd_install,
|
|
29
29
|
cmd_uninstall,
|
|
30
|
-
|
|
30
|
+
fetch_remote_sources_or_none,
|
|
31
|
+
local_sources,
|
|
31
32
|
)
|
|
32
33
|
|
|
33
34
|
FETCHER_GROUP = "quantilica.fetchers"
|
|
@@ -189,7 +190,13 @@ def list_sources(
|
|
|
189
190
|
plugins = _load_plugins(FETCHER_GROUP)
|
|
190
191
|
|
|
191
192
|
if remote:
|
|
192
|
-
remote_registry =
|
|
193
|
+
remote_registry = fetch_remote_sources_or_none()
|
|
194
|
+
if remote_registry is None:
|
|
195
|
+
console.print(
|
|
196
|
+
"[yellow]O índice não respondeu; a lista abaixo traz só os "
|
|
197
|
+
"apelidos conhecidos e os fetchers instalados.[/yellow]"
|
|
198
|
+
)
|
|
199
|
+
remote_registry = local_sources()
|
|
193
200
|
table = Table(title="Todas as fontes de dados conhecidas", show_header=True)
|
|
194
201
|
table.add_column("Fonte", style="cyan")
|
|
195
202
|
table.add_column("Pacote", style="magenta")
|