Aaravkumar commited on
Commit
cb1f2f8
·
verified ·
1 Parent(s): ca6ace5

Upload 7 files

Browse files
Files changed (7) hide show
  1. app.py +97 -69
  2. chunker.py +31 -0
  3. embedder.py +19 -0
  4. loader.py +17 -0
  5. requirements.txt +7 -0
  6. retriever.py +28 -0
  7. vector.py +26 -0
app.py CHANGED
@@ -1,69 +1,97 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
- chatbot = 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
- with gr.Blocks() as demo:
63
- with gr.Sidebar():
64
- gr.LoginButton()
65
- chatbot.render()
66
-
67
-
68
- if __name__ == "__main__":
69
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+ from loader import Loader
5
+ from chunker import Chunker
6
+ from embedder import Embedder
7
+ from vector import VectorStorage
8
+ from retriever import Retriever
9
+
10
+
11
+ client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")
12
+
13
+ def process_document(file):
14
+ """Systemic Entry Point: Converts PDF to Searchable Index"""
15
+ if file is None:
16
+ return None, None, "❌ Please upload a PDF first."
17
+
18
+
19
+ text = Loader(file.name).load()
20
+ chunks = Chunker().chunker(text)
21
+
22
+
23
+ embedder = Embedder()
24
+ vectors = embedder.embed(chunks)
25
+
26
+ store = VectorStorage(dimension=len(vectors[0]))
27
+ store.add(vectors, chunks)
28
+
29
+ return store, embedder, "✅ PDF Indexed. Ready to chat!"
30
+
31
+ def rag_chat(message, history, store, embedder):
32
+ """The Retrieval-Generation Loop"""
33
+ if store is None:
34
+ yield "Please upload and process a PDF on the left first."
35
+ return
36
+
37
+
38
+ retriever = Retriever(store, embedder, k=3)
39
+ context_chunks = retriever.retrieve(message)
40
+
41
+
42
+ if not context_chunks:
43
+ yield "I couldn't find any relevant information in the document to answer that."
44
+ return
45
+
46
+ context_text = "\n\n".join(context_chunks)
47
+
48
+
49
+ system_prompt = (
50
+ "You are a research assistant which gives answer to the questions of the user from the provided context only. Use the provided context to answer. "
51
+ "If the answer isn't there, say you don't know. Do not hallucinate."
52
+ )
53
+
54
+
55
+ messages = [{"role": "system", "content": system_prompt}]
56
+ messages.extend(history)
57
+ messages.append({"role": "user", "content": f"Context:\n{context_text}\n\nQuestion: {message}"})
58
+
59
+ response = ""
60
+ for token in client.chat_completion(messages, max_tokens=512, stream=True):
61
+ token_text = token.choices[0].delta.content
62
+ if token_text:
63
+ response += token_text
64
+ yield response
65
+
66
+
67
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="slate")) as demo:
68
+
69
+ store_state = gr.State()
70
+ embedder_state = gr.State()
71
+
72
+ gr.Markdown("# 📑 DocuMind AI")
73
+
74
+ with gr.Row():
75
+
76
+ with gr.Column(scale=1):
77
+ file_input = gr.File(label="Source Document", file_types=[".pdf"])
78
+ btn = gr.Button("Build Knowledge Base", variant="primary")
79
+ status = gr.Markdown("Status: Waiting for upload...")
80
+
81
+
82
+ with gr.Column(scale=3):
83
+ gr.ChatInterface(
84
+ fn=rag_chat,
85
+ additional_inputs=[store_state, embedder_state],
86
+ type="messages",
87
+ fill_height=True
88
+ )
89
+
90
+
91
+ btn.click(
92
+ fn=process_document,
93
+ inputs=[file_input],
94
+ outputs=[store_state, embedder_state, status]
95
+ )
96
+
97
+ demo.launch()
chunker.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Chunker:
2
+ def __init__(self, chunk_size=500, overlap=100):
3
+ self.chunk_size = chunk_size
4
+ self.overlap = overlap
5
+
6
+ def chunker(self, text):
7
+ if self.overlap >= self.chunk_size:
8
+ raise ValueError("Overlap must be smaller than chunk size.")
9
+
10
+ chunks = []
11
+ start = 0
12
+ text_size = len(text)
13
+
14
+ while start < text_size:
15
+ end = start + self.chunk_size
16
+
17
+
18
+ if end < text_size:
19
+ last_space = text.rfind(' ', start, end)
20
+ if last_space != -1:
21
+ end = last_space
22
+
23
+
24
+ chunk = text[start:end].strip()
25
+ if chunk:
26
+ chunks.append(chunk)
27
+
28
+
29
+ start = end - self.overlap
30
+
31
+ return chunks
embedder.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer
2
+ class Embedder:
3
+ """
4
+ converts the text into numbers
5
+ and places them close meaningfully
6
+ """
7
+ def __init__(self):
8
+ self.model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
9
+
10
+
11
+ def embed(self,chunk):
12
+ vectors = self.model.encode(chunk)
13
+ return vectors
14
+
15
+ def embed_q(self,query):
16
+ q_vector = self.model.encode(query)
17
+ return q_vector
18
+
19
+
loader.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PyPDF2
2
+
3
+
4
+ class Loader:
5
+ """
6
+ loads the text from the pdf files
7
+ """
8
+ def __init__(self,file_path):
9
+ self.file = file_path
10
+
11
+ def load(self):
12
+ reader = PyPDF2.PdfReader(self.file)
13
+ text = ""
14
+
15
+ for page in reader.pages:
16
+ text = text + page.extract_text()
17
+ return text
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ huggingface_hub
3
+ sentence-transformers
4
+ faiss-cpu
5
+ numpy
6
+ PyPDF2>=3.0.0
7
+
retriever.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Retriever:
2
+ def __init__(self, vector_store, embedder, k=5):
3
+ self.vector_store = vector_store
4
+ self.embedder = embedder
5
+ self.k = k
6
+
7
+ def retrieve(self, query):
8
+
9
+ vquery = self.embedder.embed_q(query)
10
+
11
+
12
+ scores, indices = self.vector_store.search(vquery, self.k)
13
+
14
+
15
+ if scores[0] < 0.5:
16
+ print(f"Evidence too low: {scores[0]}")
17
+ return []
18
+
19
+
20
+ results = [
21
+ self.vector_store.chunks[i]
22
+ for i in indices if i != -1
23
+ ]
24
+ return results
25
+
26
+
27
+
28
+
vector.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import faiss
2
+ import numpy as np
3
+
4
+ class VectorStorage:
5
+ def __init__(self, dimension=384):
6
+
7
+ self.index = faiss.IndexFlatIP(dimension)
8
+ self.chunks = []
9
+
10
+ def add(self, vectors, chunks):
11
+
12
+ v_array = np.array(vectors).astype('float32')
13
+
14
+ faiss.normalize_L2(v_array)
15
+
16
+ self.index.add(v_array)
17
+ self.chunks.extend(chunks)
18
+
19
+ def search(self, query_vector, k=5):
20
+
21
+ q_array = np.array([query_vector]).astype('float32')
22
+ faiss.normalize_L2(q_array)
23
+
24
+
25
+ scores, indices = self.index.search(q_array, k)
26
+ return scores[0], indices[0]