BramLeo commited on
Commit
4ace49d
·
verified ·
1 Parent(s): 6330093

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -160
app.py CHANGED
@@ -1,163 +1,54 @@
1
- # Import Library yang Diperlukan
2
  import gradio as gr
3
- import shutil
4
- import os
5
- import subprocess
6
  from llama_cpp import Llama
7
- from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
8
- from llama_index.core.llms import ChatMessage
9
- from llama_index.llms.llama_cpp import LlamaCPP
10
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
11
- from huggingface_hub import hf_hub_download
12
- from llama_index.core.node_parser import SentenceSplitter
13
-
14
- # Fungsi untuk memasang ulang llama-cpp-python dengan dukungan CUDA
15
- def install_llama_with_cuda():
16
- try:
17
- # Baca file requirements.txt
18
- with open("requirements.txt", "r") as f:
19
- packages = f.read().splitlines()
20
-
21
- # Install setiap paket dengan CMAKE_ARGS untuk dukungan CUDA
22
- for package in packages:
23
- subprocess.run(
24
- env={"CMAKE_ARGS": "-DGGML_CUDA=on"},
25
- check=True
26
- )
27
- # Periksa apakah CUDA Toolkit tersedia
28
- if not shutil.which("nvcc"):
29
- print("CUDA Toolkit tidak ditemukan. Pastikan sudah diinstal.")
30
- return
31
-
32
- print("Memasang ulang llama-cpp-python dengan dukungan CUDA...")
33
-
34
- print("llama-cpp-python berhasil diinstal ulang dengan dukungan CUDA.")
35
- except subprocess.CalledProcessError as e:
36
- print(f"Error saat menginstal ulang llama-cpp-python: {e}")
37
- except Exception as e:
38
- print(f"Kesalahan umum: {e}")
39
-
40
- # Fungsi untuk mengunduh model Llama
41
- def initialize_llama_model():
42
- # Unduh model jika belum ada di direktori kerja
43
- model_path = hf_hub_download(
44
- repo_id="TheBLoke/zephyr-7b-beta-GGUF", # Nama repo model
45
- filename="zephyr-7b-beta.Q4_K_M.gguf", # Nama file model
46
- cache_dir="./models" # Lokasi direktori untuk menyimpan model
47
- )
48
- return model_path
49
-
50
- # Fungsi untuk mengatur konfigurasi Settings
51
- def initialize_settings(model_path):
52
- Settings.llm = Llama(
53
- model_path=model_path,
54
- n_gpu_layers=1, # Sesuaikan dengan kebutuhan perangkat Anda
55
- temperature=0.7, # Sesuaikan untuk respons yang lebih cepat
56
- top_p=0.9 # Mengurangi eksplorasi token
57
- )
58
-
59
- # Fungsi untuk Menginisialisasi Index
60
- def initialize_index():
61
- # Tentukan dokumen input untuk pembacaan data
62
- documents = SimpleDirectoryReader(input_files=["bahandokumen/K3.txt",
63
- "bahandokumen/bonus.txt",
64
- "bahandokumen/cuti.txt",
65
- "bahandokumen/disiplinkerja.txt",
66
- "bahandokumen/fasilitas&bantuan.txt",
67
- "bahandokumen/fasilitaskerja.txt",
68
- "bahandokumen/hak.txt",
69
- "bahandokumen/hubunganpengusaha&serikat.txt",
70
- "bahandokumen/istilah.txt",
71
- "bahandokumen/jaminanserikat.txt",
72
- "bahandokumen/jamkes.txt",
73
- "bahandokumen/jamsos.txt",
74
- "bahandokumen/keluhkesah.txt",
75
- "bahandokumen/kenaikanupah.txt",
76
- "bahandokumen/kewajiban.txt",
77
- "bahandokumen/kompensasi.txt",
78
- "bahandokumen/larangan.txt",
79
- "bahandokumen/lembur.txt",
80
- "bahandokumen/luaskesepakatan.txt",
81
- "bahandokumen/mogok.txt",
82
- "bahandokumen/pelanggaran&sanksi.txt",
83
- "bahandokumen/pendidikan.txt",
84
- "bahandokumen/pengangkatan.txt",
85
- "bahandokumen/penilaian&promosi.txt",
86
- "bahandokumen/pensiun.txt",
87
- "bahandokumen/perjadin.txt",
88
- "bahandokumen/pesangon.txt",
89
- "bahandokumen/phk.txt",
90
- "bahandokumen/pihak.txt",
91
- "bahandokumen/pkb.txt",
92
- "bahandokumen/resign.txt",
93
- "bahandokumen/sanksi.txt",
94
- "bahandokumen/shift.txt",
95
- "bahandokumen/syaratkerja.txt",
96
- "bahandokumen/tatacara.txt",
97
- "bahandokumen/tka.txt",
98
- "bahandokumen/tunjangan.txt",
99
- "bahandokumen/uangpisah.txt",
100
- "bahandokumen/upah.txt",
101
- "bahandokumen/upahlembur.txt",
102
- "bahandokumen/waktukerja.txt"]).load_data()
103
- parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
104
- nodes = parser.get_nodes_from_documents(documents)
105
- embedding = HuggingFaceEmbedding("BAAI/bge-base-en-v1.5")
106
- Settings.embed_model = embedding
107
- index = VectorStoreIndex(nodes)
108
- return index
109
-
110
- # Inisialisasi Mesin Chat
111
- def initialize_chat_engine(index):
112
- from llama_index.core.prompts import PromptTemplate
113
- from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
114
- retriever = index.as_retriever(similarity_top_k=3)
115
- chat_engine = CondensePlusContextChatEngine.from_defaults(
116
- retriever=retriever,
117
- verbose=True,
118
- )
119
- return chat_engine
120
-
121
- # Fungsi untuk menghasilkan respons chatbot
122
- def generate_response(message, history, chat_engine):
123
- chat_messages = [
124
- ChatMessage(
125
- role="system",
126
- content="Anda adalah chatbot yang selalu menjawab pertanyaan secara singkat, ramah, dan jelas dalam bahasa Indonesia."
127
- ),
128
- ]
129
- response = chat_engine.stream_chat(message)
130
- text = "".join(response.response_gen) # Gabungkan semua token menjadi string
131
- history.append((message, text)) # Tambahkan ke riwayat
132
- return history
133
-
134
- def clear_history(chat_engine):
135
- chat_engine.clear()
136
-
137
- # Inisialisasi Komponen Gradio untuk UI
138
- def launch_gradio(chat_engine):
139
- with gr.Blocks() as demo:
140
- # Mengatur tombol untuk menghapus riwayat chat
141
- clear_btn = gr.Button("Clear")
142
- clear_btn.click(lambda: clear_history(chat_engine))
143
-
144
- # Membuat antarmuka chat
145
- chat_interface = gr.ChatInterface(
146
- lambda message, history: generate_response(message, history, chat_engine)
147
- )
148
- demo.launch()
149
-
150
- # Fungsi Utama untuk Menjalankan Aplikasi
151
- def main():
152
- install_llama_with_cuda()
153
- # Unduh model dan inisialisasi pengaturan
154
- model_path = initialize_llama_model()
155
- initialize_settings(model_path) # Mengirimkan model_path ke fungsi initialize_settings
156
- # Inisialisasi index dan engine
157
- index = initialize_index()
158
- chat_engine = initialize_chat_engine(index)
159
- # Luncurkan antarmuka
160
- launch_gradio(chat_engine)
161
-
162
- if __name__ == "__main__":
163
- main()
 
 
1
  import gradio as gr
 
 
 
2
  from llama_cpp import Llama
3
+ from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
4
+ from llama_index.core.prompts import PromptTemplate
5
+ from llama_index.core.llms import ChatMessage, MessageRole
6
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
7
+ from llama_index.core.chat_engine.condense_plus_context import CondensePlusContextChatEngine
8
+
9
+ # Load the LLaMA model
10
+ llm = Llama(
11
+ model_path="zephyr-7b-beta.Q4_K_M.gguf",
12
+ n_gpu_layers=1,
13
+ temperature=0.1,
14
+ max_new_tokens=1000,
15
+ )
16
+
17
+ # Load documents
18
+ documents = SimpleDirectoryReader(input_files=[
19
+ "data/jadwallembur.txt",
20
+ "data/absensi.txt",
21
+ "data/sisacuti.txt"
22
+ ]).load_data()
23
+
24
+ # Embed the documents using HuggingFace Embeddings
25
+ embedding = HuggingFaceEmbedding("BAAI/bge-base-en-v1.5")
26
+ nodes = [doc for doc in documents]
27
+ index = VectorStoreIndex(nodes)
28
+
29
+ # Retriever and chat engine setup
30
+ retriever = index.as_retriever(similarity_top_k=3)
31
+ chat_engine = CondensePlusContextChatEngine.from_defaults(
32
+ retriever=retriever,
33
+ verbose=True,
34
+ )
35
+
36
+ # Chat reset function
37
+ def clear_history():
38
+ chat_engine.reset()
39
+
40
+ # Chat response generator
41
+ def generate_response(message, history):
42
+ response = chat_engine.chat(message)
43
+ text = ""
44
+ for token in response.response_gen:
45
+ text += token
46
+ yield text
47
+
48
+ # Gradio UI setup
49
+ with gr.Blocks() as demo:
50
+ clear_btn = gr.Button("Clear")
51
+ clear_btn.click(clear_history)
52
+ chat_interface = gr.ChatInterface(fn=generate_response, clear_btn=clear_btn)
53
+
54
+ demo.launch()