Sayandip's picture
Update app.py
b5133d0 verified
Raw
History Blame Contribute Delete
2.27 kB
import streamlit as st
import tensorflow as tf
from PIL import Image
import numpy as np
import time
from gtts import gTTS
import tempfile
import base64
# Load the trained model
@st.cache_resource
def load_model():
model = tf.keras.models.load_model("Drowsiness Detection Model.keras")
return model
model = load_model()
# Preprocessing function
def preprocess_image(image):
# Convert to RGB to ensure 3 channels
image = image.convert("RGB")
image = image.resize((224, 224))
image_array = np.array(image) / 255.0
image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
return image_array
# Function to play speech
def speak_auto(text):
tts = gTTS(text=text, lang='en')
with tempfile.NamedTemporaryFile(delete=True, suffix=".mp3") as fp:
tts.save(fp.name)
audio_bytes = fp.read()
b64 = base64.b64encode(audio_bytes).decode()
audio_html = f"""
<audio autoplay>
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
</audio>
"""
st.markdown(audio_html, unsafe_allow_html=True)
# Streamlit UI
st.title("🚦 Drowsiness Detection Model")
st.write("Team 18 Project: Sayandip Bhattacharyya, Sidhartha Karjee, Sridatta Das, Purnendu Rudrapal")
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Display uploaded image
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image")
# Preprocess and predict
start_time = time.time()
image_array = preprocess_image(image)
prediction = model.predict(image_array)[0][0]
elapsed_time = time.time() - start_time
# Display results
label = "Drowsy" if prediction > 0.5 else "Non-Drowsy"
confidence = prediction if label == "Drowsy" else 1 - prediction
st.write(f"### Prediction: **{label}**")
st.write(f"Confidence: **{confidence:.2%}**")
st.write(f"⏱️ Inference Time: **{elapsed_time:.4f} seconds**")
# Call speak_auto function to speak out the prediction
prediction_text = f"The person in the uploaded image is {label} with a prediction confidence of {confidence:.2%}."
speak_auto(prediction_text) # Auto-play speech