Update app.py
Browse files
app.py
CHANGED
|
@@ -2,30 +2,50 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
from PIL import Image
|
| 4 |
from torchvision import transforms
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
model = torch.hub.load('facebookresearch/deit:main', 'deit_tiny_patch16_224')
|
|
|
|
| 8 |
|
| 9 |
-
# File upload component
|
| 10 |
-
file = gr.FileInput()
|
| 11 |
|
| 12 |
-
# Display image
|
| 13 |
image = gr.Image(label="Uploaded Image")
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# Run model on image
|
| 16 |
def run(file):
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
transform = transforms.Compose([
|
| 19 |
-
transforms.Resize(256),
|
| 20 |
transforms.CenterCrop(224),
|
| 21 |
transforms.ToTensor(),
|
| 22 |
-
transforms.Normalize(
|
| 23 |
])
|
|
|
|
| 24 |
tensor = transform(image)
|
| 25 |
-
tensor = tensor.unsqueeze(0)
|
|
|
|
| 26 |
with torch.no_grad():
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
return image
|
| 30 |
|
| 31 |
# Launch app
|
|
|
|
| 2 |
import torch
|
| 3 |
from PIL import Image
|
| 4 |
from torchvision import transforms
|
| 5 |
+
import huggingface_hub as hf
|
| 6 |
|
| 7 |
+
# HuggingFace model and Spaces
|
| 8 |
model = torch.hub.load('facebookresearch/deit:main', 'deit_tiny_patch16_224')
|
| 9 |
+
repo = "uploader"
|
| 10 |
|
| 11 |
+
# File upload component with local or remote option
|
| 12 |
+
file = gr.FileInput(type="file", label="Upload Image File", preview=True)
|
| 13 |
|
| 14 |
+
# Display image
|
| 15 |
image = gr.Image(label="Uploaded Image")
|
| 16 |
|
| 17 |
+
# Upload file to HuggingFace Spaces
|
| 18 |
+
def upload_to_hf(filename):
|
| 19 |
+
with open(filename, 'rb') as f:
|
| 20 |
+
data = f.read()
|
| 21 |
+
hf.upload_file(data, f"/{repo}/{filename}")
|
| 22 |
+
return f"/{repo}/{filename}"
|
| 23 |
+
|
| 24 |
# Run model on image
|
| 25 |
def run(file):
|
| 26 |
+
if file.startswith("http"): # remote file
|
| 27 |
+
filename = file.split("/")[-1]
|
| 28 |
+
filepath = upload_to_hf(filename)
|
| 29 |
+
else: # local file
|
| 30 |
+
filepath = file
|
| 31 |
+
|
| 32 |
+
image = Image.open(filepath).convert('RGB')
|
| 33 |
+
|
| 34 |
+
# preprocess, run model, return output
|
| 35 |
transform = transforms.Compose([
|
| 36 |
+
transforms.Resize(256),
|
| 37 |
transforms.CenterCrop(224),
|
| 38 |
transforms.ToTensor(),
|
| 39 |
+
transforms.Normalize([0.5,0.5,0.5],[0.5,0.5,0.5])
|
| 40 |
])
|
| 41 |
+
|
| 42 |
tensor = transform(image)
|
| 43 |
+
tensor = tensor.unsqueeze(0)
|
| 44 |
+
|
| 45 |
with torch.no_grad():
|
| 46 |
+
output = model(tensor)
|
| 47 |
+
|
| 48 |
+
image.update(filepath)
|
| 49 |
return image
|
| 50 |
|
| 51 |
# Launch app
|