tbaig1605 commited on
Commit
b536cf8
·
verified ·
1 Parent(s): 27a778b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -189
app.py CHANGED
@@ -1,203 +1,104 @@
1
  import os
2
- import re
3
- import tempfile
4
  import requests
5
- import streamlit as st
6
-
7
- # LangChain
8
- from langchain.text_splitter import RecursiveCharacterTextSplitter
9
- from langchain.vectorstores import FAISS
10
- from langchain.schema import Document
11
- from langchain_groq import ChatGroq
12
  from langchain_community.embeddings import HuggingFaceEmbeddings
13
-
14
- # PDF/DOCX/OCR
15
  from PyPDF2 import PdfReader
16
- import docx
17
- from pdf2image import convert_from_path
18
- import pytesseract
19
-
20
- # ==============================
21
- # CONFIG
22
- # ==============================
23
-
24
- st.set_page_config(page_title="Robust Google Drive RAG", layout="wide")
25
-
26
- GROQ_MODEL_NAME = "llama-3.1-8b-instant"
27
- GROQ_API_KEY = os.getenv("API")
28
- if not GROQ_API_KEY:
29
- st.error("GROQ_API_KEY not set. Add it in HF Space → Settings → Secrets.")
30
- st.stop()
31
-
32
- EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
33
- CHUNK_SIZE = 1000
34
- CHUNK_OVERLAP = 200
35
- TOP_K = 4
36
-
37
- # ==============================
38
- # GOOGLE DRIVE
39
- # ==============================
40
-
41
- def extract_drive_file_id(url: str) -> str:
42
- match = re.search(r"/d/([a-zA-Z0-9_-]+)", url)
43
- return match.group(1) if match else None
44
-
45
- def download_drive_file(file_id: str, destination: str):
46
- url = "https://drive.google.com/uc?export=download"
47
- session = requests.Session()
48
- response = session.get(url, params={"id": file_id}, stream=True)
49
- for k, v in response.cookies.items():
50
- if k.startswith("download_warning"):
51
- response = session.get(url, params={"id": file_id, "confirm": v}, stream=True)
52
- if response.status_code != 200:
53
- raise RuntimeError("Failed to download file. Check link permissions.")
54
- with open(destination, "wb") as f:
55
- for chunk in response.iter_content(32768):
56
- f.write(chunk)
57
-
58
- # ==============================
59
- # LOAD DOCUMENT
60
- # ==============================
61
 
62
- def load_pdf(path):
63
- reader = PdfReader(path)
64
- text = "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
65
- return text
66
 
67
- def load_pdf_ocr(path):
68
- pages = convert_from_path(path)
 
69
  text = ""
70
- for page in pages:
71
- text += pytesseract.image_to_string(page)
 
 
72
  return text
73
 
74
- def load_docx(path):
75
- doc = docx.Document(path)
76
- return "\n".join(p.text for p in doc.paragraphs if p.text.strip())
77
-
78
- def load_txt(path):
79
- with open(path, "r", encoding="utf-8", errors="ignore") as f:
80
- return f.read()
81
-
82
- def load_document(path):
83
- ext = path.split(".")[-1].lower()
84
- text = ""
85
- if ext == "pdf":
86
- text = load_pdf(path)
87
- if not text.strip(): # fallback to OCR
88
- text = load_pdf_ocr(path)
89
- elif ext == "docx":
90
- text = load_docx(path)
91
- elif ext == "txt":
92
- text = load_txt(path)
93
- else:
94
- raise ValueError("Unsupported file type. Only PDF/DOCX/TXT allowed.")
95
- return text.replace("\xa0", " ").replace("\n\n", "\n").strip()
96
-
97
- # ==============================
98
- # EMBEDDINGS
99
- # ==============================
100
-
101
- @st.cache_resource
102
- def load_embeddings():
103
- return HuggingFaceEmbeddings(model_name=EMBED_MODEL)
104
-
105
- # ==============================
106
- # VECTOR STORE
107
- # ==============================
108
-
109
- def build_vectorstore(text: str):
110
- splitter = RecursiveCharacterTextSplitter(
111
- chunk_size=CHUNK_SIZE,
112
- chunk_overlap=CHUNK_OVERLAP
113
  )
114
- chunks = splitter.split_text(text)
115
- docs = [Document(page_content=c) for c in chunks]
116
- vs = FAISS.from_documents(docs, load_embeddings())
117
- return vs, len(chunks)
118
 
119
- # ==============================
120
- # QA
121
- # ==============================
122
-
123
- def answer_question(question, vectorstore):
124
- docs = vectorstore.similarity_search(question, k=TOP_K)
125
- if not docs:
126
- return "The answer is not available in the provided document.", []
127
-
128
- context = "\n\n".join(d.page_content for d in docs)
129
-
130
- system_prompt = (
131
- "You must answer ONLY from the provided context.\n"
132
- "If the answer is missing, reply exactly:\n"
133
- "'The answer is not available in the provided document.'\n"
134
- "No external knowledge allowed."
135
- )
136
-
137
- llm = ChatGroq(
138
- api_key=GROQ_API_KEY,
139
- model_name=GROQ_MODEL_NAME,
140
- temperature=0
141
  )
142
-
143
- response = llm.invoke([
144
- {"role": "system", "content": system_prompt},
145
- {"role": "user", "content": f"Context:\n{context}\n\nQuestion:\n{question}"}
146
- ])
147
-
148
- return response.content.strip(), docs
149
-
150
- # ==============================
151
- # STREAMLIT UI
152
- # ==============================
153
-
154
- st.title("📄 Robust Google Drive RAG App")
155
- st.caption("Answers strictly from your document. Supports scanned PDFs via OCR.")
156
-
157
- if "vectorstore" not in st.session_state:
158
- st.session_state.vectorstore = None
159
-
160
- with st.sidebar:
161
- st.header("📂 Document")
162
- drive_link = st.text_input("Google Drive Link")
163
-
164
- if st.button("Process Document"):
165
- try:
166
- file_id = extract_drive_file_id(drive_link)
167
- if not file_id:
168
- raise ValueError("Invalid Google Drive link.")
169
-
170
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
171
- download_drive_file(file_id, tmp.name)
172
- text = load_document(tmp.name)
173
-
174
- if not text.strip():
175
- raise ValueError("Document appears empty.")
176
-
177
- vectorstore, chunks = build_vectorstore(text)
178
- st.session_state.vectorstore = vectorstore
179
- st.success(f"Document indexed successfully ({chunks} chunks).")
180
-
181
- except Exception as e:
182
- st.error(str(e))
183
-
184
- if st.button("Reset"):
185
- st.session_state.vectorstore = None
186
- st.success("Vector store cleared.")
187
-
188
- st.subheader("❓ Ask a Question")
189
- question = st.text_input("Your question")
190
-
191
- if st.button("Get Answer"):
192
- if not st.session_state.vectorstore:
193
- st.error("Process a document first.")
194
  else:
195
- answer, docs = answer_question(question, st.session_state.vectorstore)
196
- st.markdown("### ✅ Answer")
197
- st.write(answer)
198
-
199
- with st.expander("🔍 Retrieved Context"):
200
- for i, d in enumerate(docs, 1):
201
- st.markdown(f"**Chunk {i}**")
202
- st.write(d.page_content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
 
1
  import os
 
 
2
  import requests
3
+ from groq import Groq
 
 
 
 
 
 
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
  from PyPDF2 import PdfReader
8
+ import streamlit as st
9
+ from tempfile import NamedTemporaryFile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Initialize Groq client
12
+ client = Groq(api_key=os.environ['API'])
 
 
13
 
14
+ # Function to extract text from a PDF
15
+ def extract_text_from_pdf(pdf_file_path):
16
+ pdf_reader = PdfReader(pdf_file_path)
17
  text = ""
18
+ for page in pdf_reader.pages:
19
+ page_text = page.extract_text()
20
+ if page_text:
21
+ text += page_text
22
  return text
23
 
24
+ # Function to split text into chunks
25
+ def chunk_text(text, chunk_size=500, chunk_overlap=50):
26
+ text_splitter = RecursiveCharacterTextSplitter(
27
+ chunk_size=chunk_size, chunk_overlap=chunk_overlap
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  )
29
+ return text_splitter.split_text(text)
 
 
 
30
 
31
+ # Function to create embeddings and store them in FAISS
32
+ def create_embeddings_and_store(chunks, vector_db=None):
33
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
34
+ if vector_db is None:
35
+ vector_db = FAISS.from_texts(chunks, embedding=embeddings)
36
+ else:
37
+ vector_db.add_texts(chunks)
38
+ return vector_db
39
+
40
+ # Function to query the vector database and interact with Groq
41
+ def query_vector_db(query, vector_db):
42
+ docs = vector_db.similarity_search(query, k=3)
43
+ context = "\n".join([doc.page_content for doc in docs])
44
+ chat_completion = client.chat.completions.create(
45
+ messages=[
46
+ {"role": "system", "content": f"Use the following context:\n{context}"},
47
+ {"role": "user", "content": query},
48
+ ],
49
+ model="llama3-8b-8192",
 
 
 
50
  )
51
+ return chat_completion.choices[0].message.content
52
+
53
+ # Function to convert Google Drive view link to downloadable link
54
+ def get_direct_download_link(view_url):
55
+ if "drive.google.com/file/d/" in view_url:
56
+ file_id = view_url.split("/file/d/")[1].split("/")[0]
57
+ return f"https://drive.google.com/uc?export=download&id={file_id}"
58
+ return None
59
+
60
+ # Function to download and save a PDF from a URL
61
+ def download_pdf_from_url(url):
62
+ direct_url = get_direct_download_link(url)
63
+ if not direct_url:
64
+ return None
65
+ response = requests.get(direct_url)
66
+ if response.status_code == 200:
67
+ temp_file = NamedTemporaryFile(delete=False, suffix=".pdf")
68
+ temp_file.write(response.content)
69
+ temp_file.close()
70
+ return temp_file.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  else:
72
+ return None
73
+
74
+ # Streamlit app
75
+ st.title("RAG-Based QA on Google Drive PDFs")
76
+
77
+ # Only fetch from provided links
78
+ doc_links = [
79
+ "https://docs.google.com/document/d/1_3DqDH0WVFQcwb23EwFWVfHCC0fCv58p/edit?usp=drive_link&ouid=108024737681201137204&rtpof=true&sd=true",
80
+ ]
81
+
82
+ vector_db = None
83
+
84
+ # Process Google Drive documents
85
+ for idx, link in enumerate(doc_links):
86
+ st.write(f"📄 Fetching and processing PDF from Link {idx + 1}...")
87
+ pdf_path = download_pdf_from_url(link)
88
+ if pdf_path:
89
+ text = extract_text_from_pdf(pdf_path)
90
+ chunks = chunk_text(text)
91
+ vector_db = create_embeddings_and_store(chunks, vector_db=vector_db)
92
+ st.success(f"✅ Processed document {idx + 1}")
93
+ else:
94
+ st.error(f"❌ Failed to download or process PDF from Link {idx + 1}")
95
+
96
+ # User query input
97
+ user_query = st.text_input("🔍 Enter your query:")
98
+ if user_query and vector_db:
99
+ response = query_vector_db(user_query, vector_db)
100
+ st.subheader("💬 Response from LLM:")
101
+ st.write(response)
102
+ elif user_query:
103
+ st.warning("⚠️ No documents processed to query.")
104