myanmar-ghost / app.py
amkyawdev's picture
Add Gradio app
3389b47 verified
Raw
History Blame Contribute Delete
5.46 kB
"""
Myanmar Ghost - Gradio Demo for HuggingFace Spaces
This app provides an interactive demo for Myanmar sentiment analysis.
"""
import gradio as gr
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
# Try to import the model components
try:
from src.data_processing.text_normalizer import MyanmarTextNormalizer
from src.augmentation.synonym_replacer import MyanmarSynonymReplacer
MODULES_LOADED = True
except ImportError as e:
MODULES_LOADED = False
print(f"Warning: Some modules not loaded: {e}")
# Sentiment labels
SENTIMENT_LABELS = ["negative", "neutral", "positive", "sarcastic"]
# Initialize components
normalizer = MyanmarTextNormalizer() if MODULES_LOADED else None
replacer = MyanmarSynonymReplacer() if MODULES_LOADED else None
def analyze_sentiment(text: str) -> dict:
"""Analyze sentiment of Myanmar text."""
if not text.strip():
return {
"text": text,
"sentiment": "neutral",
"confidence": 0.0,
"probabilities": {label: 0.25 for label in SENTIMENT_LABELS},
}
# Normalize text
if normalizer:
normalized = normalizer.normalize_line(text)
else:
normalized = text
# Mock prediction (replace with actual model)
# In production, load the trained model here
import random
probs = [random.random() for _ in SENTIMENT_LABELS]
total = sum(probs)
probs = [p/total for p in probs]
pred_idx = probs.index(max(probs))
return {
"text": text,
"normalized_text": normalized if normalizer else text,
"sentiment": SENTIMENT_LABELS[pred_idx],
"confidence": max(probs),
"probabilities": {SENTIMENT_LABELS[i]: probs[i] for i in range(4)},
}
def get_synonyms(text: str) -> str:
"""Get synonym replacements for text."""
if not replacer or not text.strip():
return "Enter Myanmar text to see synonym examples"
aug_text, replacements = replacer.augment_text(text, replace_prob=0.5)
if not replacements:
return f"No synonym replacements found for: {text}"
result = f"Original: {text}\n\nAugmented: {aug_text}\n\nReplacements:\n"
for orig, new in replacements:
result += f" β€’ {orig} β†’ {new}\n"
return result
def show_probabilities(text: str) -> dict:
"""Show probability distribution."""
result = analyze_sentiment(text)
return result["probabilities"]
# Create Gradio interface
with gr.Blocks(
title="Myanmar Ghost - Sentiment Analysis",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown("""
# πŸ‡²πŸ‡² Myanmar Ghost
### Advanced Myanmar Sentiment Analysis
Enter Myanmar text to analyze sentiment. Supports:
- βœ… Positive/Negative/Neutral/Sarcastic classification
- πŸ”€ Text normalization
- πŸ“ Synonym augmentation
""")
with gr.Row():
with gr.Column(scale=2):
text_input = gr.Textbox(
label="Myanmar Text Input",
placeholder="ကျေးဇူးပါ α€™α€„α€Ία€Ήα€‚α€œα€¬α€•α€«...",
lines=3,
)
with gr.Row():
analyze_btn = gr.Button("πŸ” Analyze", variant="primary")
clear_btn = gr.Button("πŸ—‘οΈ Clear")
with gr.Column(scale=1):
sentiment_output = gr.Label(
label="Predicted Sentiment",
)
# Probabilities
gr.Markdown("### πŸ“Š Confidence Scores")
prob_display = gr.BarPlot(
x=["negative", "neutral", "positive", "sarcastic"],
y=[0.25, 0.25, 0.25, 0.25],
label="Probability Distribution",
y_lab="Probability",
x_lab="Sentiment",
)
# Synonym tool
gr.Markdown("### πŸ“ Synonym Augmentation")
with gr.Row():
synonym_input = gr.Textbox(
label="Text for Synonyms",
placeholder="Enter text to see synonym replacements...",
lines=2,
)
synonym_btn = gr.Button("πŸ”„ Get Synonyms")
synonym_output = gr.Textbox(
label="Synonym Results",
lines=4,
)
# Examples
gr.Examples(
examples=[
["ကျေးဇူးပါ"],
["α€™α€„α€Ία€Ήα€‚α€œα€¬α€•α€«"],
["မကျေနပ်ပါဗျ"],
["α€‘α€›α€™α€Ία€Έα€€α€±α€¬α€„α€Ία€Έα€α€šα€Ί"],
],
inputs=text_input,
)
# Event handlers
analyze_btn.click(
fn=analyze_sentiment,
inputs=text_input,
outputs=[sentiment_output, prob_display],
)
clear_btn.click(
fn=lambda: ("", {"negative": 0.25, "neutral": 0.25, "positive": 0.25, "sarcastic": 0.25}),
inputs=[],
outputs=[text_input, sentiment_output],
)
synonym_btn.click(
fn=get_synonyms,
inputs=synonym_input,
outputs=synonym_output,
)
gr.Markdown("""
---
### ℹ️ About
Myanmar Ghost is an advanced NLP project for Myanmar language understanding.
- **Model**: Transformer-based sentiment classifier
- **Features**: Multi-modal fusion, Active Learning, XAI
- **Author**: [Aung Myo Kyaw](https://huggingface.co/amkyawdev)
[GitHub Repository](https://github.com/amkyawdev/myanmar-ghost)
""")
if __name__ == "__main__":
demo.launch()