Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import numpy as np | |
| from tensorflow.keras.preprocessing.text import text_to_word_sequence | |
| from tensorflow.keras.preprocessing.sequence import pad_sequences | |
| from gensim.models import KeyedVectors | |
| from tensorflow.keras.models import load_model | |
| import gensim.downloader as api | |
| # Load the pre-trained Word2Vec model | |
| word2vec_transfer = api.load("glove-wiki-gigaword-100") | |
| # Define the function to embed a sentence with the pre-trained Word2Vec model | |
| def embed_sentence_with_TF(word2vec, sentence): | |
| embedded_sentence = [] | |
| for word in sentence: | |
| if word in word2vec: | |
| embedded_sentence.append(word2vec[word]) | |
| return np.array(embedded_sentence) | |
| # Define the function to preprocess a new movie review | |
| def preprocess_review(review): | |
| # Tokenize the review | |
| review = text_to_word_sequence(review) | |
| # Embed the review with the pre-trained Word2Vec model | |
| review_embedded = embed_sentence_with_TF(word2vec_transfer, review) | |
| # Pad the embedded review | |
| review_padded = pad_sequences([review_embedded], dtype='float32', padding='post', maxlen=200) | |
| return review_padded | |
| # Load the trained model | |
| model = load_model('my_model.h5') | |
| def predict_sentiment(review): | |
| # Preprocess the review | |
| review_padded = preprocess_review(review) | |
| # Predict the sentiment | |
| sentiment = model.predict(review_padded)[0][0] | |
| if sentiment > 0.5: | |
| return "Positive" | |
| elif sentiment == 0.5: | |
| return "Neutral" | |
| else: | |
| return "Negative" | |
| # Create a Gradio interface | |
| inputs = gr.inputs.Textbox(lines=5, label="Input Text") | |
| outputs = gr.outputs.Textbox(label="Sentiment") | |
| title = "Sentiment Analysis" | |
| description = "Enter a text and get the sentiment prediction." | |
| gr.Interface(fn=predict_sentiment, inputs=inputs, outputs=outputs, title=title, description=description).launch(share=True) | |