NORLIE JHON MALAGDAO commited on
Commit
05e9cff
·
verified ·
1 Parent(s): 6c13748

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -144
app.py CHANGED
@@ -1,175 +1,125 @@
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
 
8
- from tensorflow import keras
9
- from tensorflow.keras import layers
10
- from tensorflow.keras.models import Sequential
11
- from PIL import Image
12
- import gdown
13
- import zipfile
14
- import pathlib
15
-
16
- # Define the Google Drive shareable link
17
- gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
18
-
19
- # Extract the file ID from the URL
20
- file_id = gdrive_url.split('/d/')[1].split('/view')[0]
21
- direct_download_url = f'https://drive.google.com/uc?id={file_id}'
22
-
23
- # Define the local filename to save the ZIP file
24
- local_zip_file = 'file.zip'
25
-
26
- # Download the ZIP file
27
- gdown.download(direct_download_url, local_zip_file, quiet=False)
28
-
29
- # Directory to extract files
30
- extracted_path = 'extracted_files'
31
-
32
- # Verify if the downloaded file is a ZIP file and extract it
33
- try:
34
- with zipfile.ZipFile(local_zip_file, 'r') as zip_ref:
35
- zip_ref.extractall(extracted_path)
36
- print("Extraction successful!")
37
- except zipfile.BadZipFile:
38
- print("Error: The downloaded file is not a valid ZIP file.")
39
-
40
- # Optionally, you can delete the ZIP file after extraction
41
- os.remove(local_zip_file)
42
-
43
- # Convert the extracted directory path to a pathlib.Path object
44
- data_dir = pathlib.Path(extracted_path)
45
-
46
- # Print the directory structure to debug
47
- for root, dirs, files in os.walk(extracted_path):
48
- level = root.replace(extracted_path, '').count(os.sep)
49
- indent = ' ' * 4 * (level)
50
- print(f"{indent}{os.path.basename(root)}/")
51
- subindent = ' ' * 4 * (level + 1)
52
- for f in files:
53
- print(f"{subindent}{f}")
54
-
55
- # Path to the dataset directory
56
- data_dir = pathlib.Path('extracted_files/Pest_Dataset')
57
-
58
- img_height, img_width = 180, 180
59
- batch_size = 32
60
 
61
- # Load training and validation datasets
62
- train_ds = tf.keras.preprocessing.image_dataset_from_directory(
63
- data_dir,
64
- validation_split=0.2,
65
- subset="training",
66
- seed=123,
67
- image_size=(img_height, img_width),
68
- batch_size=batch_size
69
- )
70
 
71
- val_ds = tf.keras.preprocessing.image_dataset_from_directory(
72
- data_dir,
73
- validation_split=0.2,
74
- subset="validation",
75
- seed=123,
76
- image_size=(img_height, img_width),
77
- batch_size=batch_size
78
- )
 
 
 
 
 
 
 
 
 
 
79
 
80
- # Define data augmentation layers
81
  data_augmentation = keras.Sequential(
82
- [
83
- layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)),
84
- layers.RandomRotation(0.1),
85
- layers.RandomZoom(0.1),
86
- ]
 
 
 
87
  )
88
 
89
- # Define the model
90
- num_classes = len(train_ds.class_names)
 
 
 
 
 
 
 
 
 
91
  model = Sequential([
92
- data_augmentation,
93
- layers.Rescaling(1./255),
94
- layers.Conv2D(16, 3, padding='same', activation='relu'),
95
- layers.MaxPooling2D(),
96
- layers.Conv2D(32, 3, padding='same', activation='relu'),
97
- layers.MaxPooling2D(),
98
- layers.Conv2D(64, 3, padding='same', activation='relu'),
99
- layers.MaxPooling2D(),
100
- layers.Dropout(0.2),
101
- layers.Flatten(),
102
- layers.Dense(128, activation='relu'),
103
- layers.Dense(num_classes, activation='softmax', name="outputs") # Use softmax here
104
  ])
105
 
106
  model.compile(optimizer='adam',
107
- loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), # Change from_logits to False
108
  metrics=['accuracy'])
109
 
110
  model.summary()
111
 
112
- # Train the model
113
  epochs = 15
114
  history = model.fit(
115
- train_ds,
116
- validation_data=val_ds,
117
- epochs=epochs
118
  )
119
 
120
- # Plot training history
121
- plt.plot(history.history['accuracy'], label='accuracy')
122
- plt.plot(history.history['val_accuracy'], label='val_accuracy')
123
- plt.xlabel('Epoch')
124
- plt.ylabel('Accuracy')
125
- plt.legend()
126
- plt.show()
127
-
128
- plt.plot(history.history['loss'], label='loss')
129
- plt.plot(history.history['val_loss'], label='val_loss')
130
- plt.xlabel('Epoch')
131
- plt.ylabel('Loss')
132
- plt.legend()
133
- plt.show()
134
-
135
-
136
-
137
-
138
- # Define category descriptions
139
- category_descriptions = {
140
- "Ants": "Ants are small insects known for their complex social structures and teamwork.",
141
- "Bees": "Bees are flying insects known for their role in pollination and producing honey.",
142
- "Beetles": "Beetles are a group of insects with hard exoskeletons and wings. They are the largest order of insects.",
143
- "Caterpillars": "Caterpillars are the larval stage of butterflies and moths, known for their voracious appetite.",
144
- "Earthworms": "Earthworms are segmented worms that are crucial for soil health and nutrient cycling.",
145
- "Earwigs": "Earwigs are insects with pincers on their abdomen and are known for their nocturnal activity.",
146
- "Grasshoppers": "Grasshoppers are insects known for their powerful hind legs, which they use for jumping.",
147
- "Moths": "Moths are nocturnal insects related to butterflies, known for their attraction to light.",
148
- "Slugs": "Slugs are soft-bodied mollusks that are similar to snails but lack a shell.",
149
- "Snails": "Snails are mollusks with a coiled shell, known for their slow movement and slimy trail.",
150
- "Wasps": "Wasps are stinging insects that can be solitary or social, and some species are important pollinators.",
151
- "Weevils": "Weevils are a type of beetle with a long snout, known for being pests to crops and stored grains."
152
- }
153
 
154
- # Define the prediction function
155
  def predict_image(img):
156
  img = np.array(img)
157
  img_resized = tf.image.resize(img, (180, 180))
158
  img_4d = tf.expand_dims(img_resized, axis=0)
159
  prediction = model.predict(img_4d)[0]
160
- predicted_class = np.argmax(prediction)
161
- predicted_label = class_names[predicted_class]
162
- predicted_description = category_descriptions[predicted_label]
163
- return {predicted_label: f"{float(prediction[predicted_class]):.2f} - {predicted_description}"}
164
 
165
- # Set up Gradio interface
166
  image = gr.Image()
167
- label = gr.Label(num_top_classes=1)
168
 
169
  # Define custom CSS for background image
170
  custom_css = """
171
  body {
172
- background-image: url('extracted_files/Pest_Dataset/bees/bees (444).jpg');
173
  background-size: cover;
174
  background-repeat: no-repeat;
175
  background-attachment: fixed;
@@ -181,8 +131,7 @@ gr.Interface(
181
  fn=predict_image,
182
  inputs=image,
183
  outputs=label,
184
- title="Welcome to Agricultural Pest Image Classification",
185
- description="The image data set used was obtained from Kaggle and has a collection of 12 different types of agricultural pests: Ants, Bees, Beetles, Caterpillars, Earthworms, Earwigs, Grasshoppers, Moths, Slugs, Snails, Wasps, and Weevils",
186
  css=custom_css
187
- ).launch(debug=True)
188
-
 
1
+ batch_size = 32
2
+ img_height = 180
3
+ img_width = 180
4
+
5
+ train_ds = tf.keras.utils.image_dataset_from_directory(
6
+ data_dir,
7
+ validation_split=0.2,
8
+ subset="training",
9
+ seed=123,
10
+ image_size=(img_height, img_width),
11
+ batch_size=batch_size)
12
+
13
+ val_ds = tf.keras.utils.image_dataset_from_directory(
14
+ data_dir,
15
+ validation_split=0.2,
16
+ subset="validation",
17
+ seed=123,
18
+ image_size=(img_height, img_width),
19
+ batch_size=batch_size)
20
+
21
+ class_names = train_ds.class_names
22
+ print(class_names)
23
+
24
  import matplotlib.pyplot as plt
 
 
 
 
25
 
26
+ plt.figure(figsize=(10, 10))
27
+ for images, labels in train_ds.take(1):
28
+ for i in range(9):
29
+ ax = plt.subplot(3, 3, i + 1)
30
+ plt.imshow(images[i].numpy().astype("uint8"))
31
+ plt.title(class_names[labels[i]])
32
+ plt.axis("off")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
 
 
 
 
 
 
 
 
 
34
 
35
+ for image_batch, labels_batch in train_ds:
36
+ print(image_batch.shape)
37
+ print(labels_batch.shape)
38
+ break
39
+
40
+
41
+ AUTOTUNE = tf.data.AUTOTUNE
42
+
43
+ train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
44
+ val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
45
+
46
+ normalization_layer = layers.Rescaling(1./255)
47
+
48
+ normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
49
+ image_batch, labels_batch = next(iter(normalized_ds))
50
+ first_image = image_batch[0]
51
+ # Notice the pixel values are now in `[0,1]`.
52
+ print(np.min(first_image), np.max(first_image))
53
 
 
54
  data_augmentation = keras.Sequential(
55
+ [
56
+ layers.RandomFlip("horizontal",
57
+ input_shape=(img_height,
58
+ img_width,
59
+ 3)),
60
+ layers.RandomRotation(0.1),
61
+ layers.RandomZoom(0.1),
62
+ ]
63
  )
64
 
65
+
66
+ plt.figure(figsize=(10, 10))
67
+ for images, _ in train_ds.take(1):
68
+ for i in range(9):
69
+ augmented_images = data_augmentation(images)
70
+ ax = plt.subplot(3, 3, i + 1)
71
+ plt.imshow(augmented_images[0].numpy().astype("uint8"))
72
+ plt.axis("off")
73
+
74
+ num_classes = len(class_names)
75
+
76
  model = Sequential([
77
+ data_augmentation,
78
+ layers.Rescaling(1./255),
79
+ layers.Conv2D(16, 3, padding='same', activation='relu'),
80
+ layers.MaxPooling2D(),
81
+ layers.Conv2D(32, 3, padding='same', activation='relu'),
82
+ layers.MaxPooling2D(),
83
+ layers.Conv2D(64, 3, padding='same', activation='relu'),
84
+ layers.MaxPooling2D(),
85
+ layers.Dropout(0.2),
86
+ layers.Flatten(),
87
+ layers.Dense(128, activation='relu'),
88
+ layers.Dense(num_classes, name="outputs")
89
  ])
90
 
91
  model.compile(optimizer='adam',
92
+ loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
93
  metrics=['accuracy'])
94
 
95
  model.summary()
96
 
 
97
  epochs = 15
98
  history = model.fit(
99
+ train_ds,
100
+ validation_data=val_ds,
101
+ epochs=epochs
102
  )
103
 
104
+ import gradio as gr
105
+ import numpy as np
106
+ import tensorflow as tf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
 
108
  def predict_image(img):
109
  img = np.array(img)
110
  img_resized = tf.image.resize(img, (180, 180))
111
  img_4d = tf.expand_dims(img_resized, axis=0)
112
  prediction = model.predict(img_4d)[0]
113
+ return {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
114
+
 
 
115
 
 
116
  image = gr.Image()
117
+ label = gr.Label(num_top_classes=12)
118
 
119
  # Define custom CSS for background image
120
  custom_css = """
121
  body {
122
+ background-image: url('\extracted_files\Pest_Dataset\bees\bees (444).jpg');
123
  background-size: cover;
124
  background-repeat: no-repeat;
125
  background-attachment: fixed;
 
131
  fn=predict_image,
132
  inputs=image,
133
  outputs=label,
134
+ title="Pest Classification",
135
+ description="Upload an image of a pest to classify it into one of the predefined categories.",
136
  css=custom_css
137
+ ).launch(debug=True)