Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,9 @@ import os
|
|
| 6 |
|
| 7 |
# --- 1. Persiapan Data dan Model ---
|
| 8 |
|
|
|
|
| 9 |
CSV_FILE = "perpustakaan_faq.csv"
|
|
|
|
| 10 |
questions = []
|
| 11 |
answers = []
|
| 12 |
MODEL_LOADED = False
|
|
@@ -15,86 +17,146 @@ qa_pipeline = None
|
|
| 15 |
# Memuat data dari CSV
|
| 16 |
try:
|
| 17 |
df = pd.read_csv(CSV_FILE)
|
|
|
|
|
|
|
| 18 |
questions = df['user_query'].tolist()
|
| 19 |
answers = df['chatbot_response'].tolist()
|
|
|
|
|
|
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
-
print(f"Error memuat data CSV: {e}")
|
| 22 |
|
| 23 |
-
# Inisialisasi Model Question Answering
|
|
|
|
| 24 |
try:
|
| 25 |
model_name = "indobenchmark/indobert-base-uncased-squad"
|
|
|
|
|
|
|
| 26 |
model = AutoModelForQuestionAnswering.from_pretrained(model_name)
|
| 27 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
MODEL_LOADED = True
|
| 30 |
print(f"Model {model_name} berhasil dimuat.")
|
|
|
|
| 31 |
except Exception as e:
|
| 32 |
-
print(f"Error memuat model
|
| 33 |
MODEL_LOADED = False
|
| 34 |
print("Menggunakan fallback (pencocokan kata kunci sederhana) karena model gagal dimuat.")
|
| 35 |
|
| 36 |
# --- 2. Fungsi Logika Chatbot ---
|
| 37 |
|
| 38 |
def preprocess_query(query):
|
|
|
|
| 39 |
query = query.lower().strip()
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
def get_answer_from_qa_model(query):
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
best_score = 0.0
|
|
|
|
| 45 |
for original_answer in answers:
|
| 46 |
try:
|
| 47 |
-
result = qa_pipeline(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
if result['score'] > best_score:
|
| 49 |
best_score = result['score']
|
| 50 |
best_answer = result['answer']
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
except Exception:
|
| 53 |
continue
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
def get_answer_fallback(query):
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
preprocessed_query = preprocess_query(query)
|
| 59 |
-
best_match_answer = "Maaf, saya tidak menemukan informasi yang relevan..
|
| 60 |
max_matches = 0
|
|
|
|
| 61 |
query_words = set(word for word in preprocessed_query.split() if len(word) > 3)
|
| 62 |
|
| 63 |
for q_data, a_data in zip(questions, answers):
|
| 64 |
q_data_words = set(word for word in preprocess_query(q_data).split() if len(word) > 3)
|
|
|
|
| 65 |
matches = len(query_words.intersection(q_data_words))
|
|
|
|
| 66 |
if matches > max_matches:
|
| 67 |
max_matches = matches
|
| 68 |
best_match_answer = a_data
|
| 69 |
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
def chatbot_response(user_query, history):
|
|
|
|
|
|
|
|
|
|
| 73 |
if not user_query or not user_query.strip():
|
| 74 |
return "Halo! Silakan ajukan pertanyaan seputar layanan perpustakaan."
|
|
|
|
| 75 |
if MODEL_LOADED:
|
| 76 |
response = get_answer_from_qa_model(user_query)
|
| 77 |
else:
|
| 78 |
response = get_answer_fallback(user_query)
|
|
|
|
| 79 |
return response
|
| 80 |
|
| 81 |
# --- 3. Implementasi Gradio Interface ---
|
| 82 |
|
|
|
|
| 83 |
title = "🤖 Chatbot Layanan Perpustakaan"
|
|
|
|
|
|
|
| 84 |
model_info = (
|
| 85 |
"Model QA: **" + ("indobenchmark/indobert-base-uncased-squad" if MODEL_LOADED else "Fallback Keyword Match") + "** | "
|
| 86 |
"Data Sumber: `perpustakaan_faq.csv`"
|
| 87 |
)
|
|
|
|
| 88 |
description = (
|
| 89 |
"Ini adalah Chatbot Tanya Jawab (Question Answering) yang dibuat dari data "
|
| 90 |
"FAQ Perpustakaan. Silakan ajukan pertanyaan seputar keanggotaan, peminjaman, kunjungan, atau fasilitas."
|
| 91 |
f"\n\n---\n\n{model_info}"
|
| 92 |
)
|
|
|
|
|
|
|
| 93 |
examples = [
|
| 94 |
["Berapa lama batas waktu peminjaman buku?"],
|
| 95 |
["Apa syarat utama jika saya mau buat kartu anggota perpustakaan?"],
|
|
|
|
|
|
|
| 96 |
]
|
| 97 |
|
|
|
|
| 98 |
iface = gr.ChatInterface(
|
| 99 |
fn=chatbot_response,
|
| 100 |
title=title,
|
|
@@ -103,7 +165,8 @@ iface = gr.ChatInterface(
|
|
| 103 |
chatbot=gr.Chatbot(
|
| 104 |
height=400,
|
| 105 |
label="Asisten Perpustakaan",
|
| 106 |
-
type
|
|
|
|
| 107 |
),
|
| 108 |
)
|
| 109 |
|
|
|
|
| 6 |
|
| 7 |
# --- 1. Persiapan Data dan Model ---
|
| 8 |
|
| 9 |
+
# Nama file CSV yang diunggah
|
| 10 |
CSV_FILE = "perpustakaan_faq.csv"
|
| 11 |
+
|
| 12 |
questions = []
|
| 13 |
answers = []
|
| 14 |
MODEL_LOADED = False
|
|
|
|
| 17 |
# Memuat data dari CSV
|
| 18 |
try:
|
| 19 |
df = pd.read_csv(CSV_FILE)
|
| 20 |
+
|
| 21 |
+
# Kolom 'chatbot_response' akan dijadikan Konteks utama (Basis Pengetahuan)
|
| 22 |
questions = df['user_query'].tolist()
|
| 23 |
answers = df['chatbot_response'].tolist()
|
| 24 |
+
|
| 25 |
+
except FileNotFoundError:
|
| 26 |
+
print(f"Error: File '{CSV_FILE}' tidak ditemukan. Pastikan file berada di direktori yang sama.")
|
| 27 |
except Exception as e:
|
| 28 |
+
print(f"Error saat memuat atau memproses data CSV: {e}")
|
| 29 |
|
| 30 |
+
# Inisialisasi Model Question Answering Bahasa Indonesia
|
| 31 |
+
# Catatan: Jika model ini tetap gagal dimuat, sistem akan otomatis menggunakan fallback.
|
| 32 |
try:
|
| 33 |
model_name = "indobenchmark/indobert-base-uncased-squad"
|
| 34 |
+
|
| 35 |
+
# Coba muat model dan tokenizer
|
| 36 |
model = AutoModelForQuestionAnswering.from_pretrained(model_name)
|
| 37 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 38 |
+
|
| 39 |
+
# Inisialisasi pipeline QA
|
| 40 |
+
qa_pipeline = pipeline(
|
| 41 |
+
"question-answering",
|
| 42 |
+
model=model,
|
| 43 |
+
tokenizer=tokenizer
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
MODEL_LOADED = True
|
| 47 |
print(f"Model {model_name} berhasil dimuat.")
|
| 48 |
+
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"Error memuat model Question Answering ({model_name}): {e}")
|
| 51 |
MODEL_LOADED = False
|
| 52 |
print("Menggunakan fallback (pencocokan kata kunci sederhana) karena model gagal dimuat.")
|
| 53 |
|
| 54 |
# --- 2. Fungsi Logika Chatbot ---
|
| 55 |
|
| 56 |
def preprocess_query(query):
|
| 57 |
+
"""Membersihkan dan menormalkan query."""
|
| 58 |
query = query.lower().strip()
|
| 59 |
+
query = re.sub(r'[^\w\s]', '', query)
|
| 60 |
+
return query
|
| 61 |
|
| 62 |
def get_answer_from_qa_model(query):
|
| 63 |
+
"""
|
| 64 |
+
Mencari jawaban menggunakan Model Question Answering dari semua konteks (Answers).
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
best_answer = "Maaf, saya tidak menemukan informasi yang relevan untuk pertanyaan Anda. Silakan coba pertanyaan lain atau hubungi meja informasi perpustakaan."
|
| 68 |
best_score = 0.0
|
| 69 |
+
|
| 70 |
for original_answer in answers:
|
| 71 |
try:
|
| 72 |
+
result = qa_pipeline(
|
| 73 |
+
question=query,
|
| 74 |
+
context=original_answer
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
if result['score'] > best_score:
|
| 78 |
best_score = result['score']
|
| 79 |
best_answer = result['answer']
|
| 80 |
+
|
| 81 |
+
if best_score > 0.95:
|
| 82 |
+
break
|
| 83 |
+
|
| 84 |
except Exception:
|
| 85 |
continue
|
| 86 |
+
|
| 87 |
+
if best_score < 0.3:
|
| 88 |
+
return "Maaf, saya tidak menemukan informasi yang relevan untuk pertanyaan Anda. Silakan coba pertanyaan lain atau hubungi meja informasi perpustakaan."
|
| 89 |
+
|
| 90 |
+
return best_answer
|
| 91 |
|
| 92 |
def get_answer_fallback(query):
|
| 93 |
+
"""
|
| 94 |
+
Fungsi fallback sederhana berdasarkan pencocokan kata kunci.
|
| 95 |
+
"""
|
| 96 |
+
if not answers:
|
| 97 |
+
return "Maaf, data FAQ perpustakaan belum termuat."
|
| 98 |
+
|
| 99 |
preprocessed_query = preprocess_query(query)
|
| 100 |
+
best_match_answer = "Maaf, saya tidak menemukan informasi yang relevan untuk pertanyaan Anda. Silakan coba pertanyaan lain atau hubungi meja informasi perpustakaan."
|
| 101 |
max_matches = 0
|
| 102 |
+
|
| 103 |
query_words = set(word for word in preprocessed_query.split() if len(word) > 3)
|
| 104 |
|
| 105 |
for q_data, a_data in zip(questions, answers):
|
| 106 |
q_data_words = set(word for word in preprocess_query(q_data).split() if len(word) > 3)
|
| 107 |
+
|
| 108 |
matches = len(query_words.intersection(q_data_words))
|
| 109 |
+
|
| 110 |
if matches > max_matches:
|
| 111 |
max_matches = matches
|
| 112 |
best_match_answer = a_data
|
| 113 |
|
| 114 |
+
if max_matches < 1:
|
| 115 |
+
return "Maaf, saya tidak menemukan informasi yang relevan untuk pertanyaan Anda. Silakan coba pertanyaan lain atau hubungi meja informasi perpustakaan."
|
| 116 |
+
|
| 117 |
+
return best_match_answer
|
| 118 |
+
|
| 119 |
|
| 120 |
def chatbot_response(user_query, history):
|
| 121 |
+
"""
|
| 122 |
+
Fungsi utama yang dipanggil oleh Gradio.
|
| 123 |
+
"""
|
| 124 |
if not user_query or not user_query.strip():
|
| 125 |
return "Halo! Silakan ajukan pertanyaan seputar layanan perpustakaan."
|
| 126 |
+
|
| 127 |
if MODEL_LOADED:
|
| 128 |
response = get_answer_from_qa_model(user_query)
|
| 129 |
else:
|
| 130 |
response = get_answer_fallback(user_query)
|
| 131 |
+
|
| 132 |
return response
|
| 133 |
|
| 134 |
# --- 3. Implementasi Gradio Interface ---
|
| 135 |
|
| 136 |
+
# Deskripsi Interface
|
| 137 |
title = "🤖 Chatbot Layanan Perpustakaan"
|
| 138 |
+
|
| 139 |
+
# Informasi model untuk ditampilkan di deskripsi
|
| 140 |
model_info = (
|
| 141 |
"Model QA: **" + ("indobenchmark/indobert-base-uncased-squad" if MODEL_LOADED else "Fallback Keyword Match") + "** | "
|
| 142 |
"Data Sumber: `perpustakaan_faq.csv`"
|
| 143 |
)
|
| 144 |
+
|
| 145 |
description = (
|
| 146 |
"Ini adalah Chatbot Tanya Jawab (Question Answering) yang dibuat dari data "
|
| 147 |
"FAQ Perpustakaan. Silakan ajukan pertanyaan seputar keanggotaan, peminjaman, kunjungan, atau fasilitas."
|
| 148 |
f"\n\n---\n\n{model_info}"
|
| 149 |
)
|
| 150 |
+
|
| 151 |
+
# Contoh pertanyaan untuk memandu pengguna
|
| 152 |
examples = [
|
| 153 |
["Berapa lama batas waktu peminjaman buku?"],
|
| 154 |
["Apa syarat utama jika saya mau buat kartu anggota perpustakaan?"],
|
| 155 |
+
["Apakah ada loker penitipan barang di sini?"],
|
| 156 |
+
["Bolehkah saya membawa laptop pribadi ke dalam perpustakaan?"]
|
| 157 |
]
|
| 158 |
|
| 159 |
+
# Pembuatan Gradio Interface
|
| 160 |
iface = gr.ChatInterface(
|
| 161 |
fn=chatbot_response,
|
| 162 |
title=title,
|
|
|
|
| 165 |
chatbot=gr.Chatbot(
|
| 166 |
height=400,
|
| 167 |
label="Asisten Perpustakaan",
|
| 168 |
+
# --- PERBAIKAN FATAL: Menghapus parameter 'type' yang menyebabkan TypeError ---
|
| 169 |
+
# type="messages",
|
| 170 |
),
|
| 171 |
)
|
| 172 |
|