Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# Define custom CSS for background image
|
2 |
custom_css = """
|
3 |
body {
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import numpy as np
|
4 |
+
import os
|
5 |
+
import PIL
|
6 |
+
import tensorflow as tf
|
7 |
+
from tensorflow import keras
|
8 |
+
from tensorflow.keras import layers
|
9 |
+
from tensorflow.keras.models import Sequential
|
10 |
+
import gdown
|
11 |
+
import zipfile
|
12 |
+
import pathlib
|
13 |
+
|
14 |
+
# Define the Google Drive shareable link
|
15 |
+
gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
|
16 |
+
|
17 |
+
# Extract the file ID from the URL
|
18 |
+
file_id = gdrive_url.split('/d/')[1].split('/view')[0]
|
19 |
+
direct_download_url = f'https://drive.google.com/uc?id={file_id}'
|
20 |
+
|
21 |
+
# Define the local filename to save the ZIP file
|
22 |
+
local_zip_file = 'file.zip'
|
23 |
+
|
24 |
+
# Download the ZIP file
|
25 |
+
gdown.download(direct_download_url, local_zip_file, quiet=False)
|
26 |
+
|
27 |
+
# Directory to extract files
|
28 |
+
extracted_path = 'extracted_files'
|
29 |
+
|
30 |
+
# Verify if the downloaded file is a ZIP file and extract it
|
31 |
+
try:
|
32 |
+
with zipfile.ZipFile(local_zip_file, 'r') as zip_ref:
|
33 |
+
zip_ref.extractall(extracted_path)
|
34 |
+
print("Extraction successful!")
|
35 |
+
except zipfile.BadZipFile:
|
36 |
+
print("Error: The downloaded file is not a valid ZIP file.")
|
37 |
+
|
38 |
+
# Optionally, you can delete the ZIP file after extraction
|
39 |
+
os.remove(local_zip_file)
|
40 |
+
|
41 |
+
# Convert the extracted directory path to a pathlib.Path object
|
42 |
+
data_dir = pathlib.Path(extracted_path)
|
43 |
+
|
44 |
+
# Print the directory structure to debug
|
45 |
+
for root, dirs, files in os.walk(extracted_path):
|
46 |
+
level = root.replace(extracted_path, '').count(os.sep)
|
47 |
+
indent = ' ' * 4 * (level)
|
48 |
+
print(f"{indent}{os.path.basename(root)}/")
|
49 |
+
subindent = ' ' * 4 * (level + 1)
|
50 |
+
for f in files:
|
51 |
+
print(f"{subindent}{f}")
|
52 |
+
|
53 |
+
# Path to the dataset directory
|
54 |
+
data_dir = pathlib.Path('extracted_files/Pest_Dataset')
|
55 |
+
data_dir = pathlib.Path(data_dir)
|
56 |
+
|
57 |
+
image_count = len(list(data_dir.glob('*/*.jpg')))
|
58 |
+
print(image_count)
|
59 |
+
|
60 |
+
bees = list(data_dir.glob('bees/*'))
|
61 |
+
print(bees[0])
|
62 |
+
PIL.Image.open(str(bees[0]))
|
63 |
+
|
64 |
+
batch_size = 32
|
65 |
+
img_height = 180
|
66 |
+
img_width = 180
|
67 |
+
|
68 |
+
train_ds = tf.keras.utils.image_dataset_from_directory(
|
69 |
+
data_dir,
|
70 |
+
validation_split=0.2,
|
71 |
+
subset="training",
|
72 |
+
seed=123,
|
73 |
+
image_size=(img_height, img_width),
|
74 |
+
batch_size=batch_size)
|
75 |
+
|
76 |
+
|
77 |
+
val_ds = tf.keras.utils.image_dataset_from_directory(
|
78 |
+
data_dir,
|
79 |
+
validation_split=0.2,
|
80 |
+
subset="validation",
|
81 |
+
seed=123,
|
82 |
+
image_size=(img_height, img_width),
|
83 |
+
batch_size=batch_size)
|
84 |
+
|
85 |
+
|
86 |
+
class_names = train_ds.class_names
|
87 |
+
print(class_names)
|
88 |
+
|
89 |
+
plt.figure(figsize=(10, 10))
|
90 |
+
for images, labels in train_ds.take(1):
|
91 |
+
for i in range(9):
|
92 |
+
ax = plt.subplot(3, 3, i + 1)
|
93 |
+
plt.imshow(images[i].numpy().astype("uint8"))
|
94 |
+
plt.title(class_names[labels[i]])
|
95 |
+
plt.axis("off")
|
96 |
+
|
97 |
+
|
98 |
+
for image_batch, labels_batch in train_ds:
|
99 |
+
print(image_batch.shape)
|
100 |
+
print(labels_batch.shape)
|
101 |
+
break
|
102 |
+
|
103 |
+
AUTOTUNE = tf.data.AUTOTUNE
|
104 |
+
|
105 |
+
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
|
106 |
+
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
|
107 |
+
|
108 |
+
|
109 |
+
normalization_layer = layers.Rescaling(1./255)
|
110 |
+
|
111 |
+
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
|
112 |
+
image_batch, labels_batch = next(iter(normalized_ds))
|
113 |
+
first_image = image_batch[0]
|
114 |
+
# Notice the pixel values are now in `[0,1]`.
|
115 |
+
print(np.min(first_image), np.max(first_image))
|
116 |
+
|
117 |
+
data_augmentation = keras.Sequential(
|
118 |
+
[
|
119 |
+
layers.RandomFlip("horizontal",
|
120 |
+
input_shape=(img_height,
|
121 |
+
img_width,
|
122 |
+
3)),
|
123 |
+
layers.RandomRotation(0.1),
|
124 |
+
layers.RandomZoom(0.1),
|
125 |
+
]
|
126 |
+
)
|
127 |
+
|
128 |
+
plt.figure(figsize=(10, 10))
|
129 |
+
for images, _ in train_ds.take(1):
|
130 |
+
for i in range(9):
|
131 |
+
augmented_images = data_augmentation(images)
|
132 |
+
ax = plt.subplot(3, 3, i + 1)
|
133 |
+
plt.imshow(augmented_images[0].numpy().astype("uint8"))
|
134 |
+
plt.axis("off")
|
135 |
+
|
136 |
+
|
137 |
+
from tensorflow.keras.applications import EfficientNetB0
|
138 |
+
|
139 |
+
base_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(img_height, img_width, 3))
|
140 |
+
|
141 |
+
# Freeze the pre-trained weights
|
142 |
+
base_model.trainable = False
|
143 |
+
|
144 |
+
# Create new model on top
|
145 |
+
inputs = keras.Input(shape=(img_height, img_width, 3))
|
146 |
+
x = data_augmentation(inputs) # Apply data augmentation
|
147 |
+
x = base_model(x, training=False)
|
148 |
+
x = keras.layers.GlobalAveragePooling2D()(x)
|
149 |
+
x = keras.layers.Dropout(0.2)(x)
|
150 |
+
outputs = keras.layers.Dense(len(class_names), activation='softmax')(x)
|
151 |
+
|
152 |
+
|
153 |
+
# Compile the model
|
154 |
+
model = keras.Model(inputs, outputs)
|
155 |
+
model.compile(optimizer='adam',
|
156 |
+
loss='sparse_categorical_crossentropy',
|
157 |
+
metrics=['accuracy'])
|
158 |
+
|
159 |
+
model.summary()
|
160 |
+
|
161 |
+
# Train the model
|
162 |
+
epochs = 10
|
163 |
+
history = model.fit(
|
164 |
+
train_ds,
|
165 |
+
validation_data=val_ds,
|
166 |
+
epochs=epochs
|
167 |
+
)
|
168 |
+
|
169 |
+
|
170 |
+
# Plot training history
|
171 |
+
acc = history.history['accuracy']
|
172 |
+
val_acc = history.history['val_accuracy']
|
173 |
+
|
174 |
+
loss = history.history['loss']
|
175 |
+
val_loss = history.history['val_loss']
|
176 |
+
|
177 |
+
epochs_range = range(epochs)
|
178 |
+
|
179 |
+
plt.figure(figsize=(8, 8))
|
180 |
+
plt.subplot(1, 2, 1)
|
181 |
+
plt.plot(epochs_range, acc, label='Training Accuracy')
|
182 |
+
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
|
183 |
+
plt.legend(loc='lower right')
|
184 |
+
plt.title('Training and Validation Accuracy')
|
185 |
+
|
186 |
+
plt.subplot(1, 2, 2)
|
187 |
+
plt.plot(epochs_range, loss, label='Training Loss')
|
188 |
+
plt.plot(epochs_range, val_loss, label='Validation Loss')
|
189 |
+
plt.legend(loc='upper right')
|
190 |
+
plt.title('Training and Validation Loss')
|
191 |
+
plt.show()
|
192 |
+
|
193 |
+
|
194 |
+
# Evaluate the model on the validation dataset
|
195 |
+
results = model.evaluate(val_ds, verbose=0)
|
196 |
+
|
197 |
+
print("Validation Loss: {:.5f}".format(results[0]))
|
198 |
+
print("Validation Accuracy: {:.2f}%".format(results[1] * 100))
|
199 |
+
|
200 |
+
|
201 |
+
import gradio as gr
|
202 |
+
import numpy as np
|
203 |
+
import tensorflow as tf
|
204 |
+
|
205 |
+
def predict_image(img):
|
206 |
+
img = np.array(img)
|
207 |
+
img_resized = tf.image.resize(img, (180, 180))
|
208 |
+
img_4d = tf.expand_dims(img_resized, axis=0)
|
209 |
+
prediction = model.predict(img_4d)[0]
|
210 |
+
return {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
|
211 |
+
|
212 |
+
image = gr.Image()
|
213 |
+
label = gr.Label(num_top_classes=1)
|
214 |
+
|
215 |
+
|
216 |
# Define custom CSS for background image
|
217 |
custom_css = """
|
218 |
body {
|