THeaxxxxxxxx commited on
Commit
14317b2
·
verified ·
1 Parent(s): 07498dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -44
app.py CHANGED
@@ -2,14 +2,14 @@ import streamlit as st
2
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
 
5
- # Set page configuration
6
  st.set_page_config(
7
  page_title="Review Assistant",
8
  page_icon="📝",
9
  layout="centered"
10
  )
11
 
12
- # Custom page styling with CSS
13
  st.markdown("""
14
  <style>
15
  .main-header {
@@ -48,24 +48,18 @@ st.markdown("""
48
  font-weight: bold;
49
  margin-bottom: 0.5rem;
50
  }
51
- /* Updated button styling with icon */
52
  .stButton>button {
53
- background-color: #2563EB;
54
  color: white;
55
  border: none;
56
  padding: 0.5rem 2rem;
57
  border-radius: 6px;
58
  font-weight: 500;
59
- display: inline-flex;
60
- align-items: center;
61
- justify-content: center;
62
  }
 
63
  .stButton>button:hover {
64
- background-color: #1D4ED8;
65
- }
66
- /* Button icon styling */
67
- .button-icon {
68
- margin-right: 8px;
69
  }
70
  .footer {
71
  text-align: center;
@@ -79,30 +73,30 @@ st.markdown("""
79
  </style>
80
  """, unsafe_allow_html=True)
81
 
82
- # Main page header
83
  st.markdown("<h1 class='main-header'>Smart Review Analysis Assistant</h1>", unsafe_allow_html=True)
84
  st.markdown("<p class='sub-header'>Topic Recognition, Sentiment Analysis, and Auto Reply in One Click</p>", unsafe_allow_html=True)
85
 
86
- # Function to load ML pipelines - cached to avoid reloading
87
  @st.cache_resource
88
  def load_pipelines():
89
  """
90
- Load all three machine learning pipelines:
91
- 1. Topic classifier using zero-shot classification
92
- 2. Sentiment analysis model
93
- 3. Reply generator for customer service responses
94
 
95
- Returns the models and topic labels for use in the app
96
  """
97
- # Topic Classification Model (Zero-shot classification)
98
  topic_labels = [
99
  "billing", "account access", "customer service", "loans",
100
  "fraud", "technical issue", "credit card", "mobile app",
101
  "branch service", "transaction delay", "account closure", "information error"
102
  ]
103
 
104
- # Use float32 for better CPU compatibility
105
- dtype = torch.float32
106
 
107
  # Load topic classification model
108
  topic_classifier = pipeline(
@@ -121,9 +115,8 @@ def load_pipelines():
121
  tokenizer = AutoTokenizer.from_pretrained(model_name)
122
  model = AutoModelForCausalLM.from_pretrained(model_name)
123
 
124
- # Function to generate customer service replies
125
  def generate_reply(text):
126
- """Generate a customer service reply based on the input text"""
127
  prompt_text = f"Please write a short, polite English customer service reply to the following customer comment:\n{text}"
128
  inputs = tokenizer(prompt_text, return_tensors="pt", truncation=True, max_length=512)
129
 
@@ -138,14 +131,14 @@ def load_pipelines():
138
  early_stopping=True
139
  )
140
 
141
- # Clean up generated text
142
  reply = tokenizer.decode(gen_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()
143
  reply = reply.strip('"').replace('\n', ' ').replace(' ', ' ')
144
  return reply
145
 
146
  return topic_classifier, sentiment_classifier, generate_reply, topic_labels
147
 
148
- # Page layout and user input section
149
  st.markdown("### Enter a review for instant analysis")
150
 
151
  # Updated example review as requested
@@ -158,45 +151,40 @@ user_review = st.text_area(
158
  height=120
159
  )
160
 
161
- # Custom button with icon
162
- analyze_button = st.markdown("""
163
- <button class="stButton primaryButton">
164
- <span class="button-icon">📊</span> Analyze
165
- </button>
166
- """, unsafe_allow_html=True)
167
-
168
- # Check if button is clicked (using the regular button for functionality)
169
- if st.button("Analyze", key="hidden_button", help="Click to analyze the review"):
170
  if not user_review.strip():
171
- # Validation check
172
  st.warning("Please enter a valid review!")
173
  else:
174
- # Show loading spinner during analysis
175
  with st.spinner("Analyzing your review..."):
176
- # Load models if not already loaded
177
  if "topic_pipe" not in st.session_state:
178
  st.session_state.topic_pipe, st.session_state.sentiment_pipe, st.session_state.reply_generator, st.session_state.topic_labels = load_pipelines()
179
 
180
- # Perform topic classification
181
  topic_result = st.session_state.topic_pipe(user_review, st.session_state.topic_labels, multi_label=False)
182
  topic = topic_result['labels'][0]
 
183
 
184
- # Perform sentiment analysis
185
  sentiment_result = st.session_state.sentiment_pipe(user_review)
186
  sentiment = sentiment_result[0]['label']
 
187
 
188
- # Generate auto-reply
189
  reply_text = st.session_state.reply_generator(user_review)
190
 
191
- # Display results in a two-column layout
192
  col1, col2 = st.columns(2)
193
  with col1:
194
  st.markdown(f"<div class='result-card topic-card'><p class='result-label'>Topic:</p>{topic}</div>", unsafe_allow_html=True)
195
  with col2:
196
  st.markdown(f"<div class='result-card sentiment-card'><p class='result-label'>Sentiment:</p>{sentiment}</div>", unsafe_allow_html=True)
197
 
198
- # Display auto-reply suggestion
199
  st.markdown(f"<div class='result-card reply-card'><p class='result-label'>Auto-reply Suggestion:</p>{reply_text}</div>", unsafe_allow_html=True)
200
 
201
  # Page footer
202
- st.markdown("<div class='footer'>© 2025 Review AI Assistant</div>", unsafe_allow_html=True)
 
2
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
 
5
+ # Set page configuration for the app
6
  st.set_page_config(
7
  page_title="Review Assistant",
8
  page_icon="📝",
9
  layout="centered"
10
  )
11
 
12
+ # Custom CSS styling for the page
13
  st.markdown("""
14
  <style>
15
  .main-header {
 
48
  font-weight: bold;
49
  margin-bottom: 0.5rem;
50
  }
51
+ /* Changed button color from blue (#2563EB) to green (#10B981) */
52
  .stButton>button {
53
+ background-color: #10B981;
54
  color: white;
55
  border: none;
56
  padding: 0.5rem 2rem;
57
  border-radius: 6px;
58
  font-weight: 500;
 
 
 
59
  }
60
+ /* Changed hover color to darker green (#059669) */
61
  .stButton>button:hover {
62
+ background-color: #059669;
 
 
 
 
63
  }
64
  .footer {
65
  text-align: center;
 
73
  </style>
74
  """, unsafe_allow_html=True)
75
 
76
+ # Page headers
77
  st.markdown("<h1 class='main-header'>Smart Review Analysis Assistant</h1>", unsafe_allow_html=True)
78
  st.markdown("<p class='sub-header'>Topic Recognition, Sentiment Analysis, and Auto Reply in One Click</p>", unsafe_allow_html=True)
79
 
80
+ # ------- Load ML Pipelines -------
81
  @st.cache_resource
82
  def load_pipelines():
83
  """
84
+ Load all required machine learning models for review analysis:
85
+ - Topic classifier using zero-shot classification
86
+ - Sentiment analysis model
87
+ - Customer reply generation model
88
 
89
+ Returns models and topic labels for use in the application
90
  """
91
+ # Define topic categories for classification
92
  topic_labels = [
93
  "billing", "account access", "customer service", "loans",
94
  "fraud", "technical issue", "credit card", "mobile app",
95
  "branch service", "transaction delay", "account closure", "information error"
96
  ]
97
 
98
+ # Ensure compatibility with CPU-only environments
99
+ dtype = torch.float32 # Use float32 for better CPU compatibility
100
 
101
  # Load topic classification model
102
  topic_classifier = pipeline(
 
115
  tokenizer = AutoTokenizer.from_pretrained(model_name)
116
  model = AutoModelForCausalLM.from_pretrained(model_name)
117
 
 
118
  def generate_reply(text):
119
+ """Generate a polite customer service reply based on the given review text"""
120
  prompt_text = f"Please write a short, polite English customer service reply to the following customer comment:\n{text}"
121
  inputs = tokenizer(prompt_text, return_tensors="pt", truncation=True, max_length=512)
122
 
 
131
  early_stopping=True
132
  )
133
 
134
+ # Clean up the generated text
135
  reply = tokenizer.decode(gen_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()
136
  reply = reply.strip('"').replace('\n', ' ').replace(' ', ' ')
137
  return reply
138
 
139
  return topic_classifier, sentiment_classifier, generate_reply, topic_labels
140
 
141
+ # ------- Page Layout --------
142
  st.markdown("### Enter a review for instant analysis")
143
 
144
  # Updated example review as requested
 
151
  height=120
152
  )
153
 
154
+ # Button to trigger analysis
155
+ if st.button("Analyze"):
 
 
 
 
 
 
 
156
  if not user_review.strip():
157
+ # Validate user input
158
  st.warning("Please enter a valid review!")
159
  else:
160
+ # Show user-friendly loading message
161
  with st.spinner("Analyzing your review..."):
162
+ # Load models on first use to avoid loading message on startup
163
  if "topic_pipe" not in st.session_state:
164
  st.session_state.topic_pipe, st.session_state.sentiment_pipe, st.session_state.reply_generator, st.session_state.topic_labels = load_pipelines()
165
 
166
+ # Run topic classification
167
  topic_result = st.session_state.topic_pipe(user_review, st.session_state.topic_labels, multi_label=False)
168
  topic = topic_result['labels'][0]
169
+ # Removed confidence percentage as requested
170
 
171
+ # Run sentiment analysis
172
  sentiment_result = st.session_state.sentiment_pipe(user_review)
173
  sentiment = sentiment_result[0]['label']
174
+ # Removed confidence percentage as requested
175
 
176
+ # Generate auto reply
177
  reply_text = st.session_state.reply_generator(user_review)
178
 
179
+ # Display results in a visually appealing format
180
  col1, col2 = st.columns(2)
181
  with col1:
182
  st.markdown(f"<div class='result-card topic-card'><p class='result-label'>Topic:</p>{topic}</div>", unsafe_allow_html=True)
183
  with col2:
184
  st.markdown(f"<div class='result-card sentiment-card'><p class='result-label'>Sentiment:</p>{sentiment}</div>", unsafe_allow_html=True)
185
 
186
+ # Display suggested reply
187
  st.markdown(f"<div class='result-card reply-card'><p class='result-label'>Auto-reply Suggestion:</p>{reply_text}</div>", unsafe_allow_html=True)
188
 
189
  # Page footer
190
+ st.markdown("<div class='footer'>© 2024 Review AI Assistant</div>", unsafe_allow_html=True)