""" Sentiment Analysis β€” Positive / Negative / Neutral Course: 100 Deep Learning ch4 """ import gradio as gr from transformers import pipeline # Multi-language sentiment model classifier = pipeline( "sentiment-analysis", model="lxyuan/distilbert-base-multilingual-cased-sentiments-student", ) LABEL_MAP = { "positive": "Positive", "negative": "Negative", "neutral": "Neutral", } EMOJI_MAP = { "positive": "😊", "negative": "😞", "neutral": "😐", } def analyze(text: str): if not text.strip(): return {}, "" results = classifier(text, top_k=3) label_dict = { f"{EMOJI_MAP.get(r['label'], '')} {LABEL_MAP.get(r['label'], r['label'])}": round(r["score"], 4) for r in results } top = results[0] emoji = EMOJI_MAP.get(top["label"], "") summary = ( f"**Prediction: {emoji} {LABEL_MAP.get(top['label'], top['label'])}** " f"({top['score']:.1%} confidence)\n\n" f"| Label | Score |\n|---|---|\n" ) for r in results: bar_len = int(r["score"] * 30) bar = "β–ˆ" * bar_len + "β–‘" * (30 - bar_len) summary += f"| {LABEL_MAP.get(r['label'], r['label'])} | {bar} {r['score']:.1%} |\n" return label_dict, summary with gr.Blocks(title="Sentiment Analysis") as demo: gr.Markdown( "# Sentiment Analysis\n" "Enter text in any language to analyze its sentiment.\n" "Uses a multilingual DistilBERT model.\n" "*Course: 100 Deep Learning ch4 β€” RNN & Sequence Models*" ) with gr.Row(): with gr.Column(): text_input = gr.Textbox( label="Input Text", placeholder="Type or paste text here...", lines=4, ) btn = gr.Button("Analyze Sentiment", variant="primary") with gr.Column(): label_out = gr.Label(num_top_classes=3, label="Sentiment Scores") detail_md = gr.Markdown() btn.click(analyze, [text_input], [label_out, detail_md]) text_input.submit(analyze, [text_input], [label_out, detail_md]) gr.Examples( examples=[ "I absolutely love this product! It exceeded all my expectations.", "The movie was terrible. Worst 2 hours of my life.", "The weather today is partly cloudy with temperatures around 72Β°F.", "θΏ™δΈͺι€εŽ…ηš„ι£Ÿη‰©ιžεΈΈε₯½εƒοΌŒζœεŠ‘δΉŸεΎˆζ£’οΌ", "I'm not sure how I feel about the new update. It has some good features but also some bugs.", "Das Essen war hervorragend und die Bedienung sehr freundlich.", ], inputs=[text_input], ) if __name__ == "__main__": demo.launch()