seao-api 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.
- seao_api/__init__.py +88 -0
- seao_api/__main__.py +5 -0
- seao_api/_http.py +171 -0
- seao_api/_utils.py +191 -0
- seao_api/_version.py +1 -0
- seao_api/cli.py +383 -0
- seao_api/clients/__init__.py +16 -0
- seao_api/clients/avis.py +225 -0
- seao_api/clients/fields.py +227 -0
- seao_api/clients/search.py +276 -0
- seao_api/config.py +334 -0
- seao_api/detailed.py +280 -0
- seao_api/exceptions.py +37 -0
- seao_api/filtering.py +279 -0
- seao_api/live.py +320 -0
- seao_api/opendata/__init__.py +15 -0
- seao_api/opendata/build.py +303 -0
- seao_api/opendata/feed.py +93 -0
- seao_api/py.typed +0 -0
- seao_api-0.1.0.dist-info/METADATA +174 -0
- seao_api-0.1.0.dist-info/RECORD +24 -0
- seao_api-0.1.0.dist-info/WHEEL +4 -0
- seao_api-0.1.0.dist-info/entry_points.txt +2 -0
- seao_api-0.1.0.dist-info/licenses/LICENSE +26 -0
seao_api/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""seao_api: Python access to SEAO, Québec's public procurement system.
|
|
2
|
+
|
|
3
|
+
Unofficial: not affiliated with or endorsed by the Gouvernement du Québec.
|
|
4
|
+
Read the legal notice (docs/legal.md) before heavy use.
|
|
5
|
+
|
|
6
|
+
Quick tour::
|
|
7
|
+
|
|
8
|
+
import seao_api as seao
|
|
9
|
+
|
|
10
|
+
seao.log_to_console() # show progress messages
|
|
11
|
+
|
|
12
|
+
# Live data, in memory (nothing written)
|
|
13
|
+
df = seao.fetch_open_tenders(regions=[6], details=False)
|
|
14
|
+
one = seao.fetch_avis("ef852c0d-e273-4d40-9119-68e1847e020a")
|
|
15
|
+
|
|
16
|
+
# Same, saved as Parquet in ./seao_data (see seao.configure)
|
|
17
|
+
seao.save_open_tenders(regions=[6, 13], categories=[43], suffix="mtl")
|
|
18
|
+
|
|
19
|
+
# Open-data history (OCDS): build once, update weekly, then filter
|
|
20
|
+
seao.build_or_update()
|
|
21
|
+
rows = seao.read_opendata(["ocid", "date", "tender", "buyer"])
|
|
22
|
+
hits = seao.filter_tenders(rows, title_contains="pompe", buyer_contains="laval")
|
|
23
|
+
|
|
24
|
+
# Full SEAO detail of every notice matching a filter
|
|
25
|
+
seao.save_filtered_avis(title_contains="véhicule", buyer_contains="montreal", suffix="mtl")
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from . import config, live
|
|
29
|
+
from ._http import RateLimiter
|
|
30
|
+
from ._utils import decode_json, log_to_console
|
|
31
|
+
from ._version import __version__
|
|
32
|
+
from .clients import SEAOAvisClient, SEAOFieldsClient, SEAOSearchClient, extract_uuid
|
|
33
|
+
from .config import configure, opendata_dir, opendata_path, output_dir, reset_configuration
|
|
34
|
+
from .detailed import avis_uuids, fetch_filtered_avis, save_filtered_avis
|
|
35
|
+
from .exceptions import (
|
|
36
|
+
AvisNotFoundError,
|
|
37
|
+
DatabaseNotFoundError,
|
|
38
|
+
DataLocationWarning,
|
|
39
|
+
NotFoundError,
|
|
40
|
+
ResultLimitWarning,
|
|
41
|
+
SEAOError,
|
|
42
|
+
SEAOWarning,
|
|
43
|
+
)
|
|
44
|
+
from .filtering import SHORTCUTS, columns_needed, filter_tenders, get_path
|
|
45
|
+
from .live import fetch_avis, fetch_open_tenders, save_avis, save_open_tenders
|
|
46
|
+
from .opendata import build_or_update, read_opendata
|
|
47
|
+
|
|
48
|
+
__all__ = [
|
|
49
|
+
"SHORTCUTS",
|
|
50
|
+
"AvisNotFoundError",
|
|
51
|
+
"DataLocationWarning",
|
|
52
|
+
"DatabaseNotFoundError",
|
|
53
|
+
"NotFoundError",
|
|
54
|
+
"RateLimiter",
|
|
55
|
+
"ResultLimitWarning",
|
|
56
|
+
"SEAOAvisClient",
|
|
57
|
+
"SEAOError",
|
|
58
|
+
"SEAOFieldsClient",
|
|
59
|
+
"SEAOSearchClient",
|
|
60
|
+
"SEAOWarning",
|
|
61
|
+
"__version__",
|
|
62
|
+
"avis_uuids",
|
|
63
|
+
"build_or_update",
|
|
64
|
+
"columns_needed",
|
|
65
|
+
"config",
|
|
66
|
+
"configure",
|
|
67
|
+
"decode_json",
|
|
68
|
+
"extract_uuid",
|
|
69
|
+
"fetch_avis",
|
|
70
|
+
"fetch_filtered_avis",
|
|
71
|
+
"fetch_open_tenders",
|
|
72
|
+
"filter_tenders",
|
|
73
|
+
"get_path",
|
|
74
|
+
"live",
|
|
75
|
+
"log_to_console",
|
|
76
|
+
"opendata_dir",
|
|
77
|
+
"opendata_path",
|
|
78
|
+
"output_dir",
|
|
79
|
+
"read_opendata",
|
|
80
|
+
"reset_configuration",
|
|
81
|
+
"save_avis",
|
|
82
|
+
"save_filtered_avis",
|
|
83
|
+
"save_open_tenders",
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
import logging as _logging
|
|
87
|
+
|
|
88
|
+
_logging.getLogger(__name__).addHandler(_logging.NullHandler())
|
seao_api/__main__.py
ADDED
seao_api/_http.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""HTTP plumbing shared by every client: session, rate limit, retries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
|
|
12
|
+
from . import config
|
|
13
|
+
from .exceptions import NotFoundError
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
API_BASE = "https://api.seao.gouv.qc.ca/prod/api"
|
|
18
|
+
|
|
19
|
+
#: Statuses retried with backoff. 500 is not in the list: SEAO answers 500 for
|
|
20
|
+
#: requests it cannot handle (e.g. too many keywords), and retrying won't help.
|
|
21
|
+
RETRY_STATUSES = frozenset({429, 502, 503, 504})
|
|
22
|
+
MAX_BACKOFF_SECONDS = 300.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RateLimiter:
|
|
26
|
+
"""Spaces out requests: at most ``requests_per_second`` calls to
|
|
27
|
+
:meth:`wait` return per second. Thread-safe, so one instance can be
|
|
28
|
+
shared by several clients running in parallel threads.
|
|
29
|
+
|
|
30
|
+
The SEAO API answers HTTP 429 (Too Many Requests) when called too fast.
|
|
31
|
+
It sends no rate-limit headers, so the exact limit is unknown.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, requests_per_second: float):
|
|
35
|
+
if not requests_per_second > 0:
|
|
36
|
+
raise ValueError("requests_per_second must be > 0")
|
|
37
|
+
self.requests_per_second = float(requests_per_second)
|
|
38
|
+
self.interval = 1.0 / self.requests_per_second
|
|
39
|
+
self._lock = threading.Lock()
|
|
40
|
+
self._next = time.monotonic()
|
|
41
|
+
|
|
42
|
+
def wait(self) -> None:
|
|
43
|
+
with self._lock:
|
|
44
|
+
now = time.monotonic()
|
|
45
|
+
slot = max(now, self._next)
|
|
46
|
+
self._next = slot + self.interval
|
|
47
|
+
if slot > now:
|
|
48
|
+
time.sleep(slot - now)
|
|
49
|
+
|
|
50
|
+
def __repr__(self) -> str:
|
|
51
|
+
return f"RateLimiter(requests_per_second={self.requests_per_second:g})"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
_shared_lock = threading.Lock()
|
|
55
|
+
_shared_limiter: RateLimiter | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def shared_rate_limiter() -> RateLimiter:
|
|
59
|
+
"""The process-wide limiter used by clients that get no limiter of their
|
|
60
|
+
own. It follows ``seao_api.configure(requests_per_second=...)``."""
|
|
61
|
+
global _shared_limiter
|
|
62
|
+
rate = config.requests_per_second()
|
|
63
|
+
with _shared_lock:
|
|
64
|
+
if _shared_limiter is None or _shared_limiter.requests_per_second != rate:
|
|
65
|
+
_shared_limiter = RateLimiter(rate)
|
|
66
|
+
return _shared_limiter
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def new_session(user_agent: str | None = None) -> requests.Session:
|
|
70
|
+
"""A ``requests.Session`` that identifies this library honestly."""
|
|
71
|
+
session = requests.Session()
|
|
72
|
+
session.headers.update({
|
|
73
|
+
"Accept": "application/json",
|
|
74
|
+
"User-Agent": user_agent or config.user_agent(),
|
|
75
|
+
})
|
|
76
|
+
return session
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class BaseClient:
|
|
80
|
+
"""Common base of the SEAO API clients.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
timeout: Seconds before one HTTP request times out (default:
|
|
84
|
+
``seao_api.configure(timeout=...)``, else 30).
|
|
85
|
+
rate_limiter: Limiter applied before every request. Defaults to the
|
|
86
|
+
process-wide limiter (2 requests/s unless configured), shared by
|
|
87
|
+
every client, so several clients together stay polite.
|
|
88
|
+
max_retries: Retries on HTTP 429/502/503/504, a dropped connection or
|
|
89
|
+
a timeout.
|
|
90
|
+
backoff: First wait before a retry, in seconds, doubled at each
|
|
91
|
+
attempt (capped at 5 minutes). A ``Retry-After`` header wins.
|
|
92
|
+
user_agent: ``User-Agent`` header (default: ``seao-api/<version>``).
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
def __init__(
|
|
96
|
+
self,
|
|
97
|
+
timeout: float | None = None,
|
|
98
|
+
rate_limiter: RateLimiter | None = None,
|
|
99
|
+
max_retries: int = 5,
|
|
100
|
+
backoff: float = 30.0,
|
|
101
|
+
user_agent: str | None = None,
|
|
102
|
+
):
|
|
103
|
+
self.timeout = timeout if timeout is not None else config.timeout()
|
|
104
|
+
self.rate_limiter = rate_limiter if rate_limiter is not None else shared_rate_limiter()
|
|
105
|
+
self.max_retries = max_retries
|
|
106
|
+
self.backoff = backoff
|
|
107
|
+
self._session = new_session(user_agent)
|
|
108
|
+
|
|
109
|
+
# --------------------------------------------------------------- requests
|
|
110
|
+
|
|
111
|
+
def _request(self, url: str, params: dict[str, Any] | None = None) -> requests.Response:
|
|
112
|
+
"""GET with rate limit and retries. Returns the last response."""
|
|
113
|
+
resp: requests.Response | None = None
|
|
114
|
+
for attempt in range(self.max_retries + 1):
|
|
115
|
+
self.rate_limiter.wait()
|
|
116
|
+
try:
|
|
117
|
+
resp = self._session.get(url, params=params, timeout=self.timeout)
|
|
118
|
+
except (requests.ConnectionError, requests.Timeout) as exc:
|
|
119
|
+
if attempt == self.max_retries:
|
|
120
|
+
raise
|
|
121
|
+
delay = self._backoff(attempt)
|
|
122
|
+
logger.warning("%s on %s; retrying in %.0f s", type(exc).__name__, url, delay)
|
|
123
|
+
time.sleep(delay)
|
|
124
|
+
continue
|
|
125
|
+
if resp.status_code not in RETRY_STATUSES or attempt == self.max_retries:
|
|
126
|
+
break
|
|
127
|
+
delay = self._retry_after(resp) or self._backoff(attempt)
|
|
128
|
+
logger.warning("HTTP %s on %s; retrying in %.0f s", resp.status_code, url, delay)
|
|
129
|
+
time.sleep(delay)
|
|
130
|
+
assert resp is not None
|
|
131
|
+
return resp
|
|
132
|
+
|
|
133
|
+
def _get_json(
|
|
134
|
+
self,
|
|
135
|
+
url: str,
|
|
136
|
+
params: dict[str, Any] | None = None,
|
|
137
|
+
*,
|
|
138
|
+
not_found: type[NotFoundError] = NotFoundError,
|
|
139
|
+
what: str = "",
|
|
140
|
+
) -> Any:
|
|
141
|
+
"""GET ``url`` and return the unwrapped ``apiData`` of the response.
|
|
142
|
+
|
|
143
|
+
Every SEAO response is wrapped as ``{"apiData": ..., "messages": ...,
|
|
144
|
+
"redirectTo": ...}``. HTTP 404 raises ``not_found``; other errors raise
|
|
145
|
+
``requests.HTTPError``.
|
|
146
|
+
"""
|
|
147
|
+
resp = self._request(url, params)
|
|
148
|
+
if resp.status_code == 404:
|
|
149
|
+
raise not_found(f"{what or url} not found (HTTP 404)")
|
|
150
|
+
resp.raise_for_status()
|
|
151
|
+
body = resp.json()
|
|
152
|
+
return body.get("apiData", body) if isinstance(body, dict) else body
|
|
153
|
+
|
|
154
|
+
def _backoff(self, attempt: int) -> float:
|
|
155
|
+
return min(self.backoff * 2**attempt, MAX_BACKOFF_SECONDS)
|
|
156
|
+
|
|
157
|
+
@staticmethod
|
|
158
|
+
def _retry_after(resp: requests.Response) -> float | None:
|
|
159
|
+
value = resp.headers.get("Retry-After", "").strip()
|
|
160
|
+
return min(float(value), MAX_BACKOFF_SECONDS) if value.isdigit() else None
|
|
161
|
+
|
|
162
|
+
# -------------------------------------------------------------- lifecycle
|
|
163
|
+
|
|
164
|
+
def close(self) -> None:
|
|
165
|
+
self._session.close()
|
|
166
|
+
|
|
167
|
+
def __enter__(self):
|
|
168
|
+
return self
|
|
169
|
+
|
|
170
|
+
def __exit__(self, *_exc: object) -> None:
|
|
171
|
+
self.close()
|
seao_api/_utils.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Small helpers: run logs, file names, atomic Parquet writes, durations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ------------------------------------------------------------------ run logs
|
|
18
|
+
#
|
|
19
|
+
# Each data folder has a ``log.txt``: a ``Created: <timestamp>`` header, then
|
|
20
|
+
# one tab-separated event per line, ``<utc timestamp>\t<EVENT>\t<field>...``.
|
|
21
|
+
#
|
|
22
|
+
# opendata/log.txt (written by seao_api.opendata):
|
|
23
|
+
# PROCESSED <resource_id> <file title> <n releases>
|
|
24
|
+
# FAILED <resource_id> <file title> <error>
|
|
25
|
+
# RESET database rebuilt from scratch
|
|
26
|
+
# DONE mode=init|update processed=N failed=N rows=N
|
|
27
|
+
# A RESET line forgets every PROCESSED line written before it.
|
|
28
|
+
#
|
|
29
|
+
# <output_dir>/log.txt (written by the save_* functions):
|
|
30
|
+
# OPEN_SEARCH criteria=<json> found=N fetched=N failed=N capped=... file=<name>
|
|
31
|
+
# AVIS <uuid> numero=... sections=<a,b,...> file=<name>
|
|
32
|
+
# FILTER_AVIS filters=<json> match=... rows=N avis=N fetched=N failed=N
|
|
33
|
+
# interrupted=... duration=... file=<name>
|
|
34
|
+
# FAILED <uuid> <error>
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def now_iso() -> str:
|
|
38
|
+
return datetime.now(tz=timezone.utc).isoformat(timespec="seconds")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def append_log(log_path: str | os.PathLike[str], *fields: object) -> None:
|
|
42
|
+
"""Append one timestamped, tab-separated event line to ``log_path``
|
|
43
|
+
(created with a ``Created:`` header if missing or empty)."""
|
|
44
|
+
log_path = Path(log_path)
|
|
45
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
clean = [str(f).replace("\t", " ").replace("\n", " ") for f in fields]
|
|
47
|
+
with open(log_path, "a", encoding="utf-8") as f:
|
|
48
|
+
if f.tell() == 0:
|
|
49
|
+
f.write(f"Created: {now_iso()}\n")
|
|
50
|
+
f.write("\t".join([now_iso(), *clean]) + "\n")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def read_processed(log_path: str | os.PathLike[str]) -> set[str]:
|
|
54
|
+
"""Resource ids marked ``PROCESSED`` since the last ``RESET``."""
|
|
55
|
+
log_path = Path(log_path)
|
|
56
|
+
processed: set[str] = set()
|
|
57
|
+
if not log_path.exists():
|
|
58
|
+
return processed
|
|
59
|
+
for line in log_path.read_text(encoding="utf-8").splitlines():
|
|
60
|
+
parts = line.split("\t")
|
|
61
|
+
if len(parts) < 2:
|
|
62
|
+
continue
|
|
63
|
+
if parts[1] == "RESET":
|
|
64
|
+
processed.clear()
|
|
65
|
+
elif parts[1] == "PROCESSED" and len(parts) >= 3:
|
|
66
|
+
processed.add(parts[2])
|
|
67
|
+
return processed
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------- file names
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def suffixed_name(stem: str, suffix: str | None = None, ext: str = "parquet") -> str:
|
|
74
|
+
"""``<stem>.<ext>``, or ``<stem>_<suffix>.<ext>`` when a suffix is given.
|
|
75
|
+
|
|
76
|
+
Leading and trailing ``_`` of the suffix are removed. A suffix holding a
|
|
77
|
+
path separator or ``:``, or starting with ``.``, raises ``ValueError``.
|
|
78
|
+
"""
|
|
79
|
+
if not suffix:
|
|
80
|
+
return f"{stem}.{ext}"
|
|
81
|
+
suffix = suffix.strip().strip("_")
|
|
82
|
+
if not suffix or any(c in suffix for c in "/\\:") or suffix.startswith("."):
|
|
83
|
+
raise ValueError(f"invalid suffix {suffix!r}: it must be a plain file-name part")
|
|
84
|
+
return f"{stem}_{suffix}.{ext}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def write_parquet_atomic(df: pd.DataFrame, path: Path) -> Path:
|
|
88
|
+
"""Write ``df`` to ``path`` through a temporary file, so a crash never
|
|
89
|
+
leaves a half-written file behind."""
|
|
90
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
tmp_path = path.with_name(path.name + ".tmp")
|
|
92
|
+
df.to_parquet(tmp_path, index=False, compression="zstd")
|
|
93
|
+
tmp_path.replace(path)
|
|
94
|
+
return path
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ------------------------------------------------------------- DataFrames
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _loads(cell: Any) -> Any:
|
|
101
|
+
if isinstance(cell, float) and cell != cell: # NaN: a missing value (pandas >= 3)
|
|
102
|
+
return None
|
|
103
|
+
if isinstance(cell, str) and cell[:1] in ("{", "["):
|
|
104
|
+
try:
|
|
105
|
+
return json.loads(cell)
|
|
106
|
+
except ValueError:
|
|
107
|
+
return cell
|
|
108
|
+
return cell
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _is_json_column(series: pd.Series) -> bool:
|
|
112
|
+
from pandas.api.types import is_object_dtype, is_string_dtype
|
|
113
|
+
|
|
114
|
+
if not (is_object_dtype(series.dtype) or is_string_dtype(series.dtype)):
|
|
115
|
+
return False
|
|
116
|
+
first = series.dropna()
|
|
117
|
+
first = first.iloc[0] if len(first) else None
|
|
118
|
+
return isinstance(first, str) and first[:1] in ("{", "[")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def decode_json(df: pd.DataFrame, columns: Iterable[str] | None = None) -> pd.DataFrame:
|
|
122
|
+
"""Return a copy of ``df`` whose JSON text columns are parsed into Python
|
|
123
|
+
objects (dicts and lists).
|
|
124
|
+
|
|
125
|
+
seao_api stores nested data as JSON text (open-data columns such as
|
|
126
|
+
``tender`` or ``awards``; notice sections such as ``consulter``). By
|
|
127
|
+
default every column whose first non-null value looks like JSON is
|
|
128
|
+
decoded; pass ``columns`` to choose. Decoding is slow on millions of
|
|
129
|
+
rows: filter first.
|
|
130
|
+
|
|
131
|
+
Example::
|
|
132
|
+
|
|
133
|
+
df = seao_api.decode_json(seao_api.fetch_avis(uuid))
|
|
134
|
+
df.loc[0, "consulter"]["avisResumeInformation"]["datePublicationUtc"]
|
|
135
|
+
"""
|
|
136
|
+
out = df.copy()
|
|
137
|
+
cols = list(columns) if columns is not None else [c for c in out.columns if _is_json_column(out[c])]
|
|
138
|
+
for c in cols:
|
|
139
|
+
out[c] = out[c].astype(object).map(_loads)
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------- misc
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def jsonable(value: Any) -> Any:
|
|
147
|
+
"""Make criteria JSON-friendly for the logs (tuples/sets -> lists, callables -> repr)."""
|
|
148
|
+
if isinstance(value, dict):
|
|
149
|
+
return {str(k): jsonable(v) for k, v in value.items()}
|
|
150
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
151
|
+
return [jsonable(v) for v in value]
|
|
152
|
+
if callable(value):
|
|
153
|
+
return repr(value)
|
|
154
|
+
return value
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def fmt_duration(seconds: float) -> str:
|
|
158
|
+
"""``1:02:03`` / ``4:05`` style duration."""
|
|
159
|
+
seconds = int(round(max(seconds, 0)))
|
|
160
|
+
h, rem = divmod(seconds, 3600)
|
|
161
|
+
m, s = divmod(rem, 60)
|
|
162
|
+
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def clock(seconds_from_now: float) -> str:
|
|
166
|
+
"""Local wall-clock time in ``seconds_from_now``, e.g. ``21:45``."""
|
|
167
|
+
return (datetime.now() + timedelta(seconds=seconds_from_now)).strftime("%H:%M")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def shorten(text: str, width: int) -> str:
|
|
171
|
+
return text if len(text) <= width else text[: width - 1] + "…"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def log_to_console(level: int | str = logging.INFO) -> None:
|
|
175
|
+
"""Print seao_api progress messages to the console (stderr).
|
|
176
|
+
|
|
177
|
+
The library logs through the standard :mod:`logging` module under the
|
|
178
|
+
``seao_api`` logger and prints nothing by default. Call this once in a
|
|
179
|
+
script or notebook to see progress::
|
|
180
|
+
|
|
181
|
+
import seao_api
|
|
182
|
+
seao_api.log_to_console() # INFO: progress of long runs
|
|
183
|
+
seao_api.log_to_console("DEBUG") # more detail
|
|
184
|
+
"""
|
|
185
|
+
lib_logger = logging.getLogger("seao_api")
|
|
186
|
+
lib_logger.setLevel(level)
|
|
187
|
+
if not any(getattr(h, "_seao_console", False) for h in lib_logger.handlers):
|
|
188
|
+
handler = logging.StreamHandler()
|
|
189
|
+
handler.setFormatter(logging.Formatter("%(message)s"))
|
|
190
|
+
handler._seao_console = True # type: ignore[attr-defined]
|
|
191
|
+
lib_logger.addHandler(handler)
|
seao_api/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|