Skip to content

Embeddings of a single notes directory

Working with a growing collection of markdown notes locally, I needed fast semantic sorting without moving data to the cloud. The solution: local embedding generation via sentence-transformers and FAISS-based search, everything staying on disk under full control.

Why need embeddings

In a notes folder, finding a file by keywords in title or body can be hard. An embedding (vector representation of text) lets compare file contents as points in multi-dimensional space. Practically, this enables searching similar notes, grouping topics, and building a simple personal index. No external services, all computation on the DevOps machine.

Tools and local run

Main stack: Python, sentence-transformers for embeddings, faiss-cpu for approximate nearest neighbor search. Install with one command:

pip install sentence-transformers faiss-cpu

Model choice depends on languages/topics in notes. all-MiniLM-L6-v2 suits most text corpora, supports RU and EN. For domain-specific precision, swap model from Hugging Face repo, keeping compatibility with library input format.

Tip

After installation can quickly verify with one command:

python -c "from sentence_transformers import SentenceTransformer; m = SentenceTransformer('all-MiniLM-L6-v2'); print(m.encode(['тестовый текст']).shape)"

Notes directory structure

Typical structure: root notes/ folder, .md files, possibly subfolders by years or projects. Paths must be stable, script walks them recursively.

notes/
├── 2024/
│   ├── devops/
│   └── python/
├── personal/
└── drafts/

Script scans only .md files, ignores _drafts or .git to avoid service data.

Vector generation script

Minimal script gen_embeddings.py walks directory, reads each markdown, forms embedding, saves to .npy alongside source. Allows not storing heavy matrix in memory, update indexes per file.

#!/usr/bin/env python3
import os, sys, argparse
from sentence_transformers import SentenceTransformer
import numpy as np

def main():
    parser = argparse.ArgumentParser(description="Generate embeddings for a notes directory")
    parser.add_argument("root", help="Path to notes root directory")
    parser.add_argument("--model", default="all-MiniLM-L6-v2", help="SentenceTransformer model name")
    parser.add_argument("--skip-git", action="store_true", help="Skip .git directories")
    args = parser.parse_args()

    model = SentenceTransformer(args.model)
    root = os.path.abspath(args.root)
    skipped = 0

    for dirpath, dirnames, filenames in os.walk(root):
        if args.skip_git and '.git' in dirnames:
            dirnames.clear()
            skipped += 1
            continue
        for fname in filenames:
            if not fname.endswith('.md'):
                continue
            fpath = os.path.join(dirpath, fname)
            try:
                with open(fpath, encoding='utf-8') as f:
                    text = f.read()
                emb = model.encode(text, convert_to_numpy=True)
                out_path = fpath.replace('.md', '.npy')
                np.save(out_path, emb)
            except Exception as e:
                print(f"WARN: skip {fpath}: {e}", file=sys.stderr)

    print(f"Done. Skipped {skipped} git dirs." if skipped else "Done.")

if __name__ == "__main__":
    main()

Run one-liner:

python3 gen_embeddings.py notes/

After execution, .npy files appear alongside each .md, size (384,) for chosen model, ready for search.

Search and use results

Search built on FAISS. Example search.py accepts query and returns paths to three most similar notes:

#!/usr/bin/env python3
import os, sys, numpy as np
from sentence_transformers import SentenceTransformer
import faiss

def main():
    if len(sys.argv) < 3:
        print("Usage: search.py <query> <notes_root>")
        sys.exit(1)
    query = sys.argv[1]
    root = sys.argv[2]
    model = SentenceTransformer("all-MiniLM-L6-v2")
    k = 3

    vectors, paths = [], []
    for dirpath, _, filenames in os.walk(root):
        for fname in filenames:
            if not fname.endswith('.npy'):
                continue
            fpath = os.path.join(dirpath, fname)
            try:
                vec = np.load(fpath)
                vectors.append(vec)
                paths.append(fpath.replace('.npy', '.md'))
            except:
                continue

    if not vectors:
        print("No embeddings found. Run gen_embeddings.py first.")
        sys.exit(0)

    xb = np.vstack(vectors)
    index = faiss.IndexFlatIP(xb.shape[1])  # inner product (cosine at normalization)
    index.add(xb)

    q = model.encode([query], convert_to_numpy=True)
    q = faiss.normalize_L2(q)
    D, I = index.search(q, k)

    for idx in I[0]:
        print(f"-> {paths[idx]} (score: {D[0][list(I[0]).index(idx)]:.4f})")

if __name__ == "__main__":
    main()

Usage:

python3 search.py "docker compose restart" notes/

Output shows files and similarity score. All data stays on disk, queries don’t leave machine.

Warning

With large file counts (>10 000) IndexFlatIP may consume significant RAM. For production directories, switch to faiss.IndexIVFFlat with prior training, requiring split into training and search sets.

Security and data privacy

Main plus local approach: data never leaves environment. Embeddings are mathematical text representations, files remain untouched. If notes contain confidential data, consider: using own model trained on local data, or filtering paths excluding confidential or secrets directories. Storing .npy alongside markdown doesn’t increase leak risk, as they’re not readable without corresponding script.

Automation of updates

To keep index fresh after each note edit, set up simple cron job or git hook. Example update_embeddings.sh:

#!/usr/bin/env bash
cd "$HOME/notes"
python3 gen_embeddings.py . --skip-git

Add to crontab (daily run at 03:00):

0 3 * * * /home/user/bin/update_embeddings.sh >> /home/user/log/emb_update.log 2>&1

Can also use git hooks: post-commit in notes repo will regenerate embeddings for changed file, but full recalculation is simpler and more reliable for small folders.

Conclusion and ideas for next steps

Local embeddings for single notes directory give fast semantic access without external service dependencies. Configured generation script and FAISS search work within minutes after library install. Possible next steps:

  • Integrate with vim/neovim via plugin for searching similar notes directly from editor.
  • Replace IndexFlatIP with quantized index IndexIVFPQ to save RAM with thousands of files.
  • Add metadata (tags, author, date) into vector alongside text for more precise filtering.
  • Export index to format understandable by other tools (e.g., json with coordinates for later t-SNE/UMAP visualization).

Archive of scripts and example configs posted to personal repo for quick replication on other machines.