Download app.py from MRM5/Neural_Entity_Sentiment_Intelligence: direct link, hf CLI and curl.
- Browser
- Download file 2.26 kB
-
https://huggingface.co/spaces/MRM5/Neural_Entity_Sentiment_Intelligence/resolve/main/app.py
- Command line
-
hf download hf://spaces/MRM5/Neural_Entity_Sentiment_Intelligence/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MRM5/Neural_Entity_Sentiment_Intelligence/resolve/main/app.py
2.26 kB
| import gradio as gr | |
| import tensorflow as tf | |
| import pickle | |
| import re | |
| import string | |
| import numpy as np | |
| # 1. LOAD ASSETS (Assumes files are in the root directory) | |
| with open('nb_model.pkl', 'rb') as f: | |
| nb_model = pickle.load(f) | |
| with open('lr_model.pkl', 'rb') as f: | |
| lr_model = pickle.load(f) | |
| # Load Custom MLP | |
| nn_model = tf.keras.models.load_model('sentiment_model.h5') | |
| with open('tfidf_vectorizer.pkl', 'rb') as f: | |
| tfidf = pickle.load(f) | |
| with open('label_encoder.pkl', 'rb') as f: | |
| le = pickle.load(f) | |
| # 2. SIMPLE CLEANING FUNCTION | |
| def clean_tweet(text): | |
| text = text.lower() | |
| text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE) | |
| text = re.sub(r'@\w+', '', text) | |
| text = text.translate(str.maketrans('', '', string.punctuation)) | |
| return re.sub(r'\s+', ' ', text).strip() | |
| # 3. PREDICTION LOGIC | |
| def predict_sentiment(tweet, model_choice): | |
| cleaned = clean_tweet(tweet) | |
| vec = tfidf.transform([cleaned]).toarray() | |
| if model_choice == "Naive Bayes": | |
| pred = nb_model.predict(vec)[0] | |
| label = le.inverse_transform([pred])[0] | |
| elif model_choice == "Logistic Regression": | |
| pred = lr_model.predict(vec)[0] | |
| label = le.inverse_transform([pred])[0] | |
| else: | |
| probs = nn_model.predict(vec) | |
| label = le.inverse_transform([np.argmax(probs)])[0] | |
| return f"Sentiment: {label.upper()}" | |
| # 4. AESTHETIC INTERFACE | |
| # We use a built-in soft theme for a clean, modern look. | |
| # The 'css' argument hides the 'Share via Link' button. | |
| demo = gr.Interface( | |
| fn=predict_sentiment, | |
| inputs=[ | |
| gr.Textbox(label="Enter Tweet Content", lines=3, placeholder="Type a tweet here..."), | |
| gr.Dropdown( | |
| ["Naive Bayes", "Logistic Regression", "Custom Neural Network (MLP)"], | |
| label="Select Model", | |
| value="Custom Neural Network (MLP)" | |
| ) | |
| ], | |
| outputs=gr.Text(label="Analysis Result"), | |
| title=" Twitter Entity Sentiment Analyzer", | |
| description="Enter a tweet to detect its sentiment (Positive, Negative, Neutral, or Irrelevant) using your chosen AI model.", | |
| theme=gr.themes.Soft(), | |
| css=".share-button { display: none !important; }" | |
| ) | |
| # 5. LAUNCH | |
| if __name__ == "__main__": | |
| demo.launch() |