superbsaeed commited on
Commit
0c7ba36
Β·
verified Β·
1 Parent(s): a3c6963

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -32
app.py CHANGED
@@ -14,6 +14,9 @@ vectorstore = None
14
  qa_chain = None
15
  retrieved_docs = {}
16
 
 
 
 
17
  # ── Embedding model (loaded once) ─────────────────────────────
18
  embeddings = HuggingFaceEmbeddings(
19
  model_name="sentence-transformers/all-MiniLM-L6-v2",
@@ -28,9 +31,9 @@ def format_docs(docs):
28
  for doc in docs
29
  )
30
 
31
- def build_chain(groq_api_key: str):
32
  llm = ChatGroq(
33
- api_key=groq_api_key,
34
  model="llama-3.3-70b-versatile",
35
  temperature=0.2,
36
  max_tokens=1024,
@@ -63,22 +66,21 @@ Answer:""",
63
  "question": question
64
  }
65
 
66
- chain = (
67
  RunnableLambda(retrieve_and_format)
68
  | PROMPT
69
  | llm
70
  | StrOutputParser()
71
  )
72
- return chain
73
 
74
  # ── Core functions ────────────────────────────────────────────
75
- def process_pdf(pdf_file, groq_api_key, progress=gr.Progress()):
76
  global vectorstore, qa_chain
77
 
78
  if pdf_file is None:
79
  return "⚠️ Please upload a PDF file."
80
- if not groq_api_key.strip():
81
- return "⚠️ Please enter your Groq API key."
82
 
83
  try:
84
  progress(0.1, desc="Loading PDF...")
@@ -97,7 +99,7 @@ def process_pdf(pdf_file, groq_api_key, progress=gr.Progress()):
97
  vectorstore = FAISS.from_documents(chunks, embeddings)
98
 
99
  progress(0.9, desc="Setting up RAG chain...")
100
- qa_chain = build_chain(groq_api_key.strip())
101
 
102
  progress(1.0, desc="Done!")
103
  return f"βœ… Ready! Loaded **{len(pages)} pages** β†’ **{len(chunks)} chunks**."
@@ -108,7 +110,8 @@ def process_pdf(pdf_file, groq_api_key, progress=gr.Progress()):
108
 
109
  def answer_question(question, history):
110
  if vectorstore is None or qa_chain is None:
111
- history.append((question, "⚠️ Please upload a PDF and enter your Groq API key first."))
 
112
  return "", history
113
  if not question.strip():
114
  return "", history
@@ -125,9 +128,10 @@ def answer_question(question, history):
125
  answer += f"\n\nπŸ“„ *Sources: pages {pages}*"
126
 
127
  except Exception as e:
128
- answer = f"❌ Error generating answer: {str(e)}"
129
 
130
- history.append((question, answer))
 
131
  return "", history
132
 
133
 
@@ -138,33 +142,25 @@ def clear_all():
138
  retrieved_docs = {}
139
  return [], "", "πŸ—‘οΈ Cleared. Upload a new PDF to start again."
140
 
141
- # ── Gradio UI (Gradio 6 compatible) ──────────────────────────
142
- with gr.Blocks(title="PDF RAG Chatbot") as demo: # ← theme removed from here
143
 
144
- gr.Markdown("""
145
- # πŸ“š PDF RAG Chatbot
146
- Upload a PDF, enter your Groq API key, then ask questions about the document.
147
- """)
148
 
149
  with gr.Row():
 
 
150
  with gr.Column(scale=1):
151
- gr.Markdown("### βš™οΈ Setup")
152
- groq_key_box = gr.Textbox(
153
- label="Groq API Key",
154
- placeholder="gsk_...",
155
- type="password",
156
- value=os.environ.get("GROQ_API_KEY", "")
157
- )
158
- pdf_upload = gr.File(
159
- label="Upload PDF",
160
- file_types=[".pdf"]
161
- )
162
  process_btn = gr.Button("πŸ“₯ Process PDF", variant="primary")
163
  status_box = gr.Markdown("*Upload a PDF to begin.*")
164
 
 
165
  with gr.Column(scale=2):
166
  gr.Markdown("### πŸ’¬ Chat")
167
- chatbot = gr.Chatbot(height=480) # ← bubble_full_width removed
168
  with gr.Row():
169
  question_box = gr.Textbox(
170
  placeholder="Ask a question about your PDF...",
@@ -174,10 +170,10 @@ with gr.Blocks(title="PDF RAG Chatbot") as demo: # ← theme removed fr
174
  submit_btn = gr.Button("Send", variant="primary", scale=1)
175
  clear_btn = gr.Button("πŸ—‘οΈ Clear Chat & Reset")
176
 
177
- # ── Event handlers ─────────────────────────────────────────
178
  process_btn.click(
179
  process_pdf,
180
- inputs=[pdf_upload, groq_key_box],
181
  outputs=[status_box]
182
  )
183
  submit_btn.click(
@@ -195,4 +191,4 @@ with gr.Blocks(title="PDF RAG Chatbot") as demo: # ← theme removed fr
195
  outputs=[chatbot, question_box, status_box]
196
  )
197
 
198
- demo.launch(theme=gr.themes.Soft()) # ← theme moved here
 
14
  qa_chain = None
15
  retrieved_docs = {}
16
 
17
+ # ── Groq key from HF Secret ───────────────────────────────────
18
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
19
+
20
  # ── Embedding model (loaded once) ─────────────────────────────
21
  embeddings = HuggingFaceEmbeddings(
22
  model_name="sentence-transformers/all-MiniLM-L6-v2",
 
31
  for doc in docs
32
  )
33
 
34
+ def build_chain():
35
  llm = ChatGroq(
36
+ api_key=GROQ_API_KEY,
37
  model="llama-3.3-70b-versatile",
38
  temperature=0.2,
39
  max_tokens=1024,
 
66
  "question": question
67
  }
68
 
69
+ return (
70
  RunnableLambda(retrieve_and_format)
71
  | PROMPT
72
  | llm
73
  | StrOutputParser()
74
  )
 
75
 
76
  # ── Core functions ────────────────────────────────────────────
77
+ def process_pdf(pdf_file, progress=gr.Progress()):
78
  global vectorstore, qa_chain
79
 
80
  if pdf_file is None:
81
  return "⚠️ Please upload a PDF file."
82
+ if not GROQ_API_KEY:
83
+ return "❌ GROQ_API_KEY secret is not set in HF Space settings."
84
 
85
  try:
86
  progress(0.1, desc="Loading PDF...")
 
99
  vectorstore = FAISS.from_documents(chunks, embeddings)
100
 
101
  progress(0.9, desc="Setting up RAG chain...")
102
+ qa_chain = build_chain()
103
 
104
  progress(1.0, desc="Done!")
105
  return f"βœ… Ready! Loaded **{len(pages)} pages** β†’ **{len(chunks)} chunks**."
 
110
 
111
  def answer_question(question, history):
112
  if vectorstore is None or qa_chain is None:
113
+ history.append({"role": "user", "content": question})
114
+ history.append({"role": "assistant", "content": "⚠️ Please upload a PDF first."})
115
  return "", history
116
  if not question.strip():
117
  return "", history
 
128
  answer += f"\n\nπŸ“„ *Sources: pages {pages}*"
129
 
130
  except Exception as e:
131
+ answer = f"❌ Error: {str(e)}"
132
 
133
+ history.append({"role": "user", "content": question})
134
+ history.append({"role": "assistant", "content": answer})
135
  return "", history
136
 
137
 
 
142
  retrieved_docs = {}
143
  return [], "", "πŸ—‘οΈ Cleared. Upload a new PDF to start again."
144
 
 
 
145
 
146
+ # ── Gradio UI ─────────────────────────────────────────────────
147
+ with gr.Blocks(title="PDF RAG Chatbot") as demo:
148
+
149
+ gr.Markdown("# πŸ“š PDF RAG Chatbot\nUpload a PDF and ask questions about it.")
150
 
151
  with gr.Row():
152
+
153
+ # ── Left panel ────────────────────────────────────────
154
  with gr.Column(scale=1):
155
+ gr.Markdown("### πŸ“„ Upload Document")
156
+ pdf_upload = gr.File(label="Choose PDF", file_types=[".pdf"])
 
 
 
 
 
 
 
 
 
157
  process_btn = gr.Button("πŸ“₯ Process PDF", variant="primary")
158
  status_box = gr.Markdown("*Upload a PDF to begin.*")
159
 
160
+ # ── Right panel ───────────────────────────────────────
161
  with gr.Column(scale=2):
162
  gr.Markdown("### πŸ’¬ Chat")
163
+ chatbot = gr.Chatbot(height=500, type="messages")
164
  with gr.Row():
165
  question_box = gr.Textbox(
166
  placeholder="Ask a question about your PDF...",
 
170
  submit_btn = gr.Button("Send", variant="primary", scale=1)
171
  clear_btn = gr.Button("πŸ—‘οΈ Clear Chat & Reset")
172
 
173
+ # ── Event handlers ────────────────────────────────────────
174
  process_btn.click(
175
  process_pdf,
176
+ inputs=[pdf_upload],
177
  outputs=[status_box]
178
  )
179
  submit_btn.click(
 
191
  outputs=[chatbot, question_box, status_box]
192
  )
193
 
194
+ demo.launch(theme=gr.themes.Soft())