brfiscal 0.1.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.
- brfiscal/__init__.py +25 -0
- brfiscal/__main__.py +74 -0
- brfiscal/_sinonimos.py +63 -0
- brfiscal/_tabela.py +255 -0
- brfiscal/_texto.py +61 -0
- brfiscal/cest.py +155 -0
- brfiscal/contrib/__init__.py +0 -0
- brfiscal/contrib/django/__init__.py +5 -0
- brfiscal/contrib/django/admin.py +28 -0
- brfiscal/contrib/django/apps.py +8 -0
- brfiscal/contrib/django/carga.py +81 -0
- brfiscal/contrib/django/fields.py +33 -0
- brfiscal/contrib/django/management/__init__.py +0 -0
- brfiscal/contrib/django/management/commands/__init__.py +0 -0
- brfiscal/contrib/django/management/commands/brfiscal_carregar.py +48 -0
- brfiscal/contrib/django/migrations/0001_initial.py +112 -0
- brfiscal/contrib/django/migrations/__init__.py +0 -0
- brfiscal/contrib/django/models.py +75 -0
- brfiscal/contrib/django/validators.py +58 -0
- brfiscal/dados/cest.json.gz +0 -0
- brfiscal/dados/ncm.json.gz +0 -0
- brfiscal/fontes/__init__.py +0 -0
- brfiscal/fontes/cest.py +192 -0
- brfiscal/fontes/ncm.py +96 -0
- brfiscal/ncm.py +142 -0
- brfiscal/py.typed +0 -0
- brfiscal-0.1.0.dist-info/METADATA +209 -0
- brfiscal-0.1.0.dist-info/RECORD +32 -0
- brfiscal-0.1.0.dist-info/WHEEL +5 -0
- brfiscal-0.1.0.dist-info/entry_points.txt +2 -0
- brfiscal-0.1.0.dist-info/licenses/LICENSE +21 -0
- brfiscal-0.1.0.dist-info/top_level.txt +1 -0
brfiscal/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""brfiscal - tabelas fiscais brasileiras com espelho local versionado.
|
|
2
|
+
|
|
3
|
+
Tabelas disponíveis: :mod:`brfiscal.ncm`, :mod:`brfiscal.cest`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from importlib.metadata import PackageNotFoundError
|
|
7
|
+
from importlib.metadata import version as _version
|
|
8
|
+
|
|
9
|
+
from . import cest, ncm
|
|
10
|
+
from ._tabela import DadosIndisponiveis, Metadados, Resultado, configurar
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
__version__ = _version("brfiscal")
|
|
14
|
+
except PackageNotFoundError: # rodando direto do código-fonte, sem instalar
|
|
15
|
+
__version__ = "0.0.0"
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"DadosIndisponiveis",
|
|
19
|
+
"Metadados",
|
|
20
|
+
"Resultado",
|
|
21
|
+
"__version__",
|
|
22
|
+
"cest",
|
|
23
|
+
"configurar",
|
|
24
|
+
"ncm",
|
|
25
|
+
]
|
brfiscal/__main__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Linha de comando: ``brfiscal info``, ``brfiscal atualizar ncm``, ``brfiscal buscar ncm "x"``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import DadosIndisponiveis, cest, ncm
|
|
10
|
+
from ._tabela import diretorio_dados
|
|
11
|
+
|
|
12
|
+
TABELAS = {"ncm": ncm, "cest": cest}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _info() -> int:
|
|
16
|
+
for nome, mod in TABELAS.items():
|
|
17
|
+
try:
|
|
18
|
+
m = mod.metadados()
|
|
19
|
+
print(f"{nome}: {m.total} itens, vigente em {m.vigencia} ({m.ato}) - {m.fonte}")
|
|
20
|
+
except DadosIndisponiveis:
|
|
21
|
+
print(f"{nome}: sem dados (rode `brfiscal atualizar {nome}`)")
|
|
22
|
+
return 0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _atualizar(args: argparse.Namespace) -> int:
|
|
26
|
+
destino = Path(args.destino) if args.destino else diretorio_dados()
|
|
27
|
+
if destino is None:
|
|
28
|
+
print("Informe --destino ou defina BRFISCAL_DADOS.", file=sys.stderr)
|
|
29
|
+
return 2
|
|
30
|
+
if args.tabela == "ncm":
|
|
31
|
+
from .fontes import ncm as fonte
|
|
32
|
+
|
|
33
|
+
arquivo = fonte.atualizar(destino, Path(args.origem) if args.origem else None)
|
|
34
|
+
else:
|
|
35
|
+
from .fontes import cest as fonte_cest
|
|
36
|
+
|
|
37
|
+
origem = Path(args.origem) if args.origem else None
|
|
38
|
+
if origem and origem.suffix.lower() == ".csv":
|
|
39
|
+
arquivo = fonte_cest.atualizar_de_csv(destino, origem)
|
|
40
|
+
else:
|
|
41
|
+
arquivo = fonte_cest.atualizar(destino, origem)
|
|
42
|
+
print(f"Gravado {arquivo}")
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _buscar(args: argparse.Namespace) -> int:
|
|
47
|
+
for r in TABELAS[args.tabela].buscar(args.texto, limite=args.limite):
|
|
48
|
+
item = r.item
|
|
49
|
+
print(f"{item.codigo_formatado:<12} {r.pontuacao:>5.2f} {item.descricao}")
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main(argv: list[str] | None = None) -> int:
|
|
54
|
+
p = argparse.ArgumentParser(prog="brfiscal")
|
|
55
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
56
|
+
sub.add_parser("info", help="mostra versão/vigência dos espelhos")
|
|
57
|
+
a = sub.add_parser("atualizar", help="baixa a tabela oficial e grava o espelho")
|
|
58
|
+
a.add_argument("tabela", choices=sorted(TABELAS))
|
|
59
|
+
a.add_argument("--destino", help="diretório de saída (padrão: $BRFISCAL_DADOS)")
|
|
60
|
+
a.add_argument("--origem", help="arquivo local em vez de baixar")
|
|
61
|
+
b = sub.add_parser("buscar", help="busca por descrição")
|
|
62
|
+
b.add_argument("tabela", choices=sorted(TABELAS))
|
|
63
|
+
b.add_argument("texto")
|
|
64
|
+
b.add_argument("--limite", type=int, default=10)
|
|
65
|
+
args = p.parse_args(argv)
|
|
66
|
+
if args.cmd == "info":
|
|
67
|
+
return _info()
|
|
68
|
+
if args.cmd == "atualizar":
|
|
69
|
+
return _atualizar(args)
|
|
70
|
+
return _buscar(args)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
raise SystemExit(main())
|
brfiscal/_sinonimos.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Sinônimos para aproximar o nome comercial do produto do texto da NCM.
|
|
2
|
+
|
|
3
|
+
O texto oficial da NCM é técnico ("águas gaseificadas adicionadas de açúcar") e o
|
|
4
|
+
nome no cadastro é comercial ("refrigerante"). Esta lista é um ponto de partida,
|
|
5
|
+
focado em varejo alimentar; contribuições são bem-vindas (veja CONTRIBUTING.md).
|
|
6
|
+
|
|
7
|
+
Chave: termo como o usuário escreve (sem acento, minúsculo).
|
|
8
|
+
Valor: palavras que aparecem no texto oficial da NCM.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
NCM: dict[str, str] = {
|
|
12
|
+
"refrigerante": "aguas gaseificadas adicionadas acucar aromatizadas",
|
|
13
|
+
"refri": "aguas gaseificadas adicionadas acucar aromatizadas",
|
|
14
|
+
"suco": "sucos frutas",
|
|
15
|
+
"leite condensado": "leite concentrados adicionados acucar",
|
|
16
|
+
"arroz branco": "arroz branqueado polido",
|
|
17
|
+
"sabao po": "preparacoes lavagem",
|
|
18
|
+
"lava roupa": "preparacoes lavagem",
|
|
19
|
+
"mussarela": "queijos frescos",
|
|
20
|
+
"muçarela": "queijos frescos",
|
|
21
|
+
"requeijao": "queijos fundidos",
|
|
22
|
+
"iogurte": "iogurte leitelho fermentados",
|
|
23
|
+
"sabao": "saboes",
|
|
24
|
+
"detergente": "agentes organicos superficie preparacoes tensoativas",
|
|
25
|
+
"amaciante": "preparacoes amaciamento",
|
|
26
|
+
"biscoito": "bolachas biscoitos",
|
|
27
|
+
"bolacha": "bolachas biscoitos",
|
|
28
|
+
"recheado": "bolachas biscoitos",
|
|
29
|
+
"salgadinho": "produtos obtidos expansao torrefacao",
|
|
30
|
+
"macarrao": "massas alimenticias",
|
|
31
|
+
"miojo": "massas alimenticias",
|
|
32
|
+
"cafe": "cafe torrado",
|
|
33
|
+
"achocolatado": "preparacoes contendo cacau",
|
|
34
|
+
"margarina": "margarina",
|
|
35
|
+
"manteiga": "manteiga",
|
|
36
|
+
"salsicha": "enchidos",
|
|
37
|
+
"linguica": "enchidos",
|
|
38
|
+
"mortadela": "enchidos",
|
|
39
|
+
"presunto": "pernas pas pedacos",
|
|
40
|
+
"frango": "galos galinhas",
|
|
41
|
+
"carne": "carnes bovinos",
|
|
42
|
+
"alcatra": "carnes bovinos desossadas",
|
|
43
|
+
"picanha": "carnes bovinos desossadas",
|
|
44
|
+
"fralda": "fraldas",
|
|
45
|
+
"absorvente": "absorventes",
|
|
46
|
+
"shampoo": "xampus",
|
|
47
|
+
"xampu": "xampus",
|
|
48
|
+
"desodorante": "desodorantes",
|
|
49
|
+
"creme dental": "dentifricios",
|
|
50
|
+
"pasta dental": "dentifricios",
|
|
51
|
+
"pao": "paes",
|
|
52
|
+
"cerveja": "cervejas malte",
|
|
53
|
+
"vinho": "vinhos uvas frescas",
|
|
54
|
+
"cachaca": "cachaca",
|
|
55
|
+
"agua mineral": "aguas minerais",
|
|
56
|
+
"oleo": "oleo",
|
|
57
|
+
"azeite": "azeite oliva",
|
|
58
|
+
"acucar": "acucar cana",
|
|
59
|
+
"sal": "sal",
|
|
60
|
+
"farinha": "farinhas",
|
|
61
|
+
"fuba": "farinha milho",
|
|
62
|
+
"racao": "preparacoes utilizadas alimentacao animais",
|
|
63
|
+
}
|
brfiscal/_tabela.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Infraestrutura comum a todas as tabelas: carga do espelho, metadados e busca."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import gzip
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
from collections.abc import Callable, Iterator
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from importlib import resources
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Generic, TypeVar
|
|
15
|
+
|
|
16
|
+
from ._texto import STOPWORDS, normalizar, tokens
|
|
17
|
+
|
|
18
|
+
T = TypeVar("T")
|
|
19
|
+
|
|
20
|
+
#: Variável de ambiente com um diretório de espelhos atualizados
|
|
21
|
+
#: (gerados por ``brfiscal atualizar``). Se o arquivo da tabela existir lá,
|
|
22
|
+
#: ele tem prioridade sobre o espelho embutido no pacote.
|
|
23
|
+
ENV_DIRETORIO = "BRFISCAL_DADOS"
|
|
24
|
+
|
|
25
|
+
_diretorio_dados: Path | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DadosIndisponiveis(RuntimeError):
|
|
29
|
+
"""O espelho da tabela não está embutido nem foi baixado."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def configurar(diretorio: str | os.PathLike[str] | None) -> None:
|
|
33
|
+
"""Define (ou limpa, com ``None``) o diretório de espelhos atualizados."""
|
|
34
|
+
global _diretorio_dados
|
|
35
|
+
_diretorio_dados = Path(diretorio) if diretorio is not None else None
|
|
36
|
+
for tabela in _REGISTRO.values():
|
|
37
|
+
tabela.recarregar()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def diretorio_dados() -> Path | None:
|
|
41
|
+
if _diretorio_dados is not None:
|
|
42
|
+
return _diretorio_dados
|
|
43
|
+
env = os.environ.get(ENV_DIRETORIO)
|
|
44
|
+
return Path(env) if env else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Metadados:
|
|
49
|
+
"""De onde veio o espelho e a partir de quando vale."""
|
|
50
|
+
|
|
51
|
+
tabela: str
|
|
52
|
+
fonte: str
|
|
53
|
+
vigencia: str
|
|
54
|
+
ato: str = ""
|
|
55
|
+
gerado_em: str = ""
|
|
56
|
+
total: int = 0
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def de_dict(cls, dados: dict[str, Any]) -> Metadados:
|
|
60
|
+
campos = {k: dados[k] for k in cls.__dataclass_fields__ if k in dados}
|
|
61
|
+
return cls(**campos)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Resultado(Generic[T]):
|
|
66
|
+
"""Um item encontrado na busca, com pontuação de 0 a 1 (relativa à consulta)."""
|
|
67
|
+
|
|
68
|
+
item: T
|
|
69
|
+
pontuacao: float
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def ler_espelho(arquivo: Path) -> dict[str, Any]:
|
|
73
|
+
with gzip.open(arquivo, "rt", encoding="utf-8") as fh:
|
|
74
|
+
return json.load(fh)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def gravar_espelho(arquivo: Path, meta: dict[str, Any], itens: list[dict[str, Any]]) -> Path:
|
|
78
|
+
arquivo.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
meta = {**meta, "total": len(itens)}
|
|
80
|
+
with gzip.open(arquivo, "wt", encoding="utf-8", compresslevel=9) as fh:
|
|
81
|
+
json.dump({"meta": meta, "itens": itens}, fh, ensure_ascii=False, separators=(",", ":"))
|
|
82
|
+
return arquivo
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_REGISTRO: dict[str, Tabela[Any]] = {}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class Tabela(Generic[T]):
|
|
89
|
+
"""Tabela carregada sob demanda a partir de um espelho ``<nome>.json.gz``."""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
nome: str,
|
|
94
|
+
fabrica: Callable[[dict[str, Any]], T],
|
|
95
|
+
chave: Callable[[T], str],
|
|
96
|
+
texto_busca: Callable[[T], list[tuple[str, float]]],
|
|
97
|
+
filtro_busca: Callable[[T], bool] | None = None,
|
|
98
|
+
sinonimos: dict[str, str] | None = None,
|
|
99
|
+
) -> None:
|
|
100
|
+
self.nome = nome
|
|
101
|
+
self._fabrica = fabrica
|
|
102
|
+
self._chave = chave
|
|
103
|
+
self._texto_busca = texto_busca
|
|
104
|
+
self._filtro_busca = filtro_busca
|
|
105
|
+
self._sinonimos = {normalizar(k): v for k, v in (sinonimos or {}).items()}
|
|
106
|
+
self._itens: dict[str, T] | None = None
|
|
107
|
+
self._meta: Metadados | None = None
|
|
108
|
+
self._indice: dict[str, dict[str, float]] | None = None
|
|
109
|
+
self._vocab: list[str] = []
|
|
110
|
+
_REGISTRO[nome] = self
|
|
111
|
+
|
|
112
|
+
# carga ---------------------------------------------------------------
|
|
113
|
+
@property
|
|
114
|
+
def arquivo(self) -> Path:
|
|
115
|
+
externo = diretorio_dados()
|
|
116
|
+
if externo is not None and (externo / f"{self.nome}.json.gz").exists():
|
|
117
|
+
return externo / f"{self.nome}.json.gz"
|
|
118
|
+
return Path(str(resources.files("brfiscal") / "dados" / f"{self.nome}.json.gz"))
|
|
119
|
+
|
|
120
|
+
def recarregar(self) -> None:
|
|
121
|
+
self._itens = None
|
|
122
|
+
self._meta = None
|
|
123
|
+
self._indice = None
|
|
124
|
+
|
|
125
|
+
def _carregar(self) -> dict[str, T]:
|
|
126
|
+
if self._itens is None:
|
|
127
|
+
arquivo = self.arquivo
|
|
128
|
+
if not arquivo.exists():
|
|
129
|
+
raise DadosIndisponiveis(
|
|
130
|
+
f"Espelho da tabela {self.nome!r} não encontrado. "
|
|
131
|
+
f"Rode `brfiscal atualizar {self.nome}`."
|
|
132
|
+
)
|
|
133
|
+
bruto = ler_espelho(arquivo)
|
|
134
|
+
self._meta = Metadados.de_dict(bruto["meta"])
|
|
135
|
+
itens = (self._fabrica(d) for d in bruto["itens"])
|
|
136
|
+
self._itens = {self._chave(i): i for i in itens}
|
|
137
|
+
return self._itens
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def metadados(self) -> Metadados:
|
|
141
|
+
self._carregar()
|
|
142
|
+
assert self._meta is not None
|
|
143
|
+
return self._meta
|
|
144
|
+
|
|
145
|
+
def __iter__(self) -> Iterator[T]:
|
|
146
|
+
return iter(self._carregar().values())
|
|
147
|
+
|
|
148
|
+
def __len__(self) -> int:
|
|
149
|
+
return len(self._carregar())
|
|
150
|
+
|
|
151
|
+
def obter(self, chave: str) -> T | None:
|
|
152
|
+
return self._carregar().get(chave)
|
|
153
|
+
|
|
154
|
+
# busca ---------------------------------------------------------------
|
|
155
|
+
def _montar_indice(self) -> dict[str, dict[str, float]]:
|
|
156
|
+
if self._indice is None:
|
|
157
|
+
indice: dict[str, dict[str, float]] = defaultdict(dict)
|
|
158
|
+
for item in self._carregar().values():
|
|
159
|
+
if self._filtro_busca and not self._filtro_busca(item):
|
|
160
|
+
continue
|
|
161
|
+
chave = self._chave(item)
|
|
162
|
+
for texto, peso in self._texto_busca(item):
|
|
163
|
+
for tok in tokens(texto):
|
|
164
|
+
atual = indice[tok].get(chave, 0.0)
|
|
165
|
+
indice[tok][chave] = max(atual, peso)
|
|
166
|
+
self._indice = dict(indice)
|
|
167
|
+
self._vocab = sorted(self._indice)
|
|
168
|
+
return self._indice
|
|
169
|
+
|
|
170
|
+
def _expandir(self, tok: str) -> list[tuple[str, float]]:
|
|
171
|
+
"""Termo exato, ou termos que começam com ele (abreviações: 'bisc' -> 'biscoito')."""
|
|
172
|
+
indice = self._montar_indice()
|
|
173
|
+
if tok in indice:
|
|
174
|
+
return [(tok, 1.0)]
|
|
175
|
+
if len(tok) < 3:
|
|
176
|
+
return []
|
|
177
|
+
from bisect import bisect_left
|
|
178
|
+
|
|
179
|
+
i = bisect_left(self._vocab, tok)
|
|
180
|
+
saida = []
|
|
181
|
+
while i < len(self._vocab) and self._vocab[i].startswith(tok):
|
|
182
|
+
saida.append((self._vocab[i], 0.8))
|
|
183
|
+
i += 1
|
|
184
|
+
return saida
|
|
185
|
+
|
|
186
|
+
def _consulta(self, texto: str) -> list[list[tuple[list[str], float]]]:
|
|
187
|
+
"""Cada palavra da consulta vira um grupo de alternativas.
|
|
188
|
+
|
|
189
|
+
Uma alternativa é uma lista de termos que precisam aparecer *todos* no item
|
|
190
|
+
(a própria palavra, ou a expressão sinônima, com peso menor). Sinônimos de
|
|
191
|
+
duas palavras ("creme dental") substituem as duas.
|
|
192
|
+
"""
|
|
193
|
+
palavras = [p for p in normalizar(texto).split() if p not in STOPWORDS]
|
|
194
|
+
grupos: list[list[tuple[list[str], float]]] = []
|
|
195
|
+
i = 0
|
|
196
|
+
while i < len(palavras):
|
|
197
|
+
par = " ".join(palavras[i : i + 2])
|
|
198
|
+
if i + 1 < len(palavras) and par in self._sinonimos:
|
|
199
|
+
grupos.append([(tokens(self._sinonimos[par]), 0.9)])
|
|
200
|
+
i += 2
|
|
201
|
+
continue
|
|
202
|
+
proprios = tokens(palavras[i])
|
|
203
|
+
if proprios:
|
|
204
|
+
grupo = [(proprios, 1.0)]
|
|
205
|
+
if extra := self._sinonimos.get(palavras[i]):
|
|
206
|
+
grupo.append((tokens(extra), 0.9))
|
|
207
|
+
grupos.append(grupo)
|
|
208
|
+
i += 1
|
|
209
|
+
unicos: list[list[tuple[list[str], float]]] = []
|
|
210
|
+
for g in grupos:
|
|
211
|
+
if g not in unicos:
|
|
212
|
+
unicos.append(g)
|
|
213
|
+
return unicos
|
|
214
|
+
|
|
215
|
+
def _casar(self, termos: list[str]) -> dict[str, float]:
|
|
216
|
+
"""Itens que contêm todos os termos (com expansão por prefixo) e seu peso."""
|
|
217
|
+
indice = self._montar_indice()
|
|
218
|
+
resultado: dict[str, float] | None = None
|
|
219
|
+
for termo in termos:
|
|
220
|
+
atual: dict[str, float] = {}
|
|
221
|
+
for t, fator in self._expandir(termo):
|
|
222
|
+
for chave, peso in indice[t].items():
|
|
223
|
+
atual[chave] = max(atual.get(chave, 0.0), peso * fator)
|
|
224
|
+
if resultado is None:
|
|
225
|
+
resultado = atual
|
|
226
|
+
else:
|
|
227
|
+
resultado = {c: min(v, atual[c]) for c, v in resultado.items() if c in atual}
|
|
228
|
+
if not resultado:
|
|
229
|
+
return {}
|
|
230
|
+
return resultado or {}
|
|
231
|
+
|
|
232
|
+
def buscar(self, texto: str, limite: int = 10) -> list[Resultado[T]]:
|
|
233
|
+
"""Busca por descrição (ex.: nome do produto). Retorna sugestões, não verdade absoluta."""
|
|
234
|
+
consulta = self._consulta(texto)
|
|
235
|
+
if not consulta:
|
|
236
|
+
return []
|
|
237
|
+
total = max(len(self._carregar()), 1)
|
|
238
|
+
pontos: dict[str, float] = defaultdict(float)
|
|
239
|
+
maximo = 0.0
|
|
240
|
+
for grupo in consulta:
|
|
241
|
+
melhor: dict[str, float] = {}
|
|
242
|
+
for termos, fator in grupo:
|
|
243
|
+
for chave, peso in self._casar(termos).items():
|
|
244
|
+
melhor[chave] = max(melhor.get(chave, 0.0), peso * fator)
|
|
245
|
+
if not melhor:
|
|
246
|
+
continue # palavra desconhecida (marca, gramatura): não penaliza
|
|
247
|
+
idf = math.log(1 + total / len(melhor))
|
|
248
|
+
maximo += idf
|
|
249
|
+
for chave, valor in melhor.items():
|
|
250
|
+
pontos[chave] += valor * idf
|
|
251
|
+
if not pontos or maximo == 0:
|
|
252
|
+
return []
|
|
253
|
+
itens = self._carregar()
|
|
254
|
+
ordenados = sorted(pontos.items(), key=lambda kv: (-kv[1], kv[0]))[:limite]
|
|
255
|
+
return [Resultado(itens[c], round(p / maximo, 4)) for c, p in ordenados]
|
brfiscal/_texto.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Normalização de texto para busca (sem dependências externas)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
|
|
8
|
+
_HTML = re.compile(r"<[^>]+>")
|
|
9
|
+
_NAO_ALFANUM = re.compile(r"[^a-z0-9]+")
|
|
10
|
+
# Pesos/medidas típicos de nome de produto: 140G, 1,5L, 2KG, 500ML, 12UN, 6X1L
|
|
11
|
+
_MEDIDA = re.compile(r"^\d+([.,]\d+)?(x\d+)?(g|gr|kg|mg|ml|l|lt|un|und|cx|pct|m|cm|mm)?$")
|
|
12
|
+
|
|
13
|
+
STOPWORDS = frozenset(
|
|
14
|
+
"a as o os de da das do dos e em no na nos nas com sem para por ou um uma "
|
|
15
|
+
"ao aos que se seu sua the of and".split()
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def remover_html(texto: str) -> str:
|
|
20
|
+
return _HTML.sub("", texto)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sem_acentos(texto: str) -> str:
|
|
24
|
+
nfkd = unicodedata.normalize("NFKD", texto)
|
|
25
|
+
return "".join(c for c in nfkd if not unicodedata.combining(c))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalizar(texto: str) -> str:
|
|
29
|
+
"""Minúsculas, sem acento, sem HTML e só com letras/números separados por espaço."""
|
|
30
|
+
texto = sem_acentos(remover_html(texto)).lower()
|
|
31
|
+
return _NAO_ALFANUM.sub(" ", texto).strip()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def radical(palavra: str) -> str:
|
|
35
|
+
"""Stemming bem simples de plural em português (biscoitos -> biscoito, paes -> pao)."""
|
|
36
|
+
if len(palavra) <= 3:
|
|
37
|
+
return palavra
|
|
38
|
+
for sufixo, troca in (
|
|
39
|
+
("oes", "ao"),
|
|
40
|
+
("aes", "ao"),
|
|
41
|
+
("ais", "al"),
|
|
42
|
+
("eis", "el"),
|
|
43
|
+
("res", "r"),
|
|
44
|
+
("zes", "z"),
|
|
45
|
+
("ns", "m"),
|
|
46
|
+
):
|
|
47
|
+
if palavra.endswith(sufixo) and len(palavra) > len(sufixo):
|
|
48
|
+
return palavra[: -len(sufixo)] + troca
|
|
49
|
+
if palavra.endswith("s") and not palavra.endswith("ss"):
|
|
50
|
+
return palavra[:-1]
|
|
51
|
+
return palavra
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def tokens(texto: str) -> list[str]:
|
|
55
|
+
"""Quebra o texto em radicais úteis para busca, ignorando stopwords e medidas."""
|
|
56
|
+
saida = []
|
|
57
|
+
for palavra in normalizar(texto).split():
|
|
58
|
+
if palavra in STOPWORDS or _MEDIDA.match(palavra) or len(palavra) < 2:
|
|
59
|
+
continue
|
|
60
|
+
saida.append(radical(palavra))
|
|
61
|
+
return saida
|
brfiscal/cest.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""CEST - Código Especificador da Substituição Tributária (Convênio ICMS 142/2018).
|
|
2
|
+
|
|
3
|
+
O CEST tem 7 dígitos: ``SS.III.DD`` (segmento, item, especificação). Cada CEST lista
|
|
4
|
+
NCMs (às vezes só o início do código, como ``1905`` ou ``1905.31``). Por isso a
|
|
5
|
+
relação NCM -> CEST é de **um para muitos**: um mesmo NCM pode ter vários CESTs, e
|
|
6
|
+
quem escolhe é a descrição do produto. A lib sugere; o usuário confirma.
|
|
7
|
+
|
|
8
|
+
Exemplo::
|
|
9
|
+
|
|
10
|
+
from brfiscal import cest
|
|
11
|
+
|
|
12
|
+
cest.para_ncm("19053100") # CESTs possíveis para o NCM
|
|
13
|
+
cest.validar_par("19053100", "1705700")
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from enum import Enum
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from ._tabela import Metadados, Resultado, Tabela
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"Cest",
|
|
27
|
+
"SituacaoPar",
|
|
28
|
+
"ValidacaoPar",
|
|
29
|
+
"buscar",
|
|
30
|
+
"formatar",
|
|
31
|
+
"limpar",
|
|
32
|
+
"metadados",
|
|
33
|
+
"obter",
|
|
34
|
+
"para_ncm",
|
|
35
|
+
"validar",
|
|
36
|
+
"validar_par",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
_SO_DIGITOS = re.compile(r"\D")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Cest:
|
|
44
|
+
codigo: str
|
|
45
|
+
"""7 dígitos."""
|
|
46
|
+
descricao: str
|
|
47
|
+
segmento: str
|
|
48
|
+
"""Nome do segmento (anexo), ex.: ``Produtos alimentícios``."""
|
|
49
|
+
ncms: tuple[str, ...]
|
|
50
|
+
"""NCMs/prefixos de NCM listados para o CEST (só dígitos)."""
|
|
51
|
+
item: str = ""
|
|
52
|
+
"""Número do item no anexo (ex.: ``17.0``)."""
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def codigo_formatado(self) -> str:
|
|
56
|
+
return formatar(self.codigo)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def codigo_segmento(self) -> str:
|
|
60
|
+
return self.codigo[:2]
|
|
61
|
+
|
|
62
|
+
def aceita_ncm(self, ncm: str) -> bool:
|
|
63
|
+
ncm = limpar(ncm)
|
|
64
|
+
return any(ncm.startswith(p) for p in self.ncms)
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def de_dict(cls, d: dict[str, Any]) -> Cest:
|
|
68
|
+
return cls(
|
|
69
|
+
codigo=d["c"],
|
|
70
|
+
descricao=d["d"],
|
|
71
|
+
segmento=d.get("s", ""),
|
|
72
|
+
ncms=tuple(d.get("n", ())),
|
|
73
|
+
item=d.get("it", ""),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class SituacaoPar(str, Enum):
|
|
78
|
+
OK = "ok"
|
|
79
|
+
"""O CEST lista esse NCM."""
|
|
80
|
+
CEST_INEXISTENTE = "cest_inexistente"
|
|
81
|
+
NCM_NAO_LISTADO = "ncm_nao_listado"
|
|
82
|
+
"""O CEST existe, mas não lista esse NCM."""
|
|
83
|
+
SEM_CEST = "sem_cest"
|
|
84
|
+
"""Nenhum CEST foi informado e o NCM não aparece em nenhum CEST (esperado)."""
|
|
85
|
+
CEST_FALTANDO = "cest_faltando"
|
|
86
|
+
"""Nenhum CEST informado, mas o NCM aparece em algum CEST: confirmar com o produto."""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class ValidacaoPar:
|
|
91
|
+
situacao: SituacaoPar
|
|
92
|
+
sugestoes: tuple[Cest, ...] = ()
|
|
93
|
+
"""CESTs que listam o NCM (para o usuário escolher pela descrição)."""
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def ok(self) -> bool:
|
|
97
|
+
return self.situacao in (SituacaoPar.OK, SituacaoPar.SEM_CEST)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_tabela: Tabela[Cest] = Tabela(
|
|
101
|
+
"cest",
|
|
102
|
+
fabrica=Cest.de_dict,
|
|
103
|
+
chave=lambda c: c.codigo,
|
|
104
|
+
texto_busca=lambda c: [(c.descricao, 1.0), (c.segmento, 0.3)],
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def limpar(codigo: str | int) -> str:
|
|
109
|
+
return _SO_DIGITOS.sub("", str(codigo))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def formatar(codigo: str | int) -> str:
|
|
113
|
+
"""``1705700`` -> ``17.057.00``."""
|
|
114
|
+
c = limpar(codigo)
|
|
115
|
+
return f"{c[:2]}.{c[2:5]}.{c[5:]}" if len(c) == 7 else c
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def obter(codigo: str | int) -> Cest | None:
|
|
119
|
+
return _tabela.obter(limpar(codigo))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def validar(codigo: str | int) -> bool:
|
|
123
|
+
return obter(codigo) is not None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def para_ncm(ncm: str | int) -> list[Cest]:
|
|
127
|
+
"""CESTs cujo anexo lista o NCM (pelo código completo ou por prefixo)."""
|
|
128
|
+
n = limpar(ncm)
|
|
129
|
+
return [c for c in _tabela if c.aceita_ncm(n)]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validar_par(ncm: str | int, cest: str | int | None) -> ValidacaoPar:
|
|
133
|
+
"""Confere se o CEST informado é compatível com o NCM."""
|
|
134
|
+
possiveis = tuple(para_ncm(ncm))
|
|
135
|
+
if not cest or not limpar(cest):
|
|
136
|
+
situacao = SituacaoPar.CEST_FALTANDO if possiveis else SituacaoPar.SEM_CEST
|
|
137
|
+
return ValidacaoPar(situacao, possiveis)
|
|
138
|
+
item = obter(cest)
|
|
139
|
+
if item is None:
|
|
140
|
+
return ValidacaoPar(SituacaoPar.CEST_INEXISTENTE, possiveis)
|
|
141
|
+
if item.aceita_ncm(limpar(ncm)):
|
|
142
|
+
return ValidacaoPar(SituacaoPar.OK, possiveis)
|
|
143
|
+
return ValidacaoPar(SituacaoPar.NCM_NAO_LISTADO, possiveis)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def buscar(texto: str, limite: int = 10) -> list[Resultado[Cest]]:
|
|
147
|
+
return _tabela.buscar(texto, limite=limite)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def metadados() -> Metadados:
|
|
151
|
+
return _tabela.metadados
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def tabela() -> Tabela[Cest]:
|
|
155
|
+
return _tabela
|
|
File without changes
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from django.contrib import admin
|
|
2
|
+
|
|
3
|
+
from .models import Cest, CestNcm, Ncm, VersaoTabela
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@admin.register(Ncm)
|
|
7
|
+
class NcmAdmin(admin.ModelAdmin):
|
|
8
|
+
list_display = ["codigo", "descricao", "ativo"]
|
|
9
|
+
list_filter = ["ativo"]
|
|
10
|
+
search_fields = ["codigo", "descricao_completa"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CestNcmInline(admin.TabularInline):
|
|
14
|
+
model = CestNcm
|
|
15
|
+
extra = 0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@admin.register(Cest)
|
|
19
|
+
class CestAdmin(admin.ModelAdmin):
|
|
20
|
+
list_display = ["codigo", "descricao", "segmento", "ativo"]
|
|
21
|
+
list_filter = ["segmento", "ativo"]
|
|
22
|
+
search_fields = ["codigo", "descricao", "ncms__ncm_prefixo"]
|
|
23
|
+
inlines = [CestNcmInline]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@admin.register(VersaoTabela)
|
|
27
|
+
class VersaoTabelaAdmin(admin.ModelAdmin):
|
|
28
|
+
list_display = ["tabela", "vigencia", "ato", "total", "carregada_em"]
|