Spaces:
Sleeping
Sleeping
File size: 1,901 Bytes
27d2338 0893248 27d2338 3d31657 38b3ee8 27d2338 18dbf41 27d2338 |
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 |
import os
import clip
import torch
from torchvision.datasets import CIFAR100
from PIL import Image
import gradio as gr
# Load the model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load('ViT-B/32', device)
# Download the dataset
cifar100 = CIFAR100(root=os.path.expanduser("~/.cache"), download=True, train=False)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in cifar100.classes]).to(device)
def generateOutput(source):
# Prepare the inputs
# image, class_id = cifar100[3637]
image = Image.fromarray(source.astype('uint8'), 'RGB')
image_input = preprocess(image).unsqueeze(0).to(device)
with torch.no_grad():
image_features = model.encode_image(image_input)
text_features = model.encode_text(text_inputs)
# Pick the top 5 most similar labels for the image
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
values, indices = similarity[0].topk(5)
# Result in Text
outputText = "\nTop predictions:\n"
for value, index in zip(values, indices):
outputText = outputText + f"{cifar100.classes[index]:>16s}: {100 * value.item():.2f}% \n"
return(outputText)
title = "CLIP Classification Inference Trials"
description = "Shows the CLIP Classification based on CIFAR100 data with your own image"
examples = [["Elephants.jpg"],["bloom-blooming-blossom-462118.jpg"], ["Puppies.jpg"], ["photo2.JPG"], ["MultipleItems.jpg"]]
demo = gr.Interface(
generateOutput,
inputs = [
gr.Image(width=256, height=256, label="Input Image"),
],
outputs = [
gr.Text(),
],
title = title,
description = description,
examples = examples,
cache_examples=False
)
demo.launch() |