doepe 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.
doepe/__init__.py ADDED
@@ -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
+ ]
doepe/api.json ADDED
@@ -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
+ }
doepe/client.py ADDED
@@ -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
doepe/py.typed ADDED
File without changes
@@ -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.
@@ -0,0 +1,8 @@
1
+ doepe/__init__.py,sha256=Ey1t8p6xjzh-sGgIMhZLbdhxSskGBMf926fTSVvDSFA,774
2
+ doepe/api.json,sha256=ud75NK2uWggC1h1VCMD-WCAJ1imAPZo3uA25FJi8a_8,2260
3
+ doepe/client.py,sha256=Xs9T45WQXMHqBalNoYLfMEQRu3bRQ0IolqNBsttWjNg,22536
4
+ doepe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ doepe-0.1.0.dist-info/METADATA,sha256=bo2QWgidWeKZKbP4zGbgEVXSqeAG_2Qou5UHXrzv8mQ,4949
6
+ doepe-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ doepe-0.1.0.dist-info/licenses/LICENSE,sha256=PMwyQZQrSXJHiu81DaYsLtydpMVHnjQe_pId2Zf66sU,1070
8
+ doepe-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) 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.