Spaces:
Runtime error
Runtime error
File size: 1,881 Bytes
d0a7b8d |
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 |
import clip
import gradio as gr
import numpy as np
import simple_chalk as chalk
import torch
from googletrans import Translator
from PIL import Image
TOP_N = 5
def match_texts(in_img: Image) -> list:
"""γ’γγ«ζΊε"""
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
""" γγγΉγεε¦η """
translator = Translator()
trans_dict = {}
with open("./sentences_ja.txt") as f:
for ja_sentence in f:
en_sentence = translator.translate(ja_sentence, dest="en", src="ja").text
trans_dict[en_sentence] = ja_sentence
en_sentences = list(trans_dict.keys())
texts = clip.tokenize(en_sentences).to(device)
""" η»εεε¦η """
# image: Tensor (3, 224, 224) -> (1, 3, 224, 224)
image = preprocess(in_img).unsqueeze(0).to(device)
""" CLIP γ’γγ«γ§ε¦η """
with torch.no_grad():
logits_per_image, logits_per_text = model(image, texts)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
probs_per_image = probs.reshape(-1)
sort_index = np.argsort(probs_per_image)[::-1]
""" ε¦ηη΅ζοΌγγγΉγοΌεΊε """
idxs = sort_index.tolist()
# θ±θͺεΊε
# confidences = {en_sentences[i]: float(probs_per_image[i]) for i in idxs}
# ζ₯ζ¬θͺε€ζεΊε
confidences = {trans_dict[en_sentences[i]]: float(probs_per_image[i]) for i in idxs}
return confidences
if __name__ == "__main__":
inputs = gr.Image(type="pil", label="η»εγε
₯ε")
outputs = gr.Label(num_top_classes=TOP_N, label=f"δΈθ΄γγγγγΉγ Top-{TOP_N}")
gr.Interface(
fn=match_texts,
inputs=inputs,
outputs=outputs,
examples=["examples-01.jpg", "examples-02.jpg", "examples-03.jpg"],
allow_flagging="never",
).launch(share=False)
|