Sentiment / app.py
amirrezaa's picture
Update app.py
03e61f9 verified
"""
Gradio App for Multilingual Sentiment Analysis
"""
import gradio as gr
from sentiment_analyzer import MultilingualSentimentAnalyzer
def analyze_sentiment(text, language, method):
"""Analyze sentiment and return formatted results"""
if not text or not text.strip():
return "Please enter some text to analyze."
try:
analyzer = MultilingualSentimentAnalyzer(language=language, method=method)
result = analyzer.analyze(text)
# Format the output nicely
output = f"""
## Sentiment Analysis Results
**Polarity:** {result['polarity'].upper()}
**Confidence:** {result['confidence']*100:.1f}%
**Scores:**
- Positive: {result['positive_score']:.2f}
- Negative: {result['negative_score']:.2f}
**Details:**
- Method: {result['method']}
- Language: {result['language']}
- Words analyzed: {result.get('word_count', 0)}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
def batch_analyze(texts, language, method):
"""Analyze multiple texts"""
if not texts:
return "Please enter texts to analyze (one per line)."
text_list = [t.strip() for t in texts.split('\n') if t.strip()]
if not text_list:
return "No valid texts found."
try:
analyzer = MultilingualSentimentAnalyzer(language=language, method=method)
results = analyzer.analyze_batch(text_list)
stats = analyzer.get_statistics(text_list)
output = f"""
## Batch Analysis Results
**Statistics:**
- Total texts: {stats['total_texts']}
- Average confidence: {stats['average_confidence']*100:.1f}%
**Polarity Distribution:**
"""
for polarity, percentage in stats['polarity_percentages'].items():
output += f"- {polarity.capitalize()}: {percentage}%\n"
output += "\n**Individual Results:**\n"
for i, (text, result) in enumerate(zip(text_list, results), 1):
output += f"\n{i}. \"{text[:50]}...\" → {result['polarity']} ({result['confidence']*100:.1f}%)\n"
return output
except Exception as e:
return f"Error: {str(e)}"
# Create Gradio interface
with gr.Blocks(title="Multilingual Sentiment Analysis", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 🌍 Multilingual Sentiment Analysis Tool
Analyze sentiment in **English**, **Turkish**, and **Persian** text using non-deep-learning approaches.
This tool uses lexicon-based, rule-based, and hybrid methods for interpretable sentiment analysis.
""")
with gr.Tabs():
with gr.TabItem("Single Text Analysis"):
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="Enter Text",
placeholder="Type your text here...",
lines=5
)
language = gr.Dropdown(
choices=["english", "turkish", "persian"],
value="english",
label="Language"
)
method = gr.Dropdown(
choices=["lexicon", "rule", "hybrid"],
value="hybrid",
label="Analysis Method"
)
analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
with gr.Column():
output = gr.Markdown(label="Results")
analyze_btn.click(
fn=analyze_sentiment,
inputs=[text_input, language, method],
outputs=output
)
with gr.TabItem("Batch Analysis"):
with gr.Row():
with gr.Column():
batch_texts = gr.Textbox(
label="Enter Texts (one per line)",
placeholder="Enter multiple texts, one per line...",
lines=10
)
batch_language = gr.Dropdown(
choices=["english", "turkish", "persian"],
value="english",
label="Language"
)
batch_method = gr.Dropdown(
choices=["lexicon", "rule", "hybrid"],
value="hybrid",
label="Analysis Method"
)
batch_btn = gr.Button("Analyze Batch", variant="primary")
with gr.Column():
batch_output = gr.Markdown(label="Batch Results")
batch_btn.click(
fn=batch_analyze,
inputs=[batch_texts, batch_language, batch_method],
outputs=batch_output
)
with gr.TabItem("Examples"):
gr.Markdown("""
### Example Texts to Try:
**English:**
- "I love this product! It's absolutely amazing!!! 😊"
- "This is terrible. I hate it."
- "Not bad, actually it's quite good!"
**Turkish:**
- "Bu ürünü çok seviyorum! Harika!"
- "Berbat bir deneyim. Hiç beğenmedim."
**Persian:**
- "این محصول عالی است!"
- "خیلی بد بود"
""")
gr.Markdown("""
---
**About:** This tool uses lexicon-based, rule-based, and hybrid approaches (without deep learning)
for interpretable sentiment analysis. Supports English, Turkish, and Persian languages.
""")
if __name__ == "__main__":
demo.launch()