GiladtheFixer's picture
Update app.py
287394e verified
import gradio as gr
import tensorflow as tf
from transformers import pipeline
from huggingface_hub import from_pretrained_keras
import numpy as np
from keras.preprocessing.sequence import pad_sequences
from keras.datasets import imdb
global model
# ื˜ืขื™ื ืช ื”ืžื•ื“ืœ ืž-Hugging Face Hub
try:
global model
model = from_pretrained_keras("GiladtheFixer/Sentiment_Analysis")
print("Model loaded successfully!")
except Exception as e:
print(f"Error loading model: {e}")
# ืงื‘ืœืช ืื™ื ื“ืงืก ื”ืžื™ืœื™ื ืฉืœ IMDB
word_index = imdb.get_word_index()
def preprocess_text(text):
# ื”ืžืจื” ืœืžื™ืœื™ื
words = text.lower().split()
# ื”ืžืจื” ืœืžืกืคืจื™ื
sequence = [word_index.get(word, 0) for word in words]
# ื™ืฆื™ืจืช ื•ืงื˜ื•ืจ one-hot ื‘ื’ื•ื“ืœ 10000
vector = np.zeros((1, 10000))
for num in sequence:
if num < 10000: # ืžืชืขืœื ืžืžื™ืœื™ื ืฉื”ืื™ื ื“ืงืก ืฉืœื”ืŸ ื’ื“ื•ืœ ืž-10000
vector[0, num] = 1.
return vector
def predict_sentiment(text):
global model
try:
# ืขื™ื‘ื•ื“ ื”ื˜ืงืกื˜
processed_text = preprocess_text(text)
# ื—ื™ื–ื•ื™
prediction = model.predict(processed_text)[0][0]
sentiment = "Positive" if prediction > 0.5 else "Negative"
confidence = float(prediction if prediction > 0.5 else 1 - prediction)
return {
"Sentiment": sentiment,
"Confidence": f"{confidence:.2%}"
}
except Exception as e:
return {
"Error": str(e)
}
# ื™ืฆื™ืจืช ืžืžืฉืง Gradio
iface = gr.Interface(
fn=predict_sentiment,
inputs=[
gr.Textbox(label="Enter text to analyze", lines=4, placeholder="Type your text here...")
],
outputs=gr.JSON(label="Prediction Results"),
title="Sentiment Analysis",
description="Enter any text to analyze its sentiment. The model will predict whether the text is positive or negative.",
examples=[
["This movie was absolutely fantastic! I loved every minute of it."],
["The service was terrible and the food was cold."],
["It was okay, nothing special but not bad either."]
],
theme=gr.themes.Soft()
)
# ื”ืคืขืœืช ื”ืžืžืฉืง
if __name__ == "__main__":
iface.launch(share=True) # ืฉื ื” ืœ-share=False ืื ืืชื” ืœื ืจื•ืฆื” ืœื™ื™ืฆืจ ืงื™ืฉื•ืจ ืฆื™ื‘ื•ืจื™