Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Imports
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
print("Torch version:", torch.__version__)
|
| 7 |
+
# Create the sentiment analysis pipeline
|
| 8 |
+
sentiment_pipe = pipeline("sentiment-analysis")
|
| 9 |
+
|
| 10 |
+
# Define analysis function
|
| 11 |
+
def analyze_sentiment(text):
|
| 12 |
+
result = sentiment_pipe(text)[0]
|
| 13 |
+
label = result["label"]
|
| 14 |
+
score = result["score"]
|
| 15 |
+
|
| 16 |
+
if label == "POSITIVE":
|
| 17 |
+
emoji = "π"
|
| 18 |
+
img_url = "https://thepreachersword.com/wp-content/uploads/2017/05/cheerful.jpg" # cheerful
|
| 19 |
+
sentiment_text = f"Positive sentiment detected! Confidence: {score:.2f} {emoji}"
|
| 20 |
+
elif label == "NEGATIVE":
|
| 21 |
+
emoji = "π"
|
| 22 |
+
img_url = "https://cdn.pixabay.com/photo/2024/04/24/14/24/ai-generated-8717915_640.png" # sad
|
| 23 |
+
sentiment_text = f"Negative sentiment detected! Confidence: {score:.2f} {emoji}"
|
| 24 |
+
else:
|
| 25 |
+
emoji = "π"
|
| 26 |
+
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
|
| 27 |
+
sentiment_text = f"Neutral or other sentiment detected. Confidence: {score:.2f} {emoji}"
|
| 28 |
+
|
| 29 |
+
return sentiment_text, img_url
|
| 30 |
+
|
| 31 |
+
# Create Gradio Blocks interface
|
| 32 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="teal")) as demo:
|
| 33 |
+
gr.Markdown(
|
| 34 |
+
"""
|
| 35 |
+
# π Sentiment Analysis App
|
| 36 |
+
Enter any text below to analyze its sentiment and see a matching mood image!
|
| 37 |
+
"""
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
text_input = gr.Textbox(label="Enter your text", placeholder="Write something here...")
|
| 41 |
+
analyze_button = gr.Button("Analyze Sentiment π")
|
| 42 |
+
|
| 43 |
+
output_text = gr.Textbox(label="Sentiment Result")
|
| 44 |
+
output_image = gr.Image(label="Mood Image", interactive=False)
|
| 45 |
+
|
| 46 |
+
analyze_button.click(fn=analyze_sentiment, inputs=text_input, outputs=[output_text, output_image])
|
| 47 |
+
|
| 48 |
+
# Launch the app
|
| 49 |
+
demo.launch()
|