-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
70 lines (45 loc) · 1.51 KB
/
lambda_function.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
67
#!/usr/bin/env python
# coding: utf-8
# for array operations
import numpy as np
# for img download from url
from io import BytesIO
from urllib import request
# for img preprocessing
from PIL import Image
# for running tflite model
import tflite_runtime.interpreter as tflite
def download_image(url):
with request.urlopen(url) as resp:
buffer = resp.read()
stream = BytesIO(buffer)
img = Image.open(stream)
return img
def prepare_image(img, target_size):
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize(target_size, Image.NEAREST)
return img
# to replace
# with Image.open('1280px-Smaug_par_David_Demaret.jpg') as img:
# img = img.resize((150, 150), Image.NEAREST)
interpreter = tflite.Interpreter(model_path = 'dino_dragon.tflite')
input_index = interpreter.get_input_details()[0]['index']
output_index = interpreter.get_output_details()[0]['index']
classes = ['dragon', 'dino']
###
def predict(url):
img = download_image(url)
img = prepare_image(img, (150, 150))
x = np.array(img, dtype='float32')
X = np.array([x]) / 255
interpreter.allocate_tensors()
interpreter.set_tensor(input_index, X)
interpreter.invoke()
preds = [float(interpreter.get_tensor(output_index)[0][0]), \
float(1-interpreter.get_tensor(output_index)[0][0])]
return(dict(zip(classes, preds)))
def lambda_handler(event, context):
url = event['url']
result = predict(url)
return(result)