-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
54 lines (37 loc) · 1.42 KB
/
main.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
from google.cloud import storage
import tensorflow as tf
from PIL import Image
import numpy as np
model = None
interpreter = None
input_index = None
output_index = None
class_names = ["Early Blight", "Late Blight", "Healthy"]
BUCKET_NAME = "codebasics-tf-models" # Here you need to put the name of your GCP bucket
def download_blob(bucket_name, source_blob_name, destination_file_name):
"""Downloads a blob from the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(f"Blob {source_blob_name} downloaded to {destination_file_name}.")
def predict(request):
global model
if model is None:
download_blob(
BUCKET_NAME,
"models/potatoes.h5",
"/tmp/potatoes.h5",
)
model = tf.keras.models.load_model("/tmp/potatoes.h5")
image = request.files["file"]
image = np.array(
Image.open(image).convert("RGB").resize((256, 256)) # image resizing
)
image = image/255 # normalize the image in 0 to 1 range
img_array = tf.expand_dims(img, 0)
predictions = model.predict(img_array)
print("Predictions:",predictions)
predicted_class = class_names[np.argmax(predictions[0])]
confidence = round(100 * (np.max(predictions[0])), 2)
return {"class": predicted_class, "confidence": confidence}