Spaces:
Runtime error
Runtime error
Update app.py
Browse files17 unmodified lines18192021222324252122232425272829262728293132303132333435363738394034354243444536373847484950515253545556575859606162394041424344454647484917 unmodified linesclass_names = ["Ajloun Castle", "Jeresh", "Petra", "Roman amphitheater", "Umm_Qais", "Wadi_Rum"]
def classify_image(img, model_choice): def preprocess_input(img, model): # Placeholder for preprocessing steps # Replace with actual preprocessing steps based on the model processed_img = img / 255.0 return processed_img # Resize the input image based on the selected model's expected input shape input_size = (150, 150) # Assuming a common input size for all models img = tf.image.resize(img, input_size) img = image.img_to_array(img)
# Keep the input size as (150, 150) since your model expects that size input_size = (150, 150) img_resized = cv2.resize(img, input_size) # Preprocess input based on the selected model tokenizer = AutoTokenizer.from_pretrained(model_choice) inputs = tokenizer(images=img, return_tensors="tf", padding=True)
# Preprocess the input image img_preprocessed = preprocess_input(img_resized, model_choice) # Make predictions based on the selected model model = AutoModelForImageClassification.from_pretrained(model_choice) predictions = model(**inputs).logits
# Run inference based on the selected model model = { "ResNet": onnx_resnet_model, "EfficientNet": onnx_efficientnet_model, "VGGNet": onnx_vggnet_model, # "InceptionV3": onnx_inception_model # Uncomment or remove based on your needs }[model_choice] class_idx = tf.argmax(predictions[0])
try: predictions = model.run(None, {"input": img_preprocessed}) class_idx = np.argmax(predictions) class_name = class_names[class_idx] # Map class index to class name class_name = tokenizer.convert_ids_to_tokens(class_idx.numpy())
# Get the top 3 predictions top_predictions = sorted(enumerate(predictions[0]), key=lambda x: x[1], reverse=True)[:3] top_classes = [class_names[idx] for idx, _ in top_predictions] top_probs = [round(prob * 100, 2) for _, prob in top_predictions]
result = { "Original Image": img.tolist(), # Convert to list for compatibility with Gradio "Resized Image": img_resized.tolist(), f"Predicted class using {model_choice}": class_name, "Top 3 Predictions": list(zip(top_classes, top_probs)), "Confidence Scores": predictions[0].tolist() } except Exception as e: result = {"Error": str(e)}
return result # Return the predicted class name as a string return f"Predicted class using {model_choice}: {class_name}"
# Example usageimg = tf.random.normal(shape=(224, 224, 3)) # Replace with your image datamodel_choice = "facebook/vit-base-patch16-224-in21k-finetuned-image-coco" # Replace with your desired modelresult = classify_image(img, model_choice)print(result)image_input = gr.Image()
# Create a Gradio interface with a dropdown for model selectionapp.py+20-37