validator-documents 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.
@@ -0,0 +1,77 @@
1
+ """validator-documents: Validação e formatação de documentos brasileiros.
2
+
3
+ Documentos suportados:
4
+ - CPF
5
+ - CNPJ
6
+ - PIS/NIS/PASEP/NIT
7
+ - Título Eleitoral
8
+ - CNH
9
+ - RENAVAM
10
+ - Placa veicular (antigo e Mercosul)
11
+ """
12
+
13
+ from .cnh import formatar_cnh, gerar_cnh, validar_cnh
14
+ from .cnpj import formatar_cnpj, gerar_cnpj, validar_cnpj
15
+ from .cpf import formatar_cpf, gerar_cpf, validar_cpf
16
+ from .exceptions import DocumentoError, DocumentoInvalido, DocumentoNaoIdentificado
17
+ from .models import (
18
+ CNH,
19
+ CNPJ,
20
+ CPF,
21
+ PIS,
22
+ Placa,
23
+ Renavam,
24
+ TituloEleitoral,
25
+ )
26
+ from .pis import formatar_pis, gerar_pis, validar_pis
27
+ from .placa import formatar_placa, gerar_placa, validar_placa
28
+ from .renavam import formatar_renavam, gerar_renavam, validar_renavam
29
+ from .titulo_eleitoral import (
30
+ formatar_titulo_eleitoral,
31
+ gerar_titulo_eleitoral,
32
+ validar_titulo_eleitoral,
33
+ )
34
+ from .validar import TipoDocumento, identificar_documento, validar_documento
35
+
36
+ __all__ = [
37
+ # Funções funcionais por tipo
38
+ "validar_cpf",
39
+ "formatar_cpf",
40
+ "gerar_cpf",
41
+ "validar_cnpj",
42
+ "formatar_cnpj",
43
+ "gerar_cnpj",
44
+ "validar_pis",
45
+ "formatar_pis",
46
+ "gerar_pis",
47
+ "validar_titulo_eleitoral",
48
+ "formatar_titulo_eleitoral",
49
+ "gerar_titulo_eleitoral",
50
+ "validar_cnh",
51
+ "formatar_cnh",
52
+ "gerar_cnh",
53
+ "validar_renavam",
54
+ "formatar_renavam",
55
+ "gerar_renavam",
56
+ "validar_placa",
57
+ "formatar_placa",
58
+ "gerar_placa",
59
+ # Despacho genérico
60
+ "validar_documento",
61
+ "identificar_documento",
62
+ "TipoDocumento",
63
+ # Modelos Pydantic
64
+ "CPF",
65
+ "CNPJ",
66
+ "PIS",
67
+ "TituloEleitoral",
68
+ "CNH",
69
+ "Renavam",
70
+ "Placa",
71
+ # Exceções
72
+ "DocumentoError",
73
+ "DocumentoInvalido",
74
+ "DocumentoNaoIdentificado",
75
+ ]
76
+
77
+ __version__ = "0.1.0"
@@ -0,0 +1,23 @@
1
+ """Utilitários compartilhados pelos validadores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+
8
+ def normalizar(dado: str | int) -> str:
9
+ """Remove todos os caracteres que não são dígitos.
10
+
11
+ Aceita ``str`` (com ou sem máscara) ou ``int``. Retorna a sequência de
12
+ dígitos como ``str``.
13
+ """
14
+ if isinstance(dado, str):
15
+ return re.sub(r"\D", "", dado)
16
+ if isinstance(dado, int):
17
+ return str(dado)
18
+ raise ValueError("O dado deve ser uma string ou um número inteiro.")
19
+
20
+
21
+ def tem_digitos_repetidos(digitos: str) -> bool:
22
+ """Indica se todos os dígitos são iguais (ex.: ``11111111111``)."""
23
+ return len(set(digitos)) == 1
@@ -0,0 +1,67 @@
1
+ """Validação e formatação de CNH (Carteira Nacional de Habilitação).
2
+
3
+ Algoritmo oficial (baseado em validate-docbr e legislação):
4
+ - 11 dígitos; 9 primeiros são o registro, 2 últimos são DVs.
5
+ - Primeiro DV: pesos 9..1 sobre os 9 primeiros dígitos, módulo 11.
6
+ Se resto >= 10 → DV = 0 e _dsc = 2; caso contrário _dsc = 0.
7
+ - Segundo DV: pesos 1..9 sobre os 9 primeiros dígitos, módulo 11.
8
+ DV = resto - _dsc; se < 0 → +11; se >= 10 → 0.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from ._utils import normalizar, tem_digitos_repetidos
14
+
15
+ _TAMANHO = 11
16
+
17
+
18
+ def _primeiro_dv(digitos: str) -> tuple[int, int]:
19
+ """Calcula primeiro DV e retorna (dv, _dsc)."""
20
+ total = sum(int(d) * w for d, w in zip(digitos[:9], range(9, 0, -1), strict=False))
21
+ resto = total % 11
22
+ if resto >= 10:
23
+ return 0, 2
24
+ return resto, 0
25
+
26
+
27
+ def _segundo_dv(digitos: str, dsc: int) -> int:
28
+ total = sum(int(d) * w for d, w in zip(digitos[:9], range(1, 10), strict=False))
29
+ resto = total % 11
30
+ dv = resto - dsc
31
+ if dv < 0:
32
+ dv += 11
33
+ if dv >= 10:
34
+ return 0
35
+ return dv
36
+
37
+
38
+ def validar_cnh(cnh: str | int) -> bool:
39
+ """Valida uma CNH pelos dois dígitos verificadores."""
40
+ cnh = normalizar(cnh)
41
+ if len(cnh) != _TAMANHO or tem_digitos_repetidos(cnh):
42
+ return False
43
+
44
+ primeiro, dsc = _primeiro_dv(cnh)
45
+ segundo = _segundo_dv(cnh, dsc)
46
+ return cnh[-2:] == f"{primeiro}{segundo}"
47
+
48
+
49
+ def formatar_cnh(cnh: str | int) -> str:
50
+ """Formata uma CNH no padrão ``XXX XXX XXX XX``."""
51
+ cnh = normalizar(cnh)
52
+ if len(cnh) != _TAMANHO:
53
+ raise ValueError("CNH deve conter 11 dígitos para formatação.")
54
+ return f"{cnh[:3]} {cnh[3:6]} {cnh[6:9]} {cnh[9:]}"
55
+
56
+
57
+ def gerar_cnh() -> str:
58
+ """Gera uma CNH válida aleatória formatada."""
59
+ import random
60
+
61
+ base = [str(random.randint(0, 9)) for _ in range(9)]
62
+ primeiro, dsc = _primeiro_dv("".join(base))
63
+ base.append(str(primeiro))
64
+ segundo = _segundo_dv("".join(base), dsc)
65
+ base.append(str(segundo))
66
+ cnh = "".join(base)
67
+ return formatar_cnh(cnh)
@@ -0,0 +1,47 @@
1
+ """Validação e formatação de CNPJ."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._utils import normalizar, tem_digitos_repetidos
6
+
7
+ _TAMANHO = 14
8
+
9
+ _PESOS_DV_1 = (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
10
+ _PESOS_DV_2 = (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
11
+
12
+
13
+ def _digito_verificador(digitos: str, pesos: tuple[int, ...]) -> int:
14
+ resto = sum(int(d) * p for d, p in zip(digitos, pesos, strict=False)) % 11
15
+ return 0 if resto < 2 else 11 - resto
16
+
17
+
18
+ def validar_cnpj(cnpj: str | int) -> bool:
19
+ """Valida um CNPJ pelos dígitos verificadores."""
20
+ cnpj = normalizar(cnpj)
21
+ if len(cnpj) != _TAMANHO or tem_digitos_repetidos(cnpj):
22
+ return False
23
+
24
+ primeiro = _digito_verificador(cnpj[:12], _PESOS_DV_1)
25
+ segundo = _digito_verificador(cnpj[:13], _PESOS_DV_2)
26
+ return cnpj[-2:] == f"{primeiro}{segundo}"
27
+
28
+
29
+ def formatar_cnpj(cnpj: str | int) -> str:
30
+ """Formata um CNPJ no padrão ``XX.XXX.XXX/XXXX-XX``."""
31
+ cnpj = normalizar(cnpj)
32
+ if len(cnpj) != _TAMANHO:
33
+ raise ValueError("CNPJ deve conter 14 dígitos para formatação.")
34
+ return f"{cnpj[:2]}.{cnpj[2:5]}.{cnpj[5:8]}/{cnpj[8:12]}-{cnpj[12:]}"
35
+
36
+
37
+ def gerar_cnpj() -> str:
38
+ """Gera um CNPJ válido aleatório formatado."""
39
+ import random
40
+
41
+ base = [str(random.randint(0, 9)) for _ in range(12)]
42
+ primeiro = _digito_verificador("".join(base), _PESOS_DV_1)
43
+ base.append(str(primeiro))
44
+ segundo = _digito_verificador("".join(base), _PESOS_DV_2)
45
+ base.append(str(segundo))
46
+ cnpj = "".join(base)
47
+ return formatar_cnpj(cnpj)
@@ -0,0 +1,48 @@
1
+ """Validação e formatação de CPF.
2
+
3
+ Fonte do algoritmo: módulo 11, dígitos verificadores calculados com pesos
4
+ decrescentes de 10 a 2 (primeiro DV) e de 11 a 2 (segundo DV).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ._utils import normalizar, tem_digitos_repetidos
10
+
11
+ _TAMANHO = 11
12
+
13
+
14
+ def _digito_verificador(digitos: str, pesos: tuple[int, ...]) -> int:
15
+ resto = sum(int(d) * p for d, p in zip(digitos, pesos, strict=False)) % 11
16
+ return 0 if resto < 2 else 11 - resto
17
+
18
+
19
+ def validar_cpf(cpf: str | int) -> bool:
20
+ """Valida um CPF pelos dígitos verificadores."""
21
+ cpf = normalizar(cpf)
22
+ if len(cpf) != _TAMANHO or tem_digitos_repetidos(cpf):
23
+ return False
24
+
25
+ primeiro = _digito_verificador(cpf[:9], tuple(range(10, 1, -1)))
26
+ segundo = _digito_verificador(cpf[:10], tuple(range(11, 1, -1)))
27
+ return cpf[-2:] == f"{primeiro}{segundo}"
28
+
29
+
30
+ def formatar_cpf(cpf: str | int) -> str:
31
+ """Formata um CPF no padrão ``XXX.XXX.XXX-XX``."""
32
+ cpf = normalizar(cpf)
33
+ if len(cpf) != _TAMANHO:
34
+ raise ValueError("CPF deve conter 11 dígitos para formatação.")
35
+ return f"{cpf[:3]}.{cpf[3:6]}.{cpf[6:9]}-{cpf[9:]}"
36
+
37
+
38
+ def gerar_cpf() -> str:
39
+ """Gera um CPF válido aleatório formatado."""
40
+ import random
41
+
42
+ base = [str(random.randint(0, 9)) for _ in range(9)]
43
+ primeiro = _digito_verificador("".join(base), tuple(range(10, 1, -1)))
44
+ base.append(str(primeiro))
45
+ segundo = _digito_verificador("".join(base), tuple(range(11, 1, -1)))
46
+ base.append(str(segundo))
47
+ cpf = "".join(base)
48
+ return formatar_cpf(cpf)
@@ -0,0 +1,13 @@
1
+ """Exceções do pacote :mod:`validator_documents`."""
2
+
3
+
4
+ class DocumentoError(ValueError):
5
+ """Erro base para problemas de validação de documentos."""
6
+
7
+
8
+ class DocumentoInvalido(DocumentoError):
9
+ """Documento inválido — comprimento, formato ou dígitos verificadores incorretos."""
10
+
11
+
12
+ class DocumentoNaoIdentificado(DocumentoError):
13
+ """Não foi possível identificar o tipo do documento."""
@@ -0,0 +1,115 @@
1
+ """Modelos Pydantic tipados para documentos brasileiros.
2
+
3
+ Cada modelo valida o documento na construção e expõe ``.valor`` (somente dígitos)
4
+ e ``.formatado`` (com máscara padrão).
5
+ """
6
+
7
+ from typing import Self
8
+
9
+ from pydantic import BaseModel, ConfigDict, field_validator
10
+
11
+ from . import cnh, cnpj, cpf, pis, placa, renavam, titulo_eleitoral
12
+ from ._utils import normalizar
13
+ from .exceptions import DocumentoInvalido
14
+
15
+
16
+ class _DocumentoBase(BaseModel):
17
+ """Base comum: normaliza, valida DV/formato, expõe formatado."""
18
+
19
+ model_config = ConfigDict(frozen=True, str_strip_whitespace=True)
20
+
21
+ valor: str
22
+
23
+ _gerar_fn = None # type: ignore[assignment]
24
+
25
+ @field_validator("valor", mode="before")
26
+ @classmethod
27
+ def _normalizar(cls, v: str | int) -> str:
28
+ return normalizar(v)
29
+
30
+ @field_validator("valor")
31
+ @classmethod
32
+ def _validar(cls, v: str) -> str:
33
+ if not cls._validar_fn(v):
34
+ raise DocumentoInvalido(f"{cls.__name__} inválido: {v!r}")
35
+ return v
36
+
37
+ @property
38
+ def formatado(self) -> str:
39
+ return type(self)._formatar_fn(self.valor)
40
+
41
+ @classmethod
42
+ def gerar(cls) -> Self:
43
+ """Gera uma instância válida aleatória do documento."""
44
+ if cls._gerar_fn is None:
45
+ raise NotImplementedError(f"{cls.__name__} não implementa geração.")
46
+ valor = cls._gerar_fn()
47
+ return cls(valor=valor)
48
+
49
+
50
+ class CPF(_DocumentoBase):
51
+ """CPF — Cadastro de Pessoas Físicas."""
52
+
53
+ _validar_fn = staticmethod(cpf.validar_cpf)
54
+ _formatar_fn = staticmethod(cpf.formatar_cpf)
55
+ _gerar_fn = staticmethod(cpf.gerar_cpf)
56
+
57
+
58
+ class CNPJ(_DocumentoBase):
59
+ """CNPJ — Cadastro Nacional da Pessoa Jurídica."""
60
+
61
+ _validar_fn = staticmethod(cnpj.validar_cnpj)
62
+ _formatar_fn = staticmethod(cnpj.formatar_cnpj)
63
+ _gerar_fn = staticmethod(cnpj.gerar_cnpj)
64
+
65
+
66
+ class PIS(_DocumentoBase):
67
+ """PIS/NIS/PASEP/NIT."""
68
+
69
+ _validar_fn = staticmethod(pis.validar_pis)
70
+ _formatar_fn = staticmethod(pis.formatar_pis)
71
+ _gerar_fn = staticmethod(pis.gerar_pis)
72
+
73
+
74
+ class TituloEleitoral(_DocumentoBase):
75
+ """Título de Eleitor."""
76
+
77
+ _validar_fn = staticmethod(titulo_eleitoral.validar_titulo_eleitoral)
78
+ _formatar_fn = staticmethod(titulo_eleitoral.formatar_titulo_eleitoral)
79
+ _gerar_fn = staticmethod(titulo_eleitoral.gerar_titulo_eleitoral)
80
+
81
+
82
+ class CNH(_DocumentoBase):
83
+ """CNH — Carteira Nacional de Habilitação."""
84
+
85
+ _validar_fn = staticmethod(cnh.validar_cnh)
86
+ _formatar_fn = staticmethod(cnh.formatar_cnh)
87
+ _gerar_fn = staticmethod(cnh.gerar_cnh)
88
+
89
+
90
+ class Renavam(_DocumentoBase):
91
+ """RENAVAM — Registro Nacional de Veículos Automotores."""
92
+
93
+ _validar_fn = staticmethod(renavam.validar_renavam)
94
+ _formatar_fn = staticmethod(renavam.formatar_renavam)
95
+ _gerar_fn = staticmethod(renavam.gerar_renavam)
96
+
97
+
98
+ class Placa(_DocumentoBase):
99
+ """Placa veicular (padrão antigo ou Mercosul)."""
100
+
101
+ _validar_fn = staticmethod(placa.validar_placa)
102
+ _formatar_fn = staticmethod(placa.formatar_placa)
103
+ _gerar_fn = staticmethod(placa.gerar_placa)
104
+
105
+ @field_validator("valor", mode="before")
106
+ @classmethod
107
+ def _normalizar(cls, v: str | int) -> str:
108
+ # Placa mantém letras — normalização diferente
109
+ if isinstance(v, str):
110
+ import re
111
+
112
+ return re.sub(r"[^A-Z0-9]", "", v.upper())
113
+ if isinstance(v, int):
114
+ return str(v)
115
+ raise DocumentoInvalido("Placa deve ser string ou inteiro.")
@@ -0,0 +1,42 @@
1
+ """Validação e formatação de PIS/NIS/PASEP/NIT."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._utils import normalizar, tem_digitos_repetidos
6
+
7
+ _TAMANHO = 11
8
+
9
+ _MULTIPLICADORES = (3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
10
+
11
+
12
+ def validar_pis(pis: str | int) -> bool:
13
+ """Valida um PIS/NIS/PASEP/NIT pelo dígito verificador."""
14
+ pis = normalizar(pis)
15
+ if len(pis) != _TAMANHO or tem_digitos_repetidos(pis):
16
+ return False
17
+
18
+ total = sum(int(d) * m for d, m in zip(pis[:10], _MULTIPLICADORES, strict=False))
19
+ resto = total % 11
20
+ digito = 0 if resto < 2 else 11 - resto
21
+ return pis[-1] == str(digito)
22
+
23
+
24
+ def formatar_pis(pis: str | int) -> str:
25
+ """Formata um PIS no padrão ``XXX.XXXXX.XX-X``."""
26
+ pis = normalizar(pis)
27
+ if len(pis) != _TAMANHO:
28
+ raise ValueError("PIS deve conter 11 dígitos para formatação.")
29
+ return f"{pis[:3]}.{pis[3:8]}.{pis[8:10]}-{pis[10:]}"
30
+
31
+
32
+ def gerar_pis() -> str:
33
+ """Gera um PIS/NIS/PASEP/NIT válido aleatório formatado."""
34
+ import random
35
+
36
+ base = [str(random.randint(0, 9)) for _ in range(10)]
37
+ total = sum(int(d) * m for d, m in zip(base, _MULTIPLICADORES, strict=False))
38
+ resto = total % 11
39
+ digito = 0 if resto < 2 else 11 - resto
40
+ base.append(str(digito))
41
+ pis = "".join(base)
42
+ return formatar_pis(pis)
@@ -0,0 +1,71 @@
1
+ """Validação e formatação de placas veiculares brasileiras.
2
+
3
+ Suporta dois padrões:
4
+ - Antigo: ``ABC-1234`` (3 letras + 4 dígitos)
5
+ - Mercosul: ``ABC1D23`` (3 letras + 1 dígito + 1 letra + 2 dígitos)
6
+
7
+ Não há dígito verificador — validação é apenas por formato/regex.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ _PLACA_ANTIGA = re.compile(r"^[A-Z]{3}\d{4}$")
15
+ _PLACA_MERCOSUL = re.compile(r"^[A-Z]{3}\d[A-Z]\d{2}$")
16
+
17
+
18
+ def _normalizar_placa(placa: str | int) -> str:
19
+ s = str(placa).upper().strip()
20
+ return re.sub(r"[^A-Z0-9]", "", s)
21
+
22
+
23
+ def _eh_placa_valida(normalizada: str) -> bool:
24
+ return bool(_PLACA_ANTIGA.fullmatch(normalizada) or _PLACA_MERCOSUL.fullmatch(normalizada))
25
+
26
+
27
+ def validar_placa(placa: str | int) -> bool:
28
+ """Valida uma placa pelo formato (antigo ou Mercosul)."""
29
+ return _eh_placa_valida(_normalizar_placa(placa))
30
+
31
+
32
+ def formatar_placa(placa: str | int) -> str:
33
+ """Formata a placa:
34
+ - Antigo: ``ABC-1234``
35
+ - Mercosul: ``ABC1D23`` (sem hífen, padrão oficial)
36
+ """
37
+ n = _normalizar_placa(placa)
38
+ if _PLACA_ANTIGA.fullmatch(n):
39
+ return f"{n[:3]}-{n[3:]}"
40
+ if _PLACA_MERCOSUL.fullmatch(n):
41
+ return n # padrão Mercosul oficial sem hífen
42
+ raise ValueError("Formato de placa inválido para formatação.")
43
+
44
+
45
+ def gerar_placa(mercosul: bool = False) -> str:
46
+ """Gera uma placa válida aleatória.
47
+
48
+ Args:
49
+ mercosul: Se True, gera padrão Mercosul; se False, padrão antigo.
50
+
51
+ Returns:
52
+ Placa formatada (antigo com hífen, Mercosul sem hífen).
53
+ """
54
+ import random
55
+
56
+ letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
57
+ digitos = "0123456789"
58
+
59
+ if mercosul:
60
+ # ABC1D23
61
+ n = (
62
+ "".join(random.choices(letras, k=3))
63
+ + random.choice(digitos)
64
+ + random.choice(letras)
65
+ + "".join(random.choices(digitos, k=2))
66
+ )
67
+ return n # sem hífen
68
+ else:
69
+ # ABC-1234
70
+ n = "".join(random.choices(letras, k=3)) + "".join(random.choices(digitos, k=4))
71
+ return f"{n[:3]}-{n[3:]}"
@@ -0,0 +1,45 @@
1
+ """Validação e formatação de RENAVAM (Registro Nacional de Veículos Automotores).
2
+
3
+ Algoritmo: módulo 11 com pesos fixos sobre os 10 primeiros dígitos.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from ._utils import normalizar
9
+
10
+ _TAMANHO = 11
11
+
12
+ _PESOS = (3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
13
+
14
+
15
+ def validar_renavam(renavam: str | int) -> bool:
16
+ """Valida um RENAVAM pelo dígito verificador."""
17
+ renavam = normalizar(renavam)
18
+ if len(renavam) != _TAMANHO:
19
+ return False
20
+
21
+ total = sum(int(d) * p for d, p in zip(renavam[:10], _PESOS, strict=False))
22
+ resto = (total * 10) % 11
23
+ digito = 0 if resto == 10 else resto
24
+ return renavam[-1] == str(digito)
25
+
26
+
27
+ def formatar_renavam(renavam: str | int) -> str:
28
+ """Formata um RENAVAM no padrão ``XXXXXXXXXX-X``."""
29
+ renavam = normalizar(renavam)
30
+ if len(renavam) != _TAMANHO:
31
+ raise ValueError("RENAVAM deve conter 11 dígitos para formatação.")
32
+ return f"{renavam[:10]}-{renavam[10:]}"
33
+
34
+
35
+ def gerar_renavam() -> str:
36
+ """Gera um RENAVAM válido aleatório formatado."""
37
+ import random
38
+
39
+ base = [str(random.randint(0, 9)) for _ in range(10)]
40
+ total = sum(int(d) * p for d, p in zip(base, _PESOS, strict=False))
41
+ resto = (total * 10) % 11
42
+ digito = 0 if resto == 10 else resto
43
+ base.append(str(digito))
44
+ renavam = "".join(base)
45
+ return formatar_renavam(renavam)
@@ -0,0 +1,70 @@
1
+ """Validação e formatação de Título Eleitoral.
2
+
3
+ Fonte normativa: Resolução TSE nº 23.659/2021, Art. 36 — 8 dígitos sequenciais,
4
+ 2 dígitos de UF (01 a 28) e 2 dígitos verificadores, ambos por Módulo 11.
5
+
6
+ A ressalva histórica que transforma resto 0 em dígito 1 para SP/MG (01/02)
7
+ não consta na Resolução e, portanto, não é aplicada aqui.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ._utils import normalizar
13
+
14
+ _TAMANHO = 12
15
+
16
+ _PESOS_DV_1 = (2, 3, 4, 5, 6, 7, 8, 9)
17
+ _PESOS_DV_2 = (7, 8, 9)
18
+
19
+ _UFS_VALIDAS = tuple(f"{uf:02d}" for uf in range(1, 29))
20
+
21
+
22
+ def _modulo_11(digitos: list[int], pesos: tuple[int, ...]) -> int:
23
+ resto = sum(d * p for d, p in zip(digitos, pesos, strict=False)) % 11
24
+ return 0 if resto == 10 else resto
25
+
26
+
27
+ def validar_titulo_eleitoral(titulo: str | int) -> bool:
28
+ """Valida um Título Eleitoral pelos dois dígitos verificadores."""
29
+ titulo = normalizar(titulo)
30
+ if len(titulo) != _TAMANHO:
31
+ return False
32
+
33
+ digitos = [int(d) for d in titulo]
34
+ if titulo[8:10] not in _UFS_VALIDAS:
35
+ return False
36
+
37
+ primeiro = _modulo_11(digitos[0:8], _PESOS_DV_1)
38
+ segundo = _modulo_11(digitos[8:10] + [primeiro], _PESOS_DV_2)
39
+ return titulo[-2:] == f"{primeiro}{segundo}"
40
+
41
+
42
+ def formatar_titulo_eleitoral(titulo: str | int) -> str:
43
+ """Formata um Título Eleitoral no padrão ``XXXX XXXX XXXX``."""
44
+ titulo = normalizar(titulo)
45
+ if len(titulo) != _TAMANHO:
46
+ raise ValueError("Título Eleitoral deve conter 12 dígitos para formatação.")
47
+ return f"{titulo[0:4]} {titulo[4:8]} {titulo[8:]}"
48
+
49
+
50
+ def gerar_titulo_eleitoral() -> str:
51
+ """Gera um Título Eleitoral válido aleatório formatado.
52
+
53
+ Usa UF aleatória (01 a 28) e segue a Resolução TSE 23.659/2021
54
+ (sem exceção SP/MG para resto 0).
55
+ """
56
+ import random
57
+
58
+ # 8 dígitos sequenciais aleatórios
59
+ base = [str(random.randint(0, 9)) for _ in range(8)]
60
+ # UF aleatória 01-28
61
+ uf = f"{random.randint(1, 28):02d}"
62
+ base.extend(list(uf))
63
+
64
+ digitos = [int(d) for d in base]
65
+ primeiro = _modulo_11(digitos[0:8], _PESOS_DV_1)
66
+ segundo = _modulo_11(digitos[8:10] + [primeiro], _PESOS_DV_2)
67
+ base.extend([str(primeiro), str(segundo)])
68
+
69
+ titulo = "".join(base)
70
+ return formatar_titulo_eleitoral(titulo)
@@ -0,0 +1,94 @@
1
+ """Despacho de validação por tipo e identificação de documento."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Literal
7
+
8
+ from . import cnh, cnpj, cpf, pis, placa, renavam, titulo_eleitoral
9
+ from ._utils import normalizar
10
+ from .exceptions import DocumentoNaoIdentificado
11
+ from .placa import _PLACA_ANTIGA, _PLACA_MERCOSUL
12
+
13
+ TipoDocumento = Literal[
14
+ "CPF",
15
+ "CNPJ",
16
+ "PIS",
17
+ "TITULO_ELEITORAL",
18
+ "CNH",
19
+ "RENAVAM",
20
+ "PLACA",
21
+ ]
22
+
23
+ _VALIDADORES: dict[TipoDocumento, tuple[callable, callable, int | None]] = {
24
+ "CPF": (cpf.validar_cpf, cpf.formatar_cpf, 11),
25
+ "CNPJ": (cnpj.validar_cnpj, cnpj.formatar_cnpj, 14),
26
+ "PIS": (pis.validar_pis, pis.formatar_pis, 11),
27
+ "TITULO_ELEITORAL": (
28
+ titulo_eleitoral.validar_titulo_eleitoral,
29
+ titulo_eleitoral.formatar_titulo_eleitoral,
30
+ 12,
31
+ ),
32
+ "CNH": (cnh.validar_cnh, cnh.formatar_cnh, 11),
33
+ "RENAVAM": (renavam.validar_renavam, renavam.formatar_renavam, 11),
34
+ "PLACA": (placa.validar_placa, placa.formatar_placa, None),
35
+ }
36
+
37
+ _TAMANHO_PARA_TIPOS: dict[int, list[TipoDocumento]] = {}
38
+ for tipo, (_, _, tamanho) in _VALIDADORES.items():
39
+ if tamanho is not None:
40
+ _TAMANHO_PARA_TIPOS.setdefault(tamanho, []).append(tipo)
41
+
42
+
43
+ def validar_documento(
44
+ valor: str | int, tipo: TipoDocumento | None = None, formatado: bool = False
45
+ ) -> str | bool:
46
+ """Valida um documento pelo tipo explícito ou tenta identificar automaticamente.
47
+
48
+ Args:
49
+ valor: Documento como string ou int.
50
+ tipo: Tipo explícito (ex.: "CPF"). Se None, tenta identificar por comprimento.
51
+ formatado: Se True, retorna o documento formatado; se False, retorna bool.
52
+
53
+ Returns:
54
+ bool (formatado=False) ou str formatado (formatado=True).
55
+
56
+ Raises:
57
+ DocumentoNaoIdentificado: Se tipo=None e o comprimento for ambíguo.
58
+ """
59
+ if tipo is None:
60
+ tipo = identificar_documento(valor)
61
+
62
+ validar_fn, formatar_fn, _ = _VALIDADORES[tipo]
63
+ valido = validar_fn(valor)
64
+ if formatado and valido:
65
+ return formatar_fn(valor)
66
+ return valido
67
+
68
+
69
+ def identificar_documento(valor: str | int) -> TipoDocumento:
70
+ """Identifica o tipo de documento pelo comprimento (apenas dígitos).
71
+
72
+ Raises:
73
+ DocumentoNaoIdentificado: Se o comprimento for ambíguo ou não mapeado.
74
+ """
75
+ raw = str(valor).strip()
76
+ # Placa: detecta por regex ANTES de normalizar (mantém letras)
77
+ n = re.sub(r"[^A-Z0-9]", "", raw.upper())
78
+ if _PLACA_ANTIGA.fullmatch(n) or _PLACA_MERCOSUL.fullmatch(n):
79
+ return "PLACA"
80
+
81
+ s = normalizar(valor)
82
+ tamanho = len(s)
83
+
84
+ candidatos = _TAMANHO_PARA_TIPOS.get(tamanho, [])
85
+ if len(candidatos) == 1:
86
+ return candidatos[0]
87
+ if not candidatos:
88
+ raise DocumentoNaoIdentificado(
89
+ f"Comprimento {tamanho} não corresponde a nenhum tipo conhecido."
90
+ )
91
+ raise DocumentoNaoIdentificado(
92
+ f"Comprimento {tamanho} é ambíguo: {', '.join(candidatos)}. "
93
+ f"Use validar_documento(valor, tipo='...') explicitamente."
94
+ )
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.5
2
+ Name: validator-documents
3
+ Version: 0.1.0
4
+ Summary: Validação e formatação de documentos brasileiros (CPF, CNPJ, PIS, Título Eleitoral, CNH, RENAVAM, Placa).
5
+ Project-URL: Homepage, https://github.com/edmaker89/validator_documents_package
6
+ Project-URL: Repository, https://github.com/edmaker89/validator_documents_package
7
+ Project-URL: Issues, https://github.com/edmaker89/validator_documents_package/issues
8
+ Author-email: edmaker89 <edmaker@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: brasil,cnh,cnpj,cpf,pis,placa,renavam,titulo-eleitoral,validador
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: pydantic>=2.5
22
+ Provides-Extra: dev
23
+ Requires-Dist: build>=1.2; extra == 'dev'
24
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
25
+ Requires-Dist: pytest>=8; extra == 'dev'
26
+ Requires-Dist: ruff>=0.6; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # validator-documents
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/validator-documents.svg)](https://pypi.org/project/validator-documents/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/validator-documents.svg)](https://pypi.org/project/validator-documents/)
33
+ [![License](https://img.shields.io/pypi/l/validator-documents.svg)](https://opensource.org/licenses/MIT)
34
+ [![CI](https://github.com/edmaker89/validator_documents_package/actions/workflows/ci.yml/badge.svg)](https://github.com/edmaker89/validator_documents_package/actions/workflows/ci.yml)
35
+ [![Coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/edmaker89/validator_documents_package/main/coverage-badge.json)](https://github.com/edmaker89/validator_documents_package/actions/workflows/ci.yml)
36
+
37
+ Validação e formatação de documentos brasileiros com tipagem Pydantic v2.
38
+
39
+ **Documentos suportados:**
40
+ - CPF (Cadastro de Pessoas Físicas)
41
+ - CNPJ (Cadastro Nacional da Pessoa Jurídica)
42
+ - PIS/NIS/PASEP/NIT
43
+ - Título Eleitoral
44
+ - CNH (Carteira Nacional de Habilitação)
45
+ - RENAVAM (Registro Nacional de Veículos Automotores)
46
+ - Placa veicular (padrão antigo e Mercosul)
47
+
48
+ ## Instalação
49
+
50
+ ```bash
51
+ pip install validator-documents
52
+ ```
53
+
54
+ Requer Python ≥ 3.10.
55
+
56
+ ## Uso rápido
57
+
58
+ ### Funções funcionais (por tipo)
59
+
60
+ ```python
61
+ from validator_documents import (
62
+ validar_cpf,
63
+ formatar_cpf,
64
+ validar_cnpj,
65
+ formatar_cnpj,
66
+ validar_pis,
67
+ formatar_pis,
68
+ validar_titulo_eleitoral,
69
+ formatar_titulo_eleitoral,
70
+ validar_cnh,
71
+ formatar_cnh,
72
+ validar_renavam,
73
+ formatar_renavam,
74
+ validar_placa,
75
+ formatar_placa,
76
+ )
77
+
78
+ # Validação
79
+ validar_cpf("775.488.241-81") # True
80
+ validar_cnpj("67.646.869/6391-55") # True
81
+ validar_pis("435.20735.46-7") # True
82
+ validar_titulo_eleitoral("7634 6850 1392") # True
83
+ validar_cnh("636 778 226 35") # True
84
+ validar_renavam("1502137447-1") # True
85
+ validar_placa("ABC1234") # True (antigo)
86
+ validar_placa("ABC1D23") # True (Mercosul)
87
+
88
+ # Formatação
89
+ formatar_cpf("77548824181") # "775.488.241-81"
90
+ formatar_cnpj("67646869639155") # "67.646.869/6391-55"
91
+ formatar_placa("abc1234") # "ABC-1234"
92
+ ```
93
+
94
+ ### Geração de documentos válidos (para testes/fixtures)
95
+
96
+ ```python
97
+ from validator_documents import (
98
+ gerar_cpf,
99
+ gerar_cnpj,
100
+ gerar_pis,
101
+ gerar_titulo_eleitoral,
102
+ gerar_cnh,
103
+ gerar_renavam,
104
+ gerar_placa,
105
+ )
106
+
107
+ # Funções funcionais
108
+ cpf = gerar_cpf() # "775.488.241-81"
109
+ cnpj = gerar_cnpj() # "67.646.869/6391-55"
110
+ pis = gerar_pis() # "435.20735.46-7"
111
+ titulo = gerar_titulo_eleitoral() # "7634 6850 1392"
112
+ cnh = gerar_cnh() # "636 778 226 35"
113
+ renavam = gerar_renavam() # "1502137447-1"
114
+ placa_antigo = gerar_placa() # "ABC-1234"
115
+ placa_mercosul = gerar_placa(True) # "ABC1D23"
116
+ ```
117
+
118
+ ### Modelos Pydantic com `.gerar()`
119
+
120
+ ```python
121
+ from validator_documents import CPF, CNPJ, PIS, TituloEleitoral, CNH, Renavam, Placa
122
+
123
+ # Classe método .gerar() retorna instância tipada válida
124
+ cpf = CPF.gerar()
125
+ cpf.valor # "77548824181" (apenas dígitos)
126
+ cpf.formatado # "775.488.241-81"
127
+
128
+ cnpj = CNPJ.gerar()
129
+ pis = PIS.gerar()
130
+ # ... idem para TituloEleitoral, CNH, Renavam, Placa
131
+
132
+ # Placa Mercosul via função + modelo
133
+ from validator_documents import gerar_placa
134
+
135
+ placa_mercosul = Placa(valor=gerar_placa(mercosul=True))
136
+ placa_mercosul.formatado # "ABC1D23" (sem hífen)
137
+ ```
138
+
139
+ ### Despacho genérico
140
+
141
+ ```python
142
+ from validator_documents import validar_documento, identificar_documento
143
+
144
+ # Tipo explícito (recomendado para evitar ambiguidade de 11 dígitos)
145
+ validar_documento("77548824181", tipo="CPF") # True
146
+ validar_documento("775.488.241-81", tipo="CPF", formatado=True) # "775.488.241-81"
147
+
148
+ # Identificação automática (funciona apenas quando não ambíguo)
149
+ identificar_documento("77548824181") # "CPF"
150
+ identificar_documento("ABC1234") # "PLACA"
151
+
152
+ # 11 dígitos é ambíguo (CPF/PIS/CNH/RENAVAM) — lança DocumentoNaoIdentificado
153
+ identificar_documento("12345678901") # Exception: use tipo explícito
154
+ ```
155
+
156
+ ### Modelos Pydantic (tipagem estática)
157
+
158
+ ```python
159
+ from validator_documents import CPF, CNPJ, PIS, TituloEleitoral, CNH, Renavam, Placa
160
+
161
+ cpf = CPF(valor="775.488.241-81")
162
+ cpf.valor # "77548824181" (apenas dígitos)
163
+ cpf.formatado # "775.488.241-81"
164
+
165
+ # Valida na construção — levanta DocumentoInvalido se inválido
166
+ try:
167
+ CPF(valor="11111111111")
168
+ except DocumentoInvalido as e:
169
+ print(e) # "CPF inválido: '11111111111'"
170
+ ```
171
+
172
+ ### Tipos de exceção
173
+
174
+ ```python
175
+ from validator_documents import DocumentoInvalido, DocumentoNaoIdentificado
176
+
177
+ # DocumentoInvalido — DV/formato incorreto
178
+ # DocumentoNaoIdentificado — identificação automática ambígua
179
+ ```
180
+
181
+ ## Compatibilidade e decisões de design
182
+
183
+ | Documento | Tamanho | DV? | Padrão de formatação |
184
+ |-----------|---------|-----|----------------------|
185
+ | CPF | 11 | Sim | `XXX.XXX.XXX-XX` |
186
+ | CNPJ | 14 | Sim | `XX.XXX.XXX/XXXX-XX` |
187
+ | PIS | 11 | Sim | `XXX.XXXXX.XX-X` |
188
+ | Título Eleitoral | 12 | Sim | `XXXX XXXX XXXX` |
189
+ | CNH | 11 | Sim | `XXX XXX XXX XX` |
190
+ | RENAVAM | 11 | Sim | `XXXXXXXXXX-X` |
191
+ | Placa | 7 alfanum. | Não | `ABC-1234` (antigo) / `ABC1D23` (Mercosul) |
192
+
193
+ **Decisões relevantes:**
194
+ - **Identificação automática por comprimento** é limitada: 11 dígitos corresponde a CPF, PIS, CNH e RENAVAM — nesses casos, use `validar_documento(valor, tipo="...")` explícito.
195
+ - **Título Eleitoral**: segue a Resolução TSE 23.659/2021 (sem exceção SP/MG onde resto 0 vira 1). Se seu caso de uso exigir a exceção legada, abra uma issue.
196
+ - **Placa Mercosul**: formatada sem hífen (`ABC1D23`), conforme padrão oficial.
197
+ - **Dígitos repetidos** (ex.: `111.111.111-11`) são rejeitados para CPF, CNPJ, PIS e CNH.
198
+
199
+ ## Desenvolvimento
200
+
201
+ ```bash
202
+ # Instala dependências de dev
203
+ pip install ".[dev]"
204
+
205
+ # Lint
206
+ ruff check .
207
+
208
+ # Format
209
+ ruff format .
210
+
211
+ # Testes + cobertura
212
+ pytest -q
213
+ ```
214
+
215
+ ## Licença
216
+
217
+ MIT — veja [LICENSE](LICENSE).
@@ -0,0 +1,16 @@
1
+ validator_documents/__init__.py,sha256=Sw15rKr_gZficvIsUMCQsdt2LrQ_IZNvhsqxMmUfWT8,1796
2
+ validator_documents/_utils.py,sha256=O472BdJ9GDMzRG1JuYWZl1BKE39zKz5XYHbZUypmmP4,670
3
+ validator_documents/cnh.py,sha256=OPxdlUua_6-HCX-2wVfNu3oTN7vYQ4vKOd4L4JJ35b4,2083
4
+ validator_documents/cnpj.py,sha256=MyMwWjgaEuFTWgfn-Heggp_lBRykz2tJV-xc6c-SITw,1535
5
+ validator_documents/cpf.py,sha256=oEciog5XlQUq9CgiOAFJRwoUgxpXMqFzETs0xNiNoBU,1571
6
+ validator_documents/exceptions.py,sha256=xEnAR3vf3wkrR693YfCCM1hynNI8dSrL-P_QmVv5efc,404
7
+ validator_documents/models.py,sha256=qXyicf95t4DyqgGow-ODiF9p6V0c4-JEFTVQZR9XbCA,3489
8
+ validator_documents/pis.py,sha256=WJ6qiqJZaraAr6nAbHelr-U6-rnHPp0hEin_WPshb6k,1300
9
+ validator_documents/placa.py,sha256=Kk0JKl3bs173eHDBOnZ2MoSNJ8lNcugKg8-SxJf7rnE,2069
10
+ validator_documents/renavam.py,sha256=Fuj4xrZlpN_qrXjG_Vy7We8oI7KyM9WybT_c7ObYAAg,1368
11
+ validator_documents/titulo_eleitoral.py,sha256=mloDawbuAbo8QU0QQJHQtaAXQilc3lBkeOF8JOfIsQM,2280
12
+ validator_documents/validar.py,sha256=eAT9FeWFqWAPSQ_GlI0zHD-sXDBKULyDkoanixJdeBY,3060
13
+ validator_documents-0.1.0.dist-info/METADATA,sha256=RTpDZvn1lC9Ehkq2dYGKGhk5HCtgLj7h-H3hl54xSAw,7214
14
+ validator_documents-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
15
+ validator_documents-0.1.0.dist-info/licenses/LICENSE,sha256=l4EGbBOYpNqZYi8l6gjf3UAgQCWdrSQvZydi-X5poq8,1065
16
+ validator_documents-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 edmaker89
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.