NORLIE JHON MALAGDAO commited on
Commit
5e0f68f
·
verified ·
1 Parent(s): 6f29b97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -49
app.py CHANGED
@@ -15,6 +15,8 @@ import gdown
15
  import zipfile
16
  import pathlib
17
 
 
 
18
  # Define the Google Drive shareable link
19
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
20
 
@@ -53,77 +55,87 @@ for root, dirs, files in os.walk(extracted_path):
53
  subindent = ' ' * 4 * (level + 1)
54
  for f in files:
55
  print(f"{subindent}{f}")
 
56
 
 
 
57
  # Path to the dataset directory
58
  data_dir = pathlib.Path('extracted_files/Pest_Dataset')
 
59
 
60
- img_height, img_width = 180, 180
61
- batch_size = 32
 
62
 
 
 
63
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
64
- data_dir,
65
- validation_split=0.2,
66
- subset="training",
67
- seed=123,
68
- image_size=(img_height, img_width),
69
- batch_size=batch_size
70
- )
71
 
72
  val_ds = tf.keras.preprocessing.image_dataset_from_directory(
73
- data_dir,
74
- validation_split=0.2,
75
- subset="validation",
76
- seed=123,
77
- image_size=(img_height, img_width),
78
- batch_size=batch_size
79
- )
 
80
 
81
  class_names = train_ds.class_names
82
  print(class_names)
83
 
 
 
 
84
  plt.figure(figsize=(10, 10))
85
  for images, labels in train_ds.take(1):
86
- for i in range(9):
87
- ax = plt.subplot(3, 3, i + 1)
88
- plt.imshow(images[i].numpy().astype("uint8"))
89
- plt.title(class_names[labels[i]])
90
- plt.axis("off")
91
-
92
- # Define data augmentation
93
- data_augmentation = keras.Sequential([
94
- layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)),
95
- layers.RandomRotation(0.1),
96
- layers.RandomZoom(0.1),
97
- ])
98
 
99
  num_classes = 12
100
 
101
  model = Sequential([
102
- data_augmentation,
103
- layers.Rescaling(1./255),
104
- layers.Conv2D(16, 3, padding='same', activation='relu'),
105
- layers.MaxPooling2D(),
106
- layers.Conv2D(32, 3, padding='same', activation='relu'),
107
- layers.MaxPooling2D(),
108
- layers.Conv2D(64, 3, padding='same', activation='relu'),
109
- layers.MaxPooling2D(),
110
- layers.Dropout(0.2),
111
- layers.Flatten(),
112
- layers.Dense(128, activation='relu'),
113
- layers.Dense(num_classes, name="outputs")
114
  ])
115
 
 
116
  model.compile(optimizer='adam',
117
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
118
  metrics=['accuracy'])
119
 
120
- epochs = 10
121
  history = model.fit(
122
- train_ds,
123
- validation_data=val_ds,
124
- epochs=epochs
125
  )
126
 
 
 
 
 
 
 
127
  def predict_image(img):
128
  img = np.array(img)
129
  img_resized = tf.image.resize(img, (180, 180))
@@ -131,13 +143,26 @@ def predict_image(img):
131
  prediction = model.predict(img_4d)[0]
132
  return {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
133
 
134
- image = gr.Image()
 
135
  label = gr.Label(num_top_classes=5)
136
 
 
 
 
 
 
 
 
 
 
 
 
137
  gr.Interface(
138
- fn=predict_image,
139
- inputs=image,
140
- outputs=label,
141
  title="Pest Classification",
142
- description="Upload an image of a pest to classify it into one of the predefined categories."
 
143
  ).launch(debug=True)
 
15
  import zipfile
16
  import pathlib
17
 
18
+
19
+
20
  # Define the Google Drive shareable link
21
  gdrive_url = 'https://drive.google.com/file/d/1HjHYlQyRz5oWt8kehkt1TiOGRRlKFsv8/view?usp=drive_link'
22
 
 
55
  subindent = ' ' * 4 * (level + 1)
56
  for f in files:
57
  print(f"{subindent}{f}")
58
+
59
 
60
+ # Path to the dataset directory
61
+ import pathlib
62
  # Path to the dataset directory
63
  data_dir = pathlib.Path('extracted_files/Pest_Dataset')
64
+ data_dir = pathlib.Path(data_dir)
65
 
66
+ bees = list(data_dir.glob('bees/*'))
67
+ print(bees[0])
68
+ PIL.Image.open(str(bees[0]))
69
 
70
+ img_height,img_width=180,180
71
+ batch_size=32
72
  train_ds = tf.keras.preprocessing.image_dataset_from_directory(
73
+ data_dir,
74
+ validation_split=0.2,
75
+ subset="training",
76
+ seed=123,
77
+ image_size=(img_height, img_width),
78
+ batch_size=batch_size)
79
+
80
 
81
  val_ds = tf.keras.preprocessing.image_dataset_from_directory(
82
+ data_dir,
83
+ validation_split=0.2,
84
+ subset="validation",
85
+ seed=123,
86
+ image_size=(img_height, img_width),
87
+ batch_size=batch_size)
88
+
89
+
90
 
91
  class_names = train_ds.class_names
92
  print(class_names)
93
 
94
+
95
+ import matplotlib.pyplot as plt
96
+
97
  plt.figure(figsize=(10, 10))
98
  for images, labels in train_ds.take(1):
99
+ for i in range(9):
100
+ ax = plt.subplot(3, 3, i + 1)
101
+ plt.imshow(images[i].numpy().astype("uint8"))
102
+ plt.title(class_names[labels[i]])
103
+ plt.axis("off")
104
+
 
 
 
 
 
 
105
 
106
  num_classes = 12
107
 
108
  model = Sequential([
109
+ layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
110
+ layers.Conv2D(16, 3, padding='same', activation='relu'),
111
+ layers.MaxPooling2D(),
112
+ layers.Conv2D(32, 3, padding='same', activation='relu'),
113
+ layers.MaxPooling2D(),
114
+ layers.Conv2D(64, 3, padding='same', activation='relu'),
115
+ layers.MaxPooling2D(),
116
+ layers.Flatten(),
117
+ layers.Dense(128, activation='relu'),
118
+ layers.Dense(num_classes,activation='softmax')
 
 
119
  ])
120
 
121
+
122
  model.compile(optimizer='adam',
123
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
124
  metrics=['accuracy'])
125
 
126
+ epochs=10
127
  history = model.fit(
128
+ train_ds,
129
+ validation_data=val_ds,
130
+ epochs=epochs
131
  )
132
 
133
+
134
+
135
+ import gradio as gr
136
+ import numpy as np
137
+ import tensorflow as tf
138
+
139
  def predict_image(img):
140
  img = np.array(img)
141
  img_resized = tf.image.resize(img, (180, 180))
 
143
  prediction = model.predict(img_4d)[0]
144
  return {class_names[i]: float(prediction[i]) for i in range(len(class_names))}
145
 
146
+
147
+ image = gr.Image()
148
  label = gr.Label(num_top_classes=5)
149
 
150
+ # Define custom CSS for background image
151
+ custom_css = """
152
+ body {
153
+ background-image: url('\extracted_files\Pest_Dataset\bees\bees (444).jpg');
154
+ background-size: cover;
155
+ background-repeat: no-repeat;
156
+ background-attachment: fixed;
157
+ color: white;
158
+ }
159
+ """
160
+
161
  gr.Interface(
162
+ fn=predict_image,
163
+ inputs=image,
164
+ outputs=label,
165
  title="Pest Classification",
166
+ description="Upload an image of a pest to classify it into one of the predefined categories.",
167
+ css=custom_css
168
  ).launch(debug=True)