AkmalYafa commited on
Commit
ba9065b
Β·
verified Β·
1 Parent(s): de6b675

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +85 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,87 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import torch.nn.functional as F
5
 
6
+ # ================= CONFIG STREAMLIT =================
7
+ st.set_page_config(
8
+ page_title="Emotion Mining - Tom Lembong Case",
9
+ page_icon="πŸ’¬",
10
+ layout="wide"
11
+ )
12
+
13
+ # ================= MODEL CONFIG =================
14
+ MODEL_PATH = "./model" # ganti path ke folder model kamu
15
+ LABELS = ["SADNESS", "ANGER", "HOPE", "DISAPPOINTMENT", "SUPPORT"]
16
+
17
+ # ================= LOAD MODEL =================
18
+ @st.cache_resource(show_spinner=True)
19
+ def load_model(path):
20
+ tokenizer = AutoTokenizer.from_pretrained(path)
21
+ model = AutoModelForSequenceClassification.from_pretrained(path)
22
+ model.eval()
23
+ return tokenizer, model
24
+
25
+ tokenizer, model = load_model(MODEL_PATH)
26
+
27
+ # ================= SIDEBAR =================
28
+ st.sidebar.title("πŸ’¬ Emotion Mining")
29
+ st.sidebar.markdown("Masukkan komentar Instagram terkait kasus **Tom Lembong** dan dapatkan klasifikasi emosi.")
30
+
31
+ input_text = st.sidebar.text_area("πŸ“ Komentar Instagram", height=150)
32
+ predict_btn = st.sidebar.button("πŸš€ Klasifikasikan")
33
+
34
+ # ================= MAIN PAGE =================
35
+ st.title("πŸ“Š Emotion Mining - Kasus Tom Lembong")
36
+
37
+ with st.expander("ℹ️ Tentang Dataset", expanded=True):
38
+ st.markdown("""
39
+ **Latar Belakang Kasus:**
40
+ Tom Lembong, mantan Menteri Perdagangan, pada tahun 2024 ditetapkan sebagai tersangka kasus korupsi impor gula.
41
+ Ia sempat dijatuhi hukuman, namun kemudian mendapat abolisi dari Presiden.
42
+ Kasus ini menimbulkan berbagai emosi publik di media sosial, khususnya Instagram.
43
+
44
+ **Tujuan Dataset:**
45
+ Mengklasifikasikan komentar publik ke dalam **5 kategori emosi**:
46
+ - 😒 **SADNESS** – komentar sedih atau prihatin
47
+ - 😑 **ANGER** – komentar marah atau mengecam
48
+ - πŸ™ **HOPE** – komentar penuh harapan atau doa
49
+ - 😞 **DISAPPOINTMENT** – rasa kecewa atau frustrasi
50
+ - 🀝 **SUPPORT** – dukungan atau semangat
51
+
52
+ **Evaluasi:**
53
+ Model dievaluasi menggunakan **Macro F1-Score**, agar performa tetap seimbang meskipun distribusi label tidak merata.
54
+ """)
55
+
56
+ st.markdown("---")
57
+
58
+ # ================= PREDIKSI =================
59
+ if predict_btn:
60
+ if not input_text.strip():
61
+ st.warning("⚠️ Masukkan komentar terlebih dahulu!")
62
+ else:
63
+ # Tokenisasi
64
+ inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True, max_length=128)
65
+
66
+ # Inference
67
+ with torch.no_grad():
68
+ outputs = model(**inputs)
69
+ probs = F.softmax(outputs.logits, dim=-1).squeeze().tolist()
70
+
71
+ # Ambil hasil
72
+ pred_idx = int(torch.argmax(outputs.logits))
73
+ pred_label = LABELS[pred_idx]
74
+
75
+ # Layout 2 kolom: Hasil + Chart
76
+ col1, col2 = st.columns([1, 2])
77
+
78
+ with col1:
79
+ st.markdown("### πŸ“Œ Hasil Prediksi")
80
+ st.success(f"**Emosi:** {pred_label}")
81
+
82
+ with col2:
83
+ st.markdown("### πŸ“Š Distribusi Probabilitas")
84
+ st.bar_chart({label: prob for label, prob in zip(LABELS, probs)})
85
+
86
+ st.markdown("---")
87
+ st.caption("Made with ❀️ by Akmal | Powered by HuggingFace & Streamlit")