Update app.py
Browse files
app.py
CHANGED
@@ -12,78 +12,28 @@ from llama_index.core.llms import ChatMessage
|
|
12 |
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
13 |
from llama_index.core.schema import Document
|
14 |
|
15 |
-
# ===================================
|
16 |
-
# 1️⃣ Fungsi Membaca Data PKB.json
|
17 |
-
# ===================================
|
18 |
-
def read_pkb_json():
|
19 |
-
try:
|
20 |
-
with open("pkb.json", "r", encoding="utf-8") as file:
|
21 |
-
data = json.load(file)
|
22 |
-
|
23 |
-
pkb_text = "=== Perjanjian Kerja Bersama ===\n"
|
24 |
-
for bab, content in data["perjanjian_kerja_bersama"].items():
|
25 |
-
pkb_text += f"\n## {content['judul']} ##\n"
|
26 |
-
for pasal, pasal_data in content.items():
|
27 |
-
if pasal != "judul":
|
28 |
-
pkb_text += f"\n### {pasal_data['judul']} ###\n"
|
29 |
-
for item in pasal_data["isi"]:
|
30 |
-
if isinstance(item, dict):
|
31 |
-
pkb_text += f"- {item['istilah']}: {item['definisi']}\n"
|
32 |
-
else:
|
33 |
-
pkb_text += f"- {item}\n"
|
34 |
-
return pkb_text
|
35 |
-
except Exception as e:
|
36 |
-
return f"❌ ERROR membaca PKB.json: {str(e)}"
|
37 |
-
|
38 |
-
# ===================================
|
39 |
-
# 2️⃣ Fungsi Membaca Data Google Spreadsheet
|
40 |
-
# ===================================
|
41 |
def read_google_sheets():
|
42 |
try:
|
43 |
-
# Tentukan scope akses ke Google Sheets & Drive
|
44 |
scope = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
|
45 |
-
|
46 |
-
# Load kredensial dari file credentials.json
|
47 |
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
|
48 |
client = gspread.authorize(creds)
|
49 |
-
|
50 |
-
# ID Spreadsheet (tetap sama untuk semua sheet)
|
51 |
SPREADSHEET_ID = "1e_cNMhwF-QYpyYUpqQh-XCw-OdhWS6EuYsoBUsVtdNg"
|
52 |
-
|
53 |
-
# 📌 Daftar nama worksheet yang akan dibaca
|
54 |
sheet_names = ["datatarget", "datacuti", "dataabsen", "datalembur", "pkb"]
|
55 |
-
|
56 |
-
all_data = [] # 🔹 List untuk menyimpan semua data
|
57 |
-
|
58 |
-
# 📌 Loop untuk membaca setiap worksheet
|
59 |
spreadsheet = client.open_by_key(SPREADSHEET_ID)
|
60 |
for sheet_name in sheet_names:
|
61 |
try:
|
62 |
sheet = spreadsheet.worksheet(sheet_name)
|
63 |
data = sheet.get_all_values()
|
64 |
-
|
65 |
-
# Tambahkan header nama sheet sebelum data untuk membedakan
|
66 |
-
all_data.append(f"=== Data dari {sheet_name.upper()} ===")
|
67 |
all_data.extend([" | ".join(row) for row in data])
|
68 |
-
all_data.append("\n") # Pisahkan tiap sheet dengan newline
|
69 |
-
|
70 |
except gspread.exceptions.WorksheetNotFound:
|
71 |
-
all_data.append(f"
|
72 |
-
|
73 |
-
# Gabungkan semua data menjadi satu string panjang
|
74 |
-
formatted_text = "\n".join(all_data)
|
75 |
-
|
76 |
-
return formatted_text
|
77 |
-
|
78 |
except gspread.exceptions.SpreadsheetNotFound:
|
79 |
-
return "
|
80 |
-
|
81 |
except Exception as e:
|
82 |
-
return f"
|
83 |
|
84 |
-
# ===================================
|
85 |
-
# 2️⃣ Fungsi untuk Mengunduh Model Llama
|
86 |
-
# ===================================
|
87 |
def initialize_llama_model():
|
88 |
model_path = hf_hub_download(
|
89 |
repo_id="TheBLoke/zephyr-7b-beta-GGUF",
|
@@ -92,102 +42,65 @@ def initialize_llama_model():
|
|
92 |
)
|
93 |
return model_path
|
94 |
|
95 |
-
# ===================================
|
96 |
-
# 3️⃣ Inisialisasi Model dan Pengaturan
|
97 |
-
# ===================================
|
98 |
def initialize_settings(model_path):
|
99 |
Settings.llm = LlamaCPP(
|
100 |
model_path=model_path,
|
101 |
temperature=0.7,
|
102 |
)
|
103 |
|
104 |
-
# ===================================
|
105 |
-
# 4️⃣ Inisialisasi Index dari Data Spreadsheet
|
106 |
-
# ===================================
|
107 |
def initialize_index():
|
108 |
-
text_data = read_google_sheets()
|
109 |
document = Document(text=text_data)
|
110 |
-
documents = [document]
|
111 |
-
|
112 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
113 |
-
nodes = parser.get_nodes_from_documents(
|
114 |
-
|
115 |
-
|
116 |
-
Settings.embed_model = embedding
|
117 |
-
|
118 |
-
index = VectorStoreIndex(nodes)
|
119 |
-
return index
|
120 |
|
121 |
-
# ===================================
|
122 |
-
# 5️⃣ Inisialisasi Mesin Chatbot
|
123 |
-
# ===================================
|
124 |
def initialize_chat_engine(index):
|
125 |
retriever = index.as_retriever(similarity_top_k=3)
|
126 |
-
|
127 |
retriever=retriever,
|
128 |
-
verbose=
|
129 |
)
|
130 |
-
return chat_engine
|
131 |
|
132 |
-
# ===================================
|
133 |
-
# 6️⃣ Fungsi untuk Menghasilkan Respons Chatbot
|
134 |
-
# ===================================
|
135 |
def generate_response(message, history, chat_engine):
|
136 |
if history is None:
|
137 |
history = []
|
138 |
-
|
139 |
-
#
|
140 |
-
text_data = read_google_sheets() + "\n" + read_pkb_json()
|
141 |
-
|
142 |
-
document = Document(text=text_data)
|
143 |
-
documents = [document]
|
144 |
-
|
145 |
-
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
146 |
-
nodes = parser.get_nodes_from_documents(documents)
|
147 |
-
index = VectorStoreIndex(nodes)
|
148 |
-
retriever = index.as_retriever(similarity_top_k=3)
|
149 |
-
|
150 |
-
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
151 |
-
retriever=retriever,
|
152 |
-
verbose=True,
|
153 |
-
)
|
154 |
-
|
155 |
chat_messages = [
|
156 |
ChatMessage(
|
157 |
role="system",
|
158 |
content=(
|
159 |
"Anda adalah chatbot yang dirancang khusus untuk berbicara dalam Bahasa Indonesia. "
|
160 |
-
"Anda tidak diperbolehkan menjawab dalam bahasa lain
|
161 |
"Gunakan gaya bahasa profesional tetapi tetap ramah. "
|
162 |
"Jika informasi tidak tersedia dalam dokumen, katakan dengan sopan bahwa Anda tidak tahu. "
|
163 |
"Pastikan setiap jawaban diberikan secara ringkas, jelas, dan sesuai konteks."
|
164 |
),
|
165 |
),
|
|
|
166 |
]
|
167 |
-
|
168 |
-
response = chat_engine.stream_chat(message)
|
169 |
-
text = "".join(response.response_gen)
|
170 |
-
|
171 |
-
history.append((message, text))
|
172 |
-
return history
|
173 |
|
174 |
-
#
|
175 |
-
#
|
176 |
-
|
|
|
|
|
|
|
177 |
def main():
|
178 |
model_path = initialize_llama_model()
|
179 |
-
initialize_settings(model_path)
|
180 |
-
|
181 |
index = initialize_index()
|
182 |
-
chat_engine = initialize_chat_engine(index)
|
183 |
|
184 |
def chatbot_response(message, history):
|
185 |
-
return generate_response(message,
|
186 |
|
187 |
gr.Interface(
|
188 |
fn=chatbot_response,
|
189 |
-
inputs=
|
190 |
-
outputs=
|
191 |
).launch()
|
192 |
|
193 |
if __name__ == "__main__":
|
|
|
12 |
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
13 |
from llama_index.core.schema import Document
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
def read_google_sheets():
|
16 |
try:
|
|
|
17 |
scope = ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"]
|
|
|
|
|
18 |
creds = ServiceAccountCredentials.from_json_keyfile_name("credentials.json", scope)
|
19 |
client = gspread.authorize(creds)
|
|
|
|
|
20 |
SPREADSHEET_ID = "1e_cNMhwF-QYpyYUpqQh-XCw-OdhWS6EuYsoBUsVtdNg"
|
|
|
|
|
21 |
sheet_names = ["datatarget", "datacuti", "dataabsen", "datalembur", "pkb"]
|
22 |
+
all_data = []
|
|
|
|
|
|
|
23 |
spreadsheet = client.open_by_key(SPREADSHEET_ID)
|
24 |
for sheet_name in sheet_names:
|
25 |
try:
|
26 |
sheet = spreadsheet.worksheet(sheet_name)
|
27 |
data = sheet.get_all_values()
|
|
|
|
|
|
|
28 |
all_data.extend([" | ".join(row) for row in data])
|
|
|
|
|
29 |
except gspread.exceptions.WorksheetNotFound:
|
30 |
+
all_data.append(f"ERROR: Worksheet {sheet_name} tidak ditemukan.")
|
31 |
+
return "\n".join(all_data).strip()
|
|
|
|
|
|
|
|
|
|
|
32 |
except gspread.exceptions.SpreadsheetNotFound:
|
33 |
+
return "ERROR: Spreadsheet tidak ditemukan."
|
|
|
34 |
except Exception as e:
|
35 |
+
return f"ERROR: {str(e)}"
|
36 |
|
|
|
|
|
|
|
37 |
def initialize_llama_model():
|
38 |
model_path = hf_hub_download(
|
39 |
repo_id="TheBLoke/zephyr-7b-beta-GGUF",
|
|
|
42 |
)
|
43 |
return model_path
|
44 |
|
|
|
|
|
|
|
45 |
def initialize_settings(model_path):
|
46 |
Settings.llm = LlamaCPP(
|
47 |
model_path=model_path,
|
48 |
temperature=0.7,
|
49 |
)
|
50 |
|
|
|
|
|
|
|
51 |
def initialize_index():
|
52 |
+
text_data = read_google_sheets()
|
53 |
document = Document(text=text_data)
|
|
|
|
|
54 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
55 |
+
nodes = parser.get_nodes_from_documents([document])
|
56 |
+
Settings.embed_model = HuggingFaceEmbedding("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
57 |
+
return VectorStoreIndex(nodes)
|
|
|
|
|
|
|
|
|
58 |
|
|
|
|
|
|
|
59 |
def initialize_chat_engine(index):
|
60 |
retriever = index.as_retriever(similarity_top_k=3)
|
61 |
+
return CondensePlusContextChatEngine.from_defaults(
|
62 |
retriever=retriever,
|
63 |
+
verbose=False # Matikan verbose agar output lebih bersih
|
64 |
)
|
|
|
65 |
|
|
|
|
|
|
|
66 |
def generate_response(message, history, chat_engine):
|
67 |
if history is None:
|
68 |
history = []
|
69 |
+
|
70 |
+
# Prompt untuk memastikan jawaban tetap dalam Bahasa Indonesia
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
chat_messages = [
|
72 |
ChatMessage(
|
73 |
role="system",
|
74 |
content=(
|
75 |
"Anda adalah chatbot yang dirancang khusus untuk berbicara dalam Bahasa Indonesia. "
|
76 |
+
"Anda tidak diperbolehkan menjawab dalam bahasa lain. "
|
77 |
"Gunakan gaya bahasa profesional tetapi tetap ramah. "
|
78 |
"Jika informasi tidak tersedia dalam dokumen, katakan dengan sopan bahwa Anda tidak tahu. "
|
79 |
"Pastikan setiap jawaban diberikan secara ringkas, jelas, dan sesuai konteks."
|
80 |
),
|
81 |
),
|
82 |
+
ChatMessage(role="user", content=message),
|
83 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
+
response = chat_engine.chat(chat_messages) # Menggunakan prompt secara eksplisit
|
86 |
+
text = response.response # Ambil teks respons dari model
|
87 |
+
|
88 |
+
history.append((message, text)) # Menyimpan riwayat percakapan dengan format yang benar
|
89 |
+
return text # Mengembalikan teks respons langsung tanpa simbol aneh
|
90 |
+
|
91 |
def main():
|
92 |
model_path = initialize_llama_model()
|
93 |
+
initialize_settings(model_path)
|
|
|
94 |
index = initialize_index()
|
95 |
+
chat_engine = initialize_chat_engine(index)
|
96 |
|
97 |
def chatbot_response(message, history):
|
98 |
+
return generate_response(message, chat_engine)
|
99 |
|
100 |
gr.Interface(
|
101 |
fn=chatbot_response,
|
102 |
+
inputs="text",
|
103 |
+
outputs="text",
|
104 |
).launch()
|
105 |
|
106 |
if __name__ == "__main__":
|