-
Notifications
You must be signed in to change notification settings - Fork 28
feat: integrate local ONNX inference for offline plant disease detection #67
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vedant-kawale-27
wants to merge
2
commits into
jpdevhub:main
Choose a base branch
from
vedant-kawale-27:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import os | ||
| import json | ||
| import torch | ||
| import torch.nn as nn | ||
| from torchvision import models | ||
|
|
||
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | ||
| MODEL_DIR = os.path.join(BASE_DIR, "model") | ||
| CLASS_NAMES_PATH = os.path.join(MODEL_DIR, "class_names.json") | ||
| MODEL_PATH = os.path.join(MODEL_DIR, "plant_disease_resnet18.pth") | ||
|
|
||
| # Output paths | ||
| FRONTEND_PUBLIC_DIR = os.path.join(os.path.dirname(BASE_DIR), "frontend", "public") | ||
| ONNX_MODEL_DIR = os.path.join(FRONTEND_PUBLIC_DIR, "model") | ||
| os.makedirs(ONNX_MODEL_DIR, exist_ok=True) | ||
| ONNX_PATH = os.path.join(ONNX_MODEL_DIR, "plant_disease_resnet18.onnx") | ||
|
|
||
| def export_model(): | ||
| # Load class names | ||
| with open(CLASS_NAMES_PATH, "r") as f: | ||
| class_names = json.load(f) | ||
| num_classes = len(class_names) | ||
|
|
||
| print(f"[INFO] Loaded {num_classes} class names from {CLASS_NAMES_PATH}") | ||
|
|
||
| # Instantiate the ResNet18 model | ||
| model = models.resnet18(weights=None) | ||
| model.fc = nn.Linear(model.fc.in_features, num_classes) | ||
|
|
||
| # Load local fine-tuned weights if available | ||
| if os.path.exists(MODEL_PATH) and os.path.getsize(MODEL_PATH) > 0: | ||
| print(f"[INFO] Loading fine-tuned weights from {MODEL_PATH}...") | ||
| try: | ||
| model.load_state_dict(torch.load(MODEL_PATH, map_location="cpu")) | ||
| print("[INFO] Weights loaded successfully.") | ||
| except Exception as e: | ||
| print(f"[ERROR] Failed to load model weights: {e}") | ||
| raise | ||
| else: | ||
| raise FileNotFoundError( | ||
| f"Fine-tuned model weights not found at {MODEL_PATH}. " | ||
| "Please ensure you have placed the trained ResNet18 model (.pth file) in the backend/model/ directory before exporting." | ||
| ) | ||
|
|
||
| model.eval() | ||
|
|
||
| # Preprocessing dummy input matching ImageNet requirements: 1 image, 3 channels, 224x224 shape | ||
| dummy_input = torch.randn(1, 3, 224, 224, requires_grad=False) | ||
|
|
||
| print(f"[INFO] Exporting PyTorch model to ONNX format at {ONNX_PATH}...") | ||
| torch.onnx.export( | ||
| model, | ||
| dummy_input, | ||
| ONNX_PATH, | ||
| export_params=True, | ||
| opset_version=12, | ||
| do_constant_folding=True, | ||
| input_names=["input"], | ||
| output_names=["output"], | ||
| dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}}, | ||
| ) | ||
| print(f"[SUCCESS] ONNX model exported to {ONNX_PATH}") | ||
|
|
||
| # Apply 8-bit dynamic quantization if onnxruntime is available | ||
| try: | ||
| import onnxruntime | ||
| from onnxruntime.quantization import quantize_dynamic, QuantType | ||
|
|
||
| QUANT_ONNX_PATH = os.path.join(ONNX_MODEL_DIR, "plant_disease_resnet18_quant.onnx") | ||
| print(f"[INFO] onnxruntime is installed. Performing 8-bit dynamic quantization to {QUANT_ONNX_PATH}...") | ||
|
|
||
| quantize_dynamic( | ||
| model_input=ONNX_PATH, | ||
| model_output=QUANT_ONNX_PATH, | ||
| weight_type=QuantType.QUInt8 | ||
| ) | ||
| print("[SUCCESS] Quantization complete.") | ||
|
|
||
| # Replace the larger float32 file with the quantized version to save space (46MB -> 11MB) | ||
| if os.path.exists(QUANT_ONNX_PATH) and os.path.getsize(QUANT_ONNX_PATH) > 0: | ||
| os.replace(QUANT_ONNX_PATH, ONNX_PATH) | ||
| print(f"[INFO] Replaced {ONNX_PATH} with the quantized model (~11.6MB).") | ||
| except ImportError: | ||
| print("[WARN] onnxruntime is not installed. Skipping dynamic quantization. The output model will be standard float32 (~46.8MB).") | ||
| except Exception as e: | ||
| print(f"[ERROR] Quantization failed: {e}") | ||
|
|
||
| if __name__ == "__main__": | ||
| export_model() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.