quantilica-cli 0.14.0__tar.gz → 0.15.1__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.14.0 → quantilica_cli-0.15.1}/CHANGELOG.md +32 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/PKG-INFO +4 -4
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/README.md +1 -1
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/pyproject.toml +4 -4
- quantilica_cli-0.15.1/src/quantilica/cli/catalog.py +424 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/cli.py +2 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/lake.py +29 -2
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/sdk.py +256 -75
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/sources.py +13 -0
- quantilica_cli-0.15.1/tests/conftest.py +17 -0
- quantilica_cli-0.15.1/tests/test_catalog_cli.py +179 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_lake_cli.py +23 -2
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_sdk.py +59 -1
- quantilica_cli-0.15.1/tests/test_sdk_backfill.py +102 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_sdk_force_probe.py +23 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.githooks/pre-commit +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.githooks/pre-push +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.github/workflows/public-hygiene.yml +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.github/workflows/publish.yml +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.github/workflows/test.yml +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/.gitignore +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/LICENSE +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/__init__.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/health.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/manifests.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/cli/ui.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/src/quantilica/py.typed +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/__init__.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/lake_build_fakes.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/lake_fixtures.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_health.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_manifests.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_package_hygiene.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_sdk_mes_string.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_sdk_onda_a2.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_sources.py +0 -0
- {quantilica_cli-0.14.0 → quantilica_cli-0.15.1}/tests/test_ui.py +0 -0
|
@@ -5,6 +5,38 @@ Todas as mudanças notáveis deste projeto serão documentadas neste arquivo.
|
|
|
5
5
|
O formato segue [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/),
|
|
6
6
|
e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
|
7
7
|
|
|
8
|
+
## [Não lançado]
|
|
9
|
+
|
|
10
|
+
## [0.15.1] - 2026-11-06
|
|
11
|
+
|
|
12
|
+
### Alterado
|
|
13
|
+
|
|
14
|
+
- `quantilica lake build --profile`: a ajuda passa a citar os perfis `batch` e `monolithic`; `96gb-batch` e `96gb-monolithic` continuam aceitos (depreciados no `quantilica-analytics`). O extra `lake` passa a exigir `quantilica-analytics>=0.11.0`.
|
|
15
|
+
|
|
16
|
+
## [0.15.0] - 2026-11-03
|
|
17
|
+
|
|
18
|
+
### Adicionado
|
|
19
|
+
|
|
20
|
+
- `quantilica catalog sync`: novo grupo `catalog` com o comando `sync`. Lê os descritores `_dataset.json` do lake, extrai esquemas Arrow e uma amostra de linhas (`--sample-size`, no máximo 20) e envia o catálogo à API do serviço indicado por `--portal-url` e `--api-key`. `--source` limita a uma fonte, `--lake-dir` aponta o lake e `--dry-run` só mostra o conteúdo que seria enviado.
|
|
21
|
+
- `quantilica lake build --profile` e `--dataset`: `--profile` aplica um perfil de memória (`96gb-batch` ou `96gb-monolithic`) e `--dataset` limita a conversão aos datasets pedidos. Exigem o extra `lake` com `quantilica-analytics>=0.9.0`.
|
|
22
|
+
- SDK dos coletores: `FetcherApp.command_backfill()` registra um subcomando `backfill` de carga histórica com ponto de retomada em `<saída>/.backfill/<nome>.json` (`--resume`/`--restart`, e as opções `--rateio` e `--regional` repassadas à fonte que as declara).
|
|
23
|
+
- SDK dos coletores: `FetcherApp(freshness_policy=...)` aplica a política de frescura (`quantilica.core.sync.FreshnessPolicy`). Com `remote_only` não há sonda `HEAD` e o download ativa a deduplicação por SHA-256 do `quantilica-core`.
|
|
24
|
+
- SDK dos coletores: o download infere o formato esperado pela extensão (`expected_format`, também aceito em `download_entry`) e repassa a conferência de assinatura do conteúdo ao `quantilica-core` quando o cliente de download a suporta.
|
|
25
|
+
- Fontes novas no mapa de comandos: `antt`, `bcb-microdados`, `capes`, `ipeadata`, `loterias`, `ons`, `pgfn`, `infosiga`, `sigtap` (também `datasus-sigtap`) e `transparencia-sp`.
|
|
26
|
+
|
|
27
|
+
### Alterado
|
|
28
|
+
|
|
29
|
+
- Exige `quantilica-core>=0.16.0`; o extra `lake` exige `quantilica-analytics>=0.9.0`.
|
|
30
|
+
- O caminho de destino dos arquivos baixados e o `dataset_id` gravado no manifesto passam a vir do `quantilica-core` (`path_for_entry`), os mesmos usados pelos coletores.
|
|
31
|
+
- `quantilica lake build`: a ajuda descreve a retomada como ela funciona a partir do `quantilica-analytics` 0.9.0 (só a execução interrompida é retomada; `--retry-errors` refaz as tarefas que falharam na execução mais recente).
|
|
32
|
+
|
|
33
|
+
### Corrigido
|
|
34
|
+
|
|
35
|
+
- `make_resolve_groups` aceita alias com valor `str` (por exemplo `all` para `exp`). Antes o valor era expandido caractere a caractere e a sincronização padrão ou completa falhava com "Grupo desconhecido".
|
|
36
|
+
- Com `freshness_policy=remote_only`, a deduplicação por SHA-256 só é repassada ao cliente de download que a aceita; antes o `FtpClient` recebia o argumento e a sincronização falhava com `TypeError`.
|
|
37
|
+
- `catalog sync`: os tipos JSON que não são primitivos são normalizados, os grupos de linhas são dimensionados com segurança e os caminhos do lake são resolvidos de forma robusta.
|
|
38
|
+
- Os testes de `--help` do `lake` não dependem mais de cor forçada no CI.
|
|
39
|
+
|
|
8
40
|
## [0.14.0] - 2026-10-30
|
|
9
41
|
|
|
10
42
|
### Adicionado
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: quantilica-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.15.1
|
|
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
|
|
@@ -16,11 +16,11 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Classifier: Typing :: Typed
|
|
18
18
|
Requires-Python: >=3.12
|
|
19
|
-
Requires-Dist: quantilica-core>=0.
|
|
19
|
+
Requires-Dist: quantilica-core>=0.16.0
|
|
20
20
|
Requires-Dist: rich>=13.0.0
|
|
21
21
|
Requires-Dist: typer>=0.15.0
|
|
22
22
|
Provides-Extra: lake
|
|
23
|
-
Requires-Dist: quantilica-analytics>=0.
|
|
23
|
+
Requires-Dist: quantilica-analytics>=0.11.0; extra == 'lake'
|
|
24
24
|
Description-Content-Type: text/markdown
|
|
25
25
|
|
|
26
26
|
# quantilica-cli
|
|
@@ -60,7 +60,7 @@ bruto local → `select` → `build` → `audit`:
|
|
|
60
60
|
# 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
|
|
61
61
|
quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
|
|
62
62
|
|
|
63
|
-
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma
|
|
63
|
+
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma uma execução interrompida
|
|
64
64
|
quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
|
|
65
65
|
|
|
66
66
|
# 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
|
|
@@ -35,7 +35,7 @@ bruto local → `select` → `build` → `audit`:
|
|
|
35
35
|
# 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
|
|
36
36
|
quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
|
|
37
37
|
|
|
38
|
-
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma
|
|
38
|
+
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma uma execução interrompida
|
|
39
39
|
quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
|
|
40
40
|
|
|
41
41
|
# 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "quantilica-cli"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.15.1"
|
|
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" }]
|
|
@@ -20,20 +20,20 @@ classifiers = [
|
|
|
20
20
|
"Programming Language :: Python :: 3.13",
|
|
21
21
|
]
|
|
22
22
|
dependencies = [
|
|
23
|
-
"quantilica-core>=0.
|
|
23
|
+
"quantilica-core>=0.16.0",
|
|
24
24
|
"rich>=13.0.0",
|
|
25
25
|
"typer>=0.15.0",
|
|
26
26
|
]
|
|
27
27
|
|
|
28
28
|
[project.optional-dependencies]
|
|
29
29
|
# Motor de `quantilica lake build` e `quantilica lake audit`.
|
|
30
|
-
lake = ["quantilica-analytics>=0.
|
|
30
|
+
lake = ["quantilica-analytics>=0.11.0"]
|
|
31
31
|
|
|
32
32
|
[project.scripts]
|
|
33
33
|
quantilica = "quantilica.cli.cli:main"
|
|
34
34
|
|
|
35
35
|
[dependency-groups]
|
|
36
|
-
dev = ["ruff>=0.9.0", "pytest>=8.0.0"]
|
|
36
|
+
dev = ["ruff>=0.9.0", "pytest>=8.0.0", "pyarrow>=15.0.0"]
|
|
37
37
|
|
|
38
38
|
# Os fetchers são instalados independentemente pelo usuário — quantilica-cli
|
|
39
39
|
# os descobre via entry points (grupo "quantilica.fetchers") sem dependência direta.
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""Comandos `quantilica catalog` — sincronização com o Portal (Subplano 3).
|
|
2
|
+
|
|
3
|
+
Varre o Universal Hive Parquet Lake local (QUANTILICA_LAKE_DIR ou lake_root),
|
|
4
|
+
lê descritores `_dataset.json`, inspeciona schemas Arrow e amostras (até 20 linhas),
|
|
5
|
+
monta o payload consolidado e dispara para a API do Portal via:
|
|
6
|
+
POST /api/v2/admin/catalog/sync (com autenticação via Bearer token).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import datetime as dt
|
|
12
|
+
import decimal
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Annotated, Any
|
|
20
|
+
|
|
21
|
+
import typer
|
|
22
|
+
from rich.console import Console
|
|
23
|
+
from rich.table import Table
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("quantilica.cli.catalog")
|
|
26
|
+
console = Console()
|
|
27
|
+
err_console = Console(stderr=True)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _sanitize_value(val: Any) -> Any:
|
|
31
|
+
"""Converte valores Python/Arrow em tipos primitivos compatíveis com JSON."""
|
|
32
|
+
if val is None:
|
|
33
|
+
return None
|
|
34
|
+
if isinstance(val, bool):
|
|
35
|
+
return val
|
|
36
|
+
if isinstance(val, (int, float, str)):
|
|
37
|
+
return val
|
|
38
|
+
if isinstance(val, decimal.Decimal):
|
|
39
|
+
return float(val)
|
|
40
|
+
if hasattr(val, "isoformat"):
|
|
41
|
+
return val.isoformat()
|
|
42
|
+
if isinstance(val, bytes):
|
|
43
|
+
try:
|
|
44
|
+
return val.decode("utf-8")
|
|
45
|
+
except UnicodeDecodeError:
|
|
46
|
+
return val.hex()
|
|
47
|
+
if isinstance(val, dict):
|
|
48
|
+
return {str(k): _sanitize_value(v) for k, v in val.items()}
|
|
49
|
+
if isinstance(val, (list, tuple, set)):
|
|
50
|
+
return [_sanitize_value(x) for x in val]
|
|
51
|
+
if hasattr(val, "as_py"):
|
|
52
|
+
return _sanitize_value(val.as_py())
|
|
53
|
+
return str(val)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
app = typer.Typer(
|
|
57
|
+
help="Gerenciar e sincronizar o catálogo de dados do ecossistema com o Portal.",
|
|
58
|
+
no_args_is_help=True,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _default_lake_dir() -> Path:
|
|
63
|
+
"""Obtém o diretório padrão do Lake a partir do SDK ou ambiente."""
|
|
64
|
+
try:
|
|
65
|
+
from quantilica.core.lake import lake_root
|
|
66
|
+
|
|
67
|
+
return lake_root()
|
|
68
|
+
except Exception:
|
|
69
|
+
env = os.environ.get("QUANTILICA_LAKE_DIR") or os.environ.get(
|
|
70
|
+
"QUANTILICA_DATA_DIR"
|
|
71
|
+
)
|
|
72
|
+
if env:
|
|
73
|
+
p = Path(env).expanduser().resolve()
|
|
74
|
+
return p / "lake" if (p / "lake").is_dir() else p
|
|
75
|
+
return Path("~/data/lake").expanduser().resolve()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _extract_dataset_metadata(
|
|
79
|
+
descriptor_path: Path, sample_size: int = 20, lake_root: Path | None = None
|
|
80
|
+
) -> dict[str, Any] | None:
|
|
81
|
+
"""Extrai metadados, colunas e amostras de um _dataset.json e seus Parquets."""
|
|
82
|
+
try:
|
|
83
|
+
desc_text = descriptor_path.read_text(encoding="utf-8")
|
|
84
|
+
desc_data = json.loads(desc_text)
|
|
85
|
+
except Exception as exc:
|
|
86
|
+
logger.warning("Falha ao ler descritor %s: %s", descriptor_path, exc)
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
source_id = desc_data.get("source_id")
|
|
90
|
+
dataset_id = desc_data.get("dataset_id")
|
|
91
|
+
if not source_id or not dataset_id:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
dataset_dir = descriptor_path.parent
|
|
95
|
+
parquet_files = list(dataset_dir.rglob("*.parquet"))
|
|
96
|
+
total_arquivos = len(parquet_files)
|
|
97
|
+
total_bytes = sum(f.stat().st_size for f in parquet_files)
|
|
98
|
+
|
|
99
|
+
ultima_materializacao: str | None = None
|
|
100
|
+
if parquet_files:
|
|
101
|
+
mtime = max(f.stat().st_mtime for f in parquet_files)
|
|
102
|
+
ultima_materializacao = dt.datetime.fromtimestamp(mtime, tz=dt.UTC).isoformat()
|
|
103
|
+
|
|
104
|
+
full_id = f"{source_id}/{dataset_id}"
|
|
105
|
+
alias = desc_data.get("alias", dataset_id)
|
|
106
|
+
|
|
107
|
+
# Colunas
|
|
108
|
+
columns: list[dict[str, Any]] = []
|
|
109
|
+
order = 0
|
|
110
|
+
|
|
111
|
+
partition_keys = desc_data.get("partition_keys", []) or []
|
|
112
|
+
partition_types = desc_data.get("partition_types", {}) or {}
|
|
113
|
+
for p_key in partition_keys:
|
|
114
|
+
columns.append(
|
|
115
|
+
{
|
|
116
|
+
"dataset_id": full_id,
|
|
117
|
+
"nome": p_key,
|
|
118
|
+
"dtype_arrow": partition_types.get(p_key, "Utf8"),
|
|
119
|
+
"eh_particao_hive": True,
|
|
120
|
+
"eh_chave_cruzamento": False,
|
|
121
|
+
"percentual_nulos": 0.0,
|
|
122
|
+
"descricao": f"Chave de partição Hive ({p_key})",
|
|
123
|
+
"display_order": order,
|
|
124
|
+
}
|
|
125
|
+
)
|
|
126
|
+
order += 1
|
|
127
|
+
|
|
128
|
+
sample_rows: list[dict[str, Any]] = []
|
|
129
|
+
schema_arrow_json: dict[str, Any] = {}
|
|
130
|
+
|
|
131
|
+
if parquet_files:
|
|
132
|
+
first_parquet = parquet_files[0]
|
|
133
|
+
try:
|
|
134
|
+
import pyarrow.parquet as pq
|
|
135
|
+
|
|
136
|
+
pf = pq.ParquetFile(first_parquet)
|
|
137
|
+
schema = pf.schema_arrow
|
|
138
|
+
schema_arrow_json = {f.name: str(f.type) for f in schema}
|
|
139
|
+
|
|
140
|
+
for field in schema:
|
|
141
|
+
if field.name not in partition_keys:
|
|
142
|
+
columns.append(
|
|
143
|
+
{
|
|
144
|
+
"dataset_id": full_id,
|
|
145
|
+
"nome": field.name,
|
|
146
|
+
"dtype_arrow": str(field.type),
|
|
147
|
+
"eh_particao_hive": False,
|
|
148
|
+
"eh_chave_cruzamento": False,
|
|
149
|
+
"percentual_nulos": 0.0,
|
|
150
|
+
"descricao": None,
|
|
151
|
+
"display_order": order,
|
|
152
|
+
}
|
|
153
|
+
)
|
|
154
|
+
order += 1
|
|
155
|
+
|
|
156
|
+
if sample_size > 0 and pf.num_row_groups > 0:
|
|
157
|
+
table = pf.read_row_group(0)
|
|
158
|
+
if table.num_rows > sample_size:
|
|
159
|
+
table = table.slice(0, sample_size)
|
|
160
|
+
# Serialização segura para JSON
|
|
161
|
+
pydict = table.to_pydict()
|
|
162
|
+
keys = list(pydict.keys())
|
|
163
|
+
for idx in range(table.num_rows):
|
|
164
|
+
row: dict[str, Any] = {}
|
|
165
|
+
for k in keys:
|
|
166
|
+
row[k] = _sanitize_value(pydict[k][idx])
|
|
167
|
+
sample_rows.append(row)
|
|
168
|
+
except Exception as exc:
|
|
169
|
+
logger.debug(
|
|
170
|
+
"Não foi possível inspecionar Parquet com pyarrow (%s): %s",
|
|
171
|
+
first_parquet,
|
|
172
|
+
exc,
|
|
173
|
+
)
|
|
174
|
+
|
|
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
|
+
}
|
|
186
|
+
|
|
187
|
+
if lake_root:
|
|
188
|
+
try:
|
|
189
|
+
lake_path = str(dataset_dir.relative_to(lake_root))
|
|
190
|
+
except ValueError:
|
|
191
|
+
lake_path = f"{source_id}/{dataset_id}"
|
|
192
|
+
else:
|
|
193
|
+
try:
|
|
194
|
+
lake_path = str(dataset_dir.relative_to(dataset_dir.parent.parent))
|
|
195
|
+
except ValueError:
|
|
196
|
+
lake_path = f"{source_id}/{dataset_id}"
|
|
197
|
+
|
|
198
|
+
dataset_obj = {
|
|
199
|
+
"id": full_id,
|
|
200
|
+
"source_id": source_id,
|
|
201
|
+
"nome": alias.replace("-", " ").replace("_", " ").title(),
|
|
202
|
+
"descricao": (
|
|
203
|
+
f"Dataset {alias} extraído e materializado no Universal Hive Parquet Lake."
|
|
204
|
+
),
|
|
205
|
+
"frequencia_temporal": "mensal",
|
|
206
|
+
"granularidade_espacial": "nacional",
|
|
207
|
+
"lake_path": lake_path,
|
|
208
|
+
"manifest_sha256": None,
|
|
209
|
+
"ultima_materializacao_em": ultima_materializacao,
|
|
210
|
+
"total_linhas": 0,
|
|
211
|
+
"total_bytes": total_bytes,
|
|
212
|
+
"total_arquivos": total_arquivos,
|
|
213
|
+
"em_destaque": False,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
sample_obj = {
|
|
217
|
+
"dataset_id": full_id,
|
|
218
|
+
"linhas_amostra": sample_rows,
|
|
219
|
+
"schema_arrow_json": schema_arrow_json,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
"source": source_obj,
|
|
224
|
+
"dataset": dataset_obj,
|
|
225
|
+
"columns": columns,
|
|
226
|
+
"sample": sample_obj,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def extract_catalog_payload(
|
|
231
|
+
lake_dir: Path,
|
|
232
|
+
source_filter: str | None = None,
|
|
233
|
+
sample_size: int = 20,
|
|
234
|
+
) -> dict[str, Any]:
|
|
235
|
+
"""Varre o diretório do Lake e extrai o payload consolidado de metadados."""
|
|
236
|
+
sources_dict: dict[str, dict[str, Any]] = {}
|
|
237
|
+
datasets_list: list[dict[str, Any]] = []
|
|
238
|
+
columns_list: list[dict[str, Any]] = []
|
|
239
|
+
samples_list: list[dict[str, Any]] = []
|
|
240
|
+
|
|
241
|
+
if not lake_dir.is_dir():
|
|
242
|
+
logger.warning("Diretório do Lake %s não existe.", lake_dir)
|
|
243
|
+
return {
|
|
244
|
+
"sources": [],
|
|
245
|
+
"datasets": [],
|
|
246
|
+
"columns": [],
|
|
247
|
+
"samples": [],
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
# Busca todos os descritores _dataset.json
|
|
251
|
+
descriptor_paths = sorted(lake_dir.rglob("_dataset.json"))
|
|
252
|
+
for desc_path in descriptor_paths:
|
|
253
|
+
meta = _extract_dataset_metadata(
|
|
254
|
+
desc_path, sample_size=sample_size, lake_root=lake_dir
|
|
255
|
+
)
|
|
256
|
+
if not meta:
|
|
257
|
+
continue
|
|
258
|
+
|
|
259
|
+
src = meta["source"]
|
|
260
|
+
if source_filter and src["id"] != source_filter:
|
|
261
|
+
continue
|
|
262
|
+
|
|
263
|
+
sources_dict[src["id"]] = src
|
|
264
|
+
datasets_list.append(meta["dataset"])
|
|
265
|
+
columns_list.extend(meta["columns"])
|
|
266
|
+
if meta["sample"]["linhas_amostra"] or meta["sample"]["schema_arrow_json"]:
|
|
267
|
+
samples_list.append(meta["sample"])
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
"sources": list(sources_dict.values()),
|
|
271
|
+
"datasets": datasets_list,
|
|
272
|
+
"columns": columns_list,
|
|
273
|
+
"samples": samples_list,
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def send_catalog_payload(
|
|
278
|
+
portal_url: str,
|
|
279
|
+
payload: dict[str, Any],
|
|
280
|
+
api_key: str | None = None,
|
|
281
|
+
) -> dict[str, Any]:
|
|
282
|
+
"""Envia o payload via HTTP POST para o endpoint de sincronização do Portal."""
|
|
283
|
+
endpoints = [
|
|
284
|
+
f"{portal_url.rstrip('/')}/api/v2/admin/catalog/sync",
|
|
285
|
+
f"{portal_url.rstrip('/')}/api/v2/catalog/sync",
|
|
286
|
+
]
|
|
287
|
+
|
|
288
|
+
body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
|
|
289
|
+
headers = {
|
|
290
|
+
"Content-Type": "application/json",
|
|
291
|
+
"Accept": "application/json",
|
|
292
|
+
}
|
|
293
|
+
if api_key:
|
|
294
|
+
headers["Authorization"] = f"Bearer {api_key.strip()}"
|
|
295
|
+
|
|
296
|
+
last_error: Exception | None = None
|
|
297
|
+
|
|
298
|
+
for url in endpoints:
|
|
299
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
300
|
+
try:
|
|
301
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
302
|
+
resp_text = resp.read().decode("utf-8")
|
|
303
|
+
return json.loads(resp_text)
|
|
304
|
+
except urllib.error.HTTPError as exc:
|
|
305
|
+
# Se for 404 tenta o próximo endpoint
|
|
306
|
+
if exc.code == 404 and url != endpoints[-1]:
|
|
307
|
+
continue
|
|
308
|
+
err_body = exc.read().decode("utf-8", errors="replace")
|
|
309
|
+
raise RuntimeError(
|
|
310
|
+
f"Falha na sincronização HTTP {exc.code} em {url}: {err_body}"
|
|
311
|
+
) from exc
|
|
312
|
+
except Exception as exc:
|
|
313
|
+
last_error = exc
|
|
314
|
+
if url != endpoints[-1]:
|
|
315
|
+
continue
|
|
316
|
+
raise RuntimeError(f"Erro de conexão com o portal em {url}: {exc}") from exc
|
|
317
|
+
|
|
318
|
+
if last_error:
|
|
319
|
+
raise last_error
|
|
320
|
+
return {}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@app.command("sync")
|
|
324
|
+
def cmd_catalog_sync(
|
|
325
|
+
lake_dir: Annotated[
|
|
326
|
+
Path | None,
|
|
327
|
+
typer.Option(
|
|
328
|
+
"--lake-dir",
|
|
329
|
+
help="Diretório raiz do Universal Hive Parquet Lake.",
|
|
330
|
+
),
|
|
331
|
+
] = None,
|
|
332
|
+
portal_url: Annotated[
|
|
333
|
+
str,
|
|
334
|
+
typer.Option(
|
|
335
|
+
"--portal-url",
|
|
336
|
+
help="URL base do Quantilica Portal.",
|
|
337
|
+
envvar="QUANTILICA_PORTAL_URL",
|
|
338
|
+
),
|
|
339
|
+
] = "http://localhost:8000",
|
|
340
|
+
api_key: Annotated[
|
|
341
|
+
str | None,
|
|
342
|
+
typer.Option(
|
|
343
|
+
"--api-key",
|
|
344
|
+
"--token",
|
|
345
|
+
help="Chave de API administrativa para autenticação.",
|
|
346
|
+
envvar="QUANTILICA_ADMIN_API_KEY",
|
|
347
|
+
),
|
|
348
|
+
] = None,
|
|
349
|
+
source: Annotated[
|
|
350
|
+
str | None,
|
|
351
|
+
typer.Option(
|
|
352
|
+
"--source",
|
|
353
|
+
"-s",
|
|
354
|
+
help="Filtrar por ID de fonte específica (ex: cvm, anp, b3).",
|
|
355
|
+
),
|
|
356
|
+
] = None,
|
|
357
|
+
sample_size: Annotated[
|
|
358
|
+
int,
|
|
359
|
+
typer.Option(
|
|
360
|
+
"--sample-size",
|
|
361
|
+
help="Número de linhas de amostra a extrair (máx 20).",
|
|
362
|
+
),
|
|
363
|
+
] = 20,
|
|
364
|
+
dry_run: Annotated[
|
|
365
|
+
bool,
|
|
366
|
+
typer.Option(
|
|
367
|
+
"--dry-run",
|
|
368
|
+
help="Exibe o payload JSON extraído sem enviar HTTP para o Portal.",
|
|
369
|
+
),
|
|
370
|
+
] = False,
|
|
371
|
+
) -> None:
|
|
372
|
+
"""Sincroniza os metadados do Universal Hive Parquet Lake com o Portal."""
|
|
373
|
+
target_lake = (lake_dir or _default_lake_dir()).expanduser().resolve()
|
|
374
|
+
console.print(
|
|
375
|
+
f"[cyan]Varrendo Universal Hive Parquet Lake em:[/cyan] {target_lake}"
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
safe_sample_size = max(0, min(sample_size, 20))
|
|
379
|
+
payload = extract_catalog_payload(
|
|
380
|
+
target_lake, source_filter=source, sample_size=safe_sample_size
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
sources_count = len(payload.get("sources", []))
|
|
384
|
+
datasets_count = len(payload.get("datasets", []))
|
|
385
|
+
columns_count = len(payload.get("columns", []))
|
|
386
|
+
samples_count = len(payload.get("samples", []))
|
|
387
|
+
|
|
388
|
+
table = Table(title="Metadados Extraídos para Sincronização", show_header=True)
|
|
389
|
+
table.add_column("Entidade", style="cyan")
|
|
390
|
+
table.add_column("Quantidade", style="green", justify="right")
|
|
391
|
+
table.add_row("Fontes Oficiais", str(sources_count))
|
|
392
|
+
table.add_row("Datasets Parquet", str(datasets_count))
|
|
393
|
+
table.add_row("Colunas e Chaves", str(columns_count))
|
|
394
|
+
table.add_row("Amostras de Dados", str(samples_count))
|
|
395
|
+
console.print(table)
|
|
396
|
+
|
|
397
|
+
if dry_run:
|
|
398
|
+
console.print(
|
|
399
|
+
"[yellow]Modo --dry-run ativo:[/yellow] nenhum dado enviado para o portal."
|
|
400
|
+
)
|
|
401
|
+
console.print_json(
|
|
402
|
+
json.dumps(payload, ensure_ascii=False, indent=2, default=str)
|
|
403
|
+
)
|
|
404
|
+
return
|
|
405
|
+
|
|
406
|
+
if datasets_count == 0:
|
|
407
|
+
console.print(
|
|
408
|
+
"[yellow]Nenhum descritor _dataset.json encontrado.[/yellow] "
|
|
409
|
+
"Execute 'quantilica lake build' para materializar datasets."
|
|
410
|
+
)
|
|
411
|
+
return
|
|
412
|
+
|
|
413
|
+
console.print(
|
|
414
|
+
f"[cyan]Enviando payload ({sources_count} fontes, "
|
|
415
|
+
f"{datasets_count} datasets)...[/cyan]"
|
|
416
|
+
)
|
|
417
|
+
try:
|
|
418
|
+
res = send_catalog_payload(portal_url, payload, api_key=api_key)
|
|
419
|
+
console.print(
|
|
420
|
+
f"[green]✓ Catálogo sincronizado com sucesso![/green] Resposta: {res}"
|
|
421
|
+
)
|
|
422
|
+
except Exception as exc:
|
|
423
|
+
err_console.print(f"[red]Erro ao sincronizar catálogo:[/red] {exc}")
|
|
424
|
+
raise typer.Exit(code=1) from exc
|
|
@@ -13,6 +13,7 @@ from rich.logging import RichHandler
|
|
|
13
13
|
from rich.table import Table
|
|
14
14
|
|
|
15
15
|
from quantilica.cli import __version__
|
|
16
|
+
from quantilica.cli.catalog import app as catalog_app
|
|
16
17
|
from quantilica.cli.health import cmd_health
|
|
17
18
|
from quantilica.cli.lake import app as lake_app
|
|
18
19
|
from quantilica.cli.manifests import app as manifests_app
|
|
@@ -34,6 +35,7 @@ app = typer.Typer(
|
|
|
34
35
|
help="Quantilica — ferramentas de dados abertos brasileiros.",
|
|
35
36
|
no_args_is_help=True,
|
|
36
37
|
)
|
|
38
|
+
app.add_typer(catalog_app, name="catalog")
|
|
37
39
|
app.add_typer(lake_app, name="lake")
|
|
38
40
|
app.add_typer(manifests_app, name="manifests")
|
|
39
41
|
app.add_typer(sources_app, name="sources")
|
|
@@ -206,6 +206,25 @@ def build(
|
|
|
206
206
|
"as que têm conversor)",
|
|
207
207
|
),
|
|
208
208
|
] = None,
|
|
209
|
+
dataset: Annotated[
|
|
210
|
+
str | None,
|
|
211
|
+
typer.Option(
|
|
212
|
+
"--dataset",
|
|
213
|
+
"--datasets",
|
|
214
|
+
help="Datasets a construir, separados por vírgula (padrão: todos da fonte)",
|
|
215
|
+
),
|
|
216
|
+
] = None,
|
|
217
|
+
profile: Annotated[
|
|
218
|
+
str | None,
|
|
219
|
+
typer.Option(
|
|
220
|
+
"--profile",
|
|
221
|
+
help=(
|
|
222
|
+
"Perfil de recursos: 'batch' (6 workers x 14GB) ou "
|
|
223
|
+
"'monolithic' (1 worker x 64GB). Os nomes antigos "
|
|
224
|
+
"'96gb-batch' e '96gb-monolithic' ainda são aceitos"
|
|
225
|
+
),
|
|
226
|
+
),
|
|
227
|
+
] = None,
|
|
209
228
|
workers: Annotated[
|
|
210
229
|
int | None,
|
|
211
230
|
typer.Option("--workers", min=1, help="Processos em paralelo"),
|
|
@@ -233,7 +252,8 @@ def build(
|
|
|
233
252
|
retry_errors: Annotated[
|
|
234
253
|
bool,
|
|
235
254
|
typer.Option(
|
|
236
|
-
"--retry-errors",
|
|
255
|
+
"--retry-errors",
|
|
256
|
+
help="Refaz só as tarefas que falharam na execução mais recente",
|
|
237
257
|
),
|
|
238
258
|
] = False,
|
|
239
259
|
no_disk_check: Annotated[
|
|
@@ -249,7 +269,7 @@ def build(
|
|
|
249
269
|
),
|
|
250
270
|
] = False,
|
|
251
271
|
) -> None:
|
|
252
|
-
"""Converte a visão vigente em Parquet; retoma
|
|
272
|
+
"""Converte a visão vigente em Parquet; retoma uma execução interrompida."""
|
|
253
273
|
try:
|
|
254
274
|
from quantilica.analytics.lake_build import (
|
|
255
275
|
InsufficientDiskError,
|
|
@@ -260,12 +280,19 @@ def build(
|
|
|
260
280
|
raise _missing_analytics("build", exc) from None
|
|
261
281
|
|
|
262
282
|
wanted = _split_sources(sources)
|
|
283
|
+
wanted_datasets = (
|
|
284
|
+
[part.strip() for part in dataset.split(",") if part.strip()]
|
|
285
|
+
if dataset
|
|
286
|
+
else None
|
|
287
|
+
)
|
|
263
288
|
try:
|
|
264
289
|
with _log_to_stderr():
|
|
265
290
|
summary = lake_build(
|
|
266
291
|
input,
|
|
267
292
|
lake,
|
|
268
293
|
sources=wanted,
|
|
294
|
+
datasets=wanted_datasets,
|
|
295
|
+
profile=profile,
|
|
269
296
|
workers=workers,
|
|
270
297
|
memory=memory,
|
|
271
298
|
threads=threads,
|