Ling / ui /sentiment_ui.py
Nam Fam
update files
ea99abb
import gradio as gr
from utils.ner_helpers import is_llm_model
from typing import Dict, List, Any
from tasks.sentiment_analysis import sentiment_analysis
def sentiment_ui():
"""Sentiment analysis UI component"""
# Define models
SENTIMENT_MODELS = [
"gemini-2.0-flash" # Only allow gemini-2.0-flash for now
# "gpt-4",
# "claude-2",
# "distilbert-base-uncased-finetuned-sst-2-english",
# "finiteautomata/bertweet-base-sentiment-analysis"
]
DEFAULT_MODEL = "gemini-2.0-flash"
def analyze_sentiment(text, model, custom_instructions):
"""Process text for sentiment analysis"""
if not text.strip():
return "No text provided"
use_llm = is_llm_model(model)
result = sentiment_analysis(
text=text,
model=model,
custom_instructions=custom_instructions,
use_llm=use_llm
)
# Try to normalize the result
result = result.lower().strip()
if "positive" in result:
return "Positive"
elif "negative" in result:
return "Negative"
elif "neutral" in result:
return "Neutral"
else:
# Return as is for other results
return result
# UI Components
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
label="Input Text",
lines=6,
placeholder="Enter text to analyze sentiment...",
elem_id="sentiment-input-text"
)
gr.Examples(
examples=[
["I am very satisfied with the customer service of this company."],
["The product did not meet my expectations and I am disappointed."]
],
inputs=[input_text],
label="Examples"
)
model = gr.Dropdown(
SENTIMENT_MODELS,
value=DEFAULT_MODEL,
label="Model",
interactive=True,
elem_id="sentiment-model-dropdown"
)
custom_instructions = gr.Textbox(
label="Custom Instructions (optional)",
lines=2,
placeholder="Add any custom instructions for the model...",
elem_id="sentiment-custom-instructions"
)
btn = gr.Button("Analyze Sentiment", variant="primary", elem_id="sentiment-analyze-btn")
with gr.Column():
output = gr.Textbox(
label="Sentiment Analysis",
elem_id="sentiment-output"
)
# with gr.Accordion("About Sentiment Analysis", open=False):
# gr.Markdown("""
# ## Sentiment Analysis
# Sentiment analysis identifies the emotional tone behind text. The model analyzes your input text and classifies it as:
# - **Positive**: Text expresses positive emotions, approval, or optimism
# - **Negative**: Text expresses negative emotions, criticism, or pessimism
# - **Neutral**: Text is factual or does not express strong sentiment
# ### Model Types
# - **LLM Models** (Gemini, GPT, Claude): Provide sophisticated analysis with better understanding of context
# - **Traditional Models**: Specialized models trained specifically for sentiment analysis tasks
# Use the advanced options to customize how the model analyzes your text.
# """)
# Event handlers
btn.click(
analyze_sentiment,
inputs=[input_text, model, custom_instructions],
outputs=output
)
return None