Sentiment_demo / app.py
anabury's picture
Update app.py
91f79af verified
raw
history blame
2.83 kB
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
from langdetect import detect
from googletrans import Translator
# Multilingual sentiment model
MODEL = "nlptown/bert-base-multilingual-uncased-sentiment"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
sentiment_model = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
translator = Translator()
# Map stars (1–5) to emotion labels with emojis
STAR_EMOJIS = {
1: "😡 Very Negative",
2: "☹️ Negative",
3: "😐 Neutral",
4: "🙂 Positive",
5: "🤩 Very Positive"
}
# Suggested actions in English
ACTIONS = {
1: "Take a break, reflect on the situation, or seek support.",
2: "Consider what’s bothering you and try to address it calmly.",
3: "Maintain balance; you’re feeling neutral, continue as usual.",
4: "Share your positive experience and stay motivated!",
5: "Celebrate and spread your joy; keep up the enthusiasm!"
}
def analyze_sentiment(text):
# Sentiment analysis
result = sentiment_model(text)[0]
stars = int(result["label"][0])
sentiment = STAR_EMOJIS.get(stars, result["label"])
confidence = f"{result['score']:.2f}"
# Detect language
try:
lang = detect(text)
except:
lang = "en"
# Translate action to detected language
action_en = ACTIONS.get(stars, "")
if lang != "en":
try:
action_translated = translator.translate(action_en, dest=lang).text
except:
action_translated = action_en
else:
action_translated = action_en
return [[sentiment, confidence, action_translated]]
# Example texts including Yoruba
examples = [
["I absolutely love this new phone, the camera is stunning!"], # English
["Mo nifẹ́ fíìmù yìí gan-an!"], # Yoruba Positive
["Mo bínú gan-an sí ìṣẹ̀lẹ̀ náà."], # Yoruba Negative
["Je déteste quand cette application plante sans cesse."], # French
]
# Gradio UI
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(lines=3, placeholder="Type a sentence in any supported language..."),
outputs=gr.Dataframe(
headers=["Emotion (1–5 Stars)", "Confidence", "What to do"],
row_count=1,
col_count=(3, "fixed"),
),
examples=examples,
title="🌍 Multilingual Emotion & Action Analyzer",
description=(
"Supports multiple languages including English, Yoruba, French, German, Spanish, etc. "
"Detects emotion (1–5 stars) and provides suggested actions in the same language as input."
),
)
if __name__ == "__main__":
demo.launch()