pyontl 1.0.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.
pyontl/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ pyontl - Biblioteca para acesso a dados da ONTL
3
+ """
4
+
5
+ from .core import getDataset
6
+ from .metadata import getMetadados, getMetadados_filterableColumns
7
+
8
+ __version__ = "1.0.0"
9
+ __all__ = [
10
+ "getDataset",
11
+ "getMetadados",
12
+ "getMetadados_filterableColumns"
13
+ ]
pyontl/core.py ADDED
@@ -0,0 +1,74 @@
1
+ import pandas as pd
2
+ from .utils import make_request
3
+
4
+ def getDataset(year=2000, dataset="antt_pracaspedagio",
5
+ column_order_by="int_idapracaspedagio",
6
+ column_filter_year="int_ano"):
7
+ """
8
+ Busca dados paginados de um dataset específico por ano.
9
+
10
+ Esta função realiza requisições paginadas à API da ONTL para recuperar
11
+ todos os registros de um determinado ano.
12
+
13
+ Args:
14
+ year (int, optional): Ano dos dados a serem buscados. Padrão: 2000.
15
+ dataset (str, optional): Nome do dataset. Padrão: "antt_pracaspedagio".
16
+ column_order_by (str, optional): Coluna para ordenação dos resultados.
17
+ Padrão: "int_idapracaspedagio".
18
+ column_filter_year (str, optional): Nome da coluna que contém o ano
19
+ para filtragem. Padrão: "int_ano".
20
+
21
+ Returns:
22
+ pandas.DataFrame: DataFrame contendo todos os registros encontrados
23
+ para o ano especificado.
24
+
25
+ Raises:
26
+ Exception: Em caso de erro na requisição HTTP.
27
+
28
+ Examples:
29
+ >>> import pyontl
30
+ >>> # Buscar dados de 2023
31
+ >>> df_2023 = pyontl.getDataset(year=2023)
32
+ >>> print(f"Encontrados {len(df_2023)} registros")
33
+ Encontrados 1500 registros
34
+
35
+ >>> # Buscar dados de dataset específico
36
+ >>> df_custom = pyontl.getDataset(
37
+ ... year=2022,
38
+ ... dataset="meu_dataset",
39
+ ... column_filter_year="ano"
40
+ ... )
41
+
42
+ Note:
43
+ A função realiza múltiplas requisições paginadas até recuperar
44
+ todos os dados disponíveis.
45
+ """
46
+
47
+ base_url = f"https://ontl-apim.infrasa.gov.br/api/public/datasets/{dataset}"
48
+ all_records = []
49
+ page = 1
50
+ per_page = 100
51
+
52
+ while True:
53
+ params = {
54
+ "per_page": per_page,
55
+ "page": page,
56
+ "order_by": column_order_by,
57
+ column_filter_year: year
58
+ }
59
+
60
+ try:
61
+ response = make_request(base_url, params=params)
62
+ data = response.get("data", [])
63
+
64
+ if not data:
65
+ break
66
+
67
+ all_records.extend(data)
68
+ page += 1
69
+
70
+ except Exception as e:
71
+ print(f"Erro ao buscar dados para o ano {year}: {e}")
72
+ break
73
+
74
+ return pd.DataFrame(all_records)
pyontl/metadata.py ADDED
@@ -0,0 +1,76 @@
1
+ import pandas as pd
2
+ from .utils import make_request
3
+
4
+ def getMetadados(dataset="antt_pracaspedagio"):
5
+ """
6
+ Obtém metadados completos e estruturais do dataset especificado.
7
+
8
+ Fornece informações detalhadas sobre a estrutura, colunas, tipos de dados
9
+ e metadados técnicos do conjunto de dados, essencial para entender
10
+ a organização dos dados antes de realizar consultas.
11
+
12
+ Args:
13
+ dataset (str, optional): Nome do dataset da ONTL.
14
+ Padrão: "antt_pracaspedagio".
15
+
16
+ Returns:
17
+ dict: Dicionário com metadados completos incluindo:
18
+ - table: Nome da tabela
19
+ - filterableColumns: Lista de colunas filtráveis
20
+ - Estrutura completa de metadados da API
21
+
22
+ Examples:
23
+ >>> metadados = getMetadados()
24
+ >>> print(f"Colunas filtráveis: {metadados.get('filterableColumns', [])}")
25
+ >>> print(f"Estrutura da tabela: {metadados.get('table', 'N/A')}")
26
+
27
+ Raises:
28
+ Exception: Em caso de erro na requisição HTTP.
29
+ """
30
+
31
+ metadados_url = f"https://ontl-apim.infrasa.gov.br/api/public/datasets/{dataset}/meta"
32
+
33
+ try:
34
+ return make_request(metadados_url)
35
+ except Exception as e:
36
+ print(f"Erro ao buscar metadados: {e}")
37
+ return {}
38
+
39
+ def getMetadados_filterableColumns(dataset="antt_pracaspedagio"):
40
+ """
41
+ Recupera lista de colunas filtráveis dos metadados do dataset.
42
+
43
+ Gera um DataFrame com as colunas que podem ser utilizadas para filtrar
44
+ os dados na API, facilitando a construção de consultas específicas.
45
+
46
+ Args:
47
+ dataset (str, optional): Nome do dataset da ONTL.
48
+ Padrão: "antt_pracaspedagio".
49
+
50
+ Returns:
51
+ pandas.DataFrame: DataFrame com duas colunas:
52
+ - dataset: Nome do dataset
53
+ - column_name: Nome da coluna filtrável
54
+
55
+ Examples:
56
+ >>> colunas = getMetadados_filterableColumns()
57
+ >>> print(f"Número de colunas filtráveis: {len(colunas)}")
58
+ >>> print(colunas.head())
59
+
60
+ Raises:
61
+ Exception: Em caso de erro ao acessar os metadados.
62
+ """
63
+
64
+ try:
65
+ meta = getMetadados(dataset)
66
+ cols = meta.get("filterableColumns ", [])
67
+ table = meta.get("table", [])
68
+
69
+ return pd.DataFrame({
70
+ "dataset": [table] * len(cols),
71
+ "column_name": cols
72
+ })
73
+
74
+ except Exception as e:
75
+ print(f"Erro ao recuperar metadados de colunas filtráveis: {e}")
76
+ return pd.DataFrame({"dataset": [], "column_name": []})
pyontl/utils.py ADDED
@@ -0,0 +1,32 @@
1
+ import requests
2
+
3
+ def make_request(url, params=None, timeout=60):
4
+ """
5
+ Faz uma requisição HTTP GET com tratamento de erros.
6
+
7
+ Função auxiliar para realizar requisições à API da ONTL com
8
+ tratamento robusto de exceções e configurações de timeout.
9
+
10
+ Args:
11
+ url (str): URL para a requisição.
12
+ params (dict, optional): Parâmetros de consulta (query string).
13
+ Padrão: None.
14
+ timeout (int, optional): Timeout em segundos. Padrão: 60.
15
+
16
+ Returns:
17
+ dict: Resposta da API em formato JSON.
18
+
19
+ Raises:
20
+ Exception: Erro na requisição HTTP (conexão, timeout, etc.)
21
+
22
+ Examples:
23
+ >>> resposta = make_request("https://ontl-apim.infrasa.gov.br/api/public/datasets/antt_pracaspedagio/meta")
24
+ >>> print(resposta.keys())
25
+ """
26
+
27
+ try:
28
+ response = requests.get(url, params=params, timeout=timeout)
29
+ response.raise_for_status()
30
+ return response.json()
31
+ except requests.exceptions.RequestException as e:
32
+ raise Exception(f"Erro na requisição para {url}: {e}")
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyontl
3
+ Version: 1.0.0
4
+ Summary: Biblioteca Python para acesso a dados da ONTL.
5
+ Project-URL: Homepage, https://github.com/DevSciHub/pyontl
6
+ Project-URL: Repository, https://github.com/DevSciHub/pyontl.git
7
+ Author-email: DevSci <dev.sci.space@gmail.com>
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.8
10
+ Requires-Dist: pandas>=1.1.0
11
+ Requires-Dist: requests>=2.25.0
@@ -0,0 +1,8 @@
1
+ pyontl/__init__.py,sha256=bhuBviuPeleiXjZeP7cmy5Yr-mW0UEzntMEmhQjA-RM,277
2
+ pyontl/core.py,sha256=gnm1Psdq2Ql61bfMAwor0mYCvfZsGhxp0C8Y-7QtiVk,2454
3
+ pyontl/metadata.py,sha256=5KugWRbu6C9CcBhxOrAn56Xonkgv3UymjM56YuuoafA,2666
4
+ pyontl/utils.py,sha256=0rNs4_C89PV1HCe04HsYFT0K05ygxcRwSCB-NdQLG6Q,1138
5
+ pyontl-1.0.0.dist-info/METADATA,sha256=qhzOzjL0fq75cB13RtZp7t0qyPcs-0h2DjrlhEjufsQ,383
6
+ pyontl-1.0.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
7
+ pyontl-1.0.0.dist-info/licenses/LICENSE,sha256=1aFE7aijaPY5JfRG_H3Ao2B3wswjtlhAJZin3NV3NXA,1091
8
+ pyontl-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Dev Sci Space
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.