imeesam commited on
Commit
48acffd
Β·
verified Β·
1 Parent(s): 2f93d26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -98
app.py CHANGED
@@ -1,26 +1,29 @@
1
- # app.py β€” PDF upload version
2
-
3
  import os
4
  import gradio as gr
5
- from langchain_community.document_loaders import PyPDFLoader
 
 
 
 
 
 
6
  from langchain_text_splitters import RecursiveCharacterTextSplitter
7
  from langchain_community.embeddings import HuggingFaceEmbeddings
8
  from langchain_community.vectorstores import FAISS
9
  from langchain_groq import ChatGroq
10
- from langchain.prompts import ChatPromptTemplate
11
- from langchain.schema.runnable import RunnablePassthrough
12
- from langchain.schema.output_parser import StrOutputParser
13
 
14
  # ── Config ─────────────────────────────────────────────────────────────────────
15
  EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
16
  GROQ_MODEL = "llama-3.1-8b-instant"
17
- CHUNK_SIZE = 300 # larger chunks work better for dense PDFs
18
- CHUNK_OVERLAP = 100
 
19
  TOP_K = 4
20
 
21
  RAG_PROMPT = ChatPromptTemplate.from_template("""
22
- You are a helpful assistant. Answer the question using ONLY the context below.
23
- If the answer is not in the context, say "I don't have enough information."
 
24
 
25
  Context:
26
  {context}
@@ -30,141 +33,146 @@ Question: {question}
30
  Answer:
31
  """)
32
 
33
- # ── Load embedding model once at startup (slow, ~30s) ─────────────────────────
34
- print("Loading embedding model...")
35
  embeddings = HuggingFaceEmbeddings(
36
  model_name=EMBED_MODEL,
37
  model_kwargs={"device": "cpu"},
38
  encode_kwargs={"normalize_embeddings": True}
39
  )
40
- print("Embeddings ready.")
41
 
42
- # Global state β€” replaced whenever new PDFs are uploaded
43
- rag_chain = None
44
  vectorstore = None
45
 
46
- # ── Core logic ─────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def process_pdfs(pdf_files):
48
- """
49
- Called when user clicks 'Process PDFs'.
50
- pdf_files: list of temp file paths Gradio provides.
51
- Returns a status message.
52
- """
53
  global rag_chain, vectorstore
54
 
55
  if not pdf_files:
56
- return "No files uploaded. Please upload at least one PDF."
57
 
58
  all_chunks = []
59
- splitter = RecursiveCharacterTextSplitter(
60
- chunk_size=CHUNK_SIZE,
61
- chunk_overlap=CHUNK_OVERLAP,
62
- separators=["\n\n", "\n", ".", " ", ""]
63
- )
64
 
65
  for pdf_file in pdf_files:
66
  try:
67
- # pdf_file is a temp path string like /tmp/gradio/abc123/file.pdf
68
- loader = PyPDFLoader(pdf_file)
69
- pages = loader.load() # one Document per page
70
-
71
- # Add filename to metadata for traceability
72
- filename = os.path.basename(pdf_file)
73
- for page in pages:
74
- page.metadata["source"] = filename
75
-
76
- chunks = splitter.split_documents(pages)
77
  all_chunks.extend(chunks)
78
- print(f"Loaded {filename}: {len(pages)} pages β†’ {len(chunks)} chunks")
 
79
 
80
  except Exception as e:
81
- return f"Error loading {pdf_file}: {str(e)}"
82
 
83
  if not all_chunks:
84
- return "No text could be extracted. Check if the PDFs contain selectable text (not scanned images)."
85
 
86
- # Build FAISS index from all chunks
87
- print(f"Indexing {len(all_chunks)} chunks...")
88
  vectorstore = FAISS.from_documents(all_chunks, embeddings)
89
- retriever = vectorstore.as_retriever(search_kwargs={"k": TOP_K})
90
 
91
- # Build LLM
92
- llm = ChatGroq(
93
- model=GROQ_MODEL,
94
- temperature=0.2,
95
- max_tokens=1024,
96
- groq_api_key=os.environ["GROQ_API_KEY"]
97
  )
98
 
99
  def format_docs(docs):
100
- # Include source filename in context so the LLM knows where info came from
101
  return "\n\n".join(
102
- f"[Source: {d.metadata.get('source', 'unknown')}, "
103
- f"Page {d.metadata.get('page', '?')+1}]\n{d.page_content}"
104
  for d in docs
105
  )
106
 
 
 
 
 
 
 
 
107
  rag_chain = (
108
- {"context": retriever | format_docs, "question": RunnablePassthrough()}
 
109
  | RAG_PROMPT
110
  | llm
111
  | StrOutputParser()
112
  )
113
 
114
- total_pages = sum(
115
- len(PyPDFLoader(f).load()) for f in pdf_files
116
- )
117
- return (
118
- f"Ready! Indexed {len(pdf_files)} PDF(s), "
119
- f"{total_pages} pages, "
120
- f"{len(all_chunks)} chunks. You can now ask questions."
121
- )
122
-
123
 
 
124
  def chat(message, history):
125
  if rag_chain is None:
126
- return "", history + [[message, "Please upload and process PDFs first."]]
127
- if not message.strip():
128
- return "", history
129
- try:
130
- response = rag_chain.invoke(message)
131
- except Exception as e:
132
- response = f"Error: {str(e)}"
133
  history.append([message, response])
 
134
  return "", history
135
 
 
 
136
 
137
- # ── Gradio UI ──────────────────────────────────────────────────────────────────
138
- with gr.Blocks(title="PDF RAG Chatbot", theme=gr.themes.Soft()) as demo:
139
- gr.Markdown("## PDF RAG Chatbot\nUpload your PDFs, then ask questions about them.")
140
 
141
  with gr.Row():
142
- with gr.Column(scale=1):
143
- pdf_input = gr.File(
144
- label="Upload PDFs",
145
- file_types=[".pdf"],
146
- file_count="multiple" # allow multiple files at once
147
- )
148
- process_btn = gr.Button("Process PDFs", variant="primary")
149
- status_box = gr.Textbox(
150
- label="Status",
151
- interactive=False,
152
- placeholder="Upload PDFs and click Process..."
153
- )
154
 
155
- with gr.Column(scale=2):
156
- chatbot = gr.Chatbot(height=450, label="Chat")
157
- msg = gr.Textbox(placeholder="Ask a question about your PDFs...", label="Question")
158
- clear = gr.Button("Clear chat")
159
 
160
- # Wire up events
161
- process_btn.click(
162
- fn=process_pdfs,
163
- inputs=[pdf_input],
164
- outputs=[status_box]
165
- )
166
- msg.submit(chat, [msg, chatbot], [msg, chatbot])
167
- clear.click(lambda: [], outputs=[chatbot])
168
 
169
- if __name__ == "__main__":
170
- demo.launch()
 
 
 
1
  import os
2
  import gradio as gr
3
+ import fitz # PyMuPDF
4
+
5
+ from langchain_core.documents import Document
6
+ from langchain_core.prompts import ChatPromptTemplate
7
+ from langchain_core.runnables import RunnablePassthrough
8
+ from langchain_core.output_parsers import StrOutputParser
9
+
10
  from langchain_text_splitters import RecursiveCharacterTextSplitter
11
  from langchain_community.embeddings import HuggingFaceEmbeddings
12
  from langchain_community.vectorstores import FAISS
13
  from langchain_groq import ChatGroq
 
 
 
14
 
15
  # ── Config ─────────────────────────────────────────────────────────────────────
16
  EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
17
  GROQ_MODEL = "llama-3.1-8b-instant"
18
+
19
+ CHUNK_SIZE = 1000
20
+ CHUNK_OVERLAP = 150
21
  TOP_K = 4
22
 
23
  RAG_PROMPT = ChatPromptTemplate.from_template("""
24
+ You are a helpful assistant.
25
+ Answer ONLY using the context below.
26
+ If context is insufficient, say "I don't have enough information."
27
 
28
  Context:
29
  {context}
 
33
  Answer:
34
  """)
35
 
36
+ # ── Embeddings ────────────────────────────────────────────────────────────────
37
+ print("Loading embeddings...")
38
  embeddings = HuggingFaceEmbeddings(
39
  model_name=EMBED_MODEL,
40
  model_kwargs={"device": "cpu"},
41
  encode_kwargs={"normalize_embeddings": True}
42
  )
43
+ print("Embeddings loaded.")
44
 
45
+ # ── Globals ────────────────────────────────────────────────────────────────────
46
+ rag_chain = None
47
  vectorstore = None
48
 
49
+ # ── Text cleaning ─────────────────────────────────────────────────────────────
50
+ def clean_text(text):
51
+ lines = text.split("\n")
52
+ cleaned = []
53
+
54
+ for line in lines:
55
+ line = line.strip()
56
+
57
+ if len(line) < 30:
58
+ continue
59
+
60
+ # remove paper noise
61
+ if any(x in line.lower() for x in ["cvpr", "eccv", "ieee", "arxiv", "doi"]):
62
+ continue
63
+
64
+ cleaned.append(line)
65
+
66
+ return "\n".join(cleaned)
67
+
68
+ # ── PDF Loader (FIXED) ────────────────────────────────────────────────────────
69
+ def load_pdf(file_path):
70
+ docs = []
71
+ pdf = fitz.open(file_path)
72
+
73
+ for i, page in enumerate(pdf):
74
+ text = page.get_text()
75
+ text = clean_text(text)
76
+
77
+ docs.append(
78
+ Document(
79
+ page_content=text,
80
+ metadata={"page": i}
81
+ )
82
+ )
83
+
84
+ return docs
85
+
86
+ # ── Chunking ──────────────────────────────────────────────────────────────────
87
+ splitter = RecursiveCharacterTextSplitter(
88
+ chunk_size=CHUNK_SIZE,
89
+ chunk_overlap=CHUNK_OVERLAP,
90
+ separators=["\n\n", "\n", ".", " ", ""]
91
+ )
92
+
93
+ # ── Build RAG ─────────────────────────────────────────────────────────────────
94
  def process_pdfs(pdf_files):
 
 
 
 
 
95
  global rag_chain, vectorstore
96
 
97
  if not pdf_files:
98
+ return "Upload at least one PDF."
99
 
100
  all_chunks = []
 
 
 
 
 
101
 
102
  for pdf_file in pdf_files:
103
  try:
104
+ docs = load_pdf(pdf_file)
105
+ chunks = splitter.split_documents(docs)
 
 
 
 
 
 
 
 
106
  all_chunks.extend(chunks)
107
+
108
+ print(f"{pdf_file} β†’ {len(chunks)} chunks")
109
 
110
  except Exception as e:
111
+ return f"Error: {str(e)}"
112
 
113
  if not all_chunks:
114
+ return "No usable text found in PDFs."
115
 
116
+ print("Building FAISS index...")
 
117
  vectorstore = FAISS.from_documents(all_chunks, embeddings)
 
118
 
119
+ # MMR retriever (better than plain similarity)
120
+ retriever = vectorstore.as_retriever(
121
+ search_type="mmr",
122
+ search_kwargs={"k": TOP_K, "fetch_k": 10}
 
 
123
  )
124
 
125
  def format_docs(docs):
 
126
  return "\n\n".join(
127
+ f"[Page {d.metadata.get('page', 0)+1}]\n{d.page_content}"
 
128
  for d in docs
129
  )
130
 
131
+ llm = ChatGroq(
132
+ model=GROQ_MODEL,
133
+ temperature=0.2,
134
+ max_tokens=1024,
135
+ groq_api_key=os.environ["GROQ_API_KEY"]
136
+ )
137
+
138
  rag_chain = (
139
+ {"context": retriever | format_docs,
140
+ "question": RunnablePassthrough()}
141
  | RAG_PROMPT
142
  | llm
143
  | StrOutputParser()
144
  )
145
 
146
+ return f"Ready! Indexed {len(pdf_files)} PDFs with {len(all_chunks)} chunks."
 
 
 
 
 
 
 
 
147
 
148
+ # ── Chat function ─────────────────────────────────────────────────────────────
149
  def chat(message, history):
150
  if rag_chain is None:
151
+ return "", history + [[message, "Please process PDFs first."]]
152
+
153
+ response = rag_chain.invoke(message)
 
 
 
 
154
  history.append([message, response])
155
+
156
  return "", history
157
 
158
+ # ── UI ───────────────────────────────────────────────────────────────────────
159
+ with gr.Blocks(title="Fixed RAG Chatbot") as demo:
160
 
161
+ gr.Markdown("## πŸ“„ Improved PDF RAG Chatbot")
 
 
162
 
163
  with gr.Row():
164
+ with gr.Column():
165
+ pdf_input = gr.File(file_types=[".pdf"], file_count="multiple")
166
+ btn = gr.Button("Process PDFs", variant="primary")
167
+ status = gr.Textbox(label="Status")
 
 
 
 
 
 
 
 
168
 
169
+ with gr.Column():
170
+ chatbox = gr.Chatbot(height=450)
171
+ msg = gr.Textbox(label="Ask a question")
172
+ clear = gr.Button("Clear")
173
 
174
+ btn.click(process_pdfs, pdf_input, status)
175
+ msg.submit(chat, [msg, chatbox], [msg, chatbox])
176
+ clear.click(lambda: [], outputs=chatbox)
 
 
 
 
 
177
 
178
+ demo.launch()