quite new to the programming world and trying to create a Streamlit web app for image classification (GCP AutoML, single-label model, hosted in a GS bucket). I got the following error message; complete code follows below. Your input is appreciated.
UnboundLocalError: cannot access local variable 'image_bytes' where it is not associated with a value
Traceback: File "C:\Python\Python311\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 534, in _run_script exec(code, module.dict) File "D:\OneDrive - XXXXXXX\Desktop\Python\appcopyv4.py", line 66, in predicted_class_name, predicted_class_confidence = predict_image(image_bytes, model_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\OneDrive - XXXXXXX\Desktop\Python\appcopyv4.py", line 22, in predict_image image = np.frombuffer(image_bytes, dtype=np.uint8)
import streamlit as st
from PIL import Image
import numpy as np
from google.cloud import automl_v1beta1
from google.cloud import automl as automl_v1beta1; ImagePayload = automl_v1beta1
from google.cloud.automl_v1beta1 import PredictionServiceClient
from google.oauth2 import service_account
Replace with your project ID and model ID
keyfile_path = 'D:\OneDrive - XXXXXXX\Desktop\Python\xxxxxxxxxxxxx-123456-122s3df4455563.json' # Replace with your key file path
PROJECT_ID = " xxxxxxxxxxxxx-123456"
model_id = "123456798123456789"
Create a client for the AutoML API
client = automl_v1beta1.AutoMlClient.from_service_account_file(keyfile_path)
location = f'https://storage.cloud.google.com/[bucket name]/model-123456798123456789' # Replace with your model's location
Define the function to make predictions using the AutoML model
def predict_image(image, model_id):
# Convert the PIL image to a NumPy array
image = np.frombuffer(image_bytes, dtype=np.uint8)
# Convert the image to bytes based on format
if image.dtype == np.uint8: # JPG or JPEG
image_bytes = image.tobytes()
elif image.dtype == np.uint16: # PNG
image_bytes = image.astype(np.uint8).tobytes()
else:
raise Exception("Unsupported image format")
# Create the prediction request
prediction_request = automl_v1beta1.PredictRequest(
name=f"projects/{PROJECT_ID}/locations/us-central1/models/{model_id}",
image_payload=ImagePayload(image=image_bytes),
)
# Send the request and get the response
prediction_response = client.predict(prediction_request)
# Get the predicted class and confidence score
predicted_class_name = prediction_response.payload[0].classification.top_1_label
predicted_class_confidence = prediction_response.payload[0].classification.top_1_score
return predicted_class_name, predicted_class_confidence
Initialize the Streamlit app
st.title("Image Classification with AutoML")
Upload an image file
uploaded_file = st.file_uploader("Choose an image...", type=["JPG", "JPEG", "PNG"])
Check if an image is uploaded
if uploaded_file is not None:
# Read the uploaded image
image = Image.open(uploaded_file)
# Show the uploaded image
st.image(image, caption="Uploaded Image")
# Extract the image bytes from the uploaded file
image_bytes = uploaded_file.read()
# Pass the image bytes and model ID to the predict_image function
predicted_class_name, predicted_class_confidence = predict_image(image_bytes, model_id)
# Display the prediction
st.write(f"Predicted class: {predicted_class_name}")
st.write(f"Confidence score: {predicted_class_confidence:.2f}")
Thanks for your feedback!