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 = "
⚠️ Low confidence. Try rephrasing the review." if confidence < 0.5 else "" result_html = f"""

Prediction: {label}

Confidence: {confidence:.2%}

{warning}
""" 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( "
💬📊 Review Analyzer
" ) 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)