Umar4321 commited on
Commit
bc853b8
·
verified ·
1 Parent(s): 4a5df81

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +288 -0
app.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import pickle
4
+ from typing import List, Dict, Any
5
+
6
+ import streamlit as st
7
+ import numpy as np
8
+
9
+ from sentence_transformers import SentenceTransformer
10
+ import faiss
11
+ import PyPDF2
12
+ import docx
13
+ from groq import Groq
14
+
15
+ DEFAULT_EMBED_MODEL = "all-MiniLM-L6-v2"
16
+ DEFAULT_CHUNK_SIZE = 200
17
+ DEFAULT_CHUNK_OVERLAP = 50
18
+ DEFAULT_TOP_K = 5
19
+ INDEX_PATH = "faiss_index.bin"
20
+ METADATA_PATH = "metadata.pkl"
21
+
22
+ @st.cache_resource
23
+ def load_embedding_model(model_name: str = DEFAULT_EMBED_MODEL):
24
+ return SentenceTransformer(model_name)
25
+
26
+
27
+ def save_uploaded_file(uploaded_file) -> str:
28
+ tmpdir = tempfile.gettempdir()
29
+ temp_path = os.path.join(tmpdir, uploaded_file.name)
30
+ with open(temp_path, "wb") as f:
31
+ f.write(uploaded_file.getbuffer())
32
+ return temp_path
33
+
34
+
35
+ def extract_text_from_pdf(path: str) -> str:
36
+ text_pages = []
37
+ try:
38
+ reader = PyPDF2.PdfReader(path)
39
+ for page in reader.pages:
40
+ page_text = page.extract_text() or ""
41
+ text_pages.append(page_text)
42
+ except Exception:
43
+ return ""
44
+ return "\n\n".join(text_pages)
45
+
46
+
47
+ def extract_text_from_docx(path: str) -> str:
48
+ try:
49
+ doc = docx.Document(path)
50
+ paragraphs = [p.text for p in doc.paragraphs]
51
+ return "\n\n".join(paragraphs)
52
+ except Exception:
53
+ return ""
54
+
55
+
56
+ def extract_text_from_txt(path: str) -> str:
57
+ try:
58
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
59
+ return f.read()
60
+ except Exception:
61
+ return ""
62
+
63
+
64
+ def chunk_text(text: str, chunk_size: int = DEFAULT_CHUNK_SIZE, overlap: int = DEFAULT_CHUNK_OVERLAP) -> List[str]:
65
+ words = text.split()
66
+ chunks: List[str] = []
67
+ start = 0
68
+ n = len(words)
69
+ while start < n:
70
+ end = min(start + chunk_size, n)
71
+ chunk = " ".join(words[start:end])
72
+ chunks.append(chunk)
73
+ if end == n:
74
+ break
75
+ start = max(0, end - overlap)
76
+ return chunks
77
+
78
+
79
+ def build_faiss_index(embeddings: np.ndarray) -> faiss.IndexFlat:
80
+ embeddings = np.ascontiguousarray(embeddings.astype('float32'))
81
+ d = embeddings.shape[1]
82
+ index = faiss.IndexFlatIP(d)
83
+ index.add(embeddings)
84
+ return index
85
+
86
+
87
+ def normalize_embeddings(vecs: np.ndarray) -> np.ndarray:
88
+ vecs = np.asarray(vecs, dtype=np.float32)
89
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True)
90
+ norms[norms == 0] = 1.0
91
+ return vecs / norms
92
+
93
+
94
+ def save_index_and_metadata(index: faiss.Index, metadata: List[Dict[str, Any]], index_path: str = INDEX_PATH, meta_path: str = METADATA_PATH):
95
+ try:
96
+ faiss.write_index(index, index_path)
97
+ with open(meta_path, "wb") as f:
98
+ pickle.dump(metadata, f)
99
+ except Exception:
100
+ pass
101
+
102
+
103
+ def load_index_and_metadata(index_path: str = INDEX_PATH, meta_path: str = METADATA_PATH):
104
+ try:
105
+ if os.path.exists(index_path) and os.path.exists(meta_path):
106
+ index = faiss.read_index(index_path)
107
+ with open(meta_path, "rb") as f:
108
+ metadata = pickle.load(f)
109
+ return index, metadata
110
+ except Exception:
111
+ return None, None
112
+ return None, None
113
+
114
+
115
+ def get_groq_client_from_env(hardcoded_key: str = None) -> Groq | None:
116
+ key = os.environ.get("GROQ_API_KEY") or (hardcoded_key or None)
117
+ if not key:
118
+ return None
119
+ return Groq(api_key=key)
120
+
121
+
122
+ def groq_chat_answer(client: Groq, messages: List[Dict[str, str]], model: str = "llama-3.3-70b-versatile", temperature: float = 0.0, max_tokens: int = 512) -> str:
123
+ try:
124
+ chat_completion = client.chat.completions.create(
125
+ messages=messages,
126
+ model=model,
127
+ temperature=temperature,
128
+ max_tokens=max_tokens,
129
+ )
130
+ return getattr(chat_completion.choices[0].message, 'content', '')
131
+ except Exception:
132
+ return ""
133
+
134
+
135
+ def main():
136
+ st.set_page_config(page_title="RAG with Groq + Sentence-Transformers", layout="wide")
137
+ st.title("RAG (Retrieval Augmented Generation) — Groq + sentence-transformers + FAISS")
138
+
139
+ st.sidebar.header("Index / Retrieval settings")
140
+ chunk_size = int(st.sidebar.number_input("Chunk size (words)", min_value=50, max_value=2000, value=DEFAULT_CHUNK_SIZE, step=50))
141
+ chunk_overlap = int(st.sidebar.number_input("Chunk overlap (words)", min_value=0, max_value=500, value=DEFAULT_CHUNK_OVERLAP, step=10))
142
+ top_k = int(st.sidebar.number_input("Top-k results to retrieve", min_value=1, max_value=50, value=DEFAULT_TOP_K))
143
+
144
+ st.sidebar.markdown("---")
145
+ st.sidebar.write("Groq API key (optional - recommended to use env var)")
146
+ hardcoded_key = st.sidebar.text_input("Paste GROQ key here (will be used if env var not set)", value="")
147
+
148
+ with st.spinner("Loading embedding model..."):
149
+ embed_model = load_embedding_model()
150
+
151
+ index, metadata = load_index_and_metadata()
152
+ if index is None:
153
+ st.info("No existing FAISS index found. Upload documents and click 'Ingest documents' to build index.")
154
+ else:
155
+ try:
156
+ nt = index.ntotal
157
+ except Exception:
158
+ nt = 0
159
+ st.success(f"Loaded FAISS index with {nt} vectors.")
160
+
161
+ st.header("1) Upload documents")
162
+ uploaded_files = st.file_uploader("Upload PDF / DOCX / TXT files", type=["pdf", "docx", "txt"], accept_multiple_files=True)
163
+
164
+ if uploaded_files:
165
+ st.session_state["uploaded_list"] = [f.name for f in uploaded_files]
166
+ st.write("Files ready to ingest:", st.session_state["uploaded_list"])
167
+
168
+ if st.button("Ingest documents"):
169
+ if not uploaded_files:
170
+ st.warning("Please upload at least one file before ingesting.")
171
+ else:
172
+ all_chunks: List[str] = []
173
+ metadata = []
174
+ for uploaded in uploaded_files:
175
+ tmp_path = save_uploaded_file(uploaded)
176
+ name = uploaded.name
177
+ text = ""
178
+ if name.lower().endswith(".pdf"):
179
+ text = extract_text_from_pdf(tmp_path)
180
+ elif name.lower().endswith(".docx"):
181
+ text = extract_text_from_docx(tmp_path)
182
+ elif name.lower().endswith(".txt"):
183
+ text = extract_text_from_txt(tmp_path)
184
+ else:
185
+ continue
186
+
187
+ if not text or not text.strip():
188
+ continue
189
+
190
+ chunks = chunk_text(text, chunk_size=chunk_size, overlap=chunk_overlap)
191
+ for i, c in enumerate(chunks):
192
+ all_chunks.append(c)
193
+ metadata.append({"source": name, "chunk_id": i, "text": c})
194
+
195
+ if not all_chunks:
196
+ st.error("No chunks were generated. Aborting.")
197
+ else:
198
+ with st.spinner("Computing embeddings..."):
199
+ embeddings = embed_model.encode(all_chunks, show_progress_bar=True, convert_to_numpy=True)
200
+ embeddings = normalize_embeddings(embeddings)
201
+
202
+ index = build_faiss_index(embeddings)
203
+ save_index_and_metadata(index, metadata)
204
+ st.success(f"Index built and saved. {len(all_chunks)} chunks indexed.")
205
+
206
+ st.markdown("---")
207
+
208
+ st.header("2) Ask questions (uses retrieved context + Groq generation)")
209
+ query = st.text_area("Enter your question here", height=120)
210
+
211
+ col1, col2 = st.columns([1, 3])
212
+ with col1:
213
+ if st.button("Ask"):
214
+ if not query or not query.strip():
215
+ st.warning("Please enter a question.")
216
+ else:
217
+ if index is None or metadata is None:
218
+ st.warning("No index available. Please ingest documents first.")
219
+ else:
220
+ q_emb = embed_model.encode([query], convert_to_numpy=True)
221
+ q_emb = normalize_embeddings(q_emb)
222
+ q_emb = np.ascontiguousarray(q_emb.astype('float32'))
223
+ k = max(1, min(top_k, int(index.ntotal)))
224
+ if k == 0:
225
+ st.warning("Index is empty. Ingest documents first.")
226
+ else:
227
+ D, I = index.search(q_emb, k)
228
+ hits = I[0].tolist() if I is not None else []
229
+
230
+ contexts = []
231
+ for idx in hits:
232
+ if idx < 0 or idx >= len(metadata):
233
+ continue
234
+ meta = metadata[idx]
235
+ contexts.append(meta)
236
+
237
+ client = get_groq_client_from_env(hardcoded_key if hardcoded_key else None)
238
+ if client is None:
239
+ st.error("Groq client could not be created. Set groq API key in env or sidebar.")
240
+ else:
241
+ system_msg = {
242
+ "role": "system",
243
+ "content": "You are an assistant that answers user questions using ONLY the context passages provided. If the answer is not contained in the context, say you don't know. Provide short answers and include the source(s) for any factual claims."
244
+ }
245
+
246
+ context_blocks = []
247
+ for c in contexts:
248
+ block = f"[Source: {c['source']} | chunk_id: {c['chunk_id']}]\n{c['text']}"
249
+ context_blocks.append(block)
250
+
251
+ context_text = "\n\n---\n\n".join(context_blocks)
252
+
253
+ user_msg_text = (
254
+ f"Context passages:\n\n{context_text}\n\n"
255
+ f"Question: {query}\n\n"
256
+ "Instructions: Use only the context passages above to answer. If the context does not contain enough information, respond that you don't know. Keep the answer concise and cite the source tags in square brackets."
257
+ )
258
+
259
+ user_msg = {"role": "user", "content": user_msg_text}
260
+
261
+ with st.spinner("Generating answer from Groq model..."):
262
+ answer = groq_chat_answer(client, messages=[system_msg, user_msg])
263
+
264
+ if answer:
265
+ st.subheader("Answer")
266
+ st.write(answer)
267
+
268
+ st.subheader("Retrieved passages (for transparency)")
269
+ for c in contexts:
270
+ st.markdown(f"**Source:** {c['source']} — chunk {c['chunk_id']}")
271
+ st.write(c['text'][:500])
272
+ st.markdown("---")
273
+
274
+ st.sidebar.markdown("---")
275
+ st.sidebar.header("Index status")
276
+ if index is not None:
277
+ try:
278
+ st.sidebar.write(f"Vectors in index: {index.ntotal}")
279
+ except Exception:
280
+ st.sidebar.write("Vectors in index: unknown")
281
+ else:
282
+ st.sidebar.write("No index built yet")
283
+
284
+ st.sidebar.markdown("\nMade for development in Colab + Streamlit.\nUse responsibly and avoid publishing API keys.")
285
+
286
+
287
+ if __name__ == '__main__':
288
+ main()