Spaces:
Sleeping
Sleeping
import logging | |
import gradio as gr | |
import torch | |
import numpy as np | |
import pandas as pd | |
from transformers import AutoTokenizer, AutoModel | |
import re | |
from nltk.tokenize import sent_tokenize | |
import fitz # PyMuPDF | |
from tqdm import tqdm | |
import os | |
import uuid | |
import requests | |
from sentence_transformers import CrossEncoder | |
import faiss | |
import nltk | |
# Download NLTK data | |
nltk.download('punkt') | |
nltk.download('punkt_tab') | |
# Configure logging | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
# Ensure the uploads folder exists | |
UPLOAD_FOLDER = 'uploads' | |
os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
# Load embedding models and tokenizers | |
EMBEDDING_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" | |
embedding_tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME) | |
embedding_model = AutoModel.from_pretrained(EMBEDDING_MODEL_NAME) | |
# Load CrossEncoder for reranking | |
rerank_model = CrossEncoder("mixedbread-ai/mxbai-rerank-large-v1") | |
# Load Hugging Face API tokens from environment variables | |
HF_API_TOKEN = os.environ["HF_API_TOKEN"] # Unified token for all models | |
print(os.environ) | |
print(HF_API_TOKEN) | |
# Define Hugging Face API URLs | |
MISTRAL_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3" | |
PHI_API_URL = "https://api-inference.huggingface.co/models/microsoft/Phi-3.5-mini-instruct" | |
QWEN_API_URL = 'https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct' | |
# Initialize global variables to store current DataFrame and embeddings | |
current_df = None | |
current_embeddings = None | |
# Helper function to check allowed file extensions | |
def allowed_file(filename): | |
return '.' in filename and filename.rsplit('.', 1)[1].lower() == 'pdf' | |
# PDF Processing Functions | |
def open_and_read_pdf(pdf_path): | |
doc = fitz.open(pdf_path) | |
pages_and_texts = [] | |
for page_num, page in tqdm(enumerate(doc), total=len(doc), desc="Reading PDF Pages"): | |
text = page.get_text() | |
pages_and_texts.append({"page_number": page_num + 1, "text": text}) | |
return pages_and_texts | |
def clean_text(text): | |
# Remove numbers surrounded by spaces or newlines | |
text = re.sub(r"(\s*\n*\s*\d+\s*\n*\s*)", " ", text) | |
# Replace " \n" with a single space | |
text = re.sub(r" \n", " ", text) | |
# Remove extra spaces | |
text = re.sub(r"\s+", " ", text).strip() | |
return text | |
def split_into_paragraphs(pages_and_texts): | |
paragraph_delimiter = r"(?:\s*\n\s*\n\s*|\s{2,}\n)" | |
combined_text = "" | |
page_boundaries = [] | |
for page_data in pages_and_texts: | |
start_idx = len(combined_text) | |
combined_text += page_data["text"] | |
page_boundaries.append((start_idx, len(combined_text), page_data["page_number"])) | |
paragraphs = re.split(paragraph_delimiter, combined_text) | |
paragraph_data = [] | |
for paragraph in paragraphs: | |
cleaned_paragraph = clean_text(paragraph) | |
if not cleaned_paragraph: | |
continue | |
if len(paragraph.split(" ")) < 20: | |
continue | |
paragraph_start_idx = combined_text.find(paragraph) | |
paragraph_end_idx = paragraph_start_idx + len(paragraph) | |
pages_spanned = set() | |
for start, end, page_number in page_boundaries: | |
if paragraph_start_idx < end and paragraph_end_idx > start: | |
pages_spanned.add(page_number) | |
paragraph_data.append({ | |
"page_number": sorted(pages_spanned), | |
"char_count": len(cleaned_paragraph), | |
"word_count": len(cleaned_paragraph.split(" ")), | |
"sentence_count": len(sent_tokenize(cleaned_paragraph)), | |
"text": cleaned_paragraph | |
}) | |
return pd.DataFrame(paragraph_data) | |
def split_into_chunks(pages_and_texts, chunk_size): | |
combined_text = "" | |
page_boundaries = [] | |
for page_data in pages_and_texts: | |
start_idx = len(combined_text) | |
combined_text += page_data["text"] | |
page_boundaries.append((start_idx, len(combined_text), page_data["page_number"])) | |
chunks = [combined_text[i:i + chunk_size] for i in range(0, len(combined_text), chunk_size)] | |
chunk_data = [] | |
for chunk in chunks: | |
cleaned_chunk = clean_text(chunk) | |
if not cleaned_chunk: | |
continue | |
chunk_start_idx = combined_text.find(chunk) | |
chunk_end_idx = chunk_start_idx + len(chunk) | |
pages_spanned = set() | |
for start, end, page_number in page_boundaries: | |
if chunk_start_idx < end and chunk_end_idx > start: | |
pages_spanned.add(page_number) | |
chunk_data.append({ | |
"page_number": sorted(pages_spanned), | |
"char_count": len(cleaned_chunk), | |
"word_count": len(cleaned_chunk.split(" ")), | |
"sentence_count": len(sent_tokenize(cleaned_chunk)), | |
"text": cleaned_chunk | |
}) | |
return pd.DataFrame(chunk_data) | |
def split_into_sentences(pages_and_texts, num_sentences=10): | |
combined_text = "" | |
page_boundaries = [] | |
for page_data in pages_and_texts: | |
start_idx = len(combined_text) | |
combined_text += page_data["text"] | |
page_boundaries.append((start_idx, len(combined_text), page_data["page_number"])) | |
sentence_boundary_pattern = r'(?<=[.!?])(?=\s|\n)' | |
sentences = re.split(sentence_boundary_pattern, combined_text) | |
chunks = ["".join(sentences[i:i + num_sentences]) for i in range(0, len(sentences), num_sentences)] | |
chunk_data = [] | |
for chunk in chunks: | |
cleaned_chunk = clean_text(chunk) | |
if not cleaned_chunk: | |
continue | |
chunk_start_idx = combined_text.find(chunk) | |
chunk_end_idx = chunk_start_idx + len(chunk) | |
pages_spanned = set() | |
for start, end, page_number in page_boundaries: | |
if chunk_start_idx < end and chunk_end_idx > start: | |
pages_spanned.add(page_number) | |
chunk_data.append({ | |
"page_number": sorted(pages_spanned), | |
"char_count": len(cleaned_chunk), | |
"word_count": len(cleaned_chunk.split(" ")), | |
"sentence_count": len(sent_tokenize(cleaned_chunk)), | |
"text": cleaned_chunk | |
}) | |
return pd.DataFrame(chunk_data) | |
def split_into_pages(pages_and_texts): | |
pages_data = [] | |
for page_data in pages_and_texts: | |
cleaned_page = clean_text(page_data["text"]) | |
pages_data.append({ | |
"page_number": page_data["page_number"], | |
"char_count": len(cleaned_page), | |
"word_count": len(cleaned_page.split(" ")), | |
"sentence_count": len(sent_tokenize(cleaned_page)), | |
"text": cleaned_page | |
}) | |
return pd.DataFrame(pages_data) | |
def create_df_from_pdf(pdf_path, method="sentence", fixed_size=512, num_sentences=10): | |
pages_and_texts = open_and_read_pdf(pdf_path) | |
if method == "paragraph": | |
df = split_into_paragraphs(pages_and_texts) | |
elif method == "fixed": | |
df = split_into_chunks(pages_and_texts, fixed_size) | |
elif method == "sentence": | |
df = split_into_sentences(pages_and_texts, num_sentences) | |
elif method == "page": | |
df = split_into_pages(pages_and_texts) | |
else: | |
raise ValueError("Unsupported splitting method.") | |
return df | |
def get_text_embedding(model, tokenizer, text): | |
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512) | |
with torch.no_grad(): | |
outputs = model(**inputs) | |
return outputs.last_hidden_state.mean(dim=1).numpy()[0] | |
def retrieve_top_k_similar(query, embeddings, embedding_model, embedding_tokenizer, top_k=5, method="cosine"): | |
query_embedding = get_text_embedding(embedding_model, embedding_tokenizer, query) | |
if method == "cosine": | |
query_tensor = torch.tensor(query_embedding) | |
similarity = torch.nn.functional.cosine_similarity(embeddings, query_tensor, dim=-1) | |
similarity_top_k = torch.topk(similarity, k=top_k) | |
return similarity_top_k.values.numpy(), similarity_top_k.indices.numpy() | |
elif method == "faiss": | |
d = embeddings.shape[1] | |
index = faiss.IndexFlatL2(d) | |
index.add(embeddings.numpy()) | |
query_embedding_reshaped = query_embedding.reshape(1, -1).astype('float32') | |
D, I = index.search(query_embedding_reshaped, k=top_k) | |
return D.reshape(-1), I.reshape(-1) | |
else: | |
raise ValueError("Unsupported similarity method.") | |
# Templates | |
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. | |
Following are the examples: | |
QA Example 1 | |
Context: | |
Page 1: "Water scarcity affects over 2 billion people worldwide due to climate change and poor resource management." | |
Page 2: "Desalination is a key technological solution but comes with challenges such as high energy costs and environmental concerns." | |
Query: | |
What are the main solutions to water scarcity? | |
Answer: | |
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. | |
QA Example 2 | |
Context: | |
Page 1: "Photosynthesis is the process by which plants convert sunlight into energy, primarily occurring in the chloroplasts." | |
Page 2: "The process consists of light-dependent reactions and the Calvin cycle, where glucose is synthesized." | |
Query: | |
What is glucose? | |
Answer: | |
Unfortunately, the context provided does not contain the answer to your inquiry. | |
Context Pages: | |
Page {page1}: {context1} | |
Page {page2}: {context2} | |
Page {page3}: {context3} | |
Query: | |
{query} | |
Please ensure that your answer is complete, ends at the end of a sentence, and does not trail off.""" | |
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. | |
Context Pages: | |
Page {page1} : {context1} | |
Page {page2}: {context2} | |
Page {page3}: {context3} | |
Query: | |
{query} | |
Guidelines for Response: | |
Provide a detailed, explanatory answer, but do not make it too long. | |
Optionally quote from the context if helpful, citing the page. | |
Specify which pages support your response. | |
Only use the context to answer and do not answer the question if the answer is not in the context. | |
If the context does not contain the answer, say that you cannot deduce the answer from the context. | |
Please ensure that your answer is complete, ends at the end of a sentence, and does not trail off.""" | |
templates = [template1, template2] | |
def get_items_for_prompt(query, df, indices): | |
required_columns = ["page_number", "text"] | |
for col in required_columns: | |
if col not in df.columns: | |
raise KeyError(f"Required column '{col}' not found in DataFrame.") | |
if len(indices) < 3: | |
raise ValueError("Not enough indices to generate prompts. Ensure top_k >= 3.") | |
dict1 = { | |
"query": query, | |
"page1": df["page_number"].iloc[indices[0]], | |
"page2": df["page_number"].iloc[indices[1]], | |
"page3": df["page_number"].iloc[indices[2]], | |
"context1": df["text"].iloc[indices[0]], | |
"context2": df["text"].iloc[indices[1]], | |
"context3": df["text"].iloc[indices[2]] | |
} | |
return dict1 | |
def generate_prompts(query, indices, df, templates): | |
dict1 = get_items_for_prompt(query, df, indices) | |
prompts = [ | |
template.format( | |
page1=dict1["page1"], | |
page2=dict1["page2"], | |
page3=dict1["page3"], | |
context1=dict1["context1"], | |
context2=dict1["context2"], | |
context3=dict1["context3"], | |
query=dict1["query"] | |
) | |
for template in templates | |
] | |
return prompts | |
def query_hf_mistral(prompt, api_url=MISTRAL_API_URL): | |
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} | |
formatted_prompt = "<s>[INST]" + prompt + " [/INST] Model answer</s>" | |
payload = { | |
"inputs": formatted_prompt, | |
"parameters": { | |
"max_new_tokens": 500, | |
"temperature": 0.2, | |
"return_full_text": False | |
} | |
} | |
response = requests.post(api_url, headers=headers, json=payload) | |
if response.status_code != 200: | |
raise Exception(f"Mistral API request failed with status code {response.status_code}: {response.text}") | |
response_data = response.json() | |
if isinstance(response_data, list): | |
return response_data[0].get("generated_text", "No response available.") | |
else: | |
return response_data.get("generated_text", "No response available.") | |
def query_hf_phi(prompt, api_url=PHI_API_URL): | |
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} | |
formatted_prompt = prompt + "\n\nOutput:" | |
payload = { | |
"inputs": formatted_prompt, | |
"parameters": { | |
"max_new_tokens": 500, | |
"temperature": 0.2, | |
"return_full_text": False | |
} | |
} | |
response = requests.post(api_url, headers=headers, json=payload) | |
if response.status_code != 200: | |
raise Exception(f"Phi API request failed with status code {response.status_code}: {response.text}") | |
response_data = response.json() | |
if isinstance(response_data, list): | |
return response_data[0].get("generated_text", "No response available.") | |
else: | |
return response_data.get("generated_text", "No response available.") | |
def query_hf_qwen(prompt, api_url=QWEN_API_URL): | |
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"} | |
formatted_prompt = "<|im_start|>system\n" + prompt + "<|im_end|>\n<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n" | |
payload = { | |
"inputs": formatted_prompt, | |
"parameters": { | |
"max_new_tokens": 500, | |
"temperature": 0.2, | |
"return_full_text": False | |
} | |
} | |
response = requests.post(api_url, headers=headers, json=payload) | |
if response.status_code != 200: | |
raise Exception(f"Qwen API request failed with status code {response.status_code}: {response.text}") | |
response_data = response.json() | |
if isinstance(response_data, list): | |
return response_data[0].get("generated_text", "No response available.") | |
else: | |
return response_data.get("generated_text", "No response available.") | |
def evaluate_prompts(prompts, model_functions): | |
results = [] | |
for i, prompt in enumerate(prompts): | |
for func in model_functions: | |
try: | |
response = func(prompt) | |
except Exception as e: | |
response = f"Error: {str(e)}" | |
results.append({ | |
"prompt_number": i + 1, | |
"model_function": func.__name__, | |
"response": response | |
}) | |
return results | |
def ensure_complete_sentence(text): | |
if re.search(r'[.!?]$', text.strip()): | |
return text | |
else: | |
return text + "." | |
# Gradio UI Functions | |
def handle_file_upload(file): | |
global current_df, current_embeddings | |
# Check if no file was provided | |
if not file: | |
return "No file selected." | |
# If the file is bytes (e.g. from an in-memory upload) | |
if isinstance(file, bytes): | |
logger.info("File received as raw bytes, no name provided.") | |
# Generate a filename for the uploaded file | |
filename = f"{uuid.uuid4()}_uploaded_file.pdf" | |
file_path = os.path.join(UPLOAD_FOLDER, filename) | |
try: | |
with open(file_path, "wb") as f_out: | |
f_out.write(file) | |
logger.info(f"File saved to {file_path}") | |
except Exception as e: | |
logger.error(f"Error saving file: {e}") | |
return f"Error saving file: {str(e)}" | |
else: | |
# If it's not bytes, then it might be a dict-like object. | |
# Attempt to treat it as a dictionary with 'name' and 'data' keys | |
if not isinstance(file, dict) or "name" not in file or "data" not in file: | |
return "Invalid file structure. Expected a dict with 'name' and 'data'." | |
logger.info(f"Received file info: {file}") | |
base_name = os.path.basename(file["name"]) | |
filename = f"{uuid.uuid4()}_{base_name}" | |
file_path = os.path.join(UPLOAD_FOLDER, filename) | |
try: | |
with open(file_path, "wb") as f_out: | |
f_out.write(file["data"]) | |
logger.info(f"File saved to {file_path}") | |
except Exception as e: | |
logger.error(f"Error saving file: {e}") | |
return f"Error saving file: {str(e)}" | |
# Process the saved file to create embeddings | |
try: | |
# Create a DataFrame from the PDF | |
df = create_df_from_pdf(file_path, method="sentence") | |
logger.info(f"Number of chunks created from PDF: {len(df)}") | |
# Generate embeddings for each text chunk in the DataFrame | |
embeddings = [] | |
for _, row in tqdm(df.iterrows(), total=df.shape[0], desc="Generating embeddings"): | |
text_chunk = row.get("text", "") | |
emb = get_text_embedding(embedding_model, embedding_tokenizer, text_chunk) | |
embeddings.append(emb) | |
embeddings = np.array(embeddings, dtype='float32') | |
# Store results globally | |
current_df = df.copy() | |
current_df["embedding"] = list(embeddings) | |
current_embeddings = torch.tensor(current_df["embedding"].tolist()) | |
return "File successfully uploaded and processed." | |
except Exception as e: | |
logger.error(f"Error during file processing: {e}") | |
return f"Error: {str(e)}" | |
def handle_query_input(query_text, top_k=3, method="faiss"): | |
global current_df, current_embeddings | |
if current_df is None or current_embeddings is None: | |
return "No PDF uploaded. Please upload a PDF first." | |
if not query_text: | |
return "Query is required." | |
try: | |
similarity_scores, indices = retrieve_top_k_similar( | |
query_text, | |
current_embeddings, | |
embedding_model, | |
embedding_tokenizer, | |
top_k=top_k, | |
method=method | |
) | |
if len(indices) < 3: | |
raise ValueError(f"Requested top_k=3 but only {len(indices)} chunks available.") | |
# Rerank using CrossEncoder | |
docs = current_df["text"].iloc[indices].tolist() | |
reranked = rerank_model.predict([(query_text, doc) for doc in docs]) | |
reranked_indices = np.argsort(-reranked)[:top_k] # Descending order | |
final_indices = indices[reranked_indices] | |
# Generate prompts | |
prompts = generate_prompts(query_text, final_indices, current_df, templates) | |
model_functions = [query_hf_mistral, query_hf_phi, query_hf_qwen] | |
responses = evaluate_prompts(prompts, model_functions) | |
# Beautify and structure the result output | |
formatted_response = "<h2 style='color: #333; border-bottom: 1px solid #ccc;'>Query Results</h2>" | |
for res in responses: | |
prompt_num = res["prompt_number"] | |
model_func = res["model_function"].replace("_", " ").title() | |
response_text = ensure_complete_sentence(res["response"]) | |
formatted_response += f""" | |
<div style='background: #f9f9f9; border-radius: 5px; padding: 10px; margin: 10px 0;'> | |
<h3 style='margin-bottom:5px;'>Prompt {prompt_num} - {model_func}</h3> | |
<p style='margin:0;'>{response_text}</p> | |
</div> | |
""" | |
return formatted_response | |
except KeyError as ke: | |
logger.error(f"KeyError: {ke}") | |
return str(ke) | |
except ValueError as ve: | |
logger.error(f"ValueError: {ve}") | |
return str(ve) | |
except Exception as e: | |
logger.error(f"An unexpected error occurred: {e}") | |
return "An internal error occurred." | |
# Build Gradio Interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# PDF Query System") | |
gr.Markdown("Upload a PDF and then ask questions about it.") | |
with gr.Row(): | |
with gr.Column(): | |
file_input = gr.File(label="Upload PDF", file_types=[".pdf"], type="binary") | |
upload_button = gr.Button("Process PDF") | |
upload_status = gr.Textbox(label="Upload Status", interactive=False) | |
with gr.Column(): | |
query_input = gr.Textbox(label="Enter your query:") | |
submit_query_button = gr.Button("Submit Query") | |
results_output = gr.HTML(label="Results", elem_id="results") | |
upload_button.click(fn=handle_file_upload, inputs=file_input, outputs=upload_status) | |
submit_query_button.click(fn=handle_query_input, inputs=[query_input], outputs=results_output, show_progress=True) | |
# Run Gradio app | |
# demo.launch(server_name="0.0.0.0", server_port=5001) | |
demo.launch() |