Khalid707's picture
Create app.py
07568cc verified
# Imports
import gradio as gr
from transformers import pipeline
import torch
print("Torch version:", torch.__version__)
# Create the sentiment analysis pipeline
sentiment_pipe = pipeline("sentiment-analysis")
# Define analysis function
def analyze_sentiment(text):
result = sentiment_pipe(text)[0]
label = result["label"]
score = result["score"]
if label == "POSITIVE":
emoji = "😊"
img_url = "https://thepreachersword.com/wp-content/uploads/2017/05/cheerful.jpg" # cheerful
sentiment_text = f"Positive sentiment detected! Confidence: {score:.2f} {emoji}"
elif label == "NEGATIVE":
emoji = "😞"
img_url = "https://cdn.pixabay.com/photo/2024/04/24/14/24/ai-generated-8717915_640.png" # sad
sentiment_text = f"Negative sentiment detected! Confidence: {score:.2f} {emoji}"
else:
emoji = "😐"
img_url = "https://media.istockphoto.com/id/1453968261/photo/thoughtful-senior-man-looks-into-copy-space-as-he-stands-outdoors-in-nature.jpg?s=612x612&w=0&k=20&c=V6KOTTki3thkrDNqIG4QBvmpCAoqO9aQ-9mtSy2BR9k=" # neutral
sentiment_text = f"Neutral or other sentiment detected. Confidence: {score:.2f} {emoji}"
return sentiment_text, img_url
# Create Gradio Blocks interface
with gr.Blocks(theme=gr.themes.Default(primary_hue="teal")) as demo:
gr.Markdown(
"""
# πŸ“ Sentiment Analysis App
Enter any text below to analyze its sentiment and see a matching mood image!
"""
)
text_input = gr.Textbox(label="Enter your text", placeholder="Write something here...")
analyze_button = gr.Button("Analyze Sentiment πŸ”")
output_text = gr.Textbox(label="Sentiment Result")
output_image = gr.Image(label="Mood Image", interactive=False)
analyze_button.click(fn=analyze_sentiment, inputs=text_input, outputs=[output_text, output_image])
# Launch the app
demo.launch()