Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,14 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
import os
|
|
|
|
|
|
|
|
|
|
|
4 |
import torch
|
|
|
5 |
from llama_cpp import Llama
|
6 |
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
|
7 |
from llama_index.core.llms import ChatMessage
|
@@ -10,8 +17,8 @@ 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 |
def check_cuda_availability():
|
14 |
-
"""Memeriksa apakah CUDA tersedia."""
|
15 |
if torch.cuda.is_available():
|
16 |
print("CUDA Toolkit tersedia di sistem.")
|
17 |
return True
|
@@ -19,58 +26,35 @@ def check_cuda_availability():
|
|
19 |
print("CUDA Toolkit tidak ditemukan di sistem.")
|
20 |
return False
|
21 |
|
22 |
-
|
23 |
-
"""Menginstal ulang llama-cpp-python dengan dukungan CUDA jika tersedia."""
|
24 |
-
try:
|
25 |
-
if check_cuda_availability():
|
26 |
-
print("Memasang ulang llama-cpp-python dengan dukungan CUDA...")
|
27 |
-
pip_path = "/home/user/.pyenv/versions/3.10.16/bin/pip" # Sesuaikan dengan lingkungan Anda
|
28 |
-
result = subprocess.run(
|
29 |
-
[pip_path, "install", "llama-cpp-python", "--force-reinstall", "--no-cache-dir"],
|
30 |
-
env={"CMAKE_ARGS": "-DGGML_CUDA=on"},
|
31 |
-
stdout=subprocess.PIPE,
|
32 |
-
stderr=subprocess.PIPE,
|
33 |
-
text=True,
|
34 |
-
check=True
|
35 |
-
)
|
36 |
-
print(result.stdout)
|
37 |
-
print("llama-cpp-python berhasil diinstal ulang dengan dukungan CUDA.")
|
38 |
-
else:
|
39 |
-
print("CUDA tidak tersedia. Menggunakan mode CPU.")
|
40 |
-
except subprocess.CalledProcessError as e:
|
41 |
-
print(f"Error saat menginstal ulang llama-cpp-python: {e.stderr}")
|
42 |
-
except Exception as e:
|
43 |
-
print(f"Kesalahan umum: {e}")
|
44 |
-
|
45 |
def initialize_llama_model():
|
46 |
-
|
47 |
model_path = hf_hub_download(
|
48 |
-
repo_id="TheBLoke/zephyr-7b-beta-GGUF",
|
49 |
-
filename="zephyr-7b-beta.Q4_K_M.gguf",
|
50 |
-
cache_dir="./models"
|
51 |
)
|
52 |
return model_path
|
53 |
|
54 |
-
|
55 |
-
|
56 |
Settings.llm = Llama(
|
57 |
model_path=model_path,
|
58 |
-
|
59 |
-
temperature=0.7,
|
60 |
-
top_p=0.9
|
61 |
)
|
62 |
|
|
|
63 |
def initialize_index():
|
64 |
-
|
65 |
-
documents = SimpleDirectoryReader(input_files=[
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
"bahandokumen/waktukerja.txt"
|
73 |
-
]).load_data()
|
74 |
|
75 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
76 |
nodes = parser.get_nodes_from_documents(documents)
|
@@ -79,25 +63,24 @@ def initialize_index():
|
|
79 |
index = VectorStoreIndex(nodes)
|
80 |
return index
|
81 |
|
|
|
82 |
def initialize_chat_engine(index):
|
83 |
-
"""Menginisialisasi mesin chat dari index."""
|
84 |
from llama_index.core.prompts import PromptTemplate
|
85 |
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
86 |
-
|
87 |
retriever = index.as_retriever(similarity_top_k=3)
|
88 |
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
89 |
retriever=retriever,
|
90 |
-
verbose=True
|
91 |
)
|
92 |
return chat_engine
|
93 |
|
|
|
94 |
def generate_response(message, history, chat_engine):
|
95 |
-
"""Menghasilkan respons dari chatbot."""
|
96 |
chat_messages = [
|
97 |
ChatMessage(
|
98 |
role="system",
|
99 |
content="Anda adalah chatbot yang selalu menjawab pertanyaan secara singkat, ramah, dan jelas dalam bahasa Indonesia."
|
100 |
-
)
|
101 |
]
|
102 |
response = chat_engine.stream_chat(message)
|
103 |
text = "".join(response.response_gen) # Gabungkan semua token menjadi string
|
@@ -105,40 +88,32 @@ def generate_response(message, history, chat_engine):
|
|
105 |
return history
|
106 |
|
107 |
def clear_history(chat_engine):
|
108 |
-
"""Menghapus riwayat chat."""
|
109 |
chat_engine.clear()
|
110 |
|
|
|
111 |
def launch_gradio(chat_engine):
|
112 |
-
"""Meluncurkan antarmuka Gradio."""
|
113 |
with gr.Blocks() as demo:
|
|
|
114 |
clear_btn = gr.Button("Clear")
|
115 |
clear_btn.click(lambda: clear_history(chat_engine))
|
116 |
|
|
|
117 |
chat_interface = gr.ChatInterface(
|
118 |
lambda message, history: generate_response(message, history, chat_engine)
|
119 |
)
|
120 |
demo.launch()
|
121 |
|
|
|
122 |
def main():
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
print(f"Terjadi kesalahan: {e}")
|
133 |
|
134 |
if __name__ == "__main__":
|
135 |
-
|
136 |
-
|
137 |
-
parser = argparse.ArgumentParser()
|
138 |
-
parser.add_argument("--install", action="store_true", help="Pasang ulang llama-cpp-python")
|
139 |
-
args = parser.parse_args()
|
140 |
-
|
141 |
-
if args.install:
|
142 |
-
install_llama_with_cuda()
|
143 |
-
else:
|
144 |
-
main()
|
|
|
1 |
+
# Import Library yang Diperlukan
|
2 |
import gradio as gr
|
3 |
+
import shutil
|
4 |
import os
|
5 |
+
import subprocess
|
6 |
+
import sys
|
7 |
+
import platform
|
8 |
+
import transformers
|
9 |
+
import numpy
|
10 |
import torch
|
11 |
+
|
12 |
from llama_cpp import Llama
|
13 |
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
|
14 |
from llama_index.core.llms import ChatMessage
|
|
|
17 |
from huggingface_hub import hf_hub_download
|
18 |
from llama_index.core.node_parser import SentenceSplitter
|
19 |
|
20 |
+
# Fungsi untuk memeriksa dan memastikan CUDA tersedia
|
21 |
def check_cuda_availability():
|
|
|
22 |
if torch.cuda.is_available():
|
23 |
print("CUDA Toolkit tersedia di sistem.")
|
24 |
return True
|
|
|
26 |
print("CUDA Toolkit tidak ditemukan di sistem.")
|
27 |
return False
|
28 |
|
29 |
+
# Fungsi untuk mengunduh model Llama
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
def initialize_llama_model():
|
31 |
+
# Unduh model jika belum ada di direktori kerja
|
32 |
model_path = hf_hub_download(
|
33 |
+
repo_id="TheBLoke/zephyr-7b-beta-GGUF", # Nama repo model
|
34 |
+
filename="zephyr-7b-beta.Q4_K_M.gguf", # Nama file model
|
35 |
+
cache_dir="./models" # Lokasi direktori untuk menyimpan model
|
36 |
)
|
37 |
return model_path
|
38 |
|
39 |
+
# Fungsi untuk mengatur konfigurasi Settings (tanpa CUDA)
|
40 |
+
def initialize_settings(model_path):
|
41 |
Settings.llm = Llama(
|
42 |
model_path=model_path,
|
43 |
+
n_threads=4, # Sesuaikan jumlah thread CPU sesuai kebutuhan
|
44 |
+
temperature=0.7, # Sesuaikan untuk respons yang lebih cepat
|
45 |
+
top_p=0.9 # Mengurangi eksplorasi token
|
46 |
)
|
47 |
|
48 |
+
# Fungsi untuk Menginisialisasi Index
|
49 |
def initialize_index():
|
50 |
+
# Tentukan dokumen input untuk pembacaan data
|
51 |
+
documents = SimpleDirectoryReader(input_files=["bahandokumen/K3.txt",
|
52 |
+
"bahandokumen/bonus.txt",
|
53 |
+
"bahandokumen/cuti.txt",
|
54 |
+
"bahandokumen/disiplinkerja.txt",
|
55 |
+
"bahandokumen/fasilitas&bantuan.txt",
|
56 |
+
"bahandokumen/upahlembur.txt",
|
57 |
+
"bahandokumen/waktukerja.txt"]).load_data()
|
|
|
|
|
58 |
|
59 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
60 |
nodes = parser.get_nodes_from_documents(documents)
|
|
|
63 |
index = VectorStoreIndex(nodes)
|
64 |
return index
|
65 |
|
66 |
+
# Inisialisasi Mesin Chat
|
67 |
def initialize_chat_engine(index):
|
|
|
68 |
from llama_index.core.prompts import PromptTemplate
|
69 |
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
|
|
70 |
retriever = index.as_retriever(similarity_top_k=3)
|
71 |
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
72 |
retriever=retriever,
|
73 |
+
verbose=True,
|
74 |
)
|
75 |
return chat_engine
|
76 |
|
77 |
+
# Fungsi untuk menghasilkan respons chatbot
|
78 |
def generate_response(message, history, chat_engine):
|
|
|
79 |
chat_messages = [
|
80 |
ChatMessage(
|
81 |
role="system",
|
82 |
content="Anda adalah chatbot yang selalu menjawab pertanyaan secara singkat, ramah, dan jelas dalam bahasa Indonesia."
|
83 |
+
),
|
84 |
]
|
85 |
response = chat_engine.stream_chat(message)
|
86 |
text = "".join(response.response_gen) # Gabungkan semua token menjadi string
|
|
|
88 |
return history
|
89 |
|
90 |
def clear_history(chat_engine):
|
|
|
91 |
chat_engine.clear()
|
92 |
|
93 |
+
# Inisialisasi Komponen Gradio untuk UI
|
94 |
def launch_gradio(chat_engine):
|
|
|
95 |
with gr.Blocks() as demo:
|
96 |
+
# Mengatur tombol untuk menghapus riwayat chat
|
97 |
clear_btn = gr.Button("Clear")
|
98 |
clear_btn.click(lambda: clear_history(chat_engine))
|
99 |
|
100 |
+
# Membuat antarmuka chat
|
101 |
chat_interface = gr.ChatInterface(
|
102 |
lambda message, history: generate_response(message, history, chat_engine)
|
103 |
)
|
104 |
demo.launch()
|
105 |
|
106 |
+
# Fungsi Utama untuk Menjalankan Aplikasi
|
107 |
def main():
|
108 |
+
# Tidak perlu memeriksa atau menginstal llama-cpp-python dengan CUDA
|
109 |
+
# Unduh model dan inisialisasi pengaturan
|
110 |
+
model_path = initialize_llama_model()
|
111 |
+
initialize_settings(model_path) # Mengirimkan model_path ke fungsi initialize_settings
|
112 |
+
# Inisialisasi index dan engine
|
113 |
+
index = initialize_index()
|
114 |
+
chat_engine = initialize_chat_engine(index)
|
115 |
+
# Luncurkan antarmuka
|
116 |
+
launch_gradio(chat_engine)
|
|
|
117 |
|
118 |
if __name__ == "__main__":
|
119 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|