bioamla.common¶
Dependency-free building blocks shared by the domain packages. Nothing here imports a heavy dependency at module load time.
bioamla.common ¶
bioamla.common — dependency-free shared internals.
This package holds the pure-stdlib building blocks used across the domain packages: audio/config constants, file helpers, batch-progress utilities, TOML configuration, and the HTTP client machinery. Nothing here imports a heavy/optional dependency at module load time.
Constants¶
Constants and Configuration Defaults¶
Pure audio/processing constants and default configuration values used throughout the bioamla package.
This module is dependency-free: it intentionally does NOT re-export the HTTP
client machinery (that lives in :mod:bioamla.common.http).
Usage
from bioamla.common.constants import ( SUPPORTED_AUDIO_EXTENSIONS, DEFAULT_SAMPLE_RATE, DefaultConfig, )
DefaultConfig ¶
Default configuration parameters for bioamla audio processing.
Attributes:
| Name | Type | Description |
|---|---|---|
MODEL_NAME |
str
|
Default Hugging Face model identifier for AST |
SAMPLE_RATE |
int
|
Standard sample rate for audio processing (Hz) |
MAX_AUDIO_LENGTH |
int
|
Maximum audio length for processing (seconds) |
MIN_CONFIDENCE |
float
|
Minimum confidence threshold for predictions |
TOP_K |
int
|
Default number of top predictions to return |
Configuration¶
Config objects are validated on construction, and each has a JSON Schema. The
schemas for this release are published alongside these docs, one file per config
in schemas/ (for example
ast-train-file.schema.json for the ast train --config file). Regenerate them
with bioamla system schema --all -o docs/schemas; bioamla system schema lists
the names.
To validate a training config in an editor, point its TOML schema support at the file. With Taplo (Even Better TOML in VS Code), put this on the first line:
#:schema https://raw.githubusercontent.com/jmcmeen/bioamla/main/docs/schemas/ast-train-file.schema.json
Config objects, validation, JSON Schema export, and TOML reading.
The option objects across bioamla (BatchConfig, ClusteringConfig,
EmbeddingConfig, ...) are declared with :func:config_dataclass: ordinary
dataclasses (positional arguments, :func:dataclasses.asdict,
:func:dataclasses.replace all work) that pydantic validates on construction.
A wrong type or an unknown field raises
:class:~bioamla.exceptions.ConfigValidationError naming the field.
- :func:
validate_configbuilds a config from a plain mapping, such as a parsed TOML table, and names the source file in its errors. - :func:
config_schemareturns a config's JSON Schema, for editor completion and validation of config files. :data:CONFIG_CLASSESlists the exported configs. - :func:
load_tomlreads a TOML file into a plain dict. Domain functions take explicit parameters and never read a settings file; the training command's--configfile is the one consumer.
pydantic is imported when the first config class is defined, not when this module
loads, so modules that only need :func:load_toml stay light.
config_dataclass ¶
config_dataclass(cls: type[T]) -> type[T]
Declare a validated config: a pydantic dataclass that rejects unknown fields.
Use in place of @dataclass. Construction validates (and coerces, e.g.
"3" to 3 for an int field) every field; a failure raises
:class:~bioamla.exceptions.ConfigValidationError. Errors raised by the class's own
__post_init__ propagate unchanged. Attribute assignment after
construction is not validated.
validate_config ¶
validate_config(
cls: type[T],
data: Mapping[str, Any],
source: str | Path | None = None,
) -> T
Build a config from a mapping, validating every field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type[T]
|
A class declared with :func: |
required |
data
|
Mapping[str, Any]
|
Field values, e.g. a table from :func: |
required |
source
|
str | Path | None
|
The file the data came from, named in error messages. |
None
|
Returns:
| Type | Description |
|---|---|
T
|
The validated config. |
Raises:
| Type | Description |
|---|---|
ConfigValidationError
|
If a value has the wrong type or a key isn't a field. The message lists every problem with its dotted key path. |
resolve_config_class ¶
resolve_config_class(name: str) -> type
Return the config class registered under name in :data:CONFIG_CLASSES.
Raises:
| Type | Description |
|---|---|
ConfigError
|
If |
DependencyError
|
If the class's package needs an extra that isn't installed. |
config_schema ¶
config_schema(config: str | type) -> dict[str, Any]
Return the JSON Schema for a config class or a :data:CONFIG_CLASSES name.
Private fields (names starting with _) are left out.
config_schema_report ¶
config_schema_report(
name: str | None = None,
output: str | Path | None = None,
) -> dict[str, Any]
A config's JSON Schema, optionally written to output; without name, the
configs that have one.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
If |
DependencyError
|
If the config's package needs a missing extra. |
export_config_schemas ¶
export_config_schemas(
output_dir: str | Path,
) -> dict[str, Any]
Write every exported config's JSON Schema to <name>.schema.json in
output_dir.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
dict[str, Any]
|
package needs an extra that isn't installed is skipped. |
load_toml ¶
load_toml(filepath: str | Path) -> dict[str, Any]
Load a TOML file into a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the TOML file. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Parsed configuration as a nested dict. |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the file doesn't exist. |
ConfigError
|
If TOML parsing fails. |
Deprecated names¶
Deprecated names kept importable for a while after a rename.
A module that renames a public name keeps the old one working through a PEP 562
module __getattr__ built here. Accessing the old name returns the new object
and emits a :class:DeprecationWarning that points at the caller's line.
deprecated_aliases ¶
deprecated_aliases(
module_name: str,
namespace: dict[str, Any],
aliases: Mapping[str, str],
) -> Callable[[str], Any]
Build a module __getattr__ that serves old names for renamed ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_name
|
str
|
The module's |
required |
namespace
|
dict[str, Any]
|
The module's |
required |
aliases
|
Mapping[str, str]
|
Old name -> new name. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[str], Any]
|
A function to assign to the module's |
Example
getattr = deprecated_aliases(name, globals(), {"OldName": "NewName"})
Logging¶
Library records about files, batches and training runs carry structured fields
(operation, file, index, total, run_id, epoch, elapsed_s, status,
error). Per-item and per-step records are logged at DEBUG; a training run's start
and end at INFO. From the command line, bioamla --log-format json --log-level debug
<command> writes them to stderr as JSON lines.
Structured fields on bioamla's log records, and a JSON formatter for them.
Library code logs through :mod:logging. Records about a file, a batch or a
training run also carry structured fields (passed with extra=), so a consumer
such as a GUI, a batch runner or a log aggregator can read them without parsing
the message text. :data:LOG_FIELDS is the contract: these names, with these
meanings, are what bioamla attaches. A record carries only the fields that apply.
The library never configures handlers. An application that wants the fields as
JSON lines attaches :class:JsonFormatter to a handler::
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.getLogger("bioamla").addHandler(handler)
The bioamla command does this with bioamla --log-format json.
JsonFormatter ¶
Bases: Formatter
Format each record as one JSON object per line.
Keys: time (UTC, ISO 8601), level, logger, message, then every
:data:LOG_FIELDS field present on the record, then exception when the
record has exception info. Values that aren't JSON types (e.g. paths) are
written as strings.
log_fields ¶
log_fields(**fields: Any) -> dict[str, dict[str, Any]]
Build the extra= argument for a log call, checked against :data:LOG_FIELDS.
None values are dropped, so callers can pass optional fields directly.
Example
logger.info("Segmented %s", path, **log_fields(file=str(path), index=3, total=10))
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If a name isn't in :data: |
Files¶
Files Module¶
Pure stdlib file and path operations: - File discovery and existence checking - Text/binary read/write helpers - Download utilities and URL helpers - Path utilities and sanitization - ZIP archive helpers - Raising path validators (require_exists, prepare_output_path)
This module is dependency-free and uses :mod:pathlib / :func:open /
:mod:shutil directly. It does NOT define a File/TextFile/BinaryFile
dataclass hierarchy.
AtomicFileWriter ¶
Write a file in pieces, so it appears whole or not at all.
The bytes go to a temporary file in the target's folder; :meth:commit moves it
into place (replacing an existing file only with overwrite) and leaving the
with block without committing removes it.
Example
with AtomicFileWriter("rec.wav") as w: ... for chunk in chunks: ... w.write(chunk) ... w.commit()
Raises:
| Type | Description |
|---|---|
FileExistsError
|
From :meth: |
OSError
|
If the folder can't be created or written. |
read_text ¶
read_text(
filepath: str | Path, encoding: str = "utf-8"
) -> str
Read entire text file contents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the text file |
required |
encoding
|
str
|
Character encoding |
'utf-8'
|
Returns:
| Type | Description |
|---|---|
str
|
File contents as string |
write_text ¶
write_text(
filepath: str | Path,
content: str,
encoding: str = "utf-8",
) -> int
Write content to a text file, creating parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the text file |
required |
content
|
str
|
String content to write |
required |
encoding
|
str
|
Character encoding |
'utf-8'
|
Returns:
| Type | Description |
|---|---|
int
|
Number of characters written |
npy_path ¶
npy_path(path: str | Path) -> str
The file numpy.save writes for path: .npy is added unless the name
already ends in it (as numpy decides, case-sensitively).
write_text_atomic ¶
write_text_atomic(
filepath: str | Path,
content: str,
encoding: str = "utf-8",
) -> None
Write content via a temporary file in the same folder and a rename, so a
reader (or a crash) never sees a half-written file.
read_binary ¶
read_binary(filepath: str | Path) -> bytes
Read entire binary file contents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the binary file |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
File contents as bytes |
write_binary ¶
write_binary(filepath: str | Path, content: bytes) -> int
Write content to a binary file, creating parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the binary file |
required |
content
|
bytes
|
Bytes content to write |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of bytes written |
append_text ¶
append_text(
filepath: str | Path,
content: str,
encoding: str = "utf-8",
) -> int
Append content to a text file, creating parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the text file |
required |
content
|
str
|
String content to append |
required |
encoding
|
str
|
Character encoding |
'utf-8'
|
Returns:
| Type | Description |
|---|---|
int
|
Number of characters written |
append_binary ¶
append_binary(filepath: str | Path, content: bytes) -> int
Append content to a binary file, creating parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str | Path
|
Path to the binary file |
required |
content
|
bytes
|
Bytes content to append |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of bytes written |
get_files_by_extension ¶
get_files_by_extension(
directory: str | Path,
extensions: list[str] | None = None,
recursive: bool = True,
) -> list[str]
Get a list of files in a directory filtered by extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Path to the directory to search |
required |
extensions
|
list[str] | None
|
List of file extensions to include (e.g., ['.wav', '.mp3']). If None, returns all files. |
None
|
recursive
|
bool
|
If True, search subdirectories recursively |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of file paths matching the criteria, sorted alphabetically |
create_directory ¶
create_directory(path: str | Path) -> Path
Create a directory and all parent directories if they don't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the directory to create |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path that was created as a Path object |
ensure_directory ¶
ensure_directory(path: str | Path) -> Path
Ensure a directory exists, creating it (and parents) if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the directory |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path to the directory as a Path object |
require_exists ¶
require_exists(path: str | Path) -> Path
Return Path(path) if it exists, else raise :class:NotFoundError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path that must exist. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path as a :class: |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the path does not exist. |
prepare_output_path ¶
prepare_output_path(path: str | Path) -> Path
Return Path(path) after ensuring its parent directory exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination path whose parent should be created. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path as a :class: |
get_extension_from_url ¶
get_extension_from_url(url: str) -> str
Extract a file extension from a URL.
Checks for common audio file extensions in the URL and returns the appropriate extension. Falls back to .mp3 if no extension is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL to extract the extension from |
required |
Returns:
| Type | Description |
|---|---|
str
|
The file extension including the leading dot (e.g., ".wav") |
get_extension_from_content_type ¶
get_extension_from_content_type(content_type: str) -> str
Map an HTTP Content-Type header to a file extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content_type
|
str
|
The Content-Type header value |
required |
Returns:
| Type | Description |
|---|---|
str
|
The corresponding file extension (including dot), or empty string if unknown |
download_file ¶
download_file(
url: str,
output_path: str | Path,
show_progress: bool = True,
) -> Path
Download a file from a URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to download from |
required |
output_path
|
str | Path
|
Path to save the downloaded file |
required |
show_progress
|
bool
|
If True, log the download at INFO level |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the downloaded file |
sanitize_filename ¶
sanitize_filename(
name: str, *, lowercase: bool = True
) -> str
Sanitize a string for use as a filename or directory name.
Converts the name to lowercase (unless lowercase=False), replaces spaces,
control characters (tabs, newlines, ...) and characters invalid in file
names with underscores, and ensures a valid result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The string to sanitize |
required |
lowercase
|
bool
|
Lowercase the result (the default). |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A sanitized string safe for use as a filename. |
str
|
Returns "unknown" if the result would be empty. |
Examples:
>>> sanitize_filename("My Species Name")
'my_species_name'
>>> sanitize_filename("Test: File?")
'test__file_'
>>> sanitize_filename("")
'unknown'
get_relative_path ¶
get_relative_path(filepath: Path, base_path: Path) -> str
Get the relative path of a file from a base directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Path
|
Absolute path to the file |
required |
base_path
|
Path
|
Base directory path |
required |
Returns:
| Type | Description |
|---|---|
str
|
Relative path as a string |
Note
Falls back to the filename if the file is not under the base path.
extract_zip_file ¶
extract_zip_file(
zip_path: str | Path, extract_to: str | Path
) -> list[str]
Extract a ZIP file to a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
extract_to
|
str | Path
|
Directory to extract files to |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of extracted file paths |
create_zip_file ¶
create_zip_file(
files: list[str | Path], zip_path: str | Path
) -> str
Create a ZIP file from a list of files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
files
|
list[str | Path]
|
List of file paths to include in the ZIP |
required |
zip_path
|
str | Path
|
Path for the output ZIP file |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to the created ZIP file |
zip_directory ¶
zip_directory(
directory: str | Path, zip_path: str | Path
) -> str
Create a ZIP file from a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Path to the directory to zip |
required |
zip_path
|
str | Path
|
Path for the output ZIP file |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to the created ZIP file |
download_to_dir ¶
download_to_dir(
url: str,
output_dir: str | Path = ".",
show_progress: bool = True,
) -> str
Download url into output_dir, named after the URL's last path part
(downloaded_file if it has none).
Returns:
| Type | Description |
|---|---|
str
|
The file written. |
Raises:
| Type | Description |
|---|---|
BioamlaError
|
If the download fails. |
unzip_to ¶
unzip_to(
zip_file: str | Path,
output_dir: str | Path = ".",
*,
max_bytes: int = UNZIP_MAX_BYTES,
) -> list[str]
Extract a ZIP archive into output_dir.
Every entry is checked before anything is written: it must land inside
output_dir with links already there followed (so an entry can't write through
a link to somewhere else), and it can't touch workspace metadata (a .bioamla
folder).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_file
|
str | Path
|
The archive. |
required |
output_dir
|
str | Path
|
Where to extract it. |
'.'
|
max_bytes
|
int
|
Refuse archives that would extract to more than this. |
UNZIP_MAX_BYTES
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The extracted paths. |
Raises:
| Type | Description |
|---|---|
NotFoundError
|
If the archive doesn't exist. |
InvalidInputError
|
If an entry would leave |
BioamlaError
|
If it isn't a valid ZIP or can't be extracted. |
zip_path ¶
zip_path(source: str | Path, zip_file: str | Path) -> str
Zip a folder (its contents) or a single file into zip_file.
Raises:
| Type | Description |
|---|---|
BioamlaError
|
If the archive can't be written. |
HTTP¶
HTTP Client Utilities¶
Provides rate limiting and common HTTP client functionality for interfacing with external APIs.
Features: - Thread-safe rate limiting with configurable requests per second - Automatic retry with exponential backoff - Unified HTTP client with timeout and error handling - Disk-based caching with TTL for API responses
APICache
dataclass
¶
Simple disk-based cache for API responses.
Caches JSON responses to disk with TTL (time-to-live) support. Uses MD5 hash of request parameters as cache key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl_seconds
|
int
|
Time-to-live for cache entries in seconds. Default is 24 hours (86400 seconds). |
86400
|
enabled
|
bool
|
Whether caching is enabled. Default True. |
True
|
Example
cache = APICache(ttl_seconds=3600) # 1 hour TTL key = cache.make_key("https://api.example.com", {"q": "test"}) cache.set(key, {"result": "data"}) data = cache.get(key) # Returns cached data or None
make_key ¶
make_key(
url: str, params: dict[str, Any] | None = None
) -> str
Generate a cache key from URL and parameters.
get ¶
get(key: str) -> dict[str, Any] | None
Get a cached response if it exists and hasn't expired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Cache key from make_key(). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Cached data or None if not found/expired. |
set ¶
set(key: str, data: dict[str, Any]) -> None
Cache a response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Cache key from make_key(). |
required |
data
|
dict[str, Any]
|
Response data to cache. |
required |
RateLimiter
dataclass
¶
Thread-safe rate limiter using token bucket algorithm.
Limits the number of requests that can be made within a time window to comply with API rate limits.
Thread Safety
This class is fully thread-safe. All public methods use internal
locking via threading.Lock to ensure safe concurrent access
from multiple threads. Safe to share a single instance across
worker threads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requests_per_second
|
float
|
Maximum requests allowed per second. |
1.0
|
burst_size
|
int
|
Maximum burst of requests allowed (default: 1). |
1
|
Example
limiter = RateLimiter(requests_per_second=1.0) limiter.acquire() # Blocks if rate limit exceeded
Make API request here¶
acquire ¶
acquire(tokens: int = 1) -> float
Acquire tokens, blocking if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
int
|
Number of tokens to acquire. |
1
|
Returns:
| Type | Description |
|---|---|
float
|
Time waited in seconds. |
try_acquire ¶
try_acquire(tokens: int = 1) -> bool
Try to acquire tokens without blocking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
int
|
Number of tokens to acquire. |
1
|
Returns:
| Type | Description |
|---|---|
bool
|
True if tokens were acquired, False otherwise. |
APIClient ¶
HTTP client with retry, rate limiting, and optional caching support.
Provides a unified interface for making API requests with automatic error handling and exponential backoff retry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Base URL for API requests. |
''
|
rate_limiter
|
RateLimiter | None
|
RateLimiter instance for rate limiting. |
None
|
timeout
|
int
|
Request timeout in seconds (default: 30). |
30
|
max_retries
|
int
|
Maximum number of retries (default: 3). |
3
|
user_agent
|
str
|
User-Agent header value. |
'bioamla/1.0'
|
cache
|
APICache | None
|
Optional APICache instance for response caching. |
None
|
Example
client = APIClient( ... base_url="https://api.example.com", ... rate_limiter=RateLimiter(requests_per_second=1.0), ... cache=APICache(ttl_seconds=3600), # Cache for 1 hour ... ) response = client.get("/endpoint", params={"q": "search"})
get ¶
get(
endpoint: str,
params: dict[str, Any] | None = None,
use_cache: bool = True,
**kwargs: Any,
) -> dict[str, Any]
Make a GET request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
API endpoint (appended to base_url). |
required |
params
|
dict[str, Any] | None
|
Query parameters. |
None
|
use_cache
|
bool
|
Whether to use cache for this request (default True). |
True
|
**kwargs
|
Any
|
Additional arguments passed to requests. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Response JSON as dictionary. |
Raises:
| Type | Description |
|---|---|
RequestException
|
On request failure. |
post ¶
post(
endpoint: str,
data: dict[str, Any] | None = None,
json_data: dict[str, Any] | None = None,
**kwargs: Any,
) -> dict[str, Any]
Make a POST request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
API endpoint. |
required |
data
|
dict[str, Any] | None
|
Form data. |
None
|
json_data
|
dict[str, Any] | None
|
JSON data. |
None
|
**kwargs
|
Any
|
Additional arguments passed to requests. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Response JSON as dictionary. |
download ¶
download(
url: str,
filepath: str | Path,
chunk_size: int = 8192,
progress_callback: OnProgress | None = None,
) -> Path
Download a file from URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to download from. |
required |
filepath
|
str | Path
|
Local path to save file. |
required |
chunk_size
|
int
|
Download chunk size in bytes. |
8192
|
progress_callback
|
OnProgress | None
|
Callback(downloaded_bytes, total_bytes). |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to downloaded file. |
clear_cache ¶
clear_cache() -> int
Clear all cached API responses.
Returns:
| Type | Description |
|---|---|
int
|
Number of cache files removed. |
rate_limited ¶
rate_limited(
requests_per_second: float = 1.0,
) -> Callable[[F], F]
Decorator to rate limit a function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requests_per_second
|
float
|
Maximum calls per second. |
1.0
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function. |
Example
@rate_limited(0.5) # 1 call per 2 seconds ... def fetch_data(): ... return requests.get("https://api.example.com/data")
Batch progress¶
Batch Progress Utilities¶
Stdlib-only helpers for reporting progress during batch operations and a
free process_batch function adapted from the old BaseService._process_batch.
BatchProgress
dataclass
¶
BatchProcessResult
dataclass
¶
Result of :func:process_batch.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list[T]
|
Successful per-item results, in the order items succeeded. |
errors |
list[tuple[object, Exception]]
|
List of |
process_batch ¶
process_batch(
items: list[I],
processor: Callable[[I], T],
on_progress: ProgressCallback | None = None,
continue_on_error: bool = True,
) -> BatchProcessResult
Process a batch of items sequentially with progress reporting.
Iterates items, calls processor(item) for each, collects results,
and reports progress via on_progress. On a per-item error it either
continues (collecting the (item, error) pair) or re-raises depending
on continue_on_error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[I]
|
Items to process. |
required |
processor
|
Callable[[I], T]
|
Callable applied to each item. |
required |
on_progress
|
ProgressCallback | None
|
Optional callback invoked with a :class: |
None
|
continue_on_error
|
bool
|
If True, collect errors and keep going; if False, re-raise the first exception. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
BatchProcessResult
|
class: |