Delete api_example.py
Browse files- api_example.py +0 -235
api_example.py
DELETED
|
@@ -1,235 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
API Example untuk Sentiment Analysis
|
| 3 |
-
Contoh penggunaan model secara programmatic (tanpa Gradio UI)
|
| 4 |
-
Berguna untuk integrasi dengan sistem lain
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from app import SentimentAnalyzer
|
| 8 |
-
import json
|
| 9 |
-
|
| 10 |
-
def example_basic_usage():
|
| 11 |
-
"""Contoh penggunaan dasar"""
|
| 12 |
-
print("=" * 60)
|
| 13 |
-
print("EXAMPLE 1: Basic Usage")
|
| 14 |
-
print("=" * 60)
|
| 15 |
-
|
| 16 |
-
# Initialize analyzer
|
| 17 |
-
analyzer = SentimentAnalyzer()
|
| 18 |
-
|
| 19 |
-
# Analyze single text
|
| 20 |
-
text = "Bantuan bencana sangat lambat, sudah 3 hari belum dapat makanan!"
|
| 21 |
-
result = analyzer.analyze(text)
|
| 22 |
-
|
| 23 |
-
print(f"\nText: {text}")
|
| 24 |
-
print(f"Result: {json.dumps(result, indent=2, ensure_ascii=False)}")
|
| 25 |
-
|
| 26 |
-
def example_batch_processing():
|
| 27 |
-
"""Contoh batch processing untuk admin bencana"""
|
| 28 |
-
print("\n" + "=" * 60)
|
| 29 |
-
print("EXAMPLE 2: Batch Processing for Emergency Admin")
|
| 30 |
-
print("=" * 60)
|
| 31 |
-
|
| 32 |
-
analyzer = SentimentAnalyzer()
|
| 33 |
-
|
| 34 |
-
# Simulasi pesan dari masyarakat
|
| 35 |
-
messages = [
|
| 36 |
-
"Posko pengungsian penuh, tidak ada tempat tidur!",
|
| 37 |
-
"Terima kasih atas bantuan yang cepat",
|
| 38 |
-
"Kapan distribusi bantuan selanjutnya?",
|
| 39 |
-
"Air bersih habis, kondisi darurat!",
|
| 40 |
-
"Tim medis sangat membantu, terima kasih",
|
| 41 |
-
"Bagaimana cara mendapatkan bantuan?",
|
| 42 |
-
"Hadeh lambat banget nih pelayanan!",
|
| 43 |
-
"Alhamdulillah bantuan sudah sampai"
|
| 44 |
-
]
|
| 45 |
-
|
| 46 |
-
# Batch analysis
|
| 47 |
-
results = analyzer.batch_analyze(messages)
|
| 48 |
-
|
| 49 |
-
# Categorize by priority
|
| 50 |
-
high_priority = [] # NEGATIVE with high confidence
|
| 51 |
-
medium_priority = [] # NEGATIVE with medium confidence
|
| 52 |
-
low_priority = [] # POSITIVE or NEUTRAL
|
| 53 |
-
|
| 54 |
-
for msg, result in zip(messages, results):
|
| 55 |
-
if result['label'] == 'NEGATIVE':
|
| 56 |
-
if result['confidence'] >= 0.8:
|
| 57 |
-
high_priority.append((msg, result))
|
| 58 |
-
else:
|
| 59 |
-
medium_priority.append((msg, result))
|
| 60 |
-
else:
|
| 61 |
-
low_priority.append((msg, result))
|
| 62 |
-
|
| 63 |
-
# Display results
|
| 64 |
-
print(f"\n📊 Processing Summary:")
|
| 65 |
-
print(f" Total messages: {len(messages)}")
|
| 66 |
-
print(f" 🔴 High Priority (Urgent): {len(high_priority)}")
|
| 67 |
-
print(f" 🟡 Medium Priority: {len(medium_priority)}")
|
| 68 |
-
print(f" 🟢 Low Priority: {len(low_priority)}")
|
| 69 |
-
|
| 70 |
-
print(f"\n🚨 HIGH PRIORITY COMPLAINTS (Need immediate action):")
|
| 71 |
-
for i, (msg, result) in enumerate(high_priority, 1):
|
| 72 |
-
print(f" {i}. {msg}")
|
| 73 |
-
print(f" → Confidence: {result['confidence']:.1%}")
|
| 74 |
-
|
| 75 |
-
if not high_priority:
|
| 76 |
-
print(" ✅ No urgent complaints!")
|
| 77 |
-
|
| 78 |
-
def example_filtering_workflow():
|
| 79 |
-
"""Contoh workflow filtering untuk admin"""
|
| 80 |
-
print("\n" + "=" * 60)
|
| 81 |
-
print("EXAMPLE 3: Admin Workflow - Smart Filtering")
|
| 82 |
-
print("=" * 60)
|
| 83 |
-
|
| 84 |
-
analyzer = SentimentAnalyzer()
|
| 85 |
-
|
| 86 |
-
# Simulasi 1000 pesan (simplified to 20 for demo)
|
| 87 |
-
all_messages = [
|
| 88 |
-
"Bantuan lambat sekali!",
|
| 89 |
-
"Terima kasih",
|
| 90 |
-
"Kapan bantuan tiba?",
|
| 91 |
-
"Kondisi darurat, tidak ada air!",
|
| 92 |
-
"Tim bantuan sangat baik",
|
| 93 |
-
"Bagaimana cara daftar?",
|
| 94 |
-
"Parah banget pelayanan!",
|
| 95 |
-
"Sudah dapat bantuan, terima kasih",
|
| 96 |
-
"Tolong segera kirim bantuan!",
|
| 97 |
-
"Lokasi kami masih terisolasi!",
|
| 98 |
-
"Alhamdulillah selamat",
|
| 99 |
-
"Apa syarat bantuan?",
|
| 100 |
-
"Gak ada koordinasi sama sekali!",
|
| 101 |
-
"Tim medis cepat tanggap",
|
| 102 |
-
"Berapa lama proses bantuan?",
|
| 103 |
-
"Posko penuh, gak bisa masuk!",
|
| 104 |
-
"Relawan sangat membantu",
|
| 105 |
-
"Info jalur evakuasi?",
|
| 106 |
-
"Hadeh ribet banget!",
|
| 107 |
-
"Sukses untuk tim bantuan"
|
| 108 |
-
]
|
| 109 |
-
|
| 110 |
-
print(f"\n📥 Receiving {len(all_messages)} messages...")
|
| 111 |
-
|
| 112 |
-
# Analyze all
|
| 113 |
-
results = analyzer.batch_analyze(all_messages)
|
| 114 |
-
|
| 115 |
-
# Smart filtering
|
| 116 |
-
needs_action = []
|
| 117 |
-
for msg, result in zip(all_messages, results):
|
| 118 |
-
if result['label'] == 'NEGATIVE' and result['confidence'] >= 0.7:
|
| 119 |
-
needs_action.append({
|
| 120 |
-
'message': msg,
|
| 121 |
-
'confidence': result['confidence'],
|
| 122 |
-
'priority': 'HIGH' if result['confidence'] >= 0.8 else 'MEDIUM'
|
| 123 |
-
})
|
| 124 |
-
|
| 125 |
-
# Sort by confidence (most confident first)
|
| 126 |
-
needs_action.sort(key=lambda x: x['confidence'], reverse=True)
|
| 127 |
-
|
| 128 |
-
print(f"\n✅ Filtered results:")
|
| 129 |
-
print(f" Original messages: {len(all_messages)}")
|
| 130 |
-
print(f" Need action: {len(needs_action)}")
|
| 131 |
-
print(f" Time saved: ~{100 - (len(needs_action)/len(all_messages)*100):.0f}%")
|
| 132 |
-
|
| 133 |
-
print(f"\n📋 Messages requiring action (sorted by confidence):")
|
| 134 |
-
for i, item in enumerate(needs_action, 1):
|
| 135 |
-
priority_icon = "🔴" if item['priority'] == 'HIGH' else "🟡"
|
| 136 |
-
print(f" {i}. {priority_icon} [{item['priority']}] {item['message']}")
|
| 137 |
-
print(f" Confidence: {item['confidence']:.1%}")
|
| 138 |
-
|
| 139 |
-
def example_json_export():
|
| 140 |
-
"""Contoh export hasil ke JSON untuk integrasi sistem lain"""
|
| 141 |
-
print("\n" + "=" * 60)
|
| 142 |
-
print("EXAMPLE 4: JSON Export for System Integration")
|
| 143 |
-
print("=" * 60)
|
| 144 |
-
|
| 145 |
-
analyzer = SentimentAnalyzer()
|
| 146 |
-
|
| 147 |
-
messages = [
|
| 148 |
-
"Bantuan sangat lambat!",
|
| 149 |
-
"Terima kasih atas bantuan",
|
| 150 |
-
"Kapan bantuan tiba?"
|
| 151 |
-
]
|
| 152 |
-
|
| 153 |
-
# Analyze and prepare for export
|
| 154 |
-
export_data = {
|
| 155 |
-
'timestamp': '2026-01-31T10:30:00',
|
| 156 |
-
'total_analyzed': len(messages),
|
| 157 |
-
'results': []
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
for msg in messages:
|
| 161 |
-
result = analyzer.analyze(msg)
|
| 162 |
-
export_data['results'].append({
|
| 163 |
-
'text': msg,
|
| 164 |
-
'sentiment': result['label'],
|
| 165 |
-
'category': result['kategori'],
|
| 166 |
-
'confidence': round(result['confidence'], 4),
|
| 167 |
-
'interpretation': result['interpretation']
|
| 168 |
-
})
|
| 169 |
-
|
| 170 |
-
# Convert to JSON
|
| 171 |
-
json_output = json.dumps(export_data, indent=2, ensure_ascii=False)
|
| 172 |
-
|
| 173 |
-
print("\n📤 JSON Export:")
|
| 174 |
-
print(json_output)
|
| 175 |
-
|
| 176 |
-
# Save to file (optional)
|
| 177 |
-
with open('/tmp/sentiment_results.json', 'w', encoding='utf-8') as f:
|
| 178 |
-
f.write(json_output)
|
| 179 |
-
|
| 180 |
-
print("\n✅ Results exported to: /tmp/sentiment_results.json")
|
| 181 |
-
|
| 182 |
-
def example_custom_threshold():
|
| 183 |
-
"""Contoh custom threshold untuk use case spesifik"""
|
| 184 |
-
print("\n" + "=" * 60)
|
| 185 |
-
print("EXAMPLE 5: Custom Threshold Configuration")
|
| 186 |
-
print("=" * 60)
|
| 187 |
-
|
| 188 |
-
analyzer = SentimentAnalyzer()
|
| 189 |
-
|
| 190 |
-
text = "Pelayanan agak lambat tapi masih oke"
|
| 191 |
-
result = analyzer.analyze(text)
|
| 192 |
-
|
| 193 |
-
print(f"\nText: {text}")
|
| 194 |
-
print(f"Sentiment: {result['label']}")
|
| 195 |
-
print(f"Confidence: {result['confidence']:.2%}")
|
| 196 |
-
|
| 197 |
-
# Custom threshold untuk prioritas
|
| 198 |
-
print("\n🔧 Custom Priority Rules:")
|
| 199 |
-
|
| 200 |
-
if result['label'] == 'NEGATIVE':
|
| 201 |
-
if result['confidence'] >= 0.9:
|
| 202 |
-
priority = "CRITICAL - Immediate action required"
|
| 203 |
-
elif result['confidence'] >= 0.7:
|
| 204 |
-
priority = "HIGH - Action needed within 1 hour"
|
| 205 |
-
elif result['confidence'] >= 0.5:
|
| 206 |
-
priority = "MEDIUM - Review within 24 hours"
|
| 207 |
-
else:
|
| 208 |
-
priority = "LOW - Monitor"
|
| 209 |
-
else:
|
| 210 |
-
priority = "INFO - No action needed"
|
| 211 |
-
|
| 212 |
-
print(f"Priority Level: {priority}")
|
| 213 |
-
|
| 214 |
-
if __name__ == "__main__":
|
| 215 |
-
print("\n" + "="*60)
|
| 216 |
-
print("🔧 SENTIMENT ANALYSIS API - USAGE EXAMPLES")
|
| 217 |
-
print("="*60)
|
| 218 |
-
print("Model: w11wo/indonesian-roberta-base-sentiment-classifier")
|
| 219 |
-
print("="*60)
|
| 220 |
-
|
| 221 |
-
# Run all examples
|
| 222 |
-
example_basic_usage()
|
| 223 |
-
example_batch_processing()
|
| 224 |
-
example_filtering_workflow()
|
| 225 |
-
example_json_export()
|
| 226 |
-
example_custom_threshold()
|
| 227 |
-
|
| 228 |
-
print("\n" + "="*60)
|
| 229 |
-
print("✅ ALL EXAMPLES COMPLETED")
|
| 230 |
-
print("="*60)
|
| 231 |
-
print("\n💡 Tips:")
|
| 232 |
-
print(" - Gunakan batch_analyze() untuk efisiensi tinggi")
|
| 233 |
-
print(" - Set custom threshold sesuai kebutuhan use case")
|
| 234 |
-
print(" - Export hasil ke JSON untuk integrasi sistem lain")
|
| 235 |
-
print(" - Prioritas keluhan berdasarkan confidence score")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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