Team Ai
Apppublic

PranavReddy18/Email_Spam_Classification

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py68 linesDownload Raw Back to root
1import streamlit as st
2import tensorflow as tf
3from tensorflow.keras.preprocessing.text import Tokenizer
4from tensorflow.keras.preprocessing.sequence import pad_sequences
5
6# Load your saved model and tokenizer
7def load_model_and_tokenizer():
8    # Assuming the model is saved as 'spam_ham_model.h5' and tokenizer saved as 'tokenizer.pickle'
9    model = tf.keras.models.load_model('model.h5')
10
11    # You need to have a way to load the tokenizer that you used
12    import pickle
13    with open('tokenizer.pkl', 'rb') as handle:
14        tokenizer = pickle.load(handle)
15    
16    return model, tokenizer
17
18# Preprocessing function for the user input
19def preprocess_input(texts, tokenizer, maxlen=50):
20    sequences = tokenizer.texts_to_sequences(texts)
21    return pad_sequences(sequences, maxlen=maxlen, padding='post')
22
23# Prediction function
24def predict_text(model, tokenizer, sample_texts, maxlen=50):
25    X_predict = preprocess_input(sample_texts, tokenizer, maxlen)
26    predictions = model.predict(X_predict)
27    
28    results = []
29    for text, pred in zip(sample_texts, predictions):
30        label = "spam" if pred[0] > 0.5 else "ham"
31        results.append({
32            "Text": text,
33            "Predicted Label": label,
34            "Prediction Confidence": f"{pred[0]:.4f}"
35        })
36    return results
37
38# Streamlit App Interface
39def main():
40    st.title('Spam vs Ham Text Classifier')
41    st.markdown("""
42    This is a simple Streamlit app that predicts whether a given text is **Spam** or **Ham** using a pre-trained model.
43    """)
44
45    # Load model and tokenizer
46    model, tokenizer = load_model_and_tokenizer()
47
48    # Text input
49    text_input = st.text_area("Enter the text you want to classify:")
50
51    # Button to predict
52    if st.button("Predict"):
53        if text_input:
54            # Get the prediction
55            prediction_results = predict_text(model, tokenizer, [text_input])
56            
57            # Display the result
58            for result in prediction_results:
59                st.write(f"**Text**: {result['Text']}")
60                st.write(f"**Predicted Label**: {result['Predicted Label']}")
61                st.write(f"**Prediction Confidence**: {result['Prediction Confidence']}")
62        else:
63            st.error("Please enter some text to classify.")
64
65# Run the app
66if __name__ == "__main__":
67    main()
68