Python API¶
Everything below is importable from the top-level package (import machyon). This page is generated from the
source code, so signatures and defaults are always those of the installed version
(1.2.4).
Downloading¶
download
¶
download(
source,
save_dir: str | PathLike = "images",
names=None,
**options,
) -> Report
machyon.download("urls.csv", "images/") - the whole library in one line.
Blocks until done and returns a Report. Inside Jupyter or any running event loop,
use await machyon.adownload(...) instead.
adownload
async
¶
adownload(
source,
save_dir: str | PathLike = "images",
names=None,
**options,
) -> Report
await machyon.adownload(urls, "images/") - for code that already runs an event loop.
Downloader
¶
Downloader(
save_dir: str | PathLike = "images",
config: DownloadConfig | None = None,
on_progress: Callable[[ProgressSnapshot], object]
| None = None,
**options,
)
Fast async image downloads for Python, with every file accounted for.
async with machyon.Downloader("images/") as dl:
report = await dl.download("urls.csv") # or a list of URLs
print(report)
save_dir is where files go. Every DownloadConfig field can be passed as a
keyword (Downloader("out", max_retries=10, headers={...})) or via config=.
on_progress: an optional callable that receives a ProgressSnapshot about twice a
second while download() or retry_failed() runs, and exactly once more when the call ends
(with done=True), however it ends. It runs on the downloader's event loop, so keep it light
and non-blocking (store the snapshot, or put it on a queue). If it raises, the error is logged
once and the download carries on. With no callback, nothing extra runs.
download
async
¶
download(
source,
names=None,
*,
url_col: str | None = None,
name_col: str | None = None,
start: int = 0,
end: int | None = None,
retry_failures: bool = True,
retry_permanent: bool = True,
) -> Report
Download everything in source into save_dir.
source: a file path (CSV/TSV/TXT/JSON/JSONL/Parquet), a DataFrame, or any iterable of
URLs, (url, filename) pairs or dicts.
names: how files are named - a template like "{index}_{hash}{ext}" (default
"{hash}{ext}"), a callable (url, index, row) -> name, or a list of names
matching the URLs one-to-one.
url_col / name_col: which columns hold the URL / an explicit filename (tables only).
start / end: only rows [start, end).
retry_failures: after the pass, wait briefly and sweep transient failures once more.
retry_permanent: rows that failed_downloads.jsonl already records as permanent failures (404, not an
image...) for the same URL are requested again (the default). False carries them over as failed,
with their recorded reason, without a request: Report.carried counts them.
Files already present are skipped, so calling this again resumes an interrupted run. Each call has its own
retry allowance: a transient failure gets 1 + max_retries attempts in the pass and, with
retry_failures, as many again in the final sweep.
retry_failed
async
¶
retry_failed(
include_permanent: bool = False,
only: set | None = None,
start: int = 0,
end: int | None = None,
) -> Report | None
Retry recorded failures under their original filenames - including failures recorded
by earlier runs in save_dir/failed_downloads.jsonl. Permanent failures (404, not an
image, ...) are skipped unless include_permanent=True.
Progress¶
Pass on_progress= to Downloader(), download() or adownload() to follow a call while it runs. The function
receives a ProgressSnapshot about twice a second, and exactly one final snapshot (done=True) however the call
ends: completed, cancelled or with an error. Every number is measured; when the source's length is unknown,
total stays None and no percentage can be derived.
import machyon
def show(p: machyon.ProgressSnapshot) -> None:
pct = f"{100 * p.accounted / p.total:.0f}%" if p.total else "?"
print(f"{p.phase:8} {p.accounted} rows ({pct}), {p.failed} failed, limit {p.concurrency}")
machyon.download("manifest.csv", "images", on_progress=show)
The callback runs on the event loop, so keep it quick: record the snapshot or hand it to a queue. An exception it
raises is logged once and never stops the download. Without on_progress, nothing is sampled.
ProgressSnapshot
dataclass
¶
ProgressSnapshot(
total: int | None,
planned: int,
downloaded: int,
skipped: int,
failed: int,
retries: int,
throttled: int,
hedged: int,
bytes: int,
in_flight: int,
concurrency: int,
elapsed: float,
phase: str,
retrying: int = 0,
done: bool = False,
outcome: str | None = None,
)
Where a download() or retry_failed() call stands, measured, never estimated.
Rows are input rows (a URL that appears on several rows is fetched once but counts once per row). Every count covers the current call only, including its final retry sweep.
total: rows the call will process, when known in advance (a file, a list); None for a stream of unknown
length. On the final snapshot it is the number of rows actually processed, as in Report.total.
planned: rows read from the source and planned so far.
downloaded / skipped: rows whose file was downloaded / was already complete on disk.
failed: rows that failed during this call and are still failed (a row that fails and then succeeds on a retry
is not counted). Its final value equals Report.failed.
retries / throttled / hedged: retry attempts (across all rows and both rounds, so it can be far larger than the
number of rows), 429 or 503 answers, duplicate requests raced against a straggler.
retrying: rows that failed transiently and are waiting for, or making, another automatic attempt right now. It
returns to 0 as each one succeeds or uses up its allowance (then it is in failed).
bytes: bytes of image data written.
in_flight: HTTP attempts running right now.
concurrency: the current concurrency limit: how many attempts Machyon allows at once, not how many are running.
elapsed: seconds since the call started.
phase: "download" for the main pass, "retry" for the final sweep and for retry_failed().
done: True on the last snapshot of the call, and only on that one. Exactly one is delivered per call,
however the call ends.
outcome: on the last snapshot, "completed", "cancelled" or "error"; None before.
accounted
property
¶
Rows that already have an outcome: downloaded, already on disk, or failed.
Configuration¶
DownloadConfig holds every option. Each field can also be passed straight to download(), adownload() or
Downloader() as a keyword. The configuration reference lists them grouped, with their CLI
flags.
DownloadConfig
dataclass
¶
DownloadConfig(
concurrency: int = 32,
max_concurrency: int = 256,
adaptive: bool = True,
hedge: bool = True,
warm_start: bool = True,
profile_path: str | None = None,
max_retries: int = 5,
backoff: float = 0.5,
timeout: float = 15.0,
max_request_time: float = 120.0,
max_retry_after: float = 120.0,
headers: dict[str, str] = dict(),
referer: str | None = None,
user_agent: str = DEFAULT_USER_AGENT,
verify_ssl: bool = True,
tls_trust: str = "native",
use_compression: bool = True,
validate: bool = True,
verify_existing: bool = False,
fsync: bool = False,
stream_threshold: int = 4 * 1024 * 1024,
write_threads: int | None = None,
shard_size: int = 200000,
progress: bool = True,
log_dir: str | None = None,
metrics_dir: str | None = None,
)
Every knob Machyon has. The defaults are tuned for "a big list of image URLs on an ordinary laptop and home connection": you normally change none of them.
replace
¶
replace(**changes: Any) -> DownloadConfig
A copy with some fields changed (unknown names raise TypeError).
from_ini
classmethod
¶
from_ini(
path: str | PathLike, section: str = "SETTINGS"
) -> DownloadConfig
Load from an INI file. Keys are field names, case-insensitive (concurrency = 64).
The aliases CONCURRENT_LIMIT, MAX_CONNECTIONS and BACKOFF_FACTOR are accepted too.
Results¶
Report
dataclass
¶
Report(
total: int = 0,
downloaded: int = 0,
skipped: int = 0,
failed: int = 0,
bytes: int = 0,
duration: float = 0.0,
retries: int = 0,
throttled: int = 0,
deduplicated: int = 0,
hedged: int = 0,
carried: int = 0,
peak_concurrency: int = 0,
final_concurrency: int = 0,
latency_p50: float = 0.0,
latency_p95: float = 0.0,
failure_reasons: dict = dict(),
failure_examples: dict = dict(),
start_time: float = 0.0,
end_time: float = 0.0,
)
Filenames and inputs¶
NameTemplate
¶
Compiled filename template. Call with (url, index, row) -> relative filename.
read_rows
¶
Yield (url, row) from a file path, a DataFrame, or an iterable.
Iterables may contain URL strings, (url, name) pairs, or dicts. For pairs the row is
{"name": name}, which download() uses as the filename.
generate_hashed_name
¶
Short deterministic BLAKE2b hex string (not for security).
Inspecting a source¶
machyon.sources.inspect() reads the first rows of a manifest exactly as download() would and reports what it
found: the format, the columns, which one holds the URLs (and whether it was guessed), and a preview. It reads no
further than the preview, and it never raises for a problem with the file: problems come back in error.
from machyon.sources import inspect
info = inspect("manifest.csv", limit=5)
if info.ok:
print(info.format, info.url_col, info.urls)
else:
kind, message = info.error # e.g. ("no_url_column", "...") with info.columns still filled in
inspect
¶
inspect(
path: str | PathLike,
url_col: str | None = None,
limit: int = 20,
) -> SourceInspection
Read the first limit rows of a source file the way download() reads them, without reading the rest.
The same reader as download() is used, so the columns, the guessed URL column and the URLs are the ones a
download would use. Plain .json files are parsed whole (as download() does); every other format stops
after limit + 1 rows. Never raises for a problem with the file: see SourceInspection.error.
SourceInspection
dataclass
¶
SourceInspection(
format: str,
columns: list[str] | None = None,
url_col: str | None = None,
url_col_guessed: bool = False,
rows: list[dict] = list(),
urls: list[str] = list(),
more: bool = False,
error: tuple[str, str] | None = None,
)
A look at the first rows of a source file: what download() would read from it.
format: "csv", "tsv", "txt", "json", "jsonl" or "parquet" (from the file extension;
anything unrecognised is read as one URL per line, like download() does).
columns: the column names, for tables and lists of objects; None for a plain list of URLs (a TXT file, a
CSV whose first line is already a URL, a JSON list of URLs or of [url, name] pairs).
url_col: the column download() would take the URLs from: the one you named, or the guessed one; None
when there are no columns, or when it can't be guessed (see error).
url_col_guessed: True when url_col was guessed rather than named.
rows: up to limit rows as dicts, in file order. A plain list of URLs gives {"url": ...} (and
"name" for pairs).
urls: the URL of each of those rows ("" where a row has none).
more: True if the source has more rows than limit. Nothing here counts the rows in the whole source.
error: None, or what went wrong, as (kind, message). Kinds: "not_found", "empty",
"unreadable" (malformed or not text), "missing_dependency", "no_url_column",
"unknown_column". With "no_url_column" and "unknown_column", columns and rows are still
filled in, so a caller can let the user pick the column.
Running and logging¶
setup_logging
¶
setup_logging(
log_dir: str | PathLike | None = None,
level: int = INFO,
file_level: int = INFO,
) -> Logger
Configure the machyon logger. Idempotent: safe to call any number of times.
Libraries normally shouldn't configure logging; Machyon only does it when you ask
(Downloader(log_dir=...), console_log=True, or the CLI).
Errors¶
MachyonError
¶
Bases: Exception
Base class for Machyon errors.
FatalDiskError
¶
Bases: MachyonError, RuntimeError
The destination can't be written (disk full, read-only, quota). The run stopped early; every unfinished row is recorded in the failure manifest so it can be resumed.
Advanced¶
AdaptiveLimiter
¶
A semaphore whose capacity tunes itself while the download runs.
- Slow start: doubles concurrency while throughput keeps improving.
- Hill-climb: once gains flatten, holds there and periodically probes +12.5%.
- Revert: if a step up made throughput worse (bandwidth saturated / server queueing), steps back down - fewer sockets for the same speed.
- Throttle (429/503, burst of connection errors): multiplicative decrease and a remembered ceiling that relaxes slowly, so it doesn't re-hit the rate limit.
The window right after each change is discarded so connection warm-up (TCP/TLS handshakes for new sockets) doesn't masquerade as a slowdown.
Class-based API¶
ImageDownloader and ImageRenamer take explicit lists and give step-by-step control on the same engine.
download_images is their one-call helper, and Config reads the INI files they accept.
ImageDownloader
¶
ImageDownloader(
save_dir=None,
cache_dir=None,
concurrent_limit=None,
max_connections=None,
max_retries=None,
backoff_factor=None,
timeout=None,
config_path=None,
memory_cache_size=None,
prefetch_dns=True,
use_compression=True,
metrics_dir=None,
tuning_profile_path=None,
*,
log_dir=None,
adaptive=None,
use_warm_start=True,
**options,
)
Bases: Downloader
Class-based downloader on top of Downloader: explicit (links, names) lists,
INI configuration, and step-by-step methods (metrics_json, retry_failed_downloads, ...).
ImageRenamer
¶
ImageRenamer(
index_col=None,
link_col="image_link",
group_col=None,
entity_col="entity_name",
extension="png",
name_format="{index}_{image_name}_{group_id}_{entity}.{extension}",
)
Build (urls, filenames) from a CSV with fixed column roles (index, link, group, entity).
Names are deterministic, so re-running on the same CSV recognises finished files. For free-form
naming, machyon.download(..., names="{template}") is simpler.
download_images
async
¶
download_images(
image_links,
image_names=None,
save_dir="downloads",
**kwargs,
) -> Report
One-call helper for the class-based API (names default to the URL's file name).
Config
¶
Plain INI accessor used by ImageDownloader(config_path=...) (Config(path).get("SETTINGS", "SAVE_DIR")).