Update app.py
Browse files
app.py
CHANGED
@@ -1,44 +1,34 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
import os
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
from
|
8 |
-
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings, Document
|
9 |
-
from llama_index.core.node_parser import SentenceSplitter
|
10 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
11 |
from huggingface_hub import hf_hub_download
|
12 |
-
from llama_index.
|
13 |
|
14 |
-
# Fungsi untuk
|
15 |
-
def
|
16 |
-
|
17 |
-
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
except Exception as e:
|
26 |
-
print(f"β Gagal mengambil data: {e}")
|
27 |
-
return None
|
28 |
-
|
29 |
-
# Fungsi untuk update index chatbot dengan data terbaru dari Google Sheets
|
30 |
-
def update_index():
|
31 |
-
print(f"π [{datetime.now()}] Mengupdate index dengan data terbaru...")
|
32 |
-
|
33 |
-
df = fetch_google_sheets_data()
|
34 |
-
if df is None:
|
35 |
-
print("β οΈ Tidak bisa memperbarui index karena gagal membaca Google Sheets.")
|
36 |
-
return
|
37 |
-
|
38 |
-
documents = [Document(text=" | ".join(map(str, row.values))) for _, row in df.iterrows()]
|
39 |
|
40 |
-
|
41 |
-
|
|
|
42 |
"bahandokumen/K3.txt",
|
43 |
"bahandokumen/bonus.txt",
|
44 |
"bahandokumen/cuti.txt",
|
@@ -47,59 +37,114 @@ def update_index():
|
|
47 |
"bahandokumen/upahlembur.txt",
|
48 |
"bahandokumen/waktukerja.txt"
|
49 |
]).load_data()
|
50 |
-
|
51 |
-
documents.extend(text_documents)
|
52 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
53 |
nodes = parser.get_nodes_from_documents(documents)
|
54 |
-
|
55 |
-
embedding = HuggingFaceEmbedding("firqaaa/indo-sentence-bert-base")
|
56 |
Settings.embed_model = embedding
|
57 |
-
|
58 |
-
global index
|
59 |
index = VectorStoreIndex(nodes)
|
60 |
-
|
61 |
|
62 |
-
# Inisialisasi
|
63 |
-
def initialize_chat_engine():
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
-
#
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
response = chat_engine.stream_chat(message)
|
70 |
-
text = "".join(response.response_gen)
|
71 |
-
history.append((message, text))
|
72 |
return history
|
73 |
|
74 |
-
#
|
75 |
-
def
|
76 |
-
|
77 |
-
while True:
|
78 |
-
schedule.run_pending()
|
79 |
-
time.sleep(60)
|
80 |
|
81 |
-
#
|
82 |
-
def
|
83 |
-
thread = threading.Thread(target=schedule_update, daemon=True)
|
84 |
-
thread.start()
|
85 |
-
|
86 |
-
# Inisialisasi Gradio
|
87 |
-
def launch_gradio():
|
88 |
with gr.Blocks() as demo:
|
89 |
-
gr.
|
|
|
|
|
|
|
|
|
|
|
90 |
demo.launch()
|
91 |
|
92 |
-
# Fungsi
|
93 |
def main():
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
print("β³ Menjalankan scheduler update index (setiap jam 12 malam)...")
|
100 |
-
start_scheduler()
|
101 |
-
|
102 |
-
launch_gradio()
|
103 |
|
104 |
if __name__ == "__main__":
|
105 |
-
main()
|
|
|
1 |
+
# Import Library yang Diperlukan
|
2 |
import gradio as gr
|
3 |
import pandas as pd
|
4 |
import os
|
5 |
+
from llama_cpp import Llama
|
6 |
+
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
|
7 |
+
from llama_index.core.llms import ChatMessage
|
8 |
+
from llama_index.llms.llama_cpp import LlamaCPP
|
|
|
|
|
9 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
10 |
from huggingface_hub import hf_hub_download
|
11 |
+
from llama_index.core.node_parser import SentenceSplitter
|
12 |
|
13 |
+
# Fungsi untuk mengunduh model Llama
|
14 |
+
def initialize_llama_model():
|
15 |
+
model_path = hf_hub_download(
|
16 |
+
repo_id="TheBLoke/zephyr-7b-beta-GGUF", # Repo model Llama
|
17 |
+
filename="zephyr-7b-beta.Q4_K_M.gguf", # Nama file model
|
18 |
+
cache_dir="./models" # Direktori penyimpanan model
|
19 |
+
)
|
20 |
+
return model_path
|
21 |
|
22 |
+
# Fungsi untuk mengatur konfigurasi Settings
|
23 |
+
def initialize_settings(model_path):
|
24 |
+
Settings.llm = LlamaCPP(
|
25 |
+
model_path=model_path,
|
26 |
+
temperature=0.7,
|
27 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
# Fungsi untuk Menginisialisasi Index dari dokumen
|
30 |
+
def initialize_index():
|
31 |
+
documents = SimpleDirectoryReader(input_files=[
|
32 |
"bahandokumen/K3.txt",
|
33 |
"bahandokumen/bonus.txt",
|
34 |
"bahandokumen/cuti.txt",
|
|
|
37 |
"bahandokumen/upahlembur.txt",
|
38 |
"bahandokumen/waktukerja.txt"
|
39 |
]).load_data()
|
40 |
+
|
|
|
41 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
42 |
nodes = parser.get_nodes_from_documents(documents)
|
43 |
+
embedding = HuggingFaceEmbedding("BAAI/bge-base-en-v1.5")
|
|
|
44 |
Settings.embed_model = embedding
|
|
|
|
|
45 |
index = VectorStoreIndex(nodes)
|
46 |
+
return index
|
47 |
|
48 |
+
# Inisialisasi Mesin Chat
|
49 |
+
def initialize_chat_engine(index):
|
50 |
+
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
51 |
+
retriever = index.as_retriever(similarity_top_k=3)
|
52 |
+
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
53 |
+
retriever=retriever,
|
54 |
+
verbose=True,
|
55 |
+
)
|
56 |
+
return chat_engine
|
57 |
+
|
58 |
+
# === INTEGRASI GOOGLE SHEETS ===
|
59 |
+
# Fungsi untuk membaca Google Sheets (Public)
|
60 |
+
def get_public_gsheet_data(sheet_id, sheet_name):
|
61 |
+
url = f"https://docs.google.com/spreadsheets/d/1740C15sMgOowI5wv5Q-kmYQUXMJUEyRSrFXRwIMc4Z0/edit?gid=1097907532#gid=1097907532"
|
62 |
+
df = pd.read_csv(url)
|
63 |
+
return df
|
64 |
+
|
65 |
+
# Fungsi untuk mencari data cuti, absen, atau target kerja berdasarkan nama
|
66 |
+
def search_employee_data(nama):
|
67 |
+
sheet_id = "1740C15sMgOowI5wv5Q-kmYQUXMJUEyRSrFXRwIMc4Z0" # Ganti dengan ID Google Sheets Anda
|
68 |
+
sheet_name = "datatarget" # Ganti dengan nama sheet (misalnya "DataKaryawan")
|
69 |
|
70 |
+
# Ambil data dari Google Sheets
|
71 |
+
df = get_public_gsheet_data(sheet_id, sheet_name)
|
72 |
+
|
73 |
+
# Pastikan format kolom sesuai dengan struktur yang diberikan
|
74 |
+
df.columns = ["Bulan", "Kategori"] + ["Coiling", "B-Ken", "Lapping", "Suriawase", "Chrome Plating", "PVD", "GT", "Ferrox/Mn. Parker"]
|
75 |
+
|
76 |
+
# Pastikan bulan dicari dengan format yang sesuai (case-insensitive)
|
77 |
+
bulan_data = df[df["Bulan"].str.contains(bulan, case=False, na=False)]
|
78 |
+
|
79 |
+
if bulan_data.empty:
|
80 |
+
return f"Tidak ditemukan data untuk bulan '{bulan}'."
|
81 |
+
|
82 |
+
# Ambil hanya baris dengan kategori "Target", "Aktual", dan "Difference"
|
83 |
+
target = bulan_data[bulan_data["Kategori"].str.contains("Target", case=False, na=False)]
|
84 |
+
aktual = bulan_data[bulan_data["Kategori"].str.contains("Aktual", case=False, na=False)]
|
85 |
+
difference = bulan_data[bulan_data["Kategori"].str.contains("Difference", case=False, na=False)]
|
86 |
+
|
87 |
+
# Cek apakah mesin yang diminta ada di dalam kolom
|
88 |
+
if mesin not in df.columns:
|
89 |
+
return f"Mesin '{mesin}' tidak ditemukan dalam data."
|
90 |
+
|
91 |
+
# Format hasil jika data tersedia
|
92 |
+
hasil = (
|
93 |
+
f"π
**Bulan: {bulan.capitalize()}**\n"
|
94 |
+
f"π§ **Mesin: {mesin}**\n"
|
95 |
+
f"π― **Target Produksi**: {target[mesin].values[0] if not target.empty else 'Tidak ada data'}\n"
|
96 |
+
f"π **Aktual Produksi**: {aktual[mesin].values[0] if not aktual.empty else 'Tidak ada data'}\n"
|
97 |
+
f"βοΈ **Perbedaan (Difference)**: {difference[mesin].values[0] if not difference.empty else 'Tidak ada data'}"
|
98 |
+
)
|
99 |
+
|
100 |
+
return hasil
|
101 |
+
|
102 |
+
# Fungsi untuk menghasilkan respons chatbot
|
103 |
+
def generate_response(message, history, chat_engine):
|
104 |
+
chat_messages = [
|
105 |
+
ChatMessage(
|
106 |
+
role="system",
|
107 |
+
content="Anda adalah chatbot yang selalu menjawab pertanyaan secara singkat, ramah, dan jelas dalam bahasa Indonesia."
|
108 |
+
),
|
109 |
+
]
|
110 |
+
|
111 |
+
# Deteksi apakah pertanyaan terkait cuti, absen, atau target kerja
|
112 |
+
message_lower = message.lower()
|
113 |
+
if any(x in message_lower for x in ["absen", "target", "bulan", "mesin"]):
|
114 |
+
words = message.split()
|
115 |
+
for word in words:
|
116 |
+
data = search_employee_data(word)
|
117 |
+
if "tidak ditemukan" not in data.lower():
|
118 |
+
return history + [(message, data)] # Jika data ditemukan, kembalikan jawaban
|
119 |
+
|
120 |
+
# Jika pertanyaan umum, gunakan Llama
|
121 |
response = chat_engine.stream_chat(message)
|
122 |
+
text = "".join(response.response_gen) # Gabungkan semua token menjadi string
|
123 |
+
history.append((message, text)) # Tambahkan ke riwayat
|
124 |
return history
|
125 |
|
126 |
+
# Fungsi untuk menghapus riwayat chat
|
127 |
+
def clear_history(chat_engine):
|
128 |
+
chat_engine.clear()
|
|
|
|
|
|
|
129 |
|
130 |
+
# Inisialisasi Komponen Gradio untuk UI
|
131 |
+
def launch_gradio(chat_engine):
|
|
|
|
|
|
|
|
|
|
|
132 |
with gr.Blocks() as demo:
|
133 |
+
clear_btn = gr.Button("Clear")
|
134 |
+
clear_btn.click(lambda: clear_history(chat_engine))
|
135 |
+
|
136 |
+
chat_interface = gr.ChatInterface(
|
137 |
+
lambda message, history: generate_response(message, history, chat_engine)
|
138 |
+
)
|
139 |
demo.launch()
|
140 |
|
141 |
+
# Fungsi Utama untuk Menjalankan Aplikasi
|
142 |
def main():
|
143 |
+
model_path = initialize_llama_model()
|
144 |
+
initialize_settings(model_path)
|
145 |
+
index = initialize_index()
|
146 |
+
chat_engine = initialize_chat_engine(index)
|
147 |
+
launch_gradio(chat_engine)
|
|
|
|
|
|
|
|
|
148 |
|
149 |
if __name__ == "__main__":
|
150 |
+
main()
|