Rausda6 commited on
Commit
947eaf5
·
verified ·
1 Parent(s): a87bcf4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -0
app.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
3
+ from PIL import Image
4
+ import torch
5
+ import numpy as np
6
+ import space
7
+ # Load model and processor from the Hugging Face Hub
8
+ MODEL_REPO = "Rausda6/autotrain-yh172-uui7d" # Replace with your actual model repo name
9
+ model = AutoModelForImageClassification.from_pretrained(MODEL_REPO)
10
+ processor = AutoImageProcessor.from_pretrained(MODEL_REPO)
11
+
12
+ labels = model.config.id2label
13
+ @spaces.GPU
14
+ def classify_image(img: Image.Image):
15
+ inputs = processor(images=img, return_tensors="pt")
16
+ with torch.no_grad():
17
+ outputs = model(**inputs)
18
+ logits = outputs.logits
19
+ probs = torch.nn.functional.softmax(logits, dim=-1)[0]
20
+
21
+ # Build result dictionary with confidence values
22
+ probs_dict = {labels[i]: float(probs[i]) for i in range(len(probs))}
23
+ # Sort and format nicely
24
+ sorted_probs = sorted(probs_dict.items(), key=lambda x: x[1], reverse=True)
25
+ top_label, top_score = sorted_probs[0]
26
+
27
+ return {"Prediction": top_label, "Confidence": f"{top_score:.2%}"}, dict(sorted_probs)
28
+
29
+ # Gradio interface
30
+ demo = gr.Interface(
31
+ fn=classify_image,
32
+ inputs=gr.Image(type="pil"),
33
+ outputs=[gr.Label(label="Top Prediction"), gr.Label(num_top_classes=6, label="Class Probabilities")],
34
+ title="Image Classification with AutoTrain Model",
35
+ description="Upload a JPG image to classify it using the fine-tuned model."
36
+ )
37
+
38
+ demo.launch()