File size: 1,611 Bytes
40b3df0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline
from PIL import Image
import torch


clf = pipeline(
    task="zero-shot-image-classification",
    model="openai/clip-vit-large-patch14",   # 100 % open weights
    device=0 if torch.cuda.is_available() else -1
)

def classify(image: Image.Image, labels: str) -> dict:
    """
    image : PIL image uploaded by user
    labels: comma-separated string, e.g. 'cat,dog,horse'
    """
    if image is None:
        return {}
    candidate_labels = [lbl.strip() for lbl in labels.split(",") if lbl.strip()]
    if not candidate_labels:
        return {}
    preds = clf(image, candidate_labels=candidate_labels)
    # Gradio expects {label: score, ...}
    return {p["label"]: p["score"] for p in preds}



# 3.  Gradio interface
# ------------------------------------------------------------------
demo = gr.Interface(
    fn=classify,
    inputs=[
        gr.Image(type="pil", label="Upload an image"),
        gr.Textbox(
            placeholder="cat, dog, horse",
            label="Candidate labels (comma-separated)",
        ),
    ],
    outputs=gr.Label(num_top_classes=5, label="Scores"),
    title="Zero-Shot Image Classifier 🤗 CLIP",
    description="Type any labels you want—the open-source CLIP model will score them.",
    examples=[["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", "cat, dog, fox"]],
)


# 4.  Launch (Spaces sets server_name & port automatically)
# ------------------------------------------------------------------
if __name__ == "__main__":
    demo.launch()