Metadata-Version: 2.3
Name: esp32kb
Version: 0.2.0
Summary: Build an on-device knowledge base (text chunks + INT8 MiniLM embeddings) and scaffold a ready-to-flash sketch for the ESP32-P4 vector-search demo.
Keywords: esp32,esp32-p4,embeddings,vector-search,tinyml,onnx,minilm
Author: Simone Salerno
Author-email: Simone Salerno <info@salernosimone.com>
License: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Embedded Systems
Requires-Dist: numpy
Requires-Dist: onnxruntime
Requires-Dist: questionary>=2.1.1
Requires-Dist: transformers
Requires-Dist: typer
Requires-Python: >=3.10
Project-URL: Homepage, https://github.com/salernosimone/python-esp32kb
Project-URL: Repository, https://github.com/salernosimone/python-esp32kb
Project-URL: Issues, https://github.com/salernosimone/python-esp32kb/issues
Description-Content-Type: text/markdown

# esp32kb

Build an on-device knowledge base for the KB ESP32-P4 demo — a MiniLM-L3
embedding search that runs entirely on the board, with no PC attached at
runtime.

Point the tool at a folder of markdown/text documents and it produces a
ready-to-flash Arduino sketch: sentence-aware chunks, INT8 embeddings, the
packed `kb.img` container (vectors + text + file index + WordPiece vocabulary),
`VectorSearch.h` with the model geometry baked in, a demo `.ino` when the
folder has none, the partition table and a `flash.sh` that compiles and flashes
everything.

## Install

```sh
uvx esp32kb --help            # or: pip install esp32kb
# from a checkout:
uv run --project esp32kb esp32kb --help
```

## Usage

```sh
# documents -> kb.img + a ready-to-flash sketch
esp32kb embed --root path/to/documents --sketch-dir path/to/Arduino/project
```

`embed` is the only command: it embeds the documents, packs `kb.img`, scaffolds
the sketch and then asks whether to run the generated `flash.sh`. Pass `--yes`
to skip the confirmation, or `--no-flash` to only prepare the folder.

Flashing needs `arduino-cli` on `PATH`; scaffolding works without it.

Everything defaults relative to `--sketch-dir` (the current folder by default),
so the bundled MiniLM-L3 model is enough. Existing `.ino`, `.espdl` and
`partitions.csv` files are never overwritten; `VectorSearch.h` and `flash.sh`
are generated/refreshed on every run.

Running `esp32kb embed` with no flags prints the full option list plus
copy-paste examples:

```sh
esp32kb embed --root ~/papers --sketch-dir ~/Arduino/KB
esp32kb embed --root ~/papers --onnx ./model/maskseq.onnx --sketch-dir ~/Arduino/KB
```

### `esp32kb embed` flags

| flag | default | meaning |
|------|---------|---------|
| `--root` / `-r` | required | folder with the documents to index (recursively) |
| `--output-folder` / `-o` | `<sketch-dir>/model/kb` | where the `.bin` files and `kb.img` are written |
| `--sketch-dir` / `-s` | current folder | folder to scaffold with the header, `.ino`, partition table, model and `flash.sh` |
| `--onnx` | `<sketch-dir>/model/maskseq.onnx` if present, else bundled | float32 MiniLM-L3 the PC embeds with |
| `--port` / `-p` | `$PORT`, else selector of detected ports | serial port used when flashing |
| `--fqbn` | `$FQBN`, else selector of ESP32-P4 boards | arduino-cli board spec used when flashing |
| `--yes` / `-y` | off | skip the flash confirmation |
| `--no-flash` | off | scaffold only, never ask to flash |

### What `embed` writes

| path | contents |
|------|----------|
| `<output>/vectors.bin` | 32 B header + N × dim INT8 (16-byte aligned rows) |
| `<output>/meta.bin` | 16 B header + N × 16 B records (file id, text offset/length) |
| `<output>/chunks.bin` | 16 B header + concatenated UTF-8 chunk text |
| `<output>/files.bin` | 16 B header + N × padded filename records |
| `<output>/vocab.txt` | WordPiece vocabulary, one token per line |
| `<output>/kb.img` | container: magic/version/section table + the payloads above |
| `<sketch>/VectorSearch.h` | the whole library, with `KB_SEQ`/`KB_DIM`/`KB_TOPK` and the container magics baked in (no config header) |
| `<sketch>/<folder>.ino` | working demo sketch, written only when the folder has no `.ino` |
| `<sketch>/partitions.csv` | 32 MB flash layout, written only when missing |
| `<sketch>/model/minilm_l3.espdl` | INT8 model the firmware loads, copied from the bundle only when missing |
| `<sketch>/flash.sh` | compiles the sketch and flashes app + model + `kb.img` in one upload |

`kb_config.h` and `kb_queries.h` written by older esp32kb versions are removed
when scaffolding, since the configuration now lives in `VectorSearch.h`.

`flash.sh` honours `PORT`, `FQBN` and `ARDUINO_LIBS`. When flashing
interactively (after answering `y`, or with `--yes`) and `PORT`/`FQBN` are not
configured, `esp32kb` shows selector menus: ports parsed from
`arduino-cli board list`, and ESP32-P4 boards from `arduino-cli board listall`.
Set `PORT`/`FQBN` yourself (flag or environment) to skip them. Running the
script directly probes `arduino-cli board list` and prompts only for what it
cannot find.

You can still override the target from the shell:

```sh
PORT=/dev/ttyACM0 ./flash.sh
```

The sequence length and embedding width are read straight from the ONNX model,
so the chunks, the INT8 vectors **and** the scaffolded `VectorSearch.h` can
never disagree with the model. Change the sequence length in one place — the
`SEQ=…` you export the ONNX with — and re-run `esp32kb embed`.

## Pipeline

```
documents
  -> chunks (<= seq-2 WordPiece tokens each)
  -> MiniLM-L3 embeddings (masked mean pool, L2 normalized)
  -> symmetric INT8 quantization, one global scale
  -> vectors.bin / meta.bin / chunks.bin / files.bin / vocab.txt
  -> kb.img          single little-endian container with a section table
  -> VectorSearch.h  KB_SEQ / KB_DIM / KB_TOPK + container magics (C++ constants)
```

The vocabulary travels inside `kb.img`, so the device tokenizes queries itself.

## Additive attention mask

If the ONNX model exposes a second `attention_mask` input (the variant built
by `model/export_onnx_mask.py`), `esp32kb` feeds it the correct per-query
padding bias (0 on real tokens, negative on `[PAD]`). This preserves retrieval
quality at longer sequence lengths, where the frozen all-ones mask used by the
plain export otherwise collapses query embeddings. With the stock single-input
ONNX the behavior is unchanged.
