File size: 5,781 Bytes
b3c6a04 |
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
"""
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()
|