Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
67 lines (50 loc) · 2.27 KB
/
Copy pathapp.py
File metadata and controls
67 lines (50 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 📚 1️⃣ Import All Required Libraries
import streamlit as st
import pickle
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
# 📦 2️⃣ Load the Trained LSTM Model
model = load_model("next_word_LSTM.h5")
# 📄 3️⃣ Load the Tokenizer
with open("tokenizer.pickle", "rb") as handle:
tokenizer = pickle.load(handle)
# 🤖 4️⃣ Prediction Function
def predict_next_word(model, tokenizer, text, max_sequence_len):
# 1️⃣ Tokenize the input text
token_list = tokenizer.texts_to_sequences([text])[0]
# 2️⃣ Truncate if too long
if len(token_list) >= max_sequence_len:
token_list = token_list[-(max_sequence_len-1):]
# 3️⃣ Pad the sequence
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
# 4️⃣ Predict the next word
predicted = model.predict(token_list, verbose=0)
predicted_word_index = np.argmax(predicted, axis=1)[0]
# 5️⃣ Map back to word
for word, index in tokenizer.word_index.items():
if index == predicted_word_index:
return word
return None
# 🌐 5️⃣ Build Streamlit Web App
st.set_page_config(page_title="Next Word Prediction", layout="centered")
st.title("🔮 Next Word Predictor using LSTM")
st.markdown("Type a few words and the model will guess the next word!")
# 📥 6️⃣ Text Input
input_text = st.text_input("Enter a sequence of words:", placeholder="e.g. to be or not to")
# 🔘 7️⃣ Prediction Button
if st.button("Predict Next Word"):
if input_text.strip() == "":
st.warning("Please enter some text.")
else:
max_sequence_len = model.input_shape[1] + 1 # since input_length = max_len - 1 during training
next_word = predict_next_word(model, tokenizer, input_text, max_sequence_len)
if next_word:
st.success(f"✨ Predicted next word: **{next_word}**")
else:
st.error("Couldn't predict the next word.")
# ▶️ 8️⃣ Run the Streamlit App
# streamlit run app.py
# • 💻 Runs the web app in your browser.
# • 🕐 Takes a little time to load the model — this is normal.
# • ⚠️ Some warnings may appear, like tf.get_default_graph is deprecated — you can ignore