# Build your first image dataset

Turn a CSV of image URLs into a folder of images sorted by category, a report of what happened, and a gallery you can open in your browser. One Machyon call does the downloading.

**Level**Beginner

**Uses**`machyon.download()`, filename templates, the `Report`

**Time**About 10 minutes

## What you will build

A script that reads a CSV of 14 image links, downloads them into folders by category, and writes a gallery page. Here is the gallery from a real run:

![The gallery: photos of a cat, a dog and a highland cow under "Animals", landscapes under "Nature", each with its file path and the photographer's name](<https://divyanshusingh96.github.io/machyon/assets/cookbook/first-dataset-gallery-light.webp>) ![The gallery: photos of a cat, a dog and a highland cow under "Animals", landscapes under "Nature", each with its file path and the photographer's name](<https://divyanshusingh96.github.io/machyon/assets/cookbook/first-dataset-gallery-dark.webp>)

Two of the 14 links are broken on purpose, so you also see what Machyon does when a download can't succeed.

## What you will learn

- How to download a whole table of links with one function call.
- How to tell Machyon which column holds the URL.
- How to name and sort files using your own columns, with a filename template.
- How to read the `Report`: what was downloaded, skipped, or failed, and why.
- Why "the server answered" is not the same as "you got an image".
- What happens when you run the same download again.

## How it works

```text
manifest.csv ──► machyon.download() ──► dataset/images/<category>/<id>_<name>.jpg
                         │                 dataset/images/failed_downloads.jsonl
                         ▼
                      Report ──────────► dataset/report.json
                                         dataset/gallery.html  (built from the files on disk)
```

The gallery is built from the files that are actually on disk, not from the manifest, so it can't show an image that wasn't downloaded.

## Requirements

- Python 3.11 or newer.
- An internet connection (the photos come from [Picsum Photos](<https://picsum.photos/>)).

## Installation

Make a folder for the project, and inside it a virtual environment:

```powershell
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install machyon
```

```bash
python -m venv .venv
source .venv/bin/activate
pip install machyon
```

Then save the two files below into that folder, as `manifest.csv` and `build_dataset.py`. You'll find both in the repository too, in [`examples/cookbook/first_dataset/`](<https://github.com/DivyanshuSingh96/machyon/tree/main/examples/cookbook/first_dataset>).

> [!NOTE]
>
> **Working on Machyon itself?**
>
> From a clone of the repository, install your local copy instead with `pip install -e .`, then run the script from `examples/cookbook/first_dataset/`.

## The manifest

Each row is one image: an `id`, a `name`, a `category`, the `image_url`, and who took the photo. The photos are by the photographers named in each row, shared on Unsplash under the [Unsplash License](<https://unsplash.com/license>); the manifest only lists links to them.

manifest.csv

```text
id,name,category,image_url,author,source,license
1,cat,animals,https://picsum.photos/id/40/640/427.jpg,Ryan Mcguire,https://unsplash.com/photos/N-1XGL54pQg,Unsplash License
2,dog,animals,https://picsum.photos/id/169/640/427.jpg,Noel Lopez,https://unsplash.com/photos/BjelfpszQDw,Unsplash License
3,highland-cow,animals,https://picsum.photos/id/200/640/427.jpg,Elias Carlsson,https://unsplash.com/photos/wSb8d-ke5-4,Unsplash License
4,forest-lake,nature,https://picsum.photos/id/10/640/427.jpg,Paul Jarvis,https://unsplash.com/photos/6J--NXulQCs,Unsplash License
5,waterfall,nature,https://picsum.photos/id/15/640/427.jpg,Paul Jarvis,https://unsplash.com/photos/NYDo21ssGao,Unsplash License
6,mountains,nature,https://picsum.photos/id/29/640/427.jpg,Go Wild,https://unsplash.com/photos/V0yAek6BgGk,Unsplash License
7,bridge-at-night,city,https://picsum.photos/id/43/640/427.jpg,Oleg Chursin,https://unsplash.com/photos/IoCWq07GaG4,Unsplash License
8,street,city,https://picsum.photos/id/57/640/427.jpg,Nicholas Swanson,https://unsplash.com/photos/SyBYM8R6VU4,Unsplash License
9,canal,city,https://picsum.photos/id/164/640/427.jpg,Linh Nguyen,https://unsplash.com/photos/agkblvPff5U,Unsplash License
10,mug,objects,https://picsum.photos/id/30/640/427.jpg,Shyamanta Baruah,https://unsplash.com/photos/aeVA-j1y2BY,Unsplash License
11,record-player,objects,https://picsum.photos/id/39/640/427.jpg,Luke Chesser,https://unsplash.com/photos/pFqrYbhIAXs,Unsplash License
12,clock,objects,https://picsum.photos/id/175/640/427.jpg,petradr,https://unsplash.com/photos/8hgm6mKK04U,Unsplash License
13,missing-photo,broken,https://picsum.photos/id/100000/640/427.jpg,,,(deliberately broken: no such photo)
14,not-a-photo,broken,https://picsum.photos/,,,"(deliberately broken: a web page, not an image)"
```

The last two rows are the deliberately broken ones: a photo that doesn't exist, and a link to a web page instead of an image.

## The script

build\_dataset.py

```python
"""Build your first image dataset with Machyon: download, organise, check the report, browse a gallery.

    pip install machyon
    python build_dataset.py                                    # manifest.csv -> dataset/, then opens the gallery
    python build_dataset.py --manifest my.csv --out my-dataset --no-open

Walkthrough: https://divyanshusingh96.github.io/machyon/cookbook/first-dataset/
"""
from __future__ import annotations

import argparse
import csv
import html
import json
import webbrowser
from pathlib import Path

import machyon

HERE = Path(__file__).resolve().parent
NAMES = "{category}/{id}_{name}{ext}"           # e.g. animals/1_cat.jpg


def build(manifest: Path, out: Path) -> machyon.Report:
    """Download every row of the manifest into out/images, then write out/report.json and out/gallery.html."""
    images = out / "images"

    # 1. The whole download is one call. Machyon reads the CSV, takes the URL from the "image_url" column, and
    #    names each file from the template using the row's own columns.
    report = machyon.download(manifest, images, url_col="image_url", names=NAMES)

    # 2. The report says what happened to every row: downloaded, already on disk (skipped), or failed.
    (out / "report.json").write_text(json.dumps(report.to_dict(), indent=2), encoding="utf-8")

    # 3. Rows that failed are listed, with the reason, in the failure ledger next to the images.
    failures = read_failures(images)

    # 4. A gallery built from the files that are actually on disk.
    rows = read_rows(manifest)
    write_gallery(out / "gallery.html", rows, images, report, failures)
    return report


def read_rows(manifest: Path) -> list[dict]:
    with open(manifest, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def read_failures(images: Path) -> dict[str, dict]:
    """URL -> ledger entry, for every row that couldn't be downloaded."""
    ledger = images / "failed_downloads.jsonl"
    if not ledger.exists():
        return {}
    entries = [json.loads(line) for line in ledger.read_text(encoding="utf-8").splitlines() if line.strip()]
    return {e["url"]: e for e in entries}


def find_file(images: Path, row: dict) -> Path | None:
    """The file Machyon wrote for this row. {ext} is decided per file, so look for any extension."""
    matches = sorted((images / row["category"]).glob(f"{row['id']}_{row['name']}.*"))
    return matches[0] if matches else None


def write_gallery(path: Path, rows: list[dict], images: Path, report: machyon.Report, failures: dict) -> None:
    esc = html.escape
    sections: dict[str, list[str]] = {}
    for row in rows:
        file = find_file(images, row)
        if file is None:
            continue
        src = file.relative_to(path.parent).as_posix()
        credit = ""
        if row.get("author") and row.get("source"):
            credit = (f'<br>Photo: <a href="{esc(row["source"])}">{esc(row["author"])}</a>'
                      f' ({esc(row.get("license", ""))})')
        sections.setdefault(row["category"], []).append(
            f'<figure><img src="{esc(src)}" alt="{esc(row["name"])}" loading="lazy">'
            f'<figcaption><b>{esc(row["name"])}</b> <code>{esc(src)}</code>{credit}</figcaption></figure>')
    failed_rows = "".join(
        f'<tr><td>{esc(row["id"])}</td><td>{esc(row["name"])}</td><td><code>{esc(failures[row["image_url"]]["reason"])}'
        f'</code></td><td>{esc(failures[row["image_url"]].get("error", ""))}</td></tr>'
        for row in rows if row["image_url"] in failures)
    body = "".join(f'<h2>{esc(cat)} <small>{len(figs)}</small></h2><div class="grid">{"".join(figs)}</div>'
                   for cat, figs in sections.items())
    failed = (f'<h2>Couldn\'t be downloaded <small>{report.failed}</small></h2><table><tr><th>id</th><th>name</th>'
              f'<th>reason</th><th>details</th></tr>{failed_rows}</table>') if failed_rows else ""
    path.write_text(f"""<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>My first image dataset</title>
<style>
  :root {{ color-scheme: light dark; --ink: #2B3C52; --muted: #4F637D; --paper: #FFFBF0; --card: #fff; }}
  @media (prefers-color-scheme: dark) {{ :root {{ --ink: #ECF1FF; --muted: #AEB9DD; --paper: #2A3142; --card: #323A4F; }} }}
  body {{ margin: 0; font: 16px/1.55 system-ui, sans-serif; color: var(--ink); background: var(--paper); }}
  main {{ max-width: 70rem; margin: 0 auto; padding: 1.5rem 1rem 3rem; }}
  h1 {{ margin: 0 0 .3rem; }} h2 {{ margin: 2rem 0 .6rem; text-transform: capitalize; }}
  h2 small {{ color: var(--muted); font-weight: 400; font-size: .8em; }}
  .summary {{ color: var(--muted); }}
  .grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); gap: 1rem; }}
  figure {{ margin: 0; background: var(--card); border-radius: 10px; overflow: hidden; box-shadow: 0 4px 18px rgba(0,0,0,.08); }}
  img {{ display: block; width: 100%; aspect-ratio: 3 / 2; object-fit: cover; }}
  figcaption {{ padding: .5rem .7rem .7rem; font-size: .8rem; color: var(--muted); }}
  figcaption b {{ color: var(--ink); }} a {{ color: inherit; }}
  code {{ font-size: .85em; }}
  table {{ border-collapse: collapse; width: 100%; font-size: .85rem; }}
  th, td {{ text-align: left; padding: .4rem .6rem; border-bottom: 1px solid rgba(127,127,127,.3); }}
</style></head>
<body><main>
<h1>My first image dataset</h1>
<p class="summary">Downloaded with Machyon {esc(machyon.__version__)}: {report.downloaded} downloaded,
{report.skipped} already on disk, {report.failed} couldn't be downloaded, in {report.duration:.1f} s.</p>
{body}
{failed}
</main></body></html>
""", encoding="utf-8")


def main(argv: list[str] | None = None) -> machyon.Report:
    ap = argparse.ArgumentParser(description="Build a small image dataset and a gallery to browse it.")
    ap.add_argument("--manifest", type=Path, default=HERE / "manifest.csv")
    ap.add_argument("--out", type=Path, default=Path("dataset"))
    ap.add_argument("--no-open", action="store_true", help="don't open the gallery in the browser")
    a = ap.parse_args(argv)
    a.out.mkdir(parents=True, exist_ok=True)

    report = build(a.manifest, a.out)
    print(report)
    print(f"Images:  {(a.out / 'images').resolve()}")
    print(f"Report:  {(a.out / 'report.json').resolve()}")
    print(f"Gallery: {(a.out / 'gallery.html').resolve()}")
    if not a.no_open:
        webbrowser.open((a.out / "gallery.html").resolve().as_uri())
    return report


if __name__ == "__main__":
    main()
```

Run it:

```bash
python build_dataset.py
```

## Understanding the Machyon API

All the downloading is this one call:

```python
report = machyon.download(manifest, images, url_col="image_url", names="{category}/{id}_{name}{ext}")
```

- **`manifest`**: the input. Machyon reads CSV files directly; it also reads TSV, TXT, JSON, JSON Lines, Parquet, DataFrames and plain lists (see [Input sources](<https://divyanshusingh96.github.io/machyon/guides/input-sources/index.md>)).
- **`images`**: the folder to download into. Machyon creates it, and any folders the names need.
- **`url_col="image_url"`**: which column holds the link. Here Machyon would find it anyway, because `image_url` is one of the column names it recognises (with `url`, `image_link`, `link` and a few others), but naming it makes the script clearer and keeps working if you add another link column.
- **`names="{category}/{id}_{name}{ext}"`**: a [filename template](<https://divyanshusingh96.github.io/machyon/guides/naming/index.md>). `{category}`, `{id}` and `{name}` come from each row's own columns; `{ext}` is the image's real format. The `/` makes a folder per category.
- **`report`**: a `Report`. `report.downloaded`, `report.skipped` and `report.failed` always add up to the number of rows; `report.failure_reasons` counts why rows failed, and `report.to_dict()` gives you everything as a dictionary (that's what `report.json` is).

## Expected output

From a real run:

```text
12 downloaded, 0 already on disk, 2 failed in 1.9s (6.2 img/s, 0.28 MB/s) | failures: {'not_image': 1, 'http_404': 1}
```

```text
dataset/
├── gallery.html
├── report.json
└── images/
    ├── animals/   1_cat.jpg  2_dog.jpg  3_highland-cow.jpg
    ├── city/      7_bridge-at-night.jpg  8_street.jpg  9_canal.jpg
    ├── nature/    4_forest-lake.jpg  5_waterfall.jpg  6_mountains.jpg
    ├── objects/   10_mug.jpg  11_record-player.jpg  12_clock.jpg
    ├── broken/    (empty: nothing is left behind for rows that failed)
    ├── failed_downloads.jsonl
    └── failed_downloads.txt
```

The two failures are in `failed_downloads.jsonl`, one JSON line each:

```json
{"url": "https://picsum.photos/id/100000/640/427.jpg", "names": ["broken/13_missing-photo.jpg"], "reason": "http_404", "error": "HTTP 404 Not Found"}
{"url": "https://picsum.photos/", "names": ["broken/14_not-a-photo.{ext}"], "reason": "not_image", "error": "Content-Type text/html, body starts b'<!doctype html>...'"}
```

The second one is the important lesson. That link answered **200 OK**, the code that usually means success, but what came back was a web page. Machyon checks the first bytes of every download, saw HTML instead of an image, and refused to save it as a `.jpg`. Its name still says `{ext}` because no image format was ever found.

## Run it again

Run the same command a second time:

```text
0 downloaded, 12 already on disk, 2 failed in 0.6s (0.0 img/s, 0.00 MB/s) | failures: {'not_image': 1, 'http_404': 1}
```

The 12 photos are already there, so they're skipped in well under a second. The two broken rows are tried again, because maybe they work now; they don't, so they're recorded again. This is also how you resume a download that was interrupted: run the same command.

## Experiment with it

- **Change the folders:** use `names="{name}/{id}{ext}"` and see the layout change. Add `{hash}` for names that can never collide.
- **Add your own rows:** any direct link to an image works. Add a row with a new category and run it again: only the new image is downloaded.
- **Try another format:** save the manifest as JSON Lines (one object per line with the same keys) and pass that file instead. The rest of the script doesn't change.
- **Read the report in Python:** print `report.failure_examples` to see each failure reason with an example URL and a hint.

## Troubleshooting

- **Every row failed with a connection error:** check your internet connection, or whether a proxy is required. `machyon doctor` checks your setup.
- **An error about an unknown key in the template, before anything downloads:** every `{...}` in `names` must be a column of the manifest or one of `{index}`, `{hash}`, `{stem}`, `{ext}` and `{host}`. The error lists the keys you can use.
- **The gallery shows nothing:** open it from the `dataset` folder, next to `images/`, because it uses relative paths.

More in [Troubleshooting](<https://divyanshusingh96.github.io/machyon/troubleshooting/index.md>).

## Next

- [Adaptive Concurrency Lab](<https://divyanshusingh96.github.io/machyon/lab/adaptive-concurrency/index.md>): watch what Machyon does when a server says "too many".
- [Amazon ML Challenge](<https://divyanshusingh96.github.io/machyon/getting-started/amazon-ml-challenge/index.md>): the same idea at 263,859 rows.
- [The failure ledger](<https://divyanshusingh96.github.io/machyon/reliability/failure-ledger/index.md>): everything in `failed_downloads.jsonl`, and how to retry.
