fudii0921's picture
Update app.py
e031e10 verified
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()