Spaces:
Sleeping
Sleeping
| 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() | |