Add Plant Disease Classification (CNN) project#4
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds a Plant Disease Classification project: Git LFS rules, dependency list, Apache-2.0 license, documentation (README, EfficientNet guide), class label JSON, and a Gradio EfficientNet-B0 inference app that loads a checkpoint and returns annotated predictions. Changes
Sequence DiagramsequenceDiagram
participant User as "User"
participant UI as "Gradio UI"
participant App as "app.py"
participant FS as "File System"
participant Model as "EfficientNet-B0"
participant Device as "Device (CUDA/CPU)"
User->>UI: open app / upload image
UI->>App: predict(image)
App->>FS: read `class_names.json` and checkpoint
FS-->>App: return labels and weights
App->>Model: instantiate via `timm` (num_classes)
App->>Device: move model, set eval()
App->>Model: preprocess image → forward pass
Model-->>App: logits
App->>App: softmax → top class + confidence, create annotated image
App->>UI: return annotated image + Markdown
UI-->>User: display results
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (3)
Plant Disease CNNs/class_names.json (1)
1-1: Consider formatting JSON for readability.The single-line JSON is valid but difficult to read and maintain. Consider formatting with one class per line and adding a trailing newline.
✨ Suggested format (excerpt)
[ "Apple___Apple_scab", "Apple___Black_rot", "Apple___Cedar_apple_rust", ... "Tomato___healthy" ]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/class_names.json at line 1, The class_names.json file is a single-line JSON array which is hard to read; reformat the JSON in class_names.json (the array of class strings like "Apple___Apple_scab", "Tomato___healthy", etc.) to pretty-printed form with one class per line, proper indentation and a trailing newline at EOF so the file is more maintainable and diff-friendly.Plant Disease CNNs/app.py (2)
7-8: Unused imports.
torch.nn(line 7) is imported but never used.torch.nn.functional(line 8) is used forF.softmax.✨ Suggested fix
from PIL import Image -import torch.nn as nn import torch.nn.functional as F🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/app.py around lines 7 - 8, The import of torch.nn is unused while torch.nn.functional is used via the alias F for F.softmax; remove the unused torch.nn import to clean up imports and keep only the functional import (e.g., ensure F is imported as torch.nn.functional and delete the unused torch.nn import symbol) so references like F.softmax continue to work and no unused-import warnings remain.
17-18: Missing error handling for file loading.If
class_names.jsonorefficientnet_plant_best.pthis missing, the app will crash with an unhelpful error. Consider adding descriptive error handling for better debugging, especially in deployment environments.✨ Example improvement
import os CLASS_NAMES_PATH = "class_names.json" MODEL_PATH = "efficientnet_plant_best.pth" if not os.path.exists(CLASS_NAMES_PATH): raise FileNotFoundError(f"Class names file not found: {CLASS_NAMES_PATH}") if not os.path.exists(MODEL_PATH): raise FileNotFoundError(f"Model weights not found: {MODEL_PATH}")Also applies to: 31-34
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/app.py around lines 17 - 18, The code opens "class_names.json" and loads model weights without checks, causing unhelpful crashes; update the block that sets class_names and the model-loading logic (references: class_names, "class_names.json", and the model weight path "efficientnet_plant_best.pth"/where torch.load is called) to first verify the files exist (os.path.exists) and either raise a clear FileNotFoundError or log a descriptive error and exit; additionally wrap the json.load and model load in try/except to catch and surface JSONDecodeError or torch loading errors with contextual messages so failures are informative in deployment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@Plant` Disease CNNs/app.py:
- Around line 96-111: Remove the redundant blocking call to interface.launch()
so the Gradio Blocks UI (with demo) can run; delete the interface.launch() line
and ensure only demo.launch() is used. Also fix the output mapping for
btn.click: update the outputs list to match predict()'s return values
(annotated_img and result_text) and replace the single output_label (gr.Label())
with the correct components (e.g., an Image component for annotated_img and a
Label/Text component for result_text) so btn.click(predict, inputs=input_image,
outputs=...) matches predict's return tuple.
In `@Plant` Disease CNNs/EfficientNet.md:
- Around line 3-5: The README/section has mixed references to EfficientNetB3 and
B0 while the code (app.py) constructs the model using efficientnet_b0; update
the documentation to be consistent by either (a) changing the header and any B3
mentions to reference EfficientNet-B0 (or "EfficientNet-B0") and noting that the
project uses timm's efficientnet_b0 in app.py, or (b) if you intend to use B3,
modify app.py to instantiate efficientnet_b3 instead—ensure all mentions of
EfficientNetB3, EfficientNet-B0, and the timm model name efficientnet_b0 in the
docs and code match.
- Around line 20-22: The Markdown code fence around the pip install command uses
the wrong language tag; update the fenced code block containing "pip install
timm" (the triple-backtick block) to use a shell/bash language tag by replacing
```python with ```bash so the command is correctly highlighted and rendered.
- Around line 88-90: The Markdown code fence around the Python snippet is
malformed (it closes with four backticks). Edit the block that contains the line
"optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)" to use a standard
triple-backtick fence (``` ) for both opening and closing, replacing the
four-backtick closing fence with three backticks so the snippet renders
correctly.
In `@Plant` Disease CNNs/README.md:
- Around line 15-28: The README's "Transformers" examples (pipeline,
AutoModel.from_pretrained) are misleading because the repo's app.py uses timm
and Gradio directly and does not import transformers; either clarify these
snippets are optional examples for a separately published HF model or remove
them and update requirements.txt to drop transformers; specifically edit
README.md to state that pipeline and AutoModel usage are for a separately
published Hugging Face model (or delete that section), and if you remove the
examples, remove transformers from requirements.txt and/or note in app.py why
transformers is not used while timm and Gradio are required.
- Around line 77-84: The README.md currently contains Hugging Face Spaces YAML
frontmatter (title: LeafDiseaseML, sdk_version: 6.8.0, app_file: app.py, pinned:
false) placed mid/bottom and without proper --- delimiters; move a proper
frontmatter block to the very top of README.md (before the "# 🌿 Plant Disease
Classification" header), wrap it with --- delimiters, and include required keys
such as title: LeafDiseaseML, emoji, sdk: gradio, sdk_version: 6.8.0, app_file:
app.py, colorFrom/colorTo, and pinned: false so HF Spaces can parse it.
- Around line 63-66: The README currently claims EfficientNetB3 and
TensorFlow/Keras, but the implementation (see app.py) instantiates
efficientnet_b0 via timm and uses PyTorch; update the README to reflect the real
implementation by replacing "EfficientNetB3" with "EfficientNet-B0", replace
"TensorFlow / Keras" with "PyTorch (timm)", and ensure the Tech Stack table and
the quick model summary match app.py's actual symbols (efficientnet_b0, timm,
PyTorch) so documentation and code are consistent.
In `@Plant` Disease CNNs/requirements.txt:
- Around line 1-8: Update the requirements file to match actual imports used by
the app: add gradio because app.py imports and uses it (ensure correct version
if needed), remove the duplicate numpy entry so it appears only once, and remove
transformers since app.py does not import or use it to avoid unnecessary
installs; verify torch/torchvision/timm/pillow/matplotlib remain as required by
the code.
---
Nitpick comments:
In `@Plant` Disease CNNs/app.py:
- Around line 7-8: The import of torch.nn is unused while torch.nn.functional is
used via the alias F for F.softmax; remove the unused torch.nn import to clean
up imports and keep only the functional import (e.g., ensure F is imported as
torch.nn.functional and delete the unused torch.nn import symbol) so references
like F.softmax continue to work and no unused-import warnings remain.
- Around line 17-18: The code opens "class_names.json" and loads model weights
without checks, causing unhelpful crashes; update the block that sets
class_names and the model-loading logic (references: class_names,
"class_names.json", and the model weight path
"efficientnet_plant_best.pth"/where torch.load is called) to first verify the
files exist (os.path.exists) and either raise a clear FileNotFoundError or log a
descriptive error and exit; additionally wrap the json.load and model load in
try/except to catch and surface JSONDecodeError or torch loading errors with
contextual messages so failures are informative in deployment.
In `@Plant` Disease CNNs/class_names.json:
- Line 1: The class_names.json file is a single-line JSON array which is hard to
read; reformat the JSON in class_names.json (the array of class strings like
"Apple___Apple_scab", "Tomato___healthy", etc.) to pretty-printed form with one
class per line, proper indentation and a trailing newline at EOF so the file is
more maintainable and diff-friendly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7794bd20-9b5e-46e0-8a98-f91b8785fd97
⛔ Files ignored due to path filters (8)
Plant Disease CNNs/img/__results___15_0.pngis excluded by!**/*.pngPlant Disease CNNs/img/__results___16_0.pngis excluded by!**/*.pngPlant Disease CNNs/img/__results___16_1.pngis excluded by!**/*.pngPlant Disease CNNs/img/__results___16_2.pngis excluded by!**/*.pngPlant Disease CNNs/img/__results___16_3.pngis excluded by!**/*.pngPlant Disease CNNs/img/__results___16_4.pngis excluded by!**/*.pngPlant Disease CNNs/img/demo.gifis excluded by!**/*.gifPlant Disease CNNs/img/flow1.pngis excluded by!**/*.png
📒 Files selected for processing (8)
Plant Disease CNNs/.gitattributesPlant Disease CNNs/EfficientNet.mdPlant Disease CNNs/LICENSEPlant Disease CNNs/README.mdPlant Disease CNNs/app.pyPlant Disease CNNs/class_names.jsonPlant Disease CNNs/plant-disease-cnn.ipynbPlant Disease CNNs/requirements.txt
Agent-Logs-Url: https://github.com/ARUNAGIRINATHAN-K/Beginner-Data-Science-Projects/sessions/eaa2ff4d-f09e-434d-93b4-794c664c0c5a Co-authored-by: ARUNAGIRINATHAN-K <167340745+ARUNAGIRINATHAN-K@users.noreply.github.com>
Agent-Logs-Url: https://github.com/ARUNAGIRINATHAN-K/Beginner-Data-Science-Projects/sessions/e4a37e3c-229c-44b5-b208-24fcaa6e7155 Co-authored-by: ARUNAGIRINATHAN-K <167340745+ARUNAGIRINATHAN-K@users.noreply.github.com>
…-launch-call Fix Plant Disease CNNs: align docs/code to EfficientNet-B0, clean up requirements and imports
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
Plant Disease CNNs/README.md (1)
37-40:⚠️ Potential issue | 🟠 MajorFix the direct-load Transformers example.
AutoModel.from_pretrained(..., dtype="auto")is not the task-specific loader for an image-classification checkpoint, anddtypeis not the usual PyTorchfrom_pretrainedkwarg here. Copying this snippet will likely give readers the wrong model class or a runtime error.Suggested fix
-# Load model directly -from transformers import AutoModel -model = AutoModel.from_pretrained("ARUNAGIRINATHAN/plant_disease", dtype="auto") +# Load model directly +from transformers import AutoImageProcessor, AutoModelForImageClassification + +processor = AutoImageProcessor.from_pretrained("ARUNAGIRINATHAN/plant_disease") +model = AutoModelForImageClassification.from_pretrained( + "ARUNAGIRINATHAN/plant_disease", + torch_dtype="auto", +)For Hugging Face Transformers image classification models, is `AutoModel.from_pretrained(..., dtype="auto")` a valid direct-loading example, or should documentation use `AutoModelForImageClassification` with `torch_dtype` (and typically `AutoImageProcessor`) instead?🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/README.md around lines 37 - 40, The example incorrectly uses AutoModel.from_pretrained(..., dtype="auto") for an image-classification checkpoint; replace it with the task-specific loader AutoModelForImageClassification and load the processor with AutoImageProcessor, and if a dtype hint is needed use the PyTorch kwarg torch_dtype when calling AutoModelForImageClassification.from_pretrained; update the snippet to use AutoImageProcessor.from_pretrained(...) and AutoModelForImageClassification.from_pretrained(..., torch_dtype=...) so readers get the correct model class and processor for image classification.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@Plant` Disease CNNs/app.py:
- Around line 45-46: The predict function should validate the input before
calling transform(image): check that the image is not None and is a valid
non-empty file/object (e.g., PIL Image or bytes) and if invalid return/raise a
clear validation error (e.g., ValueError or a Flask/fastAPI-friendly error)
instead of calling transform; update predict (and any callers) to perform this
guard before img_tensor = transform(image).unsqueeze(0).to(device) so the UI
receives a descriptive validation message rather than a backend error.
- Around line 16-31: The code opens "class_names.json" and loads
"efficientnet_plant_best.pth" using relative paths which fail if the working
directory isn't the app.py folder; change these to resolve paths relative to the
app.py file (use the module file location, e.g. Path(__file__).resolve().parent)
and build absolute paths for the class_names.json open and for torch.load so
timm.create_model and model.load_state_dict still use the same model/num_classes
but the asset lookups use the resolved paths to the files.
---
Duplicate comments:
In `@Plant` Disease CNNs/README.md:
- Around line 37-40: The example incorrectly uses AutoModel.from_pretrained(...,
dtype="auto") for an image-classification checkpoint; replace it with the
task-specific loader AutoModelForImageClassification and load the processor with
AutoImageProcessor, and if a dtype hint is needed use the PyTorch kwarg
torch_dtype when calling AutoModelForImageClassification.from_pretrained; update
the snippet to use AutoImageProcessor.from_pretrained(...) and
AutoModelForImageClassification.from_pretrained(..., torch_dtype=...) so readers
get the correct model class and processor for image classification.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 4a7f09a0-02f5-4e65-99e4-1a4d47082d8e
📒 Files selected for processing (5)
Plant Disease CNNs/EfficientNet.mdPlant Disease CNNs/README.mdPlant Disease CNNs/app.pyPlant Disease CNNs/class_names.jsonPlant Disease CNNs/requirements.txt
✅ Files skipped from review due to trivial changes (3)
- Plant Disease CNNs/requirements.txt
- Plant Disease CNNs/class_names.json
- Plant Disease CNNs/EfficientNet.md
ARUNAGIRINATHAN-K
left a comment
There was a problem hiding this comment.
All mentioned error and conflicts are solved
Agent-Logs-Url: https://github.com/ARUNAGIRINATHAN-K/Beginner-Data-Science-Projects/sessions/d5bdd376-6b0b-4c1e-831e-66f93996eaf0 Co-authored-by: ARUNAGIRINATHAN-K <167340745+ARUNAGIRINATHAN-K@users.noreply.github.com>
…hs-in-cnn-app fix: resolve asset paths relative to __file__ in Plant Disease CNNs app
There was a problem hiding this comment.
♻️ Duplicate comments (1)
Plant Disease CNNs/app.py (1)
49-50:⚠️ Potential issue | 🟠 MajorRestore the empty-upload guard in
predict().Line 50 still dereferences
imageunconditionally, so an empty submission falls through totransform()and fails as a backend error instead of a clear user message.Suggested fix
def predict(image): + if image is None: + raise ValueError("Please upload a leaf image before running prediction.") img_tensor = transform(image).unsqueeze(0).to(device)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/app.py around lines 49 - 50, The predict(image) function currently dereferences image unconditionally; add an empty-upload guard at the top of predict to check for a missing/empty image (e.g., if image is None or otherwise falsy) and return or raise a clear error (e.g., raise ValueError or return an error response) before calling transform(image). Ensure the guard sits before the existing img_tensor = transform(image).unsqueeze(0).to(device) line so transform is never called with an empty input.
🧹 Nitpick comments (1)
Plant Disease CNNs/app.py (1)
88-97: Remove the unusedgr.Interfacedefinition.The Interface object (lines 88-97) is never instantiated or launched—only
demo.launch()is called. This leaves dead code that duplicates the same inference contract as the Blocks UI and creates unnecessary maintenance burden.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@Plant` Disease CNNs/app.py around lines 88 - 97, Remove the dead gr.Interface definition that creates an unused "interface" variable (the block calling gr.Interface with fn=predict and image/markdown outputs); delete that entire declaration so only the Blocks-based UI (the existing demo and its demo.launch call) remains; ensure the predict function is still referenced only by the Blocks components and that no other code depends on the removed "interface" variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@Plant` Disease CNNs/app.py:
- Around line 49-50: The predict(image) function currently dereferences image
unconditionally; add an empty-upload guard at the top of predict to check for a
missing/empty image (e.g., if image is None or otherwise falsy) and return or
raise a clear error (e.g., raise ValueError or return an error response) before
calling transform(image). Ensure the guard sits before the existing img_tensor =
transform(image).unsqueeze(0).to(device) line so transform is never called with
an empty input.
---
Nitpick comments:
In `@Plant` Disease CNNs/app.py:
- Around line 88-97: Remove the dead gr.Interface definition that creates an
unused "interface" variable (the block calling gr.Interface with fn=predict and
image/markdown outputs); delete that entire declaration so only the Blocks-based
UI (the existing demo and its demo.launch call) remains; ensure the predict
function is still referenced only by the Blocks components and that no other
code depends on the removed "interface" variable.
Agent-Logs-Url: https://github.com/ARUNAGIRINATHAN-K/Beginner-Data-Science-Projects/sessions/b7b24d3d-7958-4ee5-a2db-65f40bb80883 Co-authored-by: ARUNAGIRINATHAN-K <167340745+ARUNAGIRINATHAN-K@users.noreply.github.com>
…tion-empty-guard fix(plant-disease-cnns): guard against empty image input and remove dead gr.Interface
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@Plant` Disease CNNs/app.py:
- Around line 49-53: The predict function may receive RGBA or grayscale images
so transform(image) can produce tensors with 4 or 1 channels, breaking
EfficientNet-B0's 3-channel input; before applying transform in predict, convert
the PIL/ndarray image to RGB (e.g., image = image.convert("RGB") for PIL or use
cv2/canvases to convert arrays) to guarantee 3 channels, then proceed with
img_tensor = transform(image).unsqueeze(0).to(device); ensure this conversion
happens inside predict and covers both PIL Image and numpy array inputs when
present.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
Agent-Logs-Url: https://github.com/ARUNAGIRINATHAN-K/Beginner-Data-Science-Projects/sessions/be584b4f-3d95-4a9b-baf1-53075a99347f Co-authored-by: ARUNAGIRINATHAN-K <167340745+ARUNAGIRINATHAN-K@users.noreply.github.com>
…l-handling Fix RGBA/grayscale image channel mismatch in Plant Disease CNN predict
tkarim45
left a comment
There was a problem hiding this comment.
Thanks for the contribution, @ARUNAGIRINATHAN-K — and for the patient back-and-forth with CodeRabbit. The training notebook, Gradio app, and EfficientNet docs all look good. CI is green.
One optional doc cleanup before/after merge:
-
Plant Disease CNNs/README.md:37-40— the "Load model directly" snippet usesAutoModel.from_pretrained(..., dtype="auto"), which won't load an image-classification head. Since the README correctly notes that the localapp.pydoesn't depend ontransformers, this is purely informational for users wanting to load your published HF model — but the snippet as written would fail. Suggested:from transformers import AutoImageProcessor, AutoModelForImageClassification processor = AutoImageProcessor.from_pretrained("ARUNAGIRINATHAN/plant_disease") model = AutoModelForImageClassification.from_pretrained( "ARUNAGIRINATHAN/plant_disease", torch_dtype="auto", )
Happy to merge as-is if you'd rather fix this in a follow-up. Nice work!
|
@tkarim45 Since the local Appreciate the detailed feedback and the merge readiness check! |
|
Thanks @ARUNAGIRINATHAN-K! Let's keep it as a single PR — please push the README snippet fix to this branch and I'll merge as soon as CI goes green again. No rush. |
This PR adds a new beginner-friendly computer vision project: Plant Disease Classification Using CNNs, deployed as a Hugging Face Space.
What’s included:
This Provides a practical end-to-end example of image classification from notebook experimentation to deployment suitable for beginners exploring CNNs and applied ML.
Checklist:
Summary by CodeRabbit
New Features
Documentation
Chores