-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1813 lines (1438 loc) · 67.8 KB
/
app.py
File metadata and controls
1813 lines (1438 loc) · 67.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
120
121
122
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
220
221
222
223
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
310
311
312
313
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
362
363
364
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Enterprise PDF Summarizer System
# High-end PDF processing with MCP server and Gemini API integration
import asyncio
import json
import logging
import os
import re
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional, Tuple, Union, Any
from pathlib import Path
import hashlib
from datetime import datetime
# PDF Processing
import PyPDF2
import pdfplumber
import camelot
import tabula
import pytesseract
from PIL import Image
import fitz # PyMuPDF for better text extraction
# AI/ML
import google.generativeai as genai
import numpy as np
import os
os.environ["TRANSFORMERS_CACHE"] = "/app/cache"
os.environ["HF_HOME"] = "/app/cache"
os.environ["HF_DATASETS_CACHE"] = "/app/cache"
from sentence_transformers import SentenceTransformer
import faiss
# Web Framework
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse
from pydantic import BaseModel, Field
import uvicorn
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi import Request
# Utilities
import aiofiles
import httpx
from concurrent.futures import ThreadPoolExecutor
import pickle
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from dotenv import load_dotenv
import os
# Load .env file
load_dotenv() # by default it looks for .env in project root
# Now Config will pick up the environment variables
class Config:
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
MCP_SERVER_URL = os.getenv("MCP_SERVER_URL", "http://localhost:8080")
CHUNK_SIZE = 1000
CHUNK_OVERLAP = 200
MAX_TOKENS_PER_REQUEST = 4000
UPLOAD_DIR = "uploads"
SUMMARIES_DIR = "summaries"
EMBEDDINGS_DIR = "embeddings"
SUPPORTED_FORMATS = [".pdf"]
# Data Models
@dataclass
class DocumentChunk:
id: str
content: str
page_number: int
section: str
chunk_type: str # text, table, image
embedding: Optional[np.ndarray] = None
@dataclass
class SummaryRequest:
summary_type: str = "medium" # short, medium, detailed
tone: str = "formal" # formal, casual, technical, executive
focus_areas: List[str] = None
custom_questions: List[str] = None
language: str = "en"
@dataclass
class Summary:
id: str
document_id: str
summary_type: str
tone: str
content: str
key_points: List[str]
entities: List[str]
topics: List[str]
confidence_score: float
created_at: datetime
# Add these imports at the top of your file (missing imports)
import io
import traceback
class PDFProcessor:
"""Advanced PDF processing with comprehensive error handling"""
def __init__(self):
self.executor = ThreadPoolExecutor(max_workers=4)
async def process_pdf(self, file_path: str) -> Tuple[List[DocumentChunk], Dict[str, Any]]:
"""Extract text, tables, and images from PDF with robust error handling"""
chunks = []
metadata = {}
try:
logger.info(f"Starting PDF processing: {file_path}")
# Validate file exists and is readable
if not Path(file_path).exists():
raise FileNotFoundError(f"PDF file not found: {file_path}")
file_size = Path(file_path).stat().st_size
if file_size == 0:
raise ValueError(f"PDF file is empty: {file_path}")
logger.info(f"Processing PDF: {Path(file_path).name} (size: {file_size} bytes)")
# Test if PDF can be opened with PyMuPDF
try:
test_doc = fitz.open(file_path)
page_count = test_doc.page_count
logger.info(f"PDF has {page_count} pages")
test_doc.close()
if page_count == 0:
raise ValueError("PDF has no pages")
except Exception as e:
logger.error(f"Cannot open PDF with PyMuPDF: {str(e)}")
raise ValueError(f"Invalid or corrupted PDF file: {str(e)}")
# Extract text and structure with error handling
try:
text_chunks = await self._extract_text_with_structure_safe(file_path)
chunks.extend(text_chunks)
logger.info(f"Extracted {len(text_chunks)} text chunks")
except Exception as e:
logger.error(f"Text extraction failed: {str(e)}")
logger.error(traceback.format_exc())
# Continue processing even if text extraction fails
# Extract tables with error handling
try:
table_chunks = await self._extract_tables_safe(file_path)
chunks.extend(table_chunks)
logger.info(f"Extracted {len(table_chunks)} table chunks")
except Exception as e:
logger.warning(f"Table extraction failed: {str(e)}")
# Extract and process images with error handling
try:
image_chunks = await self._process_images_safe(file_path)
chunks.extend(image_chunks)
logger.info(f"Extracted {len(image_chunks)} image chunks")
except Exception as e:
logger.warning(f"Image processing failed: {str(e)}")
# If no chunks were extracted, create fallback
if not chunks:
logger.warning("No chunks extracted, attempting fallback text extraction")
fallback_chunks = await self._fallback_text_extraction(file_path)
chunks.extend(fallback_chunks)
# Generate metadata
metadata = await self._generate_metadata_safe(file_path, chunks)
logger.info(f"Successfully processed PDF: {len(chunks)} total chunks extracted")
# Ensure we always return a tuple
return chunks, metadata
except Exception as e:
logger.error(f"Critical error processing PDF: {str(e)}")
logger.error(traceback.format_exc())
# Return empty but valid results to prevent tuple unpacking errors
empty_metadata = {
"file_name": Path(file_path).name if Path(file_path).exists() else "unknown",
"file_size": 0,
"total_chunks": 0,
"text_chunks": 0,
"table_chunks": 0,
"image_chunks": 0,
"sections": [],
"page_count": 0,
"processed_at": datetime.now().isoformat(),
"error": str(e)
}
return [], empty_metadata
async def _extract_text_with_structure_safe(self, file_path: str) -> List[DocumentChunk]:
"""Extract text with comprehensive error handling"""
chunks = []
doc = None
try:
doc = fitz.open(file_path)
for page_num in range(doc.page_count):
try:
# FIX: Use correct page access method
page = doc[page_num]
# Extract text with structure
blocks = page.get_text("dict")
if not blocks or "blocks" not in blocks:
logger.warning(f"No text blocks found on page {page_num + 1}")
continue
for block in blocks["blocks"]:
if "lines" in block:
text_content = ""
for line in block["lines"]:
for span in line["spans"]:
if "text" in span:
text_content += span["text"] + " "
if len(text_content.strip()) > 20: # Minimum meaningful content
# Detect section headers
section = self._detect_section(text_content, blocks)
# Create chunks
text_chunks = self._split_text_into_chunks(
text_content.strip(),
page_num + 1,
section
)
chunks.extend(text_chunks)
except Exception as page_error:
logger.warning(f"Error processing page {page_num + 1}: {str(page_error)}")
continue
except Exception as e:
logger.error(f"Error in text extraction: {str(e)}")
raise
finally:
if doc:
doc.close()
return chunks
async def _extract_tables_safe(self, file_path: str) -> List[DocumentChunk]:
"""Extract tables with multiple fallback methods"""
chunks = []
# Method 1: Try Camelot (if available)
try:
import camelot
tables = camelot.read_pdf(file_path, pages='all', flavor='lattice')
for i, table in enumerate(tables):
if not table.df.empty and hasattr(table, 'accuracy') and table.accuracy > 50:
table_text = self._table_to_text(table.df)
chunk_id = hashlib.md5(f"table_{i}_{file_path}".encode()).hexdigest()
chunk = DocumentChunk(
id=chunk_id,
content=table_text,
page_number=getattr(table, 'page', 1),
section=f"Table {i+1}",
chunk_type="table"
)
chunks.append(chunk)
if chunks:
logger.info(f"Extracted {len(chunks)} tables using Camelot")
return chunks
except ImportError:
logger.warning("Camelot not available for table extraction")
except Exception as e:
logger.warning(f"Camelot table extraction failed: {str(e)}")
# Method 2: Try pdfplumber (more reliable, no Java needed)
try:
import pdfplumber
with pdfplumber.open(file_path) as pdf:
for page_num, page in enumerate(pdf.pages):
try:
tables = page.extract_tables()
for i, table_data in enumerate(tables):
if table_data and len(table_data) > 1:
# Convert to text format
table_text = self._array_to_table_text(table_data)
chunk_id = hashlib.md5(f"table_plumber_{page_num}_{i}_{file_path}".encode()).hexdigest()
chunk = DocumentChunk(
id=chunk_id,
content=table_text,
page_number=page_num + 1,
section=f"Table {len(chunks) + 1}",
chunk_type="table"
)
chunks.append(chunk)
except Exception as page_error:
logger.warning(f"Error extracting tables from page {page_num + 1}: {str(page_error)}")
continue
if chunks:
logger.info(f"Extracted {len(chunks)} tables using pdfplumber")
return chunks
except ImportError:
logger.warning("pdfplumber not available")
except Exception as e:
logger.warning(f"pdfplumber table extraction failed: {str(e)}")
return chunks
def _array_to_table_text(self, table_data: List[List]) -> str:
"""Convert 2D array to readable table text"""
text_parts = []
if not table_data:
return "Empty table"
# First row as headers
if table_data[0]:
headers_text = " | ".join([str(cell or "") for cell in table_data[0]])
text_parts.append(f"Table Headers: {headers_text}")
# Data rows (limit to prevent huge chunks)
for i, row in enumerate(table_data[1:], 1):
if i > 15: # Limit rows
text_parts.append(f"... and {len(table_data) - 16} more rows")
break
row_text = " | ".join([str(cell or "") for cell in row])
text_parts.append(f"Row {i}: {row_text}")
return "\n".join(text_parts)
async def _process_images_safe(self, file_path: str) -> List[DocumentChunk]:
"""Extract and process images with comprehensive error handling"""
chunks = []
doc = None
try:
# Check if pytesseract is available
try:
import pytesseract
from PIL import Image
except ImportError:
logger.warning("OCR libraries not available, skipping image processing")
return chunks
doc = fitz.open(file_path)
for page_num in range(doc.page_count):
try:
page = doc[page_num]
image_list = page.get_images()
for img_index, img in enumerate(image_list):
try:
# Extract image
xref = img[0]
pix = fitz.Pixmap(doc, xref)
if pix.n - pix.alpha < 4: # GRAY or RGB
# Convert to PIL Image
img_data = pix.tobytes("ppm")
pil_image = Image.open(io.BytesIO(img_data))
# Perform OCR
ocr_text = pytesseract.image_to_string(pil_image, lang='eng')
if len(ocr_text.strip()) > 10:
chunk_id = hashlib.md5(f"image_{page_num}_{img_index}".encode()).hexdigest()
chunk = DocumentChunk(
id=chunk_id,
content=f"Image content (OCR): {ocr_text.strip()}",
page_number=page_num + 1,
section=f"Image {img_index + 1}",
chunk_type="image"
)
chunks.append(chunk)
pix = None
except Exception as img_error:
logger.warning(f"Error processing image {img_index} on page {page_num + 1}: {str(img_error)}")
continue
except Exception as page_error:
logger.warning(f"Error processing images on page {page_num + 1}: {str(page_error)}")
continue
except Exception as e:
logger.warning(f"Image processing failed: {str(e)}")
finally:
if doc:
doc.close()
return chunks
async def _fallback_text_extraction(self, file_path: str) -> List[DocumentChunk]:
"""Fallback text extraction using simple methods"""
chunks = []
try:
logger.info("Attempting fallback text extraction")
doc = fitz.open(file_path)
for page_num in range(doc.page_count):
try:
page = doc[page_num]
# Simple text extraction
text = page.get_text()
if text and len(text.strip()) > 20:
# Split into chunks
fallback_chunks = self._split_text_into_chunks(
text.strip(),
page_num + 1,
f"Page {page_num + 1}"
)
chunks.extend(fallback_chunks)
logger.info(f"Fallback extraction found {len(fallback_chunks)} chunks on page {page_num + 1}")
except Exception as page_error:
logger.warning(f"Fallback extraction failed on page {page_num + 1}: {str(page_error)}")
continue
doc.close()
if chunks:
logger.info(f"Fallback extraction successful: {len(chunks)} chunks")
else:
logger.warning("Fallback extraction found no content")
# Create a minimal chunk to avoid empty results
minimal_chunk = DocumentChunk(
id=hashlib.md5(f"minimal_{file_path}".encode()).hexdigest(),
content=f"Document processed but no readable content extracted from {Path(file_path).name}",
page_number=1,
section="Document Info",
chunk_type="text"
)
chunks.append(minimal_chunk)
except Exception as e:
logger.error(f"Fallback text extraction failed: {str(e)}")
# Create error chunk to avoid empty results
error_chunk = DocumentChunk(
id=hashlib.md5(f"error_{file_path}".encode()).hexdigest(),
content=f"Error processing document: {str(e)}",
page_number=1,
section="Error",
chunk_type="text"
)
chunks.append(error_chunk)
return chunks
async def _generate_metadata_safe(self, file_path: str, chunks: List[DocumentChunk]) -> Dict[str, Any]:
"""Generate metadata with error handling"""
try:
metadata = {
"file_name": Path(file_path).name,
"file_size": Path(file_path).stat().st_size,
"total_chunks": len(chunks),
"text_chunks": len([c for c in chunks if c.chunk_type == "text"]),
"table_chunks": len([c for c in chunks if c.chunk_type == "table"]),
"image_chunks": len([c for c in chunks if c.chunk_type == "image"]),
"sections": list(set([c.section for c in chunks])) if chunks else [],
"page_count": max([c.page_number for c in chunks]) if chunks else 0,
"processed_at": datetime.now().isoformat(),
"processing_status": "success" if chunks else "no_content_extracted"
}
return metadata
except Exception as e:
logger.error(f"Error generating metadata: {str(e)}")
return {
"file_name": "unknown",
"file_size": 0,
"total_chunks": 0,
"text_chunks": 0,
"table_chunks": 0,
"image_chunks": 0,
"sections": [],
"page_count": 0,
"processed_at": datetime.now().isoformat(),
"processing_status": "error",
"error": str(e)
}
# Keep your existing helper methods with minor fixes
def _split_text_into_chunks(self, text: str, page_num: int, section: str) -> List[DocumentChunk]:
"""Split text into manageable chunks with overlap"""
chunks = []
if not text or len(text.strip()) < 10:
return chunks
words = text.split()
chunk_size = Config.CHUNK_SIZE
overlap = Config.CHUNK_OVERLAP
for i in range(0, len(words), chunk_size - overlap):
chunk_words = words[i:i + chunk_size]
chunk_text = " ".join(chunk_words)
if len(chunk_text.strip()) > 20: # Minimum chunk size
chunk_id = hashlib.md5(f"{chunk_text[:100]}{page_num}".encode()).hexdigest()
chunk = DocumentChunk(
id=chunk_id,
content=chunk_text,
page_number=page_num,
section=section,
chunk_type="text"
)
chunks.append(chunk)
return chunks
def _detect_section(self, text: str, blocks: Dict) -> str:
"""Detect section headers using font size and formatting"""
# Simple heuristic - look for short lines with larger fonts
lines = text.split('\n')
for line in lines[:3]: # Check first few lines
if len(line.strip()) < 100 and len(line.strip()) > 10:
if any(keyword in line.lower() for keyword in
['chapter', 'section', 'introduction', 'conclusion', 'summary']):
return line.strip()
return "Main Content"
def _table_to_text(self, df) -> str:
"""Convert DataFrame to readable text"""
text_parts = []
# Add column headers
headers = " | ".join([str(col) for col in df.columns])
text_parts.append(f"Table Headers: {headers}")
# Add rows (limit to prevent huge chunks)
for i, (_, row) in enumerate(df.iterrows()):
if i >= 15: # Limit rows
text_parts.append(f"... and {len(df) - 15} more rows")
break
row_text = " | ".join([str(val) for val in row.values])
text_parts.append(f"Row {i+1}: {row_text}")
return "\n".join(text_parts)
async def _process_images(self, file_path: str) -> List[DocumentChunk]:
"""Extract and process images using OCR"""
chunks = []
try:
doc = fitz.open(file_path)
for page_num in range(doc.page_count):
# FIX: Use doc[page_num] instead of doc.page(page_num)
page = doc[page_num] # or page = doc.load_page(page_num)
image_list = page.get_images()
for img_index, img in enumerate(image_list):
try:
# Extract image
xref = img[0]
pix = fitz.Pixmap(doc, xref)
if pix.n - pix.alpha < 4: # GRAY or RGB
# Convert to PIL Image
img_data = pix.tobytes("ppm")
pil_image = Image.open(io.BytesIO(img_data))
# Perform OCR
ocr_text = pytesseract.image_to_string(pil_image, lang='eng')
if len(ocr_text.strip()) > 10: # Only if meaningful text found
chunk_id = hashlib.md5(f"image_{page_num}_{img_index}".encode()).hexdigest()
chunk = DocumentChunk(
id=chunk_id,
content=f"Image content (OCR): {ocr_text.strip()}",
page_number=page_num + 1,
section=f"Image {img_index + 1}",
chunk_type="image"
)
chunks.append(chunk)
pix = None
except Exception as e:
logger.warning(f"Error processing image {img_index} on page {page_num}: {str(e)}")
doc.close()
except Exception as e:
logger.warning(f"Image processing failed: {str(e)}")
return chunks
async def _generate_metadata(self, file_path: str, chunks: List[DocumentChunk]) -> Dict[str, Any]:
"""Generate document metadata"""
metadata = {
"file_name": Path(file_path).name,
"file_size": Path(file_path).stat().st_size,
"total_chunks": len(chunks),
"text_chunks": len([c for c in chunks if c.chunk_type == "text"]),
"table_chunks": len([c for c in chunks if c.chunk_type == "table"]),
"image_chunks": len([c for c in chunks if c.chunk_type == "image"]),
"sections": list(set([c.section for c in chunks])),
"page_count": max([c.page_number for c in chunks]) if chunks else 0,
"processed_at": datetime.now().isoformat()
}
return metadata
class GeminiSummarizer:
"""Gemini API integration for advanced summarization"""
def __init__(self, api_key: str):
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel('gemini-1.5-flash')
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
async def summarize_chunks(self, chunks: List[DocumentChunk],
request: SummaryRequest) -> List[str]:
"""Summarize individual chunks"""
summaries = []
# Create batch requests for efficiency
batch_size = 5
for i in range(0, len(chunks), batch_size):
batch = chunks[i:i + batch_size]
batch_summaries = await self._process_chunk_batch(batch, request)
summaries.extend(batch_summaries)
return summaries
async def _process_chunk_batch(self, chunks: List[DocumentChunk],
request: SummaryRequest) -> List[str]:
"""Process a batch of chunks"""
tasks = []
for chunk in chunks:
prompt = self._create_chunk_prompt(chunk, request)
task = self._call_gemini_api(prompt)
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
summaries = []
for i, result in enumerate(results):
if isinstance(result, Exception):
logger.error(f"Error summarizing chunk {chunks[i].id}: {str(result)}")
summaries.append(f"[Error processing content from {chunks[i].section}]")
else:
summaries.append(result)
return summaries
def _create_chunk_prompt(self, chunk: DocumentChunk, request: SummaryRequest) -> str:
"""Create optimized prompt for chunk summarization"""
tone_instructions = {
"formal": "Use professional, academic language",
"casual": "Use conversational, accessible language",
"technical": "Use precise technical terminology",
"executive": "Focus on key insights and implications for decision-making"
}
length_instructions = {
"short": "Provide 1-2 sentences capturing the essence",
"medium": "Provide 2-3 sentences with key details",
"detailed": "Provide a comprehensive paragraph with full context"
}
prompt_parts = [
f"Summarize the following {chunk.chunk_type} content from {chunk.section}:",
f"Content: {chunk.content[:2000]}", # Limit content length
f"Style: {tone_instructions.get(request.tone, 'Use clear, professional language')}",
f"Length: {length_instructions.get(request.summary_type, 'Provide appropriate detail')}",
]
if request.focus_areas:
prompt_parts.append(f"Focus particularly on: {', '.join(request.focus_areas)}")
if request.custom_questions:
prompt_parts.append(f"Address these questions if relevant: {'; '.join(request.custom_questions)}")
prompt_parts.append("Provide only the summary without meta-commentary.")
return "\n\n".join(prompt_parts)
async def _call_gemini_api(self, prompt: str) -> str:
"""Make API call to Gemini"""
try:
response = await asyncio.to_thread(
self.model.generate_content,
prompt,
generation_config=genai.types.GenerationConfig(
max_output_tokens=500,
temperature=0.3,
)
)
return response.text.strip()
except Exception as e:
logger.error(f"Gemini API call failed: {str(e)}")
raise
async def create_final_summary(self, chunk_summaries: List[str],
metadata: Dict[str, Any],
request: SummaryRequest) -> Summary:
"""Create final cohesive summary from chunk summaries"""
# Combine summaries intelligently
combined_text = "\n".join(chunk_summaries)
final_prompt = self._create_final_summary_prompt(combined_text, metadata, request)
try:
final_content = await self._call_gemini_api(final_prompt)
# Extract key points and entities
key_points = await self._extract_key_points(final_content)
entities = await self._extract_entities(final_content)
topics = await self._extract_topics(combined_text)
summary_id = hashlib.md5(f"{final_content[:100]}{datetime.now()}".encode()).hexdigest()
summary = Summary(
id=summary_id,
document_id=metadata.get("file_name", "unknown"),
summary_type=request.summary_type,
tone=request.tone,
content=final_content,
key_points=key_points,
entities=entities,
topics=topics,
confidence_score=0.85, # Would implement actual confidence scoring
created_at=datetime.now()
)
return summary
except Exception as e:
logger.error(f"Error creating final summary: {str(e)}")
raise
def _create_final_summary_prompt(self, combined_summaries: str,
metadata: Dict[str, Any],
request: SummaryRequest) -> str:
"""Create prompt for final summary generation"""
word_limits = {
"short": "50-100 words (2-3 sentences maximum)",
"medium": "200-400 words (2-3 paragraphs)",
"detailed": "500-1000 words (multiple paragraphs with comprehensive coverage)"
}
prompt = f"""
Create a cohesive {request.summary_type} summary from the following section summaries of a document:
Document Information:
- File: {metadata.get('file_name', 'Unknown')}
- Pages: {metadata.get('page_count', 'Unknown')}
- Sections: {', '.join(metadata.get('sections', [])[:5])}
Section Summaries:
{combined_summaries[:4000]}
Requirements:
- Length: {word_limits.get(request.summary_type, '200-400 words')}
- Tone: {request.tone}
- Create a flowing narrative that integrates all key information
- Eliminate redundancy while preserving important details
- Structure with clear logical flow
"""
if request.focus_areas:
prompt += f"\n- Emphasize: {', '.join(request.focus_areas)}"
if request.custom_questions:
prompt += f"\n- Address: {'; '.join(request.custom_questions)}"
return prompt
async def _extract_key_points(self, text: str) -> List[str]:
"""Extract key points from summary"""
prompt = f"""
Extract 5-7 key points from this summary as bullet points:
{text[:1500]}
Format as a simple list, one point per line.
"""
try:
response = await self._call_gemini_api(prompt)
points = [line.strip().lstrip('•-*').strip()
for line in response.split('\n')
if line.strip() and len(line.strip()) > 10]
return points[:7]
except:
return []
async def _extract_entities(self, text: str) -> List[str]:
"""Extract named entities"""
prompt = f"""
Extract important named entities (people, organizations, locations, products, concepts) from:
{text[:1500]}
List them separated by commas, no explanations.
"""
try:
response = await self._call_gemini_api(prompt)
entities = [e.strip() for e in response.split(',') if e.strip()]
return entities[:10]
except:
return []
async def _extract_topics(self, text: str) -> List[str]:
"""Extract main topics"""
prompt = f"""
Identify 3-5 main topics/themes from this content:
{text[:2000]}
List topics as single words or short phrases, separated by commas.
"""
try:
response = await self._call_gemini_api(prompt)
topics = [t.strip() for t in response.split(',') if t.strip()]
return topics[:5]
except:
return []
def generate_embeddings(self, chunks: List[DocumentChunk]) -> np.ndarray:
"""Generate embeddings for semantic search"""
texts = [chunk.content for chunk in chunks]
embeddings = self.embedding_model.encode(texts)
# Update chunks with embeddings
for i, chunk in enumerate(chunks):
chunk.embedding = embeddings[i]
return embeddings
class VectorStore:
"""FAISS-based vector storage for semantic search"""
def __init__(self, dimension: int = 384):
self.dimension = dimension
self.index = faiss.IndexFlatL2(dimension)
self.chunk_map = {}
def add_chunks(self, chunks: List[DocumentChunk], embeddings: np.ndarray):
"""Add chunks and embeddings to the store"""
self.index.add(embeddings.astype('float32'))
for i, chunk in enumerate(chunks):
self.chunk_map[i] = chunk
def search(self, query_embedding: np.ndarray, top_k: int = 5) -> List[Tuple[DocumentChunk, float]]:
"""Semantic search for relevant chunks"""
distances, indices = self.index.search(
query_embedding.reshape(1, -1).astype('float32'),
top_k
)
results = []
for i, (distance, idx) in enumerate(zip(distances[0], indices[0])):
if idx in self.chunk_map:
chunk = self.chunk_map[idx]
similarity = 1 / (1 + distance) # Convert distance to similarity
results.append((chunk, similarity))
return results
def save(self, path: str):
"""Save index and chunk map"""
faiss.write_index(self.index, f"{path}_index.faiss")
with open(f"{path}_chunks.pkl", 'wb') as f:
pickle.dump(self.chunk_map, f)
def load(self, path: str):
"""Load index and chunk map"""
self.index = faiss.read_index(f"{path}_index.faiss")
with open(f"{path}_chunks.pkl", 'rb') as f:
self.chunk_map = pickle.load(f)
class MCPServerClient:
"""MCP Server client for orchestration and monitoring"""
def __init__(self, server_url: str):
self.server_url = server_url
self.client = httpx.AsyncClient()
async def register_document(self, doc_id: str, metadata: Dict[str, Any]):
"""Register document processing with MCP server"""
try:
response = await self.client.post(
f"{self.server_url}/documents/register",
json={"doc_id": doc_id, "metadata": metadata}
)
return response.json()
except Exception as e:
logger.warning(f"MCP server registration failed: {str(e)}")
return {}
async def log_processing_metrics(self, doc_id: str, metrics: Dict[str, Any]):
"""Log processing metrics to MCP server"""
try:
await self.client.post(
f"{self.server_url}/metrics/log",
json={"doc_id": doc_id, "metrics": metrics}
)
except Exception as e:
logger.warning(f"MCP metrics logging failed: {str(e)}")
async def get_model_health(self) -> Dict[str, Any]:
"""Check model health via MCP server"""
try:
response = await self.client.get(f"{self.server_url}/health")
return response.json()
except Exception as e:
logger.warning(f"MCP health check failed: {str(e)}")
return {"status": "unknown"}
# FastAPI Application
app = FastAPI(title="Enterprise PDF Summarizer", version="1.0.0")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def serve_home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize components
pdf_processor = PDFProcessor()
summarizer = GeminiSummarizer(Config.GEMINI_API_KEY)
vector_store = VectorStore()
mcp_client = MCPServerClient(Config.MCP_SERVER_URL)
# Ensure directories exist
for dir_name in [Config.UPLOAD_DIR, Config.SUMMARIES_DIR, Config.EMBEDDINGS_DIR]:
Path(dir_name).mkdir(exist_ok=True)
# API Models
class SummaryRequestModel(BaseModel):
summary_type: str = Field("medium", description="short, medium, or detailed")
tone: str = Field("formal", description="formal, casual, technical, or executive")
focus_areas: Optional[List[str]] = Field(None, description="Areas to focus on")
custom_questions: Optional[List[str]] = Field(None, description="Custom questions to address")
language: str = Field("en", description="Language code")
class SearchQueryModel(BaseModel):
query: str = Field(..., description="Search query")
top_k: int = Field(5, description="Number of results")
# API Endpoints