File size: 2,004 Bytes
d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 9f907b6 d6b5e52 29cbe49 d6b5e52 9f907b6 d6b5e52 | 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 64 65 66 | import gradio as gr
import tensorflow as tf
import json
import numpy as np
import os
print("π Starting IMDB Sentiment Analysis App...")
# Load pre-trained model and artifacts
try:
model = tf.keras.models.load_model('model/saved_model.keras')
with open('model/word_index.json', 'r') as f:
word_index = json.load(f)
print("β
Pre-trained model loaded successfully!")
except Exception as e:
print(f"β Error loading model: {e}")
exit(1)
MAX_LEN = 200
def preprocess_text(text):
"""Convert text to sequence using the trained model's preprocessing"""
text = text.lower().replace('<br />', ' ').replace('/', ' ')
tokens = text.split()
sequence = []
for word in tokens:
word_id = word_index.get(word, 2) # 2 = UNK
if word_id >= 4:
sequence.append(word_id)
sequence = sequence[:MAX_LEN]
sequence = sequence + [0] * (MAX_LEN - len(sequence))
return np.array([sequence])
def predict_sentiment(text):
"""Predict sentiment using pre-trained model"""
if text.strip() == "":
return {"Please enter text": 0.0}
try:
processed_text = preprocess_text(text)
prediction = model.predict(processed_text, verbose=0)[0][0]
if prediction > 0.5:
return {"Positive π": float(prediction)}
else:
return {"Negative π": float(1 - prediction)}
except Exception as e:
return {"Error in prediction": 0.0}
# Gradio interface
demo = gr.Interface(
fn=predict_sentiment,
inputs=gr.Textbox(lines=3, placeholder="Enter movie review..."),
outputs=gr.Label(num_top_classes=2),
examples=[
["The acting was superb."],
["Terrible movie. Waste of time. Poor acting and boring storyline."],
],
title="π¬ IMDB Sentiment Analysis (Pre-trained Model)",
description="Uses a neural network pre-trained on IMDB reviews. Predictions are instant!"
)
if __name__ == "__main__":
demo.launch() |