Skip to main content
Glama

clarity-engine

CI Python 3.11 to 3.14 MIT licence

Website: mqfarooqi1.github.io/clarity-engine

A weekend project on a problem I keep running into at work: you're handed a pile of text with labels, and a good chunk of the labels are wrong. Before you train anything, it's worth trying to clean them up. This repo is me working through a few approaches end to end and seeing how far each one actually gets.

Everything here runs on a synthetic dataset I generate in-process, so the numbers below are best read as "this is the shape of the effect," not as production benchmarks. Real label noise is rarely as well-behaved as the uniform random corruption I inject here.

What's in here

Script

What it does

Needs an API key?

clarity_engine.py

k-NN label correction, then trains a classifier on the cleaned labels

no

distill_demo.py

toy knowledge-distillation: big model labels data, tiny model imitates it

no

conformal_demo.py

conformal prediction — returns label sets with a coverage guarantee

no

llm_denoise.py

uses an LLM (Claude) to relabel only the genuinely ambiguous cases

yes

embeddings.py

the sentence-embedding model all of them use

no

ADVANCED.md

notes on how these pieces fit together and what I'd do at scale

—

Related MCP server: Duplicate supplier invoice check MCP server

The setup

The generator makes 930 short "customer messages" across 5 intents (billing, technical, shipping, cancellation, praise) and adds the kind of mess real text has: typos, lowercasing, padding, and some genuinely vague one-word messages. Then it simulates sloppy annotation: it picks rows at a 45% rate and gives each a label drawn at random from all five intents. One in five of those draws lands back on the true label, so 41.8% of the labels end up wrong (389 of 930). I score classifier predictions against clean test labels.

An earlier version of this README said about 45% of labels were corrupted, and the script printed 51% — the share of rows picked, which with this seed happened to be 50.5%. It also measured recovery against those picked rows, which credited the cleaning with "fixing" labels that were never wrong. Everything below counts the labels that actually are.

The core idea is unremarkable and that's fine: a single label is noisy, but meaning is more stable. Two messages about double-charges land near each other in embedding space even if one is mislabelled, so you can use a message's neighbours to second-guess its label.

Label cleaning: similarity-weighted k-NN voting

clarity_engine.py embeds every message with all-MiniLM-L6-v2, finds each message's 15 nearest neighbours by cosine similarity, and lets them vote on the label (weighted by similarity). This is basically label propagation / a soft k-NN smoother — nothing novel, but it's easy to inspect and it works because random noise scatters across classes while the true class stays the plurality.

One thing about this dataset shapes how to read the results: it repeats many messages word for word (336 distinct in 930), so many neighbours are exactly tied, and rounding decides which of them get picked. Two embedding libraries that agree to six decimal places can land on different sides of those ties. So the numbers below are the median and range over 30 runs, each with the embeddings nudged by one part in a million — far too little to change any meaning, but enough to re-roll the ties. python clarity_engine.py --stability reproduces them. Even the medians move a little from machine to machine — by up to about a point across the processors CI runs on, because ONNX Runtime picks different low-level routines on different CPUs and the last bits decide ties. The tables are from one Windows machine; the conclusions below hold on all of them.

What happens to the labels:

Median

Range over 30 runs

wrong labels put right

85.6%

83.0 – 87.1%

right labels made wrong

7.7%

6.8 – 9.1%

label accuracy, from 58.2% to

89.5%

87.6 – 90.2%

The original experiment splits by row and cleans the whole pool before training. Noisy test labels can therefore influence the corrected training labels, and exact message strings can occur on both sides of the split. The following scores describe that transductive setup.

Trained on

Median

Range over 30 runs

the raw noisy labels

84.1%

83.7 – 84.1%

consensus-corrected labels

91.4%

90.1 – 92.3%

corrected + dropping low-confidence rows

91.2%

85.8 – 93.6%

What that says:

  • Cleaning works. The corrected labels beat the raw ones in all 30 runs, by about 7 points, without ever seeing ground truth.

  • It has a cost. It turns about 8% of the labels that were right into wrong ones. Net, label accuracy goes from 58% to about 89%.

  • The confidence gate does not reliably help. It beats plain correction in half the runs or fewer — between 8 and 15 of the 30, depending on the machine — and swings by seven or eight points. The reason is in the figure below: roughly a hundred rows (68 to 126 on the machines tested so far) sit within 0.005 of its 0.6 cut-off — 9 of 15 neighbours agreeing is exactly 0.6 — so rounding decides whether they are kept. An earlier version of this README reported the gate as the best result (about 93%), from a run that landed near the top of that range.

  • Logistic regression on these embeddings is already fairly noise-robust, so the raw baseline is higher than you'd expect, and the gain would look different under non-random (systematic) noise.

The figures come from a single run:

problem denoising results

Evaluation on unseen message strings

Run python clarity_engine.py --grouped-holdout for a separate classifier comparison. It keeps all copies of an exact message string in one fold and cleans only the training fold's noisy labels. One Windows run with Python 3.14.10, scikit-learn 1.9.1, fastembed 0.9.1, and ONNX Runtime 1.32.0 used 698 training rows and 232 test rows. The raw, corrected, and gated models scored 78.0%, 84.1%, and 85.3%, respectively. The gate retained 37% of training rows. All three classifiers use the same fixed test fold, and variants of a synthetic message template can still occur on both sides. Small numerical differences can change which rows clear the confidence gate.

On the model choice

Two things mattered more than the classifier itself:

  1. The embedding does the heavy lifting. A frozen sentence-transformer + a plain logistic-regression head gets you most of the way; swapping the head for an SVM or small MLP barely moves it.

  2. Fixing the labels was a bigger lever than changing the model. Same classifier, cleaner labels, about 7 points.

The other three scripts (smaller experiments)

These are short demos of standard techniques, included because the "clean the labels, then decide what to train" story naturally leads into them. None of them is doing anything novel.

distill_demo.py — knowledge distillation. A larger model (full 384-d embeddings) acts as a teacher and labels data with soft probabilities; a tiny linear student (8-d input, 45 params) trains to imitate it. The student gets within about 3 points of the teacher (91% against 94%) at 1/42 of the size. The textbook claim that soft labels beat hard labels did not hold up here. An earlier version seemed to show it — by 0.4 points on one split, which is one test message, with the two students starting from different random weights. Compared fairly, each pair from the same start, over 30 splits, soft labels came out 0.5 points worse on average (95% CI −0.84 to −0.14) and won only 8 of the 30. The script prints that comparison.

distillation

conformal_demo.py — conformal prediction. Instead of one label, it returns a set with a coverage guarantee: the true label lands in the set at least, say, 90% of the time. Confident messages get a single label; the genuinely vague ones ("ok", "?") expand to several — which is the honest answer. I used randomised APS, since plain APS over-covered badly and produced bloated sets on this data.

The interesting part is a detail of the method. Randomised APS can only hit its target by sometimes returning an empty set, which is a strange thing to hand a person, so a practical version always keeps the top class. The guarantee still holds, but coverage can then never fall below the classifier's own top-1 accuracy — 95% here. The script runs both, averaged over 200 random draws:

Target

Never-empty sets

Textbook sets

Empty sets (textbook)

80%

98.0%

81.2%

16.8%

90%

98.6%

90.3%

8.3%

95%

99.3%

95.9%

3.5%

So never-empty sets over-cover heavily at low targets — not because accuracy lets small sets cover well, but because they are not allowed to be empty.

conformal

llm_denoise.py — LLM relabelling. For the cases k-NN voting can't resolve, this sends the message (plus its noisy neighbours as context) to Claude and asks for a label with a confidence and an explicit "uncertain" option, using structured outputs so the result is always one of the known classes. The point isn't to relabel everything with an LLM — that's slow and expensive — but to spend it only on the residual the cheap method leaves behind. It runs Claude Opus 5.5 with room for its thinking (16,000 tokens; an earlier limit of 2,000 could be used up before the label was written), and raises DenoiseError if the model declines or is cut off, rather than quietly returning nothing. It needs Anthropic credentials — ANTHROPIC_API_KEY, or a profile from ant auth login; without them it prints what it would do.

Running it

Python 3.11 to 3.14. Python 3.15 is waiting on ONNX Runtime; see Future scope.

pip install -r requirements.txt

python clarity_engine.py               # label cleaning + training, writes figures to visuals/
python clarity_engine.py --stability   # the medians and ranges above (a few seconds)
python clarity_engine.py --grouped-holdout  # clean train labels and test on unseen exact strings
python distill_demo.py                 # teacher -> student distillation
python conformal_demo.py               # conformal prediction sets

# optional, needs credentials:
export ANTHROPIC_API_KEY=...        # PowerShell: $env:ANTHROPIC_API_KEY="..."
python llm_denoise.py

The first run downloads the all-MiniLM-L6-v2 embedding model (about 90 MB, once), then everything is offline except the LLM script. It runs through fastembed on ONNX Runtime, so there is no PyTorch to install; the vectors match sentence-transformers' to six decimal places, which is where the tie-breaking above comes from.

Audit a labelled CSV

Use label_audit.py to flag inconsistent labels in a UTF-8 CSV with text and label columns. For the offline audit, install scikit-learn if needed.

python -m pip install 'scikit-learn>=1.4,<2'
python label_audit.py tickets.csv --output audit.json

The JSON report lists exact-text label conflicts first, then suggested labels ranked by weighted neighbour vote share. Each suggestion shows up to three supporting texts and their record numbers. Record 1 is the first data record after the header. Repeated copies of the same text cast one vote, and conflicting texts are excluded from the neighbour vote. Suggestions require support from at least two distinct texts. Vote share measures agreement among those neighbours.

The default character TF-IDF audit works without an API key or model download. Use --embedding minilm with the project requirements installed to use the same local embedding model as the experiments above. The first MiniLM run may download model files. The audit leaves the source CSV untouched and requires a new output path.

The BANKING77 pilot shows what the default audit caught on 3,080 public examples after deliberately changing 308 labels. It includes the first 20 findings, their evidence, and instructions for reproducing the test.

Use the audit in Codex

Clarity Engine exposes one read-only MCP tool, audit_csv_labels. From a checkout of this repo, install it in a Python environment, then register that Python interpreter with Codex. The setup below uses the included synthetic CSV.

python -m pip install .
codex mcp add clarity-engine -- python -m clarity_engine_mcp --data-dir "/absolute/path/to/clarity-engine/examples"

Use the absolute path to your environment's Python if Codex launches with a different PATH. On Windows, for example, use "C:\path\to\venv\Scripts\python.exe" as the command and "C:\path\to\clarity-engine\examples" as the data directory. In a new Codex chat, ask Clarity Engine to audit support-labels.csv and show the record numbers and evidence for the first five findings.

The tool accepts a relative .csv path inside the configured directory, up to 2 MiB and 5,000 records. Summary counts cover the full file, and max_findings controls the preview size from 1 to 25. Processing is local and uses TF-IDF. Findings include text excerpts and labels that the MCP client receives. Point the server at a folder containing only CSVs you intend to make available to that client. Use the CLI for an untruncated JSON report.

The Docker image starts the same stdio tool with only the synthetic example inside its data directory. This gives listing reviewers a sample to try.

Tests

pip install -r requirements-dev.txt
pytest                      # everything
pytest -m "not model"       # skip the ones that load the embedding model

The tests marked model re-run every number on this page with the real model — the stability table, the distillation comparison, both conformal rules — and CI runs them on Linux, Windows and macOS. The LLM script's tests drive the real Anthropic SDK against scripted responses, so they check the request it sends and its handling of refusals and truncated answers without a key or any cost.

Future scope

  • Real noise. Use a real labelled sample as ground truth instead of uniform random corruption. Real mistakes cluster in particular classes and in hard examples, and the evaluation is only as honest as its noise model.

  • Fix the gate's ties. Many messages repeat word for word, and identical copies all vote with weight 1.0. So when a message's 15 neighbours are all copies of it and 9 of them carry the same label, its vote share is exactly 0.6, which is the gate's cut-off. Voting once per distinct message, or a cut-off between the steps such votes move in (0.63 sits between 9/15 and 10/15), should stop rounding from deciding which rows are kept. The gate could then be judged on its merits, with a cut-off chosen on held-out data rather than by hand.

  • A second opinion. Cross-check the k-NN cleaning against confident learning (cleanlab): trust the rows where both agree, and send the disagreements to review or to the LLM.

  • Calibration. Measure expected calibration error, not just accuracy, before trusting any confidence score.

  • Scale. Swap exact k-NN for an approximate index (FAISS, hnswlib) past about 100,000 rows.

  • Python 3.15. Add it to CI once ONNX Runtime, which the embedding model runs on, publishes wheels for it. As of November 2026 it hasn't.

Whatever gets added, report a spread rather than a single run: ties and thresholds moved the gate's result by several points here.

See ADVANCED.md for the longer version of these notes.


Muhammad Farooqi · https://github.com/mqfarooqi1

Available Tools

1 tool
audit_csv_labelsA
Read-onlyIdempotent

Flag conflicting and likely incorrect labels in one text-and-label CSV.

Returns counts, observed labels, supporting text excerpts and weighted neighbour votes. Exact-text conflicts come first. Suggestions require human review. The input limit is 2 MiB and 5,000 records. Processing uses local character TF-IDF.

Inputs: path (required), max_findings. Returns: findings, embedding, neighbors, input_records, +6 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 1 tool

    Disambiguation5/5

    There is only one tool, so there is no possibility of selecting the wrong one. Its purpose (flagging conflicting/incorrect CSV labels) is stated clearly and unambiguously.

    Naming Consistency4/5

    The single name audit_csv_labels follows a clear verb_noun_resource snake_case pattern. With only one tool there is no cross-tool consistency to verify, but the convention itself is clean and predictable.

    Tool Count2/5

    A one-tool server is very thin for a 'Clarity Engine'; there is no companion operation such as applying suggested fixes, exporting a report, or re-running on a subset. It sits at the low end of the appropriate-count range.

    Completeness3/5

    The audit tool is self-contained (returns counts, labels, excerpts, neighbour votes), but the lifecycle dead-ends: there is no way to accept/apply suggested corrections or fetch a single record's detail. Notable gaps remain for a labelling workflow.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      Enables users to review a supplied batch of supplier invoices or vendor bills for repeated references, normalized reference variations, and identical amount-and-date candidates, returning grouped evidence and exact review reasons from local history. Supports saved reports, CSV export, and use with MCP clients such as Claude Desktop, Claude Code, and Cursor.
      8
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables agents to find duplicate customers and contacts in CSV files by comparing emails, phone numbers, names, and companies, returning confidence levels and the evidence behind each match. It also inspects CSV files to reveal detected columns and row counts without exposing row contents.
      57 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables inspection of a trade business's CSV/TSV exports to surface work and materials that were never invoiced, listing each finding with amount, reason, and source location, separated into proven and to-be-verified. All amounts are computed deterministically in exact cent arithmetic, so the model only maps columns and spellings.
      MIT