Spaces:
Running
Running
from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient | |
from msrest.authentication import ApiKeyCredentials | |
from dotenv import load_dotenv | |
from PIL import Image | |
import os | |
import gradio as gr | |
from io import BytesIO | |
# Get Configuration Settings | |
load_dotenv() | |
prediction_endpoint = os.getenv('PredictionEndpoint') | |
prediction_key = os.getenv('PredictionKey') | |
project_id = os.getenv('ProjectID') | |
model_name = os.getenv('ModelName') | |
def classifyImage(image): | |
try: | |
# Convert PIL Image to bytes | |
image_bytes = BytesIO() | |
image.save(image_bytes, format='JPEG') | |
image_bytes = image_bytes.getvalue() | |
# Authenticate a client for the training API | |
credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key}) | |
prediction_client = CustomVisionPredictionClient(endpoint=prediction_endpoint, credentials=credentials) | |
# Classify test images | |
results = prediction_client.classify_image(project_id, model_name, image_bytes) | |
# Loop over each label prediction and print any with probability > 50% | |
for prediction in results.predictions: | |
if prediction.probability > 0.5: | |
summary = ('{} ({:.0%})'.format(prediction.tag_name, prediction.probability)) | |
return summary | |
except Exception as ex: | |
return None, f"Error: {str(ex)}" | |
title = "Detect 3 types of fruits - Carrot, Cucumber, Pear" | |
interface = gr.Interface( | |
fn=classifyImage, | |
inputs=gr.Image(type="pil", label="Input Image"), | |
outputs=gr.Textbox(label="Fruit detection with confidence level"), | |
title=title, | |
) | |
# Launch the interface | |
interface.launch(share=True) | |