Download app.py from Muthu27/riperoute-efficientnet-b0: direct link, hf CLI and curl.
- Browser
- Download file 7.46 kB
-
https://huggingface.co/Muthu27/riperoute-efficientnet-b0/resolve/main/app.py
- Command line
-
hf download hf://Muthu27/riperoute-efficientnet-b0/app.py
-
curl -L -o app.py https://huggingface.co/Muthu27/riperoute-efficientnet-b0/resolve/main/app.py
7.46 kB
| import datetime, tempfile | |
| import numpy as np | |
| import torch, torch.nn as nn | |
| import torch.nn.functional as F | |
| import gradio as gr | |
| import matplotlib.cm as cm | |
| from PIL import Image | |
| from torchvision import transforms, models | |
| from reportlab.lib.pagesizes import A4 | |
| from reportlab.lib import colors | |
| from reportlab.lib.units import cm as CM | |
| from reportlab.lib.styles import getSampleStyleSheet | |
| from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer | |
| from reportlab.platypus import Table, TableStyle | |
| from reportlab.platypus import Image as RLImage | |
| CLASSES = ["overripe", "ripe", "rotten", "unripe"] | |
| device = "cpu" | |
| mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] | |
| eval_tf = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean, std), | |
| ]) | |
| model = models.efficientnet_b0(weights=None) | |
| model.classifier[1] = nn.Linear(model.classifier[1].in_features, 4) | |
| model.load_state_dict(torch.load("effnetb0_noise_aug.pth", map_location=device)) | |
| model.eval() | |
| # EXAMPLE values: replace with a cited source before using in a report | |
| SHELF_LIFE = { | |
| "ambient": {"unripe": (7, 10), "ripe": (3, 4), "overripe": (1, 2), "rotten": (0, 0)}, | |
| "cold_chain": {"unripe": (18, 25), "ripe": (5, 7), "overripe": (2, 3), "rotten": (0, 0)}, | |
| } | |
| ROUTES = {"local market": 1, "air freight": 3, "sea freight": 14} | |
| BUFFER = 2 | |
| GRADES = { | |
| "unripe": ("A", "Export grade", "#2e7d32"), | |
| "ripe": ("B", "Premium, air freight or short-haul", "#1565c0"), | |
| "overripe": ("C", "Local market or processing", "#e65100"), | |
| "rotten": ("Reject", "Discard", "#b71c1c"), | |
| } | |
| def export_decision(min_days): | |
| options = [r for r, t in ROUTES.items() if min_days >= t + BUFFER] | |
| if not options: | |
| return "Not suitable for export: sell immediately in local market or process" | |
| best = max(options, key=lambda r: ROUTES[r]) | |
| return "Suitable for: " + ", ".join(options) + ". Best option: " + best | |
| def gradcam_pil(img): | |
| store = {} | |
| def fwd(m, i, o): | |
| store["a"] = o.detach() | |
| o.register_hook(lambda g: store.__setitem__("g", g.detach())) | |
| h = model.features[-1].register_forward_hook(fwd) | |
| x = eval_tf(img).unsqueeze(0) | |
| model.zero_grad() | |
| with torch.enable_grad(): | |
| out = model(x) | |
| probs = F.softmax(out, dim=1)[0].detach() | |
| idx = out.argmax(1).item() | |
| out[0, idx].backward() | |
| h.remove() | |
| w = store["g"].mean(dim=(2, 3), keepdim=True) | |
| cam = F.relu((w * store["a"]).sum(1, keepdim=True)) | |
| cam = F.interpolate(cam, size=(224, 224), mode="bilinear", align_corners=False)[0, 0] | |
| cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8) | |
| return cam.numpy(), probs, idx | |
| def make_pdf(img, overlay, cls, conf, probs, storage, lo, hi, decision): | |
| grade, meaning, color = GRADES[cls] | |
| styles = getSampleStyleSheet() | |
| normal = styles["Normal"] | |
| tmp = tempfile.mkdtemp() | |
| p1 = tmp + "/input.jpg" | |
| p2 = tmp + "/gradcam.jpg" | |
| img.resize((300, 300)).save(p1) | |
| Image.fromarray(overlay).resize((300, 300)).save(p2) | |
| now = datetime.datetime.now() | |
| out = tmp + "/RipeRoute_Report.pdf" | |
| doc = SimpleDocTemplate(out, pagesize=A4, leftMargin=2*CM, | |
| rightMargin=2*CM, topMargin=2*CM, bottomMargin=2*CM) | |
| story = [] | |
| story.append(Paragraph("RipeRoute: Banana Grading Report", styles["Title"])) | |
| story.append(Paragraph("Generated: " + now.strftime("%d %b %Y, %H:%M"), normal)) | |
| story.append(Spacer(1, 14)) | |
| pics = Table([ | |
| [RLImage(p1, 6.5*CM, 6.5*CM), RLImage(p2, 6.5*CM, 6.5*CM)], | |
| ["Input photo", "Grad-CAM (model focus)"], | |
| ]) | |
| pics.setStyle(TableStyle([("ALIGN", (0, 0), (-1, -1), "CENTER")])) | |
| story.append(pics) | |
| story.append(Spacer(1, 14)) | |
| g_text = '<font color="' + color + '"><b>Grade ' + grade + "</b></font> (" + meaning + ")" | |
| rows = [ | |
| ["Grade", Paragraph(g_text, normal)], | |
| ["Ripeness class", cls], | |
| ["Confidence", str(round(conf * 100, 1)) + "%"], | |
| ["Storage condition", storage], | |
| ["Estimated shelf life", str(lo) + "-" + str(hi) + " days"], | |
| ["Shipping decision", Paragraph(decision, normal)], | |
| ] | |
| t = Table(rows, colWidths=[5*CM, 11*CM]) | |
| t.setStyle(TableStyle([ | |
| ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), | |
| ("BACKGROUND", (0, 0), (0, -1), colors.whitesmoke), | |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), | |
| ])) | |
| story.append(t) | |
| story.append(Spacer(1, 12)) | |
| if conf < 0.80: | |
| warn = "Low confidence. Retake the photo with good light and a plain background." | |
| story.append(Paragraph('<font color="#b71c1c"><b>Warning:</b> ' + warn + "</font>", normal)) | |
| story.append(Spacer(1, 12)) | |
| prob_rows = [["Class", "Probability"]] | |
| order = sorted(range(4), key=lambda i: -float(probs[i])) | |
| for i in order: | |
| prob_rows.append([CLASSES[i], str(round(float(probs[i]) * 100, 1)) + "%"]) | |
| pt = Table(prob_rows, colWidths=[5*CM, 4*CM]) | |
| pt.setStyle(TableStyle([ | |
| ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), | |
| ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), | |
| ])) | |
| story.append(Paragraph("<b>Class probabilities</b>", normal)) | |
| story.append(Spacer(1, 4)) | |
| story.append(pt) | |
| story.append(Spacer(1, 16)) | |
| note = ("Notes: Grade A/B/C is derived from the predicted ripeness class and is " | |
| "not an official export grading standard. Shelf-life and transit values " | |
| "are assumed example values. This is an image-based estimate only; " | |
| "internal quality, finger length and defects are not assessed.") | |
| story.append(Paragraph(note, styles["Italic"])) | |
| doc.build(story) | |
| return out | |
| def analyze(img, storage): | |
| if img is None: | |
| return None, None, "Please upload a banana photo.", None | |
| img = img.convert("RGB") | |
| cam, probs, idx = gradcam_pil(img) | |
| small = np.array(img.resize((224, 224))).astype(np.float32) / 255 | |
| heat = cm.jet(cam)[..., :3] | |
| overlay = ((0.55 * small + 0.45 * heat).clip(0, 1) * 255).astype(np.uint8) | |
| labels = {CLASSES[i]: float(probs[i]) for i in range(4)} | |
| cls = CLASSES[idx] | |
| conf = probs[idx].item() | |
| lo, hi = SHELF_LIFE[storage][cls] | |
| decision = export_decision(lo) | |
| grade, meaning, _ = GRADES[cls] | |
| pdf_path = make_pdf(img, overlay, cls, conf, probs, storage, lo, hi, decision) | |
| text = "## Grade " + grade + " (" + meaning + ")\n\n" | |
| text += "**Ripeness:** " + cls + " (confidence " + str(round(conf * 100, 1)) + "%)\n\n" | |
| text += "**Storage:** " + storage + "\n\n" | |
| text += "**Estimated shelf life:** " + str(lo) + "-" + str(hi) + " days\n\n" | |
| text += "**Decision:** " + decision | |
| if conf < 0.80: | |
| text += "\n\n**Warning:** low confidence. Retake the photo." | |
| return labels, overlay, text, pdf_path | |
| demo = gr.Interface( | |
| fn=analyze, | |
| inputs=[ | |
| gr.Image(type="pil", label="Banana photo"), | |
| gr.Radio(["cold_chain", "ambient"], value="cold_chain", label="Storage condition"), | |
| ], | |
| outputs=[ | |
| gr.Label(num_top_classes=4, label="Class probabilities"), | |
| gr.Image(label="Grad-CAM"), | |
| gr.Markdown(label="Result"), | |
| gr.File(label="Download PDF report"), | |
| ], | |
| title="RipeRoute: Banana Grading and Export Advisor", | |
| description="Upload a banana photo. Shelf-life and transit values are assumed example values.", | |
| flagging_mode="never", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |