Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,243 +1,103 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from sentence_transformers import SentenceTransformer
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
import docx
|
| 7 |
-
import os
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
import json
|
| 10 |
-
import fitz # PyMuPDF for better PDF handling
|
| 11 |
-
import re
|
| 12 |
-
from tqdm import tqdm
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
# Split into chunks (~ 500 chars each)
|
| 34 |
-
chunks = self.split_into_chunks(text)
|
| 35 |
-
for chunk in chunks:
|
| 36 |
-
text_chunks.append({
|
| 37 |
-
"content": chunk,
|
| 38 |
-
"metadata": {
|
| 39 |
-
"source": os.path.basename(file_path),
|
| 40 |
-
"type": "pdf",
|
| 41 |
-
"preview": preview
|
| 42 |
-
}
|
| 43 |
-
})
|
| 44 |
-
return text_chunks
|
| 45 |
-
except Exception as e:
|
| 46 |
-
print(f"Error processing PDF {file_path}: {e}")
|
| 47 |
-
return []
|
| 48 |
-
|
| 49 |
-
def extract_text_from_docx(self, file_path):
|
| 50 |
-
try:
|
| 51 |
-
doc = docx.Document(file_path)
|
| 52 |
-
text_chunks = []
|
| 53 |
-
|
| 54 |
-
full_text = ""
|
| 55 |
-
for para in doc.paragraphs:
|
| 56 |
-
full_text += para.text + "\n"
|
| 57 |
-
|
| 58 |
-
chunks = self.split_into_chunks(full_text)
|
| 59 |
-
for chunk in chunks:
|
| 60 |
-
text_chunks.append({
|
| 61 |
-
"content": chunk,
|
| 62 |
-
"metadata": {
|
| 63 |
-
"source": os.path.basename(file_path),
|
| 64 |
-
"type": "docx"
|
| 65 |
-
}
|
| 66 |
-
})
|
| 67 |
-
return text_chunks
|
| 68 |
-
except Exception as e:
|
| 69 |
-
print(f"Error processing DOCX {file_path}: {e}")
|
| 70 |
-
return []
|
| 71 |
-
|
| 72 |
-
def split_into_chunks(self, text, chunk_size=500, overlap=50):
|
| 73 |
-
chunks = []
|
| 74 |
-
start = 0
|
| 75 |
-
text_length = len(text)
|
| 76 |
-
|
| 77 |
-
while start < text_length:
|
| 78 |
-
end = start + chunk_size
|
| 79 |
-
|
| 80 |
-
# Adjust chunk end to nearest sentence or paragraph break
|
| 81 |
-
if end < text_length:
|
| 82 |
-
# Look for sentence endings (.!?) followed by space or newline
|
| 83 |
-
match = re.search(r'[.!?]\s+', text[end-50:end+50])
|
| 84 |
-
if match:
|
| 85 |
-
end = end - 50 + match.end()
|
| 86 |
-
|
| 87 |
-
chunk = text[start:end].strip()
|
| 88 |
-
if chunk: # Only add non-empty chunks
|
| 89 |
-
chunks.append(chunk)
|
| 90 |
-
|
| 91 |
-
start = end - overlap
|
| 92 |
-
|
| 93 |
-
return chunks
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
return all_chunks
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
similarities = np.dot(self.embeddings, query_embedding) / (
|
| 138 |
-
np.linalg.norm(self.embeddings, axis=1) * np.linalg.norm(query_embedding)
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
top_indices = np.argsort(similarities)[-top_k:][::-1]
|
| 142 |
-
|
| 143 |
-
results = []
|
| 144 |
-
for idx in top_indices:
|
| 145 |
-
results.append({
|
| 146 |
-
"content": self.documents[idx],
|
| 147 |
-
"metadata": self.metadata[idx],
|
| 148 |
-
"score": float(similarities[idx])
|
| 149 |
-
})
|
| 150 |
-
|
| 151 |
-
return results
|
| 152 |
|
| 153 |
-
# Initialize
|
| 154 |
-
|
| 155 |
-
rag.load_documents()
|
| 156 |
|
| 157 |
-
def
|
| 158 |
-
|
| 159 |
-
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
if 1 <= page <= len(doc):
|
| 164 |
-
page_content = doc[page-1]
|
| 165 |
-
# Convert page to image
|
| 166 |
-
pix = page_content.get_pixmap(matrix=fitz.Matrix(2, 2)) # 2x zoom for better quality
|
| 167 |
-
img_path = f"temp_{source}_{page}.png"
|
| 168 |
-
pix.save(img_path)
|
| 169 |
-
return img_path
|
| 170 |
-
else:
|
| 171 |
-
return "Invalid page number"
|
| 172 |
-
except Exception as e:
|
| 173 |
-
return f"Error previewing document: {e}"
|
| 174 |
-
|
| 175 |
-
def search_documents(query, top_k=5, include_preview=True):
|
| 176 |
-
if not query.strip():
|
| 177 |
-
return "Please enter a query", None
|
| 178 |
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
output += f"\n\n📄 Document: {metadata['source']}\n"
|
| 189 |
-
if metadata['type'] == 'pdf':
|
| 190 |
-
output += f"📍 Page {metadata['preview']['page']}/{metadata['preview']['total_pages']}"
|
| 191 |
-
output += f" • Relevance: {score_percentage}%\n"
|
| 192 |
-
output += f"───────────────────\n{result['content']}\n"
|
| 193 |
-
|
| 194 |
-
# Get preview for the first PDF result if requested
|
| 195 |
-
if i == 1 and include_preview and metadata['type'] == 'pdf':
|
| 196 |
-
preview_path = preview_document(metadata['source'], metadata['preview']['page'])
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
label="Question"
|
| 208 |
-
),
|
| 209 |
-
gr.Slider(
|
| 210 |
-
minimum=1,
|
| 211 |
-
maximum=10,
|
| 212 |
-
value=5,
|
| 213 |
-
step=1,
|
| 214 |
-
label="Number of results"
|
| 215 |
-
),
|
| 216 |
-
gr.Checkbox(
|
| 217 |
-
label="Show document preview",
|
| 218 |
-
value=True
|
| 219 |
-
)
|
| 220 |
-
],
|
| 221 |
-
outputs=[
|
| 222 |
-
gr.Textbox(
|
| 223 |
-
label="Search Results",
|
| 224 |
-
lines=20
|
| 225 |
-
),
|
| 226 |
-
gr.Image(
|
| 227 |
-
label="Document Preview",
|
| 228 |
-
type="filepath"
|
| 229 |
-
)
|
| 230 |
-
],
|
| 231 |
-
title="Document Search",
|
| 232 |
-
description="Search through PDFs and Word documents. Enter your question to find relevant content.",
|
| 233 |
-
theme="default",
|
| 234 |
-
allow_flagging="never",
|
| 235 |
-
examples=[
|
| 236 |
-
["What is the main topic discussed in the documents?"],
|
| 237 |
-
["Can you find specific examples of...?"],
|
| 238 |
-
]
|
| 239 |
-
)
|
| 240 |
|
| 241 |
-
|
| 242 |
-
if __name__ == "__main__":
|
| 243 |
-
interface.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import pinecone
|
| 3 |
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqGeneration
|
| 5 |
+
import torch
|
| 6 |
+
from datasets import load_dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# Initialize models and databases
|
| 9 |
+
def init_models():
|
| 10 |
+
# Load the embedding model
|
| 11 |
+
embeddings_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 12 |
+
|
| 13 |
+
# Load the LLM for answering
|
| 14 |
+
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
|
| 15 |
+
model = AutoModelForSeq2SeqGeneration.from_pretrained("google/flan-t5-base")
|
| 16 |
+
|
| 17 |
+
# Initialize Pinecone
|
| 18 |
+
pinecone.init(api_key="your-pinecone-api-key", environment="gcp-starter")
|
| 19 |
+
index = pinecone.Index("test-index")
|
| 20 |
+
|
| 21 |
+
# Load your dataset from Hugging Face
|
| 22 |
+
dataset = load_dataset("your-username/your-dataset-name", split="train")
|
| 23 |
+
|
| 24 |
+
return embeddings_model, tokenizer, model, index, dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# Generate response using retrieved context
|
| 27 |
+
def generate_answer(question, context, tokenizer, model):
|
| 28 |
+
prompt = f"Context: {context}\n\nQuestion: {question}\n\nAnswer:"
|
| 29 |
+
inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True)
|
| 30 |
+
|
| 31 |
+
outputs = model.generate(
|
| 32 |
+
**inputs,
|
| 33 |
+
max_length=512,
|
| 34 |
+
num_beams=4,
|
| 35 |
+
temperature=0.7,
|
| 36 |
+
top_p=0.9,
|
| 37 |
+
repetition_penalty=1.2,
|
| 38 |
+
early_stopping=True
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 42 |
+
return answer
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
def search_documents(query, embeddings_model, index, dataset, top_k=3):
|
| 45 |
+
# Create embedding for the query
|
| 46 |
+
query_embedding = embeddings_model.encode(query)
|
| 47 |
+
|
| 48 |
+
# Search Pinecone
|
| 49 |
+
results = index.query(
|
| 50 |
+
vector=query_embedding.tolist(),
|
| 51 |
+
top_k=top_k,
|
| 52 |
+
include_metadata=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Get full context from the dataset using metadata
|
| 56 |
+
contexts = []
|
| 57 |
+
for match in results.matches:
|
| 58 |
+
source = match.metadata['source']
|
| 59 |
+
# Find the corresponding document in the dataset
|
| 60 |
+
doc = next((item for item in dataset if item['source'] == source), None)
|
| 61 |
+
if doc:
|
| 62 |
+
contexts.append(doc['text'])
|
| 63 |
+
|
| 64 |
+
return "\n\n".join(contexts)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
# Initialize all models and databases
|
| 67 |
+
embeddings_model, tokenizer, model, index, dataset = init_models()
|
|
|
|
| 68 |
|
| 69 |
+
def process_query(query):
|
| 70 |
+
# Search for relevant documents
|
| 71 |
+
context = search_documents(query, embeddings_model, index, dataset)
|
| 72 |
|
| 73 |
+
# Generate answer
|
| 74 |
+
answer = generate_answer(query, context, tokenizer, model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# Format sources
|
| 77 |
+
sources = [f"Source: {match.metadata['source']}" for match in index.query(
|
| 78 |
+
vector=embeddings_model.encode(query).tolist(),
|
| 79 |
+
top_k=3,
|
| 80 |
+
include_metadata=True
|
| 81 |
+
).matches]
|
| 82 |
|
| 83 |
+
return answer, "\n".join(sources)
|
| 84 |
+
|
| 85 |
+
# Create the Gradio interface
|
| 86 |
+
with gr.Blocks() as demo:
|
| 87 |
+
gr.Markdown("# Document Search and Q&A")
|
| 88 |
|
| 89 |
+
with gr.Row():
|
| 90 |
+
query_input = gr.Textbox(label="Enter your question")
|
| 91 |
+
search_button = gr.Button("Search")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
with gr.Row():
|
| 94 |
+
answer_output = gr.Textbox(label="Answer")
|
| 95 |
+
sources_output = gr.Textbox(label="Sources")
|
| 96 |
+
|
| 97 |
+
search_button.click(
|
| 98 |
+
process_query,
|
| 99 |
+
inputs=[query_input],
|
| 100 |
+
outputs=[answer_output, sources_output]
|
| 101 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
demo.launch()
|
|
|
|
|
|