Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
from tkinter import Tk, filedialog
|
4 |
+
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
|
5 |
+
|
6 |
+
# Load the model and feature extractor from Hugging Face
|
7 |
+
MODEL_NAME = "shaktibiplab/Animal-Classification"
|
8 |
+
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
|
9 |
+
extractor = AutoFeatureExtractor.from_pretrained(MODEL_NAME)
|
10 |
+
|
11 |
+
# Function to load and preprocess the image
|
12 |
+
def load_and_preprocess_image(image_path):
|
13 |
+
image = Image.open(image_path).convert("RGB")
|
14 |
+
return image
|
15 |
+
|
16 |
+
# Function to classify the image
|
17 |
+
def classify_image(image_path):
|
18 |
+
image = load_and_preprocess_image(image_path)
|
19 |
+
inputs = extractor(images=image, return_tensors="pt")
|
20 |
+
outputs = model(**inputs)
|
21 |
+
logits = outputs.logits
|
22 |
+
predicted_class_idx = logits.argmax(-1).item()
|
23 |
+
return model.config.id2label[predicted_class_idx]
|
24 |
+
|
25 |
+
# Main program with file upload dialog
|
26 |
+
if __name__ == "__main__":
|
27 |
+
root = Tk()
|
28 |
+
root.withdraw() # Hide the main tkinter window
|
29 |
+
print("Please select an image file.")
|
30 |
+
|
31 |
+
# Open a file dialog to select the image
|
32 |
+
image_path = filedialog.askopenfilename(
|
33 |
+
title="Select an Image",
|
34 |
+
filetypes=[("Image Files", "*.jpg *.jpeg *.png *.bmp *.tiff")]
|
35 |
+
)
|
36 |
+
|
37 |
+
if image_path:
|
38 |
+
try:
|
39 |
+
predicted_class = classify_image(image_path)
|
40 |
+
print(f"Predicted Class: {predicted_class}")
|
41 |
+
except Exception as e:
|
42 |
+
print(f"Error: {e}")
|
43 |
+
else:
|
44 |
+
print("No file selected.")
|