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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Rice Crop Stage Detector — Gradio App
|
| 3 |
+
======================================
|
| 4 |
+
Model : MobileNetV2 (transfer learning) trained on 4 rice crop stages
|
| 5 |
+
Input : 224x224 RGB image
|
| 6 |
+
Classes: flowering, germination, noise, tillering
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import tensorflow as tf
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
# ─── CONFIG ──────────────────────────────────────────────────
|
| 15 |
+
MODEL_PATH = "rice_stage_model_v2_with_noise.keras"
|
| 16 |
+
IMG_SIZE = 224
|
| 17 |
+
CONFIDENCE_THRESHOLD = 0.70
|
| 18 |
+
|
| 19 |
+
# Class labels (must match the order from training: alphabetical by folder name)
|
| 20 |
+
CLASS_LABELS = ["flowering", "germination", "noise", "tillering"]
|
| 21 |
+
|
| 22 |
+
# Telugu translations for each stage
|
| 23 |
+
TELUGU_LABELS = {
|
| 24 |
+
"flowering": "పూత దశ (Flowering)",
|
| 25 |
+
"germination": "మొలకెత్తడం (Germination)",
|
| 26 |
+
"tillering": "పిలకలు వేయడం (Tillering)",
|
| 27 |
+
"noise": "గుర్తించలేని చిత్రం (Unrecognized)"
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
# Detailed stage descriptions
|
| 31 |
+
STAGE_INFO = {
|
| 32 |
+
"flowering": {
|
| 33 |
+
"description": "The rice plant is in the flowering/heading stage. Panicles have emerged and pollination is occurring.",
|
| 34 |
+
"description_te": "వరి మొక్క పూత దశలో ఉంది. కంకులు బయటకు వచ్చి పరాగసంపర్కం జరుగుతోంది.",
|
| 35 |
+
"advisory": "Ensure adequate water supply. Avoid pesticide spraying during active flowering. Monitor for neck blast disease.",
|
| 36 |
+
"advisory_te": "తగినంత నీటి సరఫరా ఉండేలా చూడండి. పూత సమయంలో పురుగుమందులు పిచికారీ చేయకండి. మెడవిరుపు తెగులు కోసం గమనించండి."
|
| 37 |
+
},
|
| 38 |
+
"germination": {
|
| 39 |
+
"description": "The rice seeds are in the germination/seedling stage. Young shoots are emerging from the soil.",
|
| 40 |
+
"description_te": "వరి విత్తనాలు మొలకెత్తే దశలో ఉన్నాయి. చిన్న మొక్కలు మట్టి నుండి బయటకు వస్తున్నాయి.",
|
| 41 |
+
"advisory": "Maintain thin water layer (2-3cm). Watch for seedling blight and case worm. Ensure proper nursery management.",
|
| 42 |
+
"advisory_te": "సన్నని నీటి పొర (2-3 సెం.మీ) ఉంచండి. మొలక తెగులు మరియు కేస్ వార్మ్ కోసం గమనించండి."
|
| 43 |
+
},
|
| 44 |
+
"tillering": {
|
| 45 |
+
"description": "The rice plant is actively producing tillers (side shoots). This is a critical growth phase.",
|
| 46 |
+
"description_te": "వరి మొక్క పిలకలు వేస్తోంది. ఇది కీలకమైన పెరుగుదల దశ.",
|
| 47 |
+
"advisory": "Apply nitrogen fertilizer to promote tillering. Maintain 5cm water depth. Scout for stem borer and leaf folder.",
|
| 48 |
+
"advisory_te": "పిలకలు పెరగడానికి నత్రజని ఎరువు వేయండి. 5 సెం.మీ నీటి లోతు ఉంచండి. కాండం తొలుచు పురుగు కోసం గమనించండి."
|
| 49 |
+
},
|
| 50 |
+
"noise": {
|
| 51 |
+
"description": "The uploaded image does not appear to be a recognizable rice crop stage.",
|
| 52 |
+
"description_te": "అప్లోడ్ చేసిన చిత్రం గుర్తించదగిన వరి పంట దశగా కనిపించడం లేదు.",
|
| 53 |
+
"advisory": "Please upload a clear photo of your rice crop taken from close range.",
|
| 54 |
+
"advisory_te": "దయచేసి మీ వరి పంట యొక్క స్పష్టమైన ఫోటోను దగ్గరి నుండి తీసి అప్లోడ్ చేయండి."
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
# ─── LOAD MODEL ──────────────────────────────────────────────
|
| 59 |
+
print("Loading rice stage classification model...")
|
| 60 |
+
model = tf.keras.models.load_model(MODEL_PATH)
|
| 61 |
+
print(f"Model loaded successfully. Input shape: {model.input_shape}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ─── PREDICTION FUNCTION ────────────────────────────────────
|
| 65 |
+
def classify_crop_stage(input_image):
|
| 66 |
+
"""
|
| 67 |
+
Takes a PIL Image, preprocesses it, runs inference,
|
| 68 |
+
and returns structured results.
|
| 69 |
+
"""
|
| 70 |
+
if input_image is None:
|
| 71 |
+
return "No image provided", "", "", "", {}
|
| 72 |
+
|
| 73 |
+
# Preprocess
|
| 74 |
+
img = input_image.resize((IMG_SIZE, IMG_SIZE))
|
| 75 |
+
img_array = np.array(img, dtype=np.float32) / 255.0
|
| 76 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 77 |
+
|
| 78 |
+
# Predict
|
| 79 |
+
predictions = model.predict(img_array, verbose=0)
|
| 80 |
+
class_idx = int(np.argmax(predictions[0]))
|
| 81 |
+
confidence = float(np.max(predictions[0]))
|
| 82 |
+
|
| 83 |
+
# Build confidence dict for all classes
|
| 84 |
+
confidence_scores = {
|
| 85 |
+
TELUGU_LABELS.get(cls, cls): float(predictions[0][i])
|
| 86 |
+
for i, cls in enumerate(CLASS_LABELS)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
# Check threshold
|
| 90 |
+
if confidence < CONFIDENCE_THRESHOLD or CLASS_LABELS[class_idx] == "noise":
|
| 91 |
+
stage = "noise"
|
| 92 |
+
result_text = (
|
| 93 |
+
f"**Result:** Not a recognized rice crop stage\n\n"
|
| 94 |
+
f"**Confidence:** {confidence*100:.1f}% (below {CONFIDENCE_THRESHOLD*100:.0f}% threshold)\n\n"
|
| 95 |
+
f"Please upload a clear photo of your rice crop."
|
| 96 |
+
)
|
| 97 |
+
else:
|
| 98 |
+
stage = CLASS_LABELS[class_idx]
|
| 99 |
+
info = STAGE_INFO[stage]
|
| 100 |
+
result_text = (
|
| 101 |
+
f"**Detected Stage:** {TELUGU_LABELS[stage]}\n\n"
|
| 102 |
+
f"**Confidence:** {confidence*100:.1f}%\n\n"
|
| 103 |
+
f"---\n\n"
|
| 104 |
+
f"**Description:**\n{info['description']}\n\n"
|
| 105 |
+
f"**వివరణ:**\n{info['description_te']}\n\n"
|
| 106 |
+
f"---\n\n"
|
| 107 |
+
f"**Advisory:**\n{info['advisory']}\n\n"
|
| 108 |
+
f"**సలహా:**\n{info['advisory_te']}"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
return result_text, confidence_scores
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ─── GRADIO INTERFACE ────────────────────────────────────────
|
| 115 |
+
with gr.Blocks(
|
| 116 |
+
title="Rice Crop Stage Detector",
|
| 117 |
+
theme=gr.themes.Soft(primary_hue="green")
|
| 118 |
+
) as demo:
|
| 119 |
+
|
| 120 |
+
gr.Markdown(
|
| 121 |
+
"""
|
| 122 |
+
# 🌾 Rice Crop Stage Detector
|
| 123 |
+
### వరి పంట దశ గుర్తింపు
|
| 124 |
+
|
| 125 |
+
Upload a photo of your rice crop to identify its current growth stage.
|
| 126 |
+
మీ వరి పంట ఫోటోను అప్లోడ్ చేసి ప్రస్తుత దశను తెలుసుకోండి.
|
| 127 |
+
"""
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
with gr.Row():
|
| 131 |
+
with gr.Column(scale=1):
|
| 132 |
+
input_image = gr.Image(
|
| 133 |
+
type="pil",
|
| 134 |
+
label="Upload Rice Crop Image / వరి పంట చిత్రం అప్లోడ్ చేయండి",
|
| 135 |
+
sources=["upload", "webcam"],
|
| 136 |
+
height=350
|
| 137 |
+
)
|
| 138 |
+
submit_btn = gr.Button("🔍 Detect Stage / దశ గుర్తించండి", variant="primary", size="lg")
|
| 139 |
+
|
| 140 |
+
with gr.Column(scale=1):
|
| 141 |
+
result_text = gr.Markdown(label="Detection Result")
|
| 142 |
+
confidence_chart = gr.Label(
|
| 143 |
+
label="Confidence Scores / నమ్మకం స్కోర్లు",
|
| 144 |
+
num_top_classes=4
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
submit_btn.click(
|
| 148 |
+
fn=classify_crop_stage,
|
| 149 |
+
inputs=[input_image],
|
| 150 |
+
outputs=[result_text, confidence_chart]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
gr.Markdown(
|
| 154 |
+
"""
|
| 155 |
+
---
|
| 156 |
+
**Model:** MobileNetV2 (Transfer Learning) · **Classes:** Flowering, Germination, Tillering, Noise
|
| 157 |
+
· **Threshold:** 70% confidence · **Input:** 224×224 RGB
|
| 158 |
+
"""
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# ─── LAUNCH ──────────────────────────────────────────────────
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tensorflow>=2.12.0
|
| 2 |
+
gradio>=4.0.0
|
| 3 |
+
numpy
|
| 4 |
+
Pillow
|