import gradio as gr from transformers import pipeline import matplotlib.pyplot as plt from wordcloud import WordCloud # Load sentiment analysis model sentiment_pipeline = pipeline("sentiment-analysis") # Function to analyze sentiment def analyze_sentiment(text): if not text.strip(): return "Enter text to analyze.", "", None, "" result = sentiment_pipeline(text)[0] sentiment, confidence = result['label'], result['score'] sentiment_map = { "POSITIVE": ("🟢 Positive 😊", "green"), "NEGATIVE": ("🔴 Negative 😠", "red"), "NEUTRAL": ("🟡 Neutral 😐", "orange") } sentiment_label, color = sentiment_map.get(sentiment.upper(), ("⚪ Unknown ❓", "gray")) # Generate Word Cloud wordcloud = WordCloud(width=400, height=200, background_color="white").generate(text) fig, ax = plt.subplots() ax.imshow(wordcloud, interpolation='bilinear') ax.axis("off") return sentiment_label, f"Confidence: {confidence:.2%}", fig, text # UI Layout with gr.Blocks(theme=gr.themes.Soft()) as iface: gr.Markdown("# 🎭 AI Sentiment Analyzer") gr.Markdown("Analyze sentiment in real-time with enhanced visualization.") with gr.Row(): dark_mode = gr.Checkbox(label="🌙 Dark Mode") text_input = gr.Textbox(lines=3, placeholder="Type your text here...", label="Your Input") analyze_button = gr.Button("Analyze Sentiment ✨") reset_button = gr.Button("🔄 Reset") with gr.Row(): sentiment_output = gr.Label(label="Sentiment Result") confidence_output = gr.Label(label="Confidence Score") wordcloud_output = gr.Plot(label="Word Cloud Visualization") # Attach event handlers AFTER defining components text_input.change(analyze_sentiment, inputs=text_input, outputs=[sentiment_output, confidence_output, wordcloud_output, text_input]) analyze_button.click(analyze_sentiment, inputs=text_input, outputs=[sentiment_output, confidence_output, wordcloud_output, text_input]) reset_button.click(lambda: ("", "", None, ""), inputs=[], outputs=[sentiment_output, confidence_output, wordcloud_output, text_input]) # Launch the app if __name__ == "__main__": iface.launch()