Spaces:
Runtime error
Runtime error
Commit ·
73c2742
1
Parent(s): b365514
Add application file
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tensorflow.keras.preprocessing.text import text_to_word_sequence
|
| 4 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 5 |
+
from gensim.models import KeyedVectors
|
| 6 |
+
from tensorflow.keras.models import load_model
|
| 7 |
+
import gensim.downloader as api
|
| 8 |
+
|
| 9 |
+
# Load the pre-trained Word2Vec model
|
| 10 |
+
word2vec_transfer = api.load("glove-wiki-gigaword-100")
|
| 11 |
+
|
| 12 |
+
# Define the function to embed a sentence with the pre-trained Word2Vec model
|
| 13 |
+
def embed_sentence_with_TF(word2vec, sentence):
|
| 14 |
+
embedded_sentence = []
|
| 15 |
+
for word in sentence:
|
| 16 |
+
if word in word2vec:
|
| 17 |
+
embedded_sentence.append(word2vec[word])
|
| 18 |
+
return np.array(embedded_sentence)
|
| 19 |
+
|
| 20 |
+
# Define the function to preprocess a new movie review
|
| 21 |
+
def preprocess_review(review):
|
| 22 |
+
# Tokenize the review
|
| 23 |
+
review = text_to_word_sequence(review)
|
| 24 |
+
# Embed the review with the pre-trained Word2Vec model
|
| 25 |
+
review_embedded = embed_sentence_with_TF(word2vec_transfer, review)
|
| 26 |
+
# Pad the embedded review
|
| 27 |
+
review_padded = pad_sequences([review_embedded], dtype='float32', padding='post', maxlen=200)
|
| 28 |
+
return review_padded
|
| 29 |
+
|
| 30 |
+
# Load the trained model
|
| 31 |
+
model = load_model('my_model.h5')
|
| 32 |
+
|
| 33 |
+
def predict_sentiment(review):
|
| 34 |
+
# Preprocess the review
|
| 35 |
+
review_padded = preprocess_review(review)
|
| 36 |
+
# Predict the sentiment
|
| 37 |
+
sentiment = model.predict(review_padded)[0][0]
|
| 38 |
+
if sentiment > 0.5:
|
| 39 |
+
return "Positive"
|
| 40 |
+
elif sentiment == 0.5:
|
| 41 |
+
return "Neutral"
|
| 42 |
+
else:
|
| 43 |
+
return "Negative"
|
| 44 |
+
|
| 45 |
+
# Create a Gradio interface
|
| 46 |
+
inputs = gr.inputs.Textbox(lines=5, label="Input Text")
|
| 47 |
+
outputs = gr.outputs.Textbox(label="Sentiment")
|
| 48 |
+
title = "Sentiment Analysis"
|
| 49 |
+
description = "Enter a text and get the sentiment prediction."
|
| 50 |
+
gr.Interface(fn=predict_sentiment, inputs=inputs, outputs=outputs, title=title, description=description).launch(share=True)
|