Spaces:
Sleeping
Sleeping
Ariel
commited on
Commit
•
db12d78
1
Parent(s):
dea59ea
Upload files
Browse files- Bins.json +1 -0
- README.md +7 -6
- app.py +29 -0
- images/bottle2.jpg +0 -0
- images/can2.jpg +0 -0
- images/compost2.jpg +0 -0
- images/logo.png +0 -0
- images/wine2.jpg +0 -0
- predict.py +166 -0
- requirements.txt +0 -0
Bins.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"output_class": ["Plastic bottle/Can to deposit in Supermarkets", "Big Cardboard bin", "Unrecyclable garbage", "Glass - Purple bin", "Organic waste - Composter", "Grocery Packages - Orange bin", "Paper - Blue bin"], "bin_images": ["https://ynet-pic1.yit.co.il/cdn-cgi/image/format=auto/picserver5/crop_images/2021/11/30/S1WrTikNKK/S1WrTikNKK_0_360_768_432_0_x-large.jpg", "https://www.greenkoala.co.il/wp-content/uploads/2017/08/WhatsApp-Image-2021-09-29-at-13.12.20.jpeg", "https://mediline.org.il/sites/mediline/cache/w_500,h_500,mode_pad/ofktpql3.jpg", "https://www.tmir.org.il/Download/Gallery/660-260-186_Pah_Sagol_pics4_14112021115647.jpg", "https://static.aujardin.info/cache/th/img9/composter-600x450.jpg", "https://cdn.speedsize.com/bce19381-5898-42c8-b41a-5fe7eb41262f/https://d3m9l0v76dty0.cloudfront.net/system/photos/1772748/large/5613563632c45ebfb2b39031b8090a51.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRn8eiuf5_6L6Lh5lDaFxwezeyZSVpk2PDOjYrH0cXDHDqihG5aBt3V7AlfvYSST3mdLvw&usqp=CAU"]}
|
README.md
CHANGED
@@ -1,13 +1,14 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 4.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: apache-2.0
|
11 |
---
|
|
|
12 |
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: SmartWaste
|
3 |
+
emoji: 🐢
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: red
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 4.10.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: apache-2.0
|
11 |
---
|
12 |
+
For more info check the git repo at https://github.com/ArielDrabkin/SmartWaste
|
13 |
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from predict import image_identity
|
2 |
+
import gradio as gr
|
3 |
+
import os
|
4 |
+
|
5 |
+
with gr.Blocks(theme='JohnSmith9982/small_and_pretty') as iface:
|
6 |
+
logo_url = os.path.join(os.path.dirname(__file__), "images/logo.png")
|
7 |
+
# Displaying the logo
|
8 |
+
with gr.Row(elem_classes="center-image"):
|
9 |
+
gr.Image(logo_url, show_label=False, show_download_button=False,
|
10 |
+
show_share_button=False)
|
11 |
+
iface_main = gr.Interface(image_identity,
|
12 |
+
inputs = gr.Image(label="Upload your image"), # Adding a label to the input
|
13 |
+
outputs = [gr.Image(type="numpy", label="Predicted bin"), gr.Textbox(label="Prediction 1"),
|
14 |
+
gr.Textbox(label="Probability"),
|
15 |
+
gr.Textbox(label="Prediction 2"), gr.Textbox(label="Probability"),
|
16 |
+
gr.Textbox(label="Prediction Time")],
|
17 |
+
# Adding a description
|
18 |
+
description="This application is an image recognition app that identifies recyclable objects and provides feedback on the appropriate bin for waste disposal.",
|
19 |
+
examples=[['images/bottle2.jpg'],
|
20 |
+
['images/can2.jpg'],
|
21 |
+
['images/wine2.jpg'],
|
22 |
+
['images/compost2.jpg']],
|
23 |
+
cache_examples=False) # Disabling caching
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
if __name__ == "__main__":
|
28 |
+
# Launch the interface
|
29 |
+
iface.launch(share=False)
|
images/bottle2.jpg
ADDED
images/can2.jpg
ADDED
images/compost2.jpg
ADDED
images/logo.png
ADDED
images/wine2.jpg
ADDED
predict.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from keras.models import load_model
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
import requests
|
5 |
+
from io import BytesIO
|
6 |
+
import timeit
|
7 |
+
import gdown
|
8 |
+
import json
|
9 |
+
import os
|
10 |
+
|
11 |
+
# Define the class labels for the model's output
|
12 |
+
|
13 |
+
# output_class = ["Plastic bottle/Can to deposit in Supermarkets", "Big Cardboard bin", "Unrecyclable garbage", "Glass - Purple bin", "Organic waste - Composter", "Grocery Packages - Orange bin", "Paper - Blue bin"]
|
14 |
+
|
15 |
+
with open('Bins.json', 'r') as f:
|
16 |
+
bins_dict = json.load(f)
|
17 |
+
output_class = bins_dict["output_class"]
|
18 |
+
|
19 |
+
url = "https://drive.google.com/uc?id=1TJSpf9wJYZSqIm5ytqXkU8RLuKJmmHHa"
|
20 |
+
output = 'vgg16_model_after_one_epoch.h5'
|
21 |
+
|
22 |
+
# check if path to file exist
|
23 |
+
if not os.path.exists(output):
|
24 |
+
gdown.download(url, output, quiet=False)
|
25 |
+
|
26 |
+
# Load the pre-trained model
|
27 |
+
model = load_model(output)
|
28 |
+
|
29 |
+
|
30 |
+
def predict(img_input, is_url=False):
|
31 |
+
"""
|
32 |
+
Function to predict the class labels and probabilities of an input image.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
file (str): Path to the input image file or URL.
|
36 |
+
is_url (bool): Indicates whether the file argument is a URL or local file path.
|
37 |
+
|
38 |
+
Returns:
|
39 |
+
dict: A dictionary containing the predicted class labels as keys and
|
40 |
+
their corresponding probabilities as values.
|
41 |
+
"""
|
42 |
+
if isinstance(img_input, str):
|
43 |
+
if is_url is True:
|
44 |
+
# Download the image from the URL
|
45 |
+
response = requests.get(img_input)
|
46 |
+
img = Image.open(BytesIO(response.content))
|
47 |
+
else:
|
48 |
+
# Open the image file from the local file path
|
49 |
+
img = Image.open(img_input)
|
50 |
+
else:
|
51 |
+
img = img_input
|
52 |
+
|
53 |
+
# Resize the image to match the input size expected by the model (224x224)
|
54 |
+
resized_image = img.resize((224, 224))
|
55 |
+
|
56 |
+
# Normalize the pixel values to be between 0 and 1
|
57 |
+
normalized_image = np.array(resized_image) / 255.0
|
58 |
+
|
59 |
+
# Expand dimensions to match the input shape expected by the model
|
60 |
+
pred_image = np.expand_dims(normalized_image, axis=0)
|
61 |
+
|
62 |
+
# Make predictions using the model
|
63 |
+
predicted_array = model.predict(pred_image)
|
64 |
+
|
65 |
+
# Create a dictionary of predicted class labels and probabilities
|
66 |
+
pred_labels_and_probs = {
|
67 |
+
output_class[i]: float(predicted_array[0][i])
|
68 |
+
for i in range(len(output_class))
|
69 |
+
}
|
70 |
+
|
71 |
+
return pred_labels_and_probs
|
72 |
+
|
73 |
+
|
74 |
+
def image_identity(image):
|
75 |
+
"""
|
76 |
+
Take an image as input and return prediction information and an image of the predicted waste bin.
|
77 |
+
|
78 |
+
Parameters:
|
79 |
+
image (np.array): An image in numpy array format.
|
80 |
+
|
81 |
+
Returns:
|
82 |
+
bin_image1 (np.array): An image of the predicted waste bin.
|
83 |
+
predicted_class1 (str): The class of the predicted bin.
|
84 |
+
predicted_prob1 (float): The probability of the predicted class.
|
85 |
+
predicted_class2 (str): The second most likely class.
|
86 |
+
predicted_prob2 (float): The probability of the second most likely class.
|
87 |
+
prediction_time (str): The time taken to make the prediction.
|
88 |
+
"""
|
89 |
+
image = Image.fromarray((image * 255).astype(np.uint8))
|
90 |
+
|
91 |
+
# Load the classification and image data from the JSON file
|
92 |
+
with open('Bins.json', 'r') as f:
|
93 |
+
bins_dict = json.load(f)
|
94 |
+
|
95 |
+
# Retrieve the class labels and bin images from the dictionary
|
96 |
+
output_class = bins_dict["output_class"]
|
97 |
+
bin_images = bins_dict["bin_images"]
|
98 |
+
|
99 |
+
# Record the start time before making predictions
|
100 |
+
start_time = timeit.default_timer()
|
101 |
+
|
102 |
+
# Make predictions on the provided image
|
103 |
+
predicted_class1, predicted_prob1, predicted_class2, predicted_prob2 = check_item(image)
|
104 |
+
|
105 |
+
# Record the end time after making predictions and calculate the total time taken
|
106 |
+
end_time = timeit.default_timer()
|
107 |
+
pred_time = round(end_time - start_time, 2)
|
108 |
+
prediction_time = f"{pred_time} seconds"
|
109 |
+
|
110 |
+
# Retrieve the image URL of the predicted bin
|
111 |
+
bin_1 = output_class.index(predicted_class1)
|
112 |
+
bin_image_url1 = bin_images[bin_1]
|
113 |
+
response1 = requests.get(bin_image_url1)
|
114 |
+
|
115 |
+
# Open the image and convert to a numpy array for returning
|
116 |
+
bin_image1 = Image.open(BytesIO(response1.content))
|
117 |
+
bin_image1 = np.array(bin_image1)
|
118 |
+
|
119 |
+
return bin_image1, predicted_class1, predicted_prob1, predicted_class2, predicted_prob2, prediction_time
|
120 |
+
|
121 |
+
|
122 |
+
def check_item(file_path, is_url=False):
|
123 |
+
"""
|
124 |
+
Function to make predictions on an input image and compare the results with the expected classes.
|
125 |
+
|
126 |
+
Args:
|
127 |
+
file_path (str): Path to the input image file or URL.
|
128 |
+
is_url (bool): Indicates whether the file argument is a URL or local file path.
|
129 |
+
"""
|
130 |
+
# Obtain the predicted class labels and probabilities
|
131 |
+
prediction_dict = predict(file_path, is_url)
|
132 |
+
|
133 |
+
# Get the index of the highest prediction
|
134 |
+
ind = np.argmax(list(prediction_dict.values()))
|
135 |
+
predicted_class = list(prediction_dict.keys())[ind]
|
136 |
+
predicted_prob = list(prediction_dict.values())[ind]
|
137 |
+
predicted_prob = f"{predicted_prob:.2f}"
|
138 |
+
print(f"1st Prediction probabilities: {predicted_class} {predicted_prob}")
|
139 |
+
|
140 |
+
# Get the index of the second highest prediction
|
141 |
+
sorted_probs = np.sort(list(prediction_dict.values()))
|
142 |
+
ind2 = np.argsort(list(prediction_dict.values()))[-2]
|
143 |
+
predicted_class2 = list(prediction_dict.keys())[ind2]
|
144 |
+
predicted_prob2 = sorted_probs[-2]
|
145 |
+
predicted_prob2 = f"{predicted_prob2:.2f}"
|
146 |
+
print(f"2nd Prediction probabilities: {predicted_class2} {predicted_prob2}")
|
147 |
+
return predicted_class, predicted_prob, predicted_class2, predicted_prob2
|
148 |
+
|
149 |
+
|
150 |
+
if __name__ == "__main__":
|
151 |
+
# Prompt the user to enter the file path to the input image
|
152 |
+
file_path = input("Enter the file path or URL to the input image: ")
|
153 |
+
|
154 |
+
# Prompt the user to indicate if the input is a URL or a local file path
|
155 |
+
is_url = input("Is the input a URL? (y/n): ").lower() == "y"
|
156 |
+
|
157 |
+
# Measure the time taken to make predictions
|
158 |
+
start_time = timeit.default_timer()
|
159 |
+
|
160 |
+
# Make predictions and compare with expected results
|
161 |
+
check_item(file_path, is_url)
|
162 |
+
|
163 |
+
# Calculate and print the prediction time
|
164 |
+
end_time = timeit.default_timer()
|
165 |
+
pred_time = round(end_time - start_time, 2)
|
166 |
+
print("Prediction time:", pred_time, "seconds")
|
requirements.txt
ADDED
Binary file (130 Bytes). View file
|
|