Download app.py from Speshal89/CLIP-BASE: direct link, hf CLI and curl.
- Browser
- Download file 1.07 kB
-
https://huggingface.co/spaces/Speshal89/CLIP-BASE/resolve/main/app.py
- Command line
-
hf download hf://spaces/Speshal89/CLIP-BASE/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Speshal89/CLIP-BASE/resolve/main/app.py
1.07 kB
| import gradio as gr | |
| from transformers import CLIPProcessor, CLIPModel | |
| from PIL import Image | |
| import torch | |
| # Load model and processor | |
| model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") | |
| processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") | |
| # Define predict function | |
| def predict(image, labels): | |
| print("Received image:", image) | |
| print("Received labels:", labels) | |
| if not labels or not image: | |
| return [{"label": "Invalid input", "score": 0.0}] | |
| labels = labels.split(",") | |
| inputs = processor(text=labels, images=image, return_tensors="pt", padding=True) | |
| outputs = model(**inputs) | |
| logits_per_image = outputs.logits_per_image | |
| probs = logits_per_image.softmax(dim=1)[0].tolist() | |
| return [{"label": lbl.strip(), "score": round(score, 4)} for lbl, score in zip(labels, probs)] | |
| # Define the Gradio interface | |
| demo = gr.Interface( | |
| fn=predict, | |
| inputs=[ | |
| gr.Image(type="pil", label="Image"), | |
| gr.Textbox(label="Labels (comma-separated)") | |
| ], | |
| outputs="json" | |
| ) | |
| demo.launch() | |