| import json |
| import numpy as np |
| import gradio as gr |
| from tensorflow import keras |
| from tensorflow.keras.preprocessing.sequence import pad_sequences |
|
|
| |
| MODEL_PATH = "model/sentiment_model.h5" |
| WORD_INDEX_PATH = "model/word_index.json" |
| MAX_LENGTH = 200 |
|
|
| model = keras.models.load_model(MODEL_PATH) |
|
|
| with open(WORD_INDEX_PATH, "r") as f: |
| word_index = json.load(f) |
|
|
| |
| def preprocess(text: str): |
| text = text.lower().strip() |
| tokens = text.split() |
|
|
| encoded = [word_index.get(word, 0) + 3 for word in tokens][:MAX_LENGTH] |
| padded = pad_sequences([encoded], maxlen=MAX_LENGTH, padding="post") |
| return padded |
|
|
| |
| def predict_sentiment(text: str): |
| text = text or "" |
| if not text.strip(): |
| return "Please enter some text." |
|
|
| padded = preprocess(text) |
| prob = float(model.predict(padded, verbose=0)[0][0]) |
|
|
| if prob >= 0.5: |
| label = "Positive π" |
| confidence = prob |
| else: |
| label = "Negative π" |
| confidence = 1.0 - prob |
|
|
| return f"{label} (confidence: {confidence:.3f})" |
|
|
| |
| examples = [ |
| ["I absolutely loved this movie, it was fantastic!"], |
| ["The product is okay, nothing special."], |
| ["This was a terrible experience, I am very disappointed."], |
| ["The service was quick and the staff were friendly."], |
| ["I wouldn't recommend this to anyone."] |
| ] |
|
|
| with gr.Blocks(theme=gr.themes.Soft()) as demo: |
| gr.Markdown( |
| """ |
| # π§ Sentiment Analysis Demo |
| Type a sentence or review and this neural network will guess whether the sentiment is positive or negative. |
| """ |
| ) |
|
|
| with gr.Row(): |
| with gr.Column(): |
| input_box = gr.Textbox( |
| lines=4, |
| label="Write your text here", |
| placeholder="For example: I really enjoyed this movie!" |
| ) |
| submit_btn = gr.Button("Analyze Sentiment", variant="primary") |
| with gr.Column(): |
| label_output = gr.Textbox( |
| label="Prediction", |
| lines=2 |
| ) |
|
|
| gr.Examples( |
| examples=examples, |
| inputs=input_box, |
| label="Try one of these examples" |
| ) |
|
|
| submit_btn.click( |
| fn=predict_sentiment, |
| inputs=input_box, |
| outputs=label_output |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |
|
|