Spaces:
Build error
Build error
Merge branch 'feature/local-model'
Browse files
app.py
CHANGED
|
@@ -5,34 +5,66 @@ import numpy as np
|
|
| 5 |
from io import BytesIO
|
| 6 |
import os
|
| 7 |
from typing import Union
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Make sure to set the environment variable HF_TOKEN to your Hugging Face token for using InferenceClient
|
| 10 |
HF_TOKEN = os.environ.get("HF_TOKEN", "YOUR_HF_TOKEN")
|
| 11 |
client = InferenceClient("microsoft/resnet-50", token=HF_TOKEN)
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
if image is None:
|
| 15 |
return {}
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
# Define the Gradio interface
|
| 33 |
ui = gr.Interface(
|
| 34 |
fn=resnet50,
|
| 35 |
-
inputs=gr.Image(),
|
| 36 |
outputs=gr.Label(num_top_classes=5), # Display top 5 results
|
| 37 |
title="ResNet-50 ImageNet",
|
| 38 |
description="Identify the main object in an image with probabilities. This model is a ResNet-50 neural network pre-trained on ImageNet."
|
|
|
|
| 5 |
from io import BytesIO
|
| 6 |
import os
|
| 7 |
from typing import Union
|
| 8 |
+
from transformers import AutoImageProcessor, ResNetForImageClassification
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
|
| 12 |
# Make sure to set the environment variable HF_TOKEN to your Hugging Face token for using InferenceClient
|
| 13 |
HF_TOKEN = os.environ.get("HF_TOKEN", "YOUR_HF_TOKEN")
|
| 14 |
client = InferenceClient("microsoft/resnet-50", token=HF_TOKEN)
|
| 15 |
|
| 16 |
+
processor = None
|
| 17 |
+
model = None
|
| 18 |
+
|
| 19 |
+
def load_model():
|
| 20 |
+
global processor, model
|
| 21 |
+
print("Loading model...")
|
| 22 |
+
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
|
| 23 |
+
model = ResNetForImageClassification.from_pretrained("microsoft/resnet-50")
|
| 24 |
+
print("Model loaded.")
|
| 25 |
+
|
| 26 |
+
def resnet50(image: Union[np.ndarray, Image.Image, str, None], is_local: bool) -> dict[str, float]:
|
| 27 |
if image is None:
|
| 28 |
return {}
|
| 29 |
|
| 30 |
+
if is_local:
|
| 31 |
+
if processor is None or model is None:
|
| 32 |
+
load_model()
|
| 33 |
+
inputs = processor(image, return_tensors="pt")
|
| 34 |
+
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
logits = model(**inputs).logits
|
| 37 |
+
|
| 38 |
+
# Apply softmax to convert logits to probabilities
|
| 39 |
+
probabilities = F.softmax(logits, dim=-1)[0]
|
| 40 |
+
|
| 41 |
+
# Get the top 5 predicted classes with probabilities
|
| 42 |
+
top_probs, top_labels = torch.topk(probabilities, 5)
|
| 43 |
+
|
| 44 |
+
# Map the label IDs to human-readable class names
|
| 45 |
+
top_predictions = {model.config.id2label[top_labels[i].item()]: top_probs[i].item() for i in range(5)}
|
| 46 |
+
|
| 47 |
+
return top_predictions
|
| 48 |
+
else:
|
| 49 |
+
image_in = image
|
| 50 |
+
# Convert the image to bytes if it is a PIL image or numpy array
|
| 51 |
+
if isinstance(image, np.ndarray):
|
| 52 |
+
image = Image.fromarray(image)
|
| 53 |
+
if isinstance(image, Image.Image):
|
| 54 |
+
image_bytes = BytesIO()
|
| 55 |
+
image.save(image_bytes, format="PNG")
|
| 56 |
+
image_in = image_bytes.getvalue()
|
| 57 |
+
|
| 58 |
+
# Get the model's prediction
|
| 59 |
+
prediction = client.image_classification(image_in)
|
| 60 |
+
# Return the top 5 results
|
| 61 |
+
return {pred.label: pred.score for pred in prediction}
|
| 62 |
|
| 63 |
|
| 64 |
# Define the Gradio interface
|
| 65 |
ui = gr.Interface(
|
| 66 |
fn=resnet50,
|
| 67 |
+
inputs=[gr.Image(), gr.Checkbox(label="Use local model")],
|
| 68 |
outputs=gr.Label(num_top_classes=5), # Display top 5 results
|
| 69 |
title="ResNet-50 ImageNet",
|
| 70 |
description="Identify the main object in an image with probabilities. This model is a ResNet-50 neural network pre-trained on ImageNet."
|