Sayandip's picture
Update app.py
78fb77d verified
Raw
History Blame Contribute Delete
2.31 kB
import streamlit as st
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
import time
from gtts import gTTS
import tempfile
import base64
# Load the Keras model (.keras file)
model = tf.keras.models.load_model("Model.keras")
# Image parameters for prediction
img_height, img_width = 128, 128
def predict(img):
# Start timer to track inference time
start_time = time.time()
# Preprocess the image
img_array = image.img_to_array(img) / 255.0 # Normalize pixel values
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
# Make prediction using the model
prediction = model.predict(img_array)
label = "The eyes are visibly closed, hinting at a danger ahead for the driver." if prediction[0] > 0.5 else "The eyes are visibly open, hinting at the driver's alertness."
# Calculate inference time
inference_time = time.time() - start_time
return label, round(inference_time, 4) # Return label and inference time
# Function to convert text to speech and auto-play
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("Eye State Prediction")
st.write("Team 18: Sayandip Bhattacharyya, Purnendu Rudrapal, Sridatta Das, Sidhartha Karjee")
# Upload image
uploaded_image = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_image is not None:
# Display uploaded image
img = image.load_img(uploaded_image, target_size=(img_height, img_width))
st.image(img, caption="Uploaded Image", use_container_width=True)
# Make prediction
label, inference_time = predict(img)
# Display results
st.write(f"Prediction: **{label}**")
st.write(f"Inference Time: **{inference_time} seconds**")
# Convert the result into speech and play it
speak_auto(f"{label} Inference time: {inference_time} seconds.")