File size: 1,452 Bytes
afc1774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import gradio as gr
from transformers import pipeline

# Load sentiment analysis model
sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment")

# Custom label mapping for multi-level output
label_map = {
    "LABEL_0": "Very Negative",
    "LABEL_1": "Negative",
    "LABEL_2": "Neutral",
    "LABEL_3": "Positive",
    "LABEL_4": "Very Positive"
}

def advanced_sentiment_analysis(text):
    # Predict sentiment
    result = sentiment_pipeline(text, top_k=None)[0]
    
    # Sum total scores for normalization (if needed)
    total_score = sum([entry['score'] for entry in result])
    
    # Build formatted output
    formatted_output = ""
    for entry in result:
        label = label_map.get(entry['label'], entry['label'])
        percentage = (entry['score'] / total_score) * 100
        formatted_output += f"{label}: {percentage:.2f}%\n"
    
    return formatted_output.strip()

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("### Welcome, please enter a sample of what you may respond or tell a customer,let's tell you how cool it is")
    with gr.Row():
        text_input = gr.Textbox(lines=4, placeholder="Type your message here...", label="Customer Message")
    output = gr.Textbox(label="Sentiment Analysis Result")
    analyze_button = gr.Button("Analyze Sentiment")
    
    analyze_button.click(fn=advanced_sentiment_analysis, inputs=text_input, outputs=output)

demo.launch()