Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from transformers import ViTForImageClassification, ViTImageProcessor
|
5 |
+
|
6 |
+
# Load the model and feature extractor from Hugging Face
|
7 |
+
repository_id = "Hammad712/brainmri-vit-model"
|
8 |
+
model = ViTForImageClassification.from_pretrained(repository_id)
|
9 |
+
feature_extractor = ViTImageProcessor.from_pretrained(repository_id)
|
10 |
+
|
11 |
+
# Function to perform inference
|
12 |
+
def predict(image):
|
13 |
+
# Convert image to RGB and preprocess it
|
14 |
+
image = image.convert("RGB")
|
15 |
+
inputs = feature_extractor(images=image, return_tensors="pt")
|
16 |
+
|
17 |
+
# Move the inputs to the appropriate device
|
18 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
19 |
+
model.to(device)
|
20 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
21 |
+
|
22 |
+
# Perform inference
|
23 |
+
with torch.no_grad():
|
24 |
+
outputs = model(**inputs)
|
25 |
+
|
26 |
+
# Get the predicted label
|
27 |
+
logits = outputs.logits
|
28 |
+
predicted_label = logits.argmax(-1).item()
|
29 |
+
|
30 |
+
# Map the label to "No" or "Yes"
|
31 |
+
label_map = {0: "No", 1: "Yes"}
|
32 |
+
return label_map[predicted_label]
|
33 |
+
|
34 |
+
# Streamlit app
|
35 |
+
st.title("Brain MRI Tumor Detection")
|
36 |
+
st.write("Upload an MRI image to predict whether it contains a tumor.")
|
37 |
+
|
38 |
+
# File uploader
|
39 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
40 |
+
|
41 |
+
if uploaded_file is not None:
|
42 |
+
# Display the uploaded image
|
43 |
+
image = Image.open(uploaded_file)
|
44 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
45 |
+
|
46 |
+
# Perform inference and display the result
|
47 |
+
st.write("Classifying...")
|
48 |
+
label = predict(image)
|
49 |
+
st.write(f"Predicted label: {label}")
|