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.

8 min read • View on GitHub • More from yashsankpal2727

A wide editorial illustration of a produce sorting table under a single hanging lamp. A conveyor carries fruit toward a tall, narrow inspection gate built from vertical measuring rods, where a small mechanical arm holds a loupe over each item. Most fruit passes through cleanly, but three impostors are stopped and stacked on the left: a smooth grey stone, a curled printed page representing a screenshot, and a blurred smear with no edges. The scene literalizes the article's thesis that Agrisense-AI's most important job is rejecting inputs before it grades them.
The gate is the product. Before Agrisense-AI grades a fruit, it decides whether the image is a fruit at all.
Key Takeaways

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 layered rejection pipeline: cheap pixel statistics first, then detector confidence and margin. A tile that fails any gate short-circuits to the rejected rail.

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.

PropertyAgrisense heuristic gateLearned OOD detector
Training data neededNoneLabeled in-distribution and OOD samples
Cost per requestTwo passes over a 224x224 arrayA forward pass through an extra network
ExplainabilityThresholds printed in the sourceOpaque score, hard to debug
Tuning effortHand-tuned against test imagesRetraining when the domain shifts
Failure modeBrittle on the long tailMisses novel classes it never saw
When to choose itSmall projects, explainability, no OOD dataProduction systems with real distribution shift

One model, two delivery paths

An extreme close-up editorial illustration of a loupe held over a coarse pixel grid of roughly eight by eight visible cells. Fine calipers grip two adjacent cells, and a thin measurement line arcs from one cell's center to the next, with a small tally mark in the margin recording the jump. In one corner of the grid a few cells are pure white, representing a blank patch, and a few are dense crosshatch, representing noise. The image teaches how color_variation and neighbor_difference are computed as physical measurements over a small pixel array.
Two cheap statistics, measured directly on the pixels: how much the values vary, and how far each pixel sits from its neighbor.

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.

Dimensionml_server.py (persistent service)ml/predict.py (spawned CLI)
TransportHTTP POST to a long-lived processImage on stdin, JSON on stdout
Threading modelSingle-threaded, requests serializeOne process per call, parallel by default
Model loadingPer request in the current codePer request, fresh process
Checkpoint safetytorch.load with weights_only=Falsetorch.load with weights_only=True
AuthNone on the ML endpointInherits whatever the caller enforces
CORSWildcard Access-Control-Allow-Origin: *Not applicable
Error semanticsHTTP 400 for every exceptionNon-zero exit code and stderr
Best fitLong-running local service behind a trusted proxyOccasional calls, hermetic isolation
Failure under loadRequests queue behind the single threadProcess 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.

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.