Rejeno commited on
Commit
3b985d4
Β·
verified Β·
1 Parent(s): bfda0bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -5
app.py CHANGED
@@ -1,8 +1,189 @@
 
 
 
 
 
 
1
  import os
 
 
 
2
  import zipfile
3
 
4
- # Silent extraction code
5
- if not os.path.exists("rice_leaf_diseases"):
6
- if os.path.exists("rice_leaf_diseases.zip"):
7
- with zipfile.ZipFile("rice_leaf_diseases.zip", 'r') as zip_ref:
8
- zip_ref.extractall()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import torchvision.transforms as transforms
6
+ from PIL import Image
7
  import os
8
+ import random
9
+ import pandas as pd
10
+ import matplotlib.pyplot as plt
11
  import zipfile
12
 
13
+ # βœ… First Streamlit command - required by Streamlit
14
+ st.set_page_config(page_title="Rice Disease Detection", layout="wide")
15
+
16
+ # ================= ZIP FILE HANDLING =================
17
+ DATASET_PATH = "rice_leaf_diseases"
18
+ ZIP_FILE = "rice_leaf_diseases.zip"
19
+
20
+ # Silent extraction without Streamlit messages
21
+ if not os.path.exists(DATASET_PATH):
22
+ if os.path.exists(ZIP_FILE):
23
+ with zipfile.ZipFile(ZIP_FILE, 'r') as zip_ref:
24
+ zip_ref.extractall(".") # Extract to current directory
25
+
26
+ # βœ… Load Class Names from Extracted Dataset
27
+ if os.path.exists(DATASET_PATH):
28
+ CLASS_NAMES = sorted(os.listdir(DATASET_PATH))
29
+ else:
30
+ CLASS_NAMES = ["Bacterial Leaf Blight", "Brown Spot", "Leaf Smut"] # Fallback
31
+
32
+ # ================= ORIGINAL APP CODE =================
33
+ # Define Model Class
34
+ class RiceDiseaseCNN(nn.Module):
35
+ def __init__(self, num_classes):
36
+ super(RiceDiseaseCNN, self).__init__()
37
+ self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
38
+ self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
39
+ self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
40
+ self.bn1 = nn.BatchNorm2d(32)
41
+ self.bn2 = nn.BatchNorm2d(64)
42
+ self.bn3 = nn.BatchNorm2d(128)
43
+ self.pool = nn.MaxPool2d(2, 2)
44
+ self.dropout = nn.Dropout(0.4)
45
+ self.fc1 = nn.Linear(128 * 16 * 16, 512)
46
+ self.fc2 = nn.Linear(512, num_classes)
47
+
48
+ def forward(self, x):
49
+ x = self.pool(F.relu(self.bn1(self.conv1(x))))
50
+ x = self.pool(F.relu(self.bn2(self.conv2(x))))
51
+ x = self.pool(F.relu(self.bn3(self.conv3(x))))
52
+ x = x.view(x.size(0), -1)
53
+ x = F.relu(self.fc1(x))
54
+ x = self.dropout(x)
55
+ x = self.fc2(x)
56
+ return x
57
+
58
+ # Load Model
59
+ @st.cache_resource
60
+ def load_model():
61
+ device = torch.device("cpu")
62
+ model = RiceDiseaseCNN(len(CLASS_NAMES))
63
+ model.load_state_dict(torch.load("rice_disease_cnn.pth", map_location=device))
64
+ model.eval()
65
+ return model
66
+
67
+ model = load_model()
68
+
69
+ # Define Transformations
70
+ transform = transforms.Compose([
71
+ transforms.Resize((128, 128)),
72
+ transforms.ToTensor(),
73
+ transforms.Normalize((0.5,), (0.5,))
74
+ ])
75
+
76
+ # Class Labels
77
+ class_labels = ["Bacterial Leaf Blight", "Brown Spot", "Leaf Smut"]
78
+
79
+ # Streamlit App Configuration
80
+ st.set_page_config(page_title="Rice Disease Detection", layout="wide")
81
+
82
+ # Define dataset path after extraction
83
+ dataset_path = DATASET_FOLDER
84
+
85
+ # Sidebar Navigation
86
+ st.sidebar.title("Navigation")
87
+ page = st.sidebar.radio("Go to", ["Dataset", "Data Visualization", "Model Metrics", "Classification"])
88
+
89
+ # Dataset Page
90
+ if page == "Dataset":
91
+ st.title("Rice Leaf Disease Dataset 🌾")
92
+ st.markdown("""
93
+ This dataset contains images of rice leaves affected by three common diseases:
94
+ - **Bacterial Leaf Blight**: Caused by *Xanthomonas oryzae* bacteria.
95
+ - **Brown Spot**: Caused by *Cochliobolus miyabeanus* fungus.
96
+ - **Leaf Smut**: Caused by *Entyloma oryzae* fungus.
97
+ The dataset is available on [Kaggle](https://www.kaggle.com/datasets/vbookshelf/rice-leaf-diseases).
98
+ """)
99
+
100
+ def get_sample_images(label, count=3):
101
+ label_path = os.path.join(dataset_path, label)
102
+ images = [img for img in os.listdir(label_path) if img.endswith(("png", "jpg", "jpeg"))]
103
+ sample_images = random.sample(images, min(count, len(images)))
104
+ return [os.path.join(label_path, img) for img in sample_images]
105
+
106
+ st.subheader("Sample Images from Dataset")
107
+ cols = st.columns(3)
108
+ for idx, label in enumerate(class_labels):
109
+ images = get_sample_images(label)
110
+ with cols[idx]:
111
+ st.write(f"### {label}")
112
+ for img_path in images:
113
+ st.image(img_path, use_column_width=True)
114
+
115
+ # Data Visualization Page
116
+ elif page == "Data Visualization":
117
+ st.title("Data Visualization πŸ“Š")
118
+
119
+ def get_image_count(label):
120
+ label_path = os.path.join(dataset_path, label)
121
+ return len([img for img in os.listdir(label_path) if img.endswith(("png", "jpg", "jpeg"))])
122
+
123
+ class_counts = {label: get_image_count(label) for label in class_labels}
124
+
125
+ st.subheader("Class Distribution")
126
+ df = pd.DataFrame(list(class_counts.items()), columns=["Disease", "Count"])
127
+
128
+ # Pie Chart
129
+ fig, ax = plt.subplots()
130
+ ax.pie(df["Count"], labels=df["Disease"], autopct='%1.1f%%', startangle=90)
131
+ ax.axis('equal')
132
+ st.pyplot(fig)
133
+
134
+ # Bar Chart
135
+ fig, ax = plt.subplots()
136
+ ax.bar(df["Disease"], df["Count"], color=['#1f77b4', '#ff7f0e', '#2ca02c'])
137
+ ax.set_xlabel('Disease Type')
138
+ ax.set_ylabel('Number of Images')
139
+ st.pyplot(fig)
140
+
141
+ # Model Metrics Page
142
+ elif page == "Model Metrics":
143
+ st.title("Model Performance Metrics πŸ“ˆ")
144
+ st.markdown("""
145
+ ### Model Architecture
146
+ - **Convolutional Layers** with Batch Normalization
147
+ - **MaxPooling** for dimension reduction
148
+ - **Fully Connected Layers** for classification
149
+ """)
150
+
151
+ # Confusion Matrix
152
+ st.subheader("Confusion Matrix")
153
+ st.image("con_mat.png", use_column_width=True)
154
+
155
+ # Training Curves
156
+ col1, col2 = st.columns(2)
157
+ with col1:
158
+ st.subheader("Training Loss")
159
+ st.image("train_loss.png")
160
+ with col2:
161
+ st.subheader("Validation Accuracy")
162
+ st.image("val_acc.png")
163
+
164
+ # Classification Report
165
+ st.subheader("Classification Report")
166
+ st.code("""
167
+ precision recall f1-score support
168
+ Bacterial Leaf Blight 0.90 1.00 0.95 9
169
+ Brown Spot 1.00 1.00 1.00 5
170
+ Leaf Smut 1.00 0.75 0.86 4
171
+ """)
172
+
173
+ # Classification Page
174
+ elif page == "Classification":
175
+ st.title("Rice Leaf Disease Classification πŸ”")
176
+
177
+ uploaded_file = st.file_uploader("Upload rice leaf image", type=["jpg", "png", "jpeg"])
178
+
179
+ if uploaded_file:
180
+ image = Image.open(uploaded_file).convert("RGB")
181
+ st.image(image, use_column_width=True)
182
+
183
+ # Transform and predict
184
+ image_tensor = transform(image).unsqueeze(0)
185
+ with torch.no_grad():
186
+ output = model(image_tensor)
187
+ _, predicted = torch.max(output, 1)
188
+
189
+ st.success(f"**Prediction:** {class_labels[predicted.item()]}")