Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from tensorflow.keras.preprocessing.text import Tokenizer
|
| 5 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# Load configurations
|
| 9 |
+
NUM_WORDS = 1000
|
| 10 |
+
MAXLEN = 120
|
| 11 |
+
PADDING = 'post'
|
| 12 |
+
OOV_TOKEN = "<OOV>"
|
| 13 |
+
|
| 14 |
+
with open('tokenizer.json', 'r') as f:
|
| 15 |
+
tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(f.read())
|
| 16 |
+
|
| 17 |
+
# Load the trained model
|
| 18 |
+
model = tf.keras.models.load_model("model.h5")
|
| 19 |
+
|
| 20 |
+
# Function to convert sentences to padded sequences
|
| 21 |
+
def seq_and_pad(sentences, tokenizer, padding, maxlen):
|
| 22 |
+
sequences = tokenizer.texts_to_sequences(sentences)
|
| 23 |
+
padded_sequences = pad_sequences(sequences, maxlen=maxlen, padding=padding)
|
| 24 |
+
return padded_sequences
|
| 25 |
+
|
| 26 |
+
# Function to predict the class of a sentence
|
| 27 |
+
def predict_sport_class(sentence):
|
| 28 |
+
# Convert the sentence to a padded sequence
|
| 29 |
+
sentence_seq = seq_and_pad([sentence], tokenizer, PADDING, MAXLEN)
|
| 30 |
+
# Make a prediction
|
| 31 |
+
prediction = model.predict(sentence_seq)
|
| 32 |
+
# Get the predicted label
|
| 33 |
+
predicted_label = np.argmax(prediction)
|
| 34 |
+
# Mapping the label value back to the original label
|
| 35 |
+
label_mapping = {0: "sport", 1: "business", 2: "politics", 3: "tech", 4: "entertainment"}
|
| 36 |
+
# Get the predicted class label
|
| 37 |
+
predicted_class = label_mapping[predicted_label]
|
| 38 |
+
return predicted_class
|
| 39 |
+
|
| 40 |
+
# Create the Gradio interface
|
| 41 |
+
interface = gr.Interface(
|
| 42 |
+
fn=predict_sport_class,
|
| 43 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter a sentence here..."),
|
| 44 |
+
outputs=gr.Label(num_top_classes=1),
|
| 45 |
+
title="Text Classification App",
|
| 46 |
+
description="Enter a sentence to classify it into one of the following categories: sport, business, politics, tech, entertainment.",
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
interface.launch()
|
| 50 |
+
|