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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import streamlit as st
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import re
|
6 |
+
import json
|
7 |
+
import joblib
|
8 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
9 |
+
|
10 |
+
# Impor library tambahan
|
11 |
+
import matplotlib.pyplot as plt
|
12 |
+
import seaborn as sns
|
13 |
+
from wordcloud import WordCloud
|
14 |
+
|
15 |
+
|
16 |
+
# Set judul situs web
|
17 |
+
st.set_page_config(page_title="naufalnashif-ML")
|
18 |
+
|
19 |
+
# Fungsi untuk membersihkan teks dengan ekspresi reguler
|
20 |
+
def clean_text(text):
|
21 |
+
# Tahap-1: Menghapus karakter non-ASCII
|
22 |
+
text = re.sub(r'[^\x00-\x7F]+', '', text)
|
23 |
+
|
24 |
+
# Tahap-2: Menghapus URL
|
25 |
+
text = re.sub(r'http[s]?://.[a-zA-Z0-9./_?=%&#+!]+', '', text)
|
26 |
+
text = re.sub(r'pic.twitter.com?.[a-zA-Z0-9./_?=%&#+!]+', '', text)
|
27 |
+
|
28 |
+
# Tahap-3: Menghapus mentions
|
29 |
+
text = re.sub(r'@[\w]+', '', text)
|
30 |
+
|
31 |
+
# Tahap-4: Menghapus hashtag
|
32 |
+
text = re.sub(r'#([\w]+)', '', text)
|
33 |
+
|
34 |
+
# Tahap-5: Menghapus karakter khusus (simbol)
|
35 |
+
text = re.sub(r'[!$%^&*@#()_+|~=`{}\[\]%\-:";\'<>?,./]', '', text)
|
36 |
+
|
37 |
+
# Tahap-6: Menghapus angka
|
38 |
+
text = re.sub(r'[0-9]+', '', text)
|
39 |
+
|
40 |
+
# Tahap-7: Menggabungkan spasi ganda menjadi satu spasi
|
41 |
+
text = re.sub(' +', ' ', text)
|
42 |
+
|
43 |
+
# Tahap-8: Menghapus spasi di awal dan akhir kalimat
|
44 |
+
text = text.strip()
|
45 |
+
|
46 |
+
# Tahap-9: Konversi teks ke huruf kecil
|
47 |
+
text = text.lower()
|
48 |
+
|
49 |
+
return text
|
50 |
+
|
51 |
+
# Membaca kamus kata gaul Salsabila
|
52 |
+
kamus_path = '/content/drive/MyDrive/Skripsi/assets/_json_colloquial-indonesian-lexicon.txt' # Ganti dengan path yang benar
|
53 |
+
with open(kamus_path) as f:
|
54 |
+
data = f.read()
|
55 |
+
lookp_dict = json.loads(data)
|
56 |
+
|
57 |
+
# Dict kata gaul saya sendiri yang tidak masuk di dict Salsabila
|
58 |
+
kamus_gaul_baru = {
|
59 |
+
'kurangg': 'kurang',
|
60 |
+
'udaa': 'udah',
|
61 |
+
'mnurut': 'menurut',
|
62 |
+
'anyinh': 'anjing',
|
63 |
+
'seputat': 'seputar',
|
64 |
+
'ijo' : 'hijau',
|
65 |
+
'dmma' : 'dimana',
|
66 |
+
'anjrot' : 'anjing',
|
67 |
+
'ajgg' : 'anjing',
|
68 |
+
'keboen' : 'kebun',
|
69 |
+
'aseekk' : 'asik',
|
70 |
+
'bliau' : 'beliau',
|
71 |
+
'aseek' : 'asik',
|
72 |
+
'berpaa' : 'berapa',
|
73 |
+
'berpa' : 'berapa',
|
74 |
+
'bggtt' : 'banget',
|
75 |
+
'cntoh' : 'contoh',
|
76 |
+
'anzink' : 'anjing',
|
77 |
+
'jrg' : 'jarang',
|
78 |
+
'msi' : 'masih',
|
79 |
+
'anjirt' : 'anjing',
|
80 |
+
'kesampeian' : 'kesampaian',
|
81 |
+
'dtgnya' : 'datangnya',
|
82 |
+
'dtg' : 'datang',
|
83 |
+
'dngin' : 'dingin',
|
84 |
+
'ktub' : 'kutub',
|
85 |
+
'brngkt' : 'berangkat',
|
86 |
+
'antra' : 'antara',
|
87 |
+
'pinuh': 'penuh',
|
88 |
+
'anjink': 'anjing',
|
89 |
+
'anjir' : 'anjing',
|
90 |
+
'ajg': 'anjing',
|
91 |
+
'smpet': 'sempat',
|
92 |
+
'sempet': 'sempat',
|
93 |
+
'makai': 'memakai',
|
94 |
+
'bgst': 'bangsat',
|
95 |
+
'anjg': 'anjing',
|
96 |
+
'cpk': 'lelah',
|
97 |
+
'capek': 'lelah',
|
98 |
+
'capk': 'lelah',
|
99 |
+
'cpek': 'lelah',
|
100 |
+
'anjrit': 'anjing',
|
101 |
+
'anjig': 'anjing',
|
102 |
+
'anjigg': 'anjing',
|
103 |
+
'anjingg': 'anjing',
|
104 |
+
'bukann': 'bukan',
|
105 |
+
'skrgg': 'sekarang',
|
106 |
+
'makasihh': 'terimakasih',
|
107 |
+
'asu': 'anjing',
|
108 |
+
'moga': 'semoga',
|
109 |
+
'cok': 'jancok',
|
110 |
+
'cokk': 'jancok',
|
111 |
+
'cook': 'jancok',
|
112 |
+
'cookk': 'jancok',
|
113 |
+
'amgkot': 'angkot',
|
114 |
+
'gua' : 'aku',
|
115 |
+
'gweh': 'aku',
|
116 |
+
'guah': 'aku',
|
117 |
+
'gw': 'aku',
|
118 |
+
'gwah': 'aku',
|
119 |
+
'gue' : 'aku',
|
120 |
+
'wkwkwk' : 'wkwk',
|
121 |
+
'dah' : 'udah',
|
122 |
+
'tkt' : 'takut',
|
123 |
+
'gabisa' : 'gabisa',
|
124 |
+
'umumm' : 'umum',
|
125 |
+
'umuum' : 'umum',
|
126 |
+
'yah' : 'yah',
|
127 |
+
'drtd' : 'daritadi',
|
128 |
+
'drtdi' : 'daritadi',
|
129 |
+
'ges':'gais',
|
130 |
+
'gays': 'gais',
|
131 |
+
'geys':'gais',
|
132 |
+
'trans pakuan': 'transpakuan',
|
133 |
+
'anjr' : 'anjir',
|
134 |
+
'anjer' : 'anjing',
|
135 |
+
'njir' : 'anjing',
|
136 |
+
'anjr' : 'anjing',
|
137 |
+
'trans pakuan' : 'transpakuan',
|
138 |
+
'gblk' : 'goblok',
|
139 |
+
}
|
140 |
+
|
141 |
+
# Menambahkan dict kata gaul baru ke kamus yang sudah ada
|
142 |
+
lookp_dict.update(kamus_gaul_baru)
|
143 |
+
|
144 |
+
# Fungsi untuk normalisasi kata gaul
|
145 |
+
def normalize_slang(text, slang_dict):
|
146 |
+
words = text.split()
|
147 |
+
normalized_words = [slang_dict.get(word, word) for word in words]
|
148 |
+
return ' '.join(normalized_words)
|
149 |
+
|
150 |
+
# Fungsi untuk ekstraksi fitur TF-IDF
|
151 |
+
def extract_tfidf_features(texts, tfidf_vectorizer):
|
152 |
+
tfidf_matrix = tfidf_vectorizer.transform(texts)
|
153 |
+
return tfidf_matrix
|
154 |
+
|
155 |
+
# Memuat model TF-IDF dengan joblib (pastikan path-nya benar)
|
156 |
+
tfidf_model_path = '/content/drive/MyDrive/Skripsi/output-4/Norm_model_smote/X_tfidf_model.joblib'
|
157 |
+
tfidf_vectorizer = joblib.load(tfidf_model_path)
|
158 |
+
|
159 |
+
# Fungsi untuk prediksi sentimen
|
160 |
+
def predict_sentiment(text, model, tfidf_vectorizer, slang_dict):
|
161 |
+
# Tahap-1: Membersihkan dan normalisasi teks
|
162 |
+
cleaned_text = clean_text(text)
|
163 |
+
norm_slang_text = normalize_slang(cleaned_text, slang_dict)
|
164 |
+
|
165 |
+
# Tahap-2: Ekstraksi fitur TF-IDF
|
166 |
+
tfidf_matrix = tfidf_vectorizer.transform([norm_slang_text])
|
167 |
+
|
168 |
+
# Tahap-3: Lakukan prediksi sentimen
|
169 |
+
sentiment = model.predict(tfidf_matrix)
|
170 |
+
|
171 |
+
# Tahap-4: Menggantikan indeks dengan label sentimen
|
172 |
+
labels = {0: "Negatif", 1: "Netral", 2: "Positif"}
|
173 |
+
sentiment_label = labels[int(sentiment)]
|
174 |
+
|
175 |
+
return sentiment_label
|
176 |
+
|
177 |
+
# Memuat model sentimen dengan joblib (pastikan path-nya benar)
|
178 |
+
sentiment_model_path = '/content/drive/MyDrive/Skripsi/output-4/Norm_model_smote/ensemble_clf_soft_smote.joblib'
|
179 |
+
sentiment_model = joblib.load(sentiment_model_path)
|
180 |
+
|
181 |
+
def get_emoticon(sentiment):
|
182 |
+
if sentiment == "Positif":
|
183 |
+
emoticon = "π" # Emotikon untuk sentimen positif
|
184 |
+
elif sentiment == "Negatif":
|
185 |
+
emoticon = "π" # Emotikon untuk sentimen negatif
|
186 |
+
else:
|
187 |
+
emoticon = "π" # Emotikon untuk sentimen netral
|
188 |
+
|
189 |
+
return emoticon
|
190 |
+
|
191 |
+
# Fungsi untuk membuat tautan unduhan
|
192 |
+
def get_table_download_link(df, download_format):
|
193 |
+
if download_format == "XLSX":
|
194 |
+
df.to_excel("hasil_sentimen.xlsx", index=False)
|
195 |
+
return f'<a href="hasil_sentimen.xlsx" download="hasil_sentimen.xlsx">Unduh File XLSX</a>'
|
196 |
+
else:
|
197 |
+
csv = df.to_csv(index=False)
|
198 |
+
return f'<a href="data:file/csv;base64,{b64encode(csv.encode()).decode()}" download="hasil_sentimen.csv">Unduh File CSV</a>'
|
199 |
+
|
200 |
+
|
201 |
+
# Judul
|
202 |
+
st.title("Aplikasi ML Analisis Sentimen based on data Biskita Transpakuan")
|
203 |
+
|
204 |
+
# Pilihan input teks manual atau berkas XLSX
|
205 |
+
input_option = st.radio("Pilih metode input:", ("Teks Manual", "Unggah Berkas XLSX"))
|
206 |
+
|
207 |
+
if input_option == "Teks Manual":
|
208 |
+
# Input teks dari pengguna
|
209 |
+
user_input = st.text_area("Masukkan teks:", "")
|
210 |
+
else:
|
211 |
+
# Input berkas XLSX
|
212 |
+
uploaded_file = st.file_uploader("Unggah berkas XLSX", type=["xlsx"])
|
213 |
+
st.write("**Pastikan berkas XLSX Anda memiliki kolom yang bernama 'Text'.**")
|
214 |
+
|
215 |
+
if uploaded_file is not None:
|
216 |
+
df = pd.read_excel(uploaded_file)
|
217 |
+
|
218 |
+
if 'Text' not in df.columns:
|
219 |
+
st.warning("Berkas XLSX harus memiliki kolom bernama 'Text' untuk analisis sentimen.")
|
220 |
+
else:
|
221 |
+
texts = df['Text'] # Sesuaikan dengan nama kolom di berkas XLSX Anda
|
222 |
+
|
223 |
+
# Analisis sentimen
|
224 |
+
results = []
|
225 |
+
|
226 |
+
if input_option == "Teks Manual" and user_input:
|
227 |
+
# Pisahkan teks yang dimasukkan pengguna menjadi baris-baris terpisah
|
228 |
+
user_texts = user_input.split('\n')
|
229 |
+
for text in user_texts:
|
230 |
+
sentiment_label = predict_sentiment(text, sentiment_model, tfidf_vectorizer, lookp_dict)
|
231 |
+
emoticon = get_emoticon(sentiment_label)
|
232 |
+
cleaned_text = clean_text(text)
|
233 |
+
norm_slang_text = normalize_slang(cleaned_text, lookp_dict)
|
234 |
+
results.append((text, cleaned_text, norm_slang_text, sentiment_label, emoticon))
|
235 |
+
|
236 |
+
elif input_option == "Unggah Berkas XLSX" and uploaded_file is not None:
|
237 |
+
if 'Text' in df.columns:
|
238 |
+
for text in texts:
|
239 |
+
sentiment_label = predict_sentiment(text, sentiment_model, tfidf_vectorizer, lookp_dict)
|
240 |
+
emoticon = get_emoticon(sentiment_label)
|
241 |
+
cleaned_text = clean_text(text)
|
242 |
+
norm_slang_text = normalize_slang(cleaned_text, lookp_dict)
|
243 |
+
results.append((text, cleaned_text, norm_slang_text, sentiment_label, emoticon))
|
244 |
+
else:
|
245 |
+
st.warning("Berkas XLSX harus memiliki kolom bernama 'Text' untuk analisis sentimen.")
|
246 |
+
|
247 |
+
|
248 |
+
# Membagi tampilan menjadi dua kolom
|
249 |
+
columns = st.columns(2)
|
250 |
+
|
251 |
+
# Kolom pertama untuk Word Cloud
|
252 |
+
with columns[0]:
|
253 |
+
if results:
|
254 |
+
all_texts = [result[2] for result in results if result[2] is not None and not pd.isna(result[2])]
|
255 |
+
all_texts = " ".join(all_texts)
|
256 |
+
|
257 |
+
st.subheader("Word Cloud")
|
258 |
+
|
259 |
+
if all_texts:
|
260 |
+
wordcloud = WordCloud(width=800, height=660, background_color='white',
|
261 |
+
colormap='Purples', # Warna huruf
|
262 |
+
contour_color='black', # Warna kontur
|
263 |
+
contour_width=2, # Lebar kontur
|
264 |
+
mask=None, # Gunakan mask untuk bentuk kustom
|
265 |
+
).generate(all_texts)
|
266 |
+
st.image(wordcloud.to_array())
|
267 |
+
else:
|
268 |
+
st.write("Tidak ada data untuk ditampilkan dalam Word Cloud.")
|
269 |
+
|
270 |
+
# Kolom kedua untuk Bar Chart
|
271 |
+
with columns[1]:
|
272 |
+
st.subheader("Chart")
|
273 |
+
if results:
|
274 |
+
df_results = pd.DataFrame(results, columns=["Teks", "Cleaned Text", "Norm Text", "Hasil Analisis Sentimen", "Emotikon"])
|
275 |
+
sns.set_style("whitegrid")
|
276 |
+
|
277 |
+
# Menyiapkan label kelas
|
278 |
+
class_labels = ["Negatif", "Netral", "Positif"]
|
279 |
+
|
280 |
+
# Menghitung nilai hitungan per label
|
281 |
+
value_counts = df_results["Hasil Analisis Sentimen"].value_counts()
|
282 |
+
|
283 |
+
# Mengurutkan nilai hitungan berdasarkan label
|
284 |
+
value_counts = value_counts.reindex(class_labels)
|
285 |
+
|
286 |
+
fig, ax = plt.subplots() # Buat objek Figure
|
287 |
+
sns.barplot(x=value_counts.index, y=value_counts.values, ax=ax) # Gunakan ax= untuk plot
|
288 |
+
plt.xticks(rotation=45)
|
289 |
+
|
290 |
+
st.pyplot(fig) # Tampilkan plot menggunakan st.pyplot(fig)
|
291 |
+
|
292 |
+
# Menampilkan hasil analisis sentimen dalam kotak yang dapat diperluas
|
293 |
+
with st.expander("Hasil Analisis Sentimen"):
|
294 |
+
# Tampilkan tabel hasil analisis sentimen
|
295 |
+
st.table(pd.DataFrame(results, columns=["Teks", "Cleaned Text", "Norm Text", "Hasil Analisis Sentimen", "Emotikon"]))
|
296 |
+
|
297 |
+
|
298 |
+
# Tautan untuk mengunduh hasil dalam format XLSX atau CSV
|
299 |
+
st.subheader("Unduh Hasil")
|
300 |
+
download_format = st.selectbox("Pilih format unduhan:", ["XLSX", "CSV"])
|
301 |
+
if results:
|
302 |
+
if download_format == "XLSX":
|
303 |
+
# Simpan DataFrame ke dalam file XLSX
|
304 |
+
df = pd.DataFrame(results, columns=["Teks", "Cleaned Text", "Norm Text", "Hasil Analisis Sentimen", "Emotikon"])
|
305 |
+
df.to_excel("hasil_sentimen.xlsx", index=False)
|
306 |
+
|
307 |
+
# Tampilkan tombol unduh XLSX
|
308 |
+
st.download_button(label="Unduh XLSX", data=open("hasil_sentimen.xlsx", "rb").read(), key="xlsx_download", file_name="hasil_sentimen.xlsx")
|
309 |
+
|
310 |
+
else: # Jika CSV
|
311 |
+
# Simpan DataFrame ke dalam file CSV
|
312 |
+
df = pd.DataFrame(results, columns=["Teks", "Cleaned Text", "Norm Text", "Hasil Analisis Sentimen", "Emotikon"])
|
313 |
+
csv = df.to_csv(index=False)
|
314 |
+
|
315 |
+
# Tampilkan tombol unduh CSV
|
316 |
+
st.download_button(label="Unduh CSV", data=csv, key="csv_download", file_name="hasil_sentimen.csv")
|
317 |
+
else:
|
318 |
+
st.write("Tidak ada data untuk diunduh.")
|
319 |
+
|
320 |
+
|
321 |
+
# Garis pemisah
|
322 |
+
st.divider()
|
323 |
+
|
324 |
+
# Tautan ke GitHub
|
325 |
+
github_link = "https://github.com/naufalnashif/"
|
326 |
+
st.markdown(f"GitHub: [{github_link}]({github_link})")
|
327 |
+
|
328 |
+
# Tautan ke Instagram
|
329 |
+
instagram_link = "https://www.instagram.com/naufal.nashif/"
|
330 |
+
st.markdown(f"Instagram: [{instagram_link}]({instagram_link})")
|
331 |
+
|
332 |
+
# Pesan penutup
|
333 |
+
st.write('Thank you for trying the demo!')
|
334 |
+
st.write('Best regards, Naufal Nashif')
|