doepe 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
doepe-0.1.0/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .pytest_cache/
4
+ .venv/
5
+ dist/
6
+ *.tar.gz
7
+ *.Rcheck/
8
+ .Rhistory
9
+ .Rproj.user/
10
+ .claude/scratch/
11
+ uv.lock
12
+ .DS_Store
13
+ r/docs/
14
+ python/site/
15
+ _site/
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - First release.
6
+ - `Client.items()` and `Client.items_range()`: items of a day or of a date range, from
7
+ the regular and the extra edition.
8
+ - `filter_items()`: filter by term and by category, ignoring case and accents.
9
+ - `edition_exists()`, `last_edition()`, `categories()` and `gazettes()`.
10
+ - `pdf_url()`, `cover_url()` and `download_pdf()`.
11
+ - Paced requests, automatic wait when the site quota runs out (`Client.quota`), a disk
12
+ cache (`clear_cache()`) and messages through `logging`.
13
+ - A Portuguese alias for every public name (`Cliente`, `materias()`, `filtrar()`...).
doepe-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 doepe authors
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.
doepe-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.5
2
+ Name: doepe
3
+ Version: 0.1.0
4
+ Summary: Unofficial client for the public search of the Official Gazette of the State of Pernambuco, Brazil
5
+ Project-URL: Documentation, https://strategicprojects.github.io/doepe/python/
6
+ Project-URL: Repository, https://github.com/StrategicProjects/doepe
7
+ Project-URL: Issues, https://github.com/StrategicProjects/doepe/issues
8
+ Project-URL: Changelog, https://github.com/StrategicProjects/doepe/blob/main/python/CHANGELOG.md
9
+ Author-email: André Leite <leite@castlab.org>, Marcos Wasiliew <marcos.wasiliew@gmail.com>, Hugo Vasconcelos <hugo.vasconcelos@ufpe.br>, Carlos Amorim <carlos.agaf@ufpe.br>, Diogo Bezerra <diogo.bezerra@ufpe.br>, Júlia Nascimento Barreto <juliabarreto@gd.seplag.pe.gov.br>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: brazil,cepe,diário oficial,official gazette,open government,pernambuco
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Natural Language :: Portuguese (Brazilian)
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Provides-Extra: docs
28
+ Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
29
+ Requires-Dist: mkdocstrings[python]>=0.24; extra == 'docs'
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7.0; extra == 'test'
32
+ Description-Content-Type: text/markdown
33
+
34
+ <img src="https://raw.githubusercontent.com/StrategicProjects/doepe/main/logos/logo-python.svg" align="right" height="139" alt="" />
35
+
36
+ # doepe
37
+
38
+ An **unofficial** client for the public search of the Official Gazette of the State of
39
+ Pernambuco, Brazil (*Diário Oficial do Estado de Pernambuco*). It returns the items
40
+ published in an edition as plain text, with no PDF parsing, and has no dependencies
41
+ beyond the standard library.
42
+
43
+ > **Disclaimer.** The data belong to
44
+ > [Companhia Editora de Pernambuco (CEPE)](https://www.cepe.com.br/), publisher of the
45
+ > [Official Gazette of the State](https://diariooficial.cepe.com.br/diariooficialweb/).
46
+ > This package only queries the public service of the gazette; it is not official, it is
47
+ > not affiliated with CEPE and it neither changes nor replaces the original publication,
48
+ > which is the valid source.
49
+
50
+ The service used is internal to the gazette's website: it has no contract or guarantee
51
+ and may change without notice.
52
+
53
+ Documentation (in Portuguese): <https://strategicprojects.github.io/doepe/python/>.
54
+ Using R? There is a package with the same name and the same queries:
55
+ [doepe for R](https://strategicprojects.github.io/doepe/r/).
56
+
57
+ ## Installation
58
+
59
+ ```sh
60
+ pip install doepe
61
+ ```
62
+
63
+ ## Usage
64
+
65
+ ```python
66
+ import doepe
67
+
68
+ c = doepe.Client()
69
+ items = c.items("2026-12-04") # list of Item (regular + extra edition)
70
+
71
+ doepe.filter_items(items, text=["condepe", "fidem"])
72
+ doepe.filter_items(items, category="governo do estado")
73
+
74
+ c.edition_exists("2026-12-04") # True / False
75
+ c.last_edition() # date
76
+ c.pdf_url("2026-12-04") # address of the edition's PDF
77
+
78
+ for m in c.items_range("2026-12-01", "2026-12-04"):
79
+ print(m.data, m.categoria, m.titulo)
80
+ ```
81
+
82
+ Every public name has a Portuguese alias, so a script can stay in one language:
83
+
84
+ ```python
85
+ c = doepe.Cliente()
86
+ materias = c.materias("2026-12-04")
87
+ doepe.filtrar(materias, texto=["condepe", "fidem"])
88
+ c.existe_edicao("2026-12-04")
89
+ ```
90
+
91
+ Each `Item` has `codigo`, `data`, `diario`, `categoria`, `codigo_categoria`,
92
+ `codigo_categoria_pai`, `titulo`, `subtitulo`, `texto`, `resumo` and `extra`. Field names
93
+ follow the source and are in Portuguese. `m.as_dict()` returns a dictionary, ready for
94
+ `pandas.DataFrame`.
95
+
96
+ ## What the package takes care of
97
+
98
+ - **Pacing and quota.** One request every 2 seconds. The site limits the number of
99
+ queries per time window; when the quota runs out, the client waits for the time
100
+ requested and carries on. `Client.quota` holds the balance.
101
+ - **Cache.** Editions of past days are stored on disk (`~/.cache/doepe`) and are not
102
+ requested again. `Client(cache=False)` turns it off; `clear_cache()` removes it.
103
+ - **Format.** If the site changes its response, `UnexpectedFormat` says so instead of
104
+ returning wrong data.
105
+ - **Messages.** Through the standard `logging` module, logger `"doepe"`.
106
+
107
+ ## Known limits
108
+
109
+ - The electronic version starts in 2019.
110
+ - Tables arrive flattened into the text.
111
+ - Only gazette `1` (Official Gazette of the State) was checked.
112
+ - The items carry names of people; the use of these data is the responsibility of
113
+ whoever processes them.
114
+
115
+ MIT licence.
doepe-0.1.0/README.md ADDED
@@ -0,0 +1,82 @@
1
+ <img src="https://raw.githubusercontent.com/StrategicProjects/doepe/main/logos/logo-python.svg" align="right" height="139" alt="" />
2
+
3
+ # doepe
4
+
5
+ An **unofficial** client for the public search of the Official Gazette of the State of
6
+ Pernambuco, Brazil (*Diário Oficial do Estado de Pernambuco*). It returns the items
7
+ published in an edition as plain text, with no PDF parsing, and has no dependencies
8
+ beyond the standard library.
9
+
10
+ > **Disclaimer.** The data belong to
11
+ > [Companhia Editora de Pernambuco (CEPE)](https://www.cepe.com.br/), publisher of the
12
+ > [Official Gazette of the State](https://diariooficial.cepe.com.br/diariooficialweb/).
13
+ > This package only queries the public service of the gazette; it is not official, it is
14
+ > not affiliated with CEPE and it neither changes nor replaces the original publication,
15
+ > which is the valid source.
16
+
17
+ The service used is internal to the gazette's website: it has no contract or guarantee
18
+ and may change without notice.
19
+
20
+ Documentation (in Portuguese): <https://strategicprojects.github.io/doepe/python/>.
21
+ Using R? There is a package with the same name and the same queries:
22
+ [doepe for R](https://strategicprojects.github.io/doepe/r/).
23
+
24
+ ## Installation
25
+
26
+ ```sh
27
+ pip install doepe
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ import doepe
34
+
35
+ c = doepe.Client()
36
+ items = c.items("2026-12-04") # list of Item (regular + extra edition)
37
+
38
+ doepe.filter_items(items, text=["condepe", "fidem"])
39
+ doepe.filter_items(items, category="governo do estado")
40
+
41
+ c.edition_exists("2026-12-04") # True / False
42
+ c.last_edition() # date
43
+ c.pdf_url("2026-12-04") # address of the edition's PDF
44
+
45
+ for m in c.items_range("2026-12-01", "2026-12-04"):
46
+ print(m.data, m.categoria, m.titulo)
47
+ ```
48
+
49
+ Every public name has a Portuguese alias, so a script can stay in one language:
50
+
51
+ ```python
52
+ c = doepe.Cliente()
53
+ materias = c.materias("2026-12-04")
54
+ doepe.filtrar(materias, texto=["condepe", "fidem"])
55
+ c.existe_edicao("2026-12-04")
56
+ ```
57
+
58
+ Each `Item` has `codigo`, `data`, `diario`, `categoria`, `codigo_categoria`,
59
+ `codigo_categoria_pai`, `titulo`, `subtitulo`, `texto`, `resumo` and `extra`. Field names
60
+ follow the source and are in Portuguese. `m.as_dict()` returns a dictionary, ready for
61
+ `pandas.DataFrame`.
62
+
63
+ ## What the package takes care of
64
+
65
+ - **Pacing and quota.** One request every 2 seconds. The site limits the number of
66
+ queries per time window; when the quota runs out, the client waits for the time
67
+ requested and carries on. `Client.quota` holds the balance.
68
+ - **Cache.** Editions of past days are stored on disk (`~/.cache/doepe`) and are not
69
+ requested again. `Client(cache=False)` turns it off; `clear_cache()` removes it.
70
+ - **Format.** If the site changes its response, `UnexpectedFormat` says so instead of
71
+ returning wrong data.
72
+ - **Messages.** Through the standard `logging` module, logger `"doepe"`.
73
+
74
+ ## Known limits
75
+
76
+ - The electronic version starts in 2019.
77
+ - Tables arrive flattened into the text.
78
+ - Only gazette `1` (Official Gazette of the State) was checked.
79
+ - The items carry names of people; the use of these data is the responsibility of
80
+ whoever processes them.
81
+
82
+ MIT licence.
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "doepe"
7
+ version = "0.1.0"
8
+ description = "Unofficial client for the public search of the Official Gazette of the State of Pernambuco, Brazil"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "André Leite", email = "leite@castlab.org" },
15
+ { name = "Marcos Wasiliew", email = "marcos.wasiliew@gmail.com" },
16
+ { name = "Hugo Vasconcelos", email = "hugo.vasconcelos@ufpe.br" },
17
+ { name = "Carlos Amorim", email = "carlos.agaf@ufpe.br" },
18
+ { name = "Diogo Bezerra", email = "diogo.bezerra@ufpe.br" },
19
+ { name = "Júlia Nascimento Barreto", email = "juliabarreto@gd.seplag.pe.gov.br" },
20
+ ]
21
+ keywords = ["official gazette", "diário oficial", "pernambuco", "brazil", "cepe", "open government"]
22
+ dependencies = []
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Intended Audience :: Science/Research",
26
+ "Intended Audience :: Developers",
27
+ "Natural Language :: Portuguese (Brazilian)",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Topic :: Scientific/Engineering :: Information Analysis",
36
+ "Typing :: Typed",
37
+ ]
38
+
39
+ [project.urls]
40
+ Documentation = "https://strategicprojects.github.io/doepe/python/"
41
+ Repository = "https://github.com/StrategicProjects/doepe"
42
+ Issues = "https://github.com/StrategicProjects/doepe/issues"
43
+ Changelog = "https://github.com/StrategicProjects/doepe/blob/main/python/CHANGELOG.md"
44
+
45
+ [project.optional-dependencies]
46
+ test = ["pytest>=7.0"]
47
+ docs = ["mkdocs-material>=9.5", "mkdocstrings[python]>=0.24"]
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/doepe"]
51
+
52
+ [tool.hatch.build.targets.sdist]
53
+ include = ["src", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
54
+
55
+ [tool.pytest.ini_options]
56
+ testpaths = ["tests"]
@@ -0,0 +1,45 @@
1
+ """Unofficial client for the public search of the Official Gazette of Pernambuco.
2
+
3
+ Names are in English; every public name also has a Portuguese alias.
4
+ """
5
+
6
+ from .client import (
7
+ Blocked,
8
+ Bloqueado,
9
+ Client,
10
+ Cliente,
11
+ DoepeError,
12
+ ErroDoepe,
13
+ ErroHTTP,
14
+ FormatoInesperado,
15
+ HTTPError,
16
+ Item,
17
+ LimiteExcedido,
18
+ Materia,
19
+ RateLimited,
20
+ UnexpectedFormat,
21
+ filter_items,
22
+ filtrar,
23
+ )
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ __all__ = [
28
+ "Blocked",
29
+ "Client",
30
+ "DoepeError",
31
+ "HTTPError",
32
+ "Item",
33
+ "RateLimited",
34
+ "UnexpectedFormat",
35
+ "filter_items",
36
+ # Portuguese aliases
37
+ "Bloqueado",
38
+ "Cliente",
39
+ "ErroDoepe",
40
+ "ErroHTTP",
41
+ "FormatoInesperado",
42
+ "LimiteExcedido",
43
+ "Materia",
44
+ "filtrar",
45
+ ]
@@ -0,0 +1,60 @@
1
+ {
2
+ "versao": 1,
3
+ "base_api": "https://diariooficial.cepe.com.br/diariooficial/public",
4
+ "base_arquivos": "https://cepebr-prod.s3.sa-east-1.amazonaws.com",
5
+ "endpoints": {
6
+ "materias": {
7
+ "caminho": "/visualizar-diario/buscarDiario",
8
+ "params": {"dataPublicacao": "data_tracos", "codigoDiarioOficial": "diario_base64"},
9
+ "resposta": "lista",
10
+ "campos": ["codigo", "texto", "nomeCategoria", "codigoCategoria", "dataPublicacao", "codigoDiario"],
11
+ "verificado": true
12
+ },
13
+ "materias_extra": {
14
+ "caminho": "/visualizar-diario/buscarDiarioExtra",
15
+ "params": {"dataPublicacao": "data_barras", "codigoDiarioOficial": "diario_numero"},
16
+ "resposta": "lista",
17
+ "campos": ["codigo", "texto", "nomeCategoria", "codigoCategoria", "dataPublicacao", "codigoDiario"],
18
+ "nota": "Em 2026-11-15 (dia so com edicao extra) devolveu a materia com texto vazio e o PDF em base64 no campo file; a consulta materias devolveu a mesma materia com texto.",
19
+ "verificado": true
20
+ },
21
+ "categorias": {
22
+ "caminho": "/visualizar-diario/consultarTodasCategoriasDiario",
23
+ "params": {"codigoDiarioOficial": "diario_base64"},
24
+ "resposta": "lista",
25
+ "campos": ["id", "nome"],
26
+ "verificado": true
27
+ },
28
+ "existe_edicao": {
29
+ "caminho": "/home/existeDiarioHome",
30
+ "params": {"codigoDiario": "diario_numero", "dataPublicacao": "data_barras"},
31
+ "resposta": "logico",
32
+ "verificado": true
33
+ },
34
+ "existe_extra": {
35
+ "caminho": "/home/existeDiarioExtraHome",
36
+ "params": {"codigoDiario": "diario_numero", "dataPublicacao": "data_barras"},
37
+ "resposta": "logico",
38
+ "verificado": true
39
+ },
40
+ "ultima_edicao": {
41
+ "caminho": "/home/dataUltimoJornalPublicado",
42
+ "params": {"codigoDiario": "diario_numero"},
43
+ "resposta": "data_barras",
44
+ "verificado": true
45
+ },
46
+ "diarios": {
47
+ "caminho": "/diarios",
48
+ "params": {},
49
+ "resposta": "lista",
50
+ "campos": ["codigo", "nomeFantasia"],
51
+ "verificado": true
52
+ }
53
+ },
54
+ "arquivos": {
55
+ "pdf": "{diario}/arquivos/resumoDiario/{data_iso}/{data_iso}{sufixo_extra}.pdf",
56
+ "capa": "{diario}/capas/{data_iso}{sufixo_extra}.png"
57
+ },
58
+ "sufixo_extra": "E",
59
+ "primeiro_ano": 2019
60
+ }
@@ -0,0 +1,576 @@
1
+ """Client for the public search of the Official Gazette of the State of Pernambuco.
2
+
3
+ The data belong to Companhia Editora de Pernambuco (CEPE, https://www.cepe.com.br/),
4
+ publisher of the gazette. This package is not official and is not affiliated with
5
+ CEPE; the original publication is the valid source.
6
+
7
+ The service is internal to the gazette's website: it has no contract or guarantee.
8
+ Addresses and parameter formats live in ``api.json`` (a copy of ``spec/api.json``,
9
+ the single source shared with the R package).
10
+
11
+ Names are in English, and every public name has a Portuguese alias
12
+ (``Cliente.materias()`` for ``Client.items()``, and so on). Field names of the
13
+ returned data follow the source and are in Portuguese.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import json
20
+ import logging
21
+ import os
22
+ import time
23
+ import unicodedata
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+ from collections.abc import Callable, Iterable, Iterator
28
+ from dataclasses import asdict, dataclass
29
+ from datetime import date, datetime, timedelta
30
+ from importlib import resources
31
+ from pathlib import Path
32
+
33
+ SPEC = json.loads(resources.files("doepe").joinpath("api.json").read_text("utf-8"))
34
+
35
+ # Messages go through the standard logging module, logger "doepe": quota warnings
36
+ # at WARNING, progress at INFO, each request at DEBUG. To see them:
37
+ # logging.basicConfig(level=logging.INFO)
38
+ log = logging.getLogger("doepe")
39
+
40
+ USER_AGENT = "doepe-python/0.1.0 (unofficial client; research)"
41
+
42
+ _EDITIONS = ("all", "regular", "extra")
43
+ _EDITIONS_PT = {"todas": "all", "normal": "regular", "extra": "extra"}
44
+
45
+
46
+ class DoepeError(Exception):
47
+ """Base class of the package errors."""
48
+
49
+
50
+ class HTTPError(DoepeError):
51
+ """An HTTP error answered by the site."""
52
+
53
+ def __init__(
54
+ self,
55
+ status: int,
56
+ url: str,
57
+ retry_after: float | None = None,
58
+ headers: dict | None = None,
59
+ ):
60
+ super().__init__(f"HTTP {status} at {url}")
61
+ self.status = status
62
+ self.url = url
63
+ self.retry_after = retry_after
64
+ self.headers = headers or {}
65
+
66
+
67
+ class Blocked(HTTPError):
68
+ """The site refused the request (403). Do not insist: slow down or stop."""
69
+
70
+
71
+ class RateLimited(HTTPError):
72
+ """The site answered 429: the request quota ran out.
73
+
74
+ ``retry_after`` holds, when the site reports it, how many seconds to wait.
75
+ """
76
+
77
+
78
+ class UnexpectedFormat(DoepeError):
79
+ """The response does not have the expected format; the service probably changed."""
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class Item:
84
+ """An item ("matéria") published in the gazette.
85
+
86
+ Field names follow the source and are in Portuguese: ``codigo`` (identifier),
87
+ ``data`` (edition date), ``diario`` (gazette code), ``categoria`` (category
88
+ path), ``codigo_categoria``, ``codigo_categoria_pai``, ``titulo``,
89
+ ``subtitulo``, ``texto`` (full text), ``resumo`` (beginning of the text) and
90
+ ``extra`` (``True`` if the item came from the extra-edition query).
91
+ """
92
+
93
+ codigo: int
94
+ data: date
95
+ diario: int
96
+ categoria: str
97
+ codigo_categoria: int
98
+ texto: str
99
+ titulo: str | None = None
100
+ subtitulo: str | None = None
101
+ resumo: str | None = None
102
+ codigo_categoria_pai: int | None = None
103
+ extra: bool = False
104
+
105
+ def as_dict(self) -> dict:
106
+ """The item as a dictionary, with the date as ISO text."""
107
+ d = asdict(self)
108
+ d["data"] = self.data.isoformat()
109
+ return d
110
+
111
+ def como_dict(self) -> dict:
112
+ """Portuguese alias of :meth:`as_dict`."""
113
+ return self.as_dict()
114
+
115
+
116
+ def _as_date(value: date | str) -> date:
117
+ if isinstance(value, datetime):
118
+ return value.date()
119
+ if isinstance(value, date):
120
+ return value
121
+ for fmt in ("%Y-%m-%d", "%d/%m/%Y", "%d-%m-%Y"):
122
+ try:
123
+ return datetime.strptime(value, fmt).date()
124
+ except ValueError:
125
+ pass
126
+ raise ValueError(f"unrecognised date: {value!r} (use YYYY-MM-DD or DD/MM/YYYY)")
127
+
128
+
129
+ def _encode(kind: str, day: date | None, gazette: int) -> str:
130
+ if kind == "data_tracos":
131
+ return day.strftime("%d-%m-%Y")
132
+ if kind == "data_barras":
133
+ return day.strftime("%d/%m/%Y")
134
+ if kind == "diario_base64":
135
+ return base64.b64encode(str(gazette).encode()).decode()
136
+ if kind == "diario_numero":
137
+ return str(gazette)
138
+ raise UnexpectedFormat(f"unknown parameter type in api.json: {kind}")
139
+
140
+
141
+ def _normalise(text: str) -> str:
142
+ plain = unicodedata.normalize("NFKD", text)
143
+ return "".join(c for c in plain if not unicodedata.combining(c)).casefold()
144
+
145
+
146
+ def filter_items(
147
+ items: Iterable[Item],
148
+ text: str | Iterable[str] | None = None,
149
+ category: str | None = None,
150
+ ) -> list[Item]:
151
+ """Filter items by term (in the title or in the text) and by category.
152
+
153
+ Matching ignores case and accents. With several terms, one match is enough.
154
+
155
+ Args:
156
+ items: Items returned by :meth:`Client.items`.
157
+ text: One or more terms searched in the title and in the text.
158
+ category: Part of the category name (for example ``"fazenda"``).
159
+ """
160
+ terms = [text] if isinstance(text, str) else list(text or [])
161
+ terms = [_normalise(t) for t in terms]
162
+ cat = _normalise(category) if category else None
163
+ out = []
164
+ for m in items:
165
+ if cat and cat not in _normalise(m.categoria):
166
+ continue
167
+ if terms:
168
+ body = _normalise((m.titulo or "") + "\n" + m.texto)
169
+ if not any(t in body for t in terms):
170
+ continue
171
+ out.append(m)
172
+ return out
173
+
174
+
175
+ def filtrar(
176
+ materias: Iterable[Item],
177
+ texto: str | Iterable[str] | None = None,
178
+ categoria: str | None = None,
179
+ ) -> list[Item]:
180
+ """Portuguese alias of :func:`filter_items`."""
181
+ return filter_items(materias, texto, categoria)
182
+
183
+
184
+ def _fetch_urllib(url: str, user_agent: str, timeout: float) -> tuple[bytes, dict]:
185
+ req = urllib.request.Request(
186
+ url, headers={"User-Agent": user_agent, "Accept": "application/json"}
187
+ )
188
+ try:
189
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
190
+ return resp.read(), {k.lower(): v for k, v in resp.headers.items()}
191
+ except urllib.error.HTTPError as e:
192
+ headers = {k.lower(): v for k, v in e.headers.items()}
193
+ if e.code == 403:
194
+ raise Blocked(e.code, url, headers=headers) from None
195
+ if e.code == 429:
196
+ wait = headers.get("retry-after", "")
197
+ raise RateLimited(
198
+ e.code, url, float(wait) if wait.isdigit() else None, headers
199
+ ) from None
200
+ raise HTTPError(e.code, url, headers=headers) from None
201
+
202
+
203
+ def _default_cache_dir() -> Path:
204
+ base = os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")
205
+ return Path(base) / "doepe"
206
+
207
+
208
+ class Client:
209
+ """Queries the Official Gazette of the State of Pernambuco.
210
+
211
+ Args:
212
+ interval: Minimum seconds between requests (default 2).
213
+ cache: Directory of the disk cache; ``None`` uses ``~/.cache/doepe``;
214
+ ``False`` turns it off. Only editions of days before today are stored.
215
+ user_agent: Identification sent to the site.
216
+ timeout: Seconds to wait for each response.
217
+ retries: Attempts per request.
218
+ retry_wait: Seconds to pause on a 429 without ``Retry-After`` (default 60).
219
+ max_wait: Longest pause accepted on a 429 (default 1800). The site allows
220
+ a balance of 50 to 100 per time window, depending on the address,
221
+ each query spending 2 of it, and asks for a wait when it runs out
222
+ (15 minutes was observed). If the
223
+ wait requested exceeds this, :class:`RateLimited` is raised instead
224
+ of sleeping.
225
+
226
+ Attributes:
227
+ quota: Last request balance reported by the site, per address queried
228
+ (for example ``"buscarDiario"``): ``limit``, ``remaining`` and ``at``.
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ interval: float = 2.0,
234
+ cache: str | Path | bool | None = None,
235
+ user_agent: str = USER_AGENT,
236
+ timeout: float = 60.0,
237
+ retries: int = 3,
238
+ retry_wait: float = 60.0,
239
+ max_wait: float = 1800.0,
240
+ _fetch: Callable[[str, str, float], tuple[bytes, dict]] | None = None,
241
+ ):
242
+ self.interval = interval
243
+ self.user_agent = user_agent
244
+ self.timeout = timeout
245
+ self.retries = max(1, retries)
246
+ self.retry_wait = retry_wait
247
+ self.max_wait = max_wait
248
+ self._fetch = _fetch or _fetch_urllib
249
+ self._last = 0.0
250
+ self.quota: dict[str, dict] = {}
251
+ if cache is False:
252
+ self.cache = None
253
+ else:
254
+ self.cache = _default_cache_dir() if cache in (None, True) else Path(cache)
255
+
256
+ # --- transport ------------------------------------------------------
257
+
258
+ def _pace(self) -> None:
259
+ left = self.interval - (time.monotonic() - self._last)
260
+ if left > 0:
261
+ time.sleep(left)
262
+ self._last = time.monotonic()
263
+
264
+ def _download(self, url: str) -> bytes:
265
+ for attempt in range(1, self.retries + 1):
266
+ self._pace()
267
+ try:
268
+ log.debug("GET %s", url)
269
+ body, headers = self._fetch(url, self.user_agent, self.timeout)
270
+ self._record_quota(headers, url)
271
+ return body
272
+ except Blocked:
273
+ raise
274
+ except RateLimited as e:
275
+ self._record_quota(e.headers, url)
276
+ wait = self.retry_wait if e.retry_after is None else e.retry_after
277
+ if attempt == self.retries or wait > self.max_wait:
278
+ raise
279
+ if wait >= 5:
280
+ log.warning("site request quota exhausted; waiting %.0f s", wait)
281
+ time.sleep(wait)
282
+ continue
283
+ except HTTPError as e:
284
+ if e.status < 500 or attempt == self.retries:
285
+ raise
286
+ except (urllib.error.URLError, TimeoutError) as e:
287
+ if attempt == self.retries:
288
+ raise DoepeError(f"network failure at {url}: {e}") from e
289
+ time.sleep(2**attempt)
290
+ raise AssertionError("unreachable")
291
+
292
+ def _record_quota(self, headers: dict, url: str) -> None:
293
+ """Stores in ``self.quota`` the balance reported by the site (x-ratelimit-*).
294
+
295
+ The site keeps a separate quota per address, with different limits.
296
+ """
297
+
298
+ def num(name):
299
+ v = headers.get(name, "")
300
+ return int(v) if v.isdigit() else None
301
+
302
+ limit, remaining = num("x-ratelimit-limit"), num("x-ratelimit-remaining")
303
+ if limit is None and remaining is None:
304
+ return
305
+ key = urllib.parse.urlsplit(url).path.rsplit("/", 1)[-1]
306
+ previous = self.quota.get(key, {}).get("remaining")
307
+ self.quota[key] = {"limit": limit, "remaining": remaining, "at": datetime.now()}
308
+ if remaining is not None and 0 < remaining <= 10 and (previous is None or previous > 10):
309
+ log.warning("%d requests left in the site quota for %s", remaining, key)
310
+
311
+ def _url(self, name: str, day: date | None, gazette: int) -> str:
312
+ ep = SPEC["endpoints"][name]
313
+ params = {k: _encode(t, day, gazette) for k, t in ep["params"].items()}
314
+ url = SPEC["base_api"] + ep["caminho"]
315
+ return url + ("?" + urllib.parse.urlencode(params) if params else "")
316
+
317
+ def _query(self, name: str, day: date | None = None, gazette: int = 1):
318
+ ep = SPEC["endpoints"][name]
319
+ url = self._url(name, day, gazette)
320
+ try:
321
+ value = json.loads(self._download(url))
322
+ except json.JSONDecodeError as e:
323
+ raise UnexpectedFormat(f"{name}: the response is not JSON ({url})") from e
324
+ expected = ep["resposta"]
325
+ if expected == "lista":
326
+ if not isinstance(value, list):
327
+ raise UnexpectedFormat(f"{name}: expected a list, got {type(value).__name__}")
328
+ for item in value:
329
+ missing = [c for c in ep.get("campos", []) if c not in item]
330
+ if missing:
331
+ raise UnexpectedFormat(f"{name}: item without the fields {missing}")
332
+ elif expected == "logico":
333
+ if not isinstance(value, bool):
334
+ raise UnexpectedFormat(f"{name}: expected true/false, got {value!r}")
335
+ elif expected == "data_barras":
336
+ try:
337
+ value = datetime.strptime(value, "%d/%m/%Y").date()
338
+ except (TypeError, ValueError) as e:
339
+ raise UnexpectedFormat(f"{name}: expected a date, got {value!r}") from e
340
+ return value
341
+
342
+ # --- queries --------------------------------------------------------
343
+
344
+ def items(self, date: date | str, gazette: int = 1, edition: str = "all") -> list[Item]:
345
+ """Items published on a day. A day without an edition returns an empty list.
346
+
347
+ Args:
348
+ date: Date of the edition: a ``date``, or text as ``"YYYY-MM-DD"`` or
349
+ ``"DD/MM/YYYY"``.
350
+ gazette: Code of the gazette (1 = Official Gazette of the State).
351
+ edition: ``"all"`` (default) returns the regular and the extra edition,
352
+ without repeating items; ``"regular"`` or ``"extra"`` return only
353
+ one. ``"all"`` costs two requests per day not yet cached.
354
+ """
355
+ if edition not in _EDITIONS:
356
+ raise ValueError('edition must be "all", "regular" or "extra"')
357
+ day = _as_date(date)
358
+ out = []
359
+ if edition != "extra":
360
+ out += self._edition(day, gazette, extra=False)
361
+ if edition != "regular":
362
+ # The regular query may already bring the items of the extra edition
363
+ # (with text); the extra query repeats them without text. Keep the
364
+ # first of each code.
365
+ seen = {m.codigo for m in out}
366
+ out += [m for m in self._edition(day, gazette, extra=True) if m.codigo not in seen]
367
+ return out
368
+
369
+ def _edition(self, day: date, gazette: int, extra: bool) -> list[Item]:
370
+ name = "materias_extra" if extra else "materias"
371
+ file = None
372
+ if self.cache is not None and day < date.today():
373
+ file = self.cache / str(gazette) / f"{day.isoformat()}{'E' if extra else ''}.json"
374
+ if file.exists():
375
+ return [_item(m, extra) for m in json.loads(file.read_text("utf-8"))]
376
+ # the extra query embeds the PDF in the "file" field; it does not go to the cache
377
+ raw = [{k: v for k, v in m.items() if k != "file"} for m in self._query(name, day, gazette)]
378
+ if file is not None:
379
+ file.parent.mkdir(parents=True, exist_ok=True)
380
+ tmp = file.with_suffix(".tmp")
381
+ tmp.write_text(json.dumps(raw, ensure_ascii=False), "utf-8")
382
+ tmp.replace(file)
383
+ return [_item(m, extra) for m in raw]
384
+
385
+ def items_range(
386
+ self, start: date | str, end: date | str, gazette: int = 1, edition: str = "all"
387
+ ) -> Iterator[Item]:
388
+ """Items of every edition between two dates (inclusive), as a generator."""
389
+ day, last = _as_date(start), _as_date(end)
390
+ while day <= last:
391
+ log.info("edition of %s", day.isoformat())
392
+ yield from self.items(day, gazette, edition)
393
+ day += timedelta(days=1)
394
+
395
+ def categories(self, gazette: int = 1) -> list[dict]:
396
+ """Category tree (government bodies): ``id``, ``nome``, ``idPai``, ``nomePai``, ``ativo``."""
397
+ return self._query("categorias", gazette=gazette)
398
+
399
+ def edition_exists(self, date: date | str, gazette: int = 1, extra: bool = False) -> bool:
400
+ """Whether there is an edition (or an extra edition) on the date."""
401
+ name = "existe_extra" if extra else "existe_edicao"
402
+ return self._query(name, _as_date(date), gazette)
403
+
404
+ def last_edition(self, gazette: int = 1) -> date:
405
+ """Date of the last published edition."""
406
+ return self._query("ultima_edicao", gazette=gazette)
407
+
408
+ def gazettes(self) -> list[dict]:
409
+ """Gazettes hosted by the system (``codigo``, ``nomeFantasia``)."""
410
+ return self._query("diarios")
411
+
412
+ # --- cache ----------------------------------------------------------
413
+
414
+ def clear_cache(self, before: date | str | None = None) -> int:
415
+ """Removes the cached editions; returns how many files were removed.
416
+
417
+ Args:
418
+ before: If given, removes only the editions before this date.
419
+ """
420
+ if self.cache is None or not self.cache.exists():
421
+ return 0
422
+ limit = _as_date(before) if before is not None else None
423
+ removed = 0
424
+ for file in self.cache.glob("*/????-??-??*.json"):
425
+ if limit is None or date.fromisoformat(file.name[:10]) < limit:
426
+ file.unlink()
427
+ removed += 1
428
+ log.info("%d file(s) removed from the cache", removed)
429
+ return removed
430
+
431
+ # --- files ----------------------------------------------------------
432
+
433
+ def pdf_url(self, date: date | str, gazette: int = 1, extra: bool = False) -> str:
434
+ """Address of the PDF of the full edition. Makes no request."""
435
+ return self._file_url("pdf", date, gazette, extra)
436
+
437
+ def cover_url(self, date: date | str, gazette: int = 1, extra: bool = False) -> str:
438
+ """Address of the cover image of the edition. Makes no request."""
439
+ return self._file_url("capa", date, gazette, extra)
440
+
441
+ def _file_url(self, kind: str, day, gazette: int, extra: bool) -> str:
442
+ path = SPEC["arquivos"][kind].format(
443
+ diario=gazette,
444
+ data_iso=_as_date(day).isoformat(),
445
+ sufixo_extra=SPEC["sufixo_extra"] if extra else "",
446
+ )
447
+ return SPEC["base_arquivos"] + "/" + path
448
+
449
+ def download_pdf(
450
+ self, date: date | str, dest: str | Path, gazette: int = 1, extra: bool = False
451
+ ) -> Path:
452
+ """Downloads the PDF of the full edition. ``dest`` is a directory or a file."""
453
+ url = self.pdf_url(date, gazette, extra)
454
+ dest = Path(dest)
455
+ if dest.is_dir():
456
+ dest = dest / url.rsplit("/", 1)[1]
457
+ dest.write_bytes(self._download(url))
458
+ return dest
459
+
460
+ # --- Portuguese aliases ---------------------------------------------
461
+ # Real methods, with Portuguese argument names, so that a script can stay
462
+ # in one language end to end.
463
+
464
+ def materias(self, data: date | str, diario: int = 1, edicao: str = "todas") -> list[Item]:
465
+ """Portuguese alias of :meth:`items` (``edicao``: ``"todas"``, ``"normal"``, ``"extra"``)."""
466
+ return self.items(data, diario, _edition_from_pt(edicao))
467
+
468
+ def materias_periodo(
469
+ self, inicio: date | str, fim: date | str, diario: int = 1, edicao: str = "todas"
470
+ ) -> Iterator[Item]:
471
+ """Portuguese alias of :meth:`items_range`."""
472
+ return self.items_range(inicio, fim, diario, _edition_from_pt(edicao))
473
+
474
+ def categorias(self, diario: int = 1) -> list[dict]:
475
+ """Portuguese alias of :meth:`categories`."""
476
+ return self.categories(diario)
477
+
478
+ def existe_edicao(self, data: date | str, diario: int = 1, extra: bool = False) -> bool:
479
+ """Portuguese alias of :meth:`edition_exists`."""
480
+ return self.edition_exists(data, diario, extra)
481
+
482
+ def ultima_edicao(self, diario: int = 1) -> date:
483
+ """Portuguese alias of :meth:`last_edition`."""
484
+ return self.last_edition(diario)
485
+
486
+ def diarios(self) -> list[dict]:
487
+ """Portuguese alias of :meth:`gazettes`."""
488
+ return self.gazettes()
489
+
490
+ def limpar_cache(self, antes_de: date | str | None = None) -> int:
491
+ """Portuguese alias of :meth:`clear_cache`."""
492
+ return self.clear_cache(antes_de)
493
+
494
+ def url_pdf(self, data: date | str, diario: int = 1, extra: bool = False) -> str:
495
+ """Portuguese alias of :meth:`pdf_url`."""
496
+ return self.pdf_url(data, diario, extra)
497
+
498
+ def url_capa(self, data: date | str, diario: int = 1, extra: bool = False) -> str:
499
+ """Portuguese alias of :meth:`cover_url`."""
500
+ return self.cover_url(data, diario, extra)
501
+
502
+ def baixar_pdf(
503
+ self, data: date | str, destino: str | Path, diario: int = 1, extra: bool = False
504
+ ) -> Path:
505
+ """Portuguese alias of :meth:`download_pdf`."""
506
+ return self.download_pdf(data, destino, diario, extra)
507
+
508
+ @property
509
+ def cota(self) -> dict[str, dict]:
510
+ """Portuguese alias of :attr:`quota`."""
511
+ return self.quota
512
+
513
+
514
+ class Cliente(Client):
515
+ """Portuguese alias of :class:`Client`, with Portuguese constructor arguments.
516
+
517
+ ``intervalo``, ``tentativas``, ``espera_limite`` and ``espera_maxima`` are the
518
+ same as ``interval``, ``retries``, ``retry_wait`` and ``max_wait``.
519
+ """
520
+
521
+ def __init__(
522
+ self,
523
+ intervalo: float = 2.0,
524
+ cache: str | Path | bool | None = None,
525
+ user_agent: str = USER_AGENT,
526
+ timeout: float = 60.0,
527
+ tentativas: int = 3,
528
+ espera_limite: float = 60.0,
529
+ espera_maxima: float = 1800.0,
530
+ _fetch: Callable[[str, str, float], tuple[bytes, dict]] | None = None,
531
+ ):
532
+ super().__init__(
533
+ interval=intervalo,
534
+ cache=cache,
535
+ user_agent=user_agent,
536
+ timeout=timeout,
537
+ retries=tentativas,
538
+ retry_wait=espera_limite,
539
+ max_wait=espera_maxima,
540
+ _fetch=_fetch,
541
+ )
542
+
543
+
544
+ def _edition_from_pt(edicao: str) -> str:
545
+ try:
546
+ return _EDITIONS_PT[edicao]
547
+ except KeyError:
548
+ raise ValueError('edicao deve ser "todas", "normal" ou "extra"') from None
549
+
550
+
551
+ def _item(m: dict, extra: bool = False) -> Item:
552
+ try:
553
+ return Item(
554
+ codigo=int(m["codigo"]),
555
+ data=date.fromisoformat(m["dataPublicacao"]),
556
+ diario=int(m["codigoDiario"]),
557
+ categoria=m["nomeCategoria"],
558
+ codigo_categoria=int(m["codigoCategoria"]),
559
+ texto=m["texto"] or "",
560
+ titulo=m.get("titulo") or None,
561
+ subtitulo=m.get("subtitulo") or None,
562
+ resumo=m.get("resumo") or None,
563
+ codigo_categoria_pai=m.get("codigoCategoriaPai"),
564
+ extra=extra,
565
+ )
566
+ except (KeyError, TypeError, ValueError) as e:
567
+ raise UnexpectedFormat(f"item in an unexpected format: {e!r}") from e
568
+
569
+
570
+ # Portuguese aliases of the classes: the same objects under another name.
571
+ Materia = Item
572
+ ErroDoepe = DoepeError
573
+ ErroHTTP = HTTPError
574
+ Bloqueado = Blocked
575
+ LimiteExcedido = RateLimited
576
+ FormatoInesperado = UnexpectedFormat
File without changes
@@ -0,0 +1,29 @@
1
+ [
2
+ {
3
+ "id": 1877,
4
+ "nome": "Esportes",
5
+ "idPai": 65,
6
+ "nomePai": "Licitações e Contratos",
7
+ "ativo": false,
8
+ "indentacaoOriginal": false,
9
+ "enviarAoOrgaoRegulador": false
10
+ },
11
+ {
12
+ "id": 1876,
13
+ "nome": "Esportes",
14
+ "idPai": 35,
15
+ "nomePai": "Secretarias de Estado",
16
+ "ativo": false,
17
+ "indentacaoOriginal": false,
18
+ "enviarAoOrgaoRegulador": false
19
+ },
20
+ {
21
+ "id": 1785,
22
+ "nome": "Instituto de Ciências Biológicas",
23
+ "idPai": 64,
24
+ "nomePai": "Repartições Estaduais",
25
+ "ativo": false,
26
+ "indentacaoOriginal": false,
27
+ "enviarAoOrgaoRegulador": false
28
+ }
29
+ ]
@@ -0,0 +1,22 @@
1
+ [
2
+ {
3
+ "codigo": 0,
4
+ "nomeFantasia": "Diário (ÁREA RESTRITA)"
5
+ },
6
+ {
7
+ "codigo": 1,
8
+ "nomeFantasia": "Diário Oficial do Estado de Pernambuco"
9
+ },
10
+ {
11
+ "codigo": 81,
12
+ "nomeFantasia": "Tribunal de Contas do Estado de Pernambuco"
13
+ },
14
+ {
15
+ "codigo": 102,
16
+ "nomeFantasia": "Defensoria Pública do Estado de Pernambuco"
17
+ },
18
+ {
19
+ "codigo": 121,
20
+ "nomeFantasia": "Departamento Estadual de Imprensa do Estado do Rio Grande do Norte - DEI/RN"
21
+ }
22
+ ]
@@ -0,0 +1,37 @@
1
+ [
2
+ {
3
+ "codigo": 392119,
4
+ "titulo": "CAMARA MUNICIPAL DE CORRENTES",
5
+ "subtitulo": "AVISO DE LICITAÇÃO",
6
+ "texto": "CAMARA MUNICIPAL DE CORRENTES\n\nAVISO DE LICITAÇÃO\n\nPROCESSO LICITATÓRIO Nº 008/2026. PREGÃO ELETRÔNICO N. 001/2026. Objeto: CONTRATAÇÃO DE EMPRESA PARA LOCAÇÃO DE 02 (DOIS) VEÍCULOS PARA SUPRIR ÀS NECESSIDADES DA CÂMARA MUNICIPAL DE CORRENTES/PE. Valor máximo: R$ 265.048,20. Início do acolhimento das propostas: dia 04/12/2026. Encerramento das propostas: 16/12/2026 às 08:00h. Início da sessão de d",
7
+ "textoHtml": "",
8
+ "resumo": "CAMARA MUNICIPAL DE CORRENTES AVISO DE LICITAÇÃO PROCESSO LICITATÓRIO Nº 008/2026. PREGÃO ELETRÔNICO N. 001/2026. Objeto: CONTRATAÇÃO DE EMPRESA PARA LOCAÇÃO DE 02 (DOIS) VEÍCULOS PARA SUPRIR ÀS NECES",
9
+ "nomeCategoria": "Publicações Particulares > 1 coluna (6,2cm)",
10
+ "codigoCategoria": 815,
11
+ "codigoCategoriaPai": 67,
12
+ "dataPublicacao": "2026-12-04",
13
+ "codigoDiario": 1
14
+ },
15
+ {
16
+ "codigo": 392139,
17
+ "texto": "TRIBUNAL ADMINISTRATIVO TRIBUTÁRIO DO ESTADO - 1ª Turma Julgadora\n\nRecurso Ordinário do Contribuinte no processo SF nº 2020.000006433108-45. Recorrente: SGH BRASIL COMERCIO DE OCULOS LTDA. CNPJ: 13.257.648/0021-33. Adv(s): Dr. Gilberto Ayres Moreira, OAB/SP 289.437; Dr. Fernando Westin Marcondes Pereira, OAB/SP 212.546. ACÓRDÃO 1ª TJ Nº 0255/2026(02). (Relator: Julgador Marconi de Queiroz Campos).",
18
+ "textoHtml": "",
19
+ "resumo": "TRIBUNAL ADMINISTRATIVO TRIBUTÁRIO DO ESTADO - 1ª Turma Julgadora Recurso Ordinário do Contribuinte no processo SF nº 2020.000006433108-45. Recorrente: SGH BRASIL COMERCIO DE OCULOS LTDA. CNPJ: 13.257",
20
+ "nomeCategoria": "Secretarias de Estado > Fazenda",
21
+ "codigoCategoria": 50,
22
+ "codigoCategoriaPai": 35,
23
+ "dataPublicacao": "2026-12-04",
24
+ "codigoDiario": 1
25
+ },
26
+ {
27
+ "codigo": 392181,
28
+ "titulo": "PREFEITURA MUNICIPAL DE IPOJUCA",
29
+ "texto": "PREFEITURA MUNICIPAL DE IPOJUCA\n\nComissão: Diretoria de Licitação (DL)/Prefeitura Municipal de Ipojuca/PE (PMI). Objeto Nat. Serviço. Tipo: Menor Preço Global. O Agente de Contratação, instituída pela Portaria nº 003/2026, torna público para conhecimento dos interessados que, de acordo com a Lei Federal nº 14.133/21, o Decreto Municipal nº 1051/2025, demais legislações pertinentes, e com as condiç",
30
+ "textoHtml": "",
31
+ "resumo": "PREFEITURA MUNICIPAL DE IPOJUCA Comissão: Diretoria de Licitação (DL)/Prefeitura Municipal de Ipojuca/PE (PMI). Objeto Nat. Serviço. Tipo: Menor Preço Global. O Agente de Contratação, instituída pela ",
32
+ "nomeCategoria": "Publicações Municipais",
33
+ "codigoCategoria": 66,
34
+ "dataPublicacao": "2026-12-04",
35
+ "codigoDiario": 1
36
+ }
37
+ ]
@@ -0,0 +1,242 @@
1
+ """Testes sem rede: o transporte é trocado por um que devolve as amostras de spec/fixtures."""
2
+
3
+ import json
4
+ from datetime import date
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ import doepe
10
+ from doepe.client import SPEC
11
+
12
+ RAIZ = Path(__file__).resolve().parents[2]
13
+ AMOSTRAS = Path(__file__).resolve().parent / "fixtures"
14
+
15
+
16
+ class Falso:
17
+ def __init__(self, respostas):
18
+ self.respostas = respostas
19
+ self.urls = []
20
+
21
+ def __call__(self, url, user_agent, timeout):
22
+ self.urls.append(url)
23
+ for trecho, corpo in self.respostas.items():
24
+ if trecho in url:
25
+ if isinstance(corpo, Exception):
26
+ raise corpo
27
+ return corpo if isinstance(corpo, tuple) else (corpo, {})
28
+ raise AssertionError(f"url inesperada: {url}")
29
+
30
+
31
+ def cliente(respostas, **kw):
32
+ falso = Falso(respostas)
33
+ return doepe.Client(interval=0, cache=False, _fetch=falso, **kw), falso
34
+
35
+
36
+ def amostra(nome):
37
+ return (AMOSTRAS / nome).read_bytes()
38
+
39
+
40
+ @pytest.mark.skipif(
41
+ not (RAIZ / "spec" / "api.json").exists(), reason="fora do repositório completo"
42
+ )
43
+ def test_spec_do_pacote_igual_a_fonte():
44
+ assert SPEC == json.loads((RAIZ / "spec" / "api.json").read_text("utf-8"))
45
+
46
+
47
+ def test_materias_monta_url_e_converte():
48
+ c, falso = cliente({"buscarDiario?": amostra("materias.json")})
49
+ ms = c.items("2026-12-04", edition="regular")
50
+ assert falso.urls == [
51
+ "https://diariooficial.cepe.com.br/diariooficial/public/visualizar-diario/"
52
+ "buscarDiario?dataPublicacao=04-12-2026&codigoDiarioOficial=MQ%3D%3D"
53
+ ]
54
+ assert len(ms) == 3
55
+ assert ms[0].data == date(2026, 12, 4) and ms[0].diario == 1
56
+ assert ms[0].titulo and ms[0].subtitulo
57
+ assert ms[1].titulo is None
58
+ assert ms[2].codigo_categoria_pai is None
59
+ assert ms[0].as_dict()["data"] == "2026-12-04"
60
+
61
+
62
+ def test_datas_aceitas():
63
+ c, falso = cliente({"buscarDiario?": b"[]"})
64
+ for d in ("04/12/2026", "04-12-2026", date(2026, 12, 4)):
65
+ assert c.items(d, edition="regular") == []
66
+ assert len(set(falso.urls)) == 1
67
+ with pytest.raises(ValueError):
68
+ c.items("ontem")
69
+
70
+
71
+ def test_extra_usa_endpoint_e_formatos_proprios():
72
+ c, falso = cliente({"buscarDiarioExtra?": b"[]"})
73
+ c.items("2026-12-04", edition="extra")
74
+ assert len(falso.urls) == 1
75
+ assert "dataPublicacao=04%2F12%2F2026&codigoDiarioOficial=1" in falso.urls[0]
76
+ with pytest.raises(ValueError):
77
+ c.items("2026-12-04", edition="other")
78
+
79
+
80
+ def test_todas_junta_as_duas_sem_repetir():
81
+ normal = json.loads(amostra("materias.json"))
82
+ repetida = dict(normal[0], texto="", file="JVBERi0=")
83
+ so_extra = dict(normal[1], codigo=999001, texto="DECRETO da extra")
84
+ c, falso = cliente(
85
+ {
86
+ "buscarDiario?": amostra("materias.json"),
87
+ "buscarDiarioExtra?": json.dumps([repetida, so_extra]).encode(),
88
+ }
89
+ )
90
+ ms = c.items("2026-12-04")
91
+ assert len(falso.urls) == 2
92
+ assert [m.codigo for m in ms] == [m["codigo"] for m in normal] + [999001]
93
+ assert ms[0].texto and ms[0].extra is False
94
+ assert ms[-1].extra is True
95
+ assert len(c.items("2026-12-04", edition="regular")) == 3
96
+
97
+
98
+ def test_limite_429_espera_e_desiste():
99
+ c, falso = cliente({"buscarDiario?": doepe.RateLimited(429, "x")}, retry_wait=0)
100
+ with pytest.raises(doepe.RateLimited):
101
+ c.items("2026-12-04", edition="regular")
102
+ assert len(falso.urls) == 3
103
+
104
+
105
+ def test_consultas_simples():
106
+ c, falso = cliente(
107
+ {
108
+ "existeDiarioHome": b"true",
109
+ "existeDiarioExtraHome": b"false",
110
+ "dataUltimoJornalPublicado": b'"04/12/2026"',
111
+ "/diarios": amostra("diarios.json"),
112
+ "consultarTodasCategoriasDiario": amostra("categorias.json"),
113
+ }
114
+ )
115
+ assert c.edition_exists("2026-12-04") is True
116
+ assert c.edition_exists("2026-12-04", extra=True) is False
117
+ assert c.last_edition() == date(2026, 12, 4)
118
+ assert {d["codigo"] for d in c.gazettes()} >= {1, 81}
119
+ assert "nome" in c.categories()[0]
120
+ assert "codigoDiario=1&dataPublicacao=04%2F12%2F2026" in falso.urls[0]
121
+
122
+
123
+ def test_formato_inesperado():
124
+ c, _ = cliente({"buscarDiario?": b'{"erro": 1}'})
125
+ with pytest.raises(doepe.UnexpectedFormat):
126
+ c.items("2026-12-04", edition="regular")
127
+ c, _ = cliente({"buscarDiario?": b'[{"codigo": 1}]'})
128
+ with pytest.raises(doepe.UnexpectedFormat):
129
+ c.items("2026-12-04", edition="regular")
130
+ c, _ = cliente({"buscarDiario?": b"<html>"})
131
+ with pytest.raises(doepe.UnexpectedFormat):
132
+ c.items("2026-12-04", edition="regular")
133
+
134
+
135
+ def test_bloqueio_nao_repete():
136
+ c, falso = cliente({"buscarDiario?": doepe.Blocked(403, "x")})
137
+ with pytest.raises(doepe.Blocked):
138
+ c.items("2026-12-04", edition="regular")
139
+ assert len(falso.urls) == 1
140
+
141
+
142
+ def test_cache_so_para_dias_passados(tmp_path):
143
+ falso = Falso({"buscarDiario?": amostra("materias.json")})
144
+ c = doepe.Client(interval=0, cache=tmp_path, _fetch=falso)
145
+ assert len(c.items("2023-03-15", edition="regular")) == 3
146
+ assert len(c.items("2023-03-15", edition="regular")) == 3
147
+ assert len(falso.urls) == 1
148
+ assert (tmp_path / "1" / "2023-03-15.json").exists()
149
+ c.items(date.today(), edition="regular")
150
+ c.items(date.today(), edition="regular")
151
+ assert len(falso.urls) == 3
152
+
153
+
154
+ def test_urls_de_arquivo():
155
+ c, _ = cliente({})
156
+ base = "https://cepebr-prod.s3.sa-east-1.amazonaws.com/1/"
157
+ assert c.pdf_url("2026-12-04") == base + "arquivos/resumoDiario/2026-12-04/2026-12-04.pdf"
158
+ assert c.pdf_url("2026-12-04", extra=True).endswith("/2026-12-04/2026-12-04E.pdf")
159
+ assert c.cover_url("2026-12-04") == base + "capas/2026-12-04.png"
160
+
161
+
162
+ def test_baixar_pdf(tmp_path):
163
+ c, _ = cliente({"resumoDiario": b"%PDF-1.4"})
164
+ arq = c.download_pdf("2026-12-04", tmp_path)
165
+ assert arq.name == "2026-12-04.pdf" and arq.read_bytes() == b"%PDF-1.4"
166
+
167
+
168
+ def test_filtrar_ignora_acento_e_caixa():
169
+ c, _ = cliente({"buscarDiario?": amostra("materias.json")})
170
+ ms = c.items("2026-12-04", edition="regular")
171
+ assert len(doepe.filter_items(ms, category="publicacoes municipais")) == 1
172
+ assert len(doepe.filter_items(ms, category="FAZENDA")) == 1
173
+ assert doepe.filter_items(ms, text="termo que nao existe xyz") == []
174
+ palavra = ms[1].texto.split()[0]
175
+ assert ms[1] in doepe.filter_items(ms, text=["xyz-nada", palavra.upper()])
176
+
177
+
178
+ def test_cota_registrada_e_aviso_no_fim(caplog):
179
+ cab = {"x-ratelimit-limit": "100", "x-ratelimit-remaining": "7"}
180
+ c, _ = cliente({"existeDiarioHome": (b"true", cab)})
181
+ with caplog.at_level("WARNING", logger="doepe"):
182
+ assert c.quota == {}
183
+ c.edition_exists("2026-12-04")
184
+ c.edition_exists("2026-12-04")
185
+ assert c.quota["existeDiarioHome"]["limit"] == 100
186
+ assert c.quota["existeDiarioHome"]["remaining"] == 7
187
+ assert [r.message for r in caplog.records] == [
188
+ "7 requests left in the site quota for existeDiarioHome"
189
+ ]
190
+
191
+
192
+ def test_espera_longa_demais_desiste_sem_dormir():
193
+ erro = doepe.RateLimited(429, "x", retry_after=5000, headers={"x-ratelimit-remaining": "0"})
194
+ c, falso = cliente({"buscarDiario?": erro})
195
+ with pytest.raises(doepe.RateLimited) as e:
196
+ c.items("2026-12-04", edition="regular")
197
+ assert len(falso.urls) == 1 and e.value.retry_after == 5000
198
+ assert c.quota["buscarDiario"]["remaining"] == 0
199
+
200
+
201
+ def test_limpar_cache(tmp_path):
202
+ falso = Falso({"buscarDiario?": amostra("materias.json")})
203
+ c = doepe.Client(interval=0, cache=tmp_path, _fetch=falso)
204
+ c.items("2023-03-15", edition="regular")
205
+ c.items("2024-03-15", edition="regular")
206
+ assert c.clear_cache(before="2024-01-01") == 1
207
+ assert (tmp_path / "1" / "2024-03-15.json").exists()
208
+ assert c.clear_cache() == 1
209
+ assert doepe.Client(cache=False).clear_cache() == 0
210
+
211
+
212
+ def test_apelidos_em_portugues():
213
+ falso = Falso(
214
+ {
215
+ "buscarDiario?": amostra("materias.json"),
216
+ "buscarDiarioExtra?": b"[]",
217
+ "existeDiarioHome": b"true",
218
+ "dataUltimoJornalPublicado": b'"04/12/2026"',
219
+ "/diarios": amostra("diarios.json"),
220
+ "consultarTodasCategoriasDiario": amostra("categorias.json"),
221
+ }
222
+ )
223
+ c = doepe.Cliente(intervalo=0, cache=False, tentativas=2, espera_maxima=10, _fetch=falso)
224
+ assert isinstance(c, doepe.Client) and c.interval == 0 and c.retries == 2 and c.max_wait == 10
225
+ assert c.materias("2026-12-04") == c.items("2026-12-04")
226
+ assert c.materias("2026-12-04", edicao="normal") == c.items("2026-12-04", edition="regular")
227
+ with pytest.raises(ValueError):
228
+ c.materias("2026-12-04", edicao="regular")
229
+ assert len(list(c.materias_periodo("2026-12-03", "2026-12-04", edicao="normal"))) == 6
230
+ ms = c.materias("2026-12-04", edicao="normal")
231
+ assert doepe.filtrar(ms, categoria="fazenda") == doepe.filter_items(ms, category="fazenda")
232
+ assert c.existe_edicao("2026-12-04") is True
233
+ assert c.ultima_edicao() == date(2026, 12, 4)
234
+ assert c.categorias() == c.categories() and c.diarios() == c.gazettes()
235
+ assert c.url_pdf("2026-12-04", extra=True) == c.pdf_url("2026-12-04", extra=True)
236
+ assert c.url_capa("2026-12-04") == c.cover_url("2026-12-04")
237
+ assert c.cota is c.quota
238
+ assert c.limpar_cache() == 0
239
+ assert ms[0].como_dict() == ms[0].as_dict()
240
+ assert doepe.Materia is doepe.Item and doepe.LimiteExcedido is doepe.RateLimited
241
+ assert doepe.Bloqueado is doepe.Blocked and doepe.FormatoInesperado is doepe.UnexpectedFormat
242
+ assert doepe.ErroDoepe is doepe.DoepeError and doepe.ErroHTTP is doepe.HTTPError