Huggbottle commited on
Commit
be34fa8
·
verified ·
1 Parent(s): 62de659

Update app.py to show confidence scores for genres

Browse files
Files changed (1) hide show
  1. app.py +85 -66
app.py CHANGED
@@ -1,66 +1,85 @@
1
- import gradio as gr
2
- import pickle
3
- import os
4
-
5
- # Define paths to the pickle files
6
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
7
- PKL_DIR = os.path.join(BASE_DIR, 'pkl_files')
8
-
9
- SENTIMENT_MODEL_PATH = os.path.join(PKL_DIR, 'sentiment_model.pkl')
10
- SENTIMENT_VECTORIZER_PATH = os.path.join(PKL_DIR, 'sentiment_vectorizer.pkl')
11
- GENRE_MODEL_PATH = os.path.join(PKL_DIR, 'genre_model.pkl')
12
- GENRE_VECTORIZER_PATH = os.path.join(PKL_DIR, 'genre_vectorizer.pkl')
13
-
14
- # Load models and vectorizers
15
- def load_pickle(path):
16
- with open(path, 'rb') as f:
17
- return pickle.load(f)
18
-
19
- print("Loading models...")
20
- try:
21
- sentiment_model = load_pickle(SENTIMENT_MODEL_PATH)
22
- sentiment_vectorizer = load_pickle(SENTIMENT_VECTORIZER_PATH)
23
- genre_model = load_pickle(GENRE_MODEL_PATH)
24
- genre_vectorizer = load_pickle(GENRE_VECTORIZER_PATH)
25
- print("Models loaded successfully.")
26
- except Exception as e:
27
- print(f"Error loading models: {e}")
28
- raise e
29
-
30
- def predict_review(review_text):
31
- if not review_text:
32
- return "Please enter a review.", "Please enter a review."
33
-
34
- # Sentiment Prediction
35
- try:
36
- # Transform text using the sentiment vectorizer
37
- # Note: transform expects an iterable, so we wrap review_text in a list
38
- sentiment_features = sentiment_vectorizer.transform([review_text])
39
- sentiment_prediction = sentiment_model.predict(sentiment_features)[0]
40
- except Exception as e:
41
- sentiment_prediction = f"Error in sentiment prediction: {str(e)}"
42
-
43
- # Genre Prediction
44
- try:
45
- # Transform text using the genre vectorizer
46
- genre_features = genre_vectorizer.transform([review_text])
47
- genre_prediction = genre_model.predict(genre_features)[0]
48
- except Exception as e:
49
- genre_prediction = f"Error in genre prediction: {str(e)}"
50
-
51
- return sentiment_prediction, genre_prediction
52
-
53
- # Create Gradio Interface
54
- iface = gr.Interface(
55
- fn=predict_review,
56
- inputs=gr.Textbox(lines=5, placeholder="Enter movie review here...", label="Movie Review"),
57
- outputs=[
58
- gr.Textbox(label="Predicted Sentiment"),
59
- gr.Textbox(label="Predicted Genre")
60
- ],
61
- title="Movie Review Sentiment & Genre Classifier",
62
- description="Enter a movie review to predict its sentiment and the movie genre based on the text."
63
- )
64
-
65
- if __name__ == "__main__":
66
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pickle
3
+ import os
4
+ import numpy as np
5
+
6
+ # Define paths to the pickle files
7
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
8
+ PKL_DIR = os.path.join(BASE_DIR, 'pkl_files')
9
+
10
+ SENTIMENT_MODEL_PATH = os.path.join(PKL_DIR, 'sentiment_model.pkl')
11
+ SENTIMENT_VECTORIZER_PATH = os.path.join(PKL_DIR, 'sentiment_vectorizer.pkl')
12
+ GENRE_MODEL_PATH = os.path.join(PKL_DIR, 'genre_model.pkl')
13
+ GENRE_VECTORIZER_PATH = os.path.join(PKL_DIR, 'genre_vectorizer.pkl')
14
+
15
+ # Load models and vectorizers
16
+ def load_pickle(path):
17
+ with open(path, 'rb') as f:
18
+ return pickle.load(f)
19
+
20
+ print("Loading models...")
21
+ try:
22
+ sentiment_model = load_pickle(SENTIMENT_MODEL_PATH)
23
+ sentiment_vectorizer = load_pickle(SENTIMENT_VECTORIZER_PATH)
24
+ genre_model = load_pickle(GENRE_MODEL_PATH)
25
+ genre_vectorizer = load_pickle(GENRE_VECTORIZER_PATH)
26
+ print("Models loaded successfully.")
27
+ except Exception as e:
28
+ print(f"Error loading models: {e}")
29
+ raise e
30
+
31
+ def predict_review(review_text):
32
+ if not review_text:
33
+ return "Please enter a review.", "Please enter a review."
34
+
35
+ # Sentiment Prediction
36
+ try:
37
+ # Transform text using the sentiment vectorizer
38
+ # Note: transform expects an iterable, so we wrap review_text in a list
39
+ sentiment_features = sentiment_vectorizer.transform([review_text])
40
+ sentiment_prediction = sentiment_model.predict(sentiment_features)[0]
41
+ except Exception as e:
42
+ sentiment_prediction = f"Error in sentiment prediction: {str(e)}"
43
+
44
+ # Genre Prediction
45
+ try:
46
+ # Transform text using the genre vectorizer
47
+ genre_features = genre_vectorizer.transform([review_text])
48
+
49
+ # Use decision_function to get confidence scores
50
+ if hasattr(genre_model, "decision_function"):
51
+ decision_scores = genre_model.decision_function(genre_features)[0]
52
+
53
+ # Apply Softmax to convert scores to probabilities
54
+ exp_scores = np.exp(decision_scores)
55
+ probabilities = exp_scores / np.sum(exp_scores)
56
+
57
+ # Map classes to probabilities
58
+ genre_prediction = {
59
+ label: float(prob)
60
+ for label, prob in zip(genre_model.classes_, probabilities)
61
+ }
62
+ else:
63
+ # Fallback if decision_function is not available
64
+ pred = genre_model.predict(genre_features)[0]
65
+ genre_prediction = {pred: 1.0}
66
+
67
+ except Exception as e:
68
+ genre_prediction = {"Error": str(e)}
69
+
70
+ return sentiment_prediction, genre_prediction
71
+
72
+ # Create Gradio Interface
73
+ iface = gr.Interface(
74
+ fn=predict_review,
75
+ inputs=gr.Textbox(lines=5, placeholder="Enter movie review here...", label="Movie Review"),
76
+ outputs=[
77
+ gr.Textbox(label="Predicted Sentiment"),
78
+ gr.Label(label="Predicted Genre", num_top_classes=3)
79
+ ],
80
+ title="Movie Review Sentiment & Genre Classifier",
81
+ description="Enter a movie review to predict its sentiment and the movie genre based on the text."
82
+ )
83
+
84
+ if __name__ == "__main__":
85
+ iface.launch()