Spaces:
Running
Running
Patrick Daniel
commited on
Commit
·
412cf06
1
Parent(s):
137a91d
Initial commit
Browse files- .DS_Store +0 -0
- app.py +42 -0
- requirments.txt +5 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from transformers import ViTForImageClassification, ViTImageProcessor
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# Load model and processor from Hugging Face Hub
|
| 9 |
+
model = ViTForImageClassification.from_pretrained("patcdaniel/phytoViT_508k_20250611")
|
| 10 |
+
processor = ViTImageProcessor.from_pretrained("patcdaniel/phytoViT_508k_20250611")
|
| 11 |
+
model.eval()
|
| 12 |
+
|
| 13 |
+
# Load class labels from hosted file
|
| 14 |
+
LABELS_URL = "https://huggingface.co/patcdaniel/phytoViT_508k_20250611/resolve/main/label_names.json"
|
| 15 |
+
class_labels = requests.get(LABELS_URL).json()
|
| 16 |
+
|
| 17 |
+
def predict(image):
|
| 18 |
+
image = image.convert("RGB")
|
| 19 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 20 |
+
with torch.no_grad():
|
| 21 |
+
logits = model(**inputs).logits
|
| 22 |
+
probs = torch.nn.functional.softmax(logits, dim=-1).squeeze()
|
| 23 |
+
|
| 24 |
+
# Get top 2 predictions
|
| 25 |
+
topk = torch.topk(probs, k=2)
|
| 26 |
+
top_scores = topk.values.tolist()
|
| 27 |
+
top_labels = [class_labels[i] for i in topk.indices.tolist()]
|
| 28 |
+
|
| 29 |
+
# Format output
|
| 30 |
+
output = {label: round(score, 4) for label, score in zip(top_labels, top_scores)}
|
| 31 |
+
return output
|
| 32 |
+
|
| 33 |
+
# Gradio interface
|
| 34 |
+
demo = gr.Interface(
|
| 35 |
+
fn=predict,
|
| 36 |
+
inputs=gr.Image(type="pil", label="Upload or Paste an Image"),
|
| 37 |
+
outputs=gr.Label(num_top_classes=2, label="Top Predictions"),
|
| 38 |
+
title="PhytoViT Classifier",
|
| 39 |
+
description="Upload an IFCB phytoplankton image or paste an image URL to classify it using a ViT model trained on 508k examples."
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
demo.launch()
|
requirments.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch
|
| 3 |
+
transformers
|
| 4 |
+
Pillow
|
| 5 |
+
requests
|