File size: 5,463 Bytes
3389b47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""
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()