import tensorflow as tf import gradio as gr import numpy as np # Load the custom model model = tf.keras.models.load_model("sentiment.h5") # Define a function to preprocess the input text def preprocess_text(text): # Tokenize the text tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=10000) tokenizer.fit_on_texts(text) text = tokenizer.texts_to_sequences(text) # Pad the sequences to a fixed length max_len = 30 text = tf.keras.preprocessing.sequence.pad_sequences(text, maxlen=max_len) return text # Define a function to get the sentiment scores from the model def get_sentiment_scores(text): # Preprocess the text text = preprocess_text(text) # Get the sentiment scores from the model scores = model.predict(text) # Postprocess the scores to obtain the sentiment label label = "Positive" if np.round(scores) == 1 else "Negative" return label # Define the Gradio interface interface = gr.Interface( fn=get_sentiment_scores, inputs=gr.inputs.Textbox(placeholder="Enter a positive or negative sentence here..."), outputs=gr.outputs.Textbox(label="Sentiment Label"), examples=[["This is wonderful!"], ["I hate this product."]] ) # Launch the interface interface.launch()