Update app.py
Browse files
app.py
CHANGED
@@ -1,14 +1,7 @@
|
|
1 |
-
# Import Library yang Diperlukan
|
2 |
import gradio as gr
|
3 |
-
import shutil
|
4 |
-
import os
|
5 |
import subprocess
|
6 |
-
import
|
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,15 +10,8 @@ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
|
17 |
from huggingface_hub import hf_hub_download
|
18 |
from llama_index.core.node_parser import SentenceSplitter
|
19 |
|
20 |
-
print(LlamaCPP.__version__)
|
21 |
-
try:
|
22 |
-
# Periksa versi pip
|
23 |
-
subprocess.run(["pip", "--version"], check=True)
|
24 |
-
except FileNotFoundError:
|
25 |
-
print("pip tidak ditemukan di sistem.")
|
26 |
-
|
27 |
-
# Fungsi untuk memeriksa dan memastikan CUDA tersedia
|
28 |
def check_cuda_availability():
|
|
|
29 |
if torch.cuda.is_available():
|
30 |
print("CUDA Toolkit tersedia di sistem.")
|
31 |
return True
|
@@ -34,55 +20,57 @@ def check_cuda_availability():
|
|
34 |
return False
|
35 |
|
36 |
def install_llama_with_cuda():
|
|
|
37 |
try:
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
|
|
52 |
except subprocess.CalledProcessError as e:
|
53 |
-
print(f"Error saat menginstal ulang llama-cpp-python: {e}")
|
54 |
except Exception as e:
|
55 |
print(f"Kesalahan umum: {e}")
|
56 |
|
57 |
-
# Fungsi untuk mengunduh model Llama
|
58 |
def initialize_llama_model():
|
59 |
-
|
60 |
model_path = hf_hub_download(
|
61 |
-
repo_id="TheBLoke/zephyr-7b-beta-GGUF",
|
62 |
-
filename="zephyr-7b-beta.Q4_K_M.gguf",
|
63 |
-
cache_dir="./models"
|
64 |
)
|
65 |
return model_path
|
66 |
|
67 |
-
|
68 |
-
|
69 |
Settings.llm = Llama(
|
70 |
model_path=model_path,
|
71 |
-
n_gpu_layers=1, #
|
72 |
-
temperature=0.7,
|
73 |
-
top_p=0.9
|
74 |
)
|
75 |
|
76 |
-
# Fungsi untuk Menginisialisasi Index
|
77 |
def initialize_index():
|
78 |
-
|
79 |
-
documents = SimpleDirectoryReader(input_files=[
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
86 |
|
87 |
parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
|
88 |
nodes = parser.get_nodes_from_documents(documents)
|
@@ -91,24 +79,25 @@ def initialize_index():
|
|
91 |
index = VectorStoreIndex(nodes)
|
92 |
return index
|
93 |
|
94 |
-
# Inisialisasi Mesin Chat
|
95 |
def initialize_chat_engine(index):
|
|
|
96 |
from llama_index.core.prompts import PromptTemplate
|
97 |
from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
|
|
|
98 |
retriever = index.as_retriever(similarity_top_k=3)
|
99 |
chat_engine = CondensePlusContextChatEngine.from_defaults(
|
100 |
retriever=retriever,
|
101 |
-
verbose=True
|
102 |
)
|
103 |
return chat_engine
|
104 |
|
105 |
-
# Fungsi untuk menghasilkan respons chatbot
|
106 |
def generate_response(message, history, chat_engine):
|
|
|
107 |
chat_messages = [
|
108 |
ChatMessage(
|
109 |
role="system",
|
110 |
content="Anda adalah chatbot yang selalu menjawab pertanyaan secara singkat, ramah, dan jelas dalam bahasa Indonesia."
|
111 |
-
)
|
112 |
]
|
113 |
response = chat_engine.stream_chat(message)
|
114 |
text = "".join(response.response_gen) # Gabungkan semua token menjadi string
|
@@ -116,32 +105,40 @@ def generate_response(message, history, chat_engine):
|
|
116 |
return history
|
117 |
|
118 |
def clear_history(chat_engine):
|
|
|
119 |
chat_engine.clear()
|
120 |
-
|
121 |
-
# Inisialisasi Komponen Gradio untuk UI
|
122 |
def launch_gradio(chat_engine):
|
|
|
123 |
with gr.Blocks() as demo:
|
124 |
-
# Mengatur tombol untuk menghapus riwayat chat
|
125 |
clear_btn = gr.Button("Clear")
|
126 |
clear_btn.click(lambda: clear_history(chat_engine))
|
127 |
|
128 |
-
# Membuat antarmuka chat
|
129 |
chat_interface = gr.ChatInterface(
|
130 |
lambda message, history: generate_response(message, history, chat_engine)
|
131 |
)
|
132 |
demo.launch()
|
133 |
|
134 |
-
# Fungsi Utama untuk Menjalankan Aplikasi
|
135 |
def main():
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
|
|
146 |
if __name__ == "__main__":
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
import subprocess
|
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 |
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
|
|
|
20 |
return False
|
21 |
|
22 |
def install_llama_with_cuda():
|
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 |
+
"""Mengunduh model Llama dari HuggingFace."""
|
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 |
+
def initialize_settings(model_path):
|
55 |
+
"""Mengatur konfigurasi Settings untuk Llama."""
|
56 |
Settings.llm = Llama(
|
57 |
model_path=model_path,
|
58 |
+
n_gpu_layers=1, # Gunakan GPU jika tersedia
|
59 |
+
temperature=0.7,
|
60 |
+
top_p=0.9
|
61 |
)
|
62 |
|
|
|
63 |
def initialize_index():
|
64 |
+
"""Menginisialisasi index dari dokumen input."""
|
65 |
+
documents = SimpleDirectoryReader(input_files=[
|
66 |
+
"bahandokumen/K3.txt",
|
67 |
+
"bahandokumen/bonus.txt",
|
68 |
+
"bahandokumen/cuti.txt",
|
69 |
+
"bahandokumen/disiplinkerja.txt",
|
70 |
+
"bahandokumen/fasilitas&bantuan.txt",
|
71 |
+
"bahandokumen/upahlembur.txt",
|
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 |
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 |
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 |
+
"""Fungsi utama untuk menjalankan aplikasi."""
|
124 |
+
try:
|
125 |
+
install_llama_with_cuda()
|
126 |
+
model_path = initialize_llama_model()
|
127 |
+
initialize_settings(model_path)
|
128 |
+
index = initialize_index()
|
129 |
+
chat_engine = initialize_chat_engine(index)
|
130 |
+
launch_gradio(chat_engine)
|
131 |
+
except Exception as e:
|
132 |
+
print(f"Terjadi kesalahan: {e}")
|
133 |
+
|
134 |
if __name__ == "__main__":
|
135 |
+
import argparse
|
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()
|