Can't read models from cloud storage, so the app can't predict images

54 views Asked by At

So I deployed the app that I had made to app engine and it was successful. But for some reason when I tried the /predict API I got an error where the image cannot be predicted. I tried testing the API using postman and the output is like this. Postman Test

Even though I have called the storage bucket that stores the model. This is the code I have made

app.py

 import os
 import numpy as np
 import tensorflow as tf
 from flask import Flask, request, jsonify
 #from tensorflow import keras
 #from keras.models import load_model
 from PIL import Image
 from flask_cors import CORS
 
 
 app = Flask(__name__)
 CORS(app)
 
 # global variable
 model = None #model
 #db = None

 # download model file from cloud storage 
 def download_model_file():
     from google.cloud import storage
 
     # model bucket details
     BUCKET_NAME = "spezia-bucket"
     PROJECT_ID = "capstone-spezia"
     GCS_MODEL_FILE = "spezia_model.h5"
 
     # initialise a client
     client = storage.Client(PROJECT_ID)
 
     # create a bucket object for our bucket
     bucket = client.bucket(BUCKET_NAME)
 
     # create a blob object from the filepath
     blob = bucket.blob(GCS_MODEL_FILE)
 
     #with blob.open("r") as model:
     #    print(model.read())
 
     folder = '/tmp/'
     if not os.path.exists(folder) :
         os.makedirs(folder)
     # download the file to a destination
     blob.download_to_filename(folder + "model_spezia.h5")
 
 
 #model = load_model('spezia_model.h5')
 
 @app.route('/')
 def main():
     return 'Welcome to Spezia ML Team API for predict many spices'
 
 @app.route('/predict', methods=['POST'])
 def recognize_image():
     try:
         # deploy model
         global model
         if not model:
             download_model_file()
             model = tf.keras.models.load_model('/tmp/model_spezia.h5')
 
         # open image from request
         img_sample = Image.open(request.files['image'])
         image_path = img_sample
         image_path = image_path.convert('RGB')
         image_path.close()
 
         # prepare image for prediction
         img = np.array(img_sample.resize((150,150)))
         
         x = np.expand_dims(img, axis=0)
         images = np.vstack([x])
         image_path.close()
 
 
         # predict
          prediction_array = model.predict(images)
 
          class_names =  ['asam jawa', 'cengkeh', 'daun jeruk', 'daun salam', 
                         'jahe', 'kayu manis', 'keluak', 'kemiri', 'ketumbar', 
                         'kunyit', 'lada hitam', 'pekak','serai']
         result = {
             'prediction': class_names[np.argmax(prediction_array)],
             'confidence': '{:2.0f}%'.format(100 * np.max(prediction_array))
         }
 
         return jsonify(isError=False, message='Success', statusCode=200, data=result), 200
 
      except Exception as e:
         print(str(e))
         return jsonify(message='Something went wrong'), 500
 
 if __name__ == '__main__':
     app.run(debug=True, port=8080)

requirement.txt

 Flask==2.2.2
 Flask-Cors==3.0.10
 tensorflow==2.11.0
 keras==2.11.0
 numpy==1.23.5
 Pillow==9.3.0
 google-cloud-storage==2.7.0

Thanks for help and sorry for my bad English

0

There are 0 answers