Asadeo commited on
Commit
9ca3a34
·
verified ·
1 Parent(s): c58490d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import pandas as pd
4
+
5
+ # Pesan saat startup untuk memastikan pipeline mulai dimuat.
6
+ print("Memuat model pipeline...")
7
+
8
+ # -----------------------------------------------------------------------------
9
+ # 1. Muat semua model pipeline saat aplikasi dimulai.
10
+ # Ini adalah praktik terbaik agar model siap saat input pertama masuk.
11
+ # -----------------------------------------------------------------------------
12
+ try:
13
+ # Model 1: DistilBERT
14
+ pipe_distilbert = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
15
+
16
+ # Model 2: BERT
17
+ pipe_bert = pipeline("text-classification", model="gchhablani/bert-base-cased-finetuned-sst2")
18
+
19
+ # Model 3: RoBERTa
20
+ pipe_roberta = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment")
21
+
22
+ print("Semua model berhasil dimuat.")
23
+ except Exception as e:
24
+ print(f"Error saat memuat model: {e}")
25
+ # Jika model gagal dimuat, aplikasi tidak akan bisa berjalan.
26
+ # Anda bisa menambahkan penanganan error yang lebih baik di sini.
27
+
28
+ # Mapping label untuk model RoBERTa agar lebih mudah dibaca.
29
+ roberta_label_map = {
30
+ "LABEL_0": "NEGATIVE",
31
+ "LABEL_1": "NEUTRAL",
32
+ "LABEL_2": "POSITIVE"
33
+ }
34
+
35
+ # -----------------------------------------------------------------------------
36
+ # 2. Buat fungsi utama untuk prediksi.
37
+ # Fungsi ini akan menerima input teks dan mengembalikan hasil dari ketiga model.
38
+ # -----------------------------------------------------------------------------
39
+ def predict_sentiments(text):
40
+ """
41
+ Menerima input teks, melakukan prediksi dengan tiga model,
42
+ dan mengembalikan hasilnya dalam format yang bisa ditampilkan oleh Gradio.
43
+ """
44
+ if not text.strip():
45
+ # Jika tidak ada teks, kembalikan dataframe kosong
46
+ return pd.DataFrame(columns=["Model", "Label", "Confidence Score"])
47
+
48
+ results = []
49
+
50
+ # Prediksi dengan DistilBERT
51
+ pred_distilbert = pipe_distilbert(text)[0]
52
+ results.append(["DistilBERT", pred_distilbert['label'], f"{pred_distilbert['score']:.4f}"])
53
+
54
+ # Prediksi dengan BERT
55
+ pred_bert = pipe_bert(text)[0]
56
+ results.append(["BERT", pred_bert['label'], f"{pred_bert['score']:.4f}"])
57
+
58
+ # Prediksi dengan RoBERTa
59
+ pred_roberta = pipe_roberta(text)[0]
60
+ # Ganti label RoBERTa sesuai mapping
61
+ label_roberta = roberta_label_map.get(pred_roberta['label'], pred_roberta['label'])
62
+ results.append(["RoBERTa", label_roberta, f"{pred_roberta['score']:.4f}"])
63
+
64
+ # Buat DataFrame dari hasil untuk output tabel yang rapi
65
+ df = pd.DataFrame(results, columns=["Model", "Label", "Confidence Score"])
66
+ return df
67
+
68
+ # -----------------------------------------------------------------------------
69
+ # 3. Buat dan jalankan antarmuka Gradio.
70
+ # -----------------------------------------------------------------------------
71
+ demo = gr.Interface(
72
+ fn=predict_sentiments,
73
+ inputs=gr.Textbox(
74
+ lines=5,
75
+ placeholder="Masukkan teks di sini untuk dianalisis sentimennya...",
76
+ label="Input Teks"
77
+ ),
78
+ outputs=gr.Dataframe(
79
+ headers=["Model", "Label", "Confidence Score"],
80
+ datatype=["str", "str", "str"],
81
+ label="Hasil Prediksi"
82
+ ),
83
+ title="🤖 Perbandingan Model Analisis Sentimen",
84
+ description="Aplikasi ini membandingkan hasil prediksi sentimen dari tiga model transformer yang berbeda: DistilBERT, BERT, dan RoBERTa. Cukup masukkan teks dan klik 'Submit'.",
85
+ allow_flagging="never",
86
+ examples=[
87
+ ["I love the new features, this is an amazing update!"],
88
+ ["The performance is a bit slow and sometimes it crashes."],
89
+ ["This product is okay, not great but not terrible either."]
90
+ ]
91
+ )
92
+
93
+ # Jalankan aplikasi
94
+ if __name__ == "__main__":
95
+ demo.launch()