LeemahLee's picture
debugging the error in my prediction
34bcf00
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)