"""The MNIST digits of examples/mnist.pl, as a safetensors file.

    python mnist.py [DIR]

writes, in DIR (the directory of this script by default), mnist.safetensors:

    train.images [60000, 784]  float32 in 0..1     train.labels [60000]  int32 in 0..9
    test.images  [10000, 784]                      test.labels  [10000]

from mnist.npz, the archive Keras distributes: the copy in ~/.keras/datasets when there is
one, else downloaded there. Needs numpy and safetensors.

The files are not in the repository: the examples download them from the GitHub release
examples-data-1 where they are not beside the examples, see example_data.pl. A file written
again differs from its asset: upload it to a new release, and change release/1 and sha256/2
there.
"""

import sys
import urllib.request
from pathlib import Path

import numpy as np
from safetensors.numpy import save_file

URL = "https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz"


def archive():
    path = Path.home() / ".keras" / "datasets" / "mnist.npz"
    if not path.exists():
        path.parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(URL, path)
    return np.load(path)


def main(out_dir):
    data = archive()
    tensors = {}
    for split in ["train", "test"]:
        images = data[f"x_{split}"].reshape(-1, 784).astype(np.float32) / 255.0
        tensors[f"{split}.images"] = np.ascontiguousarray(images)
        tensors[f"{split}.labels"] = data[f"y_{split}"].astype(np.int32)
    save_file(tensors, out_dir / "mnist.safetensors")


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent)
