Spaces:
Sleeping
Sleeping
| 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 ืื ืืชื ืื ืจืืฆื ืืืืฆืจ ืงืืฉืืจ ืฆืืืืจื |