quantilica-cli 0.13.0__tar.gz → 0.15.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.13.0 → quantilica_cli-0.15.0}/.github/workflows/test.yml +7 -2
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/CHANGELOG.md +32 -0
- quantilica_cli-0.15.0/PKG-INFO +83 -0
- quantilica_cli-0.15.0/README.md +58 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/pyproject.toml +6 -2
- quantilica_cli-0.15.0/src/quantilica/cli/catalog.py +424 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/cli.py +4 -0
- quantilica_cli-0.15.0/src/quantilica/cli/lake.py +444 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/sdk.py +256 -75
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/sources.py +13 -0
- quantilica_cli-0.15.0/tests/conftest.py +17 -0
- quantilica_cli-0.15.0/tests/lake_build_fakes.py +95 -0
- quantilica_cli-0.15.0/tests/lake_fixtures.py +101 -0
- quantilica_cli-0.15.0/tests/test_catalog_cli.py +179 -0
- quantilica_cli-0.15.0/tests/test_lake_cli.py +492 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_sdk.py +59 -1
- quantilica_cli-0.15.0/tests/test_sdk_backfill.py +102 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_sdk_force_probe.py +23 -0
- quantilica_cli-0.13.0/PKG-INFO +0 -49
- quantilica_cli-0.13.0/README.md +0 -26
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/.githooks/pre-commit +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/.githooks/pre-push +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/.github/workflows/public-hygiene.yml +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/.github/workflows/publish.yml +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/.gitignore +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/LICENSE +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/__init__.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/health.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/manifests.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/cli/ui.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/src/quantilica/py.typed +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/__init__.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_health.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_manifests.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_package_hygiene.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_sdk_mes_string.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_sdk_onda_a2.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_sources.py +0 -0
- {quantilica_cli-0.13.0 → quantilica_cli-0.15.0}/tests/test_ui.py +0 -0
|
@@ -9,12 +9,16 @@ on:
|
|
|
9
9
|
|
|
10
10
|
jobs:
|
|
11
11
|
test:
|
|
12
|
-
name: Test (Python ${{ matrix.python-version }})
|
|
13
|
-
runs-on:
|
|
12
|
+
name: Test (${{ matrix.os }}, Python ${{ matrix.python-version }})
|
|
13
|
+
runs-on: ${{ matrix.os }}
|
|
14
14
|
strategy:
|
|
15
15
|
fail-fast: false
|
|
16
16
|
matrix:
|
|
17
|
+
os: [ubuntu-latest]
|
|
17
18
|
python-version: ["3.12", "3.13"]
|
|
19
|
+
include:
|
|
20
|
+
- os: windows-latest
|
|
21
|
+
python-version: "3.12"
|
|
18
22
|
|
|
19
23
|
steps:
|
|
20
24
|
- uses: actions/checkout@v4
|
|
@@ -31,6 +35,7 @@ jobs:
|
|
|
31
35
|
# (2026-08-23: rtn e inmet). Três tentativas removem o flake sem
|
|
32
36
|
# esconder erro real de resolução.
|
|
33
37
|
- name: Install dependencies
|
|
38
|
+
shell: bash
|
|
34
39
|
run: |
|
|
35
40
|
for i in 1 2 3; do
|
|
36
41
|
if uv sync --group dev --python ${{ matrix.python-version }} \
|
|
@@ -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
|
+
## [0.15.0] - 2026-11-03
|
|
9
|
+
|
|
10
|
+
### Adicionado
|
|
11
|
+
|
|
12
|
+
- `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.
|
|
13
|
+
- `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`.
|
|
14
|
+
- 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).
|
|
15
|
+
- 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`.
|
|
16
|
+
- 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.
|
|
17
|
+
- Fontes novas no mapa de comandos: `antt`, `bcb-microdados`, `capes`, `ipeadata`, `loterias`, `ons`, `pgfn`, `infosiga`, `sigtap` (também `datasus-sigtap`) e `transparencia-sp`.
|
|
18
|
+
|
|
19
|
+
### Alterado
|
|
20
|
+
|
|
21
|
+
- Exige `quantilica-core>=0.16.0`; o extra `lake` exige `quantilica-analytics>=0.9.0`.
|
|
22
|
+
- 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.
|
|
23
|
+
- `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).
|
|
24
|
+
|
|
25
|
+
### Corrigido
|
|
26
|
+
|
|
27
|
+
- `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".
|
|
28
|
+
- 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`.
|
|
29
|
+
- `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.
|
|
30
|
+
- Os testes de `--help` do `lake` não dependem mais de cor forçada no CI.
|
|
31
|
+
|
|
32
|
+
## [0.14.0] - 2026-10-30
|
|
33
|
+
|
|
34
|
+
### Adicionado
|
|
35
|
+
|
|
36
|
+
- `quantilica lake select|build|audit`: monta e audita o lake a partir de um bruto local. `select` cria a visão com a versão vigente de cada arquivo (`--mode hardlink|symlink|copy`, `--exclude ARQ` com `sha256` ou caminhos); `build` converte a visão em Parquet por fonte e dataset, em processos separados e com retomada (`--sources`, `--workers`, `--memory`, `--threads`, `--scratch`, `--force`, `--retry-errors`, `--no-disk-check`, `--allow-sleep`), e sai com código 1 se houver erro e 130 se for interrompido; `audit` confere rodapés, proveniência, cobertura, estrutura e leitores (`--input`, `--ledger`, `--sources`, `--no-readers`, `--no-integrity`, `--exceptions`, `--rehash`, `--workers`, `--json`, `--json-file`) e sai com código 1 se houver achados. O ledger é opcional.
|
|
37
|
+
- Extra `lake` (`pip install "quantilica-cli[lake]"`): traz o `quantilica-analytics`, que `build` e `audit` carregam só quando rodam; sem ele, avisam o que instalar e saem com código 1. `select` só precisa do `quantilica-core` (a partir da versão que traz `materialize_view`).
|
|
38
|
+
- CI: o job de testes também roda no Windows (Python 3.12).
|
|
39
|
+
|
|
8
40
|
## [0.13.0] - 2026-10-27
|
|
9
41
|
|
|
10
42
|
### Adicionado
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: quantilica-cli
|
|
3
|
+
Version: 0.15.0
|
|
4
|
+
Summary: Unified CLI for Quantilica open data fetchers
|
|
5
|
+
Author-email: "Komesu, D.K." <daniel@dkko.me>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: brazil,cli,open-data,quantilica
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Requires-Dist: quantilica-core>=0.16.0
|
|
20
|
+
Requires-Dist: rich>=13.0.0
|
|
21
|
+
Requires-Dist: typer>=0.15.0
|
|
22
|
+
Provides-Extra: lake
|
|
23
|
+
Requires-Dist: quantilica-analytics>=0.9.0; extra == 'lake'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# quantilica-cli
|
|
27
|
+
|
|
28
|
+
CLI unificada para o ecossistema Quantilica de dados abertos brasileiros.
|
|
29
|
+
For full documentation, please visit [https://docs.quantilica.com](https://docs.quantilica.com).
|
|
30
|
+
|
|
31
|
+
## Instalação
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install quantilica-cli
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Instale os fetchers desejados separadamente:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install comex-fetcher inmet-fetcher rtn-fetcher
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Uso
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
quantilica --help
|
|
47
|
+
quantilica list-sources
|
|
48
|
+
quantilica comex sync 2024
|
|
49
|
+
quantilica inmet sync 2020 2021
|
|
50
|
+
quantilica td sync --dataset prices
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Lake
|
|
54
|
+
|
|
55
|
+
`quantilica lake` monta e audita o lake de Parquet a partir de um bruto local, sem
|
|
56
|
+
depender de banco de dados nem do ledger do acervo (ele é opcional). O fluxo é
|
|
57
|
+
bruto local → `select` → `build` → `audit`:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
|
|
61
|
+
quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
|
|
62
|
+
|
|
63
|
+
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma uma execução interrompida
|
|
64
|
+
quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
|
|
65
|
+
|
|
66
|
+
# 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
|
|
67
|
+
quantilica lake audit --lake /dados/lake --input /dados/vigente --json-file auditoria.json
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- `select` só precisa do `quantilica-core`. `build` e `audit` usam o
|
|
71
|
+
`quantilica-analytics`, que entra com `pip install "quantilica-cli[lake]"`; sem ele
|
|
72
|
+
esses dois comandos avisam o que instalar e saem com código 1.
|
|
73
|
+
- `--exclude` e `--exceptions` aceitam um arquivo texto com um item por linha (linhas
|
|
74
|
+
vazias e iniciadas por `#` são ignoradas): `sha256` ou caminho relativo no `select`,
|
|
75
|
+
caminho relativo ou padrão `fnmatch` no `audit`.
|
|
76
|
+
- `build` sai com código 1 se alguma tarefa falhar, e com 130 se for interrompido
|
|
77
|
+
(Ctrl+C); rodar de novo retoma e `--retry-errors` refaz só o que falhou. O andamento
|
|
78
|
+
sai em stderr.
|
|
79
|
+
- `audit` sai com 0 se o lake for aprovado e com 1 se houver achados. `--json` imprime
|
|
80
|
+
o relatório em JSON no stdout (o andamento fica em stderr); `--json-file ARQ` o grava.
|
|
81
|
+
- `--ledger ARQ` (opcional, só em `audit`) confere a proveniência também contra uma
|
|
82
|
+
exportação do ledger; sem ele, a conferência usa o `sha256` dos manifestos ou do
|
|
83
|
+
próprio arquivo.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# quantilica-cli
|
|
2
|
+
|
|
3
|
+
CLI unificada para o ecossistema Quantilica de dados abertos brasileiros.
|
|
4
|
+
For full documentation, please visit [https://docs.quantilica.com](https://docs.quantilica.com).
|
|
5
|
+
|
|
6
|
+
## Instalação
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install quantilica-cli
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Instale os fetchers desejados separadamente:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install comex-fetcher inmet-fetcher rtn-fetcher
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Uso
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
quantilica --help
|
|
22
|
+
quantilica list-sources
|
|
23
|
+
quantilica comex sync 2024
|
|
24
|
+
quantilica inmet sync 2020 2021
|
|
25
|
+
quantilica td sync --dataset prices
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Lake
|
|
29
|
+
|
|
30
|
+
`quantilica lake` monta e audita o lake de Parquet a partir de um bruto local, sem
|
|
31
|
+
depender de banco de dados nem do ledger do acervo (ele é opcional). O fluxo é
|
|
32
|
+
bruto local → `select` → `build` → `audit`:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
# 1. visão só com a versão vigente de cada arquivo (hardlink; cai em symlink e em cópia)
|
|
36
|
+
quantilica lake select --raw /dados/bruto --out /dados/vigente --exclude excluir.txt
|
|
37
|
+
|
|
38
|
+
# 2. conversão em Parquet, por fonte e dataset, em processos separados; retoma uma execução interrompida
|
|
39
|
+
quantilica lake build --input /dados/vigente --lake /dados/lake --workers 4 --memory 12GB
|
|
40
|
+
|
|
41
|
+
# 3. auditoria: rodapés, proveniência (sha256), cobertura, estrutura e leitores
|
|
42
|
+
quantilica lake audit --lake /dados/lake --input /dados/vigente --json-file auditoria.json
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
- `select` só precisa do `quantilica-core`. `build` e `audit` usam o
|
|
46
|
+
`quantilica-analytics`, que entra com `pip install "quantilica-cli[lake]"`; sem ele
|
|
47
|
+
esses dois comandos avisam o que instalar e saem com código 1.
|
|
48
|
+
- `--exclude` e `--exceptions` aceitam um arquivo texto com um item por linha (linhas
|
|
49
|
+
vazias e iniciadas por `#` são ignoradas): `sha256` ou caminho relativo no `select`,
|
|
50
|
+
caminho relativo ou padrão `fnmatch` no `audit`.
|
|
51
|
+
- `build` sai com código 1 se alguma tarefa falhar, e com 130 se for interrompido
|
|
52
|
+
(Ctrl+C); rodar de novo retoma e `--retry-errors` refaz só o que falhou. O andamento
|
|
53
|
+
sai em stderr.
|
|
54
|
+
- `audit` sai com 0 se o lake for aprovado e com 1 se houver achados. `--json` imprime
|
|
55
|
+
o relatório em JSON no stdout (o andamento fica em stderr); `--json-file ARQ` o grava.
|
|
56
|
+
- `--ledger ARQ` (opcional, só em `audit`) confere a proveniência também contra uma
|
|
57
|
+
exportação do ledger; sem ele, a conferência usa o `sha256` dos manifestos ou do
|
|
58
|
+
próprio arquivo.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "quantilica-cli"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.15.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" }]
|
|
@@ -20,11 +20,15 @@ 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
|
+
[project.optional-dependencies]
|
|
29
|
+
# Motor de `quantilica lake build` e `quantilica lake audit`.
|
|
30
|
+
lake = ["quantilica-analytics>=0.9.0"]
|
|
31
|
+
|
|
28
32
|
[project.scripts]
|
|
29
33
|
quantilica = "quantilica.cli.cli:main"
|
|
30
34
|
|
|
@@ -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 VPS 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 a VPS.",
|
|
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,7 +13,9 @@ 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
|
|
18
|
+
from quantilica.cli.lake import app as lake_app
|
|
17
19
|
from quantilica.cli.manifests import app as manifests_app
|
|
18
20
|
from quantilica.cli.sources import (
|
|
19
21
|
app as sources_app,
|
|
@@ -33,6 +35,8 @@ app = typer.Typer(
|
|
|
33
35
|
help="Quantilica — ferramentas de dados abertos brasileiros.",
|
|
34
36
|
no_args_is_help=True,
|
|
35
37
|
)
|
|
38
|
+
app.add_typer(catalog_app, name="catalog")
|
|
39
|
+
app.add_typer(lake_app, name="lake")
|
|
36
40
|
app.add_typer(manifests_app, name="manifests")
|
|
37
41
|
app.add_typer(sources_app, name="sources")
|
|
38
42
|
|