GiladtheFixer commited on
Commit
d6c903a
verified
1 Parent(s): 1b3e7fe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ from transformers import pipeline
4
+ from huggingface_hub import from_pretrained_keras
5
+ import numpy as np
6
+ from keras.preprocessing.sequence import pad_sequences
7
+ from keras.datasets import imdb
8
+
9
+ # 讟注讬谞转 讛诪讜讚诇 诪-Hugging Face Hub
10
+ try:
11
+ model = from_pretrained_keras("GiladtheFixer/Sentiment_Analysis")
12
+ print("Model loaded successfully!")
13
+ except Exception as e:
14
+ print(f"Error loading model: {e}")
15
+
16
+ # 拽讘诇转 讗讬谞讚拽住 讛诪讬诇讬诐 砖诇 IMDB
17
+ word_index = imdb.get_word_index()
18
+
19
+ def preprocess_text(text):
20
+ # 讛诪专讛 诇诪讬诇讬诐
21
+ words = text.lower().split()
22
+
23
+ # 讛诪专讛 诇诪住驻专讬诐
24
+ sequence = [word_index.get(word, 0) for word in words]
25
+
26
+ # 讬爪讬专转 讜拽讟讜专 one-hot 讘讙讜讚诇 10000
27
+ vector = np.zeros((1, 10000))
28
+ for num in sequence:
29
+ if num < 10000: # 诪转注诇诐 诪诪讬诇讬诐 砖讛讗讬谞讚拽住 砖诇讛谉 讙讚讜诇 诪-10000
30
+ vector[0, num] = 1.
31
+
32
+ return vector
33
+
34
+ def predict_sentiment(text):
35
+ try:
36
+ # 注讬讘讜讚 讛讟拽住讟
37
+ processed_text = preprocess_text(text)
38
+
39
+ # 讞讬讝讜讬
40
+ prediction = model.predict(processed_text)[0][0]
41
+
42
+ sentiment = "Positive" if prediction > 0.5 else "Negative"
43
+ confidence = float(prediction if prediction > 0.5 else 1 - prediction)
44
+
45
+ return {
46
+ "Sentiment": sentiment,
47
+ "Confidence": f"{confidence:.2%}"
48
+ }
49
+ except Exception as e:
50
+ return {
51
+ "Error": str(e)
52
+ }
53
+
54
+ # 讬爪讬专转 诪诪砖拽 Gradio
55
+ iface = gr.Interface(
56
+ fn=predict_sentiment,
57
+ inputs=[
58
+ gr.Textbox(label="Enter text to analyze", lines=4, placeholder="Type your text here...")
59
+ ],
60
+ outputs=gr.JSON(label="Prediction Results"),
61
+ title="Sentiment Analysis",
62
+ description="Enter any text to analyze its sentiment. The model will predict whether the text is positive or negative.",
63
+ examples=[
64
+ ["This movie was absolutely fantastic! I loved every minute of it."],
65
+ ["The service was terrible and the food was cold."],
66
+ ["It was okay, nothing special but not bad either."]
67
+ ],
68
+ theme=gr.themes.Soft()
69
+ )
70
+
71
+ # 讛驻注诇转 讛诪诪砖拽
72
+ if __name__ == "__main__":
73
+ iface.launch(share=True) # 砖谞讛 诇-share=False 讗诐 讗转讛 诇讗 专讜爪讛 诇讬讬爪专 拽讬砖讜专 爪讬讘讜专讬