File size: 3,424 Bytes
fd5473d
 
 
 
 
 
 
 
 
 
 
 
34bcf00
fd5473d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4755d
fd5473d
 
34bcf00
fd5473d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from datetime import datetime
import csv
import os

# Load model and tokenizer
model_path = "model"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForSequenceClassification.from_pretrained(model_path)

label_map = {0: "Negative", 1: "Neutral", 2: "Positive"}
colors = {"Negative": "red", "Neutral": "gray", "Positive": "green"}
FEEDBACK_FILE = "user_feedback.csv"

def predict_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=256)
    with torch.no_grad():
        outputs = model(**inputs)
        probs = torch.softmax(outputs.logits, dim=1).squeeze()
        predicted_class = torch.argmax(probs).item()

    label = label_map[predicted_class]
    confidence = probs[predicted_class].item()
    warning = "<br><span style='color:orange'>⚠️ Low confidence. Try rephrasing the review.</span>" if confidence < 0.5 else ""

    result_html = f"""
    <div style="border: 2px solid {colors[label]}; padding: 10px; border-radius: 10px;">
        <h3 style='margin-bottom: 5px;'>Prediction: <span style='color:{colors[label]}'>{label}</span></h3>
        <p>Confidence: {confidence:.2%}</p>
        {warning}
    </div>
    """
    return result_html, label, confidence

def save_feedback(label, confidence, correct):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    file_exists = os.path.isfile(FEEDBACK_FILE)
    with open(FEEDBACK_FILE, mode="a", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        if not file_exists:
            writer.writerow(["timestamp", "predicted_label", "confidence", "correct_prediction"])
        writer.writerow([timestamp, label, f"{confidence:.2%}", correct])
    return "βœ… Thanks for your feedback!"

with gr.Blocks(title="Amazon Review Sentiment App") as demo:
    gr.Markdown(
        "<div style='text-align: center; font-size: 24px;'> <b> πŸ’¬πŸ“Š Review Analyzer</b></div>"
    )

    gr.Markdown("Enter a review below to check if it's **Positive 😊**, **Neutral 😐**, or **Negative 😞**.")

    with gr.Row():
        review_input = gr.Textbox(lines=10, placeholder="Type or paste a review here...", label="Your Review")
        output_box = gr.HTML(label="Prediction Result")

    predict_btn = gr.Button("πŸ” Predict Sentiment")
    hidden_label = gr.Textbox(visible=False)
    hidden_conf = gr.Number(visible=False)

    with gr.Row():
        yes_btn = gr.Button("πŸ‘ Yes")
        no_btn = gr.Button("πŸ‘Ž No")

    feedback_output = gr.Textbox(label="Feedback Status", interactive=False)

    predict_btn.click(fn=predict_sentiment, inputs=[review_input], outputs=[output_box, hidden_label, hidden_conf])
    yes_btn.click(fn=save_feedback, inputs=[hidden_label, hidden_conf, gr.Textbox(value="yes", visible=False)], outputs=feedback_output)
    no_btn.click(fn=save_feedback, inputs=[hidden_label, hidden_conf, gr.Textbox(value="no", visible=False)], outputs=feedback_output)

    gr.Examples(
        examples=[
            "This phone exceeded all my expectations.",
            "Battery life is just okay, not great.",
            "Worst product I've ever purchased.",
            "Highly recommended!",
            "Meh. It's just fine, nothing special."
        ],
        inputs=review_input
    )

demo.launch(debug=True)