-
Notifications
You must be signed in to change notification settings - Fork 3
/
backend.py
66 lines (51 loc) · 2.02 KB
/
backend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from flask import Flask, render_template, request
import base64
import re
import boto3
import credentials
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/')
def request_image():
return render_template('webpage.html')
@app.route('/', methods=['POST'])
def get_image():
image_b64 = request.values['imageBase64']
image_data = re.sub(r'^data:image/.+;base64,', '', image_b64)
img = base64.b64decode(image_data)
with open('imageToSave.png', 'wb') as fh:
fh.write(img)
itemList = detect_labels_local_file('imageToSave.png')
print("Labels detected: " + str(itemList))
outputStr = ''
if len(is_recyclable(itemList)) == 0:
outputStr += 'Item is not recyclable'
else:
for item in is_recyclable(itemList):
outputStr += item[0] + ' with ' + str(round(item[1], 2)) + '% confidence : '
if len(is_recyclable(itemList)) > 1:
outputStr += 'Items are recyclable!'
else:
outputStr += 'Item is recyclable!'
return outputStr #whatever this returns is what is printed
def is_recyclable(itemList):
recycleList = ['Plastic', 'Bottle', 'Cardboard', 'Metal', 'Aluminum', 'Can', 'Glass', 'Battery', 'Paper', 'Glass']
recyclables = []
for item in itemList:
if item['Name'] in recycleList:
recyclables.append((item['Name'], item['Confidence']))
print(recyclables)
return recyclables
def detect_labels_local_file(photo):
client = boto3.client('rekognition', region_name='us-west-2', aws_access_key_id=credentials.access_key,
aws_secret_access_key=credentials.secret_key)
with open(photo, 'rb') as image:
response = client.detect_labels(Image={'Bytes': image.read()})
#print('Detected labels in ' + photo)
#for label in response['Labels']:
#print(label['Name'] + ' : ' + str(label['Confidence']))
return response['Labels']
if __name__ == '__main__':
while True:
app.run()