Download app.py from 4loop/NewIMDB: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/4loop/NewIMDB/resolve/main/app.py
- Command line
-
hf download hf://spaces/4loop/NewIMDB/app.py
-
curl -L -o app.py https://huggingface.co/spaces/4loop/NewIMDB/resolve/main/app.py
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() |