Spaces:
Build error
Build error
File size: 2,259 Bytes
8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c 521ad8c 8a7d74c | 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 | import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
# Load sentiment model
def load_model():
model_name = "cardiffnlp/twitter-roberta-base-sentiment"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
return sentiment_pipeline
sentiment_pipeline = load_model()
label_map = {"LABEL_0": "negative", "LABEL_1": "neutral", "LABEL_2": "positive"}
# Simple explanation generator
def explain_sentiment(text, sentiment):
text_lower = text.lower()
if sentiment == "positive":
if any(word in text_lower for word in ["love", "great", "happy", "excellent", "good", "amazing"]):
return "Detected positive language such as 'great', 'happy', or 'love'."
else:
return "Overall positive tone based on context."
elif sentiment == "negative":
if any(word in text_lower for word in ["hate", "bad", "terrible", "awful", "worst", "sad"]):
return "Detected negative words like 'hate', 'bad', or 'worst'."
else:
return "Overall negative tone based on context."
else:
return "Text appears to be neutral with no strong emotional cues."
# Gradio function
def analyze_sentiment(text):
if not text.strip():
return "Please enter some text.", ""
result = sentiment_pipeline(text)[0]
sentiment = label_map[result["label"]]
confidence = result["score"]
explanation = explain_sentiment(text, sentiment)
sentiment_result = f"**Sentiment**: {sentiment.capitalize()} \n**Confidence**: {confidence:.2f}"
return sentiment_result, explanation
# Gradio interface
iface = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(lines=4, placeholder="Type something here..."),
outputs=[
gr.Markdown(label="Sentiment Result"),
gr.Textbox(label="Explanation")
],
title="Fast Sentiment Analyzer",
description="Enter some text. This app will classify the sentiment (Positive, Negative, or Neutral) and offer a basic explanation.",
)
if __name__ == "__main__":
iface.launch() |