pure-docs-br 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.
- pure_docs_br/__init__.py +29 -0
- pure_docs_br/_internal/__init__.py +1 -0
- pure_docs_br/_internal/utils/__init__.py +1 -0
- pure_docs_br/_internal/utils/typing/__init__.py +8 -0
- pure_docs_br/_internal/utils/typing/type_checker.py +103 -0
- pure_docs_br/br_identifiers.py +283 -0
- pure_docs_br/py.typed +0 -0
- pure_docs_br-1.0.0.dist-info/METADATA +234 -0
- pure_docs_br-1.0.0.dist-info/RECORD +11 -0
- pure_docs_br-1.0.0.dist-info/WHEEL +4 -0
- pure_docs_br-1.0.0.dist-info/licenses/LICENSE +21 -0
pure_docs_br/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""pure-docs-br package."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from .br_identifiers import (
|
|
6
|
+
is_valid_cnpj,
|
|
7
|
+
is_valid_cpf,
|
|
8
|
+
mask_cnpj,
|
|
9
|
+
mask_cpf,
|
|
10
|
+
unmask_cnpj,
|
|
11
|
+
unmask_cpf,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
__version__ = version("pure-docs-br")
|
|
17
|
+
except PackageNotFoundError: # pragma: no cover - source tree without an installed dist
|
|
18
|
+
__version__ = "0.0.0"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"__version__",
|
|
23
|
+
"is_valid_cnpj",
|
|
24
|
+
"is_valid_cpf",
|
|
25
|
+
"mask_cnpj",
|
|
26
|
+
"mask_cpf",
|
|
27
|
+
"unmask_cnpj",
|
|
28
|
+
"unmask_cpf",
|
|
29
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Private internals of the pure_docs_br package (not a public API)."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Private helpers shared by the public modules."""
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Standard-library runtime type checking for plain annotated parameters.
|
|
2
|
+
|
|
3
|
+
The package ships with no runtime dependencies, so this decorator replaces a third-party
|
|
4
|
+
checker. It validates every argument whose annotation is a plain class (``str``, ``int``)
|
|
5
|
+
and leaves generic, union and string-forward annotations to mypy.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
import functools
|
|
12
|
+
import inspect
|
|
13
|
+
from typing import ParamSpec, TypeVar, get_type_hints
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_P = ParamSpec("_P")
|
|
17
|
+
_R = TypeVar("_R")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _check_argument(*, str_name: str, value: object, dict_hints: dict[str, object]) -> None:
|
|
21
|
+
"""Raise ``TypeError`` when a value is not an instance of its plain-class annotation.
|
|
22
|
+
|
|
23
|
+
Parameters
|
|
24
|
+
----------
|
|
25
|
+
str_name : str
|
|
26
|
+
Parameter name.
|
|
27
|
+
value : object
|
|
28
|
+
Argument bound to that parameter.
|
|
29
|
+
dict_hints : dict[str, object]
|
|
30
|
+
Resolved annotations of the decorated function.
|
|
31
|
+
|
|
32
|
+
Returns
|
|
33
|
+
-------
|
|
34
|
+
None
|
|
35
|
+
Nothing; the check either passes or raises.
|
|
36
|
+
|
|
37
|
+
Raises
|
|
38
|
+
------
|
|
39
|
+
TypeError
|
|
40
|
+
If the annotation is a plain class and ``value`` is not an instance of it.
|
|
41
|
+
"""
|
|
42
|
+
cls_expected = dict_hints.get(str_name)
|
|
43
|
+
if isinstance(cls_expected, type) and not isinstance(value, cls_expected):
|
|
44
|
+
raise TypeError(
|
|
45
|
+
f"parameter {str_name}={value!r} violates type hint {cls_expected.__name__}, "
|
|
46
|
+
f"got {type(value).__name__}"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _check_arguments(
|
|
51
|
+
*,
|
|
52
|
+
cls_signature: inspect.Signature,
|
|
53
|
+
dict_hints: dict[str, object],
|
|
54
|
+
args: tuple[object, ...],
|
|
55
|
+
kwargs: dict[str, object],
|
|
56
|
+
) -> None:
|
|
57
|
+
"""Check every bound argument of one call against the resolved annotations.
|
|
58
|
+
|
|
59
|
+
Parameters
|
|
60
|
+
----------
|
|
61
|
+
cls_signature : inspect.Signature
|
|
62
|
+
Signature of the decorated function.
|
|
63
|
+
dict_hints : dict[str, object]
|
|
64
|
+
Resolved annotations of the decorated function.
|
|
65
|
+
args : tuple[object, ...]
|
|
66
|
+
Positional arguments of the call.
|
|
67
|
+
kwargs : dict[str, object]
|
|
68
|
+
Keyword arguments of the call.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
None
|
|
73
|
+
Nothing; the check either passes or raises ``TypeError``.
|
|
74
|
+
"""
|
|
75
|
+
for str_name, value in cls_signature.bind(*args, **kwargs).arguments.items():
|
|
76
|
+
_check_argument(str_name=str_name, value=value, dict_hints=dict_hints)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def type_checker(fn_target: Callable[_P, _R]) -> Callable[_P, _R]:
|
|
80
|
+
"""Validate the annotated parameters of ``fn_target`` on every call.
|
|
81
|
+
|
|
82
|
+
Parameters
|
|
83
|
+
----------
|
|
84
|
+
fn_target : Callable[_P, _R]
|
|
85
|
+
Function whose plain-class annotated parameters are checked at call time.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
Callable[_P, _R]
|
|
90
|
+
The wrapped function, with its signature and docstring preserved.
|
|
91
|
+
"""
|
|
92
|
+
cls_signature = inspect.signature(fn_target)
|
|
93
|
+
dict_hints = get_type_hints(fn_target)
|
|
94
|
+
|
|
95
|
+
@functools.wraps(fn_target)
|
|
96
|
+
def fn_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
97
|
+
"""Check the bound arguments, then call the wrapped function."""
|
|
98
|
+
_check_arguments(
|
|
99
|
+
cls_signature=cls_signature, dict_hints=dict_hints, args=args, kwargs=kwargs
|
|
100
|
+
)
|
|
101
|
+
return fn_target(*args, **kwargs)
|
|
102
|
+
|
|
103
|
+
return fn_wrapper
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Brazilian identifier helpers — mask, unmask and validate CNPJ and CPF.
|
|
2
|
+
|
|
3
|
+
These are pure, stateless functions (no class — there is no state or lifecycle to
|
|
4
|
+
own). They are deliberately tolerant on input so they can be mapped over a whole
|
|
5
|
+
``pandas`` column: ``unmask_*`` strips punctuation, the spurious ``".0"`` left by a
|
|
6
|
+
float→str coercion, and (for CNPJ) handles the **2026 alphanumeric format** by keeping
|
|
7
|
+
``A-Z``/``0-9`` and only zero-padding when the value is purely numeric. ``is_valid_*``
|
|
8
|
+
return ``bool`` rather than raising on any ``str``, so a bad row never aborts a bulk
|
|
9
|
+
transformation. A non-``str`` (``None``, ``float``/``NaN``) raises ``TypeError`` from the
|
|
10
|
+
runtime type checker: stringify or drop nulls first. Short numeric values are zero-padded
|
|
11
|
+
before validation, on purpose, to recover identifiers stored as numbers that lost leading
|
|
12
|
+
zeros: ``is_valid_cpf("191")`` is ``True`` (it becomes ``00000000191``), while ``"0"`` is
|
|
13
|
+
rejected as a repeated-digit value.
|
|
14
|
+
|
|
15
|
+
The CNPJ check digits use ASCII-48 weighting, which makes a single mod-11 routine
|
|
16
|
+
validate both legacy-numeric and new-alphanumeric CNPJs (a digit's value equals itself).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import re
|
|
22
|
+
|
|
23
|
+
from pure_docs_br._internal.utils.typing import type_checker
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_INT_MODULUS = 11
|
|
27
|
+
_INT_MIN_REMAINDER = 2
|
|
28
|
+
|
|
29
|
+
_LEN_CNPJ: int = 14
|
|
30
|
+
_LEN_CPF: int = 11
|
|
31
|
+
_ASCII_ZERO: int = ord("0")
|
|
32
|
+
|
|
33
|
+
_CNPJ_WEIGHTS_DV1: tuple[int, ...] = (5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
|
|
34
|
+
_CNPJ_WEIGHTS_DV2: tuple[int, ...] = (6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2)
|
|
35
|
+
|
|
36
|
+
_RE_FLOAT_ARTIFACT: re.Pattern[str] = re.compile(r"^\s*(\d+)\.0+\s*$")
|
|
37
|
+
_RE_NON_ALNUM: re.Pattern[str] = re.compile(r"[^0-9A-Za-z]")
|
|
38
|
+
_RE_NON_DIGIT: re.Pattern[str] = re.compile(r"\D")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@type_checker
|
|
42
|
+
def _strip_float_artifact(str_value: str) -> str:
|
|
43
|
+
"""Drop a trailing ``.0`` left by a float→str coercion; otherwise trim whitespace.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
str_value : str
|
|
48
|
+
Raw identifier as read from a source (CSV cell, DataFrame value, API field).
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
str
|
|
53
|
+
``str_value`` with a ``".0…"`` tail removed when it is an integer-with-float-tail,
|
|
54
|
+
else the whitespace-trimmed input.
|
|
55
|
+
"""
|
|
56
|
+
cls_match = _RE_FLOAT_ARTIFACT.match(str_value)
|
|
57
|
+
if cls_match is not None:
|
|
58
|
+
return cls_match.group(1)
|
|
59
|
+
return str_value.strip()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@type_checker
|
|
63
|
+
def unmask_cnpj(str_value: str) -> str:
|
|
64
|
+
"""Normalise a CNPJ to its bare 14-character form (alphanumeric-aware).
|
|
65
|
+
|
|
66
|
+
Parameters
|
|
67
|
+
----------
|
|
68
|
+
str_value : str
|
|
69
|
+
A CNPJ in any shape — masked, zero-stripped, or carrying a float ``.0`` tail.
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
-------
|
|
73
|
+
str
|
|
74
|
+
Uppercased value containing only ``A-Z``/``0-9``, with a ``.0`` tail dropped
|
|
75
|
+
(scientific notation such as ``1e+13`` is not handled). Purely numeric values are
|
|
76
|
+
left-zero-padded to 14; alphanumeric values are returned as-is (already 14).
|
|
77
|
+
An empty input yields an empty string.
|
|
78
|
+
"""
|
|
79
|
+
str_clean = _strip_float_artifact(str_value)
|
|
80
|
+
str_clean = _RE_NON_ALNUM.sub("", str_clean).upper()
|
|
81
|
+
if str_clean.isdigit():
|
|
82
|
+
str_clean = str_clean.zfill(_LEN_CNPJ)
|
|
83
|
+
return str_clean
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@type_checker
|
|
87
|
+
def mask_cnpj(str_value: str) -> str:
|
|
88
|
+
"""Format a CNPJ as ``XX.XXX.XXX/XXXX-XX``.
|
|
89
|
+
|
|
90
|
+
Parameters
|
|
91
|
+
----------
|
|
92
|
+
str_value : str
|
|
93
|
+
A CNPJ in any shape (it is unmasked first).
|
|
94
|
+
|
|
95
|
+
Returns
|
|
96
|
+
-------
|
|
97
|
+
str
|
|
98
|
+
The punctuated CNPJ when it normalises to 14 characters; otherwise the bare
|
|
99
|
+
unmasked value (so malformed input is surfaced, not silently reformatted). That
|
|
100
|
+
covers empty input, short alphanumeric values and values over 14 characters; a
|
|
101
|
+
purely numeric value is never short, since it is zero-padded to 14.
|
|
102
|
+
"""
|
|
103
|
+
str_clean = unmask_cnpj(str_value)
|
|
104
|
+
if len(str_clean) != _LEN_CNPJ:
|
|
105
|
+
return str_clean
|
|
106
|
+
return f"{str_clean[:2]}.{str_clean[2:5]}.{str_clean[5:8]}/{str_clean[8:12]}-{str_clean[12:]}"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@type_checker
|
|
110
|
+
def _cnpj_check_digit(str_base: str, *, tuple_weights: tuple[int, ...]) -> int:
|
|
111
|
+
"""Compute one CNPJ check digit via ASCII-48 mod-11 weighting.
|
|
112
|
+
|
|
113
|
+
Parameters
|
|
114
|
+
----------
|
|
115
|
+
str_base : str
|
|
116
|
+
The base characters the weights apply to (12 for DV1, 13 for DV2).
|
|
117
|
+
tuple_weights : tuple of int
|
|
118
|
+
Mod-11 weights, paired left-to-right with ``str_base``.
|
|
119
|
+
|
|
120
|
+
Returns
|
|
121
|
+
-------
|
|
122
|
+
int
|
|
123
|
+
The check digit (0 when the remainder is below 2, else ``11 - remainder``).
|
|
124
|
+
"""
|
|
125
|
+
int_sum = sum(
|
|
126
|
+
(ord(str_char) - _ASCII_ZERO) * int_weight
|
|
127
|
+
for str_char, int_weight in zip(str_base, tuple_weights, strict=True)
|
|
128
|
+
)
|
|
129
|
+
int_rest = int_sum % 11
|
|
130
|
+
return 0 if int_rest < _INT_MIN_REMAINDER else _INT_MODULUS - int_rest
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@type_checker
|
|
134
|
+
def is_valid_cnpj(str_value: str) -> bool:
|
|
135
|
+
"""Validate a CNPJ's two check digits (legacy numeric or 2026 alphanumeric).
|
|
136
|
+
|
|
137
|
+
Parameters
|
|
138
|
+
----------
|
|
139
|
+
str_value : str
|
|
140
|
+
A CNPJ in any shape (it is unmasked first).
|
|
141
|
+
|
|
142
|
+
Returns
|
|
143
|
+
-------
|
|
144
|
+
bool
|
|
145
|
+
``True`` when the value normalises to 14 characters whose last two are the
|
|
146
|
+
correct numeric check digits. Repeated-character numeric values (e.g. all
|
|
147
|
+
zeros) are rejected.
|
|
148
|
+
"""
|
|
149
|
+
str_clean = unmask_cnpj(str_value)
|
|
150
|
+
return (
|
|
151
|
+
len(str_clean) == _LEN_CNPJ
|
|
152
|
+
and str_clean[12:].isdigit()
|
|
153
|
+
and not (str_clean.isdigit() and len(set(str_clean)) == 1)
|
|
154
|
+
and str_clean[12:] == _cnpj_check_digits(str_clean[:12])
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@type_checker
|
|
159
|
+
def _cnpj_check_digits(str_base: str) -> str:
|
|
160
|
+
"""Return the two check digits for a 12-character CNPJ base.
|
|
161
|
+
|
|
162
|
+
Parameters
|
|
163
|
+
----------
|
|
164
|
+
str_base : str
|
|
165
|
+
The first 12 characters of an unmasked CNPJ.
|
|
166
|
+
|
|
167
|
+
Returns
|
|
168
|
+
-------
|
|
169
|
+
str
|
|
170
|
+
The two check digits, concatenated.
|
|
171
|
+
"""
|
|
172
|
+
int_dv1 = _cnpj_check_digit(str_base, tuple_weights=_CNPJ_WEIGHTS_DV1)
|
|
173
|
+
int_dv2 = _cnpj_check_digit(f"{str_base}{int_dv1}", tuple_weights=_CNPJ_WEIGHTS_DV2)
|
|
174
|
+
return f"{int_dv1}{int_dv2}"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@type_checker
|
|
178
|
+
def unmask_cpf(str_value: str) -> str:
|
|
179
|
+
"""Normalise a CPF to its bare 11-digit form.
|
|
180
|
+
|
|
181
|
+
Parameters
|
|
182
|
+
----------
|
|
183
|
+
str_value : str
|
|
184
|
+
A CPF in any shape — masked, zero-stripped, or carrying a float ``.0`` tail.
|
|
185
|
+
|
|
186
|
+
Returns
|
|
187
|
+
-------
|
|
188
|
+
str
|
|
189
|
+
Digits only, left-zero-padded to 11 when non-empty; empty input yields ``""``.
|
|
190
|
+
"""
|
|
191
|
+
str_clean = _strip_float_artifact(str_value)
|
|
192
|
+
str_clean = _RE_NON_DIGIT.sub("", str_clean)
|
|
193
|
+
if str_clean:
|
|
194
|
+
str_clean = str_clean.zfill(_LEN_CPF)
|
|
195
|
+
return str_clean
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@type_checker
|
|
199
|
+
def mask_cpf(str_value: str) -> str:
|
|
200
|
+
"""Format a CPF as ``XXX.XXX.XXX-XX``.
|
|
201
|
+
|
|
202
|
+
Parameters
|
|
203
|
+
----------
|
|
204
|
+
str_value : str
|
|
205
|
+
A CPF in any shape (it is unmasked first).
|
|
206
|
+
|
|
207
|
+
Returns
|
|
208
|
+
-------
|
|
209
|
+
str
|
|
210
|
+
The punctuated CPF when it normalises to 11 digits; otherwise the bare
|
|
211
|
+
unmasked value. That covers empty input and values over 11 digits; a shorter
|
|
212
|
+
non-empty value is never returned, since it is zero-padded to 11.
|
|
213
|
+
"""
|
|
214
|
+
str_clean = unmask_cpf(str_value)
|
|
215
|
+
if len(str_clean) != _LEN_CPF:
|
|
216
|
+
return str_clean
|
|
217
|
+
return f"{str_clean[:3]}.{str_clean[3:6]}.{str_clean[6:9]}-{str_clean[9:]}"
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@type_checker
|
|
221
|
+
def _cpf_check_digit(str_base: str, *, int_start_weight: int) -> int:
|
|
222
|
+
"""Compute one CPF check digit via descending mod-11 weighting.
|
|
223
|
+
|
|
224
|
+
Parameters
|
|
225
|
+
----------
|
|
226
|
+
str_base : str
|
|
227
|
+
The base digits the weights apply to (9 for DV1, 10 for DV2).
|
|
228
|
+
int_start_weight : int
|
|
229
|
+
The first (largest) weight; subsequent weights descend by one.
|
|
230
|
+
|
|
231
|
+
Returns
|
|
232
|
+
-------
|
|
233
|
+
int
|
|
234
|
+
The check digit (0 when the remainder is below 2, else ``11 - remainder``).
|
|
235
|
+
"""
|
|
236
|
+
int_sum = sum(
|
|
237
|
+
int(str_char) * (int_start_weight - int_idx) for int_idx, str_char in enumerate(str_base)
|
|
238
|
+
)
|
|
239
|
+
int_rest = int_sum % 11
|
|
240
|
+
return 0 if int_rest < _INT_MIN_REMAINDER else _INT_MODULUS - int_rest
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@type_checker
|
|
244
|
+
def is_valid_cpf(str_value: str) -> bool:
|
|
245
|
+
"""Validate a CPF's two check digits.
|
|
246
|
+
|
|
247
|
+
Parameters
|
|
248
|
+
----------
|
|
249
|
+
str_value : str
|
|
250
|
+
A CPF in any shape (it is unmasked first).
|
|
251
|
+
|
|
252
|
+
Returns
|
|
253
|
+
-------
|
|
254
|
+
bool
|
|
255
|
+
``True`` when the value normalises to 11 digits whose last two are the correct
|
|
256
|
+
check digits. Repeated-digit values (e.g. all ones) are rejected.
|
|
257
|
+
"""
|
|
258
|
+
str_clean = unmask_cpf(str_value)
|
|
259
|
+
return (
|
|
260
|
+
len(str_clean) == _LEN_CPF
|
|
261
|
+
and str_clean.isdigit()
|
|
262
|
+
and len(set(str_clean)) > 1
|
|
263
|
+
and str_clean[9:] == _cpf_check_digits(str_clean)
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@type_checker
|
|
268
|
+
def _cpf_check_digits(str_clean: str) -> str:
|
|
269
|
+
"""Return the two check digits for an 11-digit CPF.
|
|
270
|
+
|
|
271
|
+
Parameters
|
|
272
|
+
----------
|
|
273
|
+
str_clean : str
|
|
274
|
+
An unmasked, 11-digit CPF.
|
|
275
|
+
|
|
276
|
+
Returns
|
|
277
|
+
-------
|
|
278
|
+
str
|
|
279
|
+
The two check digits, concatenated.
|
|
280
|
+
"""
|
|
281
|
+
int_dv1 = _cpf_check_digit(str_clean[:9], int_start_weight=10)
|
|
282
|
+
int_dv2 = _cpf_check_digit(str_clean[:10], int_start_weight=11)
|
|
283
|
+
return f"{int_dv1}{int_dv2}"
|
pure_docs_br/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pure-docs-br
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Valida, aplica e remove a máscara de documentos brasileiros
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: pure-docs-br,python,library
|
|
8
|
+
Author: guilhermegor
|
|
9
|
+
Requires-Python: >=3.11,<4.0
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Project-URL: Bug Reports, https://github.com/guilhermegor/pure-docs-br/issues
|
|
22
|
+
Project-URL: Documentation, https://guilhermegor.github.io/pure-docs-br/
|
|
23
|
+
Project-URL: Homepage, https://guilhermegor.github.io/pure-docs-br/
|
|
24
|
+
Project-URL: Repository, https://github.com/guilhermegor/pure-docs-br
|
|
25
|
+
Project-URL: Source, https://github.com/guilhermegor/pure-docs-br
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
<!-- readme-archetype: library -->
|
|
29
|
+
# pure-docs-br
|
|
30
|
+
|
|
31
|
+
<p align="center"><img src="https://raw.githubusercontent.com/guilhermegor/pure-docs-br/main/assets/logo.png" width="200" alt="pure-docs-br logo"></p>
|
|
32
|
+
|
|
33
|
+
[](https://www.repostatus.org/#active)
|
|
34
|
+

|
|
35
|
+
[](https://pypi.org/project/pure-docs-br/)
|
|
36
|
+
[](https://pepy.tech/projects/pure-docs-br)
|
|
37
|
+
[](https://guilhermegor.github.io/pure-docs-br/)
|
|
38
|
+
[](https://github.com/astral-sh/ruff)
|
|
39
|
+
[](https://mypy-lang.org)
|
|
40
|
+

|
|
41
|
+

|
|
42
|
+

|
|
43
|
+

|
|
44
|
+
|
|
45
|
+
<!-- slug: overview -->
|
|
46
|
+
## Visão geral
|
|
47
|
+
|
|
48
|
+
Valida, aplica e remove a máscara de documentos brasileiros
|
|
49
|
+
|
|
50
|
+
<!-- optional section: delete it when the project has no feature list -->
|
|
51
|
+
<!-- slug: features -->
|
|
52
|
+
## Funcionalidades
|
|
53
|
+
|
|
54
|
+
- Valida CPF e CNPJ pelos dígitos verificadores, inclusive o CNPJ alfanumérico que passa a existir em 2026.
|
|
55
|
+
- Aplica e remove a máscara (`XXX.XXX.XXX-XX` e `XX.XXX.XXX/XXXX-XX`).
|
|
56
|
+
- Tolera texto sujo: pontuação, zeros à esquerda perdidos e a cauda `.0` de um número que virou `str` (por exemplo `"52998224725.0"`).
|
|
57
|
+
- Funções puras, sem I/O e sem dependências de execução.
|
|
58
|
+
|
|
59
|
+
<!-- slug: documentation -->
|
|
60
|
+
## Documentação
|
|
61
|
+
|
|
62
|
+
O site de documentação fica em https://guilhermegor.github.io/pure-docs-br/. Para servi-lo localmente, rode `poetry run poe docs_serve`.
|
|
63
|
+
|
|
64
|
+
<!-- slug: getting-started -->
|
|
65
|
+
## Primeiros passos
|
|
66
|
+
|
|
67
|
+
O Python 3.11+ é o único pré-requisito; o `bin/venv.sh` instala o [Poetry](https://python-poetry.org/) quando ele estiver ausente.
|
|
68
|
+
|
|
69
|
+
<!-- slug: install -->
|
|
70
|
+
### Instalação
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
git clone https://github.com/guilhermegor/pure-docs-br.git
|
|
74
|
+
cd pure-docs-br
|
|
75
|
+
bash bin/venv.sh
|
|
76
|
+
poetry run poe init
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
O `poe` vive dentro do virtualenv, então o `bin/venv.sh` o cria primeiro; em seguida o
|
|
80
|
+
`poetry run poe init` o executa sem ativar nada. Se o `poetry` não estiver no `PATH` (por exemplo
|
|
81
|
+
logo depois de o `bin/venv.sh` instalá-lo com `--user`), use `bash bin/poe_exec.sh init`, que
|
|
82
|
+
encontra o `poe` do venv sozinho.
|
|
83
|
+
|
|
84
|
+
<!-- slug: usage -->
|
|
85
|
+
### Uso
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
pip install pure-docs-br
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Toda função recebe e devolve `str` (ou `bool`) e aceita o documento com ou sem máscara.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from pure_docs_br import (
|
|
95
|
+
is_valid_cnpj,
|
|
96
|
+
is_valid_cpf,
|
|
97
|
+
mask_cnpj,
|
|
98
|
+
mask_cpf,
|
|
99
|
+
unmask_cnpj,
|
|
100
|
+
unmask_cpf,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
mask_cpf("52998224725") # "529.982.247-25"
|
|
104
|
+
unmask_cpf("529.982.247-25") # "52998224725"
|
|
105
|
+
unmask_cpf("1234567") # "00001234567", completa com zeros à esquerda
|
|
106
|
+
is_valid_cpf("529.982.247-25") # True
|
|
107
|
+
is_valid_cpf("11111111111") # False, dígitos repetidos
|
|
108
|
+
|
|
109
|
+
mask_cnpj("11222333000181") # "11.222.333/0001-81"
|
|
110
|
+
mask_cnpj("12ABC34501DE35") # "12.ABC.345/01DE-35"
|
|
111
|
+
unmask_cnpj("12.abc.345/01de-35") # "12ABC34501DE35", maiúsculas
|
|
112
|
+
unmask_cnpj("11222333000181.0") # "11222333000181", descarta a cauda ".0"
|
|
113
|
+
is_valid_cnpj("11.222.333/0001-81") # True
|
|
114
|
+
is_valid_cnpj("12.ABC.345/01DE-35") # True, formato alfanumérico
|
|
115
|
+
is_valid_cnpj("11222333000182") # False, dígito verificador errado
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Entrada inválida
|
|
119
|
+
|
|
120
|
+
- Toda função exige `str`: qualquer outro tipo (`None`, `float`, `int`, inclusive o `NaN` de uma
|
|
121
|
+
coluna do pandas) lança `TypeError`. Converta antes, por exemplo com `.astype(str)`, ou filtre
|
|
122
|
+
os nulos.
|
|
123
|
+
- Dado um `str`, nenhuma função lança exceção. `is_valid_*` devolve `False` para texto vazio,
|
|
124
|
+
com tamanho errado ou com dígito verificador errado, então uma linha ruim não interrompe a
|
|
125
|
+
transformação de uma coluna inteira.
|
|
126
|
+
- `mask_*` devolve o valor sem máscara (o que `unmask_*` produz) quando ele não tem o tamanho do
|
|
127
|
+
documento. Isso ocorre com texto vazio, com mais de 11 dígitos (CPF) ou 14 caracteres (CNPJ) e
|
|
128
|
+
com CNPJ alfanumérico curto; um CPF ou CNPJ só de dígitos nunca é curto, pois `unmask_*` o
|
|
129
|
+
completa com zeros.
|
|
130
|
+
- Entrada numérica curta é completada com zeros à esquerda (11 para CPF, 14 para CNPJ) antes de
|
|
131
|
+
os dígitos verificadores serem testados, o mesmo preenchimento que `unmask_*` aplica. É
|
|
132
|
+
intencional: recupera documentos guardados como número que perderam os zeros (Excel, pandas).
|
|
133
|
+
Por consequência, `is_valid_cpf("191")` e `is_valid_cnpj("191")` devolvem `True`, pois `"191"`
|
|
134
|
+
vira `00000000191`. Valores de um só dígito repetido continuam rejeitados: `"0"` vira
|
|
135
|
+
`00000000000` e `is_valid_cpf("0")` é `False`.
|
|
136
|
+
- A cauda `.0` é descartada por `unmask_cpf` e `unmask_cnpj`. A notação científica
|
|
137
|
+
(`"1.1222333000181e+13"`) não é tratada: converta o número para texto sem expoente antes.
|
|
138
|
+
|
|
139
|
+
O dígito verificador do CNPJ segue o cálculo de módulo 11 do
|
|
140
|
+
[Serpro](https://www.serpro.gov.br/menu/noticias/videos/calculodvcnpjalfanaumerico.pdf) e da
|
|
141
|
+
[Receita Federal](https://www.gov.br/receitafederal/pt-br/centrais-de-conteudo/publicacoes/perguntas-e-respostas/cnpj/cnpj-alfanumerico.pdf).
|
|
142
|
+
|
|
143
|
+
<!-- slug: project-structure -->
|
|
144
|
+
## Estrutura do projeto
|
|
145
|
+
|
|
146
|
+
```text
|
|
147
|
+
pure-docs-br/
|
|
148
|
+
├── .github/ workflows, CODEOWNERS e template de PR
|
|
149
|
+
├── .specs/ specs de funcionalidades e trackers de backlog
|
|
150
|
+
├── bin/ scripts de gate e utilitários
|
|
151
|
+
├── docs/ documentação publicada
|
|
152
|
+
├── src/ o pacote `pure_docs_br`
|
|
153
|
+
├── tests/
|
|
154
|
+
│ ├── unit/
|
|
155
|
+
│ └── integration/
|
|
156
|
+
├── pyproject.toml
|
|
157
|
+
└── poe_tasks.toml pontos de entrada do task runner
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
<!-- slug: development -->
|
|
161
|
+
## Desenvolvimento
|
|
162
|
+
|
|
163
|
+
Depois do bootstrap descrito em Instalação, qualquer tarefa pode ser executada com
|
|
164
|
+
`poetry run poe <task>`; e `poetry run poe` sem tarefa lista todas elas.
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
poetry run poe unit_tests
|
|
168
|
+
poetry run poe integration_tests
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Quando o deploy da documentação do primeiro release tiver criado a branch `gh-pages`, rode
|
|
172
|
+
`poetry run poe enable_pages` uma vez: até que essa branch exista, o `init` deixa o Pages intocado.
|
|
173
|
+
|
|
174
|
+
### `poetry run poe` ou `bash bin/poe_exec.sh`?
|
|
175
|
+
|
|
176
|
+
Os dois rodam a mesma tarefa do mesmo `poe` do venv. Use `poetry run poe`, o comando que a
|
|
177
|
+
comunidade conhece; o `bin/poe_exec.sh` cobre os casos em que ele não basta:
|
|
178
|
+
|
|
179
|
+
| Situação | `poetry run poe` | `bash bin/poe_exec.sh` |
|
|
180
|
+
|---|---|---|
|
|
181
|
+
| Máquina comum, `poetry` no `PATH` | funciona | funciona |
|
|
182
|
+
| `poetry` fora do `PATH` (ex.: recém-instalado com `--user`) | falha: `poetry: command not found` | funciona: acha `.venv/bin/poe` (ou `.venv/Scripts/poe.exe` no Windows) sem o `poetry` |
|
|
183
|
+
| Rede corporativa com inspeção TLS (`bin/corporate_ca.pem` presente) | tarefas que baixam algo podem falhar com erro de certificado | funciona: monta o bundle de CAs e o exporta antes de rodar a tarefa |
|
|
184
|
+
| `poe` não instalado | erro genérico do Poetry | lista as formas de instalar (`bin/venv.sh`, `pipx`, plugin do Poetry) |
|
|
185
|
+
|
|
186
|
+
<!-- slug: public-api -->
|
|
187
|
+
## API pública
|
|
188
|
+
|
|
189
|
+
A superfície pública é o que o `__init__.py` do pacote lista em `__all__`:
|
|
190
|
+
`__version__`, `is_valid_cnpj`, `is_valid_cpf`, `mask_cnpj`, `mask_cpf`, `unmask_cnpj` e
|
|
191
|
+
`unmask_cpf`.
|
|
192
|
+
|
|
193
|
+
### Garantia de API da 1.x
|
|
194
|
+
|
|
195
|
+
A partir da 1.0.0 vale o semver completo. Dentro da 1.x, esses nomes continuam importáveis da raiz
|
|
196
|
+
do pacote com a mesma assinatura e o mesmo comportamento documentado: remover ou alterar um deles
|
|
197
|
+
exige uma 2.0. Uma versão MINOR só acrescenta, e uma PATCH só corrige defeitos. Tudo sob
|
|
198
|
+
`pure_docs_br._internal` é privado e fica fora da garantia.
|
|
199
|
+
|
|
200
|
+
<!-- slug: publishing -->
|
|
201
|
+
## Publicação
|
|
202
|
+
|
|
203
|
+
Os lançamentos saem dos workflows de release em `.github/workflows/`; a tag do git é a versão.
|
|
204
|
+
|
|
205
|
+
O caminho até a 1.0.0, e o gate de lançamento que o protege, está em
|
|
206
|
+
[docs/releasing-1-0-0.md](docs/releasing-1-0-0.md).
|
|
207
|
+
|
|
208
|
+
<!-- slug: contributing -->
|
|
209
|
+
## Contribuindo
|
|
210
|
+
|
|
211
|
+
Veja o [CONTRIBUTING.md](CONTRIBUTING.md) para as regras de branch, commit e revisão.
|
|
212
|
+
|
|
213
|
+
<!-- slug: license -->
|
|
214
|
+
## Licença
|
|
215
|
+
|
|
216
|
+
Este projeto é licenciado sob MIT; veja [LICENSE](LICENSE).
|
|
217
|
+
|
|
218
|
+
<!-- slug: authors -->
|
|
219
|
+
## Autores
|
|
220
|
+
|
|
221
|
+
- guilhermegor — [GitHub](https://github.com/guilhermegor) | [LinkedIn](https://www.linkedin.com/in/guilhermegor)
|
|
222
|
+
|
|
223
|
+
<!-- slug: useful-links -->
|
|
224
|
+
## Links úteis
|
|
225
|
+
|
|
226
|
+
- [Repositório no GitHub](https://github.com/guilhermegor/pure-docs-br)
|
|
227
|
+
- [Issue Tracker](https://github.com/guilhermegor/pure-docs-br/issues)
|
|
228
|
+
- [Documentação](https://guilhermegor.github.io/pure-docs-br/)
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
<sub>Gerado a partir do template lib-minimal via [BlueprintX](https://github.com/guilhermegor/blueprintx).</sub>
|
|
233
|
+
<!-- add any project disclaimer inside the sub tag above; for a library wrapping a third party, e.g. "Unofficial, community library. Not affiliated with or endorsed by ORG_NAME." -->
|
|
234
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pure_docs_br/__init__.py,sha256=xTh8t_3WEaugQS5PxL8BWWUb7ZW3NucV7gcswfOwO-s,532
|
|
2
|
+
pure_docs_br/_internal/__init__.py,sha256=Ynu7OvFSdVYqjV91IziuVdgXh22HNSEW1sSCEXtldsM,72
|
|
3
|
+
pure_docs_br/_internal/utils/__init__.py,sha256=XLVr2DDqPaUUZJXDp3ywFMuw-CqVp5yzJXzIVurRyXM,52
|
|
4
|
+
pure_docs_br/_internal/utils/typing/__init__.py,sha256=-aw5mt7P1F3buZo7tEodg4nZz_LGRGnUA7K0z5ZWD2o,156
|
|
5
|
+
pure_docs_br/_internal/utils/typing/type_checker.py,sha256=FFJQLE47IEYd_tyEIuIivlbg5R6IXzeDBlOtezXMjyQ,3181
|
|
6
|
+
pure_docs_br/br_identifiers.py,sha256=iVK4LAiJTrqUSb8Y7xUtRCK2eZXmZYWoVyo0PJOnt4I,8962
|
|
7
|
+
pure_docs_br/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
pure_docs_br-1.0.0.dist-info/METADATA,sha256=GHvqFjcismzV6FE06ygv_zx7jHArFlowXR9I-_L3vQg,10365
|
|
9
|
+
pure_docs_br-1.0.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
10
|
+
pure_docs_br-1.0.0.dist-info/licenses/LICENSE,sha256=QQvP0wwMeLv-7JVnO8fwxsni4hj_S5BSISgfZNWJ9_U,1069
|
|
11
|
+
pure_docs_br-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 guilhermegor
|
|
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.
|