normasbr 0.0.2__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.
- normasbr-0.0.2/LICENSE +21 -0
- normasbr-0.0.2/PKG-INFO +141 -0
- normasbr-0.0.2/README.md +85 -0
- normasbr-0.0.2/pyproject.toml +89 -0
- normasbr-0.0.2/pyproject.toml.orig +76 -0
- normasbr-0.0.2/src/normasbr/__init__.py +75 -0
- normasbr-0.0.2/src/normasbr/classificacao/estruturador_llm.py +121 -0
- normasbr-0.0.2/src/normasbr/classificacao/macrodimensao/existencia/anomalia.py +124 -0
- normasbr-0.0.2/src/normasbr/classificacao/macrodimensao/existencia/classificador.py +138 -0
- normasbr-0.0.2/src/normasbr/cli.py +115 -0
- normasbr-0.0.2/src/normasbr/config.py +11 -0
- normasbr-0.0.2/src/normasbr/estrutura/estruturador.py +523 -0
- normasbr-0.0.2/src/normasbr/estrutura/modelo.py +163 -0
- normasbr-0.0.2/src/normasbr/estrutura/serializacao.py +78 -0
- normasbr-0.0.2/src/normasbr/estrutura/travessia.py +78 -0
- normasbr-0.0.2/src/normasbr/ingestao/despachante.py +48 -0
- normasbr-0.0.2/src/normasbr/ingestao/doc2html.py +17 -0
- normasbr-0.0.2/src/normasbr/ingestao/downloader.py +51 -0
- normasbr-0.0.2/src/normasbr/ingestao/file2html.py +15 -0
- normasbr-0.0.2/src/normasbr/ingestao/normativa_bruta.py +7 -0
- normasbr-0.0.2/src/normasbr/ingestao/pdf2html.py +13 -0
- normasbr-0.0.2/src/normasbr/ingestao/txt2html.py +23 -0
- normasbr-0.0.2/src/normasbr/ingestao/url2html.py +19 -0
- normasbr-0.0.2/src/normasbr/segmentacao/diff_segmentacao.py +243 -0
- normasbr-0.0.2/src/normasbr/segmentacao/extrator_blocos.py +313 -0
- normasbr-0.0.2/src/normasbr/segmentacao/segmentador.py +846 -0
normasbr-0.0.2/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Instituto de Pesquisa Econômica Aplicada (Ipea)
|
|
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.
|
normasbr-0.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: normasbr
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Limpeza e estruturação de textos normativos brasileiros a partir de disversos formatos
|
|
5
|
+
Keywords: norm,law,regulation,brazil,brasil,regex,parsing
|
|
6
|
+
Author: Gabriel Garcia de Almeida
|
|
7
|
+
Author-email: Gabriel Garcia de Almeida <gabriel.almeida@ipea.gov.br>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 Instituto de Pesquisa Econômica Aplicada (Ipea)
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
Classifier: Programming Language :: Python :: 3
|
|
30
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
31
|
+
Classifier: Development Status :: 3 - Alpha
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: Intended Audience :: Education
|
|
34
|
+
Classifier: Intended Audience :: Science/Research
|
|
35
|
+
Classifier: Operating System :: OS Independent
|
|
36
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Natural Language :: Portuguese (Brazilian)
|
|
39
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
40
|
+
Requires-Dist: dotenv>=0.9.9
|
|
41
|
+
Requires-Dist: duckdb>=1.5.1
|
|
42
|
+
Requires-Dist: lxml>=6.1.0
|
|
43
|
+
Requires-Dist: mammoth>=1.12.0
|
|
44
|
+
Requires-Dist: pydantic>=2.13.5
|
|
45
|
+
Requires-Dist: pymupdf>=1.28.2
|
|
46
|
+
Requires-Dist: pyserde>=0.31.2
|
|
47
|
+
Requires-Dist: pyyaml>=6.0.3
|
|
48
|
+
Requires-Dist: requests>=2.33.1
|
|
49
|
+
Requires-Dist: tqdm>=4.67.3
|
|
50
|
+
Requires-Dist: typer>=0.23.1
|
|
51
|
+
Requires-Python: >=3.12
|
|
52
|
+
Project-URL: Homepage, https://github.com/ipea/normasbr
|
|
53
|
+
Project-URL: Repository, https://github.com/ipea/normasbr
|
|
54
|
+
Project-URL: Issues, https://github.com/ipea/normasbr/issues
|
|
55
|
+
Description-Content-Type: text/markdown
|
|
56
|
+
|
|
57
|
+
# normasbr <img align="right" src="./assets/logo.svg" alt="" width="180">
|
|
58
|
+
|
|
59
|
+
[](./LICENSE)
|
|
60
|
+
[](./pyproject.toml)
|
|
61
|
+
[](https://github.com/astral-sh/ruff)
|
|
62
|
+
[](https://github.com/ipea/normasbr/actions)
|
|
63
|
+
[](https://pypi.org/project/enderecobr)
|
|
64
|
+
[](https://pepy.tech/project/normasbr)
|
|
65
|
+
[](https://normasbr.readthedocs.io)
|
|
66
|
+
|
|
67
|
+
> ⚠️ **ATENÇÃO** ⚠️: Biblioteca ainda em estágio muito experimental, e sem garantias de retrocompatibilidade entre as versões.
|
|
68
|
+
|
|
69
|
+
**normasbr** é uma biblioteca Python que extrai, segmenta e estrutura normativas
|
|
70
|
+
brasileiras (leis, decretos, medidas provisórias etc.) a partir de HTML, PDF, DOCX ou
|
|
71
|
+
TXT, convertendo textos brutos em documentos estruturados (YML), com hierarquia completa de dispositivos
|
|
72
|
+
(norma > agrupadores > artigos > incisos > alíneas > itens).
|
|
73
|
+
|
|
74
|
+
O processamento é determinístico, usando heurísticas e expressões regulares baseadas em documentos normativos diversos.
|
|
75
|
+
|
|
76
|
+
## Pipeline
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
ingerir -> segmentar -> estruturar
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
1. **Ingestão**: normaliza HTML/PDF/DOCX/TXT para um HTML canônico;
|
|
83
|
+
2. **Segmentação**: extrai blocos de texto e classifica cada segmento
|
|
84
|
+
(artigo, parágrafo, inciso, ementa, preâmbulo, bloco de alteração etc.);
|
|
85
|
+
3. **Estruturação**: monta a árvore hierárquica da normativa a partir dos segmentos;
|
|
86
|
+
|
|
87
|
+
## Instalação
|
|
88
|
+
|
|
89
|
+
A última versão pode ser instalada com o [uv](https://docs.astral.sh/uv/):
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
uv add normasbr # Usando como biblioteca
|
|
93
|
+
uv tool install normasbr # Usando como utilitário de linha de comando
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Ou diretamente do repositório:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
uv pip install git+https://github.com/ipea/normasbr
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Exemplo de uso
|
|
103
|
+
|
|
104
|
+
### Biblioteca:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
import normasbr
|
|
108
|
+
|
|
109
|
+
for bruta in normasbr.despachar_ingestao("data/DEL5452.htm"):
|
|
110
|
+
segmentos = normasbr.Segmentador().segmentar(normasbr.extrair_blocos(bruta))
|
|
111
|
+
normas = normasbr.estruturar(segmentos, leniente=True)
|
|
112
|
+
|
|
113
|
+
print(normasbr.formatar_normativas_yml(normas))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### CLI:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
normasbr ingerir data/DEL5452.htm
|
|
120
|
+
normasbr segmentar data/docs
|
|
121
|
+
normasbr estruturar data/docs -o normas.yml
|
|
122
|
+
normasbr diff_seg snapshot.jsonl novo.jsonl
|
|
123
|
+
normasbr classificar_macrodim normas.yml saida.parquet
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Desenvolvimento
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
make setup # cria o venv e instala as dependências
|
|
130
|
+
make check # lint (ruff) + testes (pytest)
|
|
131
|
+
make format # formata o código
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Referências usadas na modelagem
|
|
135
|
+
|
|
136
|
+
- [Glossário e técnica legislativa do Congresso Nacional](https://www.congressonacional.leg.br/legislacao-e-publicacoes/glossario-tecnica-legislativa)
|
|
137
|
+
|
|
138
|
+
## Nota <a href="https://www.ipea.gov.br"><img src="./assets/ipea_logo.png" alt="Ipea" align="right" width="300"/></a>
|
|
139
|
+
|
|
140
|
+
**normasbr** é desenvolvido por uma equipe de pesquisadores do Instituto de Pesquisa
|
|
141
|
+
Econômica Aplicada (Ipea).
|
normasbr-0.0.2/README.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# normasbr <img align="right" src="./assets/logo.svg" alt="" width="180">
|
|
2
|
+
|
|
3
|
+
[](./LICENSE)
|
|
4
|
+
[](./pyproject.toml)
|
|
5
|
+
[](https://github.com/astral-sh/ruff)
|
|
6
|
+
[](https://github.com/ipea/normasbr/actions)
|
|
7
|
+
[](https://pypi.org/project/enderecobr)
|
|
8
|
+
[](https://pepy.tech/project/normasbr)
|
|
9
|
+
[](https://normasbr.readthedocs.io)
|
|
10
|
+
|
|
11
|
+
> ⚠️ **ATENÇÃO** ⚠️: Biblioteca ainda em estágio muito experimental, e sem garantias de retrocompatibilidade entre as versões.
|
|
12
|
+
|
|
13
|
+
**normasbr** é uma biblioteca Python que extrai, segmenta e estrutura normativas
|
|
14
|
+
brasileiras (leis, decretos, medidas provisórias etc.) a partir de HTML, PDF, DOCX ou
|
|
15
|
+
TXT, convertendo textos brutos em documentos estruturados (YML), com hierarquia completa de dispositivos
|
|
16
|
+
(norma > agrupadores > artigos > incisos > alíneas > itens).
|
|
17
|
+
|
|
18
|
+
O processamento é determinístico, usando heurísticas e expressões regulares baseadas em documentos normativos diversos.
|
|
19
|
+
|
|
20
|
+
## Pipeline
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
ingerir -> segmentar -> estruturar
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
1. **Ingestão**: normaliza HTML/PDF/DOCX/TXT para um HTML canônico;
|
|
27
|
+
2. **Segmentação**: extrai blocos de texto e classifica cada segmento
|
|
28
|
+
(artigo, parágrafo, inciso, ementa, preâmbulo, bloco de alteração etc.);
|
|
29
|
+
3. **Estruturação**: monta a árvore hierárquica da normativa a partir dos segmentos;
|
|
30
|
+
|
|
31
|
+
## Instalação
|
|
32
|
+
|
|
33
|
+
A última versão pode ser instalada com o [uv](https://docs.astral.sh/uv/):
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv add normasbr # Usando como biblioteca
|
|
37
|
+
uv tool install normasbr # Usando como utilitário de linha de comando
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Ou diretamente do repositório:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
uv pip install git+https://github.com/ipea/normasbr
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Exemplo de uso
|
|
47
|
+
|
|
48
|
+
### Biblioteca:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import normasbr
|
|
52
|
+
|
|
53
|
+
for bruta in normasbr.despachar_ingestao("data/DEL5452.htm"):
|
|
54
|
+
segmentos = normasbr.Segmentador().segmentar(normasbr.extrair_blocos(bruta))
|
|
55
|
+
normas = normasbr.estruturar(segmentos, leniente=True)
|
|
56
|
+
|
|
57
|
+
print(normasbr.formatar_normativas_yml(normas))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### CLI:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
normasbr ingerir data/DEL5452.htm
|
|
64
|
+
normasbr segmentar data/docs
|
|
65
|
+
normasbr estruturar data/docs -o normas.yml
|
|
66
|
+
normasbr diff_seg snapshot.jsonl novo.jsonl
|
|
67
|
+
normasbr classificar_macrodim normas.yml saida.parquet
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Desenvolvimento
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
make setup # cria o venv e instala as dependências
|
|
74
|
+
make check # lint (ruff) + testes (pytest)
|
|
75
|
+
make format # formata o código
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Referências usadas na modelagem
|
|
79
|
+
|
|
80
|
+
- [Glossário e técnica legislativa do Congresso Nacional](https://www.congressonacional.leg.br/legislacao-e-publicacoes/glossario-tecnica-legislativa)
|
|
81
|
+
|
|
82
|
+
## Nota <a href="https://www.ipea.gov.br"><img src="./assets/ipea_logo.png" alt="Ipea" align="right" width="300"/></a>
|
|
83
|
+
|
|
84
|
+
**normasbr** é desenvolvido por uma equipe de pesquisadores do Instituto de Pesquisa
|
|
85
|
+
Econômica Aplicada (Ipea).
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "normasbr"
|
|
3
|
+
version = "0.0.2"
|
|
4
|
+
description = "Limpeza e estruturação de textos normativos brasileiros a partir de disversos formatos"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
classifiers = [
|
|
7
|
+
"Programming Language :: Python :: 3",
|
|
8
|
+
"Programming Language :: Python :: 3.12",
|
|
9
|
+
"Development Status :: 3 - Alpha",
|
|
10
|
+
"Intended Audience :: Developers",
|
|
11
|
+
"Intended Audience :: Education",
|
|
12
|
+
"Intended Audience :: Science/Research",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Topic :: Text Processing :: Linguistic",
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Natural Language :: Portuguese (Brazilian)",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
]
|
|
19
|
+
keywords = [
|
|
20
|
+
"norm",
|
|
21
|
+
"law",
|
|
22
|
+
"regulation",
|
|
23
|
+
"brazil",
|
|
24
|
+
"brasil",
|
|
25
|
+
"regex",
|
|
26
|
+
"parsing",
|
|
27
|
+
]
|
|
28
|
+
requires-python = ">=3.12"
|
|
29
|
+
dependencies = [
|
|
30
|
+
"dotenv>=0.9.9",
|
|
31
|
+
"duckdb>=1.5.1",
|
|
32
|
+
"lxml>=6.1.0",
|
|
33
|
+
"mammoth>=1.12.0",
|
|
34
|
+
"pydantic>=2.13.5",
|
|
35
|
+
"pymupdf>=1.28.2",
|
|
36
|
+
"pyserde>=0.31.2",
|
|
37
|
+
"pyyaml>=6.0.3",
|
|
38
|
+
"requests>=2.33.1",
|
|
39
|
+
"tqdm>=4.67.3",
|
|
40
|
+
"typer>=0.23.1",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[project.license]
|
|
44
|
+
file = "LICENSE"
|
|
45
|
+
|
|
46
|
+
[[project.authors]]
|
|
47
|
+
name = "Gabriel Garcia de Almeida"
|
|
48
|
+
email = "gabriel.almeida@ipea.gov.br"
|
|
49
|
+
|
|
50
|
+
[project.urls]
|
|
51
|
+
Homepage = "https://github.com/ipea/normasbr"
|
|
52
|
+
Repository = "https://github.com/ipea/normasbr"
|
|
53
|
+
Issues = "https://github.com/ipea/normasbr/issues"
|
|
54
|
+
|
|
55
|
+
[project.scripts]
|
|
56
|
+
normasbr = "normasbr.cli:app"
|
|
57
|
+
|
|
58
|
+
[build-system]
|
|
59
|
+
requires = ["uv_build>=0.9.17,<0.10.0"]
|
|
60
|
+
build-backend = "uv_build"
|
|
61
|
+
|
|
62
|
+
[dependency-groups]
|
|
63
|
+
dev = [
|
|
64
|
+
"basedpyright>=1.39.10",
|
|
65
|
+
"pytest>=9.0.3",
|
|
66
|
+
"pytest-cov>=7.1.0",
|
|
67
|
+
"ruff>=0.15.9",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
[tool.pytest.ini_options]
|
|
71
|
+
addopts = "--cov=normasbr --cov-report=term-missing"
|
|
72
|
+
|
|
73
|
+
[tool.coverage.run]
|
|
74
|
+
source = ["normasbr"]
|
|
75
|
+
omit = ["normasbr/classificacao/*"]
|
|
76
|
+
|
|
77
|
+
[tool.coverage.report]
|
|
78
|
+
exclude_lines = [
|
|
79
|
+
"pragma: no cover",
|
|
80
|
+
"if __name__ == .__main__.:",
|
|
81
|
+
"if TYPE_CHECKING:",
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
[tool.basedpyright]
|
|
85
|
+
typeCheckingMode = "standard"
|
|
86
|
+
include = [
|
|
87
|
+
"src",
|
|
88
|
+
"tests",
|
|
89
|
+
]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "normasbr"
|
|
3
|
+
version = "0.0.2"
|
|
4
|
+
description = "Limpeza e estruturação de textos normativos brasileiros a partir de disversos formatos"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = { file = "LICENSE" }
|
|
7
|
+
authors = [
|
|
8
|
+
{ name = "Gabriel Garcia de Almeida", email = "gabriel.almeida@ipea.gov.br" }
|
|
9
|
+
]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Programming Language :: Python :: 3.12",
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Intended Audience :: Education",
|
|
16
|
+
"Intended Audience :: Science/Research",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Text Processing :: Linguistic",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Natural Language :: Portuguese (Brazilian)",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
]
|
|
23
|
+
keywords = ["norm", "law", "regulation", "brazil", "brasil", "regex", "parsing"]
|
|
24
|
+
|
|
25
|
+
requires-python = ">=3.12"
|
|
26
|
+
dependencies = [
|
|
27
|
+
"dotenv>=0.9.9",
|
|
28
|
+
"duckdb>=1.5.1",
|
|
29
|
+
"lxml>=6.1.0",
|
|
30
|
+
"mammoth>=1.12.0",
|
|
31
|
+
"pydantic>=2.13.5",
|
|
32
|
+
"pymupdf>=1.28.2",
|
|
33
|
+
"pyserde>=0.31.2",
|
|
34
|
+
"pyyaml>=6.0.3",
|
|
35
|
+
"requests>=2.33.1",
|
|
36
|
+
"tqdm>=4.67.3",
|
|
37
|
+
"typer>=0.23.1",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://github.com/ipea/normasbr"
|
|
42
|
+
Repository = "https://github.com/ipea/normasbr"
|
|
43
|
+
Issues = "https://github.com/ipea/normasbr/issues"
|
|
44
|
+
|
|
45
|
+
[project.scripts]
|
|
46
|
+
normasbr = "normasbr.cli:app"
|
|
47
|
+
|
|
48
|
+
[build-system]
|
|
49
|
+
requires = ["uv_build>=0.9.17,<0.10.0"]
|
|
50
|
+
build-backend = "uv_build"
|
|
51
|
+
|
|
52
|
+
[dependency-groups]
|
|
53
|
+
dev = [
|
|
54
|
+
"basedpyright>=1.39.10",
|
|
55
|
+
"pytest>=9.0.3",
|
|
56
|
+
"pytest-cov>=7.1.0",
|
|
57
|
+
"ruff>=0.15.9",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
[tool.pytest.ini_options]
|
|
61
|
+
addopts = "--cov=normasbr --cov-report=term-missing"
|
|
62
|
+
|
|
63
|
+
[tool.coverage.run]
|
|
64
|
+
source = ["normasbr"]
|
|
65
|
+
omit = ["normasbr/classificacao/*"]
|
|
66
|
+
|
|
67
|
+
[tool.coverage.report]
|
|
68
|
+
exclude_lines = [
|
|
69
|
+
"pragma: no cover",
|
|
70
|
+
"if __name__ == .__main__.:",
|
|
71
|
+
"if TYPE_CHECKING:",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
[tool.basedpyright]
|
|
75
|
+
typeCheckingMode = "standard"
|
|
76
|
+
include = ["src", "tests"]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""NormasBR: extração, segmentação e estruturação de normativas brasileiras.
|
|
2
|
+
|
|
3
|
+
Pipeline: ingestão (HTML/PDF/DOCX/TXT) > extração de blocos > segmentação >
|
|
4
|
+
estruturação > serialização (YML/JSON) > classificação.
|
|
5
|
+
|
|
6
|
+
Exemplo de uso da biblioteca:
|
|
7
|
+
|
|
8
|
+
>>> import normasbr
|
|
9
|
+
>>> normativas_brutas = normasbr.despachar_ingestao("lei.htm")
|
|
10
|
+
>>> blocos = normasbr.extrair_blocos(normativas_brutas[0])
|
|
11
|
+
>>> segmentos = normasbr.Segmentador().segmentar(blocos)
|
|
12
|
+
>>> normas = normasbr.estruturar(segmentos, leniente=True)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
16
|
+
|
|
17
|
+
from normasbr.estrutura.estruturador import estruturar
|
|
18
|
+
from normasbr.estrutura.modelo import (
|
|
19
|
+
Agrupador,
|
|
20
|
+
Dispositivo,
|
|
21
|
+
Elemento,
|
|
22
|
+
ElementoIntermediario,
|
|
23
|
+
Elementos,
|
|
24
|
+
Link,
|
|
25
|
+
Normativa,
|
|
26
|
+
)
|
|
27
|
+
from normasbr.estrutura.serializacao import (
|
|
28
|
+
carregar_normativas,
|
|
29
|
+
formatar_normativas_json,
|
|
30
|
+
formatar_normativas_yml,
|
|
31
|
+
)
|
|
32
|
+
from normasbr.estrutura.travessia import (
|
|
33
|
+
gerar_texto,
|
|
34
|
+
gerar_visualizacao_textual,
|
|
35
|
+
procurar_dispositivos,
|
|
36
|
+
)
|
|
37
|
+
from normasbr.ingestao.despachante import despachar_ingestao
|
|
38
|
+
from normasbr.ingestao.normativa_bruta import NormativaBruta
|
|
39
|
+
from normasbr.segmentacao.extrator_blocos import Bloco, extrair_blocos
|
|
40
|
+
from normasbr.segmentacao.segmentador import (
|
|
41
|
+
HEURISTICAS_PADRAO,
|
|
42
|
+
REGRAS_PADRAO,
|
|
43
|
+
Segmentador,
|
|
44
|
+
Segmento,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
__version__ = version("normasbr")
|
|
49
|
+
except PackageNotFoundError: # executando a partir do código-fonte sem instalar
|
|
50
|
+
__version__ = "0.0.0"
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"HEURISTICAS_PADRAO",
|
|
54
|
+
"REGRAS_PADRAO",
|
|
55
|
+
"Agrupador",
|
|
56
|
+
"Bloco",
|
|
57
|
+
"Dispositivo",
|
|
58
|
+
"Elemento",
|
|
59
|
+
"ElementoIntermediario",
|
|
60
|
+
"Elementos",
|
|
61
|
+
"Link",
|
|
62
|
+
"Normativa",
|
|
63
|
+
"NormativaBruta",
|
|
64
|
+
"Segmentador",
|
|
65
|
+
"Segmento",
|
|
66
|
+
"carregar_normativas",
|
|
67
|
+
"despachar_ingestao",
|
|
68
|
+
"estruturar",
|
|
69
|
+
"extrair_blocos",
|
|
70
|
+
"formatar_normativas_json",
|
|
71
|
+
"formatar_normativas_yml",
|
|
72
|
+
"gerar_texto",
|
|
73
|
+
"gerar_visualizacao_textual",
|
|
74
|
+
"procurar_dispositivos",
|
|
75
|
+
]
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# pyright: reportAny=false
|
|
2
|
+
# pyright: reportExplicitAny=false
|
|
3
|
+
# pyright: reportUnknownVariableType=false
|
|
4
|
+
|
|
5
|
+
# Preciso ignorar alguns tipos, pois internamente lido com muitos Any e Unknown.
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import random
|
|
9
|
+
import time
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Generic, TypeVar
|
|
12
|
+
|
|
13
|
+
import requests
|
|
14
|
+
from pydantic import BaseModel
|
|
15
|
+
|
|
16
|
+
T = TypeVar("T", bound=BaseModel)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass()
|
|
20
|
+
class EstruturadorDadosLLM(Generic[T]):
|
|
21
|
+
template_prompt: str
|
|
22
|
+
estrutura_esperada: type[T]
|
|
23
|
+
url: str
|
|
24
|
+
modelo: str
|
|
25
|
+
token_acesso: str | None = None
|
|
26
|
+
n_tentativas: int = 20
|
|
27
|
+
delay_base_tentativa: int = 5
|
|
28
|
+
timeout_conecao: int = 10
|
|
29
|
+
timeout_resposta: int = 30
|
|
30
|
+
|
|
31
|
+
def __call__(self, *args: Any, **kwds: Any) -> T:
|
|
32
|
+
prompt = self.template_prompt.format(*args, **kwds)
|
|
33
|
+
|
|
34
|
+
payload: dict[str, Any] = {
|
|
35
|
+
"model": self.modelo,
|
|
36
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
37
|
+
"response_format": {
|
|
38
|
+
"type": "json_schema",
|
|
39
|
+
"json_schema": {
|
|
40
|
+
"name": "resposta",
|
|
41
|
+
"schema": self.obter_json_schema(),
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
"stream": False,
|
|
45
|
+
"temperature": 0.0,
|
|
46
|
+
"chat_template_kwargs": {"enable_thinking": False},
|
|
47
|
+
"reasoning": {
|
|
48
|
+
"enabled": False,
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
resposta = self.__tentar_realizar_request(payload)
|
|
53
|
+
estruturado_bruto = str(
|
|
54
|
+
resposta.get("choices", [{}])[0].get("message", {}).get("content", "{}")
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return self.estrutura_esperada.model_validate(json.loads(estruturado_bruto))
|
|
58
|
+
|
|
59
|
+
def obter_json_schema(self):
|
|
60
|
+
return self.__simplificar_schema(self.estrutura_esperada.model_json_schema())
|
|
61
|
+
|
|
62
|
+
def __tentar_realizar_request(self, payload: dict[str, Any]):
|
|
63
|
+
for tentativa in range(self.n_tentativas):
|
|
64
|
+
try:
|
|
65
|
+
session = requests.Session()
|
|
66
|
+
session.trust_env = True
|
|
67
|
+
|
|
68
|
+
if self.token_acesso:
|
|
69
|
+
session.headers.update(
|
|
70
|
+
{"Authorization": f"Bearer {self.token_acesso}"}
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
resposta = session.post(
|
|
74
|
+
self.url,
|
|
75
|
+
json=payload,
|
|
76
|
+
timeout=(self.timeout_conecao, self.timeout_resposta),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
resposta.raise_for_status()
|
|
80
|
+
return resposta.json()
|
|
81
|
+
|
|
82
|
+
except (
|
|
83
|
+
requests.Timeout,
|
|
84
|
+
requests.ConnectionError,
|
|
85
|
+
requests.HTTPError,
|
|
86
|
+
requests.JSONDecodeError,
|
|
87
|
+
) as e:
|
|
88
|
+
if tentativa == self.n_tentativas - 1:
|
|
89
|
+
# Evitando um delay desnecessário na ultima tentativa
|
|
90
|
+
break
|
|
91
|
+
|
|
92
|
+
delay = self.delay_base_tentativa * (2**tentativa - 1)
|
|
93
|
+
# jitter aleatório para evitar thundering herd
|
|
94
|
+
delay += random.uniform(0, 5)
|
|
95
|
+
|
|
96
|
+
print(
|
|
97
|
+
f"Tentativa {tentativa + 1} falhou: {e}. Retry em {delay:.2f}s..."
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
time.sleep(delay)
|
|
101
|
+
raise Exception("Não foi possível realizar a requisição.")
|
|
102
|
+
|
|
103
|
+
def __simplificar_schema(self, schema: Any) -> dict[str, Any] | list[Any]:
|
|
104
|
+
if isinstance(schema, dict):
|
|
105
|
+
return {
|
|
106
|
+
k: self.__simplificar_schema(v)
|
|
107
|
+
for k, v in schema.items()
|
|
108
|
+
if k
|
|
109
|
+
not in {
|
|
110
|
+
"title",
|
|
111
|
+
"default",
|
|
112
|
+
"examples",
|
|
113
|
+
"$defs",
|
|
114
|
+
"description",
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if isinstance(schema, list):
|
|
119
|
+
return [self.__simplificar_schema(v) for v in schema]
|
|
120
|
+
|
|
121
|
+
return schema
|