Spaces:
Running
on
Zero
Running
on
Zero
app.py
CHANGED
@@ -8,16 +8,13 @@ import json
|
|
8 |
import hashlib
|
9 |
from pathlib import Path
|
10 |
from typing import List, Dict, Any, Tuple
|
11 |
-
import PyPDF2
|
12 |
import docx
|
13 |
import fitz # pymupdf
|
14 |
from unstructured.partition.auto import partition
|
15 |
|
16 |
-
|
17 |
os.environ["TRITON_CACHE_DIR"] = "/tmp/triton_cache"
|
18 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
19 |
|
20 |
-
|
21 |
# PyLate imports
|
22 |
from pylate import models, indexes, retrieve
|
23 |
|
@@ -29,495 +26,484 @@ metadata_db = None
|
|
29 |
|
30 |
# ===== DOCUMENT PROCESSING FUNCTIONS =====
|
31 |
|
32 |
-
|
33 |
def extract_text_from_pdf(file_path: str) -> str:
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
return text.strip()
|
58 |
-
|
59 |
|
60 |
def extract_text_from_docx(file_path: str) -> str:
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
|
72 |
def extract_text_from_txt(file_path: str) -> str:
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
|
85 |
def chunk_text(text: str, chunk_size: int = 1000, overlap: int = 100) -> List[Dict[str, Any]]:
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
|
119 |
# ===== METADATA DATABASE =====
|
120 |
|
121 |
-
|
122 |
def init_metadata_db():
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
|
151 |
def add_document_metadata(doc_id: str, filename: str, file_hash: str,
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
|
169 |
def get_document_metadata(doc_id: str) -> Dict[str, Any]:
|
170 |
-
|
171 |
-
|
172 |
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
|
183 |
# ===== PYLATE INITIALIZATION =====
|
184 |
|
185 |
-
|
186 |
@spaces.GPU
|
187 |
-
def initialize_pylate(model_name: str = "
|
188 |
-
|
189 |
-
|
190 |
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
|
195 |
-
|
196 |
-
|
197 |
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
|
211 |
-
|
212 |
-
|
213 |
|
214 |
-
|
215 |
|
216 |
-
|
217 |
-
|
218 |
|
219 |
# ===== DOCUMENT PROCESSING =====
|
220 |
|
221 |
-
|
222 |
@spaces.GPU
|
223 |
def process_documents(files, chunk_size: int = 1000, overlap: int = 100) -> str:
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
|
|
308 |
|
309 |
# ===== SEARCH FUNCTION =====
|
310 |
|
311 |
-
|
312 |
@spaces.GPU
|
313 |
def search_documents(query: str, k: int = 5, show_chunks: bool = True) -> str:
|
314 |
-
|
315 |
-
|
316 |
|
317 |
-
|
318 |
-
|
319 |
|
320 |
-
|
321 |
-
|
322 |
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
|
327 |
-
|
328 |
-
|
329 |
|
330 |
-
|
331 |
-
|
332 |
|
333 |
-
|
334 |
-
|
335 |
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
|
340 |
-
|
341 |
-
|
342 |
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
|
354 |
-
|
355 |
|
356 |
-
|
357 |
|
358 |
-
|
359 |
-
|
360 |
|
361 |
# ===== GRADIO INTERFACE =====
|
362 |
|
363 |
-
|
364 |
def create_interface():
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
|
|
513 |
|
514 |
# ===== MAIN =====
|
515 |
|
516 |
-
|
517 |
if __name__ == "__main__":
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
|
|
8 |
import hashlib
|
9 |
from pathlib import Path
|
10 |
from typing import List, Dict, Any, Tuple
|
|
|
11 |
import docx
|
12 |
import fitz # pymupdf
|
13 |
from unstructured.partition.auto import partition
|
14 |
|
|
|
15 |
os.environ["TRITON_CACHE_DIR"] = "/tmp/triton_cache"
|
16 |
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
17 |
|
|
|
18 |
# PyLate imports
|
19 |
from pylate import models, indexes, retrieve
|
20 |
|
|
|
26 |
|
27 |
# ===== DOCUMENT PROCESSING FUNCTIONS =====
|
28 |
|
|
|
29 |
def extract_text_from_pdf(file_path: str) -> str:
|
30 |
+
"""Extract text from PDF file using PyMuPDF and unstructured as fallback."""
|
31 |
+
text = ""
|
32 |
+
try:
|
33 |
+
# Use PyMuPDF (fitz) - more reliable than PyPDF2
|
34 |
+
doc = fitz.open(file_path)
|
35 |
+
for page in doc:
|
36 |
+
text += page.get_text() + "\n"
|
37 |
+
doc.close()
|
38 |
+
|
39 |
+
# If no text extracted, try unstructured
|
40 |
+
if not text.strip():
|
41 |
+
elements = partition(filename=file_path)
|
42 |
+
text = "\n".join([str(element) for element in elements])
|
43 |
+
|
44 |
+
except Exception as e:
|
45 |
+
# Final fallback to unstructured
|
46 |
+
try:
|
47 |
+
elements = partition(filename=file_path)
|
48 |
+
text = "\n".join([str(element) for element in elements])
|
49 |
+
except:
|
50 |
+
text = f"Error: Could not extract text from PDF: {str(e)}"
|
51 |
+
|
52 |
+
return text.strip()
|
|
|
|
|
53 |
|
54 |
def extract_text_from_docx(file_path: str) -> str:
|
55 |
+
"""Extract text from DOCX file."""
|
56 |
+
try:
|
57 |
+
doc = docx.Document(file_path)
|
58 |
+
text = ""
|
59 |
+
for paragraph in doc.paragraphs:
|
60 |
+
text += paragraph.text + "\n"
|
61 |
+
return text.strip()
|
62 |
+
except Exception as e:
|
63 |
+
return f"Error: Could not extract text from DOCX: {str(e)}"
|
|
|
64 |
|
65 |
def extract_text_from_txt(file_path: str) -> str:
|
66 |
+
"""Extract text from TXT file."""
|
67 |
+
try:
|
68 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
69 |
+
return file.read().strip()
|
70 |
+
except:
|
71 |
+
try:
|
72 |
+
with open(file_path, 'r', encoding='latin1') as file:
|
73 |
+
return file.read().strip()
|
74 |
+
except Exception as e:
|
75 |
+
return f"Error: Could not read text file: {str(e)}"
|
|
|
76 |
|
77 |
def chunk_text(text: str, chunk_size: int = 1000, overlap: int = 100) -> List[Dict[str, Any]]:
|
78 |
+
"""Chunk text with overlap and return metadata."""
|
79 |
+
chunks = []
|
80 |
+
start = 0
|
81 |
+
chunk_index = 0
|
82 |
+
|
83 |
+
while start < len(text):
|
84 |
+
end = start + chunk_size
|
85 |
+
chunk_text = text[start:end]
|
86 |
+
|
87 |
+
# Try to break at sentence boundary
|
88 |
+
if end < len(text):
|
89 |
+
last_period = chunk_text.rfind('.')
|
90 |
+
last_newline = chunk_text.rfind('\n')
|
91 |
+
break_point = max(last_period, last_newline)
|
92 |
+
|
93 |
+
if break_point > chunk_size * 0.7:
|
94 |
+
chunk_text = chunk_text[:break_point + 1]
|
95 |
+
end = start + break_point + 1
|
96 |
+
|
97 |
+
if chunk_text.strip():
|
98 |
+
chunks.append({
|
99 |
+
'text': chunk_text.strip(),
|
100 |
+
'start': start,
|
101 |
+
'end': end,
|
102 |
+
'index': chunk_index,
|
103 |
+
'length': len(chunk_text.strip())
|
104 |
+
})
|
105 |
+
chunk_index += 1
|
106 |
+
|
107 |
+
start = max(start + 1, end - overlap)
|
108 |
+
|
109 |
+
return chunks
|
110 |
|
111 |
# ===== METADATA DATABASE =====
|
112 |
|
|
|
113 |
def init_metadata_db():
|
114 |
+
"""Initialize SQLite database for metadata."""
|
115 |
+
global metadata_db
|
116 |
+
|
117 |
+
db_path = "metadata.db"
|
118 |
+
metadata_db = sqlite3.connect(db_path, check_same_thread=False)
|
119 |
+
|
120 |
+
metadata_db.execute("""
|
121 |
+
CREATE TABLE IF NOT EXISTS documents (
|
122 |
+
doc_id TEXT PRIMARY KEY,
|
123 |
+
filename TEXT NOT NULL,
|
124 |
+
file_hash TEXT NOT NULL,
|
125 |
+
original_text TEXT NOT NULL,
|
126 |
+
chunk_index INTEGER NOT NULL,
|
127 |
+
total_chunks INTEGER NOT NULL,
|
128 |
+
chunk_start INTEGER NOT NULL,
|
129 |
+
chunk_end INTEGER NOT NULL,
|
130 |
+
chunk_size INTEGER NOT NULL,
|
131 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
132 |
+
)
|
133 |
+
""")
|
134 |
+
|
135 |
+
metadata_db.execute("""
|
136 |
+
CREATE INDEX IF NOT EXISTS idx_filename ON documents(filename);
|
137 |
+
""")
|
138 |
+
|
139 |
+
metadata_db.commit()
|
|
|
140 |
|
141 |
def add_document_metadata(doc_id: str, filename: str, file_hash: str,
|
142 |
+
original_text: str, chunk_info: Dict[str, Any], total_chunks: int):
|
143 |
+
"""Add document metadata to database."""
|
144 |
+
global metadata_db
|
145 |
+
|
146 |
+
metadata_db.execute("""
|
147 |
+
INSERT OR REPLACE INTO documents
|
148 |
+
(doc_id, filename, file_hash, original_text, chunk_index, total_chunks,
|
149 |
+
chunk_start, chunk_end, chunk_size)
|
150 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
151 |
+
""", (
|
152 |
+
doc_id, filename, file_hash, original_text,
|
153 |
+
chunk_info['index'], total_chunks,
|
154 |
+
chunk_info['start'], chunk_info['end'], chunk_info['length']
|
155 |
+
))
|
156 |
+
metadata_db.commit()
|
|
|
157 |
|
158 |
def get_document_metadata(doc_id: str) -> Dict[str, Any]:
|
159 |
+
"""Get document metadata by ID."""
|
160 |
+
global metadata_db
|
161 |
|
162 |
+
cursor = metadata_db.execute(
|
163 |
+
"SELECT * FROM documents WHERE doc_id = ?", (doc_id,)
|
164 |
+
)
|
165 |
+
row = cursor.fetchone()
|
166 |
|
167 |
+
if row:
|
168 |
+
columns = [desc[0] for desc in cursor.description]
|
169 |
+
return dict(zip(columns, row))
|
170 |
+
return {}
|
171 |
|
172 |
# ===== PYLATE INITIALIZATION =====
|
173 |
|
|
|
174 |
@spaces.GPU
|
175 |
+
def initialize_pylate(model_name: str = "colbert-ir/colbertv2.0") -> str:
|
176 |
+
"""Initialize PyLate components on GPU."""
|
177 |
+
global model, index, retriever
|
178 |
|
179 |
+
try:
|
180 |
+
# Initialize metadata database
|
181 |
+
init_metadata_db()
|
182 |
|
183 |
+
# Load ColBERT model
|
184 |
+
model = models.ColBERT(model_name_or_path=model_name)
|
185 |
|
186 |
+
# Move to GPU if available
|
187 |
+
if torch.cuda.is_available():
|
188 |
+
model = model.to('cuda')
|
189 |
|
190 |
+
# Initialize PLAID index with CPU fallback for k-means
|
191 |
+
index = indexes.PLAID(
|
192 |
+
index_folder="./pylate_index",
|
193 |
+
index_name="documents",
|
194 |
+
override=True,
|
195 |
+
kmeans_niters=1, # Reduce k-means iterations
|
196 |
+
nbits=1 # Reduce quantization bits
|
197 |
+
)
|
198 |
|
199 |
+
# Initialize retriever
|
200 |
+
retriever = retrieve.ColBERT(index=index)
|
201 |
|
202 |
+
return f"β
PyLate initialized successfully!\nModel: {model_name}\nDevice: {'GPU' if torch.cuda.is_available() else 'CPU'}"
|
203 |
|
204 |
+
except Exception as e:
|
205 |
+
return f"β Error initializing PyLate: {str(e)}"
|
206 |
|
207 |
# ===== DOCUMENT PROCESSING =====
|
208 |
|
|
|
209 |
@spaces.GPU
|
210 |
def process_documents(files, chunk_size: int = 1000, overlap: int = 100) -> str:
|
211 |
+
"""Process uploaded documents and add to index."""
|
212 |
+
global model, index, metadata_db
|
213 |
+
|
214 |
+
if not model or not index:
|
215 |
+
return "β Please initialize PyLate first!"
|
216 |
+
|
217 |
+
if not files:
|
218 |
+
return "β No files uploaded!"
|
219 |
+
|
220 |
+
try:
|
221 |
+
all_documents = []
|
222 |
+
all_doc_ids = []
|
223 |
+
processed_files = []
|
224 |
+
|
225 |
+
for file in files:
|
226 |
+
# Get file info
|
227 |
+
filename = Path(file.name).name
|
228 |
+
file_path = file.name
|
229 |
+
|
230 |
+
# Calculate file hash
|
231 |
+
with open(file_path, 'rb') as f:
|
232 |
+
file_hash = hashlib.md5(f.read()).hexdigest()
|
233 |
+
|
234 |
+
# Extract text based on file type
|
235 |
+
if filename.lower().endswith('.pdf'):
|
236 |
+
text = extract_text_from_pdf(file_path)
|
237 |
+
elif filename.lower().endswith('.docx'):
|
238 |
+
text = extract_text_from_docx(file_path)
|
239 |
+
elif filename.lower().endswith('.txt'):
|
240 |
+
text = extract_text_from_txt(file_path)
|
241 |
+
else:
|
242 |
+
continue
|
243 |
+
|
244 |
+
if not text or text.startswith("Error:"):
|
245 |
+
processed_files.append(f"{filename}: Failed to extract text")
|
246 |
+
continue
|
247 |
+
|
248 |
+
# Chunk the text
|
249 |
+
chunks = chunk_text(text, chunk_size, overlap)
|
250 |
+
|
251 |
+
# Process each chunk
|
252 |
+
for chunk in chunks:
|
253 |
+
doc_id = f"{filename}_chunk_{chunk['index']}"
|
254 |
+
all_documents.append(chunk['text'])
|
255 |
+
all_doc_ids.append(doc_id)
|
256 |
+
|
257 |
+
# Store metadata
|
258 |
+
add_document_metadata(
|
259 |
+
doc_id=doc_id,
|
260 |
+
filename=filename,
|
261 |
+
file_hash=file_hash,
|
262 |
+
original_text=chunk['text'],
|
263 |
+
chunk_info=chunk,
|
264 |
+
total_chunks=len(chunks)
|
265 |
+
)
|
266 |
+
|
267 |
+
processed_files.append(f"{filename}: {len(chunks)} chunks")
|
268 |
+
|
269 |
+
if not all_documents:
|
270 |
+
return "β No text could be extracted from uploaded files!"
|
271 |
+
|
272 |
+
# Encode documents with PyLate
|
273 |
+
document_embeddings = model.encode(
|
274 |
+
all_documents,
|
275 |
+
batch_size=16, # Smaller batch for ZeroGPU
|
276 |
+
is_query=False,
|
277 |
+
show_progress_bar=True
|
278 |
+
)
|
279 |
+
|
280 |
+
# Add to PLAID index
|
281 |
+
index.add_documents(
|
282 |
+
documents_ids=all_doc_ids,
|
283 |
+
documents_embeddings=document_embeddings
|
284 |
+
)
|
285 |
+
|
286 |
+
result = f"β
Successfully processed {len(files)} files:\n"
|
287 |
+
result += f"π Total chunks: {len(all_documents)}\n"
|
288 |
+
result += f"π Indexed documents:\n"
|
289 |
+
for file_info in processed_files:
|
290 |
+
result += f" β’ {file_info}\n"
|
291 |
+
|
292 |
+
return result
|
293 |
+
|
294 |
+
except Exception as e:
|
295 |
+
return f"β Error processing documents: {str(e)}"
|
296 |
|
297 |
# ===== SEARCH FUNCTION =====
|
298 |
|
|
|
299 |
@spaces.GPU
|
300 |
def search_documents(query: str, k: int = 5, show_chunks: bool = True) -> str:
|
301 |
+
"""Search documents using PyLate."""
|
302 |
+
global model, retriever, metadata_db
|
303 |
|
304 |
+
if not model or not retriever:
|
305 |
+
return "β Please initialize PyLate and process documents first!"
|
306 |
|
307 |
+
if not query.strip():
|
308 |
+
return "β Please enter a search query!"
|
309 |
|
310 |
+
try:
|
311 |
+
# Encode query
|
312 |
+
query_embedding = model.encode([query], is_query=True)
|
313 |
|
314 |
+
# Search
|
315 |
+
results = retriever.retrieve(query_embedding, k=k)[0]
|
316 |
|
317 |
+
if not results:
|
318 |
+
return "π No results found for your query."
|
319 |
|
320 |
+
# Format results with metadata
|
321 |
+
formatted_results = [f"π **Search Results for:** '{query}'\n"]
|
322 |
|
323 |
+
for i, result in enumerate(results):
|
324 |
+
doc_id = result['id']
|
325 |
+
score = result['score']
|
326 |
|
327 |
+
# Get metadata
|
328 |
+
metadata = get_document_metadata(doc_id)
|
329 |
|
330 |
+
formatted_results.append(f"## Result {i+1} (Score: {score:.2f})")
|
331 |
+
formatted_results.append(
|
332 |
+
f"**File:** {metadata.get('filename', 'Unknown')}")
|
333 |
+
formatted_results.append(
|
334 |
+
f"**Chunk:** {metadata.get('chunk_index', 0) + 1}/{metadata.get('total_chunks', 1)}")
|
335 |
|
336 |
+
if show_chunks:
|
337 |
+
text = metadata.get('original_text', '')
|
338 |
+
preview = text[:300] + "..." if len(text) > 300 else text
|
339 |
+
formatted_results.append(f"**Text:** {preview}")
|
340 |
|
341 |
+
formatted_results.append("---")
|
342 |
|
343 |
+
return "\n".join(formatted_results)
|
344 |
|
345 |
+
except Exception as e:
|
346 |
+
return f"β Error searching: {str(e)}"
|
347 |
|
348 |
# ===== GRADIO INTERFACE =====
|
349 |
|
|
|
350 |
def create_interface():
|
351 |
+
"""Create the Gradio interface."""
|
352 |
+
|
353 |
+
with gr.Blocks(title="PyLate Document Search", theme=gr.themes.Soft()) as demo:
|
354 |
+
gr.Markdown("""
|
355 |
+
# π PyLate Document Search
|
356 |
+
### Powered by ColBERT and ZeroGPU
|
357 |
+
|
358 |
+
Upload documents, process them with PyLate, and perform semantic search!
|
359 |
+
|
360 |
+
**Note:** Using PyMuPDF and Unstructured for robust PDF text extraction.
|
361 |
+
""")
|
362 |
+
|
363 |
+
with gr.Tab("π Setup"):
|
364 |
+
gr.Markdown("### Initialize PyLate System")
|
365 |
+
|
366 |
+
model_choice = gr.Dropdown(
|
367 |
+
choices=[
|
368 |
+
"colbert-ir/colbertv2.0",
|
369 |
+
"sentence-transformers/all-MiniLM-L6-v2"
|
370 |
+
],
|
371 |
+
value="colbert-ir/colbertv2.0",
|
372 |
+
label="Select Model"
|
373 |
+
)
|
374 |
+
|
375 |
+
init_btn = gr.Button("Initialize PyLate", variant="primary")
|
376 |
+
init_status = gr.Textbox(label="Initialization Status", lines=3)
|
377 |
+
|
378 |
+
init_btn.click(
|
379 |
+
initialize_pylate,
|
380 |
+
inputs=model_choice,
|
381 |
+
outputs=init_status
|
382 |
+
)
|
383 |
+
|
384 |
+
with gr.Tab("π Document Upload"):
|
385 |
+
gr.Markdown("### Upload and Process Documents")
|
386 |
+
|
387 |
+
with gr.Row():
|
388 |
+
with gr.Column():
|
389 |
+
file_upload = gr.File(
|
390 |
+
file_count="multiple",
|
391 |
+
file_types=[".pdf", ".docx", ".txt"],
|
392 |
+
label="Upload Documents (PDF, DOCX, TXT)"
|
393 |
+
)
|
394 |
+
|
395 |
+
with gr.Row():
|
396 |
+
chunk_size = gr.Slider(
|
397 |
+
minimum=500,
|
398 |
+
maximum=3000,
|
399 |
+
value=1000,
|
400 |
+
step=100,
|
401 |
+
label="Chunk Size (characters)"
|
402 |
+
)
|
403 |
+
|
404 |
+
overlap = gr.Slider(
|
405 |
+
minimum=0,
|
406 |
+
maximum=500,
|
407 |
+
value=100,
|
408 |
+
step=50,
|
409 |
+
label="Chunk Overlap (characters)"
|
410 |
+
)
|
411 |
+
|
412 |
+
process_btn = gr.Button(
|
413 |
+
"Process Documents", variant="primary")
|
414 |
+
|
415 |
+
with gr.Column():
|
416 |
+
process_status = gr.Textbox(
|
417 |
+
label="Processing Status",
|
418 |
+
lines=10,
|
419 |
+
max_lines=15
|
420 |
+
)
|
421 |
+
|
422 |
+
process_btn.click(
|
423 |
+
process_documents,
|
424 |
+
inputs=[file_upload, chunk_size, overlap],
|
425 |
+
outputs=process_status
|
426 |
+
)
|
427 |
+
|
428 |
+
with gr.Tab("π Search"):
|
429 |
+
gr.Markdown("### Search Your Documents")
|
430 |
+
|
431 |
+
with gr.Row():
|
432 |
+
with gr.Column():
|
433 |
+
search_query = gr.Textbox(
|
434 |
+
label="Search Query",
|
435 |
+
placeholder="Enter your search query...",
|
436 |
+
lines=2
|
437 |
+
)
|
438 |
+
|
439 |
+
with gr.Row():
|
440 |
+
num_results = gr.Slider(
|
441 |
+
minimum=1,
|
442 |
+
maximum=20,
|
443 |
+
value=5,
|
444 |
+
step=1,
|
445 |
+
label="Number of Results"
|
446 |
+
)
|
447 |
+
|
448 |
+
show_chunks = gr.Checkbox(
|
449 |
+
value=True,
|
450 |
+
label="Show Text Chunks"
|
451 |
+
)
|
452 |
+
|
453 |
+
search_btn = gr.Button("Search", variant="primary")
|
454 |
+
|
455 |
+
with gr.Column():
|
456 |
+
search_results = gr.Textbox(
|
457 |
+
label="Search Results",
|
458 |
+
lines=15,
|
459 |
+
max_lines=20
|
460 |
+
)
|
461 |
+
|
462 |
+
search_btn.click(
|
463 |
+
search_documents,
|
464 |
+
inputs=[search_query, num_results, show_chunks],
|
465 |
+
outputs=search_results
|
466 |
+
)
|
467 |
+
|
468 |
+
with gr.Tab("βΉοΈ Info"):
|
469 |
+
gr.Markdown("""
|
470 |
+
### About This System
|
471 |
+
|
472 |
+
**PyLate Document Search** is a semantic search system that uses:
|
473 |
+
|
474 |
+
- **PyLate**: A flexible library for ColBERT models
|
475 |
+
- **ColBERT**: Late interaction retrieval for high-quality search
|
476 |
+
- **ZeroGPU**: Hugging Face's free GPU infrastructure
|
477 |
+
|
478 |
+
#### Features:
|
479 |
+
- π Multi-format document support (PDF, DOCX, TXT)
|
480 |
+
- βοΈ Intelligent text chunking with overlap
|
481 |
+
- π§ Semantic search using ColBERT embeddings
|
482 |
+
- πΎ Metadata tracking for result context
|
483 |
+
- β‘ GPU-accelerated processing
|
484 |
+
|
485 |
+
#### PDF Processing:
|
486 |
+
- Uses PyMuPDF (fitz) for reliable text extraction
|
487 |
+
- Falls back to Unstructured for complex PDFs
|
488 |
+
- No dependency on PyPDF2
|
489 |
+
|
490 |
+
#### Usage Tips:
|
491 |
+
1. Initialize the system first (required)
|
492 |
+
2. Upload your documents and process them
|
493 |
+
3. Use natural language queries for best results
|
494 |
+
4. Adjust chunk size based on your document types
|
495 |
+
|
496 |
+
Built with β€οΈ using PyLate and Gradio
|
497 |
+
""")
|
498 |
+
|
499 |
+
return demo
|
500 |
|
501 |
# ===== MAIN =====
|
502 |
|
|
|
503 |
if __name__ == "__main__":
|
504 |
+
demo = create_interface()
|
505 |
+
demo.launch(
|
506 |
+
share=False,
|
507 |
+
server_name="0.0.0.0",
|
508 |
+
server_port=7860
|
509 |
+
)
|