Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -41,25 +41,22 @@ vit.load_state_dict(torch.load("vit_epoch_2.pth", map_location=torch.device("cpu
|
|
| 41 |
### 3. Prediction function ###
|
| 42 |
|
| 43 |
def predict(img) -> Tuple[Dict[str, float], float]:
|
| 44 |
-
"""Transforms and performs a prediction on img and returns prediction and time taken."""
|
| 45 |
from PIL import UnidentifiedImageError
|
| 46 |
|
| 47 |
try:
|
| 48 |
-
# Convert ndarray to PIL if needed
|
| 49 |
if isinstance(img, np.ndarray):
|
| 50 |
-
img = Image.fromarray(img)
|
| 51 |
|
| 52 |
-
#
|
| 53 |
if img.mode != "RGB":
|
| 54 |
img = img.convert("RGB")
|
| 55 |
|
| 56 |
-
# Start timer
|
| 57 |
start_time = timer()
|
| 58 |
|
| 59 |
-
#
|
| 60 |
img_tensor = vit_transforms(img).unsqueeze(0)
|
| 61 |
|
| 62 |
-
# Inference
|
| 63 |
vit.eval()
|
| 64 |
with torch.inference_mode():
|
| 65 |
pred_probs = torch.softmax(vit(img_tensor), dim=1)
|
|
@@ -76,6 +73,7 @@ def predict(img) -> Tuple[Dict[str, float], float]:
|
|
| 76 |
except (UnidentifiedImageError, TypeError, ValueError) as e:
|
| 77 |
return {"Error": f"Invalid image input: {str(e)}"}, 0.0
|
| 78 |
|
|
|
|
| 79 |
### 4. Gradio app setup ###
|
| 80 |
|
| 81 |
# Title, description, and article text
|
|
|
|
| 41 |
### 3. Prediction function ###
|
| 42 |
|
| 43 |
def predict(img) -> Tuple[Dict[str, float], float]:
|
|
|
|
| 44 |
from PIL import UnidentifiedImageError
|
| 45 |
|
| 46 |
try:
|
| 47 |
+
# Convert ndarray to PIL.Image if needed
|
| 48 |
if isinstance(img, np.ndarray):
|
| 49 |
+
img = Image.fromarray(img.astype("uint8")) # Ensure correct dtype
|
| 50 |
|
| 51 |
+
# Ensure image is in RGB mode
|
| 52 |
if img.mode != "RGB":
|
| 53 |
img = img.convert("RGB")
|
| 54 |
|
|
|
|
| 55 |
start_time = timer()
|
| 56 |
|
| 57 |
+
# Apply transforms (expects a PIL image)
|
| 58 |
img_tensor = vit_transforms(img).unsqueeze(0)
|
| 59 |
|
|
|
|
| 60 |
vit.eval()
|
| 61 |
with torch.inference_mode():
|
| 62 |
pred_probs = torch.softmax(vit(img_tensor), dim=1)
|
|
|
|
| 73 |
except (UnidentifiedImageError, TypeError, ValueError) as e:
|
| 74 |
return {"Error": f"Invalid image input: {str(e)}"}, 0.0
|
| 75 |
|
| 76 |
+
|
| 77 |
### 4. Gradio app setup ###
|
| 78 |
|
| 79 |
# Title, description, and article text
|