File size: 2,599 Bytes
542254c 7a1c2c4 542254c 7a1c2c4 542254c 7a1c2c4 542254c 7a1c2c4 542254c 7a1c2c4 542254c 90cad01 7a1c2c4 90cad01 542254c 90cad01 542254c 7a1c2c4 542254c 7a1c2c4 |
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 |
import gradio as gr
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer
import torch
# -----------------------------
# Configuration Section
# -----------------------------
MODEL_NAME = "quocviethere/imdb-roberta" # Replace with your actual model ID
# -----------------------------
# Model Loading Section
# -----------------------------
try:
# Load tokenizer and model from Hugging Face Hub
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
# Initialize the sentiment analysis pipeline
sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
# Verify label mapping
label_mapping = model.config.id2label
print(f"Model label mapping: {label_mapping}")
except Exception as e:
print(f"Error loading model: {e}")
raise
# -----------------------------
# Sentiment Analysis Function
# -----------------------------
def analyze_sentiment(text):
try:
# Perform sentiment analysis
result = sentiment_pipeline(text)[0]
# Extract label and score
label = result['label']
score = result['score']
# Map label to sentiment
if label in label_mapping.values():
sentiment = "Positive 😊" if label == "POSITIVE" else "Negative 😞"
else:
# Handle unexpected labels
sentiment = label
print(f"Unexpected label received: {label}")
confidence = f"Confidence: {round(score * 100, 2)}%"
return sentiment, confidence
except Exception as e:
print(f"Error during sentiment analysis: {e}")
return "Error", "Could not process the input."
# -----------------------------
# Gradio Interface Section
# -----------------------------
iface = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(
lines=5,
placeholder="Enter a movie review here...",
label="Movie Review"
),
outputs=[
gr.Textbox(label="Sentiment"),
gr.Textbox(label="Confidence")
],
title="IMDb Sentiment Analysis with RoBERTa",
description="Analyze the sentiment of movie reviews using a fine-tuned RoBERTa model.",
examples=[
["I loved the cinematography and the story was captivating."],
["The movie was a complete waste of time. Poor acting and boring plot."]
],
theme="default"
)
# -----------------------------
# Launch the Interface
# -----------------------------
iface.launch()
|