yjernite HF Staff commited on
Commit
3de3756
·
verified ·
1 Parent(s): e672262

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +403 -0
app.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html # Added for escaping HTML
2
+ import json
3
+ import logging # Added for status check logging
4
+ import os # Added for environment variables
5
+
6
+ import gradio as gr
7
+ import numpy as np
8
+ from sentence_transformers import SentenceTransformer
9
+
10
+ # Added HfApi for endpoint check
11
+ from huggingface_hub import InferenceClient
12
+ from dotenv import load_dotenv # Added for .env loading
13
+
14
+ import utils.interface_utils as interface_utils
15
+ import utils.llm_utils as llm_utils
16
+
17
+ # Load environment variables from .env file
18
+ load_dotenv()
19
+
20
+ # REMOVED Endpoint name constant (will be in llm_utils)
21
+ # LLM_ENDPOINT_NAME = "phi-4-max"
22
+
23
+ # REMOVED Endpoint Status Check Function
24
+
25
+ # --- Load Data and Models ---
26
+ # These should be loaded once when the app starts.
27
+ print("Loading data and models...")
28
+
29
+ # Load data from files
30
+ processed_docs = json.load(
31
+ open("docs_passages_storage/processed_docs.json", encoding="utf-8")
32
+ )
33
+ passages = json.load(open("docs_passages_storage/passages.json", encoding="utf-8"))
34
+ doc_embeds = np.load("docs_passages_storage/passage_embeddings.npy")
35
+
36
+ # Load the embedding model - Force CPU
37
+ print("Loading embedding model on CPU...")
38
+ model_name = "Snowflake/snowflake-arctic-embed-l-v2.0"
39
+ embed_model = SentenceTransformer(model_name, device="cpu")
40
+ print("Embedding model loaded.")
41
+
42
+ # Initialize HF Client globally using env vars
43
+ hf_api_token = os.getenv("HF_TOKEN")
44
+ if not hf_api_token:
45
+ print(
46
+ "Warning: HF_TOKEN environment variable not set. Inference client might fail."
47
+ )
48
+ hf_client = InferenceClient(token=hf_api_token)
49
+
50
+ print("Data and models loaded.")
51
+
52
+
53
+ # --- Main Gradio Function ---
54
+ def get_results(query: str, progress=gr.Progress(track_tqdm=True)) -> list:
55
+ """Processes query, retrieves passages, processes each, formats output, tracks progress."""
56
+ # Define placeholders for 10 outputs (9 results + 1 summary)
57
+ if not query:
58
+ # Return default values for all 10 output slots
59
+ return ["-"] * 9 + ["### Summary\n-"]
60
+
61
+ # --- Check Endpoint Status FIRST ---
62
+ # Use token loaded previously for the client
63
+ endpoint_status = llm_utils.check_endpoint_status(
64
+ token=hf_api_token
65
+ ) # Call function from llm_utils
66
+ if endpoint_status["status"] == "error":
67
+ error_message = endpoint_status["ui_message"]
68
+ logging.error(f"Endpoint status error: {error_message}")
69
+ progress(1, desc="Endpoint Error")
70
+ # Display error in first result slot and summary slot
71
+ return [
72
+ "### Endpoint Error",
73
+ f"<p style='color: red;'>{html.escape(error_message)}</p>",
74
+ "_",
75
+ "-",
76
+ "-",
77
+ "-",
78
+ "-",
79
+ "-",
80
+ "-",
81
+ "### Summary\n_Endpoint not ready._",
82
+ ]
83
+
84
+ print(f"Processing query: {query}")
85
+ try:
86
+ progress(0, desc="Retrieving relevant documents...")
87
+ # Step 1: Retrieve top excerpts
88
+ retrieved_excerpts = llm_utils.retrieve_passages(
89
+ query=query,
90
+ doc_embeds=doc_embeds,
91
+ passages=passages,
92
+ processed_docs=processed_docs,
93
+ embed_model=embed_model,
94
+ max_docs=3,
95
+ )
96
+ progress(0.1, desc="Retrieved documents.") # Update progress after retrieval
97
+
98
+ if not retrieved_excerpts:
99
+ print("No passages retrieved.")
100
+ progress(1, desc="No relevant passages found.") # Update progress
101
+ return [
102
+ "### Document:\n-",
103
+ "<p><i>No relevant passages found.</i></p>",
104
+ "_",
105
+ ] * 3 + [
106
+ "### Summary\n_No passages found._"
107
+ ] # Add summary placeholder
108
+
109
+ # Step 2: Process each excerpt individually
110
+ processed_data = []
111
+ num_excerpts = len(retrieved_excerpts)
112
+ for i, excerpt in enumerate(retrieved_excerpts):
113
+ # Update progress description before processing each excerpt
114
+ progress(
115
+ 0.1 + (i * 0.8 / num_excerpts),
116
+ desc=f"Processing excerpt {i + 1}/{num_excerpts}...",
117
+ )
118
+ # Pass the globally initialized hf_client
119
+ processed_result = llm_utils.process_single_excerpt(
120
+ i, excerpt, query, hf_client
121
+ )
122
+ processed_data.append({"excerpt": excerpt, **processed_result})
123
+
124
+ progress(
125
+ 0.9, desc="Formatting results..."
126
+ ) # Mark processing complete, start formatting
127
+
128
+ # Step 3: Format results for Gradio output components
129
+ final_outputs = [
130
+ "### Document:\n-",
131
+ "<p><i>No result</i></p>",
132
+ "_No passage text_",
133
+ ] * 3 + [
134
+ "### Summary\n_Generating..._"
135
+ ] # Reset outputs + summary placeholder
136
+
137
+ global_quote_counter = 0 # Initialize global counter
138
+ snippets_for_llm_summary = [] # List to store formatted snippets for the LLM
139
+ all_spans_with_hover_info = (
140
+ {}
141
+ ) # Dict to store spans per passage index: {0: [(s, e, info), ...], 1: ...}
142
+
143
+ for i in range(min(len(processed_data), 3)):
144
+ result = processed_data[i]
145
+ excerpt = result["excerpt"]
146
+ citations = result["citations"]
147
+ parse_successful = result["parse_successful"]
148
+ raw_error_response = result["raw_error_response"]
149
+ passage_text = excerpt.get("passage_text", "")
150
+ doc_url = excerpt.get("document_url", "#")
151
+
152
+ # 1. Format Document URL Markdown
153
+ doc_url_md = (
154
+ f"### Document {i+1}:\n[{html.escape(doc_url)}]({html.escape(doc_url)})"
155
+ )
156
+
157
+ # 2. Format Quotes HTML
158
+ quotes_html_parts = []
159
+ if parse_successful and citations:
160
+ quotes_html_parts.append(
161
+ "<p><strong>Relevant Quotes:</strong> (hover for details)</p>"
162
+ )
163
+ quotes_html_parts.append(
164
+ "<ul style='list-style-type: none; margin-left: 10px; padding-left: 0;'>" # Use none for list type
165
+ )
166
+ for cit in citations:
167
+ global_quote_counter += 1 # Increment counter
168
+ quote_id = global_quote_counter
169
+ # Store id in citation dict (optional, but might be useful later)
170
+ cit["global_id"] = quote_id
171
+
172
+ quote = cit.get("quote", "N/A")
173
+ context = cit.get("context", "N/A")
174
+ relevance = cit.get("relevance", "N/A")
175
+ hover_text = f"Context: {html.escape(context, quote=True)}\nRelevance: {html.escape(relevance, quote=True)}"
176
+ # Update HTML to include the ID
177
+ quotes_html_parts.append(
178
+ f"<li style='margin-bottom: 5px;' title='{hover_text}'>[{quote_id}]: <i>{html.escape(quote)}</i></li>"
179
+ )
180
+
181
+ # Prepare hover text for the highlighted span in the passage
182
+ span_hover_text = f"Quote ID: {quote_id}\nContext: {context}\nRelevance: {relevance}"
183
+ # Get spans for this specific citation
184
+ citation_spans = cit.get("char_spans", [])
185
+ # Associate hover text with these spans for the current passage (index i)
186
+ if i not in all_spans_with_hover_info:
187
+ all_spans_with_hover_info[i] = []
188
+ for start, end in citation_spans:
189
+ all_spans_with_hover_info[i].append(
190
+ (start, end, span_hover_text)
191
+ )
192
+
193
+ # Add formatted snippet to list if parsing was successful
194
+ if (
195
+ parse_successful
196
+ ): # Ensure we only add successfully parsed citations
197
+ snippets_for_llm_summary.append(
198
+ {
199
+ "id": quote_id,
200
+ "context": context,
201
+ "relevance": relevance,
202
+ "quote": quote,
203
+ "document_url": doc_url, # Added document URL here
204
+ }
205
+ )
206
+ quotes_html_parts.append("</ul>")
207
+ elif not parse_successful and raw_error_response:
208
+ quotes_html_parts.append(
209
+ "<p style='color: red;'><strong>Error parsing citations:</strong></p>"
210
+ )
211
+ # Limit error display length
212
+ error_display = html.escape(raw_error_response[:1000]) + (
213
+ "..." if len(raw_error_response) > 1000 else ""
214
+ )
215
+ quotes_html_parts.append(
216
+ f"<pre style='background-color: #f8d7da; color: #721c24; padding: 5px; border-radius: 4px; white-space: pre-wrap; word-wrap: break-word;'><code>{error_display}</code></pre>"
217
+ )
218
+ else:
219
+ quotes_html_parts.append("<p><i>No specific quotes identified.</i></p>")
220
+ quotes_html = "".join(quotes_html_parts)
221
+ if not quotes_html:
222
+ quotes_html = "<p><i>No quotes processed.</i></p>"
223
+
224
+ # 3. Format Passage Markdown using the collected spans with hover info
225
+ spans_for_this_passage = all_spans_with_hover_info.get(
226
+ i, []
227
+ ) # Get spans for index i
228
+ passage_md = interface_utils.generate_highlighted_markdown(
229
+ passage_text, spans_for_this_passage
230
+ )
231
+ if not passage_md:
232
+ passage_md = "_Passage text unavailable._"
233
+
234
+ # Update the final_outputs list
235
+ final_outputs[i * 3 + 0] = doc_url_md
236
+ final_outputs[i * 3 + 1] = quotes_html
237
+ final_outputs[i * 3 + 2] = passage_md
238
+
239
+ # Step 4: Generate LLM summary
240
+ progress(0.95, desc="Generating summary...") # New progress step
241
+ summary_text = "### Summary\n_Error generating summary._" # Default error text
242
+ if snippets_for_llm_summary:
243
+ # Create a lookup for quote details by ID
244
+ snippet_lookup = {s["id"]: s for s in snippets_for_llm_summary}
245
+
246
+ # Pass the globally initialized hf_client
247
+ summary_result = llm_utils.generate_summary_answer(
248
+ snippets=snippets_for_llm_summary, query=query, hf_client=hf_client
249
+ )
250
+ if summary_result["parse_successful"]:
251
+ summary_items = []
252
+ for sentence_data in summary_result["answer_sentences"]:
253
+ sentence = sentence_data.get("sentence", "")
254
+ citation_ids = sentence_data.get("citations", [])
255
+
256
+ # Generate HTML links for citations
257
+ citation_links = []
258
+ for c_id in citation_ids:
259
+ # Look up snippet details
260
+ snippet_info = snippet_lookup.get(c_id)
261
+ if snippet_info:
262
+ url = snippet_info.get("document_url", "#")
263
+ quote_text = snippet_info.get("quote", "")
264
+ escaped_quote = html.escape(quote_text, quote=True)
265
+ link = f"<a href='{url}' title='{escaped_quote}' target='_blank'>[{c_id}]</a>"
266
+ citation_links.append(link)
267
+ else:
268
+ citation_links.append(
269
+ f"[{c_id}]"
270
+ ) # Fallback if ID not found
271
+
272
+ # Format citation string like [link1, link2]
273
+ citation_str = (
274
+ f" [{', '.join(citation_links)}]" if citation_links else ""
275
+ )
276
+ if sentence:
277
+ # Append sentence and linked citations
278
+ summary_items.append(f"{html.escape(sentence)}{citation_str}")
279
+ if summary_items:
280
+ summary_text = "### Generated Answer\n" + " ".join(summary_items)
281
+ else:
282
+ summary_text = (
283
+ "### Generated Answer\n_LLM did not generate any sentences._"
284
+ )
285
+ else:
286
+ # Display parsing error from summary LLM
287
+ summary_text = (
288
+ "### Summary Generation Error\n"
289
+ + f"<p style='color: red;'>Could not generate summary:</p><pre style='background-color: #f8d7da; color: #721c24; padding: 5px; border-radius: 4px; white-space: pre-wrap; word-wrap: break-word;'><code>{html.escape(summary_result['raw_error_response'])}</code></pre>"
290
+ )
291
+ else:
292
+ summary_text = "### Summary\n_No valid quotes found to generate summary._"
293
+
294
+ final_outputs[9] = summary_text # Add summary to the 10th slot
295
+
296
+ progress(1, desc="Done!") # Final progress update
297
+ return final_outputs
298
+
299
+ except Exception as e:
300
+ print(f"Error in get_results: {e}")
301
+ # Display error in the first result slot, update summary slot
302
+ error_outputs = (
303
+ [
304
+ "### Error Processing Query",
305
+ f"<p style='color: red;'>An unexpected error occurred: {html.escape(str(e))}</p>",
306
+ "_Error details above._",
307
+ ]
308
+ + ["-"] * 6
309
+ + ["### Summary\n_Error occurred._"]
310
+ ) # Add summary placeholder for error
311
+ progress(1, desc="Error!")
312
+ return error_outputs
313
+
314
+
315
+ # --- Gradio Interface ---
316
+
317
+ # Define custom CSS for scrollable accordion content
318
+ custom_css = """
319
+ .scrollable-passage-content {
320
+ max-height: 25vh; /* Or a fixed height like 200px */
321
+ overflow-y: auto !important; /* Add !important to override potential conflicts */
322
+ display: block; /* Ensure it behaves like a block element */
323
+ padding: 10px; /* Add some padding */
324
+ background-color: #f9f9f9; /* Match previous background */
325
+ border: 1px solid #ddd; /* Match previous border */
326
+ border-radius: 5px; /* Match previous radius */
327
+ white-space: pre-wrap; /* Preserve whitespace */
328
+ word-wrap: break-word; /* Wrap long words */
329
+ }
330
+ """
331
+
332
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft(), title="🤗 Policy Docs QA") as demo:
333
+ gr.Markdown("# 🤗 Policy Docs QA")
334
+ gr.Markdown(
335
+ "Ask a question about the loaded policy documents to retrieve relevant passages and quotes."
336
+ ) # Added description
337
+
338
+ with gr.Row():
339
+ # Column 1: Input (scale=1)
340
+ with gr.Column(scale=1):
341
+ question_input = gr.Textbox(
342
+ label="Question",
343
+ placeholder="Enter your question...",
344
+ lines=5,
345
+ )
346
+ # Add example questions
347
+ example_questions = [
348
+ "What role does replicable evaluation play in AI regulation?",
349
+ "How does dataset transparency help address risks of accidents and abuse of AI systems?",
350
+ ]
351
+ gr.Examples(
352
+ examples=example_questions,
353
+ inputs=question_input,
354
+ label="Example Questions", # Optional label
355
+ )
356
+ submit_button = gr.Button("Get Answer")
357
+
358
+ # Column 2: Results (scale=3)
359
+ with gr.Column(scale=3):
360
+ gr.Markdown("## Retrieved Passages") # Changed heading
361
+
362
+ result_outputs = [] # Rename list for clarity
363
+ for i in range(3): # Create 3 result sections
364
+ with gr.Group():
365
+ gr.Markdown(f"**Result {i+1}**")
366
+ doc_url_md = gr.Markdown(
367
+ value="### Document:\n-", label=f"Document URL {i+1}"
368
+ )
369
+ quotes_html = gr.HTML(
370
+ value="<p><i>Quotes will appear here...</i></p>",
371
+ label=f"Quotes {i+1}",
372
+ )
373
+ with gr.Accordion(f"Full Passage Context {i+1}", open=False):
374
+ passage_md = gr.Markdown(
375
+ value="_Passage text will appear here..._",
376
+ label=f"Passage {i+1}",
377
+ elem_classes="scrollable-passage-content", # Assign the class
378
+ )
379
+ result_outputs.extend([doc_url_md, quotes_html, passage_md])
380
+
381
+ # Column 3: Summary (scale=2)
382
+ with gr.Column(scale=2):
383
+ gr.Markdown("## Summary")
384
+ gr.Markdown("***⚠️ Warning:** The text below is generated by an LLM and might not accurately reflect the policy documents. Citation links are determined by the same LLM and provided for conveninece only. For reliable information, go directly to the Retrieved Passages left.*")
385
+ summary_output = gr.Markdown(
386
+ value="_Summary will appear here..._", label="Summary"
387
+ )
388
+
389
+ # Combine all output components for the click function
390
+ all_outputs = result_outputs + [summary_output]
391
+ assert (
392
+ len(all_outputs) == 10
393
+ ), "Incorrect number of total output components created."
394
+
395
+ submit_button.click(
396
+ fn=get_results,
397
+ inputs=question_input,
398
+ outputs=all_outputs, # Pass the list of 10 components
399
+ )
400
+
401
+ # --- Launch App ---
402
+ if __name__ == "__main__":
403
+ demo.launch() # share=True for public link