File size: 1,787 Bytes
11b3d03
 
 
 
 
 
2e3ac41
11b3d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import gradio as gr
from transformers import AutoImageProcessor, AutoModelForImageClassification
from PIL import Image
import torch

# Load a pre-trained image classification model
model_name = "Shio-Koube/Anime_filterer"
image_processor = AutoImageProcessor.from_pretrained(model_name)
model = AutoModelForImageClassification.from_pretrained(model_name)

def classify_image(image):
    # Ensure the image is in RGB mode
    if image is None:
        return "No image uploaded"
    
    # Convert image to RGB if needed
    if image.mode != 'RGB':
        image = image.convert('RGB')
    
    # Preprocess the image
    inputs = image_processor(images=image, return_tensors="pt")
    
    # Perform prediction
    with torch.no_grad():
        outputs = model(**inputs)
        logits = outputs.logits
    
    # Get predictions
    probabilities = torch.nn.functional.softmax(logits, dim=-1)
    
    # Get class labels and handle fewer than 5 classes
    labels = model.config.id2label
    num_classes = len(labels)
    
    # Determine number of predictions to show
    top_k = min(num_classes, 3)
    
    # Get top predictions
    top_prob, top_indices = probabilities.topk(top_k)
    
    # Format results
    results = []
    for prob, idx in zip(top_prob[0], top_indices[0]):
        label = labels[idx.item()]
        percentage = prob.item() * 100
        results.append(f"{label}: {percentage:.2f}%")
    
    return "\n".join(results)

# Create Gradio interface
iface = gr.Interface(
    fn=classify_image,
    inputs=gr.Image(type="pil"),
    outputs=gr.Textbox(label="Top Predictions"),
    title="Image Classification with Hugging Face",
    description="Upload an image to get classification predictions"
)

# Launch the app
if __name__ == "__main__":
    iface.launch()