testmodel / app.py
rararara9999's picture
Update app.py
d111573 verified
import subprocess
# Install the required packages
subprocess.check_call(["pip", "install", "--upgrade", "pip"])
subprocess.check_call(["pip", "install", "-U", "transformers"])
subprocess.check_call(["pip", "install", "-U", "accelerate"])
subprocess.check_call(["pip", "install", "datasets"])
subprocess.check_call(["pip", "install", "evaluate"])
subprocess.check_call(["pip", "install", "scikit-learn"])
subprocess.check_call(["pip", "install", "torchvision"])
# Load model directly
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("rararara9999/Model")
model = AutoModelForSequenceClassification.from_pretrained("rararara9999/Model")
from transformers import AutoModelForImageClassification, AutoImageProcessor
import torch
import numpy as np
from PIL import Image
import streamlit as st
# Load the fine-tuned model and image processor
model_checkpoint = "rararara9999/Model"
model = AutoModelForImageClassification.from_pretrained(model_checkpoint, num_labels=2)
image_processor = AutoImageProcessor.from_pretrained(model_checkpoint)
# Standalone Test Script
def test_model(image_path):
# Load and preprocess the image
image = Image.open(image_path)
inputs = image_processor(images=image, return_tensors="pt")
# Get model predictions
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
predictions = predictions.cpu().detach().numpy()
# Get the index of the largest output value
max_index = np.argmax(predictions)
labels = ["Wearing Mask", "Not Wearing Mask"]
predicted_label = labels[max_index]
print(f"The predicted label is {predicted_label}")
# Streamlit App for Interactive Testing
def main():
st.title("Face Mask Detection with HuggingFace Spaces")
st.write("Upload an image to analyze whether the person is wearing a mask:")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image.', use_column_width=True)
st.write("")
st.write("Classifying...")
# Preprocess the image
inputs = image_processor(images=image, return_tensors="pt")
# Get model predictions
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
predictions = predictions.cpu().detach().numpy()
# Get the index of the largest output value
max_index = np.argmax(predictions)
labels = ["Wearing Mask", "Not Wearing Mask"]
predicted_label = labels[max_index]
confidence = predictions[max_index]
st.write(f"Predicted Label: {predicted_label}")
st.write(f"Confidence: {confidence:.2f}")
if __name__ == "__main__":
main()