Agrisense-AI Grades Fruit. Its Best Feature Is Refusing To.
A solo-built produce grader for Indian farmers spends more code proving an image is a fruit than deciding how good it is. That inversion is the whole design.
- Agrisense-AI's most distinctive code is a rejection gate, not a classifier: it checks blankness, noise, and detector confidence before it will output a grade.
- The gate is built from four hand-tuned constants and two cheap pixel statistics, which makes it fast and explainable but brittle on the long tail.
- The same three-class grader ships through two paths, a persistent stdlib HTTP service and a per-request spawned CLI, and they disagree on checkpoint safety.
- The transferable pattern is to guard the input before you trust the model, and to fail loudly on anything the system was never built to handle.
Most fruit-grading demos end at the softmax. Upload a photo, read the label, done. Agrisense-AI, a solo-built web app for grading agricultural produce, does something stranger. Before it will tell you whether an apple is grade A or grade B, it spends its most deliberate code proving the image is even a fruit.
The inference core, ml_engine.py, opens with four constants that have nothing to do with quality. They describe what a plausible produce photo looks like and what it does not. An image that fails any one of them never reaches the grader. It is rejected outright.
That refusal is the design. The system is built to say no more often than it says A, B, or C. Most tutorials build a classifier and stop. This project builds a classifier and then builds a bouncer for it. The bouncer is the part worth reading.
Built for a phone, in Kolhapur
The audience is legible from the code. Users sign in with a phone number, stored under a unique rawPhone index, rather than an email address. The ML service accepts a district parameter that defaults to Kolhapur, a city in Maharashtra. The app carries pages for market prices and analysis history.
Read together, those choices point at smallholder farmers and small traders who want a fast, repeatable quality check without a trained inspector, and who may not have an email address to sign in with. The design follows the user rather than the other way around.
One piece of evidence discipline before we go further. The author's motivations are not documented anywhere I could find: no interview, no blog post, no statement of intent in the README. Everything below is intent read from structure, not from the author's own words. Treat it that way.
The four-number gate
detect_fruit in ml_engine.py computes two statistics on every image once it is resized to 224 by 224. The first is color_variation, the standard deviation of pixel values. The second is neighbor_difference, the mean absolute difference between adjacent pixels, a cheap gradient proxy. Both are single passes over the pixel array. Neither needs a model.
Those two numbers are compared against MIN_IMAGE_COLOR_VARIATION and MAX_IMAGE_NEIGHBOR_DIFFERENCE. Low variation means a flat, blank, or washed-out frame. High neighbor difference means noise, compression artifacts, or a screenshot of text. Either failure stops the image before the detector runs.
MIN_FRUIT_DETECTION_CONFIDENCE = 80.0
MIN_FRUIT_DETECTION_MARGIN = 20.0
MIN_IMAGE_COLOR_VARIATION = 8.0
MAX_IMAGE_NEIGHBOR_DIFFERENCE = 45.0
If the image survives the cheap checks, the fruit detector gets a turn. It has to clear two more bars: at least 80 percent confidence in its top class, and at least a 20-point lead over the runner-up. The margin requirement is the interesting one. A detector that is 85 percent sure of apple and 80 percent sure of tomato is not confident, it is confused. The margin gate catches that case.
The caveat matters. These are hand-tuned heuristics, not a learned out-of-distribution detector. They were tuned against whatever images the author tested. They are cheap, explainable, and need no training data. They will also fail on the long tail: a dark photo of a real fruit, a stylized food illustration, a fruit against a busy market backdrop.
The same philosophy appears in a smaller place. load_grade_model raises a ValueError for any commodity that is not apple, tomato, or dragon fruit. The system fails fast and loud on input it cannot handle instead of guessing.
| Property | Agrisense heuristic gate | Learned OOD detector |
|---|---|---|
| Training data needed | None | Labeled in-distribution and OOD samples |
| Cost per request | Two passes over a 224x224 array | A forward pass through an extra network |
| Explainability | Thresholds printed in the source | Opaque score, hard to debug |
| Tuning effort | Hand-tuned against test images | Retraining when the domain shifts |
| Failure mode | Brittle on the long tail | Misses novel classes it never saw |
| When to choose it | Small projects, explainability, no OOD data | Production systems with real distribution shift |
One model, two delivery paths
The same three-class EfficientNet-B0 graders ship two ways. The first is ml_server.py, a persistent microservice built on Python's standard http.server. It listens on port 8000, exposes a health endpoint and a grade endpoint, and returns JSON. The second is ml/predict.py, a command-line script that reads an image from stdin and prints JSON to stdout, designed to be launched per request through a child process from the Node backend.
The tradeoffs are concrete. The persistent service loads the model on every request in the current code, which re-reads a multi-megabyte checkpoint from disk each time. It is single-threaded, so concurrent grading requests serialize. It sets a wildcard CORS header and has no authentication, which is only safe if it is bound to localhost or shielded by the Express server in front of it. It also returns HTTP 400 for every exception, including internal failures that should be 500s.
The spawned CLI is hermetic: one process per call, no shared state, and parallel by default. It uses torch.load with weights_only=True, the safe setting that refuses arbitrary pickle deserialization. The persistent service uses weights_only=False. That is a real security asymmetry between two paths that grade the same model, and it is worth naming.
| Dimension | ml_server.py (persistent service) | ml/predict.py (spawned CLI) |
|---|---|---|
| Transport | HTTP POST to a long-lived process | Image on stdin, JSON on stdout |
| Threading model | Single-threaded, requests serialize | One process per call, parallel by default |
| Model loading | Per request in the current code | Per request, fresh process |
| Checkpoint safety | torch.load with weights_only=False | torch.load with weights_only=True |
| Auth | None on the ML endpoint | Inherits whatever the caller enforces |
| CORS | Wildcard Access-Control-Allow-Origin: * | Not applicable |
| Error semantics | HTTP 400 for every exception | Non-zero exit code and stderr |
| Best fit | Long-running local service behind a trusted proxy | Occasional calls, hermetic isolation |
| Failure under load | Requests queue behind the single thread | Process spawn overhead dominates |
Neither path is wrong. The service is the right shape for a long-running local backend behind a trusted proxy. The spawned CLI is right for occasional calls where isolation matters more than latency. What is notable is that both exist, and that they disagree on checkpoint safety.
The seams in the code
The project wears its seams openly. This is what solo, partly scaffolded shipping code looks like, and it is more useful to describe than to score.
- Three training scripts (
train.py,train_tomato.py,train_dragonfruit.py) are near-copies of one another, so a bug fix has to be made three times. - Four checkpoints ship with at least two metadata conventions. The apple and tomato models use bare integer class indices; the dragon fruit model reads a
class_to_idxmap and needs an extra translation layer. - The dragon fruit grader computes
MODEL_PATHrelative to the current working directory, so it breaks when run from anywhere else. - Training scripts hardcode the author's local paths, including Windows-style
D:drive locations, which makes them non-reproducible without edits. - The
ml_server.pydocstring advertises TensorFlow and OpenCV, but only PyTorch and Pillow are used. - Password hashing uses
scryptSync, which blocks the Node event loop for the duration of every hash. The asyncscryptcall is the correct choice in a server.
Some of this reads as AI-scaffolded. A metadata.json file and pyrefly: ignore comments in the inference core suggest the project was partly generated with an AI-assisted tool. That is an inference from the artifacts, not a claim about how the code was written. It is also, increasingly, what a one-person project looks like.
What to steal
The repo is small. It has no stars, one contributor, and no field validation. None of that changes the lesson, which is transferable to any vision or classification system fed by untrusted input.
Guard the gate before you trust the model. Prefer cheap, explainable checks first: a blankness test and a noise test cost almost nothing and catch whole categories of garbage before an expensive forward pass. Require a margin, not just a maximum, so a confused model is treated as confused. And fail loudly on inputs the system was never built to handle, whether that is a rock in the frame or a commodity the model does not know.
You do not need a learned OOD detector to get most of the benefit. You need to decide, in advance, what your system should refuse, and then write the refusal down.





