Spaces:
Sleeping
Sleeping
Download app.py from nerusskikh/wbsorter: direct link, hf CLI and curl.
- Browser
- Download file 1.69 kB
-
https://huggingface.co/spaces/nerusskikh/wbsorter/resolve/main/app.py
- Command line
-
hf download hf://spaces/nerusskikh/wbsorter/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nerusskikh/wbsorter/resolve/main/app.py
1.69 kB
| import gradio as gr | |
| import requests | |
| from PIL import Image | |
| from io import BytesIO | |
| from transformers import CLIPProcessor, CLIPModel | |
| import torch | |
| # Load the CLIP model and processor | |
| model_name = "openai/clip-vit-base-patch32" | |
| clip_processor = CLIPProcessor.from_pretrained(model_name) | |
| clip_model = CLIPModel.from_pretrained(model_name) | |
| # Define the function that will be used in the Gradio interface | |
| def classify_image(input_image, classes_string): | |
| classes = classes_string.split(';') | |
| # Load the image from the input | |
| if input_image is None: | |
| return "Please input an image or its URL." | |
| if isinstance(input_image, str): | |
| response = requests.get(input_image) | |
| input_image = Image.open(BytesIO(response.content)) | |
| inputs = clip_processor(text=classes, images=input_image, return_tensors="pt", padding=True) | |
| # Encode the image and class names | |
| with torch.no_grad(): | |
| outputs = clip_model(**inputs) | |
| # Return the class with the highest score | |
| logits_per_image = outputs.logits_per_image | |
| probs = logits_per_image.softmax(dim=1).flatten() | |
| predicted_class_index = probs.argmax().item() | |
| return {"Scores": {classes[i]: probs[i].item() for i in range(len(classes))}} | |
| # Define the Gradio interface | |
| gradio_interface = gr.Interface( | |
| fn=classify_image, | |
| inputs=[ | |
| gr.inputs.Image(type="pil", label="Image"), | |
| gr.inputs.Textbox(label=f"Classes separated by ;") | |
| ], | |
| outputs=[ | |
| gr.outputs.Textbox(label="Scores"), | |
| ], | |
| title="Image Classifier", | |
| description="Classify an image into one of multiple classes using the CLIP model.", | |
| ) | |
| # Launch the interface | |
| gradio_interface.launch() |