amkyawdev commited on
Commit
3389b47
Β·
verified Β·
1 Parent(s): 8f6910f

Add Gradio app

Browse files
Files changed (1) hide show
  1. app.py +192 -0
app.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Myanmar Ghost - Gradio Demo for HuggingFace Spaces
3
+
4
+ This app provides an interactive demo for Myanmar sentiment analysis.
5
+ """
6
+
7
+ import gradio as gr
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ # Add src to path
12
+ sys.path.insert(0, str(Path(__file__).parent))
13
+
14
+ # Try to import the model components
15
+ try:
16
+ from src.data_processing.text_normalizer import MyanmarTextNormalizer
17
+ from src.augmentation.synonym_replacer import MyanmarSynonymReplacer
18
+ MODULES_LOADED = True
19
+ except ImportError as e:
20
+ MODULES_LOADED = False
21
+ print(f"Warning: Some modules not loaded: {e}")
22
+
23
+
24
+ # Sentiment labels
25
+ SENTIMENT_LABELS = ["negative", "neutral", "positive", "sarcastic"]
26
+
27
+ # Initialize components
28
+ normalizer = MyanmarTextNormalizer() if MODULES_LOADED else None
29
+ replacer = MyanmarSynonymReplacer() if MODULES_LOADED else None
30
+
31
+
32
+ def analyze_sentiment(text: str) -> dict:
33
+ """Analyze sentiment of Myanmar text."""
34
+ if not text.strip():
35
+ return {
36
+ "text": text,
37
+ "sentiment": "neutral",
38
+ "confidence": 0.0,
39
+ "probabilities": {label: 0.25 for label in SENTIMENT_LABELS},
40
+ }
41
+
42
+ # Normalize text
43
+ if normalizer:
44
+ normalized = normalizer.normalize_line(text)
45
+ else:
46
+ normalized = text
47
+
48
+ # Mock prediction (replace with actual model)
49
+ # In production, load the trained model here
50
+ import random
51
+ probs = [random.random() for _ in SENTIMENT_LABELS]
52
+ total = sum(probs)
53
+ probs = [p/total for p in probs]
54
+
55
+ pred_idx = probs.index(max(probs))
56
+
57
+ return {
58
+ "text": text,
59
+ "normalized_text": normalized if normalizer else text,
60
+ "sentiment": SENTIMENT_LABELS[pred_idx],
61
+ "confidence": max(probs),
62
+ "probabilities": {SENTIMENT_LABELS[i]: probs[i] for i in range(4)},
63
+ }
64
+
65
+
66
+ def get_synonyms(text: str) -> str:
67
+ """Get synonym replacements for text."""
68
+ if not replacer or not text.strip():
69
+ return "Enter Myanmar text to see synonym examples"
70
+
71
+ aug_text, replacements = replacer.augment_text(text, replace_prob=0.5)
72
+
73
+ if not replacements:
74
+ return f"No synonym replacements found for: {text}"
75
+
76
+ result = f"Original: {text}\n\nAugmented: {aug_text}\n\nReplacements:\n"
77
+ for orig, new in replacements:
78
+ result += f" β€’ {orig} β†’ {new}\n"
79
+
80
+ return result
81
+
82
+
83
+ def show_probabilities(text: str) -> dict:
84
+ """Show probability distribution."""
85
+ result = analyze_sentiment(text)
86
+ return result["probabilities"]
87
+
88
+
89
+ # Create Gradio interface
90
+ with gr.Blocks(
91
+ title="Myanmar Ghost - Sentiment Analysis",
92
+ theme=gr.themes.Soft(),
93
+ ) as demo:
94
+
95
+ gr.Markdown("""
96
+ # πŸ‡²πŸ‡² Myanmar Ghost
97
+ ### Advanced Myanmar Sentiment Analysis
98
+
99
+ Enter Myanmar text to analyze sentiment. Supports:
100
+ - βœ… Positive/Negative/Neutral/Sarcastic classification
101
+ - πŸ”€ Text normalization
102
+ - πŸ“ Synonym augmentation
103
+ """)
104
+
105
+ with gr.Row():
106
+ with gr.Column(scale=2):
107
+ text_input = gr.Textbox(
108
+ label="Myanmar Text Input",
109
+ placeholder="ကျေးဇူးပါ α€™α€„α€Ία€Ήα€‚α€œα€¬α€•α€«...",
110
+ lines=3,
111
+ )
112
+
113
+ with gr.Row():
114
+ analyze_btn = gr.Button("πŸ” Analyze", variant="primary")
115
+ clear_btn = gr.Button("πŸ—‘οΈ Clear")
116
+
117
+ with gr.Column(scale=1):
118
+ sentiment_output = gr.Label(
119
+ label="Predicted Sentiment",
120
+ )
121
+
122
+ # Probabilities
123
+ gr.Markdown("### πŸ“Š Confidence Scores")
124
+ prob_display = gr.BarPlot(
125
+ x=["negative", "neutral", "positive", "sarcastic"],
126
+ y=[0.25, 0.25, 0.25, 0.25],
127
+ label="Probability Distribution",
128
+ y_lab="Probability",
129
+ x_lab="Sentiment",
130
+ )
131
+
132
+ # Synonym tool
133
+ gr.Markdown("### πŸ“ Synonym Augmentation")
134
+ with gr.Row():
135
+ synonym_input = gr.Textbox(
136
+ label="Text for Synonyms",
137
+ placeholder="Enter text to see synonym replacements...",
138
+ lines=2,
139
+ )
140
+ synonym_btn = gr.Button("πŸ”„ Get Synonyms")
141
+
142
+ synonym_output = gr.Textbox(
143
+ label="Synonym Results",
144
+ lines=4,
145
+ )
146
+
147
+ # Examples
148
+ gr.Examples(
149
+ examples=[
150
+ ["ကျေးဇူးပါ"],
151
+ ["α€™α€„α€Ία€Ήα€‚α€œα€¬α€•α€«"],
152
+ ["မကျေနပ်ပါဗျ"],
153
+ ["α€‘α€›α€™α€Ία€Έα€€α€±α€¬α€„α€Ία€Έα€α€šα€Ί"],
154
+ ],
155
+ inputs=text_input,
156
+ )
157
+
158
+ # Event handlers
159
+ analyze_btn.click(
160
+ fn=analyze_sentiment,
161
+ inputs=text_input,
162
+ outputs=[sentiment_output, prob_display],
163
+ )
164
+
165
+ clear_btn.click(
166
+ fn=lambda: ("", {"negative": 0.25, "neutral": 0.25, "positive": 0.25, "sarcastic": 0.25}),
167
+ inputs=[],
168
+ outputs=[text_input, sentiment_output],
169
+ )
170
+
171
+ synonym_btn.click(
172
+ fn=get_synonyms,
173
+ inputs=synonym_input,
174
+ outputs=synonym_output,
175
+ )
176
+
177
+ gr.Markdown("""
178
+ ---
179
+ ### ℹ️ About
180
+
181
+ Myanmar Ghost is an advanced NLP project for Myanmar language understanding.
182
+
183
+ - **Model**: Transformer-based sentiment classifier
184
+ - **Features**: Multi-modal fusion, Active Learning, XAI
185
+ - **Author**: [Aung Myo Kyaw](https://huggingface.co/amkyawdev)
186
+
187
+ [GitHub Repository](https://github.com/amkyawdev/myanmar-ghost)
188
+ """)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ demo.launch()