Spaces:
Running
Running
File size: 8,919 Bytes
734cef3 836740a e82d8dc 836740a 734cef3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LeafScan</title>
<style>
:root {
--bg: #f7f8f6; --card: #ffffff; --ink: #1f2328; --muted: #59636e; --line: #e3e6e1;
--accent: #2f7d4f; --accent-soft: #e4f1e8; --warn: #9a5b00; --warn-soft: #fbf0dc;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #111412; --card: #1a1f1c; --ink: #e8ece9; --muted: #9aa49d; --line: #2c332e;
--accent: #6cc28e; --accent-soft: #1f3327; --warn: #f0b860; --warn-soft: #3a2e17; }
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink);
font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 860px; margin: 0 auto; padding: 32px 16px 48px; }
h1 { font-size: 1.6rem; margin: 0 0 4px; }
.sub { color: var(--muted); margin: 0 0 24px; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
@media (max-width: 680px) { .grid { grid-template-columns: 1fr; } }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }
label.drop { display: flex; flex-direction: column; align-items: center; justify-content: center;
min-height: 260px; border: 2px dashed var(--line); border-radius: 10px; cursor: pointer;
color: var(--muted); text-align: center; padding: 12px; overflow: hidden; }
label.drop:hover { border-color: var(--accent); }
label.drop img { max-width: 100%; max-height: 320px; border-radius: 8px; }
input[type=file] { display: none; }
.verdict { font-size: 1.15rem; margin: 0 0 12px; min-height: 1.5em; }
.verdict.unsure { background: var(--warn-soft); color: var(--warn); padding: 10px 12px; border-radius: 8px; font-size: 1rem; }
.bar { margin: 10px 0; }
.bar .name { display: flex; justify-content: space-between; font-size: .92rem; }
.bar .track { height: 8px; background: var(--accent-soft); border-radius: 4px; margin-top: 4px; }
.bar .fill { height: 8px; background: var(--accent); border-radius: 4px; width: 0; transition: width .3s; }
.status { color: var(--muted); font-size: .9rem; }
.about { margin-top: 24px; color: var(--muted); font-size: .92rem; }
.about strong { color: var(--ink); }
a { color: var(--accent); }
</style>
</head>
<body>
<main>
<h1>🌿 LeafScan</h1>
<p class="sub">Plant disease from a leaf photo — runs entirely in your browser, nothing is uploaded.</p>
<div class="grid">
<div class="card">
<label class="drop" id="drop">
<span id="dropText">Click or drop a leaf photo here</span>
<input type="file" id="file" accept="image/*">
</label>
</div>
<div class="card">
<p class="verdict" id="verdict"></p>
<div id="bars"></div>
<p class="status" id="status">Loading the model (≈ 32 MB, once)…</p>
</div>
</div>
<div class="about">
<p><strong>What this is.</strong> A ConvNeXt-T trained on lab photos (PlantVillage), then
fine-tuned on web and field photos (PlantDoc), for <strong>38 crop / disease classes</strong>
of 14 crops. This page runs an int8-quantised copy of the model with ONNX Runtime Web.</p>
<p><strong>How much to trust it.</strong> On held-out field photos it is right about
<strong>72%</strong> of the time. Below a confidence threshold fitted on field photos it says
"Not sure": it answers about two thirds of field photos, and about <strong>85%</strong> of those
answers are right. It only knows these 38 classes and is <strong>not</strong> a substitute for
an agronomist.</p>
<p><strong>Beyond this page.</strong> The full project adds an assistant that answers your
questions about the diagnosed disease from 28 Wikipedia articles, with a local language model
that cites its sources, says "I don't know" when they do not answer, and flags sentences its
sources do not support. Its models are about 10 GB, so it runs on your own computer
(instructions in the repository).</p>
<p>Code, experiments and limitations:
<a href="https://github.com/marconcini/leafscan">github.com/marconcini/leafscan</a> ·
model: <a href="https://huggingface.co/Marconcini/leafscan-convnext-tiny">Marconcini/leafscan-convnext-tiny</a></p>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/ort.min.js"></script>
<script>
// Model files: the Hugging Face model repo by default, or ?base=<url> (local testing).
const BASE = new URLSearchParams(location.search).get("base")
|| "https://huggingface.co/Marconcini/leafscan-convnext-tiny/resolve/main/";
const MEAN = [0.485, 0.456, 0.406], STD = [0.229, 0.224, 0.225];
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/";
let session, config;
const $ = (id) => document.getElementById(id);
function prettyLabel(label) { // same as leafscan.data.pretty_label
const [crop, disease] = label.split("___");
return `${crop.replaceAll("_", " ").replaceAll(",", "").trim()} — ${disease.replaceAll("_", " ").trim()}`;
}
// Same geometry as the evaluation transform: shorter side -> round(1.14 * size), centre crop.
function preprocess(img, size) {
const short = Math.floor(size * 1.14);
const scale = short / Math.min(img.naturalWidth, img.naturalHeight);
const w = Math.round(img.naturalWidth * scale), h = Math.round(img.naturalHeight * scale);
const canvas = document.createElement("canvas");
canvas.width = size; canvas.height = size;
const ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high";
ctx.drawImage(img, -Math.round((w - size) / 2), -Math.round((h - size) / 2), w, h);
const px = ctx.getImageData(0, 0, size, size).data;
const data = new Float32Array(3 * size * size);
for (let i = 0; i < size * size; i++)
for (let c = 0; c < 3; c++)
data[c * size * size + i] = (px[4 * i + c] / 255 - MEAN[c]) / STD[c];
return new ort.Tensor("float32", data, [1, 3, size, size]);
}
async function predict(img) {
const { file, temperature, threshold } = config.onnx_int8;
const out = await session.run({ image: preprocess(img, config.img_size) });
const logits = Array.from(out.logits.data).map((z) => z / temperature);
const m = Math.max(...logits);
const exps = logits.map((z) => Math.exp(z - m));
const sum = exps.reduce((a, b) => a + b, 0);
const probs = exps.map((e) => e / sum);
const top = probs.map((p, i) => [config.classes[i], p]).sort((a, b) => b[1] - a[1]).slice(0, 3);
return { top, confident: top[0][1] >= threshold, threshold };
}
function show(pred) {
const [name, p] = pred.top[0];
const v = $("verdict");
if (pred.confident) {
v.className = "verdict";
v.innerHTML = `<strong>${prettyLabel(name)}</strong> (confidence ${Math.round(100 * p)}%)`;
} else {
v.className = "verdict unsure";
v.innerHTML = `<strong>Not sure.</strong> Best guess: ${prettyLabel(name)} (${Math.round(100 * p)}%),
below the ${Math.round(100 * pred.threshold)}% confidence needed to answer.
Try a closer photo of a single leaf, or ask an expert.`;
}
$("bars").innerHTML = pred.top.map(([c, q]) => `
<div class="bar"><div class="name"><span>${prettyLabel(c)}</span><span>${Math.round(100 * q)}%</span></div>
<div class="track"><div class="fill" style="width:${(100 * q).toFixed(1)}%"></div></div></div>`).join("");
}
async function handleFile(file) {
if (!file || !session) return;
const img = new Image();
img.src = URL.createObjectURL(file);
await img.decode();
$("dropText").replaceWith(Object.assign(img, { id: "dropText" }));
$("status").textContent = "Thinking…";
const t0 = performance.now();
show(await predict(img));
$("status").textContent = `Done in ${Math.round(performance.now() - t0)} ms, on your device.`;
}
// Test hook: predict from an image URL (used to compare with the Python implementation).
window.leafscanPredictUrl = async (url) => {
const img = new Image(); img.crossOrigin = "anonymous"; img.src = url; await img.decode();
return predict(img);
};
(async () => {
try {
config = await (await fetch(BASE + "config.json")).json();
session = await ort.InferenceSession.create(BASE + config.onnx_int8.file,
{ executionProviders: ["wasm"] });
$("status").textContent = "Ready. Choose a photo.";
window.leafscanReady = true;
} catch (e) {
$("status").textContent = "Could not load the model: " + e;
window.leafscanError = String(e);
}
})();
$("file").addEventListener("change", (e) => handleFile(e.target.files[0]));
const drop = $("drop");
drop.addEventListener("dragover", (e) => e.preventDefault());
drop.addEventListener("drop", (e) => { e.preventDefault(); handleFile(e.dataTransfer.files[0]); });
</script>
</body>
</html>
|