BramLeo commited on
Commit
6ea0e1a
·
verified ·
1 Parent(s): 0dde4ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -51
app.py CHANGED
@@ -1,64 +1,163 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
8
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
38
 
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
  ),
59
- ],
60
- )
 
 
 
61
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
 
 
 
64
  demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()