abubakaraabi786 commited on
Commit
fb9b7af
·
verified ·
1 Parent(s): 2cc151b
Files changed (1) hide show
  1. app.py +156 -69
app.py CHANGED
@@ -1,70 +1,157 @@
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
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
68
-
69
- if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import tempfile
4
+ from typing import List
5
+
6
+ import PyPDF2
7
+ from sentence_transformers import SentenceTransformer
8
+ import numpy as np
9
+ from sklearn.metrics.pairwise import cosine_similarity
10
+
11
+ from groq import Groq
12
+
13
+ # -----------------------------
14
+ # Configuration
15
+ # -----------------------------
16
+ GROQ_API_KEY = os.getenv("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")
17
+ MODEL_NAME = "llama3-8b-8192"
18
+
19
+ client = Groq(api_key=GROQ_API_KEY)
20
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
21
+
22
+ # -----------------------------
23
+ # PDF Processing
24
+ # -----------------------------
25
+ def extract_text_from_pdfs(files: List[tempfile.NamedTemporaryFile]):
26
+ documents = []
27
+ for file in files:
28
+ reader = PyPDF2.PdfReader(file)
29
+ for page_num, page in enumerate(reader.pages):
30
+ text = page.extract_text()
31
+ if text:
32
+ documents.append({
33
+ "text": text,
34
+ "source": f"{os.path.basename(file.name)} - page {page_num + 1}"
35
+ })
36
+ return documents
37
+
38
+ # -----------------------------
39
+ # Chunking
40
+ # -----------------------------
41
+ def chunk_text(documents, chunk_size=500, overlap=50):
42
+ chunks = []
43
+ for doc in documents:
44
+ text = doc["text"]
45
+ words = text.split()
46
+ start = 0
47
+ while start < len(words):
48
+ chunk_words = words[start:start + chunk_size]
49
+ chunk_text = " ".join(chunk_words)
50
+ chunks.append({
51
+ "text": chunk_text,
52
+ "source": doc["source"]
53
+ })
54
+ start += chunk_size - overlap
55
+ return chunks
56
+
57
+ # -----------------------------
58
+ # Embeddings & Retrieval
59
+ # -----------------------------
60
+ def embed_chunks(chunks):
61
+ texts = [c["text"] for c in chunks]
62
+ embeddings = embedder.encode(texts)
63
+ return embeddings
64
+
65
+ def retrieve_relevant_chunks(query, chunks, embeddings, top_k=3):
66
+ query_embedding = embedder.encode([query])
67
+ similarities = cosine_similarity(query_embedding, embeddings)[0]
68
+ top_indices = np.argsort(similarities)[-top_k:][::-1]
69
+
70
+ results = []
71
+ for idx in top_indices:
72
+ results.append(chunks[idx])
73
+ return results
74
+
75
+ # -----------------------------
76
+ # LLM Call
77
+ # -----------------------------
78
+ def ask_llm(question, context, history):
79
+ messages = history.copy()
80
+
81
+ system_prompt = (
82
+ "You are a helpful assistant. Answer the question strictly using the provided context. "
83
+ "If the answer is not in the context, say so."
84
+ )
85
+
86
+ messages.insert(0, {"role": "system", "content": system_prompt})
87
+ messages.append({
88
+ "role": "user",
89
+ "content": f"Context:\n{context}\n\nQuestion:\n{question}"
90
+ })
91
+
92
+ response = client.chat.completions.create(
93
+ model=MODEL_NAME,
94
+ messages=messages,
95
+ temperature=0.3
96
+ )
97
+
98
+ return response.choices[0].message.content
99
+
100
+ # -----------------------------
101
+ # Main Chat Logic
102
+ # -----------------------------
103
+ def chat(files, question, chat_history):
104
+ if not files:
105
+ return chat_history, "Please upload PDF files first."
106
+
107
+ documents = extract_text_from_pdfs(files)
108
+ chunks = chunk_text(documents)
109
+ embeddings = embed_chunks(chunks)
110
+
111
+ relevant_chunks = retrieve_relevant_chunks(question, chunks, embeddings)
112
+
113
+ context = ""
114
+ sources = []
115
+ for c in relevant_chunks:
116
+ context += c["text"] + "\n\n"
117
+ sources.append(c["source"])
118
+
119
+ answer = ask_llm(question, context, chat_history)
120
+
121
+ answer_with_sources = (
122
+ f"{answer}\n\n"
123
+ f"Sources:\n" + "\n".join(set(sources))
124
+ )
125
+
126
+ chat_history.append({"role": "user", "content": question})
127
+ chat_history.append({"role": "assistant", "content": answer_with_sources})
128
+
129
+ return chat_history, answer_with_sources
130
+
131
+ # -----------------------------
132
+ # Gradio UI
133
+ # -----------------------------
134
+ with gr.Blocks(title="Enhanced RAG Chatbot") as demo:
135
+ gr.Markdown("## 📚 Enhanced RAG-Based Chatbot (PDF QA)")
136
+ gr.Markdown("Upload multiple PDFs and ask questions based on their content.")
137
+
138
+ with gr.Row():
139
+ pdf_files = gr.File(
140
+ label="Upload PDF Files",
141
+ file_types=[".pdf"],
142
+ file_count="multiple"
143
+ )
144
+
145
+ chatbot = gr.Chatbot()
146
+ question = gr.Textbox(label="Ask a question")
147
+ state = gr.State([])
148
+
149
+ submit = gr.Button("Ask")
150
+
151
+ submit.click(
152
+ fn=chat,
153
+ inputs=[pdf_files, question, state],
154
+ outputs=[chatbot, chatbot]
155
+ )
156
+
157
+ demo.launch()