NewIMDB / app.py
4loop's picture
Update app.py
29cbe49 verified
Raw History Blame Contribute Delete
2 kB
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()