Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import emoji
|
| 3 |
+
import nltk
|
| 4 |
+
import numpy as np
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from nltk.tokenize import word_tokenize
|
| 7 |
+
from nltk.stem import WordNetLemmatizer
|
| 8 |
+
from tensorflow.keras.models import load_model
|
| 9 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 10 |
+
from tensorflow.keras.preprocessing.text import Tokenizer
|
| 11 |
+
|
| 12 |
+
# Ensure necessary downloads
|
| 13 |
+
nltk.download("punkt")
|
| 14 |
+
nltk.download("wordnet")
|
| 15 |
+
|
| 16 |
+
lemmatizer = WordNetLemmatizer()
|
| 17 |
+
|
| 18 |
+
def pre_process(x):
|
| 19 |
+
x = x.lower()
|
| 20 |
+
x = re.sub("<.*?>", "", x)
|
| 21 |
+
x = re.sub("http[s]?://.+?\\S+", "", x)
|
| 22 |
+
x = re.sub("[@#].+?\\S", "", x)
|
| 23 |
+
x = re.sub(r"\\_+", " ", x)
|
| 24 |
+
x = re.sub("^[A-Za-z.].*\\s-\\s", "", x)
|
| 25 |
+
x = emoji.demojize(x)
|
| 26 |
+
x = re.sub(":.*?:", "", x)
|
| 27 |
+
x = re.sub("[^a-zA-Z0-9\\s_]", "", x)
|
| 28 |
+
words = word_tokenize(x)
|
| 29 |
+
x = " ".join([lemmatizer.lemmatize(word) for word in words])
|
| 30 |
+
return x
|
| 31 |
+
|
| 32 |
+
# Load trained model
|
| 33 |
+
model = load_model("best_rnn_model.h5")
|
| 34 |
+
|
| 35 |
+
# Tokenizer (Ensure this matches the one used during training)
|
| 36 |
+
MAX_LENGTH = 100 # Set this to the same max length used in training
|
| 37 |
+
tokenizer = Tokenizer() # Load your trained tokenizer here
|
| 38 |
+
|
| 39 |
+
# Class labels
|
| 40 |
+
class_labels = ['Sports', 'Business', 'SciTech', 'World']
|
| 41 |
+
|
| 42 |
+
def predict_category(text):
|
| 43 |
+
processed_text = pre_process(text)
|
| 44 |
+
seq = tokenizer.texts_to_sequences([processed_text])
|
| 45 |
+
padded_seq = pad_sequences(seq, maxlen=MAX_LENGTH, padding='post')
|
| 46 |
+
prediction = model.predict(padded_seq)
|
| 47 |
+
predicted_label = class_labels[np.argmax(prediction)]
|
| 48 |
+
return predicted_label
|
| 49 |
+
|
| 50 |
+
# Streamlit UI
|
| 51 |
+
st.title("News Category Classifier")
|
| 52 |
+
st.write("Enter a news headline or article snippet, and the model will predict its category.")
|
| 53 |
+
|
| 54 |
+
user_input = st.text_area("Enter text here:")
|
| 55 |
+
|
| 56 |
+
if st.button("Predict"):
|
| 57 |
+
if user_input.strip():
|
| 58 |
+
prediction = predict_category(user_input)
|
| 59 |
+
st.success(f"Predicted Category: {prediction}")
|
| 60 |
+
else:
|
| 61 |
+
st.warning("Please enter some text to classify.")
|