Analysis / app.py
davidcompsc's picture
Create app.py
5b3d36c verified
import gradio as gr
from transformers import pipeline
# Load the sentiment analysis pipeline
# We use a model specifically trained on product reviews (Amazon reviews)
model_name = "LiYuan/amazon-review-sentiment-analysis"
sentiment_pipeline = pipeline("sentiment-analysis", model=model_name)
def analyze_sentiment(review_text):
"""
Analyzes the sentiment of the input text and returns a formatted result.
The model outputs star ratings (1-5 stars).
"""
if not review_text.strip():
return "Please enter some text to analyze.", None
try:
# Perform sentiment analysis
results = sentiment_pipeline(review_text)
# The model returns labels like '1 star', '2 stars', etc.
label = results[0]['label']
score = results[0]['score']
# Map star ratings to sentiment categories
star_count = int(label.split()[0])
if star_count >= 4:
sentiment = "Positive"
color = "🟒"
elif star_count == 3:
sentiment = "Neutral"
color = "🟑"
else:
sentiment = "Negative"
color = "πŸ”΄"
result_text = f"### Sentiment: {sentiment} {color}\n"
result_text += f"**Rating:** {label} ({score:.2%} confidence)\n\n"
# Add some context for computer system products
if "battery" in review_text.lower():
result_text += "- *Note: This review mentions battery life.*\n"
if "performance" in review_text.lower() or "fast" in review_text.lower() or "slow" in review_text.lower():
result_text += "- *Note: This review mentions system performance.*\n"
if "screen" in review_text.lower() or "display" in review_text.lower():
result_text += "- *Note: This review mentions the display/screen.*\n"
return result_text, {label: score}
except Exception as e:
return f"Error during analysis: {str(e)}", None
# Define the Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# πŸ’» Computer System Sentiment Analyzer")
gr.Markdown(
"Enter a review for a computer, laptop, or hardware component to analyze its sentiment. "
"This tool uses a model trained on millions of product reviews to provide accurate star ratings."
)
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
label="Product Review",
placeholder="e.g., The MacBook Pro has amazing performance and a stunning display, but the price is a bit high...",
lines=5
)
submit_btn = gr.Button("Analyze Sentiment", variant="primary")
with gr.Column():
output_markdown = gr.Markdown(label="Analysis Result")
output_label = gr.Label(label="Confidence Score")
# Examples for users to try
gr.Examples(
examples=[
["The laptop is incredibly fast and the battery lasts all day. Highly recommended!"],
["The screen arrived with dead pixels and the customer service was unhelpful. Disappointed."],
["It's a decent computer for the price. Not the fastest, but gets the job done for basic tasks."],
["The cooling system is quite loud under load, but the gaming performance is top-notch."]
],
inputs=input_text
)
submit_btn.click(
fn=analyze_sentiment,
inputs=input_text,
outputs=[output_markdown, output_label]
)
if __name__ == "__main__":
demo.launch()