utkarshgogna1 commited on
Commit
33c2824
1 Parent(s): 1361978

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +2 -8
  2. gradio_app.py +534 -0
  3. requirements.txt +11 -0
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Gradio APP
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.8.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Gradio_APP
3
+ app_file: gradio_app.py
 
 
4
  sdk: gradio
5
  sdk_version: 5.8.0
 
 
6
  ---
 
 
gradio_app.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import gradio as gr
3
+ import torch
4
+ import numpy as np
5
+ import pandas as pd
6
+ from transformers import AutoTokenizer, AutoModel
7
+ import re
8
+ from nltk.tokenize import sent_tokenize
9
+ import fitz # PyMuPDF
10
+ from tqdm import tqdm
11
+ import os
12
+ import uuid
13
+ import requests
14
+ from sentence_transformers import CrossEncoder
15
+ import faiss
16
+ import nltk
17
+ from dotenv import load_dotenv
18
+
19
+ # Load environment variables from .env file
20
+ load_dotenv()
21
+
22
+ # Download NLTK data
23
+ nltk.download('punkt')
24
+
25
+ # Configure logging
26
+ logging.basicConfig(level=logging.INFO)
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Ensure the uploads folder exists
30
+ UPLOAD_FOLDER = 'uploads'
31
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
32
+
33
+ # Load embedding models and tokenizers
34
+ EMBEDDING_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
35
+ embedding_tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME)
36
+ embedding_model = AutoModel.from_pretrained(EMBEDDING_MODEL_NAME)
37
+
38
+ # Load CrossEncoder for reranking
39
+ rerank_model = CrossEncoder("mixedbread-ai/mxbai-rerank-large-v1")
40
+
41
+ # Load Hugging Face API tokens from environment variables
42
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN") # Unified token for all models
43
+
44
+ # Define Hugging Face API URLs
45
+ MISTRAL_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
46
+ PHI_API_URL = "https://api-inference.huggingface.co/models/microsoft/Phi-3.5-mini-instruct"
47
+ QWEN_API_URL = 'https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct'
48
+
49
+ # Initialize global variables to store current DataFrame and embeddings
50
+ current_df = None
51
+ current_embeddings = None
52
+
53
+ # Helper function to check allowed file extensions
54
+ def allowed_file(filename):
55
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() == 'pdf'
56
+
57
+ # PDF Processing Functions
58
+ def open_and_read_pdf(pdf_path):
59
+ doc = fitz.open(pdf_path)
60
+ pages_and_texts = []
61
+ for page_num, page in tqdm(enumerate(doc), total=len(doc), desc="Reading PDF Pages"):
62
+ text = page.get_text()
63
+ pages_and_texts.append({"page_number": page_num + 1, "text": text})
64
+ return pages_and_texts
65
+
66
+ def clean_text(text):
67
+ # Remove numbers surrounded by spaces or newlines
68
+ text = re.sub(r"(\s*\n*\s*\d+\s*\n*\s*)", " ", text)
69
+ # Replace " \n" with a single space
70
+ text = re.sub(r" \n", " ", text)
71
+ # Remove extra spaces
72
+ text = re.sub(r"\s+", " ", text).strip()
73
+ return text
74
+
75
+ def split_into_paragraphs(pages_and_texts):
76
+ paragraph_delimiter = r"(?:\s*\n\s*\n\s*|\s{2,}\n)"
77
+ combined_text = ""
78
+ page_boundaries = []
79
+ for page_data in pages_and_texts:
80
+ start_idx = len(combined_text)
81
+ combined_text += page_data["text"]
82
+ page_boundaries.append((start_idx, len(combined_text), page_data["page_number"]))
83
+ paragraphs = re.split(paragraph_delimiter, combined_text)
84
+ paragraph_data = []
85
+ for paragraph in paragraphs:
86
+ cleaned_paragraph = clean_text(paragraph)
87
+ if not cleaned_paragraph:
88
+ continue
89
+ if len(paragraph.split(" ")) < 20:
90
+ continue
91
+ paragraph_start_idx = combined_text.find(paragraph)
92
+ paragraph_end_idx = paragraph_start_idx + len(paragraph)
93
+ pages_spanned = set()
94
+ for start, end, page_number in page_boundaries:
95
+ if paragraph_start_idx < end and paragraph_end_idx > start:
96
+ pages_spanned.add(page_number)
97
+ paragraph_data.append({
98
+ "page_number": sorted(pages_spanned),
99
+ "char_count": len(cleaned_paragraph),
100
+ "word_count": len(cleaned_paragraph.split(" ")),
101
+ "sentence_count": len(sent_tokenize(cleaned_paragraph)),
102
+ "text": cleaned_paragraph
103
+ })
104
+ return pd.DataFrame(paragraph_data)
105
+
106
+ def split_into_chunks(pages_and_texts, chunk_size):
107
+ combined_text = ""
108
+ page_boundaries = []
109
+ for page_data in pages_and_texts:
110
+ start_idx = len(combined_text)
111
+ combined_text += page_data["text"]
112
+ page_boundaries.append((start_idx, len(combined_text), page_data["page_number"]))
113
+ chunks = [combined_text[i:i + chunk_size] for i in range(0, len(combined_text), chunk_size)]
114
+ chunk_data = []
115
+ for chunk in chunks:
116
+ cleaned_chunk = clean_text(chunk)
117
+ if not cleaned_chunk:
118
+ continue
119
+ chunk_start_idx = combined_text.find(chunk)
120
+ chunk_end_idx = chunk_start_idx + len(chunk)
121
+ pages_spanned = set()
122
+ for start, end, page_number in page_boundaries:
123
+ if chunk_start_idx < end and chunk_end_idx > start:
124
+ pages_spanned.add(page_number)
125
+ chunk_data.append({
126
+ "page_number": sorted(pages_spanned),
127
+ "char_count": len(cleaned_chunk),
128
+ "word_count": len(cleaned_chunk.split(" ")),
129
+ "sentence_count": len(sent_tokenize(cleaned_chunk)),
130
+ "text": cleaned_chunk
131
+ })
132
+ return pd.DataFrame(chunk_data)
133
+
134
+ def split_into_sentences(pages_and_texts, num_sentences=10):
135
+ combined_text = ""
136
+ page_boundaries = []
137
+ for page_data in pages_and_texts:
138
+ start_idx = len(combined_text)
139
+ combined_text += page_data["text"]
140
+ page_boundaries.append((start_idx, len(combined_text), page_data["page_number"]))
141
+ sentence_boundary_pattern = r'(?<=[.!?])(?=\s|\n)'
142
+ sentences = re.split(sentence_boundary_pattern, combined_text)
143
+ chunks = ["".join(sentences[i:i + num_sentences]) for i in range(0, len(sentences), num_sentences)]
144
+ chunk_data = []
145
+ for chunk in chunks:
146
+ cleaned_chunk = clean_text(chunk)
147
+ if not cleaned_chunk:
148
+ continue
149
+ chunk_start_idx = combined_text.find(chunk)
150
+ chunk_end_idx = chunk_start_idx + len(chunk)
151
+ pages_spanned = set()
152
+ for start, end, page_number in page_boundaries:
153
+ if chunk_start_idx < end and chunk_end_idx > start:
154
+ pages_spanned.add(page_number)
155
+ chunk_data.append({
156
+ "page_number": sorted(pages_spanned),
157
+ "char_count": len(cleaned_chunk),
158
+ "word_count": len(cleaned_chunk.split(" ")),
159
+ "sentence_count": len(sent_tokenize(cleaned_chunk)),
160
+ "text": cleaned_chunk
161
+ })
162
+ return pd.DataFrame(chunk_data)
163
+
164
+ def split_into_pages(pages_and_texts):
165
+ pages_data = []
166
+ for page_data in pages_and_texts:
167
+ cleaned_page = clean_text(page_data["text"])
168
+ pages_data.append({
169
+ "page_number": page_data["page_number"],
170
+ "char_count": len(cleaned_page),
171
+ "word_count": len(cleaned_page.split(" ")),
172
+ "sentence_count": len(sent_tokenize(cleaned_page)),
173
+ "text": cleaned_page
174
+ })
175
+ return pd.DataFrame(pages_data)
176
+
177
+ def create_df_from_pdf(pdf_path, method="sentence", fixed_size=512, num_sentences=10):
178
+ pages_and_texts = open_and_read_pdf(pdf_path)
179
+ if method == "paragraph":
180
+ df = split_into_paragraphs(pages_and_texts)
181
+ elif method == "fixed":
182
+ df = split_into_chunks(pages_and_texts, fixed_size)
183
+ elif method == "sentence":
184
+ df = split_into_sentences(pages_and_texts, num_sentences)
185
+ elif method == "page":
186
+ df = split_into_pages(pages_and_texts)
187
+ else:
188
+ raise ValueError("Unsupported splitting method.")
189
+ return df
190
+
191
+ def get_text_embedding(model, tokenizer, text):
192
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
193
+ with torch.no_grad():
194
+ outputs = model(**inputs)
195
+ return outputs.last_hidden_state.mean(dim=1).numpy()[0]
196
+
197
+ def retrieve_top_k_similar(query, embeddings, embedding_model, embedding_tokenizer, top_k=5, method="cosine"):
198
+ query_embedding = get_text_embedding(embedding_model, embedding_tokenizer, query)
199
+ if method == "cosine":
200
+ query_tensor = torch.tensor(query_embedding)
201
+ similarity = torch.nn.functional.cosine_similarity(embeddings, query_tensor, dim=-1)
202
+ similarity_top_k = torch.topk(similarity, k=top_k)
203
+ return similarity_top_k.values.numpy(), similarity_top_k.indices.numpy()
204
+ elif method == "faiss":
205
+ d = embeddings.shape[1]
206
+ index = faiss.IndexFlatL2(d)
207
+ index.add(embeddings.numpy())
208
+ query_embedding_reshaped = query_embedding.reshape(1, -1).astype('float32')
209
+ D, I = index.search(query_embedding_reshaped, k=top_k)
210
+ return D.reshape(-1), I.reshape(-1)
211
+ else:
212
+ raise ValueError("Unsupported similarity method.")
213
+
214
+ # Templates
215
+ template1 = """Instruct:You are my tutor. Your task is to give me answers and explanations to my questions about the topic based on the context I provide. Think carefully about the answer by extracting relevant passages from the context before answering my question. Don’t return your thoughts, only the answer. Make sure your responses are detailed and as explanatory as possible. Optionally quote from the context, citing the page. Do not use your previous knowledge to answer the question.
216
+
217
+ Following are the examples:
218
+
219
+
220
+ QA Example 1
221
+ Context:
222
+ Page 1: "Water scarcity affects over 2 billion people worldwide due to climate change and poor resource management."
223
+ Page 2: "Desalination is a key technological solution but comes with challenges such as high energy costs and environmental concerns."
224
+ Query:
225
+ What are the main solutions to water scarcity?
226
+ Answer:
227
+ Desalination is a significant solution, as noted on Page 2, but it has challenges like high energy costs and environmental impact. Other approaches, such as improved resource management (Page 1), are also critical.
228
+
229
+ QA Example 2
230
+ Context:
231
+ Page 1: "Photosynthesis is the process by which plants convert sunlight into energy, primarily occurring in the chloroplasts."
232
+ Page 2: "The process consists of light-dependent reactions and the Calvin cycle, where glucose is synthesized."
233
+ Query:
234
+ What is glucose?
235
+ Answer:
236
+ Unfortunately, the context provided does not contain the answer to your inquiry.
237
+
238
+ Context Pages:
239
+ Page {page1}: {context1}
240
+ Page {page2}: {context2}
241
+ Page {page3}: {context3}
242
+
243
+ Query:
244
+ {query}
245
+
246
+ Please ensure that your answer is complete, ends at the end of a sentence, and does not trail off."""
247
+
248
+ template2 = """Instruct:You are a knowledgeable tutor. Answer the query below only using the given context. Pick the context you find most valuable. You are allowed to use more than one context. If you are not sure about the answer say that you don’t know the answer.
249
+
250
+ Context Pages:
251
+ Page {page1} : {context1}
252
+ Page {page2}: {context2}
253
+ Page {page3}: {context3}
254
+
255
+ Query:
256
+ {query}
257
+
258
+ Guidelines for Response:
259
+ Provide a detailed, explanatory answer, but do not make it too long.
260
+ Optionally quote from the context if helpful, citing the page.
261
+ Specify which pages support your response.
262
+ Only use the context to answer and do not answer the question if the answer is not in the context.
263
+ If the context does not contain the answer, say that you cannot deduce the answer from the context.
264
+
265
+ Please ensure that your answer is complete, ends at the end of a sentence, and does not trail off."""
266
+
267
+ templates = [template1, template2]
268
+
269
+ def get_items_for_prompt(query, df, indices):
270
+ required_columns = ["page_number", "text"]
271
+ for col in required_columns:
272
+ if col not in df.columns:
273
+ raise KeyError(f"Required column '{col}' not found in DataFrame.")
274
+
275
+ if len(indices) < 3:
276
+ raise ValueError("Not enough indices to generate prompts. Ensure top_k >= 3.")
277
+
278
+ dict1 = {
279
+ "query": query,
280
+ "page1": df["page_number"].iloc[indices[0]],
281
+ "page2": df["page_number"].iloc[indices[1]],
282
+ "page3": df["page_number"].iloc[indices[2]],
283
+ "context1": df["text"].iloc[indices[0]],
284
+ "context2": df["text"].iloc[indices[1]],
285
+ "context3": df["text"].iloc[indices[2]]
286
+ }
287
+ return dict1
288
+
289
+ def generate_prompts(query, indices, df, templates):
290
+ dict1 = get_items_for_prompt(query, df, indices)
291
+ prompts = [
292
+ template.format(
293
+ page1=dict1["page1"],
294
+ page2=dict1["page2"],
295
+ page3=dict1["page3"],
296
+ context1=dict1["context1"],
297
+ context2=dict1["context2"],
298
+ context3=dict1["context3"],
299
+ query=dict1["query"]
300
+ )
301
+ for template in templates
302
+ ]
303
+ return prompts
304
+
305
+ def query_hf_mistral(prompt, api_url=MISTRAL_API_URL):
306
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
307
+ formatted_prompt = "<s>[INST]" + prompt + " [/INST] Model answer</s>"
308
+ payload = {
309
+ "inputs": formatted_prompt,
310
+ "parameters": {
311
+ "max_new_tokens": 500,
312
+ "temperature": 0.2,
313
+ "return_full_text": False
314
+ }
315
+ }
316
+ response = requests.post(api_url, headers=headers, json=payload)
317
+
318
+ if response.status_code != 200:
319
+ raise Exception(f"Mistral API request failed with status code {response.status_code}: {response.text}")
320
+
321
+ response_data = response.json()
322
+ if isinstance(response_data, list):
323
+ return response_data[0].get("generated_text", "No response available.")
324
+ else:
325
+ return response_data.get("generated_text", "No response available.")
326
+
327
+ def query_hf_phi(prompt, api_url=PHI_API_URL):
328
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
329
+ formatted_prompt = prompt + "\n\nOutput:"
330
+ payload = {
331
+ "inputs": formatted_prompt,
332
+ "parameters": {
333
+ "max_new_tokens": 500,
334
+ "temperature": 0.2,
335
+ "return_full_text": False
336
+ }
337
+ }
338
+ response = requests.post(api_url, headers=headers, json=payload)
339
+
340
+ if response.status_code != 200:
341
+ raise Exception(f"Phi API request failed with status code {response.status_code}: {response.text}")
342
+
343
+ response_data = response.json()
344
+ if isinstance(response_data, list):
345
+ return response_data[0].get("generated_text", "No response available.")
346
+ else:
347
+ return response_data.get("generated_text", "No response available.")
348
+
349
+ def query_hf_qwen(prompt, api_url=QWEN_API_URL):
350
+ headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
351
+ formatted_prompt = "<|im_start|>system\n" + prompt + "<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n"
352
+ payload = {
353
+ "inputs": formatted_prompt,
354
+ "parameters": {
355
+ "max_new_tokens": 500,
356
+ "temperature": 0.2,
357
+ "return_full_text": False
358
+ }
359
+ }
360
+ response = requests.post(api_url, headers=headers, json=payload)
361
+
362
+ if response.status_code != 200:
363
+ raise Exception(f"Qwen API request failed with status code {response.status_code}: {response.text}")
364
+
365
+ response_data = response.json()
366
+ if isinstance(response_data, list):
367
+ return response_data[0].get("generated_text", "No response available.")
368
+ else:
369
+ return response_data.get("generated_text", "No response available.")
370
+
371
+ def evaluate_prompts(prompts, model_functions):
372
+ results = []
373
+ for i, prompt in enumerate(prompts):
374
+ for func in model_functions:
375
+ try:
376
+ response = func(prompt)
377
+ except Exception as e:
378
+ response = f"Error: {str(e)}"
379
+ results.append({
380
+ "prompt_number": i + 1,
381
+ "model_function": func.__name__,
382
+ "response": response
383
+ })
384
+ return results
385
+
386
+ def ensure_complete_sentence(text):
387
+ if re.search(r'[.!?]$', text.strip()):
388
+ return text
389
+ else:
390
+ return text + "."
391
+
392
+ # Gradio UI Functions
393
+ def handle_file_upload(file):
394
+ global current_df, current_embeddings
395
+
396
+ # Check if no file was provided
397
+ if not file:
398
+ return "No file selected."
399
+
400
+ # If the file is bytes (e.g. from an in-memory upload)
401
+ if isinstance(file, bytes):
402
+ logger.info("File received as raw bytes, no name provided.")
403
+ # Generate a filename for the uploaded file
404
+ filename = f"{uuid.uuid4()}_uploaded_file.pdf"
405
+ file_path = os.path.join(UPLOAD_FOLDER, filename)
406
+
407
+ try:
408
+ with open(file_path, "wb") as f_out:
409
+ f_out.write(file)
410
+ logger.info(f"File saved to {file_path}")
411
+ except Exception as e:
412
+ logger.error(f"Error saving file: {e}")
413
+ return f"Error saving file: {str(e)}"
414
+ else:
415
+ # If it's not bytes, then it might be a dict-like object.
416
+ # Attempt to treat it as a dictionary with 'name' and 'data' keys
417
+ if not isinstance(file, dict) or "name" not in file or "data" not in file:
418
+ return "Invalid file structure. Expected a dict with 'name' and 'data'."
419
+
420
+ logger.info(f"Received file info: {file}")
421
+ base_name = os.path.basename(file["name"])
422
+ filename = f"{uuid.uuid4()}_{base_name}"
423
+ file_path = os.path.join(UPLOAD_FOLDER, filename)
424
+
425
+ try:
426
+ with open(file_path, "wb") as f_out:
427
+ f_out.write(file["data"])
428
+ logger.info(f"File saved to {file_path}")
429
+ except Exception as e:
430
+ logger.error(f"Error saving file: {e}")
431
+ return f"Error saving file: {str(e)}"
432
+
433
+ # Process the saved file to create embeddings
434
+ try:
435
+ # Create a DataFrame from the PDF
436
+ df = create_df_from_pdf(file_path, method="sentence")
437
+ logger.info(f"Number of chunks created from PDF: {len(df)}")
438
+
439
+ # Generate embeddings for each text chunk in the DataFrame
440
+ embeddings = []
441
+ for _, row in tqdm(df.iterrows(), total=df.shape[0], desc="Generating embeddings"):
442
+ text_chunk = row.get("text", "")
443
+ emb = get_text_embedding(embedding_model, embedding_tokenizer, text_chunk)
444
+ embeddings.append(emb)
445
+ embeddings = np.array(embeddings, dtype='float32')
446
+
447
+ # Store results globally
448
+ current_df = df.copy()
449
+ current_df["embedding"] = list(embeddings)
450
+ current_embeddings = torch.tensor(current_df["embedding"].tolist())
451
+
452
+ return "File successfully uploaded and processed."
453
+ except Exception as e:
454
+ logger.error(f"Error during file processing: {e}")
455
+ return f"Error: {str(e)}"
456
+
457
+ def handle_query_input(query_text, top_k=3, method="faiss"):
458
+ global current_df, current_embeddings
459
+ if current_df is None or current_embeddings is None:
460
+ return "No PDF uploaded. Please upload a PDF first."
461
+ if not query_text:
462
+ return "Query is required."
463
+
464
+ try:
465
+ similarity_scores, indices = retrieve_top_k_similar(
466
+ query_text,
467
+ current_embeddings,
468
+ embedding_model,
469
+ embedding_tokenizer,
470
+ top_k=top_k,
471
+ method=method
472
+ )
473
+
474
+ if len(indices) < 3:
475
+ raise ValueError(f"Requested top_k=3 but only {len(indices)} chunks available.")
476
+
477
+ # Rerank using CrossEncoder
478
+ docs = current_df["text"].iloc[indices].tolist()
479
+ reranked = rerank_model.predict([(query_text, doc) for doc in docs])
480
+ reranked_indices = np.argsort(-reranked)[:top_k] # Descending order
481
+ final_indices = indices[reranked_indices]
482
+
483
+ # Generate prompts
484
+ prompts = generate_prompts(query_text, final_indices, current_df, templates)
485
+
486
+ model_functions = [query_hf_mistral, query_hf_phi, query_hf_qwen]
487
+ responses = evaluate_prompts(prompts, model_functions)
488
+
489
+ # Beautify and structure the result output
490
+ formatted_response = "<h2 style='color: #333; border-bottom: 1px solid #ccc;'>Query Results</h2>"
491
+ for res in responses:
492
+ prompt_num = res["prompt_number"]
493
+ model_func = res["model_function"].replace("_", " ").title()
494
+ response_text = ensure_complete_sentence(res["response"])
495
+ formatted_response += f"""
496
+ <div style='background: #f9f9f9; border-radius: 5px; padding: 10px; margin: 10px 0;'>
497
+ <h3 style='margin-bottom:5px;'>Prompt {prompt_num} - {model_func}</h3>
498
+ <p style='margin:0;'>{response_text}</p>
499
+ </div>
500
+ """
501
+
502
+ return formatted_response
503
+ except KeyError as ke:
504
+ logger.error(f"KeyError: {ke}")
505
+ return str(ke)
506
+ except ValueError as ve:
507
+ logger.error(f"ValueError: {ve}")
508
+ return str(ve)
509
+ except Exception as e:
510
+ logger.error(f"An unexpected error occurred: {e}")
511
+ return "An internal error occurred."
512
+
513
+
514
+ # Build Gradio Interface
515
+ with gr.Blocks() as demo:
516
+ gr.Markdown("# PDF Query System")
517
+ gr.Markdown("Upload a PDF and then ask questions about it.")
518
+
519
+ with gr.Row():
520
+ with gr.Column():
521
+ file_input = gr.File(label="Upload PDF", file_types=[".pdf"], type="binary")
522
+ upload_button = gr.Button("Process PDF")
523
+ upload_status = gr.Textbox(label="Upload Status", interactive=False)
524
+
525
+ with gr.Column():
526
+ query_input = gr.Textbox(label="Enter your query:")
527
+ submit_query_button = gr.Button("Submit Query")
528
+ results_output = gr.HTML(label="Results", elem_id="results")
529
+
530
+ upload_button.click(fn=handle_file_upload, inputs=file_input, outputs=upload_status)
531
+ submit_query_button.click(fn=handle_query_input, inputs=[query_input], outputs=results_output, show_progress=True)
532
+
533
+ # Run Gradio app
534
+ demo.launch(server_name="0.0.0.0", server_port=5001)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ nltk
3
+ fitz
4
+ requests
5
+ dotenv
6
+ faiss
7
+ sentence_transformers
8
+ tqdm
9
+ pandas
10
+ numpy
11
+ torch