File size: 1,335 Bytes
cfdd73a 6510852 42fced3 cfdd73a 42fced3 6510852 42fced3 cfdd73a 42fced3 c32099f 42fced3 6510852 c32099f 42fced3 6510852 42fced3 6510852 42fced3 6510852 42fced3 6510852 42fced3 6510852 42fced3 6510852 42fced3 6510852 cfdd73a 6510852 |
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 |
import gradio as gr
import torch
from PIL import Image
from torchvision import transforms
import huggingface_hub as hf
# HuggingFace model and Spaces
model = torch.hub.load('facebookresearch/deit:main', 'deit_tiny_patch16_224')
repo = "uploader"
# File upload component with local or remote option
file = gr.FileInput(type="file", label="Upload Image File", preview=True)
# Display image
image = gr.Image(label="Uploaded Image")
# Upload file to HuggingFace Spaces
def upload_to_hf(filename):
with open(filename, 'rb') as f:
data = f.read()
hf.upload_file(data, f"/{repo}/{filename}")
return f"/{repo}/{filename}"
# Run model on image
def run(file):
if file.startswith("http"): # remote file
filename = file.split("/")[-1]
filepath = upload_to_hf(filename)
else: # local file
filepath = file
image = Image.open(filepath).convert('RGB')
# preprocess, run model, return output
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
])
tensor = transform(image)
tensor = tensor.unsqueeze(0)
with torch.no_grad():
output = model(tensor)
image.update(filepath)
return image
# Launch app
app = gr.Interface(fn=run, inputs=[file], outputs=[image])
app.launch() |