Spaces:
Sleeping
Sleeping
File size: 2,604 Bytes
3547fac c886af8 3547fac c886af8 3547fac c886af8 3547fac e031e10 3547fac c886af8 3547fac c886af8 3547fac | 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch.nn.functional as F
# Load Pretrained Model & Tokenizer
MODEL_NAME = "nlptown/bert-base-multilingual-uncased-sentiment" # Pretrained sentiment model
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
# Function for sentiment analysis
def analyze_sentiment(user_input):
if user_input.strip():
# Tokenize and Convert Input to Tensor
inputs = tokenizer(user_input, return_tensors="pt", truncation=True, padding=True)
# Perform Sentiment Analysis
with torch.no_grad():
outputs = model(**inputs)
scores = F.softmax(outputs.logits, dim=-1).squeeze().tolist()
# Interpret Results
labels = ["้ๅธธใซๅฆๅฎ็ ๐ก", "ๅฆๅฎ็ ๐", "ไธญ็ซ็ ๐", "่ฏๅฎ็ ๐", "้ๅธธใซ่ฏๅฎ็ ๐"]
sentiment = labels[scores.index(max(scores))] # Select sentiment with highest score
# Format Confidence Scores
confidence = "\n".join([f"{label}: {score:.2%}" for label, score in zip(labels, scores)])
return f"ไบๆธฌใใใๆๆ
: {sentiment}", confidence, sentiment # Returning sentiment separately
else:
return "โ ๏ธ Please enter text before analyzing.", "", ""
# Gradio Blocks interface
with gr.Blocks() as app:
gr.Markdown("## ๐ฅ ๆๆ
ๅๆ")
gr.Markdown("ๅๆใใใใญในใใๅ
ฅๅใใฆใใ ใใ")
# Text input
user_input = gr.Textbox(label="ๅๆใใใใญในใ", info="ใทใณใฌใใผใซใง้ใใใฆใใใขใธใขๅฎๅ
จไฟ้ไผ่ญฐใงๆผ่ชฌใใใขใกใชใซใฎใใฐใปในๅฝ้ฒ้ทๅฎใๅฐๆนพๆ
ๅขใชใฉใใใใไธญๅฝใๅๆใใใฆ็นฐใ่ฟใ้้ฃใใใใจใๅใใไธญๅฝๅคๅ็ใฏใขใกใชใซๅดใซๆ่ญฐใใใใจใๆใใใซใใพใใใ")
# Outputs
sentiment_output = gr.Textbox(label="ไบๆธฌใใใๆๆ
", interactive=False)
confidence_output = gr.Textbox(label="็ขบไฟกๅบฆ", interactive=False)
top_sentiment_output = gr.Textbox(label="ๆใ้ซใๆๆ
", interactive=False) # New output for top sentiment
# Button to trigger analysis
analyze_button = gr.Button("ๆๆ
ๅๆ")
# Connect button to function
analyze_button.click(
fn=analyze_sentiment,
inputs=[user_input],
outputs=[sentiment_output, confidence_output, top_sentiment_output] # Include new output
)
# Launch the Gradio app
app.launch()
|