Felix273 commited on
Commit
df93531
·
verified ·
1 Parent(s): e5e7539

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +30 -8
app.py CHANGED
@@ -55,7 +55,7 @@ def initialize_models():
55
  "sentiment-analysis",
56
  model=model,
57
  tokenizer=tokenizer,
58
- return_all_scores=True
59
  )
60
 
61
  logger.info("Sentiment analysis model loaded successfully")
@@ -100,8 +100,28 @@ def analyze_sentiment(text: str) -> Dict:
100
  try:
101
  results = sentiment_pipeline(text)
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  # Get the highest confidence score
104
- best_result = max(results, key=lambda x: x['score'])
105
 
106
  # Map labels to human-readable format
107
  label_mapping = {
@@ -113,8 +133,10 @@ def analyze_sentiment(text: str) -> Dict:
113
  'positive': 'positive'
114
  }
115
 
116
- sentiment = label_mapping.get(best_result['label'].lower(), best_result['label'])
117
- confidence = best_result['score']
 
 
118
 
119
  return {
120
  "sentiment": sentiment,
@@ -208,7 +230,7 @@ This review expresses **{sentiment}** sentiment with {confidence:.1%} confidence
208
  def analyze_review(review_text: str, image=None) -> str:
209
  """Main function to analyze a review."""
210
  if not review_text or not review_text.strip():
211
- return "**Please enter some review text to analyze.**"
212
 
213
  try:
214
  # Analyze sentiment
@@ -222,7 +244,7 @@ def analyze_review(review_text: str, image=None) -> str:
222
 
223
  except Exception as e:
224
  logger.error(f"Error in analyze_review: {e}")
225
- return f"**Error**: Something went wrong during analysis. Please try again."
226
 
227
  # Sample reviews for examples
228
  SAMPLE_REVIEWS = [
@@ -252,7 +274,7 @@ with gr.Blocks(
252
  css="footer {visibility: hidden}"
253
  ) as demo:
254
 
255
- gr.Markdown("# 🛍️ E-commerce Sentiment Analysis")
256
  gr.Markdown("""
257
  Analyze the sentiment of product reviews with AI-powered insights.
258
  Enter a review text and optionally upload a product image to get sentiment analysis
@@ -260,7 +282,7 @@ with gr.Blocks(
260
  """)
261
 
262
  if not initialization_success:
263
- gr.Markdown("⚠️ **Warning**: Some models failed to load. Functionality may be limited.")
264
 
265
  with gr.Row():
266
  with gr.Column(scale=1):
 
55
  "sentiment-analysis",
56
  model=model,
57
  tokenizer=tokenizer,
58
+ top_k=None # Use top_k=None instead of return_all_scores=True for newer transformers versions
59
  )
60
 
61
  logger.info("Sentiment analysis model loaded successfully")
 
100
  try:
101
  results = sentiment_pipeline(text)
102
 
103
+ # Handle different pipeline output formats
104
+ logger.info(f"Pipeline results type: {type(results)}")
105
+ logger.info(f"Pipeline results: {results}")
106
+
107
+ # Ensure results is a list and handle different formats
108
+ if isinstance(results, list) and len(results) > 0:
109
+ # If results is a nested list (multiple inputs), take the first
110
+ if isinstance(results[0], list):
111
+ scores = results[0]
112
+ else:
113
+ scores = results
114
+ else:
115
+ logger.error(f"Unexpected results format: {type(results)}")
116
+ return {"error": "Invalid pipeline output format"}
117
+
118
+ # Validate that scores is a list of dictionaries
119
+ if not isinstance(scores, list) or not all(isinstance(item, dict) and 'score' in item for item in scores):
120
+ logger.error(f"Invalid scores format: {scores}")
121
+ return {"error": "Invalid scores format from pipeline"}
122
+
123
  # Get the highest confidence score
124
+ best_result = max(scores, key=lambda x: x.get('score', 0))
125
 
126
  # Map labels to human-readable format
127
  label_mapping = {
 
133
  'positive': 'positive'
134
  }
135
 
136
+ # Safely extract label and score
137
+ raw_label = best_result.get('label', 'neutral')
138
+ sentiment = label_mapping.get(str(raw_label).lower(), str(raw_label))
139
+ confidence = best_result.get('score', 0.5)
140
 
141
  return {
142
  "sentiment": sentiment,
 
230
  def analyze_review(review_text: str, image=None) -> str:
231
  """Main function to analyze a review."""
232
  if not review_text or not review_text.strip():
233
+ return "**Please enter some review text to analyze.**"
234
 
235
  try:
236
  # Analyze sentiment
 
244
 
245
  except Exception as e:
246
  logger.error(f"Error in analyze_review: {e}")
247
+ return f"**Error**: Something went wrong during analysis. Please try again."
248
 
249
  # Sample reviews for examples
250
  SAMPLE_REVIEWS = [
 
274
  css="footer {visibility: hidden}"
275
  ) as demo:
276
 
277
+ gr.Markdown("# E-commerce Sentiment Analysis")
278
  gr.Markdown("""
279
  Analyze the sentiment of product reviews with AI-powered insights.
280
  Enter a review text and optionally upload a product image to get sentiment analysis
 
282
  """)
283
 
284
  if not initialization_success:
285
+ gr.Markdown("**Warning**: Some models failed to load. Functionality may be limited.")
286
 
287
  with gr.Row():
288
  with gr.Column(scale=1):