dini15 commited on
Commit
b551f1b
·
verified ·
1 Parent(s): 7124241

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -63
app.py CHANGED
@@ -1,64 +1,130 @@
 
 
 
 
 
 
 
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 libraries
2
+ import ollama
3
+ from PyPDF2 import PdfReader
4
+ import tiktoken
5
+ import groq
6
+ import faiss
7
+ import numpy as np
8
  import gradio as gr
9
+ import json
10
+ import os
11
+ import pickle
12
+
13
+ # == Buat folder models ==
14
+ os.makedirs("models", exist_ok=True)
15
+
16
+ # == Load API Key dari File (Hindari Hardcoded Key) ==
17
+ def load_api_key():
18
+ with open("config.json", "r") as f:
19
+ config = json.load(f)
20
+ return config["GROQ_API_KEY"]
21
+
22
+ GROQ_API_KEY = load_api_key()
23
+
24
+ # == Ekstraksi Teks dari PDF ==
25
+ def extract_text_from_pdf(pdf_file: str) -> str:
26
+ """Ekstrak teks dari PDF dan gabungkan menjadi satu string."""
27
+ with open(pdf_file, 'rb') as pdf:
28
+ reader = PdfReader(pdf)
29
+ text = " ".join(page.extract_text() or "" for page in reader.pages)
30
+ return text
31
+
32
+ # == Chunking Teks ==
33
+ def chunk_text(text: str, max_tokens: int = 512) -> list:
34
+ """Membagi teks menjadi chunk berdasarkan token menggunakan tokenizer OpenAI."""
35
+ tokenizer = tiktoken.get_encoding("cl100k_base") # Gunakan tokenizer OpenAI
36
+ tokens = tokenizer.encode(text)
37
+
38
+ chunks = []
39
+ for i in range(0, len(tokens), max_tokens):
40
+ chunk_tokens = tokens[i:i+max_tokens]
41
+ chunk_text = tokenizer.decode(chunk_tokens)
42
+ chunks.append(chunk_text)
43
+
44
+ return chunks
45
+
46
+ # == Embedding dengan Ollama ==
47
+ def get_embedding(text: str):
48
+ """Mendapatkan embedding dari teks menggunakan Ollama."""
49
+ embedding = ollama.embed(model="mxbai-embed-large", input=text)
50
+ return np.array(embedding["embeddings"][0], dtype=np.float32) # Pastikan mengambil list pertama
51
+
52
+ # == Simpan Embedding ke FAISS ==
53
+ d = 1024 # Dimensi embedding dari model `mxbai-embed-large`
54
+ index = faiss.IndexFlatL2(d) # Inisialisasi FAISS Index
55
+ text_chunks = []
56
+
57
+ def add_to_db(text_chunks_local):
58
+ """Menambahkan embedding ke FAISS."""
59
+ global text_chunks
60
+ text_chunks = text_chunks_local # Simpan chunk ke global var
61
+ embeddings = np.array([get_embedding(text) for text in text_chunks], dtype=np.float32)
62
+ index.add(embeddings)
63
+
64
+ def search_db(query, k=5):
65
+ """Melakukan pencarian query dalam FAISS Index."""
66
+ query_embedding = np.array([get_embedding(query)], dtype=np.float32).reshape(1, -1)
67
+ distances, indices = index.search(query_embedding, k)
68
+ return [text_chunks[i] for i in indices[0]] # Ambil teks chunk yang relevan
69
+
70
+ def save_to_faiss(index_path="vector_index.faiss"):
71
+ """Menyimpan FAISS index ke file."""
72
+ faiss.write_index(index, index_path)
73
+
74
+ def load_faiss(index_path="vector_index.faiss"):
75
+ """Memuat kembali FAISS index dari file."""
76
+ global index
77
+ index = faiss.read_index(index_path)
78
+
79
+ # == Simpan dan Load Model Embedding ==
80
+ def save_embeddings(embeddings_path="models/embeddings.pkl"):
81
+ with open(embeddings_path, "wb") as f:
82
+ pickle.dump(index, f)
83
+
84
+ def load_embeddings(embeddings_path="models/embeddings.pkl"):
85
+ global index
86
+ with open(embeddings_path, "rb") as f:
87
+ index = pickle.load(f)
88
+
89
+ # == Integrasi LLaMA via Groq API ==
90
+ client = groq.Client(api_key=GROQ_API_KEY)
91
+
92
+ def query_llama(prompt):
93
+ """Menggunakan LLaMA untuk menjawab pertanyaan dengan konteks yang diberikan."""
94
+ response = client.chat.completions.create(
95
+ model="llama3-8b-8192",
96
+ messages=[{"role": "user", "content": prompt}],
97
+ max_tokens=512
98
+ )
99
+ return response.choices[0].message.content.strip()
100
+
101
+ # == Main Workflow ==
102
+ if __name__ == '__main__':
103
+ pdf_text = extract_text_from_pdf('dini_anggriyani_synthetic_data.pdf')
104
+ text_chunks = chunk_text(pdf_text, max_tokens=1024) # Sesuaikan dengan LLaMA
105
+
106
+ # Tambahkan ke database FAISS
107
+ add_to_db(text_chunks)
108
+ save_to_faiss() # Simpan FAISS index
109
+ save_embeddings()
110
+
111
+ # Tes pencarian RAG
112
+ retrieved_chunks = search_db("Apa isi dokumen ini?")
113
+ context = "\n".join(retrieved_chunks)
114
+
115
+ prompt = f"Gunakan informasi berikut untuk menjawab:\n{context}\n\nPertanyaan: Apa isi dokumen ini?"
116
+ answer = query_llama(prompt)
117
+ print(answer)
118
+
119
+ # == Buat Chatbot Interface ==
120
+ def chatbot_interface(user_query):
121
+ retrieved_chunks = search_db(user_query) # Sudah berupa teks
122
+ context = "\n".join(retrieved_chunks)
123
+
124
+ prompt = f"Gunakan informasi berikut untuk menjawab:\n{context}\n\nPertanyaan: {user_query}"
125
+ answer = query_llama(prompt)
126
+
127
+ return answer
128
+
129
+ iface = gr.Interface(fn=chatbot_interface, inputs="text", outputs="text", title="RAG Chatbot")
130
+ iface.launch()