EmmaL1 commited on
Commit
683e053
·
verified ·
1 Parent(s): 275eec2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -43
app.py CHANGED
@@ -3,50 +3,64 @@ from transformers import pipeline
3
  import numpy as np
4
 
5
  # Initialize sentiment analysis pipeline
6
- try:
7
- sentiment_pipeline = pipeline(model="EmmaL1/CustomModel_amazon", return_all_scores=True)
8
- qa_pipeline = pipeline("question-answering", model="distilbert/distilbert-base-cased-distilled-squad")
9
- except Exception as e:
10
- st.error(f"Failed to load models: {str(e)}")
11
- st.stop()
12
-
13
- def get_rating(prediction):
14
- """Get rating (1-5 stars) directly from model prediction"""
15
- scores = [score['score'] for score in prediction[0]] # Extract class probabilities
16
- return np.argmax(scores) + 1 # Return highest probability class (+1 because ratings start at 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def textclassification():
19
- st.title("Amazon Review Sentiment Analysis")
20
- st.write("Enter a review to analyze sentiment and predict star rating")
21
-
22
- user_input = st.text_area("Enter review text:", height=150)
23
-
24
- if st.button("Analyze") and user_input:
25
- with st.spinner("Analyzing..."):
26
- try:
27
- # Sentiment analysis and rating prediction
28
- sentiment_pred = sentiment_pipeline(user_input)
29
- rating = get_rating(sentiment_pred)
30
-
31
- # Display results
32
- st.subheader("Analysis Results")
33
- col1, col2 = st.columns(2)
34
- with col1:
35
- st.metric("Predicted Rating", f"{rating} / 5")
36
- with col2:
37
- st.metric("Sentiment", "Positive" if rating >= 3 else "Negative")
38
-
39
- # Reason analysis
40
- st.subheader("Rating Justification")
41
- qa_input = {
42
- 'question': f'Why would this review receive {rating} stars?',
43
- 'context': user_input
44
- }
45
- qa_result = qa_pipeline(qa_input)
46
- st.info(qa_result['answer'])
47
-
48
- except Exception as e:
49
- st.error(f"Analysis error: {str(e)}")
50
 
51
  if __name__ == "__main__":
52
- textclassification()
 
3
  import numpy as np
4
 
5
  # Initialize sentiment analysis pipeline
6
+ sentiment_pipeline = pipeline(model="EmmaL1/CustomModel_amazon")
7
+
8
+ # Initialize question-answering pipeline
9
+ qa_pipeline = pipeline("question-answering", model="distilbert/distilbert-base-cased-distilled-squad")
10
+
11
+ def calculate_rating(sentiment, confidence):
12
+ """
13
+ Optimized rating calculation that:
14
+ 1. Provides more granular rating distribution (1-5 stars)
15
+ 2. Uses confidence score to determine rating strength
16
+ 3. Better reflects actual review distributions
17
+ """
18
+ if sentiment == "POSITIVE":
19
+ # Positive reviews get 3-5 stars based on confidence
20
+ if confidence > 0.9:
21
+ return 5 # Very confident positive = 5 stars
22
+ elif confidence > 0.7:
23
+ return 4 # Strong positive = 4 stars
24
+ else:
25
+ return 3 # Mild positive = 3 stars
26
+ else:
27
+ # Negative reviews get 1-2 stars based on confidence
28
+ if confidence > 0.7:
29
+ return 1 # Very confident negative = 1 star
30
+ else:
31
+ return 2 # Less confident negative = 2 stars
32
 
33
  def textclassification():
34
+ st.title("Amazon Customer Sentiment Analysis, Ratings, and Reasons")
35
+ st.write("Enter a sentence to analyze its sentiment and reason:")
36
+
37
+ user_input = st.text_input("Input your text:")
38
+ if user_input:
39
+
40
+ # Sentiment Analysis
41
+ sentiment_result = sentiment_pipeline(user_input)
42
+ sentiment = sentiment_result[0]["label"]
43
+ confidence = sentiment_result[0]["score"]
44
+
45
+ st.write(f"Sentiment: {sentiment}")
46
+ st.write(f"Confidence: {confidence:.2f}")
47
+
48
+ # Determine the rating using optimized calculation
49
+ rating = calculate_rating(sentiment, confidence)
50
+
51
+ # Display the rating
52
+ st.write(f"The rating is {rating} stars")
53
+
54
+ # Question Answering
55
+ qa_input = {
56
+ 'question': f'Why is the rating {rating} star?',
57
+ 'context': user_input
58
+ }
59
+ qa_result = qa_pipeline(qa_input)
60
+ st.write(f"Reasons: {qa_result['answer']}")
61
+
62
+ def main():
63
+ textclassification()
 
64
 
65
  if __name__ == "__main__":
66
+ main()